Compare commits
98
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b4fe46725
|
||
|
|
8a486b7228
|
||
|
|
f04a670227
|
||
|
|
efba3aacf4
|
||
|
|
1d3154cefa
|
||
|
|
979a504600
|
||
|
|
c0dd0b5a50
|
||
|
|
5689994037
|
||
|
|
4344b35a27
|
||
|
|
6540d160df
|
||
|
|
a4a5c5dba1
|
||
|
|
cdb6a35371
|
||
|
|
5e45293462
|
||
|
|
7ca44ef5e2
|
||
|
|
2f43b94e56
|
||
|
|
472aff6b22
|
||
|
|
f9cca74af5
|
||
|
|
af290cd7d5
|
||
|
|
24669b7cd6
|
||
|
|
80ba7f70b9
|
||
|
|
613eba4154
|
||
|
|
ca1ace2987
|
||
|
|
dcd5adf491
|
||
|
|
adc1c4fe3e
|
||
|
|
118b2aa764
|
||
|
|
694e7f46d7
|
||
|
|
d30b74e1a4
|
||
|
|
5fcc158763
|
||
|
|
649cb526de
|
||
|
|
3e15900521
|
||
|
|
0437f802a4
|
||
|
|
e35bf3004c
|
||
|
|
a30075c8f3
|
||
|
|
f2a2acf996
|
||
|
|
6a05f56e7c
|
||
|
|
e1d99f3f0a
|
||
|
|
3046ad154a
|
||
|
|
374574b9ce
|
||
|
|
2d38ccd321
|
||
|
|
f816919071
|
||
|
|
9906554d09
|
||
|
|
9ca27cee01
|
||
|
|
dc642c62b9
|
||
|
|
2080f0b67e
|
||
|
|
9592fbeeb4
|
||
|
|
9976186599
|
||
|
|
d46e7aa548
|
||
|
|
77e1539e8f
|
||
|
|
9b700ee42c
|
||
|
|
ec9049f4ae
|
||
|
|
d0404f1968
|
||
|
|
b5e78d82bd
|
||
|
|
a5c4fdc128
|
||
|
|
9b1bf688a1
|
||
|
|
6ed3498bc0
|
||
|
|
d9654dd23c
|
||
|
|
87d391c352
|
||
|
|
737105add2
|
||
|
|
cd88c3e712
|
||
|
|
ad5c6ca12b
|
||
|
|
bd6c8df192
|
||
|
|
cb9ad78ee9
|
||
|
|
8e47a825c5
|
||
|
|
0c77109a73
|
||
|
|
fac9a3811a
|
||
|
|
6a07cf3cd4
|
||
|
|
14da5ba2b3
|
||
|
|
a4116b11a8
|
||
|
|
73e753ab57
|
||
|
|
e8d8236530
|
||
|
|
415dc653c3
|
||
|
|
3e1c320b00
|
||
|
|
44a102a96f
|
||
|
|
dff3aa67c0
|
||
|
|
8972bcfcce
|
||
|
|
3dbfcd5aca
|
||
|
|
23e3c5431a
|
||
|
|
afbe90442e
|
||
|
|
490568a980
|
||
|
|
6a7d129d09
|
||
|
|
21e5de2d73
|
||
|
|
6ae5736ffd
|
||
|
|
37cf778c44
|
||
|
|
6828dbd844
|
||
|
|
d3d78d2540
|
||
|
|
90f8980053
|
||
|
|
9257238735
|
||
|
|
0117c3e238
|
||
|
|
0be487bf96
|
||
|
|
f8a4888984
|
||
|
|
0982af8cfb
|
||
|
|
b52b6daaf0
|
||
|
|
da61967626
|
||
|
|
edff7452cb
|
||
|
|
f5ee8d75b1
|
||
|
|
9f4ae89030
|
||
|
|
0e8897b7da
|
||
|
|
6589a14073
|
No files matched your search
@@ -37,26 +37,57 @@ jobs:
|
||||
echo "369ad2b789f95a011f807e1fcb690ccef80bd7cd014fd139e73ae82dcc0baeab ktlint.jar" | sha256sum -c
|
||||
java -jar ktlint.jar "app/src/**/*.kt" "*.kts" "app/*.kts"
|
||||
|
||||
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
|
||||
- name: Wake-word engine (hash-pinned)
|
||||
run: python3 scripts/fetch-wakeword.py
|
||||
|
||||
# The wake phrases' token pieces are generated from the model's own tokenizer (bpe.model,
|
||||
# fetched above); the committed table must be what it gives.
|
||||
- name: Wake phrases match the model's tokenizer
|
||||
run: |
|
||||
python3 -m venv "$RUNNER_TEMP/wake"
|
||||
"$RUNNER_TEMP/wake/bin/pip" install --quiet --require-hashes --only-binary :all: -r scripts/wake-requirements.txt
|
||||
"$RUNNER_TEMP/wake/bin/python" scripts/gen-wake-phrases.py --check
|
||||
|
||||
- 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: Unit tests and the three builds
|
||||
run: >
|
||||
./gradlew --no-daemon testFullStandardDebugUnitTest
|
||||
assembleFullStandardDebug assembleFullNotificationsDebug assembleFdroidStandardDebug
|
||||
|
||||
# The files themselves: only the notifications build declares a notification listener, the
|
||||
# wake-word model is stored uncompressed, the F-Droid build has no engine.
|
||||
- name: What the APKs declare
|
||||
run: |
|
||||
scripts/check-apk.sh app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk standard
|
||||
scripts/check-apk.sh app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk notifications
|
||||
scripts/check-apk.sh app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk fdroid
|
||||
|
||||
# A release as the release workflow builds it, unsigned: shrunk by R8, and without the
|
||||
# emulator's x86_64 libraries. Found here rather than at a tag.
|
||||
- name: The release build's shape
|
||||
run: |
|
||||
./gradlew --no-daemon assembleFullStandardRelease
|
||||
scripts/check-apk.sh "$(ls app/build/outputs/apk/fullStandard/release/*.apk)" standard release
|
||||
|
||||
- name: Android lint (report only, for now)
|
||||
run: ./gradlew --no-daemon lintFullDebug
|
||||
run: ./gradlew --no-daemon lintFullStandardDebug
|
||||
continue-on-error: true
|
||||
|
||||
# The test build a tester installs (Actions › this run › Artifacts): debug-signed with the
|
||||
# repository's public test key, so each one installs over the last. `full` is the one to
|
||||
# use; `fdroid` is the same app without the updater.
|
||||
# repository's public test key, so each one installs over the last. The plain one is the
|
||||
# one to use; `-notifications` is the same app with the notification listener (it installs
|
||||
# over the plain one and back); `-fdroid` is the app without the updater and the wake word.
|
||||
- name: Name the test builds
|
||||
run: |
|
||||
mkdir test-builds
|
||||
short="${GITHUB_SHA::7}"
|
||||
cp app/build/outputs/apk/full/debug/app-full-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
|
||||
cp app/build/outputs/apk/fdroid/debug/app-fdroid-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
|
||||
cp app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
|
||||
cp app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-notifications.apk"
|
||||
cp app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
|
||||
(cd test-builds && sha256sum *.apk > SHA256SUMS)
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
@@ -65,6 +96,15 @@ jobs:
|
||||
path: test-builds/
|
||||
if-no-files-found: error
|
||||
|
||||
# The screens as the screenshot tests rendered them (app/src/test/.../shots), light and
|
||||
# dark, at a large and a small phone's size: the design is reviewed from these.
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: llembas-android-screenshots-${{ github.run_number }}
|
||||
path: app/build/screenshots/
|
||||
if-no-files-found: warn
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
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
|
||||
# A signed tag `vX.Y.Z` builds the three APKs, signed with the release key from the secrets,
|
||||
# and publishes them with SHA256SUMS as the GitHub Release: the standard one, `-notifications`
|
||||
# (the same app, id and key, plus the notification listener) and `-fdroid`. 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:
|
||||
@@ -43,6 +44,10 @@ jobs:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
|
||||
- name: Wake-word engine (hash-pinned)
|
||||
run: python3 scripts/fetch-wakeword.py
|
||||
|
||||
- uses: gradle/actions/wrapper-validation@v4
|
||||
|
||||
- uses: gradle/actions/setup-gradle@v4
|
||||
@@ -57,14 +62,20 @@ jobs:
|
||||
[ -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
|
||||
./gradlew --no-daemon testFullStandardReleaseUnitTest assembleFullStandardRelease assembleFullNotificationsRelease assembleFdroidStandardRelease
|
||||
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"
|
||||
cp app/build/outputs/apk/fullStandard/release/app-full-standard-release.apk "dist/llembas-android-$VERSION.apk"
|
||||
cp app/build/outputs/apk/fullNotifications/release/app-full-notifications-release.apk "dist/llembas-android-$VERSION-notifications.apk"
|
||||
cp app/build/outputs/apk/fdroidStandard/release/app-fdroid-standard-release.apk "dist/llembas-android-$VERSION-fdroid.apk"
|
||||
# What is about to be published, checked on the files: the listener only in
|
||||
# -notifications, the model stored, no x86_64 library.
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION.apk" standard release
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION-notifications.apk" notifications release
|
||||
scripts/check-apk.sh "dist/llembas-android-$VERSION-fdroid.apk" fdroid release
|
||||
{ echo "# llembas-android $VERSION"; (cd dist && sha256sum *.apk); } > SHA256SUMS
|
||||
mv SHA256SUMS dist/
|
||||
|
||||
|
||||
@@ -16,3 +16,6 @@ local.properties
|
||||
.kotlin/
|
||||
# Python
|
||||
__pycache__/
|
||||
# The wake-word engine and model: fetched by scripts/fetch-wakeword.py, never committed
|
||||
/app/libs/
|
||||
/app/src/full/assets/wakeword/
|
||||
+569
@@ -5,6 +5,575 @@ is in alpha and releases come off `main`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.0.0-beta.11] — 2026-11-18
|
||||
|
||||
Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app works as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Choose a folder on your computer instead of typing its path.** A new agent chat's *Folder
|
||||
on the device* opens a picker: the computer's places, then down through its folders and back
|
||||
up -- the back gesture goes up a level and closes at the top. A folder the computer will not
|
||||
open a session in says why and cannot be chosen; a folder you worked in before names the
|
||||
model you last used there. The path can still be typed, and that is what remains when the
|
||||
computer is not linked, does not answer, or runs a LLeMbas CLI too old to list its folders --
|
||||
the picker says which.
|
||||
- **A new agent chat starts on the model you last used in that folder.** Once the computer and
|
||||
the folder are chosen, the model shown is the folder's usual one (the computer remembers it;
|
||||
the app keeps nothing), and it changes when you choose another computer or folder. A model
|
||||
you pick yourself stays picked.
|
||||
- **Scheduled tasks have two types: Chat and Agentic.** The form asks the type first. *Chat*
|
||||
runs on your instance, as tasks always have. *Agentic* runs on one of your computers, in one
|
||||
folder there, as an agent: you choose the computer, the folder (with the picker, or typed),
|
||||
the mode (only those the computer allows), how long an approval waits, a command to watch
|
||||
(the task then runs only when its output changed), and the model -- *The folder's usual
|
||||
model* unless you choose one of your scheduling models. Editing a task says to the instance
|
||||
only what you changed, so a task's words can be put right while its computer is not linked. Agentic can be chosen only while one of your computers
|
||||
accepts scheduled work, and says so otherwise. A task's page shows its type, computer, folder
|
||||
and model; each run says where it ran and when its model was the folder's usual one, your
|
||||
default or the conversation's own.
|
||||
- **Two models with the same name on different connections are told apart.** Where an instance
|
||||
serves one model through two connections, the pickers say *Name · Connection*, and the one
|
||||
you pick is the one used -- in a chat, as the assistant's model, in a scheduled task. A
|
||||
model chosen before this still finds its row.
|
||||
- **`@` in the composer.** Type `@` and a few letters at the end of a message: in a chat the
|
||||
list offers your files, what was attached earlier in the chat and a web address, and a tap
|
||||
attaches it; in an agent chat it offers the files in the chat's folder on the computer, and
|
||||
a tap completes the path for the agent to read.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The badge on Reports is live.** The count of unread reports in the drawer follows the
|
||||
instance while the app is in front -- a report that arrives, or one read on another device,
|
||||
moves it at once. Before, it was read only when the drawer opened.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Two quick taps on *Older* no longer end the app.** The same page of older messages was
|
||||
fetched twice and put above the chat twice. One page is read at a time now, and a message is
|
||||
never added a second time.
|
||||
- **A reply whose stream ends without its last frame no longer disappears.** What had been
|
||||
written vanished until the chat was opened again. The chat is now read again at that point;
|
||||
where it cannot be read, what was written stays as it stood, with its *Stopped* or *Failed*
|
||||
line where the instance had said one.
|
||||
- **Other apps' dictation sends nothing to your instance while the phone is locked.** While
|
||||
LLeMbas is the digital assistant, an app that asks Android's speech recogniser is answered by
|
||||
your instance -- until now also over the lock screen. A locked phone now uses its own
|
||||
on-device recogniser where it has one, and otherwise tells the app that no recogniser is
|
||||
available; a phone that locks while it is listening sends nothing either.
|
||||
- **A thinking block you opened stays open.** It closed by itself when the thinking ended and
|
||||
the words began, and again when the reply finished.
|
||||
- **Edit, Regenerate, Continue and Carry out the plan tell the instance they come from the
|
||||
phone**, as a new message always did, so a reply started that way is also written for an app
|
||||
that draws no pages.
|
||||
- **The chat no longer pulls you away from what you are reading while a reply is written.** The
|
||||
view follows the reply only while you are at the end. Once you scroll up it stays exactly
|
||||
where you are -- a finger on the list ends the following at once -- and scrolling back to the
|
||||
end takes it up again. Before, the next queued turn starting, a transcript read again and a
|
||||
rotation could each throw the view to the end.
|
||||
- **Older messages no longer throw the chat to its end.** Tapping *Older* keeps the message you
|
||||
were at in place, with the older ones above it.
|
||||
- **The keyboard no longer covers the last lines**: opening it at the end of a chat keeps the
|
||||
end in view.
|
||||
- **The assistant's sheet follows the same rule.** It pulled the answer back to its end at every
|
||||
word, also for somebody reading further up.
|
||||
- **A message written on another device no longer throws the chat to its end** while you read
|
||||
further up: only a message sent from this phone does.
|
||||
|
||||
## [1.0.0-beta.10] — 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Assistant model** in Settings › Assistant: the model the assistant's new chats start on --
|
||||
*Instance default* (your account's default, as before) or any model of the instance. A large
|
||||
default model is slow to answer a spoken question; a quick one can be chosen for the assistant
|
||||
alone. It holds for every way in: the sheet, the wake word, Share. Picking a model in the
|
||||
sheet still changes it too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The wake word and the hands-free parts of the voice assistant are marked Experimental** in
|
||||
Settings: the wake word as a whole, and with the assistant *Start listening when the
|
||||
assistant opens* and *Keep a spoken conversation going*. They are new and have been tried on
|
||||
few phones: the wake word may miss the phrase, start by mistake, or hear you and still not
|
||||
open the assistant; listening may stop too early or too late. Typing a question and the
|
||||
microphone button are the parts to rely on.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word with the screen off: the sheet showed for a moment and was gone.** A phone
|
||||
whose screen is off is locked, and a sheet opened over the lock screen asked Android to unlock
|
||||
first and closed itself when that was turned down -- which is what happens when nobody is
|
||||
there to unlock. Opened to listen (the wake word, a headset's button), the sheet now stays up
|
||||
over the lock screen and listens, and Android is asked to unlock once it has heard you: a face
|
||||
or a fingerprint sends the question. Leave it, and it stays until the screen goes off.
|
||||
- **Nothing goes to your instance while the phone is locked.** Not the question, not the
|
||||
recording, not even "which models are there". With Voice input › LLeMbas the question waits on
|
||||
the phone as a recording -- the sheet says *Question heard*, with no words, and **Unlock to
|
||||
send** -- and is written down and asked once you unlock. With Voice input › Phone the phone's
|
||||
own recogniser writes it down (the recording goes wherever that recogniser sends it, as
|
||||
always) and the words are shown while they wait. No answer is shown or spoken over the lock
|
||||
screen, and an answer over the lock screen is not offered.
|
||||
- **A phone that locks while the assistant is open stops there.** The screen going off stops the
|
||||
microphone and the voice at once; a question still being listened to is dropped; an answer is
|
||||
no longer read aloud on a locked phone, a spoken conversation does not go on, and the
|
||||
conversation that was on the sheet is not readable over the lock screen -- nor a failure's
|
||||
words, which may name the instance. The screen stays on while an answer is read aloud.
|
||||
- **Another app can no longer put a question into the assistant.** The
|
||||
sheet's screen has to be startable by Android (the assist action, a headset's button), so any
|
||||
app can start it. A question handed from the assistant's own sheet no longer travels in the
|
||||
intent, where any app could have written one to be asked on your account (or to wait for your
|
||||
next unlock): it stays in the app's memory and the intent carries a one-time ticket. Opening
|
||||
listening, the last chat and turning the screen on are honoured only on intents the app made
|
||||
itself. Android's own headset actions still open it listening, as they must.
|
||||
- The sheet no longer asks its question a second time, or loses the one that waits, when the
|
||||
phone is turned, folded or switches theme while it is up.
|
||||
- Closing the sheet lets go of the microphone at once, also when it was closed in the middle of
|
||||
listening.
|
||||
- Listening no longer runs to the limit after speech into a headset that gates its noise to
|
||||
exact silence, and no longer gives up as "nothing said" on someone who goes straight on after
|
||||
the wake word in a steady voice. The phone's recogniser is not given up on while it reports
|
||||
speech but shows no words yet.
|
||||
- **A new assistant chat could start on the wrong model.** After *Continue the last chat*, *New
|
||||
chat* kept that chat's model instead of going back to the assistant's own; and a question
|
||||
sent the moment the sheet opened, before the instance had said which models it has, went to
|
||||
the instance's default whatever was chosen.
|
||||
|
||||
- **Listening went on and on in a quiet room.** With the instance's speech-to-text the sheet
|
||||
decided "somebody is speaking" and "it is quiet again" by two fixed loudness levels. A phone
|
||||
whose room noise sat above the quiet level never heard a pause, so it listened until the
|
||||
two-minute limit; and words the speech-to-text invented from silence counted as speech. Now
|
||||
the room's own level is measured from the first moment and followed all the time, and speech
|
||||
and quiet are judged against it: nothing said ends after five seconds, a question ends a
|
||||
second and a half after you stop, a click or a knock is not speech, and the limit is one
|
||||
minute. Silence is no longer sent to be written down while you have said nothing.
|
||||
- The phone's own recogniser (Voice input › Phone) is asked for the same pause, and is watched:
|
||||
one that never answers no longer leaves the sheet listening for good.
|
||||
- An app that uses the system's recogniser while LLeMbas is the assistant no longer waits the
|
||||
full fifteen seconds every time: it ends at the pause after speech, or says that nothing was
|
||||
said.
|
||||
|
||||
## [1.0.0-beta.9] — 2026-11-13
|
||||
|
||||
For LLeMbas server 2.0.0-beta.12 or later.
|
||||
|
||||
For LLeMbas server 2.0.0-beta.12 (harness spec 3.8.0); an older instance works as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Reports.** A scheduled task no longer answers into a chat: it files a report when it has
|
||||
something to tell you, or leaves a line in its history. *Reports* is in the drawer, with a
|
||||
count of the unread. The list has the unread first -- title, the task it came from, when, and
|
||||
a mark where the model called it important; pull to read it again, swipe a row one way to mark
|
||||
it read and the other to delete it (which asks once). A report reads as a page and is marked
|
||||
read when opened; **Share** hands its text to another app; **Reply** continues it as a
|
||||
conversation that stays with the report -- its bar says *Report: …*, Back returns to the
|
||||
report, and it is not among your chats.
|
||||
- **Notify when** on a scheduled task's form: *Every run* (the model writes a report every
|
||||
time, also when nothing was found), *When…* (only when your own words hold; "something needs
|
||||
my attention" to start from) or *Never* (runs are kept in the task's history only). Offered
|
||||
where the instance has Reports.
|
||||
- A task's runs show the run's own note -- what it found, or why it filed no report -- and a way
|
||||
to its report when it filed one. The run's working chat can still be opened from the run.
|
||||
|
||||
- **Last wake** in Settings › Wake word: when the phrase was last heard, what the app tried
|
||||
(the assistant's sheet, the sheet as a screen of the app, a notification) and exactly how it
|
||||
went -- opened, and after how long; Android had not connected LLeMbas as the assistant;
|
||||
Android refused, in its own words; or it did not refuse and still no sheet came -- with what
|
||||
Android itself said at that moment: whether LLeMbas was the digital assistant app, whether
|
||||
Android was really using it as its voice assistant, and when it had connected or dropped it.
|
||||
A tap shows the last five. Nothing from your account is in it.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word heard you and only a notification came, though LLeMbas is the assistant.**
|
||||
The app can open the sheet from the background only through a connection Android keeps to
|
||||
the assistant app, and it threw away the reason when that was missing or refused. It now
|
||||
keeps it (*Last wake*), says in Settings when LLeMbas is the assistant but Android has not
|
||||
connected it right now -- with the way to the system's setting -- and checks that the sheet
|
||||
really came up before it counts the wake as opened; when it did not, the notification follows
|
||||
and says *Could not open by itself — tap to ask*. What makes a phone drop that connection is
|
||||
not fixed by this: the record is there to find out.
|
||||
- Settings says so when LLeMbas is chosen as the digital assistant app but Android is not using
|
||||
it as its voice assistant (which Android can undo at a restart): the long press then opens
|
||||
it as an ordinary screen, and the wake word can only send a notification until LLeMbas is
|
||||
chosen again.
|
||||
- The wake word stayed paused "while the assistant is open" after the sheet was left with the
|
||||
Home button, or after the assistant was asked for twice in a row.
|
||||
- A report's conversation showed the line the server opens it with as if you had written it;
|
||||
such lines are a quiet note now, and that first one is left out.
|
||||
- The screen is turned on when the wake word opens the sheet (with *Only while the screen is
|
||||
on* switched off, the phrase can come while it is dark).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Notifications come from a report, not from a run**, on a *Reports* channel of their own:
|
||||
unlocked, the report's title and summary; on the lock screen only "New report". A tap opens
|
||||
the report; *Mark read* asks for the phone to be unlocked. A run that filed no report notifies
|
||||
nothing; a failed run still says that it failed. An instance on 2.0.0-beta.11 keeps sending
|
||||
its runs' notifications, and they work as before.
|
||||
- A report the model called important arrives on a channel of its own, *Important reports*,
|
||||
which may come up over what is on screen. A report read or deleted in the app takes its
|
||||
notification away. *Reports* is in the drawer only where the instance has reports. An empty
|
||||
*When…* means the instance's own default, which the field shows as a placeholder.
|
||||
- **A page in an answer is not drawn on the phone** (LLeMbas 2.0.0-beta.12 can let a model add
|
||||
HTML pages to an answer; the web and LLeMbas Desktop show them). The phone shows one quiet
|
||||
card -- *This answer has a page: …*, and where to open it -- in a chat and in a report, never
|
||||
the page's source. What you copy or share says `[page: …]` in its place. The phone's chat
|
||||
settings do not offer the switch.
|
||||
|
||||
## [1.0.0-beta.8] — 2026-11-12
|
||||
|
||||
For LLeMbas server 2.0.0-beta.11 or later. Three files now: the standard app, `-notifications` (the same app with notification summaries) and `-fdroid`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Test the wake word** (Settings › Wake word): for ten seconds the row shows what the wake word
|
||||
is doing and says *Heard it* when your phrase lands, without opening the assistant -- so a
|
||||
phrase, a sensitivity and a place in the room can be tried before relying on them.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word never started, on any phone.** The engine read its model out of the APK in a
|
||||
way that only works for files stored uncompressed, and they were not; the failure was swallowed,
|
||||
so the notification went on saying it listened. The model is now copied out by stream (once per
|
||||
model version, so an update that brings a new model replaces the old one) and stored
|
||||
uncompressed as well.
|
||||
- **The wake word's notification told the default phrase, not yours**, each time the app was
|
||||
opened. It is now written from one place, from what the wake word is really doing.
|
||||
- **Hearing the word when LLeMbas is not the phone's assistant and not on screen did nothing at
|
||||
all**: Android blocks an activity started from the background without saying so, and the app
|
||||
took the silence for success. It now posts *Heard you. Tap to ask.* on a channel of its own that
|
||||
comes up over what is on screen, and Settings › Wake word says plainly that only the phone's
|
||||
digital assistant app can open by voice over other apps, with a row that opens that setting.
|
||||
- The wake word could stay "paused while the assistant is open" for good if its service ended in
|
||||
the three seconds after the word. The hold now ends by itself, whatever happens to the service.
|
||||
- Turning the wake word off and on again quickly could leave "not listening" showing over a wake
|
||||
word that listened, or close the app (the service was stopped under a start still on its way).
|
||||
Stop is now the setting going off, and the service ends itself.
|
||||
- A change of phrase could release the engine while the old listening loop was still using it.
|
||||
The old loop is now stopped and waited for first.
|
||||
- A microphone that failed to start, or stopped giving sound, was not noticed (and one kind of
|
||||
failure kept a processor core busy for nothing). Both are failures that are shown now.
|
||||
- Opening the app with the wake word on but the microphone permission taken away could close the
|
||||
app. The service is no longer started without the permission; the state says what is missing.
|
||||
|
||||
### Changed
|
||||
|
||||
- **One display with the web, Desktop and the CLI** (harness spec 3.7.0, `display.md`):
|
||||
- A reply that was stopped or failed keeps the spec's line at its end -- *Stopped: by you*,
|
||||
*Stopped: step limit*, *Stopped: budget*, *Failed: …* -- an error in the error colour, a stop
|
||||
muted. A stopped reply said nothing at all before, and a failed one showed the raw error.
|
||||
- A finished tool call says how long it took (`0.4s`, `1m 05s`, `2h 03m`) where the instance
|
||||
sends the call's time; a running or a denied call shows none.
|
||||
- Counts in the progress line are in the phone's own number format (`12,480`, `12 480`,
|
||||
`12.480`); a tool call's title that had to be cut ends in `…`; the clock is joined by the
|
||||
shared separator instead of a copy of it.
|
||||
- The approval card offers the spec's four actions: *Allow once*, *Always allow*, *Deny*, and
|
||||
*Deny, and say why*. The plan card approves together with the mode to continue in --
|
||||
*Approve, continue in Edit* or *Approve, continue in Manual* -- and *Revise*.
|
||||
- With LLeMbas 2.0.0-beta.11: a reply that was stopped or failed says so with its reason after a
|
||||
reload too (the instance stores how it ended); *Always allow* is offered only where the request
|
||||
offers it; a tool call's time is the instance's own; a call without a title is named as the
|
||||
instance names its tool. The notifications build can take its own file from the instance's
|
||||
recommendation of the same release when the website's manifest names none.
|
||||
- **A reply ends when it is saved, and the chat's name follows** (with a server that sends `done`
|
||||
first: LLeMbas 2.0.0-beta.11). The app treats `done` as the end -- the transcript, a spoken
|
||||
answer and a queued prompt no longer wait for a model to name a new chat -- and takes the name
|
||||
from the `title` frame when it comes.
|
||||
- **Wake phrases the engine can hear.** "Hey Lembas" is gone: Lembas is not a word the engine's
|
||||
model was ever trained on, so it had to be repeated until it happened to land. The phrase is now
|
||||
a greeting and a name, each chosen in Settings › Wake word: **Hey**, **OK** or **Hello**, then
|
||||
**Assistant**, **Computer**, **Google** (Settings says a Google device nearby will answer too),
|
||||
or an ordinary name -- Victoria, Samantha, Jessica, Amanda, Olivia, Oliver, Sebastian, Jonathan,
|
||||
Alexander, Christopher. The default is "Hey Assistant", and a phrase saved by an earlier beta
|
||||
becomes it. The phrases are English whatever language the app is in, and Settings says so: the
|
||||
model knows English speech only.
|
||||
- **Sensitivity** (Low, Normal, High) in Settings › Wake word: how easily the phrase is taken as
|
||||
heard, against how often it starts by mistake. Each phrase now goes to the engine with a
|
||||
boosting score and a trigger threshold (1.0 / 0.35, 1.5 / 0.25, 2.0 / 0.15; a short phrase such
|
||||
as "OK Computer" is held 0.05 stricter). These are starting values from the engine's
|
||||
documentation, not yet tuned on phones.
|
||||
- The phrases' spelling in the model's token pieces is generated from the model's own tokenizer
|
||||
(`scripts/gen-wake-phrases.py`) and checked against its token table in CI, instead of written by
|
||||
hand. Elizabeth and Benjamin are left out: the tokenizer can only spell them letter by letter.
|
||||
- **Notification summaries moved to a build of their own**, `llembas-android-<version>-notifications.apk`:
|
||||
the same app with the same signature, plus the notification listener. Google Play Protect
|
||||
blocked installing beta.7, most likely because an app from outside the Play Store that can read
|
||||
notifications is what it looks for; the standard and F-Droid APKs now declare no notification
|
||||
listener at all, and Settings says where notification summaries went and why. The
|
||||
notifications build installs over the standard one as an ordinary update, and back; it updates
|
||||
itself only to its own kind.
|
||||
- **A smaller download.** Release APKs no longer carry the emulator's x86_64 libraries (about
|
||||
36 MB of beta.7's 98 MB) nor two libraries of the wake-word engine the app never calls.
|
||||
- **The wake word says what it is doing**, in its notification and under its switch in Settings:
|
||||
*Starting*, *Listening for "…"*, paused and why (screen off, battery saver, assistant open, no
|
||||
microphone permission, or the microphone gives no sound because another app has it or it is
|
||||
switched off), or not working and why (its model could not be unpacked, the engine did not
|
||||
start, the microphone did not start) -- with the technical reason under it in Settings. A
|
||||
failure is tried again by itself, after 2 s, 5 s, 15 s, a minute, then every five minutes.
|
||||
- A tap on a failure in Settings tries again at once; trouble after half a minute of listening
|
||||
well starts the waits over instead of counting on from old failures. Say the phrase and then
|
||||
leave a short pause: the engine takes it as heard once something else follows (Settings and the
|
||||
test row say so).
|
||||
- A microphone permission given or taken in the system's settings is noticed when the app comes
|
||||
back to the screen.
|
||||
|
||||
## [1.0.0-beta.7] — 2026-11-10
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.10 or later for phone actions).
|
||||
|
||||
### Added
|
||||
|
||||
- **Share to LLeMbas, with a say in it.** *Ask LLeMbas* in any app's share menu now opens a
|
||||
sheet over that app: what came in (the text or link, the files by name), a line for what to do
|
||||
with it (optional), and where it goes -- a **new chat** or the **last assistant chat**. Files
|
||||
are uploaded and go with the message; the chat then opens in the app.
|
||||
- **A home-screen widget**: *Ask anything* opens the assistant, the microphone opens it
|
||||
listening, and the clock opens the last assistant chat. It shows nothing from your account.
|
||||
- **Spoken conversations with the assistant.** Ask by voice and, once the answer has been read
|
||||
aloud, the assistant listens again -- until you say "stop" (or "that's all"), tap **End**, or
|
||||
say nothing for a few seconds. The sheet says *In conversation* while it lasts. With a
|
||||
Bluetooth headset connected, its microphone is used, so the conversation can stay in your ear.
|
||||
Settings › Assistant › *Keep a spoken conversation going* (on; it needs voice replies).
|
||||
- **A wake word, if you want one** (off by default). Settings › Assistant › *Wake word*: say
|
||||
"Hey Lembas" (or one of three other English phrases) and the assistant opens, listening, over
|
||||
whatever is on screen. It listens on the phone with an open-source engine (sherpa-onnx) and a
|
||||
small on-device model; nothing leaves the phone before the word, and a notification is up the
|
||||
whole time it listens. It pauses in battery saver, while the assistant is open, and -- unless
|
||||
you change it -- with the screen off. Settings explains what it costs in battery and how to
|
||||
keep a phone's battery optimisation from stopping it. Not in the F-Droid build, which builds
|
||||
every library from source.
|
||||
- **"Summarise my notifications"**, if you allow it (off by default). Settings › Assistant ›
|
||||
*Notification summaries*, plus Android's own notification-access switch, which Settings opens
|
||||
for you. Then ask the assistant about "my notifications", or tap its chip, and the
|
||||
notifications on the phone right now go with that one question -- never before you ask, never
|
||||
while the phone is locked, and the app keeps none of them.
|
||||
- **Phone actions** (with LLeMbas server 2.0 and harness spec 3.6.0): a model may offer to do
|
||||
something on this phone -- set an alarm or a timer, add a calendar event, draft a text or an
|
||||
email, open the dialler with a number, start a route (with stops), add a stop, search nearby,
|
||||
end the route, open an app or a web page, play/pause/skip, switch the torch, open a settings
|
||||
panel, or run a Tasker task. A card says what will happen; nothing happens until you tap
|
||||
**Do it**, never while the phone is locked, and drafts and calls are left for you to send and
|
||||
place. The chat (and the assistant's sheet) tells the model whether it was done, declined or
|
||||
failed. Navigation goes to Google Maps or **OsmAnd** (Settings › Navigation app: whichever is
|
||||
installed, or ask); OsmAnd can also be asked where you are and where the running route goes,
|
||||
once you allow LLeMbas inside OsmAnd.
|
||||
- **Code in colour.** The file viewer highlights a source file by its language (as the server
|
||||
names it), and a reply's code blocks by their fence's language: comments, strings, numbers,
|
||||
keywords, type names, and markup's tags and attributes, in the theme's own colours in Shire
|
||||
and Moria. Still read-only; a language it does not know is shown plain.
|
||||
- **Launcher shortcuts** (long-press the icon): Ask LLeMbas, Speak, Last chat.
|
||||
- **A headset's voice button** opens the assistant listening, when LLeMbas answers it; over the
|
||||
lock screen it asks to unlock first.
|
||||
|
||||
### Changed
|
||||
|
||||
- The Quick Settings tile always shows as ready, never greyed out.
|
||||
|
||||
## [1.0.0-beta.6] — 2026-11-10
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.9 or later for schedules on a computer, the update check through the instance, pinning, folders, memory and search).
|
||||
|
||||
### Added
|
||||
|
||||
- **The app tells you when a newer version is out.** Settings › About › *Look for new versions*:
|
||||
at most once a day, when the app starts, it asks your instance which release goes with it
|
||||
(an instance older than that reads the public list of LLeMbas for Android releases on GitHub;
|
||||
plain HTTPS, no Google service, nothing about you sent) and, when there is a newer one, says so in a notification that opens the release's page with its APKs. On by
|
||||
default in a beta, off in a release. *Include betas* offers test versions too (on by default
|
||||
in a beta). **Check for an update** asks at once, in either build; the full build can then
|
||||
install a release itself.
|
||||
- **Archived chats**, in the drawer under Scheduled: every archived chat, newest first. A tap
|
||||
opens one; **Restore chat** puts it back among your chats.
|
||||
- **Read aloud on a reply** in a chat, beside Copy, when your instance has text-to-speech: the
|
||||
same voice the assistant answers in. Tap again (or another reply's) to stop; leaving the chat
|
||||
stops it too.
|
||||
- **Pinned chats and folders** in the drawer, as on the web: pinned chats at the top wherever
|
||||
they are filed, then your folders as a tree (a tap folds or opens one, and the web folds it
|
||||
too), then the rest. A long press on a chat offers **Pin chat** and **Move to folder**; on a
|
||||
folder, **Rename folder** and **Delete folder** (its chats stay). **New folder** is beside New
|
||||
chat at the top of the drawer.
|
||||
- **Search finds words inside your chats.** Typing in the drawer's search box still filters
|
||||
the titles at once; a moment later the chats whose messages hold the words follow under *In
|
||||
the messages*, with the words marked.
|
||||
- **Generate images** in a chat, when your instance makes pictures: from **+** in the composer,
|
||||
the next message asks for one (a new chat can start with a picture too), and the picture shows in the reply at its own size. A tap opens
|
||||
it whole. Only pictures your instance made and keeps are drawn; nothing is loaded from an
|
||||
address a reply names.
|
||||
- **Memory**, in the drawer: what models remember about you, as Settings › Memory on the web.
|
||||
A tap changes or forgets one; **Remember** adds one (in the data group you pick, when you have
|
||||
more than one). What a model wrote is marked, and shown as plain text.
|
||||
- **A scheduled task that runs on one of your computers** says which, in which folder and mode,
|
||||
on its page and in each run; a run that found the computer away says *not linked now*.
|
||||
- **A scheduled task that watches a web page** says so on its page (*Only when this page
|
||||
changes*, and the address), and a run that found the page unchanged is shown as *Unchanged*.
|
||||
- **A scheduled task's notification shows its result.** Unlocked, it carries the task's name
|
||||
and the first lines of what it found (pull it open for more); on the lock screen only
|
||||
*LLeMbas* and that a scheduled task finished or failed, nothing from your account. **Run again** starts the task again from the
|
||||
notification, once the phone is unlocked. Needs an instance that sends these; an older one
|
||||
keeps the fixed sentence.
|
||||
- **A message waiting behind a reply says how many are ahead of it** and for how long it has
|
||||
waited, where the instance tells.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Allow once and Deny on an approval's notification ask for the phone to be unlocked first**
|
||||
(Android 12 and newer), so a locked phone cannot answer for you. This holds for the
|
||||
approvals a scheduled run on a computer will send too.
|
||||
- **The microphone in a chat follows Settings › Voice input**, as the assistant does: with
|
||||
*LLeMbas* it records and your instance writes the words down when you stop; with *Phone* the
|
||||
phone's own recogniser writes them into the box as you speak and stops at the end of what you
|
||||
said. The setting's explanation now says it covers both.
|
||||
|
||||
## [1.0.0-beta.5] — 2026-11-10
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.8 or later for the progress line, the subagent list and the new agent chat's Subagents setting).
|
||||
|
||||
### Changed
|
||||
|
||||
- **The app speaks your account's language**, the one chosen on your instance, rather than the
|
||||
phone's: a phone set to Slovak signed in to an English account shows the app in English.
|
||||
**Settings › Language** chooses otherwise -- *Same as my account* (the default), *Phone
|
||||
language*, or any language the app has, each named in itself. On Android 13 and newer the
|
||||
system's own per-app language (Settings › Apps › LLeMbas › Language) offers the same
|
||||
languages, and a language chosen there is kept as your choice.
|
||||
- **Agent chats are easy to find.** A new chat's page starts with **Chat** or **Agent chat**,
|
||||
one line each, side by side. With no computer linked, Agent chat is still there and says how
|
||||
to link one -- install the LLeMbas CLI, `lembas login` to this instance, allow remote work and
|
||||
start the service, each command with Copy -- with **Check again**.
|
||||
- **The assistant is a sheet over the app you are in**, not a full screen. Holding the power
|
||||
button raises it to half the height, with the app still in sight under it; drag its handle up
|
||||
for the full height, down (or Back, or a tap outside) to close it.
|
||||
- **The microphone first**: it opens listening, and the words appear as you say them. A pause
|
||||
sends them; tap the microphone to send at once, or the keyboard to type instead. (Settings ›
|
||||
Assistant can turn the listening off.)
|
||||
- **The model and the connection** at the top: the model's picture and name, the instance and
|
||||
a dot that says whether it answers; a tap picks another model, which the assistant keeps.
|
||||
- **Use screen**: when Android hands the assistant the screen (its text, a screenshot, or
|
||||
both), one tap sends it with your next question -- never without the tap. Quick actions do
|
||||
it in one go: **Summarise this**, **Translate this**, **Explain this**.
|
||||
- **Continue the last chat** the assistant made, from where it stopped; and every question in
|
||||
the sheet carries on the same chat, until **New chat**.
|
||||
- **Voice reply**: a spoken question is answered aloud through your instance's text-to-speech
|
||||
(switch it off at the top), and **Read aloud** reads any answer.
|
||||
- **Open in app** carries on the same chat in the app.
|
||||
- Why there is no wake word is said where you look for one: on stock Android only the
|
||||
assistant built into the phone may listen for one.
|
||||
- **Settings › Voice input** says what each choice is: **LLeMbas** is your instance's
|
||||
speech-to-text, through the server -- the recording goes to your instance and nowhere else;
|
||||
**Phone (Google or the system's)** is the phone's own recogniser -- words appear as you speak,
|
||||
and the recording goes wherever that recogniser sends it. No Google library is in the app: it
|
||||
uses whichever recogniser the phone has, and says so when it has none.
|
||||
|
||||
- **What a reply is doing, in the words every LLeMbas app uses.** Under a reply being written
|
||||
the app draws the server's progress -- *Queued*, *Waiting for* a model *and why*, *Loading*,
|
||||
*Reading the prompt: 1999 / 3000 tokens (66%)*, *Thinking*, *Writing: 12.5 tok/s*,
|
||||
*Running bash: bun test*, *Waiting for you*, *Waiting for subagents*, *Compacting*,
|
||||
*Retrying in 7 s*, *Stopped*, *Failed* -- with how long it has been at it, ticking each
|
||||
second (`· 1m 05s`). The same in the assistant's sheet. A server that does not send it yet
|
||||
is shown as before. A scheduled run under way says it too (*Waiting for coder: all its
|
||||
slots are in use*). The words are your instance's, in your language.
|
||||
|
||||
- **Subagents, as a list**: while a reply runs with subagents, the activity sheet
|
||||
shows the main agent and each subagent -- its name, its position, what it is doing now and
|
||||
how full its context is -- with the ones that ended after them, dimmed, saying how each ended
|
||||
(*done*, *out of context*, *stopped*), and the open slots. A subagent's row opens its
|
||||
conversation, read-only. In an agent chat the Subagents setting is there too -- a new one's
|
||||
included -- and goes to the computer the chat runs on, which runs them; a computer whose CLI
|
||||
is too old to is said beside it.
|
||||
- **An approval says which subagent asks** -- *Subagent parser (s1), reviews the parser,
|
||||
asks:* -- when a subagent needs something nobody in its tree may allow.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A corrected command on an approval runs as corrected.** A linked computer's approval card
|
||||
now shows its heading (*Run a command*), the command itself in the box you can change, and
|
||||
the server's reason; Allow sends your correction only when you changed it. The card names the
|
||||
subagent asking, when one does. (Pinned to the server's current `dev` contract.)
|
||||
|
||||
## [1.0.0-beta.4] — 2026-11-09
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.7 or later for the Subagents setting and the panel's compaction).
|
||||
|
||||
For LLeMbas server 2.0.0-beta.7 (an older 2.0 server works; the app then guesses whether
|
||||
subagents are offered and works out auto-compact itself).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Subagents, by that name.** Everything the app says about the work a chat hands off now
|
||||
calls it a subagent -- the strip, the activity sheet and the chat's options. The team's size
|
||||
in Options is **Subagents**, Min and Max -- shown when the instance says subagents are
|
||||
offered for the chat (or, for a new chat, for the model chosen), and only up to the most the
|
||||
instance allows. When the chat's model serves one request at a time, the setting says that
|
||||
subagents need another model, on another server, named in the chat. Which model a subagent
|
||||
runs on is not a setting: it is the chat's own, unless you name another in the chat.
|
||||
- **Subagents is one slider with two thumbs, Min and Max**, from 1 to the most the instance
|
||||
allows, in whole agents and with the values beside it ("Min 1 · Max 4"). The numbers count the
|
||||
chat's own agent: **1 is the agent alone, with no subagents**, and Max 4 is the agent and up to
|
||||
3 subagents. The options button says the same ("Subagents: Min 1 · Max 4").
|
||||
- **The activity sheet, laid out as a side panel is on a computer**, and always one tap away:
|
||||
the button at the top of every chat (a new one too) opens it as a sheet. **Context**: how
|
||||
much of the window is used, in per cent and in tokens of the window, a bar split by what
|
||||
fills it, each part with its tokens and share, how far it is to compacting by itself -- and a
|
||||
**Compact** button that does it now. **Background tasks**: what is running -- subagents, a
|
||||
team's members and background commands -- each on a card with how long it has run and a
|
||||
stop button (which asks first); a card opens to what it was asked, its latest step, what it
|
||||
is writing and its whole conversation, and folds those working under it into "N under it".
|
||||
The finished ones are folded away under **Finished**. Then the team's **Room** and the
|
||||
**Plan**.
|
||||
- **The line above the message box** says what runs in the background -- "2 running · 1 queued
|
||||
· 4 finished" -- only while anything does, and opens the sheet.
|
||||
|
||||
## [1.0.0-beta.3] — 2026-11-09
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.6 or later for scheduled tasks).
|
||||
|
||||
### Changed
|
||||
|
||||
- **A new look, shaped like the AI apps people know.** The app opens on a **new chat** -- the
|
||||
model's picture, a greeting, a few suggestions and the message box -- instead of a list.
|
||||
**Chats are in the drawer** (the menu button, or a swipe from the edge): search, New chat, New
|
||||
agent chat, Files, Scheduled, then today's chats, the earlier ones and the agent chats, with
|
||||
Settings and the account at the foot. Long-press a chat there to archive it.
|
||||
- **The model is the title**: its picture and name at the top of the chat; tap it to choose
|
||||
another in a sheet that shows each model's picture, what it can do (sees images, uses tools,
|
||||
its context window) and how it thinks (a Thinking switch, or its effort levels).
|
||||
- **The conversation reads cleaner**: your messages in bubbles on the right, the model's answers
|
||||
full width; its thinking and each round of tools fold into small chips you can open; code
|
||||
comes in its own block with the language and a Copy button; attached pictures show as
|
||||
thumbnails; three quiet dots while an answer is being written. Under an answer: Copy and
|
||||
Regenerate. A long press on a message: Copy, Select text, Edit (yours) or Regenerate.
|
||||
- **The message box** is one rounded field: **+** to attach (camera, photos, files), **Options**
|
||||
for what the model offers -- Thinking on or off or the effort level, the team's size, Plan
|
||||
first (or an agent chat's mode, and a new agent chat's device and folder) -- the microphone,
|
||||
and Send, which becomes Stop while an answer is being written.
|
||||
- **Settings** are grouped lists, and link to Android's notification settings for the app.
|
||||
|
||||
### Added
|
||||
|
||||
- **Scheduled**: in the drawer. Each scheduled task with its rule in words, how its last run
|
||||
went (or that it is running now) and when it runs next, and a switch to pause it; the list
|
||||
keeps itself current while it is open. A task's page has Run now (which does not use up the
|
||||
next scheduled run), Pause, its next runs and its history: each run's status, when, the model
|
||||
that ran it -- and which one it stood in for when the first was busy -- the first lines of its
|
||||
result, or why it failed or what it is waiting for and when it tries again. **A run opens its
|
||||
result in full**, with Open its chat. A new task is said in words; the instance shows what it
|
||||
understood -- the title, the rule in words, the instruction and the next five runs -- before
|
||||
anything is saved, and says why when it could not make out all of it. Editing starts from
|
||||
the words the task was made from. **Models for scheduled tasks** (the button at the top of
|
||||
Scheduled): the models scheduled work runs on, in the order they are tried, which are free
|
||||
right now, and a tick to leave one out. Needs a LLeMbas server with scheduling (2.0.0-beta.6);
|
||||
an older one says so.
|
||||
- **Notifications for scheduled tasks**, on two channels of their own (results, and failures).
|
||||
They carry no content -- the instance sends only that a task finished or failed, and which
|
||||
run -- and on the lock screen they show only the app's name and that sentence. A tap, or
|
||||
**Open**, goes to the run's result; a failure offers **Pause**, and after three failures in
|
||||
a row the notification asks whether to pause the task.
|
||||
- **Screenshots of every screen on each change**: the CI run renders the screens with made-up
|
||||
data, light and dark, on a large and a small phone and with large type, and keeps the
|
||||
pictures with the run.
|
||||
|
||||
## [1.0.0-beta.2] — 2026-11-09
|
||||
|
||||
For LLeMbas server 2.0 (2.0.0-beta.5 or later for the activity panel, the Thinking switch and team
|
||||
|
||||
@@ -40,13 +40,34 @@ certificate). The app trusts CAs you installed, as the browser does.
|
||||
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.
|
||||
A wake word is there if you want one, off by default: Settings › Assistant › Wake word, a
|
||||
greeting and a name in English ("Hey Assistant"). Android reserves its low-power, always-on
|
||||
hotword detection for the system's own preinstalled assistant, so LLeMbas listens with an
|
||||
on-device engine in a microphone service, with a notification up the whole time; nothing leaves
|
||||
the phone before the word. Not in the F-Droid build.
|
||||
|
||||
The wake word and the hands-free parts of the voice assistant (listening by itself, the spoken
|
||||
conversation) are **experimental**: new, and tried on few phones. Settings marks them so.
|
||||
|
||||
Over the lock screen the assistant can listen (the wake word, a headset's button), but nothing
|
||||
goes to the instance and no answer is shown or spoken until the phone is unlocked: with the
|
||||
instance's speech-to-text the question waits on the phone as a recording.
|
||||
|
||||
## Build
|
||||
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is the usual
|
||||
`./gradlew assembleFullDebug` with JDK 17 and the Android SDK.
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is
|
||||
`scripts/fetch-wakeword.py` (the wake-word engine and model, hash-pinned, never committed) and
|
||||
then the usual `./gradlew assembleFullStandardDebug` with JDK 17 and the Android SDK.
|
||||
|
||||
A release is three APKs of one app, signed with one key:
|
||||
|
||||
| File | Build | What it is |
|
||||
|---|---|---|
|
||||
| `llembas-android-<version>.apk` | `fullStandard` | The app: updates itself, has the wake word. The one to install. |
|
||||
| `llembas-android-<version>-notifications.apk` | `fullNotifications` | The same, plus a notification listener for *notification summaries*. Separate because Google Play Protect blocks installing an app from outside the Play Store that can read notifications; it installs over the standard one, and back. |
|
||||
| `llembas-android-<version>-fdroid.apk` | `fdroidStandard` | No updater and no wake-word engine: only what F-Droid can build from source. |
|
||||
|
||||
`scripts/check-apk.sh` checks each built file for what it must and must not declare.
|
||||
|
||||
Three things are generated from the server at one ref; the first two are pinned with a lock
|
||||
file CI checks, and CI checks the strings against the code:
|
||||
|
||||
+70
-3
@@ -1,3 +1,4 @@
|
||||
import java.time.Duration
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
@@ -30,7 +31,7 @@ android {
|
||||
// The one source of the version. versionCode is derived from it, so the two cannot
|
||||
// drift, and a beta sorts below its release: 1.0.0-beta.1 -> 1000001,
|
||||
// 1.0.0-beta.2 -> 1000002, 1.0.0 -> 1000099, 1.2.3 -> 1020399.
|
||||
versionName = "1.0.0-beta.2"
|
||||
versionName = "1.0.0-beta.11"
|
||||
versionCode = versionName!!.split("-beta.").let { parts ->
|
||||
val (a, b, c) = parts[0].split(".").map { it.toInt() }
|
||||
val pre = if (parts.size == 2) parts[1].toInt() else 99
|
||||
@@ -66,17 +67,31 @@ android {
|
||||
isShrinkResources = true
|
||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||
signingConfig = signingConfigs.findByName("release")
|
||||
// The wake-word engine's native code, for phones only: a release carries no x86_64
|
||||
// library (36 MB that only an emulator would load).
|
||||
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") }
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix = ".debug"
|
||||
// CI's run number, so a tester can tell two test builds apart in Settings › About.
|
||||
versionNameSuffix = "-debug" + (System.getenv("GITHUB_RUN_NUMBER")?.let { ".$it" } ?: "")
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
// A test build also runs on the 64-bit emulator (not 32-bit x86).
|
||||
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
|
||||
}
|
||||
}
|
||||
|
||||
// `full` updates itself from llembas.eu; `fdroid` has no updater, because F-Droid updates it.
|
||||
flavorDimensions += "distribution"
|
||||
// Two questions, three APKs.
|
||||
//
|
||||
// `distribution`: `full` updates itself from llembas.eu and has the wake-word engine; `fdroid`
|
||||
// has neither, because F-Droid updates it and builds every library from source.
|
||||
//
|
||||
// `reading`: whether the app declares a notification listener (notification summaries).
|
||||
// `standard` does not -- no listener, no permission, nothing of it in the manifest -- because
|
||||
// Google Play Protect blocks installing an app from outside the Play Store that can read
|
||||
// notifications. `notifications` is the full build plus the listener: the same application
|
||||
// id and the same key, so it installs over the standard one as an ordinary update.
|
||||
flavorDimensions += listOf("distribution", "reading")
|
||||
productFlavors {
|
||||
create("full") {
|
||||
dimension = "distribution"
|
||||
@@ -86,6 +101,26 @@ android {
|
||||
dimension = "distribution"
|
||||
buildConfigField("boolean", "SELF_UPDATE", "false")
|
||||
}
|
||||
create("standard") {
|
||||
dimension = "reading"
|
||||
}
|
||||
create("notifications") {
|
||||
dimension = "reading"
|
||||
}
|
||||
}
|
||||
|
||||
androidResources {
|
||||
// The wake-word model is read as files the engine opens itself: stored as it is, never
|
||||
// deflated a second time (it does not shrink, and nothing has to inflate it on the phone).
|
||||
noCompress += "onnx"
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
// The engine is called through its JNI library alone, which needs only onnxruntime;
|
||||
// the C and C++ API libraries its AAR also carries are for other kinds of caller.
|
||||
excludes += listOf("**/libsherpa-onnx-c-api.so", "**/libsherpa-onnx-cxx-api.so")
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
@@ -106,6 +141,21 @@ android {
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
// The screenshot tests (`shots/`) render the screens on the JVM with Robolectric, and
|
||||
// Roborazzi writes each to app/build/screenshots/ -- recorded every run, never compared:
|
||||
// they are for looking at, and CI uploads them. Nothing of this reaches the APK.
|
||||
unitTests.isIncludeAndroidResources = true
|
||||
unitTests.all { test ->
|
||||
test.systemProperty("roborazzi.test.record", "true")
|
||||
test.systemProperty("robolectric.pixelCopyRenderMode", "hardware")
|
||||
test.maxHeapSize = "3g"
|
||||
// Name each test as it starts, so a run that stops in one says which.
|
||||
test.testLogging {
|
||||
events("started", "passed", "failed", "skipped")
|
||||
exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
|
||||
}
|
||||
test.timeout.set(Duration.ofMinutes(20))
|
||||
}
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
@@ -114,6 +164,14 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// fullStandard, fullNotifications and fdroidStandard: there is no F-Droid build with the listener.
|
||||
androidComponents {
|
||||
beforeVariants { variant ->
|
||||
val flavors = variant.productFlavors.toMap()
|
||||
if (flavors["distribution"] == "fdroid" && flavors["reading"] == "notifications") variant.enable = false
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
@@ -140,8 +198,17 @@ dependencies {
|
||||
implementation(libs.markwon.tables)
|
||||
implementation(libs.markwon.strikethrough)
|
||||
implementation(libs.unifiedpush.connector)
|
||||
// The wake-word engine, sherpa-onnx (Apache-2.0), in the `full` build only: its prebuilt Android
|
||||
// library, fetched hash-pinned by scripts/fetch-wakeword.py (never committed). The `fdroid`
|
||||
// build, which F-Droid builds from source, has no engine (src/fdroid/.../wake/Engine.kt).
|
||||
add("fullImplementation", files("libs/sherpa-onnx-2.0.1.aar"))
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
testImplementation(libs.okhttp.mockwebserver)
|
||||
testImplementation(platform(libs.compose.bom))
|
||||
testImplementation(libs.compose.ui.test.junit4)
|
||||
testImplementation(libs.robolectric)
|
||||
testImplementation(libs.roborazzi)
|
||||
testImplementation(libs.roborazzi.compose)
|
||||
}
|
||||
Vendored
+3
@@ -17,3 +17,6 @@
|
||||
-dontwarn org.conscrypt.**
|
||||
-dontwarn org.bouncycastle.**
|
||||
-dontwarn org.openjsse.**
|
||||
|
||||
# The wake-word engine's JNI reads its config classes' fields by name.
|
||||
-keep class com.k2fsa.sherpa.onnx.** { *; }
|
||||
@@ -0,0 +1,14 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* The F-Droid build has no wake-word engine: F-Droid builds every library from source, and the
|
||||
* engine (sherpa-onnx, Apache-2.0) comes to the other build as its project's prebuilt Android
|
||||
* library. Settings says so; everything else about the wake word is the same code in both.
|
||||
*/
|
||||
object WakeEngine {
|
||||
const val AVAILABLE = false
|
||||
|
||||
fun create(context: Context, keywords: String): WakeDetector = throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
import com.k2fsa.sherpa.onnx.FeatureConfig
|
||||
import com.k2fsa.sherpa.onnx.KeywordSpotter
|
||||
import com.k2fsa.sherpa.onnx.KeywordSpotterConfig
|
||||
import com.k2fsa.sherpa.onnx.OnlineModelConfig
|
||||
import com.k2fsa.sherpa.onnx.OnlineStream
|
||||
import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The wake-word engine: sherpa-onnx's keyword spotter (Apache-2.0) with its small English model
|
||||
* (a 3.3M-parameter zipformer, int8, Apache-2.0), both fetched hash-pinned at build time by
|
||||
* `scripts/fetch-wakeword.py`. It runs on the phone's CPU, one thread, on the 16 kHz samples the
|
||||
* service hands it; nothing leaves the phone.
|
||||
*
|
||||
* The model's files are copied out of the APK's assets into the app's no-backup files
|
||||
* ([unpackWakeModel]: by stream, keyed by the model's version), so the engine reads them as files
|
||||
* beside a keywords file written for the chosen phrase.
|
||||
*/
|
||||
object WakeEngine {
|
||||
const val AVAILABLE = true
|
||||
|
||||
private val FILES = listOf("encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt")
|
||||
|
||||
/**
|
||||
* The engine for [keywords] (the keywords file's text). Throws a [WakeError] that says which
|
||||
* half failed -- the model's files or the engine -- and never returns nothing.
|
||||
*
|
||||
* One at a time: two service instances may overlap for a moment (the wake word turned off and
|
||||
* on again), and the unpacking and the keywords file are shared. The keywords go into a file
|
||||
* of this call's own, which the engine reads as it is made and which is gone afterwards.
|
||||
*/
|
||||
@Synchronized
|
||||
fun create(context: Context, keywords: String): WakeDetector {
|
||||
val dir = File(context.noBackupFilesDir, "wakeword")
|
||||
try {
|
||||
unpackWakeModel({ context.assets.open("wakeword/$it") }, dir, FILES)
|
||||
} catch (e: Exception) {
|
||||
throw WakeError(WakeFailure.Model, e)
|
||||
}
|
||||
checkKeywords(keywords, File(dir, "tokens.txt").readText())
|
||||
var file: File? = null
|
||||
try {
|
||||
val written = File.createTempFile("keywords", ".txt", dir)
|
||||
file = written
|
||||
written.writeText(keywords)
|
||||
val config = KeywordSpotterConfig(
|
||||
featConfig = FeatureConfig(sampleRate = RATE, featureDim = 80),
|
||||
modelConfig = OnlineModelConfig(
|
||||
transducer = OnlineTransducerModelConfig(
|
||||
encoder = File(dir, "encoder.int8.onnx").path,
|
||||
decoder = File(dir, "decoder.int8.onnx").path,
|
||||
joiner = File(dir, "joiner.int8.onnx").path,
|
||||
),
|
||||
tokens = File(dir, "tokens.txt").path,
|
||||
modelType = "zipformer2",
|
||||
numThreads = 1,
|
||||
),
|
||||
keywordsFile = written.path,
|
||||
// The engine's own default (the Kotlin wrapper's is 2). The phrase counts once
|
||||
// MORE than this many blank frames follow it -- two frames, about 80 ms of
|
||||
// anything that is not the phrase going on. So: say it, then a short pause; a
|
||||
// question run straight into the name can be missed.
|
||||
numTrailingBlanks = 1,
|
||||
)
|
||||
return SherpaDetector(KeywordSpotter(null, config))
|
||||
} catch (e: Throwable) {
|
||||
// UnsatisfiedLinkError included: a phone whose processor the library was not built for.
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
} finally {
|
||||
file?.delete()
|
||||
}
|
||||
}
|
||||
|
||||
private const val RATE = 16_000
|
||||
|
||||
private class SherpaDetector(private val spotter: KeywordSpotter) : WakeDetector {
|
||||
private val stream: OnlineStream = spotter.createStream()
|
||||
|
||||
override fun accept(samples: FloatArray): Boolean {
|
||||
stream.acceptWaveform(samples, RATE)
|
||||
while (spotter.isReady(stream)) {
|
||||
spotter.decode(stream)
|
||||
if (spotter.getResult(stream).keyword.isNotBlank()) {
|
||||
spotter.reset(stream)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun release() {
|
||||
stream.release()
|
||||
spotter.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,37 @@
|
||||
<!-- 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" />
|
||||
<!-- A spoken conversation through a Bluetooth headset: its microphone made the route. -->
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<!-- The wake word (opt-in): a microphone foreground service, and "tap to listen again"
|
||||
after a restart. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<!-- Phone actions: an alarm or a timer, set through the clock app once the person confirms. -->
|
||||
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
|
||||
<!-- Phone actions: run a Tasker task by its name (Tasker asks the person to allow it). -->
|
||||
<uses-permission android:name="net.dinglisch.android.tasker.PERMISSION_RUN_TASKS" />
|
||||
|
||||
<queries>
|
||||
<!-- UnifiedPush distributors (ntfy and others) are found by this action. -->
|
||||
<intent>
|
||||
<action android:name="org.unifiedpush.android.distributor.REGISTER" />
|
||||
</intent>
|
||||
<!-- The phone's own speech recognisers, for Settings › Voice input › Phone. -->
|
||||
<intent>
|
||||
<action android:name="android.speech.RecognitionService" />
|
||||
</intent>
|
||||
<!-- Phone actions: "open an app" by its name, and the navigation apps a route goes to. -->
|
||||
<intent>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent>
|
||||
<package android:name="com.google.android.apps.maps" />
|
||||
<package android:name="net.osmand.plus" />
|
||||
<package android:name="net.osmand" />
|
||||
<package android:name="net.osmand.dev" />
|
||||
<package android:name="net.dinglisch.android.taskerm" />
|
||||
</queries>
|
||||
|
||||
<application
|
||||
@@ -20,6 +45,7 @@
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:networkSecurityConfig="@xml/network_security_config"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.Lembas">
|
||||
@@ -33,14 +59,18 @@
|
||||
<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). -->
|
||||
<!-- The assistant's sheet as an activity: the tile, the widget, the shortcuts,
|
||||
ACTION_ASSIST, a headset's voice button, and the lock-screen path (it asks to
|
||||
unlock before sending anything). Exported for Android's own actions; what only the
|
||||
app's own parts may ask of it is told apart in OwnIntents.kt. It handles
|
||||
configuration changes itself (Compose redraws): turned, folded or switched to the
|
||||
dark theme, it is not made again, and neither is the question it holds. -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|density|fontScale"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
@@ -50,6 +80,15 @@
|
||||
<action android:name="android.intent.action.ASSIST" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<!-- A headset's voice button: the sheet opens listening. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VOICE_COMMAND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.speech.action.VOICE_SEARCH_HANDS_FREE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
@@ -57,7 +96,9 @@
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:label="@string/share_label"
|
||||
android:taskAffinity="">
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
@@ -73,6 +114,25 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Phone actions: asks another app for a result (OsmAnd's get_info) and goes. -->
|
||||
<activity
|
||||
android:name=".actions.ActionRunner$ResultActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.Lembas.Sheet" />
|
||||
|
||||
<!-- The home-screen widget: Ask, the microphone, the last assistant chat. -->
|
||||
<receiver
|
||||
android:name=".widget.AskWidget"
|
||||
android:exported="true"
|
||||
android:label="@string/tile_ask">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_ask" />
|
||||
</receiver>
|
||||
|
||||
<!-- The digital assistant: Settings › Default apps › Digital assistant app. -->
|
||||
<service
|
||||
android:name=".assist.LembasAssistService"
|
||||
@@ -107,6 +167,8 @@
|
||||
android:icon="@drawable/ic_notification"
|
||||
android:label="@string/tile_ask"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<!-- A button, not a switch. -->
|
||||
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="false" />
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
@@ -120,10 +182,35 @@
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<!-- The wake word: listens only while its notification is up (wake/WakeWordService.kt). -->
|
||||
<service
|
||||
android:name=".wake.WakeWordService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="microphone" />
|
||||
|
||||
<receiver
|
||||
android:name=".wake.WakeBootReceiver"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
|
||||
<receiver
|
||||
android:name=".push.CardActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A report's Mark read, from its notification. -->
|
||||
<receiver
|
||||
android:name=".push.ReportActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A scheduled task's Pause, from its notification. -->
|
||||
<receiver
|
||||
android:name=".push.ScheduleActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A photo for the composer: the camera app writes into one file in the cache. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.LocaleManager
|
||||
import android.content.Context
|
||||
import android.content.res.Configuration
|
||||
import android.os.Build
|
||||
import android.os.LocaleList
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The app's language. By default the account's, from the server (`/api/v2/me`'s `language`), so
|
||||
* a phone set to one language shows the app in the language the person chose on their instance;
|
||||
* Settings › Language can choose the phone's language instead, or any language the app has.
|
||||
*
|
||||
* Android 13 and newer keep a per-app language themselves (`LocaleManager`, and the system's own
|
||||
* Settings › Apps › LLeMbas › Language, which `res/xml/locales_config.xml` feeds). Older phones
|
||||
* have none: there the chosen language is kept in a small synchronous file and every activity
|
||||
* wraps its context in it ([wrap]), because the DataStore is read too late for `attachBaseContext`.
|
||||
*/
|
||||
object AppLanguage {
|
||||
/** Prefs.language: the account's language (the default). */
|
||||
const val ACCOUNT = ""
|
||||
|
||||
/** Prefs.language: the phone's language. */
|
||||
const val PHONE = "system"
|
||||
|
||||
/**
|
||||
* The languages the app has, by code, each named in itself. The same set as the
|
||||
* `values-*` folders `scripts/gen-strings.py` writes, plus English; a test holds them equal.
|
||||
*/
|
||||
val LANGUAGES: List<Pair<String, String>> = listOf(
|
||||
"en" to "English",
|
||||
"cs" to "Čeština",
|
||||
"de" to "Deutsch",
|
||||
"es" to "Español",
|
||||
"fr" to "Français",
|
||||
"hu" to "Magyar",
|
||||
"it" to "Italiano",
|
||||
"pl" to "Polski",
|
||||
"sk" to "Slovenčina",
|
||||
)
|
||||
|
||||
private val CODES = LANGUAGES.map { it.first }.toSet()
|
||||
|
||||
/** A language's own name, or null for one the app does not have. */
|
||||
fun name(code: String?): String? = LANGUAGES.firstOrNull { it.first == code?.lowercase()?.substringBefore('-')?.substringBefore('_') }?.second
|
||||
|
||||
/** The app's code for a server's language (`sk`, `pt_BR` -> `pt`), or null if the app lacks it. */
|
||||
fun known(code: String?): String? = code?.trim()?.lowercase()?.substringBefore('-')?.substringBefore('_')?.takeIf { it in CODES }
|
||||
|
||||
/**
|
||||
* The language the app should be in: a language tag, or null for the phone's own.
|
||||
* [choice] is Prefs.language; [account] the account's language as the server last said it.
|
||||
* An account in a language the app does not have follows the phone, rather than English.
|
||||
*/
|
||||
fun effective(choice: String, account: String): String? = when (choice) {
|
||||
ACCOUNT -> known(account)
|
||||
PHONE -> null
|
||||
else -> known(choice)
|
||||
}
|
||||
|
||||
private const val FILE = "language"
|
||||
private const val APPLIED = "applied"
|
||||
|
||||
/** What [apply] last set; null if it never ran. */
|
||||
fun applied(context: Context): String? = context.getSharedPreferences(FILE, Context.MODE_PRIVATE).getString(APPLIED, null)
|
||||
|
||||
/**
|
||||
* What the system says the app's language is now (Android 13+): "" for the phone's. Differs
|
||||
* from [applied] when the person chose a language in the system's settings for the app.
|
||||
*/
|
||||
fun systemChoice(context: Context): String? {
|
||||
if (Build.VERSION.SDK_INT < 33) return null
|
||||
val locales = context.getSystemService(LocaleManager::class.java)?.applicationLocales ?: return null
|
||||
return if (locales.isEmpty) "" else locales[0].language
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the app in [tag] (null: the phone's language). Does nothing when that is already so,
|
||||
* so a running app is not recreated for nothing. Android 13+ recreates the activities
|
||||
* itself; an older phone recreates [activity].
|
||||
*/
|
||||
fun apply(context: Context, tag: String?, activity: Activity? = null) {
|
||||
val value = tag.orEmpty()
|
||||
if (applied(context) == value && (Build.VERSION.SDK_INT < 33 || systemChoice(context) == value)) return
|
||||
context.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit().putString(APPLIED, value).commit()
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
context.getSystemService(LocaleManager::class.java)?.applicationLocales =
|
||||
if (value.isEmpty()) LocaleList.getEmptyLocaleList() else LocaleList.forLanguageTags(value)
|
||||
} else {
|
||||
activity?.recreate()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [base] in the chosen language, for `attachBaseContext` and for a window that is not an
|
||||
* activity's (the assistant's sheet). Android 13+ does this itself; the context is returned
|
||||
* as it is there.
|
||||
*/
|
||||
fun wrap(base: Context): Context {
|
||||
if (Build.VERSION.SDK_INT >= 33) return base
|
||||
val tag = base.getSharedPreferences(FILE, Context.MODE_PRIVATE).getString(APPLIED, null)
|
||||
if (tag.isNullOrEmpty()) return base
|
||||
val locale = Locale.forLanguageTag(tag)
|
||||
val config = Configuration(base.resources.configuration).apply { setLocales(LocaleList(locale)) }
|
||||
return base.createConfigurationContext(config)
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,86 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.os.Bundle
|
||||
import eu.llembas.android.api.EventsHub
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.auth.InstanceStore
|
||||
import eu.llembas.android.wake.AppVisibility
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
|
||||
/** The process: one store of instances, and the notification channels, made once. */
|
||||
class LembasApp : Application() {
|
||||
lateinit var instances: InstanceStore
|
||||
private set
|
||||
|
||||
/** The one connection to the person's events route, shared by all that watch it. */
|
||||
val events = EventsHub(CoroutineScope(SupervisorJob() + Dispatchers.Default))
|
||||
|
||||
/** The events route of the instance in use, as its frames; null when not signed in. */
|
||||
suspend fun eventFrames(): Flow<Frame>? {
|
||||
val instance = instances.current() ?: return null
|
||||
val api = instances.clientFor(instance)
|
||||
return events.frames(instance.id) { StreamClient(api).watch { api.events() } }
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
object : ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) = AppVisibility.activityStarted()
|
||||
|
||||
override fun onActivityStopped(activity: Activity) = AppVisibility.activityStopped()
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
|
||||
|
||||
override fun onActivityDestroyed(activity: Activity) = Unit
|
||||
},
|
||||
)
|
||||
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_SCHEDULED, getString(R.string.channel_scheduled), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_SCHEDULED_FAILURES, getString(R.string.channel_scheduled_failures), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_REPORTS_HIGH, getString(R.string.channel_reports_high), NotificationManager.IMPORTANCE_HIGH),
|
||||
).onEach { it.lockscreenVisibility = android.app.Notification.VISIBILITY_PRIVATE } +
|
||||
// A new version of the app says nothing about the account.
|
||||
NotificationChannel(CHANNEL_UPDATES, getString(R.string.channel_updates), NotificationManager.IMPORTANCE_LOW),
|
||||
)
|
||||
// LLeMbas 2.0 has no reports, so 0.1's channel for them goes rather than sit empty in
|
||||
// the system's settings.
|
||||
// 0.1's channel for its reports goes rather than sit empty in the system's settings;
|
||||
// the reports of LLeMbas 2.0 have a channel of their own (CHANNEL_REPORTS).
|
||||
manager.deleteNotificationChannel("reports")
|
||||
// The launcher's long-press shortcuts, in the app's language as it is now.
|
||||
eu.llembas.android.widget.Shortcuts.publish(this)
|
||||
eu.llembas.android.widget.AskWidget.refresh(this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_REPLIES = "replies"
|
||||
const val CHANNEL_ASKS = "asks"
|
||||
const val CHANNEL_SCHEDULED = "scheduled_results"
|
||||
const val CHANNEL_SCHEDULED_FAILURES = "scheduled_failures"
|
||||
const val CHANNEL_REPORTS = "reports_filed"
|
||||
const val CHANNEL_REPORTS_HIGH = "reports_important"
|
||||
const val CHANNEL_UPDATES = "updates"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
@@ -10,40 +11,82 @@ 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.DrawerValue
|
||||
import androidx.compose.material3.ModalNavigationDrawer
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.rememberDrawerState
|
||||
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.mutableStateMapOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.safeId
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.chat.ChatScreen
|
||||
import eu.llembas.android.ui.chats.ChatsScreen
|
||||
import eu.llembas.android.ui.files.FilesScreen
|
||||
import eu.llembas.android.ui.home.ArchivedScreen
|
||||
import eu.llembas.android.ui.home.ChatsViewModel
|
||||
import eu.llembas.android.ui.home.DrawerActions
|
||||
import eu.llembas.android.ui.home.DrawerContent
|
||||
import eu.llembas.android.ui.memory.MemoryScreen
|
||||
import eu.llembas.android.ui.reports.ReportScreen
|
||||
import eu.llembas.android.ui.reports.ReportsScreen
|
||||
import eu.llembas.android.ui.scheduled.RunScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleEditScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduleScreen
|
||||
import eu.llembas.android.ui.scheduled.ScheduledScreen
|
||||
import eu.llembas.android.ui.scheduled.SchedulingModelsScreen
|
||||
import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.wake.WakeBootReceiver
|
||||
import eu.llembas.android.wake.WakeEngine
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private data class Loaded(val instance: Instance?)
|
||||
|
||||
/** Where a notification (or the assistant, or a share) asked the app to open. */
|
||||
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null, val report: String? = null)
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
/** A chat a notification, the assistant or a share asked to open; consumed once. */
|
||||
private val opening = mutableStateOf<String?>(null)
|
||||
/** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */
|
||||
private val opening = mutableStateOf<Opening?>(null)
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
take(intent)
|
||||
followLanguage()
|
||||
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
|
||||
lifecycleScope.launch { runCatching { ReleaseCheck(this@MainActivity).daily() } }
|
||||
if (Build.VERSION.SDK_INT >= 33 &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
@@ -57,73 +100,292 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A wake word that is on, but whose service the phone stopped, listens again -- each time the
|
||||
* app comes to the screen, which is also when a microphone permission given or taken in the
|
||||
* system's settings is noticed ([WakeWordService.start] says which it is).
|
||||
*/
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
lifecycleScope.launch {
|
||||
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the app in the language Settings › Language says: the account's by default. A
|
||||
* language chosen for the app in the system's own settings (Android 13+) since the app last
|
||||
* set one is the person's choice, and is kept as such.
|
||||
*/
|
||||
private fun followLanguage() {
|
||||
lifecycleScope.launch {
|
||||
val store = lembas.instances
|
||||
val system = AppLanguage.systemChoice(this@MainActivity)
|
||||
if (system != null && system != AppLanguage.applied(this@MainActivity).orEmpty()) {
|
||||
store.savePrefs { it.copy(language = system.ifEmpty { AppLanguage.PHONE }) }
|
||||
}
|
||||
store.prefs
|
||||
.map { AppLanguage.effective(it.language, it.accountLanguage) }
|
||||
.distinctUntilChanged()
|
||||
.collect { AppLanguage.apply(applicationContext, it, this@MainActivity) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
take(intent)
|
||||
}
|
||||
|
||||
private fun take(intent: Intent?) {
|
||||
intent?.getStringExtra(Notifications.EXTRA_CHAT)?.let { opening.value = it }
|
||||
// "Tap to listen again" after a restart: the app is on screen now, so the microphone
|
||||
// service may start.
|
||||
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
|
||||
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
|
||||
}
|
||||
// Extras are whatever the sender put there (this activity can be started from outside):
|
||||
// only ids that look like ids go on to become routes.
|
||||
val chat = safeId(intent?.getStringExtra(Notifications.EXTRA_CHAT))
|
||||
val schedule = safeId(intent?.getStringExtra(Notifications.EXTRA_SCHEDULE))
|
||||
val run = safeId(intent?.getStringExtra(Notifications.EXTRA_RUN))
|
||||
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
|
||||
val report = safeId(intent?.getStringExtra(Notifications.EXTRA_REPORT))
|
||||
if (chat == null && schedule == null && report == null) return
|
||||
opening.value = Opening(chat, schedule, run, instance, report)
|
||||
// A notification from another of the person's instances: that one comes into use, and
|
||||
// its pages (keyed by the instance) open what was asked.
|
||||
if (instance != null) {
|
||||
lifecycleScope.launch {
|
||||
if (lembas.instances.active.first()?.id != instance && Push.instance(this@MainActivity, instance) != null) {
|
||||
lembas.instances.use(instance)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Root(open: String?, opened: () -> Unit) {
|
||||
private fun Root(open: Opening?, 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) { Home(instance, open, opened) }
|
||||
}
|
||||
}
|
||||
|
||||
else -> key(instance.id) {
|
||||
val nav = rememberNavController()
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
nav.navigate("chat/$it")
|
||||
opened()
|
||||
/**
|
||||
* The signed-in app: a new chat first, as the AI apps open, with every chat, Files,
|
||||
* Scheduled and Settings in the navigation drawer. A chat or a new chat is a top-level
|
||||
* page (opening one replaces the last; Back leaves the app); Files, Scheduled and
|
||||
* Settings open over it and Back returns.
|
||||
*/
|
||||
@Composable
|
||||
private fun Home(instance: Instance, open: Opening?, opened: () -> Unit) {
|
||||
val nav = rememberNavController()
|
||||
val drawer = rememberDrawerState(DrawerValue.Closed)
|
||||
val scope = rememberCoroutineScope()
|
||||
val chats: ChatsViewModel = viewModel()
|
||||
val list by chats.state.collectAsStateWithLifecycle()
|
||||
val entry by nav.currentBackStackEntryAsState()
|
||||
val route = entry?.destination?.route
|
||||
val current = entry?.arguments?.getString("id")?.takeIf { route == "chat/{id}" }
|
||||
val top: (String) -> Unit = { target ->
|
||||
scope.launch { drawer.close() }
|
||||
nav.navigate(target) {
|
||||
popUpTo(nav.graph.id) { inclusive = true }
|
||||
launchSingleTop = true
|
||||
}
|
||||
}
|
||||
val over: (String) -> Unit = { target ->
|
||||
scope.launch { drawer.close() }
|
||||
nav.navigate(target)
|
||||
}
|
||||
// The account's language, which the app follows unless Settings › Language says
|
||||
// otherwise. Read once per instance in use; kept, so the next start has it at once.
|
||||
LaunchedEffect(instance.id) {
|
||||
runCatching { lembas.instances.clientFor(instance).me() }.onSuccess { me ->
|
||||
me.accountLanguage?.let { language -> lembas.instances.savePrefs { it.copy(accountLanguage = language) } }
|
||||
}
|
||||
}
|
||||
// The list is read again each time the drawer opens, so a new title or a finished
|
||||
// reply's dot is there without a pull.
|
||||
LaunchedEffect(drawer.isOpen) { if (drawer.isOpen) chats.load() }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
// Meant for another instance: left for that one's pages, once it is in use.
|
||||
if (it.instance != null && it.instance != instance.id) return@let
|
||||
when {
|
||||
it.chat != null -> top("chat/${it.chat}")
|
||||
|
||||
it.report != null -> over("report/${it.report}")
|
||||
|
||||
it.schedule != null -> {
|
||||
over("schedule/${it.schedule}")
|
||||
it.run?.let { run -> over("schedule/${it.schedule}/run/$run") }
|
||||
}
|
||||
}
|
||||
NavHost(nav, startDestination = "chats") {
|
||||
composable("chats") {
|
||||
ChatsScreen(
|
||||
onOpen = { nav.navigate("chat/$it") },
|
||||
onNew = { nav.navigate("new") },
|
||||
onNewAgent = { nav.navigate("new-agent") },
|
||||
onSettings = { nav.navigate("settings") },
|
||||
onFiles = { nav.navigate("files") },
|
||||
)
|
||||
}
|
||||
composable("new") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpened = { id ->
|
||||
nav.navigate("chat/$id") { popUpTo("new") { inclusive = true } }
|
||||
},
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
agent = true,
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpened = { id ->
|
||||
nav.navigate("chat/$id") { popUpTo("new-agent") { inclusive = true } }
|
||||
},
|
||||
)
|
||||
}
|
||||
composable("chat/{id}") { entry ->
|
||||
ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() })
|
||||
}
|
||||
composable("files") { FilesScreen(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) }) }
|
||||
opened()
|
||||
}
|
||||
}
|
||||
val actions = remember {
|
||||
object : DrawerActions {
|
||||
override fun newChat() = top("new")
|
||||
|
||||
override fun newAgentChat() = top("new-agent")
|
||||
|
||||
override fun open(chatId: String) = top("chat/$chatId")
|
||||
|
||||
override fun archive(chat: Chat) = chats.archive(chat)
|
||||
|
||||
override fun pin(chat: Chat, pinned: Boolean) = chats.pin(chat, pinned)
|
||||
|
||||
override fun move(chat: Chat, folderId: String?) = chats.move(chat, folderId)
|
||||
|
||||
override fun newFolder(name: String, then: Chat?) = chats.newFolder(name, then)
|
||||
|
||||
override fun renameFolder(folder: Folder, name: String) = chats.renameFolder(folder, name)
|
||||
|
||||
override fun toggleFolder(folder: Folder) = chats.toggleFolder(folder)
|
||||
|
||||
override fun deleteFolder(folder: Folder) = chats.deleteFolder(folder)
|
||||
|
||||
override fun files() = over("files")
|
||||
|
||||
override fun scheduled() = over("scheduled")
|
||||
|
||||
override fun reports() = over("reports")
|
||||
|
||||
override fun archived() = over("archived")
|
||||
|
||||
override fun memory() = over("memory")
|
||||
|
||||
override fun settings() = over("settings")
|
||||
|
||||
override fun more() = chats.more()
|
||||
|
||||
override fun retry() = chats.load()
|
||||
|
||||
override fun search(query: String) = chats.search(query)
|
||||
}
|
||||
}
|
||||
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
|
||||
val reportTitles = remember { mutableStateMapOf<String, String>() }
|
||||
val menu: () -> Unit = { scope.launch { drawer.open() } }
|
||||
ModalNavigationDrawer(
|
||||
drawerState = drawer,
|
||||
// The drawer opens by a swipe only from a chat: elsewhere the swipe is Back's.
|
||||
gesturesEnabled = drawer.isOpen || route == "new" || route == "new-agent" || route == "chat/{id}",
|
||||
drawerContent = {
|
||||
DrawerContent(list, current, listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "), actions)
|
||||
},
|
||||
) {
|
||||
NavHost(nav, startDestination = "new") {
|
||||
composable("new") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
onKind = { agent -> if (agent) top("new-agent") },
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
agent = true,
|
||||
onKind = { agent -> if (!agent) top("new") },
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
)
|
||||
}
|
||||
composable("chat/{id}") { e ->
|
||||
ChatScreen(
|
||||
chatId = e.arguments?.getString("id"),
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
)
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("archived") {
|
||||
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
|
||||
}
|
||||
composable("memory") { MemoryScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("reports") { ReportsScreen(onBack = { nav.popBackStack() }, onOpen = { over("report/$it") }) }
|
||||
composable("report/{id}") { e ->
|
||||
ReportScreen(
|
||||
e.arguments?.getString("id").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onReply = { chat, title ->
|
||||
reportTitles[chat] = title
|
||||
over("report-chat/$chat")
|
||||
},
|
||||
)
|
||||
}
|
||||
// A report's conversation: the ordinary chat screen, entered from the report and
|
||||
// left back to it. It is not among the chats (the server keeps it under Reports),
|
||||
// so nothing here puts it into the drawer's list either.
|
||||
composable("report-chat/{id}") { e ->
|
||||
val id = e.arguments?.getString("id")
|
||||
ChatScreen(
|
||||
chatId = id,
|
||||
onMenu = { nav.popBackStack() },
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { nav.popBackStack() },
|
||||
report = reportTitles[id].orEmpty(),
|
||||
)
|
||||
}
|
||||
composable("scheduled") {
|
||||
ScheduledScreen(
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpen = { over("schedule/$it") },
|
||||
onNew = { over("schedule-new") },
|
||||
onModels = { over("scheduled-models") },
|
||||
)
|
||||
}
|
||||
composable("scheduled-models") {
|
||||
SchedulingModelsScreen(onBack = { nav.popBackStack() })
|
||||
}
|
||||
composable("schedule/{id}") { e ->
|
||||
val id = e.arguments?.getString("id").orEmpty()
|
||||
ScheduleScreen(
|
||||
id,
|
||||
onBack = { nav.popBackStack() },
|
||||
onEdit = { over("schedule-edit/$it") },
|
||||
onOpenRun = { run -> over("schedule/$id/run/$run") },
|
||||
onOpenReport = { report -> over("report/$report") },
|
||||
)
|
||||
}
|
||||
composable("schedule/{id}/run/{run}") { e ->
|
||||
RunScreen(
|
||||
e.arguments?.getString("id").orEmpty(),
|
||||
e.arguments?.getString("run").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpenChat = { top("chat/$it") },
|
||||
onOpenReport = { over("report/$it") },
|
||||
)
|
||||
}
|
||||
composable("schedule-new") {
|
||||
ScheduleEditScreen(null, onBack = { nav.popBackStack() }, onSaved = { id ->
|
||||
nav.navigate("schedule/$id") { popUpTo("schedule-new") { inclusive = true } }
|
||||
})
|
||||
}
|
||||
composable("schedule-edit/{id}") { e ->
|
||||
ScheduleEditScreen(e.arguments?.getString("id"), onBack = { nav.popBackStack() }, onSaved = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("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() }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Carries out a phone action the person confirmed: [run] picks the way -- one intent, the torch, a
|
||||
* media key, or a navigation app -- and answers with done, failed (and why), never silence.
|
||||
*/
|
||||
object ActionRunner {
|
||||
// The reasons go back to the model as the tool's result, so they are written for it, in English.
|
||||
private const val NOT_POSSIBLE = "the phone cannot do this action with these arguments"
|
||||
private const val NO_NAV_APP = "no navigation app chosen or installed (Google Maps or OsmAnd)"
|
||||
private const val NO_DESTINATION =
|
||||
"a stop can only be added with the route's destination: name it (destination), or the person lets LLeMbas ask OsmAnd for it"
|
||||
private const val GOOGLE_CANNOT_STOP = "Google Maps cannot be told to stop navigating; the person stops it there"
|
||||
private const val OSMAND_NEEDS_COORDINATES = "OsmAnd takes a route through stops only with every point's lat and lon"
|
||||
|
||||
/**
|
||||
* [askOsmAnd]: Settings › Phone actions says the person allowed LLeMbas inside OsmAnd, so its
|
||||
* position and the running route's destination may be asked for (`get_info`).
|
||||
*/
|
||||
suspend fun run(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean = false): ActionOutcome {
|
||||
when (action) {
|
||||
"torch" -> return PhoneActions.torch(context, args.bool("on"))
|
||||
"media" -> return PhoneActions.media(context, args.str("command").ifBlank { "toggle" })
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" -> return navigate(context, action, args, nav, askOsmAnd)
|
||||
}
|
||||
val intent = PhoneActions.intentFor(context, action, args)
|
||||
?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return PhoneActions.launch(context, intent, broadcast = action == "automation_intent")
|
||||
}
|
||||
|
||||
private suspend fun navigate(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean): ActionOutcome {
|
||||
val app = nav ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val pkg = app.installed(context) ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val travel = Travel.of(args.str("mode").ifBlank { null })
|
||||
// OsmAnd's own position and destination, if the person allowed LLeMbas to ask it.
|
||||
val info = if (app == NavApp.OsmAnd && askOsmAnd && action != "stop_navigation") osmandInfo(context, pkg) else null
|
||||
val step = when (action) {
|
||||
"navigate" -> args.place("destination")?.let {
|
||||
NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info, replace = args.bool("replace_route") == true)
|
||||
}
|
||||
|
||||
"add_stop" -> args.place("stop")?.let {
|
||||
NavIntents.addStop(app, pkg, it, args.place("destination"), travel, info, NO_DESTINATION)
|
||||
}
|
||||
|
||||
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let {
|
||||
NavIntents.searchNearby(
|
||||
app,
|
||||
pkg,
|
||||
it,
|
||||
info,
|
||||
alongRoute =
|
||||
args.str("near") == "route",
|
||||
)
|
||||
}
|
||||
|
||||
else -> NavIntents.stop(app, pkg, GOOGLE_CANNOT_STOP)
|
||||
} ?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return when (step) {
|
||||
is NavStep.Unsupported -> ActionOutcome(ActionStatus.Failed, step.reason.ifBlank { OSMAND_NEEDS_COORDINATES })
|
||||
|
||||
// The map app comes to the front and stays: it answers nothing more until the person
|
||||
// leaves it, so its having taken the intent is "done".
|
||||
is NavStep.Launch -> PhoneActions.launch(context, step.intent)
|
||||
}
|
||||
}
|
||||
|
||||
/** OsmAnd's `get_info`, when the person allowed it inside OsmAnd; null otherwise, quietly. */
|
||||
private suspend fun osmandInfo(context: Context, pkg: String): OsmAndInfo? {
|
||||
val (code, extras) = forResult(context, NavIntents.osmandInfo(pkg), timeoutMs = 4_000) ?: return null
|
||||
return if (code == Activity.RESULT_OK) OsmAndInfo.of(extras) else null
|
||||
}
|
||||
|
||||
private val waiting = ConcurrentHashMap<Int, CompletableDeferred<Pair<Int, Bundle?>>>()
|
||||
private val ids = AtomicInteger()
|
||||
|
||||
/**
|
||||
* Start [intent] for its result through [ResultActivity] -- a see-through activity of the
|
||||
* app's own, so this works from the assistant's sheet (a voice-interaction session) as well.
|
||||
*/
|
||||
suspend fun forResult(context: Context, intent: Intent, timeoutMs: Long = 60_000): Pair<Int, Bundle?>? {
|
||||
val id = ids.incrementAndGet()
|
||||
val answer = CompletableDeferred<Pair<Int, Bundle?>>()
|
||||
waiting[id] = answer
|
||||
return try {
|
||||
context.startActivity(
|
||||
Intent(context, ResultActivity::class.java)
|
||||
.putExtra(ResultActivity.EXTRA_ID, id)
|
||||
.putExtra(ResultActivity.EXTRA_INTENT, intent)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
withTimeoutOrNull(timeoutMs) { answer.await() }
|
||||
} finally {
|
||||
waiting.remove(id)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun answered(id: Int, code: Int, extras: Bundle?) {
|
||||
waiting[id]?.complete(code to extras)
|
||||
}
|
||||
|
||||
/** Asks another app for a result on [ActionRunner]'s behalf, then goes. Shows nothing of its own. */
|
||||
class ResultActivity : ComponentActivity() {
|
||||
private var id = 0
|
||||
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
answered(id, result.resultCode, result.data?.extras)
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
id = intent.getIntExtra(EXTRA_ID, 0)
|
||||
if (savedInstanceState != null) return
|
||||
@Suppress("DEPRECATION")
|
||||
val target = intent.getParcelableExtra<Intent>(EXTRA_INTENT)
|
||||
if (target == null) {
|
||||
answered(id, Activity.RESULT_CANCELED, null)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
launcher.launch(target)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
answered(id, Activity.RESULT_FIRST_USER, null)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_ID = "eu.llembas.android.RESULT_ID"
|
||||
const val EXTRA_INTENT = "eu.llembas.android.RESULT_INTENT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
|
||||
/** A place for a navigation app: coordinates when the model knows them, else words to search for. */
|
||||
data class Place(val name: String = "", val lat: Double? = null, val lon: Double? = null, val query: String = "") {
|
||||
val hasCoordinates: Boolean get() = lat != null && lon != null
|
||||
val label: String get() = name.ifBlank { query.ifBlank { if (hasCoordinates) "$lat, $lon" else "" } }
|
||||
|
||||
/** What a map app searches for: the words, else the name. */
|
||||
val searchText: String get() = query.ifBlank { name }
|
||||
}
|
||||
|
||||
/** The navigation apps the phone actions drive. */
|
||||
enum class NavApp(val id: String, val packages: List<String>) {
|
||||
GoogleMaps("google", listOf("com.google.android.apps.maps")),
|
||||
|
||||
// OsmAnd: `net.osmand.plus` is OsmAnd+ and the F-Droid build (OsmAnd~); `net.osmand` the free one.
|
||||
OsmAnd("osmand", listOf("net.osmand.plus", "net.osmand", "net.osmand.dev")),
|
||||
;
|
||||
|
||||
/** The package of this app on the phone, if it is installed. */
|
||||
fun installed(context: Context): String? = packages.firstOrNull { isInstalled(context, it) }
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Settings' choice among [installed]: the one named; by default whichever is installed, and
|
||||
* with both installed (or "ask"), null -- the card then offers each.
|
||||
*/
|
||||
fun chosen(pref: String, installed: List<NavApp>): NavApp? = when (pref) {
|
||||
PREF_ASK -> null
|
||||
"" -> installed.singleOrNull()
|
||||
else -> installed.firstOrNull { it.id == pref } ?: installed.singleOrNull()
|
||||
}
|
||||
|
||||
fun installedApps(context: Context): List<NavApp> = entries.filter { it.installed(context) != null }
|
||||
|
||||
const val PREF_ASK = "ask"
|
||||
|
||||
private fun isInstalled(context: Context, pkg: String): Boolean = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
context.packageManager.getPackageInfo(pkg, PackageManager.PackageInfoFlags.of(0))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(pkg, 0)
|
||||
}
|
||||
}.isSuccess
|
||||
}
|
||||
}
|
||||
|
||||
/** How a person travels, as the action names it. */
|
||||
enum class Travel(val id: String, val google: String, val googleNav: String, val osmand: String) {
|
||||
Drive("drive", "driving", "d", "car"),
|
||||
Walk("walk", "walking", "w", "pedestrian"),
|
||||
Bike("bike", "bicycling", "b", "bicycle"),
|
||||
Transit("transit", "transit", "d", "public_transport"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun of(id: String?): Travel = entries.firstOrNull { it.id == id } ?: Drive
|
||||
}
|
||||
}
|
||||
|
||||
/** One request to a navigation app: an [Intent], or why it cannot be done in that app. */
|
||||
sealed interface NavStep {
|
||||
data class Launch(val intent: Intent) : NavStep
|
||||
|
||||
data class Unsupported(val reason: String) : NavStep
|
||||
}
|
||||
|
||||
/**
|
||||
* What OsmAnd itself says about the route, when the person allowed LLeMbas to ask
|
||||
* (OsmAnd › Plugins › … › the app's "Location" access for its API): the phone's position and the
|
||||
* route's destination. Null when not allowed -- the actions then use what the model gave.
|
||||
*/
|
||||
data class OsmAndInfo(val lat: Double?, val lon: Double?, val destination: Place?) {
|
||||
companion object {
|
||||
fun of(extras: Bundle?): OsmAndInfo? {
|
||||
extras ?: return null
|
||||
fun d(key: String) = if (extras.containsKey(key)) extras.getDouble(key) else null
|
||||
val dLat = d("destination_lat")
|
||||
val dLon = d("destination_lon")
|
||||
return OsmAndInfo(d("lat"), d("lon"), if (dLat != null && dLon != null) Place(lat = dLat, lon = dLon) else null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The intents, per app. Google Maps: a route to a place with up to a few stops (its `dir` URL),
|
||||
* a search near here (`geo:0,0?q=`); it cannot take a stop into a route already running, nor be
|
||||
* told to stop -- adding a stop there starts the route again through the stop. OsmAnd: its intent
|
||||
* API (`osmand.api://`, a URI protocol; no OsmAnd code in this app): navigate, a route through
|
||||
* stops as a GPX passed as data, a search near a position, stop navigation.
|
||||
*/
|
||||
object NavIntents {
|
||||
private const val GOOGLE_STOPS = 9
|
||||
|
||||
/** [replace]: a route already running is replaced without the map app asking first (OsmAnd asks otherwise). */
|
||||
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, replace: Boolean = false): NavStep =
|
||||
when (app) {
|
||||
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
|
||||
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info, if (replace) "true" else "false")
|
||||
}
|
||||
|
||||
/** A stop on the way to the route's destination ([destination] from the model, else OsmAnd's own). */
|
||||
fun addStop(app: NavApp, pkg: String, stop: Place, destination: Place?, travel: Travel, info: OsmAndInfo?, noDestination: String): NavStep {
|
||||
val to = destination?.takeIf { it.hasCoordinates || it.searchText.isNotBlank() } ?: info?.destination ?: return NavStep.Unsupported(noDestination)
|
||||
// Planned again from here: the route being replaced is the one the person asked to change.
|
||||
return navigate(app, pkg, to, listOf(stop), travel, info, replace = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* [alongRoute] searches near the running route; OsmAnd is given the phone's position for both
|
||||
* (its search ranks along the route itself while one runs), Google Maps searches near here.
|
||||
*/
|
||||
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?, alongRoute: Boolean = false): NavStep = when {
|
||||
app == NavApp.OsmAnd && info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to query,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"show_search_results" to "true",
|
||||
"force" to "true",
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))).setPackage(pkg))
|
||||
}
|
||||
|
||||
fun stop(app: NavApp, pkg: String, unsupported: String): NavStep = when (app) {
|
||||
NavApp.OsmAnd -> NavStep.Launch(osmandUri(pkg, "stop_navigation"))
|
||||
NavApp.GoogleMaps -> NavStep.Unsupported(unsupported)
|
||||
}
|
||||
|
||||
/** OsmAnd's own account of the route (needs the person's grant inside OsmAnd). */
|
||||
fun osmandInfo(pkg: String): Intent = osmandUri(pkg, "get_info")
|
||||
|
||||
private fun google(pkg: String, destination: Place, stops: List<Place>, travel: Travel): NavStep {
|
||||
if (stops.isEmpty()) {
|
||||
val q = if (destination.hasCoordinates) "${destination.lat},${destination.lon}" else destination.searchText
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${Uri.encode(q)}&mode=${travel.googleNav}")).setPackage(pkg))
|
||||
}
|
||||
val url = Uri.parse("https://www.google.com/maps/dir/").buildUpon()
|
||||
.appendQueryParameter("api", "1")
|
||||
.appendQueryParameter("destination", googlePlace(destination))
|
||||
.appendQueryParameter("waypoints", stops.take(GOOGLE_STOPS).joinToString("|") { googlePlace(it) })
|
||||
.appendQueryParameter("travelmode", travel.google)
|
||||
.appendQueryParameter("dir_action", "navigate")
|
||||
.build()
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, url).setPackage(pkg))
|
||||
}
|
||||
|
||||
private fun googlePlace(p: Place) = if (p.hasCoordinates) "${p.lat},${p.lon}" else p.searchText
|
||||
|
||||
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, force: String): NavStep {
|
||||
val route = stops + destination
|
||||
return when {
|
||||
// Through stops: OsmAnd follows a route given as GPX, which needs every point's coordinates.
|
||||
stops.isNotEmpty() && route.all { it.hasCoordinates } -> NavStep.Launch(
|
||||
osmandUri(pkg, "navigate_gpx", "force" to force).putExtra("data", gpx(route)),
|
||||
)
|
||||
|
||||
stops.isNotEmpty() -> NavStep.Unsupported("")
|
||||
|
||||
destination.hasCoordinates -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate",
|
||||
"dest_lat" to destination.lat.toString(),
|
||||
"dest_lon" to destination.lon.toString(),
|
||||
"dest_name" to destination.label,
|
||||
"profile" to travel.osmand,
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
// Words only: OsmAnd searches them near the phone when it says where the phone is,
|
||||
// else its own search opens with them (geo:0,0?q=).
|
||||
info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to destination.searchText,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"profile" to travel.osmand,
|
||||
"force" to force,
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(destination.searchText))).setPackage(pkg))
|
||||
}
|
||||
}
|
||||
|
||||
private fun osmandUri(pkg: String, command: String, vararg params: Pair<String, String>): Intent {
|
||||
val uri = Uri.Builder().scheme("osmand.api").authority(command).apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }.build()
|
||||
return Intent(Intent.ACTION_VIEW, uri).setPackage(pkg)
|
||||
}
|
||||
|
||||
/** A route as GPX 1.1: its points in order, named. */
|
||||
fun gpx(points: List<Place>): String = buildString {
|
||||
append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
append("<gpx version=\"1.1\" creator=\"LLeMbas\" xmlns=\"http://www.topografix.com/GPX/1/1\"><rte>")
|
||||
for (p in points) {
|
||||
append("<rtept lat=\"${p.lat}\" lon=\"${p.lon}\"><name>")
|
||||
append(p.label.replace("&", "&").replace("<", "<").replace(">", ">"))
|
||||
append("</name></rtept>")
|
||||
}
|
||||
append("</rte></gpx>\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.provider.AlarmClock
|
||||
import android.provider.CalendarContract
|
||||
import android.provider.Settings
|
||||
import android.view.KeyEvent
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
/** How a phone action ended, as the tool's result says it. */
|
||||
enum class ActionStatus(val wire: String) { Done("done"), Declined("declined"), Failed("failed") }
|
||||
|
||||
data class ActionOutcome(val status: ActionStatus, val message: String = "")
|
||||
|
||||
/** The arguments of an action, read leniently: a model writes numbers as strings now and then. */
|
||||
class Args(val json: JsonObject) {
|
||||
private val o get() = json
|
||||
|
||||
fun str(key: String): String = (o[key] as? JsonPrimitive)?.takeIf { it.isString || it.booleanOrNull == null }?.content.orEmpty()
|
||||
|
||||
fun int(key: String): Int? = (o[key] as? JsonPrimitive)?.let { it.intOrNull ?: it.content.toIntOrNull() }
|
||||
|
||||
fun long(key: String): Long? = (o[key] as? JsonPrimitive)?.let { it.longOrNull ?: it.content.toLongOrNull() }
|
||||
|
||||
fun bool(key: String): Boolean? = (o[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.toBooleanStrictOrNull() }
|
||||
|
||||
fun obj(key: String): Args? = (o[key] as? JsonObject)?.let(::Args)
|
||||
|
||||
fun list(key: String): List<JsonElement> = (o[key] as? JsonArray).orEmpty()
|
||||
|
||||
/** A list of strings (or one string, which a model sometimes writes for a list of one). */
|
||||
fun strings(key: String): List<String> = when (val v = o[key]) {
|
||||
is JsonArray -> v.mapNotNull { (it as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty) }
|
||||
is JsonPrimitive -> listOfNotNull(v.content.trim().takeIf { it.isNotEmpty() })
|
||||
else -> emptyList()
|
||||
}
|
||||
|
||||
fun place(key: String): Place? = when (val v = o[key]) {
|
||||
is JsonObject -> placeOf(v)
|
||||
is JsonPrimitive -> v.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun places(key: String): List<Place> = list(key).mapNotNull { e ->
|
||||
when (e) {
|
||||
is JsonObject -> placeOf(e)
|
||||
is JsonPrimitive -> e.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun placeOf(v: JsonObject): Place {
|
||||
fun d(k: String) = (v[k] as? JsonPrimitive)?.let { it.doubleOrNull ?: it.content.toDoubleOrNull() }
|
||||
return Place(
|
||||
name = (v["name"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
lat = d("lat"),
|
||||
lon = d("lon"),
|
||||
query = (v["query"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** A time the model wrote: `YYYY-MM-DDTHH:MM` in the phone's zone, `YYYY-MM-DD`, or with an offset. */
|
||||
fun time(key: String): Long? {
|
||||
val raw = str(key).ifBlank { return null }
|
||||
val zone = ZoneId.systemDefault()
|
||||
return runCatching { LocalDateTime.parse(raw).atZone(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { LocalDate.parse(raw).atStartOfDay(zone).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone actions a model may propose (`phone_action`), carried out with Android's standard
|
||||
* intents once the person tapped Do it on the card. Each one either opens the app that does it,
|
||||
* with everything filled in (an alarm, an event, a draft -- the person sends a message or saves
|
||||
* an event there themselves), or does a small thing at once (the torch, play/pause).
|
||||
*
|
||||
* Nothing here runs without the card's Do it, and none of it from the lock screen. A model's
|
||||
* words are data: a URL opens only for http and https, a broadcast never names a system action,
|
||||
* a phone number goes to the dialler and is never called.
|
||||
*/
|
||||
object PhoneActions {
|
||||
/** Media keys, by the action's `command`. */
|
||||
private val MEDIA = mapOf(
|
||||
"toggle" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
"play" to KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||
"pause" to KeyEvent.KEYCODE_MEDIA_PAUSE,
|
||||
"next" to KeyEvent.KEYCODE_MEDIA_NEXT,
|
||||
"previous" to KeyEvent.KEYCODE_MEDIA_PREVIOUS,
|
||||
)
|
||||
|
||||
/** Settings panels, by the action's `panel`. Panels (Android 10+) float over the app; the rest are pages. */
|
||||
private val PANELS = mapOf(
|
||||
"wifi" to Settings.Panel.ACTION_WIFI,
|
||||
"internet" to Settings.Panel.ACTION_INTERNET_CONNECTIVITY,
|
||||
"nfc" to Settings.Panel.ACTION_NFC,
|
||||
"volume" to Settings.Panel.ACTION_VOLUME,
|
||||
"bluetooth" to Settings.ACTION_BLUETOOTH_SETTINGS,
|
||||
"location" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
|
||||
"do_not_disturb" to Settings.ACTION_ZEN_MODE_PRIORITY_SETTINGS,
|
||||
)
|
||||
|
||||
/** Tasker's public intent for running a task by its name (its TaskerIntent protocol). */
|
||||
const val TASKER_PACKAGE = "net.dinglisch.android.taskerm"
|
||||
private const val TASKER_ACTION = "net.dinglisch.android.tasker.ACTION_TASK"
|
||||
|
||||
/** The broadcast any other automation app (Automate, MacroDroid, …) can listen for. */
|
||||
const val AUTOMATION_ACTION = "eu.llembas.android.action.AUTOMATION"
|
||||
|
||||
/** A URL the phone may open for a model: web pages only. */
|
||||
fun urlAllowed(url: String): Boolean = url.trim().lowercase().let {
|
||||
(it.startsWith("http://") || it.startsWith("https://")) &&
|
||||
it.substringAfter("://").isNotBlank()
|
||||
}
|
||||
|
||||
/** `HH:MM` as hour and minute, or null. */
|
||||
fun clock(time: String): Pair<Int, Int>? {
|
||||
val m = Regex("^(\\d{1,2}):(\\d{2})$").matchEntire(time.trim()) ?: return null
|
||||
val (h, min) = m.destructured
|
||||
return (h.toInt() to min.toInt()).takeIf { it.first in 0..23 && it.second in 0..59 }
|
||||
}
|
||||
|
||||
/** SMS recipients: the numbers among [to]; a name the messaging app has to find is left to the person. */
|
||||
fun smsNumbers(to: List<String>): List<String> = to.map { it.trim() }.filter { Regex("^[+0-9 ()./#*-]{3,}$").matches(it) && it.count(Char::isDigit) >= 3 }
|
||||
|
||||
/**
|
||||
* The intent for an action that is one intent (everything but navigation, the torch and media
|
||||
* keys), or null when [action] is not one of these or its arguments do not make one.
|
||||
*/
|
||||
fun intentFor(context: Context, action: String, a: Args): Intent? = when (action) {
|
||||
"alarm" -> clock(a.str("time"))?.let { (hour, minute) ->
|
||||
Intent(AlarmClock.ACTION_SET_ALARM)
|
||||
.putExtra(AlarmClock.EXTRA_HOUR, hour)
|
||||
.putExtra(AlarmClock.EXTRA_MINUTES, minute)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
.apply {
|
||||
val days = a.strings("days").mapNotNull(::calendarDay)
|
||||
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
|
||||
}
|
||||
}
|
||||
|
||||
"timer" -> a.int("seconds")?.let { seconds ->
|
||||
Intent(AlarmClock.ACTION_SET_TIMER)
|
||||
.putExtra(AlarmClock.EXTRA_LENGTH, seconds.coerceIn(1, 86_400))
|
||||
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
}
|
||||
|
||||
// The calendar's new-event screen, filled in: the person saves it.
|
||||
"calendar_event" -> Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI)
|
||||
.putExtra(CalendarContract.Events.TITLE, a.str("title"))
|
||||
.apply {
|
||||
a.time("start")?.let { putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, it) }
|
||||
a.time("end")?.let { putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it) }
|
||||
if (a.bool("all_day") == true) putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
|
||||
a.str("location").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
a.str("notes").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
|
||||
}
|
||||
|
||||
// A draft: the messaging app opens with it, and the person sends.
|
||||
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + smsNumbers(a.strings("to")).joinToString(";") { Uri.encode(it) }))
|
||||
.putExtra("sms_body", a.str("body"))
|
||||
|
||||
"email_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
|
||||
.putExtra(Intent.EXTRA_EMAIL, a.strings("to").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_CC, a.strings("cc").toTypedArray())
|
||||
.putExtra(Intent.EXTRA_SUBJECT, a.str("subject"))
|
||||
.putExtra(Intent.EXTRA_TEXT, a.str("body"))
|
||||
|
||||
// The dialler with the number in it: the person places the call.
|
||||
"dial" -> Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(a.str("number"))))
|
||||
|
||||
"open_url" -> a.str("url").trim().takeIf(::urlAllowed)?.let { Intent(Intent.ACTION_VIEW, Uri.parse(it)) }
|
||||
|
||||
"open_app" -> appIntent(context, "", a.str("app"))
|
||||
|
||||
"settings_panel" -> PANELS[a.str("panel")]?.let { Intent(it) }
|
||||
|
||||
// Tasker (by default) runs the task by its name, the values as its local variables; any
|
||||
// other automation app gets LLeMbas's own broadcast, with the task's name and the values.
|
||||
"automation_intent" -> {
|
||||
val task = a.str("task")
|
||||
val app = a.str("app").trim()
|
||||
val values = a.obj("values")?.json.orEmpty().mapNotNull { (k, v) -> (v as? JsonPrimitive)?.let { k to it.content } }
|
||||
if (app.isBlank() || app.equals("tasker", ignoreCase = true)) {
|
||||
Intent(TASKER_ACTION)
|
||||
.setPackage(TASKER_PACKAGE)
|
||||
.putExtra("version_number", "1.1")
|
||||
.putExtra("task_name", task)
|
||||
.putExtra("task_priority", 5)
|
||||
.putStringArrayListExtra("varNames", ArrayList(values.map { "%" + it.first.lowercase() }))
|
||||
.putStringArrayListExtra("varValues", ArrayList(values.map { it.second }))
|
||||
} else {
|
||||
Intent(AUTOMATION_ACTION)
|
||||
.putExtra("task", task)
|
||||
.putExtra("app", app)
|
||||
.apply { values.forEach { (k, v) -> putExtra(k, v) } }
|
||||
}
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** An app by its package, else by the name the launcher shows (the first app whose label matches). */
|
||||
fun appIntent(context: Context, pkg: String, name: String): Intent? {
|
||||
val pm = context.packageManager
|
||||
pkg.takeIf { it.isNotBlank() }?.let { p -> pm.getLaunchIntentForPackage(p)?.let { return it } }
|
||||
if (name.isBlank()) return null
|
||||
val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = runCatching { pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL) }.getOrDefault(emptyList())
|
||||
val wanted = name.trim().lowercase()
|
||||
val found = apps.firstOrNull { it.loadLabel(pm).toString().lowercase() == wanted }
|
||||
?: apps.firstOrNull { it.loadLabel(pm).toString().lowercase().contains(wanted) }
|
||||
?: return null
|
||||
return pm.getLaunchIntentForPackage(found.activityInfo.packageName)
|
||||
}
|
||||
|
||||
/** The torch on or off (or the other way round), through the camera service; no permission needed. */
|
||||
fun torch(context: Context, on: Boolean?): ActionOutcome {
|
||||
val cameras = context.getSystemService(CameraManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no camera")
|
||||
val id = cameras.cameraIdList.firstOrNull { cameras.getCameraCharacteristics(it).get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true }
|
||||
?: return ActionOutcome(ActionStatus.Failed, "this phone has no torch")
|
||||
val target = on ?: !torchOn
|
||||
return runCatching {
|
||||
cameras.setTorchMode(id, target)
|
||||
torchOn = target
|
||||
ActionOutcome(ActionStatus.Done, if (target) "torch on" else "torch off")
|
||||
}.getOrElse { ActionOutcome(ActionStatus.Failed, it.message.orEmpty()) }
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var torchOn = false
|
||||
|
||||
/** A media key to whatever is playing. */
|
||||
fun media(context: Context, key: String): ActionOutcome {
|
||||
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media command: $key")
|
||||
val audio = context.getSystemService(AudioManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no audio")
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
|
||||
return ActionOutcome(ActionStatus.Done, key)
|
||||
}
|
||||
|
||||
/** Start [intent] as a new task; whether an app took it. */
|
||||
fun launch(context: Context, intent: Intent, broadcast: Boolean = false): ActionOutcome = try {
|
||||
if (broadcast) {
|
||||
context.sendBroadcast(intent)
|
||||
} else {
|
||||
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
ActionOutcome(ActionStatus.Done)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
ActionOutcome(ActionStatus.Failed, "no app on this phone does that")
|
||||
} catch (e: SecurityException) {
|
||||
ActionOutcome(ActionStatus.Failed, e.message.orEmpty())
|
||||
}
|
||||
|
||||
private fun calendarDay(day: String): Int? = when (day.lowercase().take(3)) {
|
||||
"sun" -> java.util.Calendar.SUNDAY
|
||||
"mon" -> java.util.Calendar.MONDAY
|
||||
"tue" -> java.util.Calendar.TUESDAY
|
||||
"wed" -> java.util.Calendar.WEDNESDAY
|
||||
"thu" -> java.util.Calendar.THURSDAY
|
||||
"fri" -> java.util.Calendar.FRIDAY
|
||||
"sat" -> java.util.Calendar.SATURDAY
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -44,16 +44,50 @@ object ActivityLogic {
|
||||
}
|
||||
|
||||
/**
|
||||
* What the strip above the composer says, as counts in order: agents working, queued,
|
||||
* waiting. Empty when nothing is going -- then there is no strip.
|
||||
* What the strip above the composer says, as counts in order: running, queued, waiting,
|
||||
* then finished. Empty when nothing is going -- then there is no strip, whatever finished.
|
||||
*/
|
||||
fun stripCounts(summary: ActivitySummary): List<Pair<String, Int>> =
|
||||
listOf("working" to summary.working, "queued" to summary.queued, "waiting" to summary.waiting).filter { it.second > 0 }
|
||||
fun stripCounts(summary: ActivitySummary): List<Pair<String, Int>> {
|
||||
if (summary.working + summary.queued + summary.waiting == 0) return emptyList()
|
||||
return listOf(
|
||||
"working" to summary.working,
|
||||
"queued" to summary.queued,
|
||||
"waiting" to summary.waiting,
|
||||
"finished" to summary.finished,
|
||||
).filter { it.second > 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* How many tokens are left before the chat compacts itself: the window's [ContextUse.threshold]
|
||||
* per cent, less what is used. Null when it never will -- the threshold is 0 (off) or 100,
|
||||
* or the window is unknown -- since a count against an unknown window is a guess. The
|
||||
* server's [ContextUse.untilCompact] and [ContextUse.autoCompact] win where it says them.
|
||||
*/
|
||||
fun untilAutoCompact(context: ContextUse): Int? {
|
||||
// The server's own count, where it gives one.
|
||||
if (context.autoCompact == false) return null
|
||||
context.untilCompact?.let { return it.coerceAtLeast(0) }
|
||||
if (context.limit <= 0 || context.threshold !in 1..99) return null
|
||||
return (context.limit.toLong() * context.threshold / 100 - context.used).toInt().coerceAtLeast(0)
|
||||
}
|
||||
|
||||
/**
|
||||
* What a task is called in its row: a team's member by its name, a subagent or a command
|
||||
* by what it was asked to do (its role, else its brief), its id only when it has neither.
|
||||
*/
|
||||
fun title(agent: ActivityAgent): String = if (agent.kind == "member") {
|
||||
agent.name
|
||||
} else {
|
||||
agent.role.ifBlank { agent.brief }.ifBlank { agent.name }
|
||||
}
|
||||
|
||||
/** Every task under [agent], however deep. */
|
||||
fun descendants(agent: ActivityAgent): Int = agent.children.sumOf { 1 + descendants(it) }
|
||||
|
||||
/** The top level split as the panel shows it: those still going, then the ended ones. */
|
||||
fun split(agents: List<ActivityAgent>): Pair<List<ActivityAgent>, List<ActivityAgent>> = agents.partition { it.isActive }
|
||||
|
||||
/** Every agent of a forest with its helpers under it, in tree order, for drawing as rows. */
|
||||
/** Every agent of a forest with its subagents under it, in tree order, for drawing as rows. */
|
||||
fun flatten(agents: List<ActivityAgent>): List<ActivityAgent> = agents.flatMap { listOf(it) + flatten(it.children) }
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
@@ -144,12 +145,102 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
// --- 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 models(chatId: String? = null): List<ModelInfo> = modelList(chatId).models
|
||||
|
||||
/** The models with the instance's subagent cap; with [chatId], whether each is offered subagents on that chat. */
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get(if (chatId != null) "/models?chat=$chatId" else "/models")
|
||||
|
||||
/** The models for a new agent chat on [deviceId], with whether it may have subagents (`agent_subagents`). */
|
||||
suspend fun agentModelList(deviceId: String?, directory: String? = null): ModelList = get(
|
||||
"/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() +
|
||||
// With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on.
|
||||
directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(),
|
||||
)
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
/** A new folder, at the top or inside [parentId] (`folder.manage`; nesting is capped). */
|
||||
suspend fun createFolder(name: String, parentId: String? = null): Folder = send<FolderEnvelope>(
|
||||
"POST",
|
||||
"/folders",
|
||||
buildJsonObject {
|
||||
put("name", name)
|
||||
if (parentId != null) put("parent_id", parentId)
|
||||
},
|
||||
).folder
|
||||
|
||||
/** Any of `name`, `parent_id`, `collapsed`. */
|
||||
suspend fun updateFolder(id: String, changes: JsonObject): Folder = send<FolderEnvelope>("PATCH", "/folders/${segment(id)}", changes).folder
|
||||
|
||||
/** The folder and the folders inside it; their chats fall back to no folder. */
|
||||
suspend fun deleteFolder(id: String) = empty(authed("$v2/folders/${segment(id)}").delete().build())
|
||||
|
||||
/** The app releases this server recommends; 404 from a server older than the route. */
|
||||
suspend fun apps(): AppsInfo = get("/apps")
|
||||
|
||||
/**
|
||||
* What `@` offers in an agent chat: the device's files matching [q], from the chat's
|
||||
* directory ([chatId]) or, before the chat exists, from the folder chosen for it ([cwd]).
|
||||
*/
|
||||
suspend fun deviceFiles(deviceId: String, q: String, chatId: String? = null, cwd: String? = null): DeviceFiles = get(
|
||||
"/devices/${segment(deviceId)}/files?q=${segment(q)}" +
|
||||
chatId?.let { "&chat=${segment(it)}" }.orEmpty() +
|
||||
cwd?.takeIf { chatId == null && it.isNotBlank() }?.let { "&cwd=${segment(it.trim())}" }.orEmpty(),
|
||||
)
|
||||
|
||||
/** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */
|
||||
suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: ""))
|
||||
|
||||
/**
|
||||
* Attach without uploading: a copy of an earlier attachment, a file of the tree as it is now,
|
||||
* or a web page's text -- whichever [mention] is. 404 for what cannot be reached, 400 for a
|
||||
* page that cannot be fetched.
|
||||
*/
|
||||
suspend fun attachFrom(mention: Mention, chatId: String? = null): Attachment = send<AttachmentEnvelope>(
|
||||
"POST",
|
||||
"/attachments/from",
|
||||
buildJsonObject {
|
||||
when (mention.kind) {
|
||||
"attachment" -> put("attachment", mention.id)
|
||||
"url" -> put("url", mention.url)
|
||||
else -> put("path", mention.path)
|
||||
}
|
||||
chatId?.let { put("chat", it) }
|
||||
},
|
||||
).attachment
|
||||
|
||||
/** The web's search in JSON: chats by their words (and meaning, where indexed), files, memories. */
|
||||
suspend fun search(q: String, within: String = "all", limit: Int = 20): SearchResults = get("/search?q=${segment(q)}&in=${segment(within)}&limit=$limit")
|
||||
|
||||
// --- Memory (`library.use`) -----------------------------------------------------------------
|
||||
|
||||
/** The person's memories, every data group, and the groups they may file one in. */
|
||||
suspend fun memories(): MemoryList = get("/memories")
|
||||
|
||||
suspend fun addMemory(content: String, groupId: String? = null): Memory = send<MemoryEnvelope>(
|
||||
"POST",
|
||||
"/memories",
|
||||
buildJsonObject {
|
||||
put("content", content)
|
||||
if (groupId != null) put("data_group_id", groupId)
|
||||
},
|
||||
).memory
|
||||
|
||||
suspend fun editMemory(id: String, content: String): Memory =
|
||||
send<MemoryEnvelope>("PATCH", "/memories/${segment(id)}", buildJsonObject { put("content", content) }).memory
|
||||
|
||||
suspend fun forgetMemory(id: String) = empty(authed("$v2/memories/${segment(id)}").delete().build())
|
||||
|
||||
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/devices").devices
|
||||
|
||||
/**
|
||||
* A directory on a linked device, for choosing where an agent chat or an Agentic schedule
|
||||
* works; without a [path], the device's places. No listing is still an answer: its `code`
|
||||
* and `error` say why.
|
||||
*/
|
||||
suspend fun deviceDirectories(deviceId: String, path: String? = null): DeviceDirectory =
|
||||
get("/devices/${segment(deviceId)}/directories" + path?.takeIf { it.isNotEmpty() }?.let { "?path=" + segment(it) }.orEmpty())
|
||||
|
||||
/** The token revokes itself (`lembas logout`'s route). */
|
||||
suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build())
|
||||
|
||||
@@ -178,6 +269,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
mode: String? = null,
|
||||
agent: AgentTarget? = null,
|
||||
agents: AgentsSetting? = null,
|
||||
forceTool: String? = null,
|
||||
): NewChat = send(
|
||||
"POST",
|
||||
"/chats",
|
||||
@@ -189,6 +281,8 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
mode?.let { put("mode", it) }
|
||||
agents?.let { put("agents", agentsJson(it)) }
|
||||
put("temporary", temporary)
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
// An agent chat runs on a linked device; an empty directory is the device's first
|
||||
// allowed one. A device that is no longer linked makes it an ordinary chat on the
|
||||
// server, rather than losing the message.
|
||||
@@ -200,12 +294,15 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun sendMessage(chatId: String, text: String, attachments: List<String> = emptyList()): Turn = send(
|
||||
/** A turn. [forceTool] makes the model call that tool (the server allows `image_generate` only). */
|
||||
suspend fun sendMessage(chatId: String, text: String, attachments: List<String> = emptyList(), forceTool: String? = null): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -219,14 +316,22 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
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) })
|
||||
// Every request that can start a reply says what this app can do, as a message does: the
|
||||
// server then knows who the reply is written for however it was asked for.
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages/$messageId/edit",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null)
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null)
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null)
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", DECLARED)
|
||||
|
||||
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
||||
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
||||
@@ -244,14 +349,168 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
/** One background agent and its whole conversation, read-only. `kind` is `member` or `job`. */
|
||||
suspend fun agent(chatId: String, kind: String, id: String): AgentDetail = get("/chats/$chatId/agents/${segment(kind)}/${segment(id)}")
|
||||
|
||||
/** The chat's subagent tree and room (spec 3.4.0); a 404 from a server without it. */
|
||||
suspend fun tree(chatId: String): TreeView = get("/chats/$chatId/tree")
|
||||
|
||||
/** A subagent's conversation by its id (`s1`), read-only; 409 while an agent chat's device is away. */
|
||||
suspend fun subagentTranscript(chatId: String, id: String): SubagentTranscript = get("/chats/$chatId/subagents/${segment(id)}/transcript")
|
||||
|
||||
/** Stop a background agent (a member leaves the team with those under it). */
|
||||
suspend fun stopAgent(chatId: String, kind: String, id: String): List<String> =
|
||||
send<Stopped>("POST", "/chats/$chatId/agents/${segment(kind)}/${segment(id)}/stop", null).stopped
|
||||
|
||||
/**
|
||||
* Summarise the earlier turns now and stop sending them (the activity sheet's Compact). The
|
||||
* server refuses in its own words (409) while a reply is being written or with nothing to
|
||||
* summarise; the transcript is read again after, for the divider it leaves.
|
||||
*/
|
||||
suspend fun compact(chatId: String) = empty(authed("$v2/chats/$chatId/compact").post(ByteArray(0).toRequestBody(null)).build())
|
||||
|
||||
suspend fun team(chatId: String, since: Int = 0): TeamView = get<TeamEnvelope>("/chats/$chatId/team?since=$since").team
|
||||
|
||||
suspend fun stopMember(chatId: String, name: String): List<String> = send<Stopped>("POST", "/chats/$chatId/team/${segment(name)}/stop", null).stopped
|
||||
|
||||
// --- Scheduled tasks (`/api/v2/schedules`; shapes in api/Schedules.kt) ----------------------
|
||||
|
||||
/** Every schedule of this person, newest first, each with its last run. */
|
||||
suspend fun schedules(): List<Schedule> = get<ScheduleList>("/schedules").schedules
|
||||
|
||||
suspend fun schedule(id: String): Schedule = get<ScheduleEnvelope>("/schedules/${segment(id)}").schedule
|
||||
|
||||
/** A page of a schedule's runs, newest first; [before] is the last run's id of the page before. */
|
||||
suspend fun scheduleRuns(id: String, before: String? = null, limit: Int = 20): ScheduleRuns =
|
||||
get("/schedules/${segment(id)}/runs?limit=$limit" + (before?.let { "&before=${segment(it)}" } ?: ""))
|
||||
|
||||
/** One run and its result in full (Markdown a model wrote: untrusted). */
|
||||
suspend fun scheduleRun(id: String, runId: String): RunResult = get("/schedules/${segment(id)}/runs/${segment(runId)}")
|
||||
|
||||
/** Words to a schedule: title, instruction, rule, the rule in words, the next runs. Saves nothing. */
|
||||
suspend fun compileSchedule(words: String, model: String? = null): ScheduleCompiled = send(
|
||||
"POST",
|
||||
"/schedules/compile",
|
||||
buildJsonObject {
|
||||
put("text", words)
|
||||
model?.let { put("model", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/** A rule read back: cleaned, in words, and its next runs. An empty rule cannot run. */
|
||||
suspend fun previewRule(rule: JsonObject): RulePreview = send("POST", "/schedules/preview", buildJsonObject { put("rule", rule) })
|
||||
|
||||
/**
|
||||
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
|
||||
* edited. The words go along as the schedule's `request`, so editing starts from them.
|
||||
*/
|
||||
suspend fun saveSchedule(
|
||||
compiled: ScheduleCompiled,
|
||||
words: String,
|
||||
id: String? = null,
|
||||
notify: String? = null,
|
||||
notifyWhen: String = "",
|
||||
where: WhereToRun = WhereToRun.Leave,
|
||||
model: String? = null,
|
||||
watch: WatchCommand? = null,
|
||||
): Schedule {
|
||||
val body = buildJsonObject {
|
||||
// The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left
|
||||
// out where the form did not say, so a schedule is never moved by a form that did not read it.
|
||||
when (where) {
|
||||
WhereToRun.Leave -> Unit
|
||||
|
||||
WhereToRun.Server -> put("runs_on", JsonNull)
|
||||
|
||||
is WhereToRun.Computer -> {
|
||||
put(
|
||||
"runs_on",
|
||||
buildJsonObject {
|
||||
put("device", where.device)
|
||||
put("cwd", where.cwd)
|
||||
put("mode", where.mode)
|
||||
where.approvalWaitMinutes?.let { put("approval_wait_minutes", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
// The model, where the form says one: empty is the folder's usual model for an
|
||||
// Agentic schedule, asked of the computer as each run starts.
|
||||
model?.let { put("model", it) }
|
||||
// The watched command, where the form says one: none at all is "watch nothing".
|
||||
watch?.let { said ->
|
||||
if (said.command.isBlank()) {
|
||||
put("watch", JsonNull)
|
||||
} else {
|
||||
put(
|
||||
"watch",
|
||||
buildJsonObject {
|
||||
put("kind", "command")
|
||||
put("command", said.command)
|
||||
said.timeoutS?.let { put("timeout_s", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
put("title", compiled.title)
|
||||
put("instruction", compiled.instruction)
|
||||
put("rule", compiled.rule)
|
||||
put("target", compiled.target)
|
||||
if (id == null) put("request", words)
|
||||
// Notify when (spec 3.8.0): left out where the form did not say, so an older server is sent nothing new.
|
||||
if (notify != null) {
|
||||
put("notify", notify)
|
||||
// The person's own words, or none: an empty condition is the server's default, in its own words.
|
||||
if (notify == "when") put("notify_when", notifyWhen.trim())
|
||||
}
|
||||
}
|
||||
return if (id == null) {
|
||||
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
|
||||
} else {
|
||||
send<ScheduleEnvelope>("PATCH", "/schedules/${segment(id)}", body).schedule
|
||||
}
|
||||
}
|
||||
|
||||
// --- Reports (`schedule.use`) ---------------------------------------------------------------
|
||||
|
||||
/** The reports, newest first; [unread] only those not read yet, [schedule] only one schedule's. */
|
||||
suspend fun reports(unread: Boolean = false, schedule: String? = null): List<Report> {
|
||||
val asked = listOfNotNull(if (unread) "unread=1" else null, schedule?.let { "schedule=" + segment(it) }).joinToString("&")
|
||||
return get<ReportList>(if (asked.isEmpty()) "/reports" else "/reports?" + asked).reports
|
||||
}
|
||||
|
||||
/** How many reports are unread: the drawer's badge. */
|
||||
suspend fun unreadReports(): Int = get<ReportList>("/reports?unread=1").unreadCount
|
||||
|
||||
/** One report with its body. Read as the report itself, or as `{report: …}` around it. */
|
||||
suspend fun report(id: String): Report {
|
||||
val answer = get<JsonObject>("/reports/${segment(id)}")
|
||||
return LembasJson.decodeFromJsonElement(Report.serializer(), answer["report"] as? JsonObject ?: answer)
|
||||
}
|
||||
|
||||
suspend fun readReport(id: String) = empty(authed("$v2/reports/${segment(id)}/read").post("{}".toRequestBody(JSON)).build())
|
||||
|
||||
suspend fun deleteReport(id: String) = empty(authed("$v2/reports/${segment(id)}").delete().build())
|
||||
|
||||
/** Continue the report as a conversation: the chat it is in, which stays under Reports. */
|
||||
suspend fun replyToReport(id: String): String? = send<ReportReply>("POST", "/reports/${segment(id)}/reply", null).chatId
|
||||
|
||||
suspend fun pauseSchedule(id: String, paused: Boolean): Schedule =
|
||||
send<ScheduleEnvelope>("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule
|
||||
|
||||
/** Run it now (202); the next scheduled run is not used up by this one. */
|
||||
suspend fun runScheduleNow(id: String): ScheduleRun = send<RunEnvelope>("POST", "/schedules/${segment(id)}/run", null).run
|
||||
|
||||
/** Delete it; [keepChat] keeps the chat its results went to. */
|
||||
suspend fun deleteSchedule(id: String, keepChat: Boolean = true) = empty(authed("$v2/schedules/${segment(id)}?keep_chat=$keepChat").delete().build())
|
||||
|
||||
/** The models scheduled work may run on, in the order they are tried, and which are free. */
|
||||
suspend fun schedulingModels(): SchedulingModels = get("/schedules/models")
|
||||
|
||||
/** The person's narrowing of that list ([ids] empty: all of them). */
|
||||
suspend fun chooseSchedulingModels(ids: List<String>): SchedulingModels =
|
||||
send("PUT", "/schedules/models", buildJsonObject { put("models", JsonArray(ids.map { JsonPrimitive(it) })) })
|
||||
|
||||
/** The person's events route: a `schedules` frame with the whole list whenever it changes. */
|
||||
fun events(): Request = authed("$v2/events").header("Accept", "text/event-stream").build()
|
||||
|
||||
// --- Model pictures --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -383,6 +642,16 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* What this app can do, sent with every request that can start a reply (spec 3.6.0):
|
||||
* the phone carries out `phone_action` calls the person confirms here, so the chat is
|
||||
* offered the tool -- and a reply for the phone is one without pages to draw.
|
||||
*/
|
||||
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
||||
|
||||
/** The body of a request that says nothing else: the declaration alone. */
|
||||
private val DECLARED = JsonObject(mapOf("client" to CAPABILITIES))
|
||||
|
||||
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
|
||||
const val SHOWN_MAX_BYTES = 1_100_000L
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// --- A linked device's directories (`GET /api/v2/devices/{id}/directories`) -------------------
|
||||
//
|
||||
// The JSON twin of the page's directory dialog (harness spec 3.9.0), as the contract pins it
|
||||
// (`contract/device_directories*.json`). Every field has a default, so a server that says less
|
||||
// still parses.
|
||||
|
||||
/** The model last used in a directory on the device, as one the person still has. */
|
||||
@Serializable
|
||||
data class DirectoryModel(val id: String = "", val name: String = "", val ref: String = "") {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String get() = name.ifBlank { id }
|
||||
}
|
||||
|
||||
/** A subdirectory: whether a session may be opened in it ([reason]: the device's words when not), and its [model]. */
|
||||
@Serializable
|
||||
data class DirectoryEntry(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One directory on a device, or -- with an empty [path] -- the device's places. Where there is
|
||||
* no listing, [code] says why (`device_not_linked`, `cli_too_old`, `no_answer`, `refused`) and
|
||||
* [error] is the sentence for the person; a typed path still works then.
|
||||
*/
|
||||
@Serializable
|
||||
data class DeviceDirectory(
|
||||
val device: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
val parent: String = "",
|
||||
val roots: List<String> = emptyList(),
|
||||
val entries: List<DirectoryEntry> = emptyList(),
|
||||
/** Whether the device says a directory's model at all. */
|
||||
val remembers: Boolean = false,
|
||||
val code: String = "",
|
||||
val error: String = "",
|
||||
) {
|
||||
/** The device's places, not a directory. */
|
||||
val places: Boolean get() = path.isEmpty()
|
||||
|
||||
/** Whether this answer is a listing; one with a [code] is the reason there is none. */
|
||||
val listed: Boolean get() = code.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a new agent chat on a device and directory starts on when the app names none
|
||||
* (`GET /models?kind=agent&device=&directory=`): [from] `directory` (the model last used
|
||||
* there) or `default`. The device remembers it; nothing here is kept by the app.
|
||||
*/
|
||||
@Serializable
|
||||
data class StartModel(val model: String = "", val from: String = "", val ref: String = "") {
|
||||
/** The model's unambiguous name where the server says one, else its id. */
|
||||
val key: String get() = ref.ifBlank { model }
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import java.text.NumberFormat
|
||||
import java.util.Locale
|
||||
|
||||
/*
|
||||
* One display in every client (harness spec 3.7.0, `display.md`): what this app says about a tool
|
||||
* call, the end of a reply and a number -- the same things, from the same data, as the web UI,
|
||||
* Desktop and the CLI.
|
||||
*/
|
||||
|
||||
/** The states that end a turn without finishing it; their line stays on the reply (`display.end`). */
|
||||
val END_PHASES = setOf("stopped", "failed")
|
||||
|
||||
/**
|
||||
* A call's short title as a line may show it (`display.md` §1, step 4): trimmed, its first line
|
||||
* only, and cut to [max] code points -- one fewer and `…` -- so a cut title says it was cut.
|
||||
* Null when nothing is left.
|
||||
*/
|
||||
fun shortTitle(text: String?, max: Int = TITLE_MAX): String? {
|
||||
val line = text?.trim()?.lineSequence()?.firstOrNull()?.trim().orEmpty()
|
||||
if (line.isEmpty()) return null
|
||||
if (line.codePointCount(0, line.length) <= max) return line
|
||||
return line.substring(0, line.offsetByCodePoints(0, max - 1)) + "…"
|
||||
}
|
||||
|
||||
/** `loop.json` `progress.what_max`. */
|
||||
const val TITLE_MAX = 80
|
||||
|
||||
/**
|
||||
* The state a drawn call is in (`display.md` §2): `running`, `done`, `failed` or `denied`, from
|
||||
* what `/api/v2` says of it.
|
||||
*/
|
||||
fun ToolCall.state(): String = when {
|
||||
// The server's own word, from spec 3.7.0; an older one leaves it to what the call carries.
|
||||
block.state in CALL_STATES -> block.state
|
||||
|
||||
status == "denied" -> "denied"
|
||||
|
||||
status == "error" || !error.isNullOrEmpty() -> "failed"
|
||||
|
||||
status == "running" || status == "pending" -> "running"
|
||||
|
||||
else -> "done"
|
||||
}
|
||||
|
||||
private val CALL_STATES = setOf("running", "done", "failed", "denied")
|
||||
|
||||
/**
|
||||
* What is written after a call's title for its time: the server's own [ToolBlock.duration] where
|
||||
* it sends one (it measured the call), else made from the call's `ms`; nothing for a call that is
|
||||
* running or was denied.
|
||||
*/
|
||||
fun ToolCall.took(): String? {
|
||||
val state = state()
|
||||
if (state == "running" || state == "denied") return null
|
||||
return block.duration.ifBlank { null } ?: callDuration(state, ms)
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a finished call took (`display.md` §2): tenths under a minute (`0.4s`), then
|
||||
* `1m 05s`, then `2h 03m`. None for a call that is running or was denied, or whose time was not
|
||||
* kept. Not a locale number: written with `.` everywhere.
|
||||
*/
|
||||
fun callDuration(state: String, ms: Long?): String? {
|
||||
if (ms == null || state == "running" || state == "denied") return null
|
||||
// Tenths, rounded half up, decide the form: 59.96 s is not "60.0s" but a minute.
|
||||
val tenths = (ms.coerceAtLeast(0) + 50) / 100
|
||||
if (tenths < 600) return "${tenths / 10}.${tenths % 10}s"
|
||||
val seconds = (ms / 1000).coerceAtLeast(60)
|
||||
val minutes = seconds / 60
|
||||
return if (minutes < 60) {
|
||||
String.format(Locale.ROOT, "%dm %02ds", minutes, seconds % 60)
|
||||
} else {
|
||||
String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a reply ended, when it did not finish (`display.md` §4): the `stopped` or `failed` progress
|
||||
* whose line stays on it. From the row's own `end` (spec 3.7.0: the phase and the reason, stored
|
||||
* with the reply); from an older server, the end the stream said (kept on the message as its
|
||||
* `progress`), else what the row knows -- that it was stopped, or its error, of which the first
|
||||
* line is the reason. Null for a reply that
|
||||
* finished, a user's message, or one still queued.
|
||||
*/
|
||||
fun Message.ending(): Progress? = when {
|
||||
role != "assistant" -> null
|
||||
|
||||
// What the server stored with the reply (spec 3.7.0): it stays true after a reload.
|
||||
end?.phase in END_PHASES -> Progress(phase = end?.phase.orEmpty(), reason = end?.reason?.ifBlank { null })
|
||||
|
||||
progress?.phase in END_PHASES -> progress
|
||||
|
||||
!error.isNullOrBlank() -> Progress(phase = "failed", reason = error.lineSequence().firstOrNull { it.isNotBlank() }?.trim())
|
||||
|
||||
stopped -> Progress(phase = "stopped")
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* A count a person reads, in [locale]'s own format -- its grouping and its decimal mark
|
||||
* (`display.md` §6): `12,480`, `12 480`, `12.480`. [Locale.ROOT] is the spec's plain format, no
|
||||
* grouping and `.`, which is what its conformance texts are written in.
|
||||
*/
|
||||
fun localeNumber(n: Long, locale: Locale): String = if (locale == Locale.ROOT) n.toString() else NumberFormat.getIntegerInstance(locale).format(n)
|
||||
|
||||
/** A measure with [decimals] places, in [locale]'s format; plain for [Locale.ROOT]. */
|
||||
fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
|
||||
if (locale == Locale.ROOT) return String.format(Locale.ROOT, "%.${decimals}f", n)
|
||||
val format = NumberFormat.getNumberInstance(locale)
|
||||
format.minimumFractionDigits = decimals
|
||||
format.maximumFractionDigits = decimals
|
||||
format.roundingMode = java.math.RoundingMode.HALF_UP
|
||||
return format.format(n)
|
||||
}
|
||||
|
||||
/** How a message is drawn in the transcript. */
|
||||
enum class Drawn {
|
||||
/** The person's own words: their bubble. */
|
||||
Person,
|
||||
|
||||
/** The model's reply. */
|
||||
Reply,
|
||||
|
||||
/** A line the server wrote in the person's place (`machine`): a quiet note, never their bubble. */
|
||||
Note,
|
||||
|
||||
/** Not drawn at all. */
|
||||
Hidden,
|
||||
}
|
||||
|
||||
/**
|
||||
* How [message] is drawn. A `user` row the server wrote itself (`machine`: a schedule's
|
||||
* instruction, the line that opens a report's conversation) is not something the person said,
|
||||
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
|
||||
* [first] such line, which only tells the model what the conversation continues, is left out,
|
||||
* since the report itself is one tap back.
|
||||
*/
|
||||
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
|
||||
!message.isUser -> Drawn.Reply
|
||||
!message.machine -> Drawn.Person
|
||||
reportChat && first -> Drawn.Hidden
|
||||
else -> Drawn.Note
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.onSubscription
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* One connection to a person's events route (`GET /events`) for everything that watches it --
|
||||
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
|
||||
* somebody watches and closed when nobody does.
|
||||
*
|
||||
* Every frame of the route is a whole state (`schedules`, `reports`), which the server sends at
|
||||
* once to a new connection. A watcher that joins a connection already open missed that, so it
|
||||
* is first told the last frame of each kind this connection carried.
|
||||
*
|
||||
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
|
||||
* when each asked for itself.
|
||||
*/
|
||||
class EventsHub(private val scope: CoroutineScope) {
|
||||
private class Line(val key: String, val frames: SharedFlow<Frame>, val latest: MutableMap<String, Frame>)
|
||||
|
||||
private var line: Line? = null
|
||||
|
||||
/** The frames of the route [key] names (an instance's id), opened by [open] when nobody watches it yet. */
|
||||
@Synchronized
|
||||
fun frames(key: String, open: () -> Flow<Frame>): Flow<Frame> {
|
||||
val now = line?.takeIf { it.key == key } ?: run {
|
||||
val latest = ConcurrentHashMap<String, Frame>()
|
||||
val shared = open()
|
||||
// A connection opened anew is told everything again: what the last one said is stale.
|
||||
.onStart { latest.clear() }
|
||||
.onEach { latest[it.event] = it }
|
||||
.catch { }
|
||||
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
|
||||
Line(key, shared, latest).also { line = it }
|
||||
}
|
||||
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,25 @@ data class LiveReply(
|
||||
val tail: Tail = Tail(),
|
||||
val plan: Plan? = null,
|
||||
val status: String = "",
|
||||
/** The structured progress beside [status] (spec 3.4.0); null from an older server, or idle. */
|
||||
val progress: Progress? = null,
|
||||
/** How the turn ended when it did not finish: the last `stopped` or `failed` progress, with its reason. */
|
||||
val end: Progress? = null,
|
||||
val cards: List<Card> = emptyList(),
|
||||
val jobs: List<Job> = emptyList(),
|
||||
/** The subagent tree (spec 3.4.0), from the `tree` frame; null until there is one. */
|
||||
val tree: SubagentTree? = null,
|
||||
val metrics: Metrics? = null,
|
||||
val steered: Set<String> = emptySet(),
|
||||
/** Set by `done`: the finished row, which replaces this in the transcript. */
|
||||
/**
|
||||
* Set by `done`: the finished row, which replaces this in the transcript. `done` is the end
|
||||
* of the reply -- the stream may stay open after it for one `title` frame, which nobody
|
||||
* waits for.
|
||||
*/
|
||||
val finished: Message? = null,
|
||||
val title: String? = null,
|
||||
/** From `done`: a model is still naming the chat, so [title] is the one made from the prompt. */
|
||||
val titlePending: Boolean = false,
|
||||
/** A queued prompt the server started when this reply ended: the next stream to follow. */
|
||||
val next: String? = null,
|
||||
val closed: Boolean = false,
|
||||
@@ -45,18 +57,38 @@ data class LiveReply(
|
||||
|
||||
"plan" -> copy(plan = decodePlan(data))
|
||||
|
||||
"status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text) } ?: this
|
||||
"status" -> decode(StatusFrame.serializer(), data)?.let { frame ->
|
||||
copy(status = frame.text, progress = frame.progress, end = frame.progress?.takeIf { it.phase in END_PHASES })
|
||||
} ?: this
|
||||
|
||||
"ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this
|
||||
|
||||
"jobs" -> decode(JobsFrame.serializer(), data)?.let { copy(jobs = it.jobs) } ?: this
|
||||
|
||||
"tree" -> decode(TreeFrame.serializer(), data)?.let { copy(tree = it.tree) } ?: 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 = "")
|
||||
"done" -> decode(DoneFrame.serializer(), data)?.let { done ->
|
||||
// The finished row says that it was stopped or failed; the stream said why (by you,
|
||||
// the step limit, the budget). The reason goes with the row, where its line stays
|
||||
// (display.md §4).
|
||||
val row = done.message
|
||||
val ended = row.stopped || !row.error.isNullOrBlank()
|
||||
copy(
|
||||
finished = if (ended && row.progress == null && end != null) row.copy(progress = end) else row,
|
||||
title = done.chat.title.ifEmpty { null },
|
||||
titlePending = done.chat.titlePending,
|
||||
next = done.next,
|
||||
cards = emptyList(),
|
||||
status = "",
|
||||
progress = null,
|
||||
)
|
||||
} ?: this
|
||||
|
||||
// After `done`, when a model has named the chat: the name, and nothing else changes.
|
||||
"title" -> decode(TitleFrame.serializer(), data)?.let { named -> copy(title = named.chat.title.ifEmpty { title }, titlePending = false) } ?: this
|
||||
|
||||
"close" -> copy(closed = true)
|
||||
|
||||
else -> this
|
||||
|
||||
@@ -72,7 +72,27 @@ data class Me(
|
||||
@SerialName("default_model") val defaultModel: String? = null,
|
||||
val permissions: Map<String, Boolean> = emptyMap(),
|
||||
val services: Map<String, Boolean> = emptyMap(),
|
||||
)
|
||||
) {
|
||||
/**
|
||||
* The language the app follows by default (`i18n.for_user`: the account's choice, else the
|
||||
* instance's); null when the server said none, so a kept earlier answer stands.
|
||||
*/
|
||||
val accountLanguage: String? get() = language.ifBlank { null }
|
||||
|
||||
/**
|
||||
* The instance's speech-to-text, through the server (the assistant's LLeMbas voice input):
|
||||
* true or false as the server said it, null when it did not say.
|
||||
*/
|
||||
val speechToText: Boolean? get() = services["stt"]
|
||||
|
||||
val hasSpeechToText: Boolean get() = speechToText == true
|
||||
|
||||
/** The instance's text-to-speech (the assistant's voice reply, Read aloud). */
|
||||
val hasTextToSpeech: Boolean get() = services["tts"] == true
|
||||
|
||||
/** The instance makes pictures for this person (`image_generate`, in a chat). */
|
||||
val hasImages: Boolean get() = services["images"] == true
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ModelInfo(
|
||||
@@ -95,7 +115,22 @@ data class ModelInfo(
|
||||
/** The picture's path on the instance (`/api/v2/models/images/…`), read with the token. */
|
||||
val image: String? = null,
|
||||
val default: Boolean = false,
|
||||
/** Whether a new chat on this model is offered subagents (server 2.0.0-beta.7); null from an older one. */
|
||||
val subagents: SubagentsOffer? = null,
|
||||
/** On a connection whose terms allow interactive use only: never a schedule's model. */
|
||||
@SerialName("interactive_only") val interactiveOnly: Boolean = false,
|
||||
/**
|
||||
* The model's one unambiguous name, `provider/id` (server 2.0.0-beta.14): two connections may
|
||||
* serve one [id], which alone names only the first of them. Empty from an older server.
|
||||
*/
|
||||
val ref: String = "",
|
||||
val provider: String = "",
|
||||
/** The connection's name, for telling two models with one [id] apart. */
|
||||
val connection: String = "",
|
||||
) {
|
||||
/** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
|
||||
/**
|
||||
* The levels, for a server that says them; an older one said only `efforts`, offered after
|
||||
* an `off` that meant "the model's default" -- as the app showed it before.
|
||||
@@ -118,23 +153,172 @@ data class ModelInfo(
|
||||
val onLevel: String get() = offered.firstOrNull { it != "off" } ?: effort
|
||||
|
||||
/**
|
||||
* Whether a new chat on this model may have a team, as far as the app can tell: the model
|
||||
* serves two requests at once (`parallel` ≥ 2, or no stated limit) and takes tools. The
|
||||
* server also needs subagents on, which only an existing chat's activity says
|
||||
* (`team_offered`); a setting it does not use is kept and does nothing.
|
||||
* Whether a new chat on this model is offered subagents: the server's word
|
||||
* (`subagents.offered`) when it says it. An older server did not, and then the app guesses
|
||||
* from the model alone: it serves two requests at once (`parallel` ≥ 2, or no stated
|
||||
* limit) and takes tools.
|
||||
*/
|
||||
val mayHaveTeam: Boolean get() = tools && (parallel == null || parallel >= 2)
|
||||
val mayHaveTeam: Boolean get() = subagents?.offered ?: (tools && (parallel == null || parallel >= 2))
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ModelList(val models: List<ModelInfo> = emptyList())
|
||||
/**
|
||||
* The model a name means, in a list: by its `ref`, else the first with that `id` -- which is
|
||||
* what a bare id names on the server too. So a name kept from before refs (a setting, a chat's
|
||||
* `model`, a schedule's) still finds its model.
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?): ModelInfo? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/** A model's name in a list of [all]: with its connection where another model there shares its id. */
|
||||
fun ModelInfo.titleAmong(all: List<ModelInfo>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** "Name · Connection" for a model one of two that share an id ([twin]), where the connection has a name; else the name. */
|
||||
fun twinTitle(name: String, connection: String, twin: Boolean): String = if (twin && connection.isNotBlank()) "$name · $connection" else name
|
||||
|
||||
@Serializable
|
||||
data class Folder(val id: String, val name: String = "", @SerialName("parent_id") val parentId: String? = null, val kind: String = "", val position: Int = 0)
|
||||
data class ModelList(
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
/** The instance's cap on a chat's subagents (server 2.0.0-beta.7); null from an older one. */
|
||||
@SerialName("subagents_cap") val subagentsCap: Int? = null,
|
||||
/** With `kind=agent` (spec 3.4.0 §14): whether a new agent chat may have subagents. */
|
||||
@SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null,
|
||||
/** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */
|
||||
val start: StartModel? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance
|
||||
* and the person allow them; [deviceRuns] whether the chosen device runs them (it lists `agents`
|
||||
* and `tree`), null while it is not linked or none was named.
|
||||
*/
|
||||
@Serializable
|
||||
data class AgentSubagents(val offered: Boolean = false, @SerialName("device_runs") val deviceRuns: Boolean? = null)
|
||||
|
||||
/**
|
||||
* Whether subagents are offered (harness spec 3.3.0, `subagents.md` §4): [offered] when
|
||||
* subagents are on and at least one model could serve; [namedOnly] when only a model the person
|
||||
* names in the chat could -- the chat's own serves one request at a time -- and the setting then
|
||||
* says so. [cap] is the instance's most, on a chat (not on a model).
|
||||
*/
|
||||
@Serializable
|
||||
data class SubagentsOffer(val offered: Boolean = false, @SerialName("named_only") val namedOnly: Boolean = false, val cap: Int? = null)
|
||||
|
||||
@Serializable
|
||||
data class Folder(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
@SerialName("parent_id") val parentId: String? = null,
|
||||
val kind: String = "",
|
||||
val position: Int = 0,
|
||||
val collapsed: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FolderEnvelope(val folder: Folder)
|
||||
|
||||
/**
|
||||
* One hit of `GET /api/v2/search`: a chat (by [id]), a file (by [path]) or a memory. [snippet] is
|
||||
* plain text -- a chat's may be model output -- and [marks] the `[start, end)` ranges matched in it.
|
||||
*/
|
||||
@Serializable
|
||||
data class SearchHit(
|
||||
val kind: String = "",
|
||||
val id: String? = null,
|
||||
val title: String = "",
|
||||
val snippet: String = "",
|
||||
val marks: List<List<Int>> = emptyList(),
|
||||
val archived: Boolean = false,
|
||||
val agent: Boolean = false,
|
||||
val path: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SearchGroup(val kind: String = "", val more: Boolean = false, val hits: List<SearchHit> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class SearchResults(
|
||||
val q: String = "",
|
||||
@SerialName("in") val within: String = "",
|
||||
val offered: List<String> = emptyList(),
|
||||
val results: List<SearchGroup> = emptyList(),
|
||||
) {
|
||||
fun hits(kind: String): List<SearchHit> = results.firstOrNull { it.kind == kind }?.hits.orEmpty()
|
||||
}
|
||||
|
||||
/** One app release the server recommends (`GET /api/v2/apps`), with the page its files are on. */
|
||||
@Serializable
|
||||
data class AppRelease(
|
||||
val version: String = "",
|
||||
val tag: String = "",
|
||||
val channel: String = "",
|
||||
val page: String = "",
|
||||
/** The release's other builds, for an updater that installs its own kind: `{url, sha256}` each, where the server knows them. */
|
||||
val notifications: AppBuild? = null,
|
||||
val fdroid: AppBuild? = null,
|
||||
)
|
||||
|
||||
/** One APK of a release: where it is and its SHA-256. */
|
||||
@Serializable
|
||||
data class AppBuild(val url: String = "", val sha256: String = "")
|
||||
|
||||
/** What `@` offers from the server (`GET /api/v2/mentions`): an earlier `attachment` by [id], a `file` of the tree by [path], or a `url`. */
|
||||
@Serializable
|
||||
data class Mention(val kind: String = "", val id: String = "", val path: String = "", val url: String = "", val name: String = "", val detail: String = "")
|
||||
|
||||
@Serializable
|
||||
data class Mentions(val items: List<Mention> = emptyList())
|
||||
|
||||
/** A file or directory on a linked device, by its [path] from the chat's directory ([kind] `file` or `dir`). */
|
||||
@Serializable
|
||||
data class DeviceFile(val path: String = "", val kind: String = "", val name: String = "")
|
||||
|
||||
/** What `@` offers in an agent chat (`GET /devices/{id}/files`): the device's files; one that cannot answer offers none and may say why. */
|
||||
@Serializable
|
||||
data class DeviceFiles(val files: List<DeviceFile> = emptyList(), val error: String = "", val device: String = "")
|
||||
|
||||
@Serializable
|
||||
data class ServerChannel(val version: String = "", val channel: String = "")
|
||||
|
||||
/**
|
||||
* Which release of each app goes with this server: a stable server names only a stable app, a
|
||||
* beta server the newer of the app's stable and beta. Null for an app it recommends none of.
|
||||
*/
|
||||
@Serializable
|
||||
data class AppsInfo(val server: ServerChannel = ServerChannel(), val apps: Map<String, AppRelease?> = emptyMap()) {
|
||||
val android: AppRelease? get() = apps["android"]
|
||||
}
|
||||
|
||||
/** A data group: whose records a memory is kept among. */
|
||||
@Serializable
|
||||
data class DataGroup(val id: String = "", val name: String = "")
|
||||
|
||||
/**
|
||||
* One memory (`/api/v2/memories`, Settings › Memory on the web): its text, who wrote it (`user`
|
||||
* or `model` -- a model's is model output, drawn as plain text), and its data group.
|
||||
*/
|
||||
@Serializable
|
||||
data class Memory(
|
||||
val id: String,
|
||||
val content: String = "",
|
||||
val author: String = "",
|
||||
@SerialName("data_group") val dataGroup: DataGroup = DataGroup(),
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
) {
|
||||
val byModel: Boolean get() = author == "model"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class MemoryList(val memories: List<Memory> = emptyList(), val groups: List<DataGroup> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class MemoryEnvelope(val memory: Memory)
|
||||
|
||||
@Serializable
|
||||
data class FolderList(val folders: List<Folder> = emptyList())
|
||||
@@ -143,7 +327,21 @@ data class FolderList(val folders: List<Folder> = emptyList())
|
||||
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 = "")
|
||||
data class LinkedDevice(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val host: String = "",
|
||||
val platform: String = "",
|
||||
/** Whether the device accepts scheduled work: only then may an Agentic schedule belong to it. */
|
||||
val scheduled: Boolean = false,
|
||||
/** The widest mode the device lets a scheduled run have; empty where it accepts none. */
|
||||
@SerialName("max_mode") val maxMode: String = "",
|
||||
/** Whether the device remembers the model last used in a directory (spec 3.9.0). */
|
||||
@SerialName("directory_model") val directoryModel: Boolean = false,
|
||||
) {
|
||||
/** What to call it: its name, else its host. */
|
||||
val label: String get() = name.ifBlank { host.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class DeviceList(val devices: List<LinkedDevice> = emptyList())
|
||||
@@ -169,13 +367,25 @@ data class Chat(
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@SerialName("system_prompt") val systemPrompt: String? = null,
|
||||
/** What may be done to this chat (`rename`, `delete`, `archive`, `pin`, `folder`); null from a server that does not say: everything. */
|
||||
val controls: List<String>? = null,
|
||||
/** The report this chat continues (`kind` `report`): such a chat lives under Reports, not among the chats. */
|
||||
val report: ChatReport? = null,
|
||||
val plan: JsonObject? = null,
|
||||
/** The team's size: how many agents, its own included, the chat may have. */
|
||||
val agents: AgentsSetting? = null,
|
||||
/** Whether this chat is offered subagents, and the cap (server 2.0.0-beta.7); null from an older one. */
|
||||
val subagents: SubagentsOffer? = null,
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
|
||||
fun allows(control: String): Boolean = controls?.contains(control) ?: true
|
||||
}
|
||||
|
||||
/** The report a chat continues: its id and title. */
|
||||
@Serializable
|
||||
data class ChatReport(val id: String = "", val title: String = "")
|
||||
|
||||
/** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */
|
||||
@Serializable
|
||||
data class AgentsSetting(val min: Int = 1, val max: Int = 4) {
|
||||
@@ -227,8 +437,23 @@ data class Metrics(
|
||||
@SerialName("tok_s") val tokPerSecond: Double = 0.0,
|
||||
)
|
||||
|
||||
/**
|
||||
* How a call is drawn (`display.md`): its [kind], the one short [title], the facts after it as
|
||||
* [chips] (an edit's `+N −M`, a non-zero `exit N`, the hits), and from spec 3.7.0 its [state]
|
||||
* (running, done, failed, denied), the [duration] of a finished call as the spec writes it, and
|
||||
* the tool's name as a person reads it ([label]). The last three are empty from an older server.
|
||||
*/
|
||||
@Serializable
|
||||
data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List<String> = emptyList(), val added: Int = 0, val removed: Int = 0)
|
||||
data class ToolBlock(
|
||||
val kind: String = "tool",
|
||||
val title: String = "",
|
||||
val chips: List<String> = emptyList(),
|
||||
val added: Int = 0,
|
||||
val removed: Int = 0,
|
||||
val state: String = "",
|
||||
val duration: String = "",
|
||||
val label: String = "",
|
||||
)
|
||||
|
||||
/** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */
|
||||
@Serializable
|
||||
@@ -248,15 +473,27 @@ data class ToolCall(
|
||||
val diff: String? = null,
|
||||
val exit: Int? = null,
|
||||
val hits: Int? = null,
|
||||
/** How long the call took, in milliseconds (spec 3.7.0: `tool_end`'s `ms`); null where it was not kept. */
|
||||
val ms: Long? = null,
|
||||
val path: String? = null,
|
||||
val truncated: Boolean = false,
|
||||
val job: JsonElement? = null,
|
||||
val children: List<ToolCall>? = null,
|
||||
/** The `show` tool's card: a file put in front of the person. Never its text. */
|
||||
val show: ShowCard? = null,
|
||||
/** `image_generate`'s picture: the server's own attachment, by id, and its size. */
|
||||
val image: GeneratedImage? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A picture the instance made (`event["image"]`): an attachment of the chat's owner, fetched
|
||||
* with the token from `GET /api/v2/attachments/{id}` and nowhere else. Its size is known before
|
||||
* it loads, so the space it takes does not jump.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedImage(val id: String = "", val width: Int = 0, val height: Int = 0)
|
||||
|
||||
/**
|
||||
* What a `show` call put in front of the person (`event["show"]`, harness spec 3.0.0): the
|
||||
* file's name and where it is, never its contents -- the viewer fetches those. A file from the
|
||||
@@ -338,7 +575,7 @@ data class FileContent(
|
||||
@Serializable
|
||||
data class SteerNote(val id: String = "", val text: String = "")
|
||||
|
||||
/** One step of a reply: `thinking`, `text`, `tools` or `steer`. */
|
||||
/** One step of a reply: `thinking`, `text`, `tools`, `steer` or `page`. */
|
||||
@Serializable
|
||||
data class Step(
|
||||
val index: Int = 0,
|
||||
@@ -347,10 +584,32 @@ data class Step(
|
||||
val text: String? = null,
|
||||
val label: String? = null,
|
||||
val markdown: String? = null,
|
||||
/** A `page` step's title (spec 3.8.0): the page itself is not sent to a client that does not draw it. */
|
||||
val title: String? = null,
|
||||
/** A `text` step's pages (spec 3.8.0): where it has any, [text] is its markdown with each page as the one line `[page: Title]`. */
|
||||
val pages: List<StepPage> = emptyList(),
|
||||
val calls: List<ToolCall> = emptyList(),
|
||||
val messages: List<SteerNote> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A reply's end when it did not finish: `stopped` with `person`, `steps`, `budget` or no reason,
|
||||
* or `failed` with the error's first line. [text] is the line in the account's language; the app
|
||||
* writes its own from [phase] and [reason], in the app's language.
|
||||
*/
|
||||
@Serializable
|
||||
data class MessageEnd(val phase: String = "", val reason: String = "", val text: String = "")
|
||||
|
||||
/** A page in a reply's text: its title (the page itself is fetched by its digest, by a client that draws pages). */
|
||||
@Serializable
|
||||
data class StepPage(val title: String = "", val digest: String = "")
|
||||
|
||||
/**
|
||||
* What a client that draws no pages shows of a `text` step: the server's own text where the step
|
||||
* has pages (each page its one line), else the markdown as it is.
|
||||
*/
|
||||
val Step.shownMarkdown: String get() = text?.takeIf { pages.isNotEmpty() && it.isNotBlank() } ?: markdown.orEmpty()
|
||||
|
||||
@Serializable
|
||||
data class Message(
|
||||
val id: String,
|
||||
@@ -359,6 +618,8 @@ data class Message(
|
||||
val complete: Boolean = true,
|
||||
val stopped: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** How a reply that did not finish ended (spec 3.7.0); null for one that finished, or from an older server. */
|
||||
val end: MessageEnd? = null,
|
||||
val queued: Boolean = false,
|
||||
val machine: Boolean = false,
|
||||
val origin: String = "",
|
||||
@@ -368,6 +629,8 @@ data class Message(
|
||||
val steps: List<Step> = emptyList(),
|
||||
val plan: JsonObject? = null,
|
||||
val metrics: Metrics? = null,
|
||||
/** A prompt queued behind a running reply: `{phase: queued, since, ahead}`; null otherwise. */
|
||||
val progress: Progress? = null,
|
||||
) {
|
||||
val isUser: Boolean get() = role == "user"
|
||||
}
|
||||
@@ -398,12 +661,24 @@ data class CardItem(
|
||||
val options: List<Option> = emptyList(),
|
||||
val multiple: Boolean = false,
|
||||
@SerialName("free_text") val freeText: Boolean = true,
|
||||
/** An approval: whether "Always allow" is offered beside "Allow once" (spec 3.7.0). An older server says nothing, and offered it always. */
|
||||
val always: Boolean = true,
|
||||
val editable: Boolean = false,
|
||||
val plan: JsonObject? = null,
|
||||
@SerialName("mode_choice") val modeChoice: Boolean = false,
|
||||
val job: String = "",
|
||||
/** The tree subagent asking (spec 3.4.0), for a call nobody in the tree may allow; null otherwise. */
|
||||
val subagent: CardSubagent? = null,
|
||||
/**
|
||||
* A `phone_action` card's action (spec 3.6.0, `phone.md` §2): `action`, `summary` and the
|
||||
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
|
||||
*/
|
||||
val phone: JsonObject? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
|
||||
|
||||
@Serializable
|
||||
data class Card(
|
||||
val id: String,
|
||||
@@ -437,6 +712,8 @@ data class Job(
|
||||
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
|
||||
@Serializable
|
||||
data class CardAnswer(
|
||||
/** A phone card's answer: what the phone did once the person confirmed or declined. */
|
||||
val result: PhoneResult? = null,
|
||||
val verdict: String = "",
|
||||
val reason: String = "",
|
||||
val choices: Map<String, List<String>> = emptyMap(),
|
||||
@@ -444,6 +721,9 @@ data class CardAnswer(
|
||||
val asks: Map<String, String> = emptyMap(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class PhoneResult(val status: String, val message: String = "")
|
||||
|
||||
@Serializable
|
||||
data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
|
||||
@@ -460,8 +740,17 @@ data class StepsFrame(val steps: List<Step> = emptyList(), val tail: Tail = Tail
|
||||
@Serializable
|
||||
data class SteeredFrame(val ids: List<String> = emptyList())
|
||||
|
||||
/**
|
||||
* The `status` frame: the free [text] every server sends, and beside it from harness spec 3.4.0
|
||||
* the structured [progress] (`progress.md`) -- null when the session is doing nothing, or from
|
||||
* an older server. A client that reads [progress] draws it and ignores [text].
|
||||
*/
|
||||
@Serializable
|
||||
data class StatusFrame(val text: String = "")
|
||||
data class StatusFrame(val text: String = "", val progress: Progress? = null)
|
||||
|
||||
/** The `tree` frame (spec 3.4.0): the subagent tree, once there is one, whenever it changes. */
|
||||
@Serializable
|
||||
data class TreeFrame(val tree: SubagentTree? = null)
|
||||
|
||||
@Serializable
|
||||
data class AskFrame(val cards: List<Card> = emptyList())
|
||||
@@ -471,10 +760,19 @@ data class JobsFrame(val jobs: List<Job> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class DoneFrame(val message: Message, val chat: DoneChat = DoneChat(), val next: String? = null) {
|
||||
/**
|
||||
* [titlePending]: a model is still naming the chat, so [title] is the one made from the
|
||||
* prompt and a `title` frame may follow before `close`. `done` is the end of the reply all
|
||||
* the same.
|
||||
*/
|
||||
@Serializable
|
||||
data class DoneChat(val id: String = "", val title: String = "")
|
||||
data class DoneChat(val id: String = "", val title: String = "", @SerialName("title_pending") val titlePending: Boolean = false)
|
||||
}
|
||||
|
||||
/** The `title` frame: the name a model gave the chat, after `done`. */
|
||||
@Serializable
|
||||
data class TitleFrame(val chat: DoneFrame.DoneChat = DoneFrame.DoneChat())
|
||||
|
||||
/** The push payload the server sends (services/push.py), as the app reads it. */
|
||||
@Serializable
|
||||
data class PushPayload(
|
||||
@@ -486,6 +784,27 @@ data class PushPayload(
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("interaction_id") val interactionId: String? = null,
|
||||
val ask: String? = null,
|
||||
/**
|
||||
* A scheduled run's result or failure (`kind` `schedule` or `schedule_failed`,
|
||||
* services/schedule/notify.py): the ids, the run's [status], `private` [visibility] (the
|
||||
* text stays off the lock screen), the [actions] the notification may offer (`open`,
|
||||
* `pause`), and [ask] `pause` when it failed so often that it asks whether to pause it.
|
||||
*/
|
||||
@SerialName("schedule_id") val scheduleId: String? = null,
|
||||
@SerialName("run_id") val runId: String? = null,
|
||||
/** A report was filed (`kind` `report`, spec 3.8.0): its id; [title] and [body] are its title and summary, [url] `/reports/{id}`. */
|
||||
@SerialName("report_id") val reportId: String? = null,
|
||||
/** A report's `normal` or `high`. */
|
||||
val importance: String? = null,
|
||||
val status: String? = null,
|
||||
val visibility: String? = null,
|
||||
val actions: List<String> = emptyList(),
|
||||
/**
|
||||
* The run's notification as the server wrote it (newer servers; the payload is encrypted end
|
||||
* to end): the task's name and the result's first lines, the lock-screen version, and the
|
||||
* actions' labels in the owner's language. Null from an older server: the fixed sentence then.
|
||||
*/
|
||||
val notification: RunNotification? = null,
|
||||
)
|
||||
|
||||
// --- The activity panel (`GET /chats/{chat}/activity`) -------------------------------------
|
||||
@@ -510,7 +829,7 @@ data class AgentStep(val tool: String = "", val label: String = "", val title: S
|
||||
|
||||
/**
|
||||
* One background agent: a team's member (`kind` member, [id] its name) or a job (`kind` job;
|
||||
* [type] `subagent` or `command`), with its own helpers in [children]. [role], [brief] and
|
||||
* [type] `subagent` or `command`), with its own subagents in [children]. [role], [brief] and
|
||||
* [text] are a model's words: shown as text, never as anything richer.
|
||||
*/
|
||||
@Serializable
|
||||
@@ -577,6 +896,14 @@ data class ContextUse(
|
||||
val percent: Double? = null,
|
||||
val measured: Boolean = false,
|
||||
val threshold: Int = 0,
|
||||
/**
|
||||
* The compaction facts (server 2.0.0-beta.7): whether the chat compacts by itself, how many
|
||||
* tokens before it does (null: never, or not known), and whether Compact can run now.
|
||||
* Null from an older server; the app then works the first two out from [threshold].
|
||||
*/
|
||||
@SerialName("auto_compact") val autoCompact: Boolean? = null,
|
||||
@SerialName("until_compact") val untilCompact: Int? = null,
|
||||
val compactable: Boolean? = null,
|
||||
@SerialName("tools_count") val toolsCount: Int = 0,
|
||||
@SerialName("mcp_count") val mcpCount: Int = 0,
|
||||
val categories: List<ContextPart> = emptyList(),
|
||||
@@ -602,6 +929,8 @@ data class Activity(
|
||||
val agents: List<ActivityAgent> = emptyList(),
|
||||
val team: ActivityTeam? = null,
|
||||
@SerialName("team_offered") val teamOffered: Boolean = false,
|
||||
/** The same fact by the word a person reads (server 2.0.0-beta.7). */
|
||||
@SerialName("subagents_offered") val subagentsOffered: Boolean? = null,
|
||||
val context: ContextUse? = null,
|
||||
val outputs: List<Output> = emptyList(),
|
||||
val plan: JsonObject? = null,
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* What a session is doing (harness spec 3.4.0, `progress.md`): one of a fixed set of [phase]s,
|
||||
* since [since] (Unix milliseconds), with the phase's data. A field that is not known is left
|
||||
* out by the sender, so every one is optional here, and the text says less without it.
|
||||
*/
|
||||
@Serializable
|
||||
data class Progress(
|
||||
val phase: String,
|
||||
val since: Long = 0,
|
||||
/** queued: turns before it. */
|
||||
val ahead: Int? = null,
|
||||
/** waiting_for_model, loading_model: the model's display name. */
|
||||
val model: String? = null,
|
||||
/** waiting_for_model: busy | slots | group. stopped: person | steps | budget. retrying, failed: the error. */
|
||||
val reason: String? = null,
|
||||
/** reading_prompt: prompt tokens processed, of [total]. */
|
||||
val done: Int? = null,
|
||||
val total: Int? = null,
|
||||
/** writing: tokens a second. */
|
||||
val rate: Double? = null,
|
||||
/** running_tool: the tool's name; waiting_for_person (approval): the tool asked about. */
|
||||
val tool: String? = null,
|
||||
/** running_tool: the call's short title. waiting_for_person: approval | question | plan. */
|
||||
val what: String? = null,
|
||||
/** waiting_for_subagents: subagents working or waiting. */
|
||||
val running: Int? = null,
|
||||
/** retrying: seconds until the retry, counted down from [since]. */
|
||||
@SerialName("in") val inSeconds: Int? = null,
|
||||
val attempt: Int? = null,
|
||||
) {
|
||||
companion object {
|
||||
/** `loop.json` `progress.no_elapsed`: drawn as their text alone. */
|
||||
val NO_ELAPSED = END_PHASES
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared texts (`loop.json` `progress.texts`, the i18n keys `progress.<phase>` …), as this
|
||||
* app holds them: [text] returns the template for a key with its arguments filled in, or null for
|
||||
* a key it does not have. The keys are the spec's with `.` as `_`: `queued_ahead`,
|
||||
* `reason_busy`, `what_approval_bare`, `stopped_reason_person`, `line`.
|
||||
*/
|
||||
fun interface ProgressWords {
|
||||
fun text(key: String, vararg args: String): String?
|
||||
}
|
||||
|
||||
/**
|
||||
* The phase's text, its fields filled (`progress.md` §2): every count and measure in [locale]'s
|
||||
* own number format (`display.md` §6: the phone's grouping and decimal mark; [Locale.ROOT] is the
|
||||
* spec's plain format), a title that had to be cut ending in `…`, `retrying`'s `in` counted down
|
||||
* to [now]. Null for a phase this app does not know -- a newer server's -- so the caller falls
|
||||
* back to the `status` text.
|
||||
*/
|
||||
fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? {
|
||||
val p = progress
|
||||
return when (p.phase) {
|
||||
"queued" -> if (p.ahead != null) words.text("queued_ahead", localeNumber(p.ahead.toLong(), locale)) else words.text("queued")
|
||||
|
||||
"waiting_for_model" -> {
|
||||
val model = p.model ?: return null
|
||||
val why = p.reason?.let { words.text("reason_$it") ?: it } ?: return null
|
||||
words.text("waiting_for_model", model, why)
|
||||
}
|
||||
|
||||
"loading_model" -> p.model?.let { words.text("loading_model", it) }
|
||||
|
||||
"reading_prompt" -> {
|
||||
val done = p.done
|
||||
val total = p.total
|
||||
if (done != null && total != null && total > 0) {
|
||||
val percent = localeNumber(done.toLong() * 100 / total, locale)
|
||||
words.text("reading_prompt", localeNumber(done.toLong(), locale), localeNumber(total.toLong(), locale), percent)
|
||||
} else {
|
||||
words.text("reading_prompt_bare")
|
||||
}
|
||||
}
|
||||
|
||||
"thinking" -> words.text("thinking")
|
||||
|
||||
"writing" -> p.rate?.let { words.text("writing", localeNumber(it, 1, locale)) } ?: words.text("writing_bare")
|
||||
|
||||
"running_tool" -> {
|
||||
val tool = p.tool ?: return null
|
||||
// The call's short title (display.md §1): one line, and `…` where it had to be cut.
|
||||
val what = shortTitle(p.what)
|
||||
if (what != null) words.text("running_tool", tool, what) else words.text("running_tool_bare", tool)
|
||||
}
|
||||
|
||||
"waiting_for_person" -> {
|
||||
val what = when (p.what) {
|
||||
"approval" -> if (!p.tool.isNullOrBlank()) words.text("what_approval", p.tool) else words.text("what_approval_bare")
|
||||
null -> null
|
||||
else -> words.text("what_${p.what}")
|
||||
} ?: return null
|
||||
words.text("waiting_for_person", what)
|
||||
}
|
||||
|
||||
"waiting_for_subagents" -> words.text("waiting_for_subagents", localeNumber((p.running ?: 0).toLong(), locale))
|
||||
|
||||
"compacting" -> words.text("compacting")
|
||||
|
||||
"retrying" -> {
|
||||
val left = ((p.inSeconds ?: 0) - ((now - p.since).coerceAtLeast(0) / 1000)).coerceAtLeast(0)
|
||||
words.text("retrying", "$left", p.reason.orEmpty())
|
||||
}
|
||||
|
||||
"stopped" -> {
|
||||
val why = p.reason?.let { words.text("stopped_reason_$it") }
|
||||
if (why != null) words.text("stopped_reason", why) else words.text("stopped")
|
||||
}
|
||||
|
||||
"failed" -> words.text("failed", p.reason.orEmpty())
|
||||
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The line a client draws (`progress.md` §3): `{{text}} · {{elapsed}}`, or the text alone for
|
||||
* `stopped` and `failed`. Null when [progressText] is.
|
||||
*/
|
||||
fun progressLine(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? {
|
||||
val text = progressText(progress, words, now, locale) ?: return null
|
||||
if (progress.phase in Progress.NO_ELAPSED) return text
|
||||
return words.text("line", text, elapsed(now - progress.since)) ?: text
|
||||
}
|
||||
|
||||
/** Whole seconds as a ticking clock writes a duration: `5s`, `1m 05s`, `1h 02m`. Never negative. */
|
||||
fun elapsed(millis: Long): String {
|
||||
val seconds = millis.coerceAtLeast(0) / 1000
|
||||
return when {
|
||||
seconds < 60 -> "${seconds}s"
|
||||
seconds < 3600 -> "${seconds / 60}m ${"%02d".format(Locale.ROOT, seconds % 60)}s"
|
||||
else -> "${seconds / 3600}h ${"%02d".format(Locale.ROOT, (seconds % 3600) / 60)}m"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonNames
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.contentOrNull
|
||||
|
||||
// --- Reports (`/api/v2/reports`, harness spec 3.8.0 `reports.md`) -----------------------------
|
||||
//
|
||||
// A schedule's run does not answer into a chat: it files a report, or it does not. The server
|
||||
// stores the reports and lists them; a report's body is Markdown, as a reply is.
|
||||
//
|
||||
// The shapes are read leniently where an id may come as a string or as an object carrying one
|
||||
// ([chat], a run's `report`), so that a server that says a little more still parses; the
|
||||
// contract fixtures (`contract/report*.json`) pin what it says.
|
||||
|
||||
/** The schedule a report came from: its id and its name. */
|
||||
@Serializable
|
||||
data class ReportSchedule(val id: String = "", val title: String = "")
|
||||
|
||||
/**
|
||||
* One report: [title] a headline, [summary] a sentence or two for a list or a notification,
|
||||
* [importance] `normal` or `high` (look now), the [schedule] that filed it, [created] when, and
|
||||
* whether it is still [unread]. Read alone it also carries its [body] (Markdown a model wrote:
|
||||
* untrusted) and the [chat] a reply continues in, once there is one.
|
||||
*/
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
@Serializable
|
||||
data class Report(
|
||||
val id: String,
|
||||
val title: String = "",
|
||||
val summary: String = "",
|
||||
val importance: String = "normal",
|
||||
val schedule: ReportSchedule? = null,
|
||||
/** The schedule's name as it was when the report was filed: what is left once the schedule itself is gone. */
|
||||
@SerialName("schedule_title") val scheduleTitle: String = "",
|
||||
@JsonNames("created_at") val created: String? = null,
|
||||
val unread: Boolean = false,
|
||||
val body: String? = null,
|
||||
/** The body as text: every page in it replaced by its one line, `[page: Title]`; the body itself where it has none. */
|
||||
val text: String? = null,
|
||||
/** The pages the body has: only these are pages -- an `html-view` fence the server does not list is a code block. */
|
||||
val pages: List<StepPage> = emptyList(),
|
||||
val model: String? = null,
|
||||
val chat: JsonElement? = null,
|
||||
) {
|
||||
val high: Boolean get() = importance == "high"
|
||||
|
||||
/** The name of the task it came from: the schedule's as it is now, else as it was. */
|
||||
val from: String get() = schedule?.title?.ifBlank { null } ?: scheduleTitle
|
||||
|
||||
/** The chat a reply to this report continues in; null before the first reply. */
|
||||
val chatId: String? get() = idOf(chat)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ReportList(val reports: List<Report> = emptyList(), val unread: Int? = null) {
|
||||
/** How many reports are unread: the server's count, else as many as it listed unread. */
|
||||
val unreadCount: Int get() = unread ?: reports.count { it.unread }
|
||||
}
|
||||
|
||||
/** `GET /events`, frame `reports`: the count of the unread, and the newest report. */
|
||||
@Serializable
|
||||
data class ReportsFrame(val unread: Int = 0, val newest: Report? = null, @SerialName("latest_created") val latestCreated: String? = null)
|
||||
|
||||
/** `POST /reports/{id}/reply`: the chat the conversation about the report is in. */
|
||||
@Serializable
|
||||
data class ReportReply(val chat: JsonElement? = null) {
|
||||
val chatId: String? get() = idOf(chat)
|
||||
}
|
||||
|
||||
/** An id that came as a string, or as an object with an `id`; null for anything else. */
|
||||
internal fun idOf(element: JsonElement?): String? = when (element) {
|
||||
is JsonPrimitive -> element.contentOrNull?.takeIf { element.isString && it.isNotBlank() }
|
||||
is JsonObject -> idOf(element["id"])
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** Reports as the list shows them: the unread first, then the newest first within each half. */
|
||||
fun sortedReports(reports: List<Report>): List<Report> = reports.sortedWith(compareByDescending<Report> { it.unread }.thenByDescending { it.created.orEmpty() })
|
||||
|
||||
/**
|
||||
* When a schedule's owner wants to hear from it (`loop.json` `scheduled.notify`): `always` (a
|
||||
* report every run), `when` (only when the person's own words hold) or `never` (history only).
|
||||
* A server before 3.8.0 said `matters` for what is now `when`; anything else is the default.
|
||||
*/
|
||||
fun notifyChoice(notify: String): String = when (notify) {
|
||||
"always", "never" -> notify
|
||||
else -> "when"
|
||||
}
|
||||
|
||||
/**
|
||||
* An id as the server makes them -- letters, digits, `_` and `-`, at most 64 -- or null. Anything
|
||||
* that came from outside the app (a push payload, an intent's extra) is passed through this
|
||||
* before it becomes part of a route or an address: a `/` in it must not open another page.
|
||||
*/
|
||||
fun safeId(id: String?): String? = id?.takeIf { SAFE_ID.matches(it) }
|
||||
|
||||
private val SAFE_ID = Regex("^[A-Za-z0-9_-]{1,64}$")
|
||||
@@ -0,0 +1,301 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
|
||||
// --- Scheduled tasks (`/api/v2/schedules`) ------------------------------------------------
|
||||
//
|
||||
// The server's shapes, as its contract fixtures pin them (`contract/schedule*.json`,
|
||||
// `event_schedules.json`; `ContractTest` reads every one). Every field has a default, so a
|
||||
// server that says less still parses.
|
||||
|
||||
/**
|
||||
* The model a run used, and how it came to it ([reason]): `pinned` (the schedule's own),
|
||||
* `switched` (it stood in for [switchedFrom], which was busy), `directory` (the folder's usual
|
||||
* model, asked of the computer), `default` (the person's default, where the folder had none) or
|
||||
* `session` (a continued conversation kept its own).
|
||||
*/
|
||||
@Serializable
|
||||
data class RunModel(
|
||||
val id: String? = null,
|
||||
val name: String? = null,
|
||||
val reason: String? = null,
|
||||
@SerialName("switched_from") val switchedFrom: String? = null,
|
||||
) {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String? get() = name ?: id
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class RunTokens(val prompt: Long = 0, val completion: Long = 0)
|
||||
|
||||
@Serializable
|
||||
data class RunCost(val micro: Long = 0, val currency: String = "")
|
||||
|
||||
/**
|
||||
* Why a run failed or waits: [kind] a class the app may read, [text] the sentence to show (the
|
||||
* server's, or the device's own), and [reason] a narrower word where there is one -- `terminal`:
|
||||
* the schedule's session was open in a terminal on the computer.
|
||||
*/
|
||||
@Serializable
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "", val reason: String? = null)
|
||||
|
||||
/**
|
||||
* One run of a schedule: when it was due and how it went. [status] is `running`, `waiting` (no
|
||||
* model free yet, or a retry: [waitingFor], [retryAt]), `ok`, `silent` (nothing worth saying),
|
||||
* `failed`, `skipped` or `missed`; [timing] `on_time`, `late`, `catch_up` or `manual`.
|
||||
* [preview] is the result's first lines -- model output, shown as plain text and never as markup.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleRun(
|
||||
val id: String = "",
|
||||
@SerialName("schedule_id") val scheduleId: String = "",
|
||||
val status: String = "",
|
||||
val timing: String = "",
|
||||
/** How many runs were missed before this one (`missed ×N`). */
|
||||
val missed: Int = 0,
|
||||
@SerialName("due_at") val dueAt: String? = null,
|
||||
@SerialName("started_at") val startedAt: String? = null,
|
||||
@SerialName("finished_at") val finishedAt: String? = null,
|
||||
@SerialName("waiting_for") val waitingFor: String? = null,
|
||||
@SerialName("retry_at") val retryAt: String? = null,
|
||||
/** What the run is doing now (harness spec 3.4.0, `progress.md`): waiting for which model and why, its reply's phase. */
|
||||
val progress: Progress? = null,
|
||||
val attempts: Int = 0,
|
||||
val model: RunModel = RunModel(),
|
||||
val tokens: RunTokens = RunTokens(),
|
||||
val cost: RunCost? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
@SerialName("report_path") val reportPath: String? = null,
|
||||
val preview: String = "",
|
||||
val error: RunError? = null,
|
||||
val notified: Boolean = false,
|
||||
/** The notification the server made for this run, when it made one (see [RunNotification]). */
|
||||
val notification: RunNotification? = null,
|
||||
/** A watching schedule's look at its address on this run (`unchanged` when nothing moved). */
|
||||
val watch: RunWatch? = null,
|
||||
/** The run's line in the history (spec 3.8.0): the answer's first line, or why no report was filed. */
|
||||
val note: String = "",
|
||||
/** The report this run filed, when it filed one: its id (or an object carrying it). */
|
||||
val report: JsonElement? = null,
|
||||
/** Where an Agentic schedule's run ran (spec 3.9.0); null for a Chat schedule's, or from an older server. */
|
||||
@SerialName("ran_on") val ranOn: RanOn? = null,
|
||||
) {
|
||||
val reportId: String? get() = idOf(report)
|
||||
}
|
||||
|
||||
/**
|
||||
* A scheduled task. [description] is the rule in words, as the server says it ("On the second
|
||||
* Monday of each month at 07:30"), in [timezone]; [rule] the server's own form of it; [request]
|
||||
* the person's words it was made from; [instruction] what the model is asked each time.
|
||||
* [notify] is `always`, `when` or `never` (spec 3.8.0; `matters` before it) and [notifyWhen] the
|
||||
* person's own words for `when`; [mode] `fresh` (a chat per run) or `continue`.
|
||||
*/
|
||||
@Serializable
|
||||
data class Schedule(
|
||||
val id: String,
|
||||
val title: String = "",
|
||||
val instruction: String = "",
|
||||
val request: String = "",
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
val timezone: String = "",
|
||||
val enabled: Boolean = true,
|
||||
@SerialName("next_run") val nextRun: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
val target: String = "chat",
|
||||
val mode: String = "",
|
||||
val notify: String = "",
|
||||
@SerialName("notify_when") val notifyWhen: String = "",
|
||||
/** What "When…" means while [notifyWhen] is empty, in the account's language. */
|
||||
@SerialName("notify_default") val notifyDefault: String = "",
|
||||
@SerialName("catch_up") val catchUp: String = "",
|
||||
@SerialName("grace_minutes") val graceMinutes: Int? = null,
|
||||
val model: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: Int? = null,
|
||||
val tools: List<String> = emptyList(),
|
||||
val origin: String = "",
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("fired_count") val firedCount: Int = 0,
|
||||
@SerialName("failure_streak") val failureStreak: Int = 0,
|
||||
/** Monitor mode: what the schedule watches; the model runs only when it changed. */
|
||||
val watch: ScheduleWatch? = null,
|
||||
/** The linked computer it runs on, as an agent chat there; null: on the server. */
|
||||
@SerialName("runs_on") val runsOn: RunsOn? = null,
|
||||
@SerialName("last_error") val lastError: String? = null,
|
||||
@SerialName("last_run") val lastRun: ScheduleRun? = null,
|
||||
val running: Boolean = false,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
) {
|
||||
val paused: Boolean get() = !enabled
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ScheduleList(val schedules: List<Schedule> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class ScheduleEnvelope(val schedule: Schedule)
|
||||
|
||||
@Serializable
|
||||
data class RunEnvelope(val run: ScheduleRun)
|
||||
|
||||
@Serializable
|
||||
data class ScheduleRuns(val runs: List<ScheduleRun> = emptyList(), val more: Boolean = false)
|
||||
|
||||
/** One run and its result in full: Markdown a model wrote, rendered as untrusted. Null: none. */
|
||||
@Serializable
|
||||
data class RunResult(val run: ScheduleRun, val text: String? = null)
|
||||
|
||||
/** `GET /events`, frame `schedules`: the whole list whenever [version] moves. */
|
||||
@Serializable
|
||||
data class SchedulesFrame(val version: String = "", val schedules: List<Schedule> = emptyList())
|
||||
|
||||
/**
|
||||
* What the server made of a person's words (`POST /schedules/compile`): a title, the
|
||||
* instruction, the rule and the rule in words, and the next runs -- shown before anything is
|
||||
* saved. [ok] false: the rest is filled as far as it went, and [reason] says why. An empty
|
||||
* [rule] cannot run, so it cannot be saved.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleCompiled(
|
||||
val ok: Boolean = false,
|
||||
val reason: String? = null,
|
||||
val title: String = "",
|
||||
val instruction: String = "",
|
||||
val target: String = "chat",
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
val timezone: String = "",
|
||||
) {
|
||||
val savable: Boolean get() = rule.isNotEmpty() && instruction.isNotBlank()
|
||||
}
|
||||
|
||||
/** A rule read back (`POST /schedules/preview`): cleaned, in words, and its next runs. */
|
||||
@Serializable
|
||||
data class RulePreview(
|
||||
val rule: JsonObject = JsonObject(emptyMap()),
|
||||
val description: String? = null,
|
||||
@SerialName("next_runs") val nextRuns: List<String> = emptyList(),
|
||||
val timezone: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* A model scheduled work may run on, in the order they are tried: [free] now or [busy] (the
|
||||
* server's words), and [chosen] when it is in the person's narrowing (all are, without one).
|
||||
*/
|
||||
@Serializable
|
||||
data class SchedulingModel(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val image: String? = null,
|
||||
val free: Boolean = false,
|
||||
val busy: String? = null,
|
||||
val chosen: Boolean = true,
|
||||
/** The model's unambiguous name (`provider/id`) and its connection's, as on every model object. */
|
||||
val ref: String = "",
|
||||
val connection: String = "",
|
||||
) {
|
||||
/** What a schedule's model is chosen and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
}
|
||||
|
||||
/** The scheduling model a name means: by its `ref`, else the first with that `id`. */
|
||||
fun List<SchedulingModel>.named(name: String?): SchedulingModel? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/** A scheduling model's name in a list of [all]: with its connection where another there shares its id. */
|
||||
fun SchedulingModel.titleAmong(all: List<SchedulingModel>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** `GET`/`PUT /schedules/models`: the models, the instance's order, and the person's narrowing. */
|
||||
@Serializable
|
||||
data class SchedulingModels(val models: List<SchedulingModel> = emptyList(), val instance: List<String> = emptyList(), val mine: List<String> = emptyList())
|
||||
|
||||
/**
|
||||
* What a watching schedule looks at before each run: [kind] `url` and the address, or -- on a
|
||||
* linked computer -- `command`, the [command] run in the schedule's folder and how many seconds
|
||||
* it may take ([timeoutS]). [target] is either, as one string.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleWatch(
|
||||
val kind: String = "",
|
||||
val target: String = "",
|
||||
val command: String = "",
|
||||
@SerialName("timeout_s") val timeoutS: Int? = null,
|
||||
@SerialName("changed_at") val changedAt: String? = null,
|
||||
)
|
||||
|
||||
/** One run's look: whether the address [changed] since the last one, or why the look failed. */
|
||||
@Serializable
|
||||
data class RunWatch(val kind: String = "", val changed: Boolean = false, val first: Boolean = false, val bytes: Long = 0, val error: String? = null)
|
||||
|
||||
/** The lock-screen half of a [RunNotification]: the task's name and Finished / Failed only. */
|
||||
@Serializable
|
||||
data class PublicNotice(val title: String = "", val body: String = "")
|
||||
|
||||
/**
|
||||
* A scheduled run's notification as the server wrote it, in the owner's language: [title] (the
|
||||
* task's name) and [body] (the result's first lines) for an unlocked phone, [public] for the
|
||||
* lock screen, and [actions] (`open`, `run_again`, `pause`) with their [labels]. [ask] names the
|
||||
* action the body asks about (`pause` after failures).
|
||||
*/
|
||||
@Serializable
|
||||
data class RunNotification(
|
||||
val title: String = "",
|
||||
val body: String = "",
|
||||
val public: PublicNotice = PublicNotice(),
|
||||
val actions: List<String> = emptyList(),
|
||||
val labels: Map<String, String> = emptyMap(),
|
||||
val ask: String = "",
|
||||
/** A report's notification: `normal` or `high`. */
|
||||
val importance: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Where a schedule runs when not on the server (harness spec 3.5.0): a linked computer
|
||||
* ([deviceName]), the folder there, the agent mode (never wider than Edit unless chosen), and how
|
||||
* long an approval it needs waits on the phone.
|
||||
*/
|
||||
@Serializable
|
||||
data class RunsOn(
|
||||
val device: String = "",
|
||||
@SerialName("device_name") val deviceName: String = "",
|
||||
val cwd: String = "",
|
||||
val mode: String = "",
|
||||
@SerialName("approval_wait_minutes") val approvalWaitMinutes: Int? = null,
|
||||
)
|
||||
|
||||
/** Where one run ran: the computer ([deviceName]), the folder there and the mode it had. */
|
||||
@Serializable
|
||||
data class RanOn(val device: String = "", @SerialName("device_name") val deviceName: String = "", val cwd: String = "", val mode: String = "")
|
||||
|
||||
/** The two types of schedule (spec 3.9.0). There is no field for it: Agentic is one with a computer. */
|
||||
val Schedule.agentic: Boolean get() = runsOn != null
|
||||
|
||||
/** A run that waits because its computer is not linked (`error.class` `device_away`). */
|
||||
val ScheduleRun.computerAway: Boolean get() = error?.kind == "device_away"
|
||||
|
||||
/**
|
||||
* What a save says about where a schedule runs, which is its type: nothing ([Leave]), on the
|
||||
* server ([Server]: Chat), or on a computer ([Computer]: Agentic) -- in a folder there, in a
|
||||
* mode, with an approval's wait in minutes (null: the server's default).
|
||||
*/
|
||||
sealed interface WhereToRun {
|
||||
data object Leave : WhereToRun
|
||||
|
||||
data object Server : WhereToRun
|
||||
|
||||
data class Computer(val device: String, val cwd: String, val mode: String, val approvalWaitMinutes: Int?) : WhereToRun
|
||||
}
|
||||
|
||||
/**
|
||||
* The command an Agentic schedule watches before each run, as a save says it: the [command]
|
||||
* (empty: watch nothing) and how many seconds it may take (null: the server's own).
|
||||
*/
|
||||
data class WatchCommand(val command: String, val timeoutS: Int?)
|
||||
@@ -55,19 +55,25 @@ class StreamClient(private val api: ApiClient) {
|
||||
/**
|
||||
* Follow an events route that ends itself now and then (`close` after a while, as the
|
||||
* activity panel's does): opened again at once after a `close`, and after a pause that
|
||||
* grows to 30 seconds when the connection drops. It runs until its collector stops; a
|
||||
* refusal (4xx) ends it with the error.
|
||||
* grows to 30 seconds when the connection drops or closes without a frame. It runs until
|
||||
* its collector stops; a refusal (4xx) ends it with the error.
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var said = false
|
||||
var refused: ApiException? = null
|
||||
once(request()).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
if (result.frame.event == "close") closed = true else emit(result.frame)
|
||||
if (result.frame.event == "close") {
|
||||
closed = true
|
||||
} else {
|
||||
said = true
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
}
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
@@ -76,7 +82,10 @@ class StreamClient(private val api: ApiClient) {
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) continue
|
||||
// A route that closes after it has said something is opened again at once. One
|
||||
// that closes having said nothing waits as a dropped one does: a server that only
|
||||
// ever answers `close` must not be asked in a tight loop.
|
||||
if (reopenAtOnce(closed, said)) continue
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
@@ -115,3 +124,6 @@ class StreamClient(private val api: ApiClient) {
|
||||
awaitClose { source.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an events route that ended is opened again without a pause: only one that [closed] itself after it [said] something. */
|
||||
fun reopenAtOnce(closed: Boolean, said: Boolean): Boolean = closed && said
|
||||
@@ -0,0 +1,85 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
|
||||
/**
|
||||
* A chat's subagent tree (harness spec 3.4.0, `subagents.md` §12): the main agent at the root,
|
||||
* every subagent under its parent, open slots, and the subagents that ended. [agents] are in
|
||||
* tree order. Android shows it as a reduced list (§12): name, position, state, the progress
|
||||
* line's text and context use, and opens a subagent's conversation read-only.
|
||||
*/
|
||||
@Serializable
|
||||
data class SubagentTree(
|
||||
val min: Int = 1,
|
||||
val max: Int = 1,
|
||||
val size: Int = 0,
|
||||
@SerialName("open_slots") val openSlots: Int = 0,
|
||||
val agents: List<TreeAgent> = emptyList(),
|
||||
val ended: List<TreeAgent> = emptyList(),
|
||||
)
|
||||
|
||||
/** One agent of the tree. [position], [task] and a progress `what` are a model's words: text only. */
|
||||
@Serializable
|
||||
data class TreeAgent(
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val position: String = "",
|
||||
val parent: String? = null,
|
||||
val state: String = "",
|
||||
val model: String = "",
|
||||
val mode: String = "",
|
||||
val request: List<String> = emptyList(),
|
||||
val manager: Boolean = false,
|
||||
val task: String = "",
|
||||
val context: TreeContext? = null,
|
||||
val progress: Progress? = null,
|
||||
val findings: Int = 0,
|
||||
/** How many of the room's messages are to or from it (a count; a newer server may say more). */
|
||||
val messages: JsonElement? = null,
|
||||
/** When it ended, Unix milliseconds; null while it lives. */
|
||||
val ended: Long? = null,
|
||||
) {
|
||||
val isMain: Boolean get() = parent == null
|
||||
|
||||
/** `floor(used × 100 / window)`, as the server's `team_read` writes it; null without a window. */
|
||||
val contextPercent: Int? get() = context?.takeIf { it.window > 0 }?.let { (it.used.toLong() * 100 / it.window).toInt() }
|
||||
}
|
||||
|
||||
/** `GET /chats/{chat}/tree`: the tree (null: none), the room, and whether it is live (false: kept while the device is away). */
|
||||
@Serializable
|
||||
data class TreeView(val tree: SubagentTree? = null, val room: List<RoomMessage> = emptyList(), val live: Boolean = true)
|
||||
|
||||
/** `GET /chats/{chat}/subagents/{id}/transcript`: its conversation, read-only, live or after it ended. */
|
||||
@Serializable
|
||||
data class SubagentTranscript(val id: String = "", val state: String = "", val turns: List<AgentTurn> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class TreeContext(val used: Int = 0, val window: Int = 0)
|
||||
|
||||
/** One row of the reduced list: an agent and how deep it sits under the main agent. */
|
||||
data class TreeRow(val agent: TreeAgent, val depth: Int, val ended: Boolean)
|
||||
|
||||
object TreeLogic {
|
||||
/** The states a subagent ends in (`subagents.md` §9). */
|
||||
val ENDED = setOf("done", "out_of_context", "stopped")
|
||||
|
||||
/**
|
||||
* The rows to draw: the live agents in tree order, each as deep as its parent chain (the main
|
||||
* agent 0), then the ended ones, flat. A parent the tree does not hold (moved, ended) counts
|
||||
* as the main agent, so no row is lost or drawn deeper than it can be.
|
||||
*/
|
||||
fun rows(tree: SubagentTree): List<TreeRow> {
|
||||
val byName = tree.agents.associateBy { it.name }
|
||||
fun depth(agent: TreeAgent, seen: Set<String> = emptySet()): Int {
|
||||
val parent = agent.parent?.let { byName[it] } ?: return if (agent.parent == null) 0 else 1
|
||||
if (parent.name in seen) return 1
|
||||
return depth(parent, seen + agent.name) + 1
|
||||
}
|
||||
return tree.agents.map { TreeRow(it, depth(it), ended = false) } + tree.ended.map { TreeRow(it, 1, ended = true) }
|
||||
}
|
||||
|
||||
/** Whether there is anything to show beyond the main agent alone. */
|
||||
fun hasSubagents(tree: SubagentTree?): Boolean = tree != null && (tree.agents.any { !it.isMain } || tree.ended.isNotEmpty() || tree.openSlots > 0)
|
||||
}
|
||||
@@ -3,17 +3,36 @@ package eu.llembas.android.assist
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import eu.llembas.android.R
|
||||
|
||||
/** A Quick Settings tile that opens the assistant's sheet: one more way in besides the power button. */
|
||||
/**
|
||||
* A Quick Settings tile that opens the assistant's sheet: one more way in besides the power
|
||||
* button. It is a button, not a switch -- always shown as ready (`STATE_INACTIVE`), never as
|
||||
* "on", and the system's default (`STATE_UNAVAILABLE` on some phones until the first update)
|
||||
* would grey it out. Over the lock screen the sheet opens there and asks to unlock before it
|
||||
* sends anything, as from any other way in.
|
||||
*/
|
||||
class AskTileService : TileService() {
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
qsTile?.apply {
|
||||
state = Tile.STATE_INACTIVE
|
||||
label = getString(R.string.tile_ask)
|
||||
updateTile()
|
||||
}
|
||||
}
|
||||
|
||||
@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))
|
||||
startActivityAndCollapse(
|
||||
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityAndCollapse(intent)
|
||||
|
||||
@@ -2,53 +2,300 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.view.WindowManager
|
||||
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.compose.runtime.mutableStateOf
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
enum class Opening {
|
||||
Sheet,
|
||||
Listen,
|
||||
Continue,
|
||||
;
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* A headset's voice button sends `VOICE_COMMAND` (or, locked, `VOICE_SEARCH_HANDS_FREE`):
|
||||
* the person means to speak, so the sheet opens listening whatever Settings says. Those
|
||||
* two are Android's, and anybody's to send. The app's own ways in -- listening for the
|
||||
* widget's microphone and the wake word, the last chat -- count only on an intent the
|
||||
* app made itself ([own], [OwnIntents]); from anyone else they are just the sheet.
|
||||
*/
|
||||
fun of(action: String?, listenExtra: Boolean, own: Boolean): Opening = when {
|
||||
own && listenExtra -> Listen
|
||||
own && action == AssistActivity.ACTION_CONTINUE -> Continue
|
||||
own && action == AssistActivity.ACTION_LISTEN -> Listen
|
||||
action in PUBLIC_LISTENING -> Listen
|
||||
else -> Sheet
|
||||
}
|
||||
|
||||
fun of(intent: Intent, own: Boolean): Opening = of(intent.action, own && intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false), own)
|
||||
|
||||
private val PUBLIC_LISTENING = setOf(Intent.ACTION_VOICE_COMMAND, "android.speech.action.VOICE_SEARCH_HANDS_FREE")
|
||||
}
|
||||
}
|
||||
|
||||
/** How the sheet starts, given whether the phone is locked. */
|
||||
enum class LockedStart {
|
||||
/** Not locked: do what the way in asked for. */
|
||||
Go,
|
||||
|
||||
/** Locked, and the way in means to speak: stay over the lock screen and listen; what is heard waits for the unlock. */
|
||||
Listen,
|
||||
|
||||
/** Locked, with a question handed over: it is shown and waits for the unlock. */
|
||||
Hold,
|
||||
|
||||
/** Locked, anything else: ask Android to unlock first; the sheet goes if that is turned down. */
|
||||
Unlock,
|
||||
}
|
||||
|
||||
/**
|
||||
* What a sheet opened while the phone is [locked] does. The wake word with the screen off, and a
|
||||
* headset's button, open it listening ([Opening.Listen]) and nobody is there to unlock: asking
|
||||
* Android to unlock first -- and closing when that is cancelled, which is what happens when
|
||||
* nobody answers the lock screen -- showed the sheet for a moment and took it away again. So it
|
||||
* stays and listens, and only *sending* waits for the unlock. Without the microphone's
|
||||
* permission there is nothing to listen with, and its prompt needs the phone unlocked anyway.
|
||||
*/
|
||||
fun lockedStart(locked: Boolean, opening: Opening, question: Boolean, micAllowed: Boolean): LockedStart = when {
|
||||
!locked -> LockedStart.Go
|
||||
question -> LockedStart.Hold
|
||||
opening == Opening.Listen && micAllowed -> LockedStart.Listen
|
||||
else -> LockedStart.Unlock
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* `ACTION_ASSIST` open, and where the voice-interaction session hands over what needs an
|
||||
* activity -- a question asked over the lock screen, or the microphone's permission prompt
|
||||
* ([EXTRA_LISTEN]). The same sheet as the session's, in a see-through window over the app
|
||||
* underneath. Shown over the lock screen, but it asks Android to unlock before it sends
|
||||
* anything -- and shows nothing from the account until then. Opened there to listen (the wake
|
||||
* word, a headset's button) it stays up and listens; the question it heard is shown and waits
|
||||
* for the unlock ([lockedStart]).
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
private lateinit var keyguard: KeyguardManager
|
||||
private var started = false
|
||||
private var byWake = false
|
||||
|
||||
/** The screen went off since the sheet was last seen: on the way back, the lock is looked at again. */
|
||||
private var wentOff = false
|
||||
|
||||
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
|
||||
private val locked = mutableStateOf(false)
|
||||
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) controller.listen()
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone was unlocked by the person themselves (a fingerprint while the sheet is up): the
|
||||
* question that waited is sent. And the screen went off: the microphone and the voice stop
|
||||
* at once, whatever the lock says yet, and nothing of the conversation is left in the
|
||||
* picture the phone keeps of the sheet; a sheet that was over the lock screen goes, so that
|
||||
* it is not what the phone shows when it is next picked up.
|
||||
*/
|
||||
private val screen = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_USER_PRESENT -> unlockedNow()
|
||||
|
||||
Intent.ACTION_SCREEN_OFF -> {
|
||||
val overLock = locked.value
|
||||
wentOff = true
|
||||
if (keyguard.isKeyguardLocked) controller.lockedNow() else controller.screenOff()
|
||||
locked.value = true
|
||||
if (overLock) finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
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()
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
screen,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// A question waits for the unlock: Android is asked for it at once (a face or a
|
||||
// fingerprint is then enough), and the sheet stays if nobody answers.
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.held }.distinctUntilChanged().collect { held ->
|
||||
if (held && locked.value) askToUnlock()
|
||||
}
|
||||
}
|
||||
// The lock screen turns the display off after a few seconds: not in the middle of a
|
||||
// question, and not in the middle of an answer read aloud (the screen going off stops it).
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.listening || it.busy || it.speaking }.distinctUntilChanged().collect { on ->
|
||||
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
}
|
||||
}
|
||||
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
|
||||
// so nothing else has woken the phone).
|
||||
woken(intent)
|
||||
// Once: made again by Android (after the app was put away and brought back), the sheet
|
||||
// must not ask the same question a second time. What waited for the unlock is kept.
|
||||
if (savedInstanceState == null) {
|
||||
take(intent)
|
||||
} else {
|
||||
savedInstanceState.getString(STATE_WAITING)?.let { controller.hold(Held(it, null, savedInstanceState.getBoolean(STATE_SPOKEN))) }
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = locked.value,
|
||||
onUnlockAndAsk = { text ->
|
||||
// Typed over the lock screen: held (in the place of a question that
|
||||
// waited already), so that whichever way the unlock is heard of first,
|
||||
// one question is asked, once.
|
||||
val waited = controller.state.value.held
|
||||
if (text.isNotBlank()) controller.ask(text)
|
||||
// A first held question asks Android to unlock by itself (onCreate).
|
||||
if (waited || text.isBlank()) askToUnlock { if (text.isBlank()) controller.opened() }
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
finish()
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
onDismiss = { finish() },
|
||||
onUnlock = { askToUnlock() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Opened again while it is up -- the headset's button pressed twice, the tile again, the wake word. */
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
woken(intent)
|
||||
// The same sheet answers again: it is up, and whoever asked for it is told so.
|
||||
if (started) AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
take(intent)
|
||||
}
|
||||
|
||||
/**
|
||||
* Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch, so
|
||||
* nothing else has woken the phone), and the sheet is remembered as the wake word's, so that
|
||||
* the assistant's own sheet can take its place if that one comes after all.
|
||||
*/
|
||||
private fun woken(intent: Intent?) {
|
||||
byWake = OwnIntents.isOwn(this, intent) && intent?.getBooleanExtra(EXTRA_WAKE, false) == true
|
||||
if (byWake) setTurnScreenOn(true)
|
||||
}
|
||||
|
||||
/**
|
||||
* On screen: only now is the sheet "up" -- for the wake word's pause (which must end when the
|
||||
* sheet is left with Home, not only when it is destroyed) and for whoever waits to hear that
|
||||
* it opened.
|
||||
*/
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
started = true
|
||||
// The phone may have locked, or been unlocked, while the sheet was out of sight.
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
// Found locked: the controller is told, unless the sheet was opened over the lock
|
||||
// screen in the first place (and is listening there).
|
||||
if (!locked.value || wentOff) controller.lockedNow()
|
||||
locked.value = true
|
||||
} else {
|
||||
unlockedNow()
|
||||
}
|
||||
wentOff = false
|
||||
open = WeakReference(this)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// "Heard you. Tap to ask." has been answered, however the sheet was opened.
|
||||
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
started = false
|
||||
if (open?.get() === this) open = null
|
||||
AssistPresence.hidden()
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
/**
|
||||
* What the way in asked for: a question handed over by the session ([AssistHandOff]),
|
||||
* listening (the headset's voice button, the widget's microphone, the Speak shortcut, the
|
||||
* wake word), the last assistant chat (the widget, the shortcut), or just the sheet. Over
|
||||
* the lock screen: [lockedStart]. Only an intent the app made itself ([OwnIntents]) can
|
||||
* hand over a question or ask for more than Android's own actions do.
|
||||
*/
|
||||
private fun take(intent: Intent) {
|
||||
val own = OwnIntents.isOwn(this, intent)
|
||||
val opening = Opening.of(intent, own)
|
||||
val handed = if (own) AssistHandOff.take(intent.getStringExtra(EXTRA_HANDOFF)) else null
|
||||
val go = {
|
||||
when {
|
||||
handed != null -> controller.hold(handed)
|
||||
opening == Opening.Continue -> controller.continueWhenReady()
|
||||
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
opening == Opening.Listen -> controller.opened(listen = true)
|
||||
else -> controller.opened()
|
||||
}
|
||||
}
|
||||
val isLocked = keyguard.isKeyguardLocked
|
||||
if (isLocked) locked.value = true
|
||||
when (lockedStart(isLocked, opening, handed != null, controller.micAllowed())) {
|
||||
// Not locked, a handed-over question is asked at once ([AssistController.hold]).
|
||||
LockedStart.Go -> go()
|
||||
|
||||
LockedStart.Listen -> controller.opened(listen = true)
|
||||
|
||||
// Shown, and Android asked to unlock (the collector in onCreate): it stays if nobody does.
|
||||
LockedStart.Hold -> handed?.let { controller.hold(it) }
|
||||
|
||||
LockedStart.Unlock -> keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
if (waiting.isNotBlank()) controller.ask(waiting)
|
||||
unlockedNow()
|
||||
go()
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
@@ -56,50 +303,93 @@ class AssistActivity : ComponentActivity() {
|
||||
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) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask Android to unlock. When it does, the question that waited is sent and [then] runs.
|
||||
* When it does not -- nobody there, or Back on the lock screen -- nothing happens: the sheet
|
||||
* stays as it is, with the way to try again.
|
||||
*/
|
||||
private fun askToUnlock(then: () -> Unit = {}) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
unlockedNow()
|
||||
then()
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked now, however that was heard of -- Android's answer to the asking,
|
||||
* the person's own unlock, the sheet coming back: once, and only if the lock itself says so.
|
||||
*/
|
||||
private fun unlockedNow() {
|
||||
if (!locked.value || keyguard.isKeyguardLocked) return
|
||||
locked.value = false
|
||||
controller.unlocked()
|
||||
}
|
||||
|
||||
/** A question that waits for the unlock outlives the sheet being made again; a recording does not. */
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
val waiting = controller.state.value.waiting
|
||||
if (waiting.isNotBlank()) {
|
||||
outState.putString(STATE_WAITING, waiting)
|
||||
outState.putBoolean(STATE_SPOKEN, controller.heldSpoken)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(screen) }
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
/** The ticket of a question handed over by the session ([AssistHandOff]); never the question. */
|
||||
const val EXTRA_HANDOFF = "eu.llembas.android.HANDOFF"
|
||||
|
||||
private const val STATE_WAITING = "waiting"
|
||||
private const val STATE_SPOKEN = "spoken"
|
||||
|
||||
/** Handed over by the session: ask for the microphone, then listen. */
|
||||
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
|
||||
|
||||
/** Open listening: the widget's microphone and the Speak shortcut. */
|
||||
const val ACTION_LISTEN = "eu.llembas.android.action.LISTEN"
|
||||
|
||||
/** Open at the last chat the assistant made: the widget and the shortcut. */
|
||||
const val ACTION_CONTINUE = "eu.llembas.android.action.CONTINUE"
|
||||
|
||||
/** The sheet, listening. */
|
||||
fun listening(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN))
|
||||
|
||||
/** The sheet that is on screen now, if this activity is it. */
|
||||
@Volatile
|
||||
private var open: WeakReference<AssistActivity>? = null
|
||||
|
||||
/** The assistant's own sheet came up: a sheet the wake word had opened in its place goes. */
|
||||
fun closeWoken() {
|
||||
open?.get()?.takeIf { it.byWake }?.finish()
|
||||
}
|
||||
|
||||
/** On the intent the wake word opens the sheet with: turn the screen on. */
|
||||
const val EXTRA_WAKE = "eu.llembas.android.WAKE"
|
||||
|
||||
/** The sheet, listening, as the wake word opens it. */
|
||||
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** The sheet, at the last assistant chat. */
|
||||
fun continuing(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE))
|
||||
|
||||
/** The sheet, taking the question left under [ticket] -- or asking for the microphone and listening. */
|
||||
fun handedOver(context: Context, ticket: String?, listen: Boolean): Intent = OwnIntents.own(
|
||||
context,
|
||||
Intent(context, AssistActivity::class.java).putExtra(EXTRA_HANDOFF, ticket).putExtra(EXTRA_LISTEN, listen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,128 +1,797 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.notify.NotificationReader
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.transformWhile
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/** One question asked in the sheet and its answer: written now ([reply]), or read back ([earlier]). */
|
||||
data class AssistTurn(val question: String, val reply: LiveReply? = null, val earlier: List<Step> = emptyList()) {
|
||||
val steps: List<Step> get() = reply?.finished?.steps ?: reply?.shown ?: earlier
|
||||
val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed
|
||||
}
|
||||
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: its [text], or -- heard where the instance
|
||||
* writes speech down -- its recording ([wav]), which stays on the phone until then.
|
||||
*/
|
||||
class Held(val text: String, val wav: ByteArray?, val spoken: Boolean)
|
||||
|
||||
/** Whether the instance answers: being asked, yes, or no (and why). */
|
||||
enum class Connection { Checking, Online, Offline }
|
||||
|
||||
/** The last chat the assistant made, offered to be continued. */
|
||||
data class LastAssist(val chatId: String, val title: String, val at: Long)
|
||||
|
||||
data class AssistUiState(
|
||||
val signedIn: Boolean = true,
|
||||
val instanceName: String = "",
|
||||
val connection: Connection = Connection.Checking,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val modelId: String? = null,
|
||||
val listening: Boolean = false,
|
||||
/** The words heard so far, while listening and while the last of them is written down. */
|
||||
val heard: String = "",
|
||||
/** How loud the microphone hears it, 0..1. */
|
||||
val level: Float = 0f,
|
||||
val busy: Boolean = false,
|
||||
val asked: String? = null,
|
||||
val turns: List<AssistTurn> = emptyList(),
|
||||
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,
|
||||
)
|
||||
val screenText: Boolean = false,
|
||||
val screenshot: Bitmap? = null,
|
||||
val last: LastAssist? = null,
|
||||
/** Whether a spoken question is answered aloud too. */
|
||||
val voiceReply: Boolean = true,
|
||||
/** Whether the instance can read aloud (its text-to-speech, for this account). */
|
||||
val canSpeak: Boolean = false,
|
||||
val speaking: Boolean = false,
|
||||
/** Whether anything can turn speech into words: the instance's speech-to-text, or the phone's. */
|
||||
val canListen: Boolean = true,
|
||||
/**
|
||||
* A spoken conversation: after each spoken answer is read aloud, the sheet listens again --
|
||||
* until the person says stop, taps End, types, or says nothing.
|
||||
*/
|
||||
val conversation: Boolean = false,
|
||||
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
|
||||
val canReadNotifications: Boolean = false,
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: typed over the lock screen, or heard
|
||||
* there by the phone's own recogniser -- the person's own words and nothing from the
|
||||
* account. Asked once the phone is unlocked.
|
||||
*/
|
||||
val waiting: String = "",
|
||||
/**
|
||||
* A question heard over the lock screen that waits as a recording, on the phone: the
|
||||
* instance writes speech down, and nothing goes to the instance while the phone is locked.
|
||||
*/
|
||||
val waitingRecording: Boolean = false,
|
||||
) {
|
||||
/** Whether a question waits for the unlock, as words or as a recording. */
|
||||
val held: Boolean get() = waiting.isNotBlank() || waitingRecording
|
||||
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.named(modelId)
|
||||
val empty: Boolean get() = turns.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* What the sheet can do. Every method does nothing by default, so the screenshot tests can draw
|
||||
* the sheet with no controller behind it.
|
||||
*/
|
||||
class AssistController(private val context: Context, private val scope: CoroutineScope) {
|
||||
interface AssistActions {
|
||||
fun listen() {}
|
||||
fun heard() {}
|
||||
fun type() {}
|
||||
fun ask(question: String) {}
|
||||
fun includeScreen(on: Boolean) {}
|
||||
fun quick(prompt: String) {}
|
||||
fun continueLast() {}
|
||||
fun newChat() {}
|
||||
fun pickModel(id: String) {}
|
||||
fun voiceReply(on: Boolean) {}
|
||||
fun readAloud() {}
|
||||
fun stopReading() {}
|
||||
fun endConversation() {}
|
||||
fun summariseNotifications() {}
|
||||
fun answerCard(card: Card, answer: CardAnswer) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant: take a question -- spoken or typed -- start a chat with it on the instance (or
|
||||
* carry on the one this sheet is in), 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.
|
||||
*
|
||||
* A chat it makes is an ordinary one: in the list on the phone and on the web afterwards, and
|
||||
* "Open in app" continues it there. Settings' "assistant chats are temporary" makes them
|
||||
* temporary instead.
|
||||
*
|
||||
* Speech in is Settings › Voice input: the instance's speech-to-text (the words are written down
|
||||
* a moment behind, from the recording so far, and a pause in speech sends it), or the phone's
|
||||
* own recogniser (the words as they are said). Speech out is the instance's text-to-speech.
|
||||
*/
|
||||
class AssistController(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* Whether the phone is locked, asked each time it matters. While it is, nothing goes to the
|
||||
* instance from here: no question, no recording to write down, not even "which models".
|
||||
*/
|
||||
private val locked: () -> Boolean = { context.getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true },
|
||||
) : AssistActions {
|
||||
private val _state = MutableStateFlow(AssistUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private val recorder = Recorder(scope)
|
||||
private val phone = PhoneRecognizer(context)
|
||||
private val speaker = Speaker(context)
|
||||
private val route = HeadsetRoute(context)
|
||||
private var following: Job? = null
|
||||
private var hearing: Job? = null
|
||||
|
||||
/** The ear for the end of speech, while the instance's speech-to-text listens. */
|
||||
private var ear: EndOfSpeech? = null
|
||||
private var usingPhone = false
|
||||
private var screenText: String? = null
|
||||
private var screenshot: Bitmap? = null
|
||||
private var stt: Boolean? = null
|
||||
|
||||
/** The account's own default model, as the instance said it: what "Instance default" means. */
|
||||
private var accountDefault: String? = null
|
||||
|
||||
/**
|
||||
* The model a new chat starts on (Settings › Assistant › Assistant model). The sheet's
|
||||
* [AssistUiState.modelId] is the model of the chat it is in, which for a continued chat is
|
||||
* that chat's own; a new chat goes back to this one.
|
||||
*/
|
||||
private var newChatModel: String? = null
|
||||
|
||||
/** The question that waits for the unlock ([hold]). */
|
||||
private var held: Held? = null
|
||||
|
||||
/** Whether the question that waits was spoken. */
|
||||
val heldSpoken: Boolean get() = held?.spoken == true
|
||||
|
||||
/** When the phone's recogniser last gave a sign of somebody speaking (elapsed ms). */
|
||||
private var phoneActiveAt = 0L
|
||||
|
||||
/** What the phone itself knows: Settings, the instance's name. */
|
||||
private val local: Job
|
||||
|
||||
/** What the instance says -- its models, what it offers: asked only once the phone is unlocked. */
|
||||
private var remote: Job? = null
|
||||
|
||||
init {
|
||||
scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } }
|
||||
local = scope.launch {
|
||||
loadLocal()
|
||||
if (!locked()) askInstance()
|
||||
}
|
||||
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
|
||||
// Settings changed the assistant's model while this sheet lives: the next new chat has it.
|
||||
scope.launch {
|
||||
context.lembas.instances.prefs.map { it.assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
|
||||
ready()
|
||||
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
|
||||
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel) else it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) }
|
||||
/** Everything known: Settings, and -- unless the phone is locked -- what the instance says. */
|
||||
private suspend fun ready() {
|
||||
local.join()
|
||||
if (!locked()) askInstance().join()
|
||||
}
|
||||
|
||||
fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
|
||||
/** Ask the instance what it has, once. */
|
||||
private fun askInstance(): Job = remote ?: scope.launch { loadRemote() }.also { remote = it }
|
||||
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
fun listen() {
|
||||
speaker.stop()
|
||||
recorder.start()
|
||||
_state.update { it.copy(listening = true, error = null) }
|
||||
/** The choices kept in Settings, and which instance: nothing here leaves the phone. */
|
||||
private suspend fun loadLocal() {
|
||||
val store = context.lembas.instances
|
||||
val instance = store.current()
|
||||
val prefs = store.prefs.first()
|
||||
_state.update {
|
||||
it.copy(
|
||||
signedIn = instance != null,
|
||||
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
|
||||
voiceReply = prefs.readAloudSpoken,
|
||||
canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context),
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
// Until the instance has said what it has, the choice in Settings stands as it is: a
|
||||
// question asked while the list could not be read still goes to the chosen model.
|
||||
newChatModel = prefs.assistantModel.ifBlank { null }
|
||||
}
|
||||
|
||||
/** Stop listening, write down what was said, and ask it. */
|
||||
fun heard() {
|
||||
/** The instance's models and what it offers this account. */
|
||||
private suspend fun loadRemote() {
|
||||
val store = context.lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
val api = store.current()?.let { store.clientFor(it) } ?: return
|
||||
try {
|
||||
val me = api.me()
|
||||
val models = api.models()
|
||||
stt = me.speechToText
|
||||
accountDefault = me.defaultModel
|
||||
val chosen = assistantModelFor(prefs.assistantModel, me.defaultModel, models)
|
||||
newChatModel = chosen
|
||||
_state.update {
|
||||
it.copy(
|
||||
connection = Connection.Online,
|
||||
models = models,
|
||||
modelId = it.modelId ?: chosen,
|
||||
canSpeak = me.hasTextToSpeech,
|
||||
canListen = me.hasSpeechToText || PhoneRecognizer.available(context),
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(connection = Connection.Offline, error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet came up. It starts listening at once -- the microphone first, as an assistant
|
||||
* opens -- unless Settings says not to or the microphone is not allowed yet (that needs an
|
||||
* activity to ask). [listen] is a way in that means to speak -- the wake word, a headset's
|
||||
* voice button -- and listens regardless.
|
||||
*
|
||||
* Over the lock screen only such a way in listens, and what it hears is held for the unlock
|
||||
* ([hold]), never asked from there; the microphone opens without waiting for the instance.
|
||||
*/
|
||||
fun opened(listen: Boolean = false) {
|
||||
scope.launch {
|
||||
if (locked()) {
|
||||
local.join()
|
||||
val s = _state.value
|
||||
if (listen && s.signedIn && !s.listening && !s.held && micAllowed()) listen()
|
||||
return@launch
|
||||
}
|
||||
ready()
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val s = _state.value
|
||||
if (s.signedIn && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
|
||||
if (listen || s.empty) listen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep [question] until the phone is unlocked ([unlocked]); it takes the place of one that
|
||||
* waited already. With the phone not locked there is nothing to wait for.
|
||||
*/
|
||||
fun hold(question: Held) {
|
||||
if (question.text.isBlank() && question.wav == null) return
|
||||
held = question
|
||||
_state.update { it.copy(waiting = question.text, waitingRecording = question.wav != null, conversation = false) }
|
||||
if (!locked()) unlocked()
|
||||
}
|
||||
|
||||
/** The question that waits, taken away from here: to be handed to another sheet. */
|
||||
fun takeHeld(): Held? {
|
||||
val waited = held
|
||||
held = null
|
||||
_state.update { it.copy(waiting = "", waitingRecording = false) }
|
||||
return waited
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked: the instance is asked what it has, and the question that waited is
|
||||
* asked now -- a recording is written down first. Does nothing while the phone is still locked.
|
||||
*/
|
||||
fun unlocked() {
|
||||
if (locked()) return
|
||||
askInstance()
|
||||
val waited = takeHeld() ?: return
|
||||
val wav = waited.wav
|
||||
if (wav == null) {
|
||||
ask(waited.text, spoken = waited.spoken)
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
_state.update { it.copy(listening = false) }
|
||||
if (wav.isEmpty()) return@launch
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean = false) {
|
||||
/**
|
||||
* The screen went off: the microphone and the voice stop, whatever the lock says -- nobody
|
||||
* is looking, and a phone that is about to lock must not go on listening or talking.
|
||||
*/
|
||||
fun screenOff() {
|
||||
speaker.stop()
|
||||
if (_state.value.listening) type()
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone locked while the sheet was up: as [screenOff], and the answer being written is
|
||||
* no longer followed. Whatever is asked from now on waits for the unlock ([ask]).
|
||||
*/
|
||||
fun lockedNow() {
|
||||
screenOff()
|
||||
following?.cancel()
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
|
||||
/** Open at the last assistant chat, once it is known which that is. */
|
||||
fun continueWhenReady() {
|
||||
scope.launch {
|
||||
ready()
|
||||
if (_state.value.last != null) continueLast() else opened()
|
||||
}
|
||||
}
|
||||
|
||||
fun micAllowed(): Boolean = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun offerScreen(text: String?, image: Bitmap?) {
|
||||
if (!text.isNullOrBlank()) screenText = text.take(MAX_SCREEN_CHARS)
|
||||
_state.update { it.copy(screenText = screenText != null, screenshot = image ?: it.screenshot) }
|
||||
}
|
||||
|
||||
override fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
|
||||
|
||||
// --- Speech in ---------------------------------------------------------------------------
|
||||
|
||||
/** Which recogniser: the one Settings names, else whichever this phone and instance have. */
|
||||
private suspend fun phoneEngine(): Boolean {
|
||||
val wanted = context.lembas.instances.prefs.first().voiceInput
|
||||
return usePhoneRecognizer(wanted, PhoneRecognizer.available(context), stt)
|
||||
}
|
||||
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
override fun listen() {
|
||||
if (_state.value.listening || !micAllowed()) return
|
||||
speaker.stop()
|
||||
hearing?.cancel()
|
||||
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
|
||||
hearing = scope.launch {
|
||||
usingPhone = phoneEngine()
|
||||
// A headset's microphone when one is there: the conversation can go on in the ear.
|
||||
val headset = route.microphone()
|
||||
if (usingPhone) {
|
||||
phone.start(
|
||||
onPartial = { words ->
|
||||
phoneActiveAt = SystemClock.elapsedRealtime()
|
||||
_state.update { it.copy(heard = words) }
|
||||
},
|
||||
onActive = { phoneActiveAt = SystemClock.elapsedRealtime() },
|
||||
onLevel = { l -> _state.update { it.copy(level = l) } },
|
||||
onResult = { words ->
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
if (words.isNotBlank()) askOrStop(words) else endConversation()
|
||||
},
|
||||
onFail = { code ->
|
||||
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
|
||||
_state.update {
|
||||
it.copy(
|
||||
listening = false,
|
||||
level = 0f,
|
||||
conversation = false,
|
||||
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
watchPhone()
|
||||
} else {
|
||||
recorder.preferred = headset
|
||||
ear = EndOfSpeech(TICK_MS)
|
||||
recorder.start()
|
||||
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
|
||||
launch { writeDownAsSaid() }
|
||||
// Nothing said is nothing sent: a speech-to-text model asked to write down
|
||||
// silence tends to invent a sentence.
|
||||
if (untilQuiet()) heard() else type()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance's speech-to-text takes a whole recording, so words "as they are said" are the
|
||||
* recording so far, written down again every moment -- one request at a time, only when half
|
||||
* a second more has been said, not past the first minute -- and not before the microphone
|
||||
* has heard anything above the room: silence written down is an invented sentence. Never
|
||||
* while the phone is locked: the recording stays on the phone until it is unlocked.
|
||||
*/
|
||||
private suspend fun writeDownAsSaid() {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
var sent = 0f
|
||||
while (scope.isActive) {
|
||||
delay(PARTIAL_EVERY_MS)
|
||||
val seconds = recorder.seconds
|
||||
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue
|
||||
sent = seconds
|
||||
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
|
||||
if (!words.isNullOrBlank() && _state.value.listening) _state.update { it.copy(heard = words) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false).
|
||||
* [EndOfSpeech] decides, from the microphone's level against the room's own and the words
|
||||
* written down so far.
|
||||
*/
|
||||
private suspend fun untilQuiet(): Boolean {
|
||||
val ear = ear ?: return false
|
||||
while (true) {
|
||||
delay(TICK_MS)
|
||||
// Over the lock screen no words are written down: the level alone decides.
|
||||
when (ear.tick(recorder.level.value, _state.value.heard)) {
|
||||
EndOfSpeech.Verdict.Said -> return true
|
||||
EndOfSpeech.Verdict.Nothing -> return false
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's recogniser finds the end of speech itself -- and is watched all the same
|
||||
* ([phoneWatch]): one that never calls back would leave the sheet listening for good.
|
||||
*/
|
||||
private suspend fun watchPhone() {
|
||||
var waited = 0L
|
||||
var words = ""
|
||||
var sameFor = 0L
|
||||
var asked = false
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
phoneActiveAt = 0L
|
||||
while (_state.value.listening) {
|
||||
delay(TICK_MS)
|
||||
waited += TICK_MS
|
||||
val heard = _state.value.heard
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameFor = 0
|
||||
} else {
|
||||
sameFor += TICK_MS
|
||||
}
|
||||
// Since it last gave a sign of somebody speaking; never, and it is as long as it has listened.
|
||||
val silentFor = if (phoneActiveAt >= began) SystemClock.elapsedRealtime() - phoneActiveAt else waited
|
||||
when (phoneWatch(waited, heard.isNotBlank(), sameFor, silentFor)) {
|
||||
PhoneWatch.Wait -> Unit
|
||||
|
||||
PhoneWatch.Finish -> if (!asked) {
|
||||
asked = true
|
||||
phone.finish()
|
||||
}
|
||||
|
||||
PhoneWatch.Take -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
askOrStop(heard)
|
||||
return
|
||||
}
|
||||
|
||||
PhoneWatch.GiveUp -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "", conversation = false) }
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop listening, write down what was said, and ask it. */
|
||||
override fun heard() {
|
||||
if (!_state.value.listening) return
|
||||
if (usingPhone) {
|
||||
phone.finish()
|
||||
return
|
||||
}
|
||||
hearing?.cancel()
|
||||
hearing = null
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f) }
|
||||
if (wav.size <= 44 + Recorder.RATE / 2) {
|
||||
_state.update { it.copy(heard = "") }
|
||||
return@launch
|
||||
}
|
||||
// Over the lock screen nothing goes to the instance, a recording to write down
|
||||
// included: it waits on the phone, and is written down and asked on the unlock.
|
||||
if (locked()) {
|
||||
_state.update { it.copy(heard = "") }
|
||||
hold(Held("", wav, spoken = true))
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false, heard = "") }
|
||||
if (text.isNotBlank()) askOrStop(text) else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop listening and keep nothing: the person would rather type -- or said nothing at all.
|
||||
* Either ends a spoken conversation.
|
||||
*/
|
||||
override fun type() {
|
||||
hearing?.cancel()
|
||||
hearing = null
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f, conversation = false) }
|
||||
}
|
||||
|
||||
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
|
||||
private fun askOrStop(words: String) {
|
||||
if (locked()) return hold(Held(words, null, spoken = true))
|
||||
val phrases = context.getString(R.string.assist_stop_words).split("|")
|
||||
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
|
||||
}
|
||||
|
||||
override fun endConversation() {
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
// --- Asking ------------------------------------------------------------------------------
|
||||
|
||||
override fun ask(question: String) = ask(question, spoken = false)
|
||||
|
||||
override fun quick(prompt: String) {
|
||||
_state.update { it.copy(includeScreen = true) }
|
||||
ask(prompt, spoken = false)
|
||||
}
|
||||
|
||||
/** The sheet's "Summarise my notifications": the notifications up now go with the question. */
|
||||
override fun summariseNotifications() = ask(context.getString(R.string.assist_notifications_prompt), spoken = false, notifications = true)
|
||||
|
||||
/**
|
||||
* Ask [question]. With the phone locked it is not asked but held for the unlock, whoever
|
||||
* called: this is the one door to the instance, and it is shut while the phone is locked.
|
||||
*/
|
||||
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
if (locked()) return hold(Held(question, null, spoken))
|
||||
if (_state.value.listening) type()
|
||||
following?.cancel()
|
||||
following = scope.launch {
|
||||
_state.update { it.copy(busy = true, asked = question, reply = null, error = null) }
|
||||
val turn = AssistTurn(question)
|
||||
_state.update { it.copy(busy = true, turns = it.turns + turn, error = null) }
|
||||
// A spoken question, answered aloud, opens a conversation (Settings › Assistant).
|
||||
val talking = spoken && context.lembas.instances.prefs.first().assistantConversation &&
|
||||
_state.value.voiceReply && _state.value.canSpeak
|
||||
_state.update { it.copy(conversation = talking) }
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: error("Not signed in.")
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val withScreen = _state.value.includeScreen
|
||||
val store = context.lembas.instances
|
||||
val api = store.client() ?: throw ApiException(401, "Not signed in.")
|
||||
val prefs = store.prefs.first()
|
||||
// A question typed the moment the sheet opened: the model is known first.
|
||||
ready()
|
||||
val now = _state.value
|
||||
val withScreen = now.includeScreen
|
||||
val attachments = buildList {
|
||||
if (withScreen) {
|
||||
screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot)).id) }
|
||||
if (withScreen) now.screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot), now.chatId).id) }
|
||||
}
|
||||
// The notifications, when asked for by the chip or by name ("my notifications") --
|
||||
// read now, only while unlocked (NotificationAccess.read), and for this question only.
|
||||
val phrases = context.getString(R.string.assist_notifications_phrases).split("|")
|
||||
val notices = if (now.canReadNotifications && (notifications || NotificationReader.asksAbout(question, phrases))) {
|
||||
NotificationReader.asText(NotificationAccess.read(context)).ifBlank { NO_NOTIFICATIONS }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val text = buildString {
|
||||
append(question)
|
||||
if (withScreen && screenText != null) append("\n\n---\nOn my screen:\n\n$screenText")
|
||||
if (notices != null) append("\n\n---\nMy notifications:\n\n$notices")
|
||||
}
|
||||
// The screen goes with one question, not every one after it.
|
||||
_state.update { it.copy(includeScreen = false) }
|
||||
val chatId = now.chatId
|
||||
val replyId: String
|
||||
val inChat: String
|
||||
if (chatId != null) {
|
||||
val sent = api.sendMessage(chatId, text, attachments)
|
||||
inChat = chatId
|
||||
replyId = sent.reply?.id ?: return@launch
|
||||
} else {
|
||||
val made = api.createChat(text, attachments, model = now.modelId ?: newChatModel, temporary = prefs.assistantTemporary)
|
||||
inChat = made.chat.id
|
||||
replyId = made.reply?.id ?: return@launch
|
||||
_state.update { it.copy(chatId = inChat) }
|
||||
if (!prefs.assistantTemporary) {
|
||||
store.savePrefs {
|
||||
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
}
|
||||
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 ->
|
||||
var live = LiveReply(replyId)
|
||||
// To `done`, which is the end of the reply: the stream may stay open after it for
|
||||
// the chat's name, and a spoken answer must not wait for that.
|
||||
StreamClient(api).follow(inChat, replyId).transformWhile { frame ->
|
||||
emit(frame)
|
||||
frame.event != "done"
|
||||
}.collect { frame ->
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { it.copy(reply = live, busy = live.finished == null) }
|
||||
_state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.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)))
|
||||
// A new chat is named by a model after `done`. The name the sheet offers the chat
|
||||
// under next time is fetched in the background, for a bounded while -- never by
|
||||
// holding the reply's stream open, and never before the answer is spoken.
|
||||
if (live.titlePending && !prefs.assistantTemporary) nameLater(api, inChat, live.title.orEmpty())
|
||||
val heardAll = if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null && live.cards.isEmpty()) {
|
||||
speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
} else {
|
||||
false
|
||||
}
|
||||
// The answer was heard to the end: listen for the next thing said. Stopped, a
|
||||
// card waiting, or nothing to read: the conversation ends there.
|
||||
if (_state.value.conversation && heardAll && micAllowed() && !locked()) listen() else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
_state.update { it.copy(error = context.explain(e), conversation = false) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat's name once a model has given it: asked for a few times over [TITLE_WAIT_MS], then
|
||||
* left -- the name made from the prompt stands, and the app's list has the real one anyway.
|
||||
*/
|
||||
private fun nameLater(api: ApiClient, chatId: String, provisional: String) {
|
||||
scope.launch {
|
||||
withTimeoutOrNull(TITLE_WAIT_MS) {
|
||||
while (true) {
|
||||
delay(TITLE_ASK_MS)
|
||||
val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty()
|
||||
if (title.isNotBlank() && title != provisional) {
|
||||
context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it }
|
||||
_state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) }
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Carry on the last chat the assistant made: its last exchange shown, the next question sent to it. */
|
||||
override fun continueLast() {
|
||||
val last = _state.value.last ?: return
|
||||
scope.launch {
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return@launch
|
||||
val detail = api.chat(last.chatId)
|
||||
val question = detail.messages.lastOrNull { it.isUser }
|
||||
val answer = detail.messages.lastOrNull { !it.isUser }
|
||||
val turns = if (question != null) listOf(AssistTurn(question.text.orEmpty(), earlier = answer?.steps.orEmpty())) else emptyList()
|
||||
_state.update { it.copy(chatId = last.chatId, turns = turns, modelId = detail.chat.model.ifBlank { null } ?: it.modelId, last = null) }
|
||||
} catch (e: Exception) {
|
||||
// A chat deleted since is simply not offered again.
|
||||
if (e is ApiException && e.status == 404) {
|
||||
context.lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
_state.update { it.copy(last = null) }
|
||||
} else {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
}
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A phone action's card, answered in the sheet: what the phone did (spec 3.6.0). */
|
||||
override fun answerCard(card: Card, answer: CardAnswer) {
|
||||
val chat = _state.value.chatId ?: return
|
||||
scope.launch {
|
||||
try {
|
||||
context.lembas.instances.client()?.answer(chat, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins: a 409 is somebody answering elsewhere already.
|
||||
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
// And on the assistant's own model again, not the one of the chat that was continued.
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false, modelId = newChatModel ?: it.modelId) }
|
||||
}
|
||||
|
||||
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
|
||||
override fun pickModel(id: String) {
|
||||
newChatModel = id
|
||||
_state.update { it.copy(modelId = id) }
|
||||
scope.launch {
|
||||
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
|
||||
val chat = _state.value.chatId ?: return@launch
|
||||
runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
|
||||
.onFailure { e -> _state.update { it.copy(error = context.explain(e)) } }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Speech out --------------------------------------------------------------------------
|
||||
|
||||
override fun voiceReply(on: Boolean) {
|
||||
if (!on) speaker.stop()
|
||||
_state.update { it.copy(voiceReply = on) }
|
||||
scope.launch { context.lembas.instances.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
|
||||
override fun readAloud() {
|
||||
val steps = _state.value.turns.lastOrNull()?.steps ?: return
|
||||
scope.launch { speak(spokenWords(steps)) }
|
||||
}
|
||||
|
||||
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
|
||||
override fun stopReading() = speaker.stop()
|
||||
|
||||
/** Read [words] aloud; true when they were heard to the end. */
|
||||
private suspend fun speak(words: String): Boolean {
|
||||
// Never aloud over the lock screen: an answer is the account's.
|
||||
if (words.isBlank() || locked()) return false
|
||||
return try {
|
||||
val api = context.lembas.instances.client() ?: return false
|
||||
speaker.playToEnd(api.speech(words))
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
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)
|
||||
@@ -131,8 +800,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
fun close() {
|
||||
following?.cancel()
|
||||
hearing?.cancel()
|
||||
speaker.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
phone.stop()
|
||||
route.release()
|
||||
// Not in a coroutine: the scope may be cancelled already, and the microphone must be let go.
|
||||
recorder.stopNow()
|
||||
held = null
|
||||
}
|
||||
|
||||
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
|
||||
@@ -144,6 +818,30 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
private const val NO_NOTIFICATIONS = "(none)"
|
||||
|
||||
/** How long, and how often, a new chat's name is asked for after its first reply. */
|
||||
private const val TITLE_WAIT_MS = 20_000L
|
||||
private const val TITLE_ASK_MS = 4_000L
|
||||
|
||||
// Listening: how often the end of speech is looked for (EndOfSpeech has the rules and
|
||||
// their numbers), and how often the recording so far is written down.
|
||||
private const val TICK_MS = EndOfSpeech.TICK_MS
|
||||
private const val PARTIAL_EVERY_MS = 1_200L
|
||||
|
||||
/**
|
||||
* The model a new assistant chat starts on: the one [chosen] in Settings while the
|
||||
* instance still has it; else ("Instance default", or a model that is gone) the
|
||||
* account's default, the instance's, or its first.
|
||||
*/
|
||||
fun assistantModelFor(chosen: String, accountDefault: String?, models: List<ModelInfo>): String? {
|
||||
// By ref, or -- a choice saved before refs, the account's default -- by id: either
|
||||
// way what comes back is the row's own unambiguous name.
|
||||
return (models.named(chosen) ?: models.named(accountDefault) ?: models.firstOrNull { it.default } ?: models.firstOrNull())?.key
|
||||
}
|
||||
|
||||
/** A reply's words, for a voice: its text steps, without the markup. */
|
||||
fun spokenWords(steps: List<Step>): String = plain(steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() })
|
||||
|
||||
/** Markdown as something a voice can read: no fences, marks or link targets. */
|
||||
fun plain(markdown: String): String = markdown
|
||||
|
||||
@@ -1,120 +1,42 @@
|
||||
@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]).
|
||||
* The assistant's sheet with its [controller] behind it: [AssistSheetFrame] over the current app,
|
||||
* [AssistSheetContent] in it. The session and [AssistActivity] differ only in what the four
|
||||
* callbacks do: over the lock screen nothing is sent before Android unlocks ([onUnlockAndAsk]);
|
||||
* the microphone's permission prompt needs an activity ([onNeedMic]).
|
||||
*/
|
||||
@Composable
|
||||
fun AssistPanel(controller: AssistController, locked: Boolean, onUnlockAndAsk: (String) -> Unit, onOpenApp: () -> Unit, onNeedMic: () -> Unit) {
|
||||
fun AssistPanel(
|
||||
controller: AssistController,
|
||||
locked: Boolean,
|
||||
onUnlockAndAsk: (String) -> Unit,
|
||||
onOpenApp: () -> Unit,
|
||||
onNeedMic: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
onUnlock: () -> 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)
|
||||
AssistSheetFrame(onDismiss = onDismiss) { handle, _ ->
|
||||
AssistSheetContent(
|
||||
state = state,
|
||||
actions = controller,
|
||||
locked = locked,
|
||||
handle = handle,
|
||||
onOpenApp = onOpenApp,
|
||||
onUnlock = onUnlock,
|
||||
onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) },
|
||||
onMic = {
|
||||
when {
|
||||
locked -> onUnlockAndAsk("")
|
||||
controller.micAllowed() -> controller.listen()
|
||||
else -> onNeedMic()
|
||||
}
|
||||
}
|
||||
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)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,23 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import android.app.assist.AssistStructure
|
||||
import android.app.role.RoleManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.ui.platform.ComposeView
|
||||
import androidx.compose.ui.platform.ViewCompositionStrategy
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.LifecycleRegistry
|
||||
@@ -20,13 +27,19 @@ import androidx.savedstate.SavedStateRegistry
|
||||
import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.wakeLogConnected
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
|
||||
/**
|
||||
@@ -36,7 +49,79 @@ import kotlinx.coroutines.runBlocking
|
||||
* 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 LembasAssistService : VoiceInteractionService() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
AssistLink.created(System.currentTimeMillis())
|
||||
}
|
||||
|
||||
override fun onReady() {
|
||||
super.onReady()
|
||||
current = this
|
||||
// When Android connected it is kept: the wake word's record says whether it was, and an
|
||||
// attempt that found it not connected is told that it came later.
|
||||
val now = System.currentTimeMillis()
|
||||
AssistLink.ready(now)
|
||||
Log.i(TAG, "assistant service connected by Android")
|
||||
background.launch { runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogConnected(it.wakeLog, now)) } } }
|
||||
}
|
||||
|
||||
override fun onShutdown() {
|
||||
// Only the instance that is the current one disconnects it: an old one going away late
|
||||
// must not say "not connected" over a new one.
|
||||
if (current === this) {
|
||||
current = null
|
||||
AssistLink.shutdown(System.currentTimeMillis())
|
||||
}
|
||||
Log.i(TAG, "assistant service disconnected by Android")
|
||||
super.onShutdown()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistLink.destroyed(System.currentTimeMillis())
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/** Android 14+: Android is about to show a session it was asked for -- or, below, could not. Kept for the wake word's record. */
|
||||
override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
|
||||
AssistLink.prepared(SystemClock.elapsedRealtime())
|
||||
super.onPrepareToShowSession(args, showFlags)
|
||||
}
|
||||
|
||||
override fun onShowSessionFailed(args: Bundle) {
|
||||
AssistLink.showFailed(SystemClock.elapsedRealtime())
|
||||
Log.w(TAG, "Android could not show the assistant's session")
|
||||
super.onShowSessionFailed(args)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
|
||||
* wake word opens the sheet through it ([showSession]), which Android allows from the
|
||||
* background, as it does for the power button.
|
||||
*/
|
||||
@Volatile
|
||||
var current: LembasAssistService? = null
|
||||
private set
|
||||
|
||||
private const val TAG = "LLeMbasWake"
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
/**
|
||||
* Whether Android itself uses this service as its voice-interaction service right now.
|
||||
* Holding the assistant role is not the same: Android keeps the service only while a
|
||||
* speech recogniser is set that it accepts, and resets it at start-up otherwise -- the
|
||||
* long press then opens the assistant as an ordinary screen, and nothing is connected
|
||||
* that could open it from the background.
|
||||
*/
|
||||
fun isActive(context: Context): Boolean =
|
||||
runCatching { VoiceInteractionService.isActiveService(context, ComponentName(context, LembasAssistService::class.java)) }.getOrDefault(false)
|
||||
|
||||
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
|
||||
fun holdsRole(context: Context): Boolean =
|
||||
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
|
||||
}
|
||||
}
|
||||
|
||||
class LembasAssistSessionService : VoiceInteractionSessionService() {
|
||||
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
|
||||
@@ -54,6 +139,13 @@ class LembasAssistSession(context: Context) :
|
||||
private val saved = SavedStateRegistryController.create(this)
|
||||
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private var controller = AssistController(context, scope)
|
||||
private val current = mutableStateOf(controller)
|
||||
|
||||
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
|
||||
private var up = false
|
||||
|
||||
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
|
||||
private var handing: Job? = null
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
@@ -62,25 +154,38 @@ class LembasAssistSession(context: Context) :
|
||||
super.onCreate()
|
||||
saved.performRestore(null)
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
// A see-through window over the whole screen: the sheet draws its own dim and sits at
|
||||
// the bottom, the app underneath stays in sight, and the sheet moves with the keyboard.
|
||||
window.window?.let { w ->
|
||||
w.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
|
||||
w.setDimAmount(0f)
|
||||
WindowCompat.setDecorFitsSystemWindows(w, false)
|
||||
@Suppress("DEPRECATION")
|
||||
w.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreateContentView(): View {
|
||||
val theme = runBlocking { context.lembas.instances.prefs.first() }.theme
|
||||
return ComposeView(context).apply {
|
||||
// In the app's language on a phone older than Android 13, which has no per-app one.
|
||||
return ComposeView(AppLanguage.wrap(context)).apply {
|
||||
setViewTreeLifecycleOwner(this@LembasAssistSession)
|
||||
setViewTreeSavedStateRegistryOwner(this@LembasAssistSession)
|
||||
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow)
|
||||
setContent {
|
||||
LembasTheme(theme) {
|
||||
// The controller is made again for each showing: read it from state, so the
|
||||
// sheet follows the new one.
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
controller = current.value,
|
||||
locked = locked(),
|
||||
onUnlockAndAsk = { text -> handOff(text) },
|
||||
onUnlockAndAsk = { text -> handOff(Held(text, null, spoken = false).takeIf { text.isNotBlank() }) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(controller.appIntent())
|
||||
startAssistantActivity(current.value.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("") },
|
||||
onNeedMic = { handOff(null, listen = true) },
|
||||
onDismiss = { hide() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -89,16 +194,47 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
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
|
||||
// Android calls this again for a show asked for while the sheet is up, and hides once:
|
||||
// the sheet is counted as up once.
|
||||
if (!up) {
|
||||
up = true
|
||||
AssistPresence.shown()
|
||||
}
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
|
||||
// this one was slow to come, goes now that this one is here.
|
||||
AssistActivity.closeWoken()
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening --
|
||||
// over the lock screen too, where what it hears is held and not asked.
|
||||
val showing = controller
|
||||
showing.opened(listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
// A question that waits for the unlock (heard, or typed, over the lock screen) goes to
|
||||
// the sheet's activity, which can ask Android to unlock. Once: Android may call onShow
|
||||
// again while the sheet is up.
|
||||
handing?.cancel()
|
||||
handing = scope.launch {
|
||||
showing.state.first { it.held && locked() }
|
||||
showing.takeHeld()?.let { handOff(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Each showing starts fresh -- a new question, the screen not included, listening first --
|
||||
* so a new controller is made as this one hides: ready for the screen the next invocation
|
||||
* hands over, which may come before or after its `onShow`.
|
||||
*/
|
||||
override fun onHide() {
|
||||
super.onHide()
|
||||
if (up) {
|
||||
up = false
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
controller = AssistController(context, scope)
|
||||
current.value = controller
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
@@ -119,7 +255,7 @@ class LembasAssistSession(context: Context) :
|
||||
controller.offerScreen(text, null)
|
||||
}
|
||||
|
||||
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Include screen" is on. */
|
||||
/** And a picture of it, if allowed ("Use screenshot"). Sent only when "Use screen" is on. */
|
||||
override fun onHandleScreenshot(screenshot: Bitmap?) {
|
||||
super.onHandleScreenshot(screenshot)
|
||||
controller.offerScreen(null, screenshot)
|
||||
@@ -135,17 +271,12 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
/**
|
||||
* 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
|
||||
* which asks Android to unlock first and only then sends it. It is left in the app's own
|
||||
* memory ([AssistHandOff]) and the intent carries its ticket. 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),
|
||||
)
|
||||
private fun handOff(question: Held?, listen: Boolean = false) {
|
||||
startAssistantActivity(AssistActivity.handedOver(context, question?.let { AssistHandOff.leave(it) }, listen))
|
||||
hide()
|
||||
}
|
||||
|
||||
private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.Orientation
|
||||
import androidx.compose.foundation.gestures.draggable
|
||||
import androidx.compose.foundation.gestures.rememberDraggableState
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.WindowInsets
|
||||
import androidx.compose.foundation.layout.asPaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
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.layout.size
|
||||
import androidx.compose.foundation.layout.statusBars
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeOff
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeUp
|
||||
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Lightbulb
|
||||
import androidx.compose.material.icons.filled.LockOpen
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.ScreenshotMonitor
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.AssistChipDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
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.material3.TextFieldDefaults
|
||||
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.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.PhoneCard
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
import eu.llembas.android.ui.chat.followsAt
|
||||
import eu.llembas.android.ui.chat.yielding
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Where a let-go drag leaves the sheet. */
|
||||
enum class SheetStop { Half, Full, Gone }
|
||||
|
||||
/**
|
||||
* Where the sheet goes when a drag of its handle ends at [height] px moving at [velocity] px/s
|
||||
* (positive is down), between [half] and [full]: a fling decides by its direction, a slow
|
||||
* release by the nearest stop -- and below most of the half, it goes.
|
||||
*/
|
||||
fun settle(height: Float, half: Float, full: Float, velocity: Float): SheetStop = when {
|
||||
velocity > FLING -> if (height < half + 1f) SheetStop.Gone else SheetStop.Half
|
||||
velocity < -FLING -> SheetStop.Full
|
||||
height < half * 0.6f -> SheetStop.Gone
|
||||
height > (half + full) / 2f -> SheetStop.Full
|
||||
else -> SheetStop.Half
|
||||
}
|
||||
|
||||
private const val FLING = 1_200f
|
||||
|
||||
/**
|
||||
* The assistant's window: the app it opened over stays in sight under a dim, and the sheet rises
|
||||
* from the bottom to about half the height. Its handle drags it to the full height or down and
|
||||
* away; a tap on the dim, or Back, closes it too. With the keyboard up, the sheet's stops are
|
||||
* measured above the keyboard.
|
||||
*/
|
||||
@Composable
|
||||
fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(handle: Modifier, expanded: Boolean) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val inspection = LocalInspectionMode.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(Color.Black.copy(alpha = 0.32f))
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = onDismiss)
|
||||
.imePadding(),
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val density = LocalDensity.current
|
||||
val full = with(density) { (maxHeight - top - 8.dp).toPx() }.coerceAtLeast(0f)
|
||||
val half = (full * 0.56f).coerceAtLeast(minOf(full, with(density) { 360.dp.toPx() }))
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val target = if (expanded) full else half
|
||||
val height = remember { Animatable(if (inspection) target else 0f) }
|
||||
LaunchedEffect(target) { height.animateTo(target) }
|
||||
val drag = rememberDraggableState { delta -> scope.launch { height.snapTo((height.value - delta).coerceIn(0f, full)) } }
|
||||
val handle = Modifier.draggable(
|
||||
drag,
|
||||
Orientation.Vertical,
|
||||
onDragStopped = { velocity ->
|
||||
when (settle(height.value, half, full, velocity)) {
|
||||
SheetStop.Gone -> {
|
||||
height.animateTo(0f)
|
||||
onDismiss()
|
||||
}
|
||||
|
||||
SheetStop.Full -> {
|
||||
expanded = true
|
||||
height.animateTo(full)
|
||||
}
|
||||
|
||||
SheetStop.Half -> {
|
||||
expanded = false
|
||||
height.animateTo(half)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
Surface(
|
||||
color = palette.surface,
|
||||
contentColor = palette.ink,
|
||||
shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp),
|
||||
tonalElevation = 2.dp,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.fillMaxWidth()
|
||||
.height(with(density) { height.value.toDp() })
|
||||
// Taps inside the sheet are the sheet's, not the dim's.
|
||||
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {},
|
||||
) {
|
||||
Column(Modifier.fillMaxSize().navigationBarsPadding()) { content(handle, expanded) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sheet's contents, from [state] alone (what the screenshot tests draw):
|
||||
*
|
||||
* - **the top**: the drag handle, the model and connection chip (the model's picture, its name,
|
||||
* the instance and whether it answers; a tap picks another model), voice reply on or off, and
|
||||
* Open in app, which carries on this same chat in the app;
|
||||
* - **the middle**: before anything is asked, the last assistant chat to continue, the quick
|
||||
* actions (the screen's, when the system handed one over), and how to open the assistant --
|
||||
* and that there is no wake word; then the questions and answers, the answers as they are
|
||||
* written;
|
||||
* - **the foot**: Use screen, then the microphone first -- while listening, the words as they are
|
||||
* heard and how loud -- or the words typed, and Send.
|
||||
*
|
||||
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat,
|
||||
* no question asked earlier, no answer, no failure's words. A question heard over the lock
|
||||
* screen waits -- shown as the person's own words where the phone wrote them down, as "Question
|
||||
* heard" where it waits as a recording -- with the way to unlock, which sends it ([onUnlock]).
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.AssistSheetContent(
|
||||
state: AssistUiState,
|
||||
actions: AssistActions,
|
||||
locked: Boolean,
|
||||
handle: Modifier = Modifier,
|
||||
onOpenApp: () -> Unit = {},
|
||||
onUnlock: () -> Unit = {},
|
||||
onSend: (String) -> Unit = actions::ask,
|
||||
onMic: () -> Unit = actions::listen,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val scroll = rememberScrollState()
|
||||
// The turns keep to their end while an answer is written only for a person who is there
|
||||
// (`ui/chat/Follow.kt`, the chat's rule): a finger on them ends the following, where they
|
||||
// come to rest says whether it is taken up again, and a question asked always shows.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
LaunchedEffect(scroll) {
|
||||
scroll.interactionSource.interactions.collect { if (it is DragInteraction.Start) following = false }
|
||||
}
|
||||
LaunchedEffect(scroll) {
|
||||
var moving = false
|
||||
snapshotFlow { scroll.isScrollInProgress }.collect { now ->
|
||||
if (moving && !now) following = followsAt(scroll.maxValue - scroll.value, slack)
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
LaunchedEffect(state.turns.size) { following = true }
|
||||
// The end moves when the answer grows and when the keyboard opens; before the first layout
|
||||
// it is not known yet.
|
||||
LaunchedEffect(scroll) {
|
||||
// Never against a finger: nothing is moved while a scroll is under way, and one of
|
||||
// ours that a finger interrupts does not end this follower (`yielding`). Whether a
|
||||
// scroll is under way is asked here and not watched: our own scroll is one too, and
|
||||
// watching it would have each scroll to the end start the next.
|
||||
snapshotFlow { if (following) scroll.maxValue else -1 }
|
||||
.collect { end -> if (end in 0 until Int.MAX_VALUE && !scroll.isScrollInProgress) yielding { scroll.scrollTo(end) } }
|
||||
}
|
||||
|
||||
// The top: the handle and the bar. Both drag the sheet.
|
||||
Column(handle.fillMaxWidth()) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(width = 36.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp)))
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
val showChip = state.signedIn && !locked
|
||||
Box(Modifier.weight(1f)) {
|
||||
if (showChip) {
|
||||
ModelChip(state, actions)
|
||||
} else {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(8.dp))
|
||||
}
|
||||
}
|
||||
if (state.canSpeak && !locked) {
|
||||
IconButton(onClick = { actions.voiceReply(!state.voiceReply) }) {
|
||||
Icon(
|
||||
if (state.voiceReply) Icons.AutoMirrored.Filled.VolumeUp else Icons.AutoMirrored.Filled.VolumeOff,
|
||||
contentDescription = stringResource(if (state.voiceReply) R.string.assist_voice_reply_on else R.string.assist_voice_reply_off),
|
||||
tint = if (state.voiceReply) palette.accent else palette.inkMuted,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.signedIn) {
|
||||
IconButton(onClick = onOpenApp) {
|
||||
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = stringResource(R.string.assist_open_in_app), tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.busy) {
|
||||
val bar = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp)
|
||||
// A preview (the screenshot tests) cannot wait out an endless animation: a still bar there.
|
||||
if (LocalInspectionMode.current) LinearProgressIndicator(progress = { 0.4f }, modifier = bar) else LinearProgressIndicator(bar)
|
||||
} else {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (!state.signedIn) {
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.Center) {
|
||||
Text(stringResource(R.string.assist_signed_out), style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_open_app)) }
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// The middle.
|
||||
Column(
|
||||
Modifier.weight(1f).fillMaxWidth().verticalScroll(scroll).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
when {
|
||||
locked && state.held -> Waiting(state.waiting, onUnlock)
|
||||
|
||||
// A conversation that was on the sheet when the phone locked: not for the lock screen.
|
||||
locked && !state.empty -> Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
state.empty -> Starting(state, actions, locked)
|
||||
|
||||
else -> state.turns.forEachIndexed { i, turn ->
|
||||
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
|
||||
}
|
||||
}
|
||||
// Not over the lock screen: a failure's words may name the instance.
|
||||
if (!locked) state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
// The foot.
|
||||
Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) {
|
||||
if (state.conversation && !locked) Conversation(actions)
|
||||
if (state.screenAvailable && !locked) ScreenToggle(state, actions)
|
||||
if (state.listening) {
|
||||
Listening(state, onDone = actions::heard, onType = actions::type)
|
||||
} else {
|
||||
val focus = remember { FocusRequester() }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (state.busy && state.heard.isNotBlank()) R.string.assist_writing_down else R.string.assist_hint)) },
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = palette.surfaceRaised,
|
||||
unfocusedContainerColor = palette.surfaceRaised,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
modifier = Modifier.weight(1f).heightIn(min = 52.dp).focusRequester(focus),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
// One slot of fixed size: the microphone, or Send once there are words.
|
||||
Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) {
|
||||
if (text.isBlank()) {
|
||||
if (state.canListen) {
|
||||
Surface(
|
||||
onClick = onMic,
|
||||
shape = CircleShape,
|
||||
color = palette.accent,
|
||||
contentColor = palette.accentInk,
|
||||
modifier = Modifier.size(52.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate)) }
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Surface(
|
||||
onClick = {
|
||||
onSend(text)
|
||||
text = ""
|
||||
},
|
||||
enabled = !state.busy || locked,
|
||||
shape = CircleShape,
|
||||
color = palette.accent,
|
||||
contentColor = palette.accentInk,
|
||||
modifier = Modifier.size(52.dp),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.heard.isNotBlank()) {
|
||||
Text(state.heard, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.padding(start = 16.dp, top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The model and the connection: its picture, its name, the instance and a dot that says whether it answers. */
|
||||
@Composable
|
||||
private fun ModelChip(state: AssistUiState, actions: AssistActions) {
|
||||
val palette = LocalPalette.current
|
||||
var open by remember { mutableStateOf(false) }
|
||||
val dot = when (state.connection) {
|
||||
Connection.Online -> palette.success
|
||||
Connection.Offline -> palette.danger
|
||||
Connection.Checking -> palette.inkFaint
|
||||
}
|
||||
val where = when (state.connection) {
|
||||
Connection.Online -> state.instanceName
|
||||
Connection.Offline -> stringResource(R.string.assist_offline, state.instanceName)
|
||||
Connection.Checking -> stringResource(R.string.assist_connecting)
|
||||
}
|
||||
Box {
|
||||
Surface(
|
||||
onClick = { if (state.models.isNotEmpty()) open = true },
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 48.dp),
|
||||
) {
|
||||
Row(Modifier.padding(start = 6.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box {
|
||||
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 32.dp)
|
||||
// The connection's dot, ringed in the chip's colour so it reads over any picture.
|
||||
val ring = Modifier.align(Alignment.BottomEnd).size(10.dp).clip(CircleShape).background(palette.surfaceRaised)
|
||||
Box(ring.padding(2.dp).clip(CircleShape).background(dot))
|
||||
}
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f, fill = false)) {
|
||||
Text(
|
||||
state.modelInfo?.name?.ifBlank { null } ?: state.modelId ?: stringResource(R.string.assist_no_model),
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(where, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
Icon(Icons.Filled.ArrowDropDown, contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
state.models.forEach { model ->
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { ModelAvatar(model, model.id, size = 24.dp) },
|
||||
text = { Text(model.titleAmong(state.models), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
trailingIcon = if (model.key == state.modelInfo?.key) {
|
||||
{ Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = {
|
||||
open = false
|
||||
actions.pickModel(model.key)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Before anything is asked: the last chat to continue, the quick actions, and how to open this. */
|
||||
@Composable
|
||||
private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
if (!locked) {
|
||||
state.last?.let { last ->
|
||||
Surface(
|
||||
onClick = actions::continueLast,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 16.dp, vertical = 12.dp).heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.History, contentDescription = null, tint = palette.accent)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.assist_continue), style = MaterialTheme.typography.titleSmall)
|
||||
Text(
|
||||
listOf(last.title, if (last.at > 0) DateUtils.getRelativeTimeSpanString(last.at).toString() else "")
|
||||
.filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.screenAvailable && !locked) {
|
||||
val summarise = stringResource(R.string.assist_quick_summarise_prompt)
|
||||
val translate = stringResource(R.string.assist_quick_translate_prompt)
|
||||
val explain = stringResource(R.string.assist_quick_explain_prompt)
|
||||
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
QuickAction(Icons.Filled.Summarize, stringResource(R.string.assist_quick_summarise)) { actions.quick(summarise) }
|
||||
QuickAction(Icons.Filled.Translate, stringResource(R.string.assist_quick_translate)) { actions.quick(translate) }
|
||||
QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) }
|
||||
}
|
||||
}
|
||||
// The notifications, read only now that it is asked, and never over the lock screen.
|
||||
if (state.canReadNotifications && !locked) {
|
||||
QuickAction(Icons.Filled.Notifications, stringResource(R.string.assist_notifications)) { actions.summariseNotifications() }
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_wake_word_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
AssistChip(
|
||||
onClick = onClick,
|
||||
label = { Text(label) },
|
||||
leadingIcon = { Icon(icon, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Over the lock screen: the question that was heard, as its bubble, and the one thing to do about
|
||||
* it. Unlocking sends it; nothing is sent and no answer shown before.
|
||||
*/
|
||||
@Composable
|
||||
private fun Waiting(question: String, onUnlock: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// The words, where the phone itself wrote them down or they were typed; a question the
|
||||
// instance will write down waits as a recording, and there are no words to show yet.
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
|
||||
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
|
||||
Text(
|
||||
question.ifBlank { stringResource(R.string.assist_question_heard) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(if (question.isBlank()) R.string.assist_recording_waits_line else R.string.assist_locked_line),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
AssistChip(
|
||||
onClick = onUnlock,
|
||||
label = { Text(stringResource(R.string.assist_unlock_to_send)) },
|
||||
leadingIcon = { Icon(Icons.Filled.LockOpen, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */
|
||||
@Composable
|
||||
private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
|
||||
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
|
||||
Text(turn.question, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp))
|
||||
}
|
||||
}
|
||||
if (turn.steps.isNotEmpty()) Steps(turn.steps)
|
||||
val reply = turn.reply
|
||||
val drawsProgress = reply != null && (progressLineOf(reply.progress) != null || reply.status.isNotBlank())
|
||||
when {
|
||||
// A phone action is confirmed here, where the phone is; any other card in the app.
|
||||
reply != null && reply.cards.any { it.kind == "phone_action" } -> reply.cards.first { it.kind == "phone_action" }.let { card ->
|
||||
PhoneCard(card) { answer -> actions.answerCard(card, answer) }
|
||||
}
|
||||
|
||||
reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) }
|
||||
|
||||
turn.writing && drawsProgress -> ProgressStatus(reply?.progress, reply?.status.orEmpty(), MaterialTheme.typography.labelSmall, palette.inkFaint)
|
||||
|
||||
last && !turn.writing && turn.steps.isNotEmpty() -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (state.canSpeak) {
|
||||
if (state.speaking) {
|
||||
AssistChip(onClick = actions::stopReading, label = { Text(stringResource(R.string.assist_stop_reading)) }, leadingIcon = {
|
||||
Icon(Icons.Filled.Stop, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
})
|
||||
} else {
|
||||
AssistChip(onClick = actions::readAloud, label = { Text(stringResource(R.string.assist_read_aloud)) }, leadingIcon = {
|
||||
Icon(Icons.AutoMirrored.Filled.VolumeUp, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
})
|
||||
}
|
||||
}
|
||||
AssistChip(onClick = actions::newChat, label = { Text(stringResource(R.string.new_chat)) }, leadingIcon = {
|
||||
Icon(Icons.Filled.EditNote, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A spoken conversation is on: the sheet will listen again after the answer is read. Says so,
|
||||
* and how it ends -- End here, "stop" said, or silence. The words give; End keeps its size.
|
||||
*/
|
||||
@Composable
|
||||
private fun Conversation(actions: AssistActions) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(16.dp), color = palette.accentSoft, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
Row(Modifier.padding(start = 14.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Forum, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.assist_conversation), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
Text(stringResource(R.string.assist_conversation_line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
TextButton(onClick = actions::endConversation, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.assist_conversation_end))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Use screen: off every time the sheet opens; on, the screen goes with the next question only. */
|
||||
@Composable
|
||||
private fun ScreenToggle(state: AssistUiState, actions: AssistActions) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
FilterChip(
|
||||
selected = state.includeScreen,
|
||||
onClick = { actions.includeScreen(!state.includeScreen) },
|
||||
label = { Text(stringResource(R.string.assist_use_screen)) },
|
||||
leadingIcon = { Icon(Icons.Filled.ScreenshotMonitor, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft, selectedLeadingIconColor = palette.accent),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
)
|
||||
if (state.includeScreen) {
|
||||
Spacer(Modifier.width(10.dp))
|
||||
state.screenshot?.let { shot ->
|
||||
Image(
|
||||
shot.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(width = 24.dp, height = 40.dp).clip(RoundedCornerShape(4.dp)).background(palette.bgSunken),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
state.screenText && state.screenshot != null -> R.string.assist_screen_both
|
||||
state.screenText -> R.string.assist_screen_text
|
||||
else -> R.string.assist_screen_shot
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Listening: the microphone, grown by how loud it hears you (a tap sends what was said), the
|
||||
* words so far, and the keyboard to type instead. The row's parts keep their sizes; the words
|
||||
* give.
|
||||
*/
|
||||
@Composable
|
||||
private fun Listening(state: AssistUiState, onDone: () -> Unit, onType: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 72.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(64.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(64.dp).scale(0.8f + 0.2f * (state.level * 3f).coerceAtMost(1f)).clip(CircleShape).background(palette.accentSoft))
|
||||
Surface(onClick = onDone, shape = CircleShape, color = palette.accent, contentColor = palette.accentInk, modifier = Modifier.size(52.dp)) {
|
||||
Box(contentAlignment = Alignment.Center) { Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.assist_send_now)) }
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(stringResource(R.string.listening), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
Text(
|
||||
state.heard.ifBlank { stringResource(R.string.assist_say_it) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = if (state.heard.isBlank()) palette.inkFaint else palette.ink,
|
||||
maxLines = 4,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onType) { Icon(Icons.Filled.Keyboard, contentDescription = stringResource(R.string.assist_type), tint = palette.inkMuted) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
/**
|
||||
* When to stop listening, for the instance's speech-to-text (which takes a whole recording and
|
||||
* finds no end of speech itself). Fed the microphone's level once a tick ([tick]); apart from
|
||||
* Android, so it is tested with sequences of levels.
|
||||
*
|
||||
* Nothing here is an absolute loudness: a room's own noise differs from phone to phone by more
|
||||
* than a voice differs from a room. The **noise floor** is measured from the first sound on and
|
||||
* followed all the time -- the quietest level of the last two seconds, taken at once when it
|
||||
* falls and slowly, in calm moments, when it rises: the dips between words keep it down while
|
||||
* somebody speaks, and a steady noise (a fan, a car) becomes the floor within a moment. Speech and quiet are
|
||||
* levels relative to it:
|
||||
*
|
||||
* - **speech** begins when the level is well above the floor in [ONSET_TICKS] of the last
|
||||
* [ONSET_WINDOW] ticks -- a voice rises and falls, and one click or knock is not speech;
|
||||
* - listening may begin in the middle of a sentence (the wake word's shape: the person goes
|
||||
* straight on), and a voice that never dips far must not become "the room": the floor rises
|
||||
* only while the sound is calm, and sound that stays above the floor without being steady is
|
||||
* speech;
|
||||
* - once somebody spoke, a **pause** of [PAUSE_MS] back near the floor ends it ([Verdict.Said]);
|
||||
* - when **nothing is said**, it gives up after [NOTHING_SAID_MS] ([Verdict.Nothing]);
|
||||
* - the words written down so far are a second ear: the same words for [SAME_WORDS_MS] end it,
|
||||
* and words count as speech for a quiet voice -- but only when the microphone heard at least
|
||||
* something above the floor, because a speech-to-text model asked to write down silence
|
||||
* invents a sentence;
|
||||
* - and never longer than [LONGEST_MS].
|
||||
*/
|
||||
class EndOfSpeech(private val tickMs: Long = TICK_MS) {
|
||||
enum class Verdict { Listening, Said, Nothing }
|
||||
|
||||
/** The room's own level, as followed so far; 0 until the microphone gave any sound. */
|
||||
var floor = 0f
|
||||
private set
|
||||
|
||||
/** Whether somebody spoke. */
|
||||
var spoke = false
|
||||
private set
|
||||
|
||||
/**
|
||||
* Whether the microphone heard anything above the room at all: only then is the recording
|
||||
* worth writing down while it runs.
|
||||
*/
|
||||
val heardSomething: Boolean get() = spoke || stirred >= STIRRED_TICKS
|
||||
|
||||
private val recent = ArrayDeque<Float>()
|
||||
private var waited = 0L
|
||||
private val loud = ArrayDeque<Boolean>()
|
||||
private var stirred = 0
|
||||
private var aboveRun = 0
|
||||
|
||||
/** The floor is a guess: listening began in the middle of sound louder than any room is taken to be. */
|
||||
private var guessed = false
|
||||
private var overGuess = 0
|
||||
private var quietFor = 0L
|
||||
private var words = ""
|
||||
private var sameWordsFor = 0L
|
||||
|
||||
/** The level from which a sound is speech beginning, and the level under which it is a pause. */
|
||||
private fun speechFrom(): Float = maxOf(floor * SPEECH_RATIO, floor + SPEECH_MARGIN)
|
||||
|
||||
private fun pauseUnder(): Float = maxOf(floor * PAUSE_RATIO, floor + PAUSE_MARGIN)
|
||||
|
||||
/** One tick: the microphone's [level] (0..1, RMS) and the [heard] words written down so far. */
|
||||
fun tick(level: Float, heard: String = ""): Verdict {
|
||||
waited += tickMs
|
||||
// Exact zero before any sound is a microphone that has not given anything yet (or gives
|
||||
// nothing at all): it says nothing about the room. After sound it is silence -- a
|
||||
// headset that gates its noise gives exactly that between sentences -- and so a pause.
|
||||
if (level > 0f) {
|
||||
follow(level)
|
||||
} else if (floor > 0f) {
|
||||
judge(loud = false, above = false)
|
||||
}
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += tickMs
|
||||
}
|
||||
if (heard.isNotBlank() && stirred >= STIRRED_TICKS) spoke = true
|
||||
return when {
|
||||
spoke && quietFor >= PAUSE_MS -> Verdict.Said
|
||||
spoke && sameWordsFor >= SAME_WORDS_MS -> Verdict.Said
|
||||
!spoke && waited >= NOTHING_SAID_MS -> Verdict.Nothing
|
||||
waited >= LONGEST_MS -> if (spoke) Verdict.Said else Verdict.Nothing
|
||||
else -> Verdict.Listening
|
||||
}
|
||||
}
|
||||
|
||||
private fun follow(level: Float) {
|
||||
recent.addLast(level)
|
||||
if (recent.size > WINDOW_TICKS) recent.removeFirst()
|
||||
val lowest = recent.min()
|
||||
// Steady over the whole window: a noise. Calm in the last half second: no voice now.
|
||||
val steady = recent.size >= CALM_TICKS && recent.max() <= lowest * STEADY_RATIO
|
||||
val last = recent.takeLast(CALM_TICKS)
|
||||
val calm = last.size >= CALM_TICKS && last.max() <= last.min() * STEADY_RATIO
|
||||
// The first sound is the room, unless somebody is already speaking -- then a guess,
|
||||
// until a dip or a calm moment shows the room. After it: down at once; up slowly, and
|
||||
// only while the sound is calm, so a voice does not lift the floor under itself.
|
||||
when {
|
||||
floor == 0f -> {
|
||||
floor = minOf(level, START_MAX)
|
||||
guessed = level > START_MAX
|
||||
}
|
||||
|
||||
lowest < floor -> {
|
||||
floor = lowest
|
||||
guessed = false
|
||||
}
|
||||
|
||||
calm -> {
|
||||
floor += (lowest - floor) * RISE
|
||||
guessed = false
|
||||
}
|
||||
}
|
||||
floor = floor.coerceAtLeast(MIN_FLOOR)
|
||||
judge(loud = level >= speechFrom(), above = level >= pauseUnder())
|
||||
// Sound that stays above the floor and is not steady is a voice: one that never dips
|
||||
// far, or -- while the floor is only a guess -- one that began before the listening did.
|
||||
overGuess = if (guessed && level > floor) overGuess + 1 else 0
|
||||
if ((aboveRun >= SUSTAINED_TICKS || overGuess >= SUSTAINED_TICKS) && !steady) spoke = true
|
||||
}
|
||||
|
||||
/** One tick's sound, judged: [loud] enough to be speech beginning, or at least [above] a pause. */
|
||||
private fun judge(loud: Boolean, above: Boolean) {
|
||||
this.loud.addLast(loud)
|
||||
if (this.loud.size > ONSET_WINDOW) this.loud.removeFirst()
|
||||
if (this.loud.count { it } >= ONSET_TICKS) spoke = true
|
||||
if (above) {
|
||||
stirred++
|
||||
aboveRun++
|
||||
quietFor = 0
|
||||
} else {
|
||||
aboveRun = 0
|
||||
quietFor += tickMs
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TICK_MS = 100L
|
||||
|
||||
/** How long the room's quietest level is looked for: two seconds. */
|
||||
private const val WINDOW_TICKS = 20
|
||||
|
||||
/** How fast the floor follows a room that got louder: a twentieth of the way each tick. */
|
||||
private const val RISE = 0.05f
|
||||
|
||||
/** No microphone is quieter than this; and the most the first sound may claim as "the room". */
|
||||
private const val MIN_FLOOR = 0.0008f
|
||||
private const val START_MAX = 0.02f
|
||||
|
||||
// Speech begins at a little over twice the floor (and at least a small step above it, for
|
||||
// a silent room); a pause is back within 1.6 times of it. Between the two nothing changes.
|
||||
private const val SPEECH_RATIO = 2.2f
|
||||
private const val SPEECH_MARGIN = 0.004f
|
||||
private const val PAUSE_RATIO = 1.6f
|
||||
private const val PAUSE_MARGIN = 0.002f
|
||||
private const val ONSET_TICKS = 3
|
||||
private const val ONSET_WINDOW = 8
|
||||
private const val STIRRED_TICKS = 4
|
||||
|
||||
// Steady, calm: the loudest within half again of the quietest -- over the window, over
|
||||
// the last half second. Sustained: above the floor for a second without a break.
|
||||
private const val CALM_TICKS = 5
|
||||
private const val STEADY_RATIO = 1.5f
|
||||
private const val SUSTAINED_TICKS = 10
|
||||
|
||||
const val PAUSE_MS = 1_500L
|
||||
const val SAME_WORDS_MS = 4_500L
|
||||
const val NOTHING_SAID_MS = 5_000L
|
||||
const val LONGEST_MS = 60_000L
|
||||
}
|
||||
}
|
||||
|
||||
/** What to do about the phone's own recogniser, which finds the end of speech itself -- usually. */
|
||||
enum class PhoneWatch {
|
||||
Wait,
|
||||
|
||||
/** Ask it to stop and give what it has. */
|
||||
Finish,
|
||||
|
||||
/** It did not answer the asking either: take the words it showed. */
|
||||
Take,
|
||||
|
||||
/** Nothing was said, and it has not said so itself. */
|
||||
GiveUp,
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch kept over the phone's recogniser, from how long it has listened ([waitedMs]), whether
|
||||
* it has shown any words ([anyWords]), for how long they have stayed the same ([sameForMs]), and
|
||||
* how long ago it last gave a sign of somebody speaking ([silentForMs]: its "speech began", a
|
||||
* loud level, new words -- not every recogniser shows words while one speaks).
|
||||
* A recogniser normally ends by itself; some never call back, and the sheet would listen for good.
|
||||
* No words and nothing heard for a while gives up; when somebody did speak before that quiet, it
|
||||
* is first asked for what it has.
|
||||
*/
|
||||
fun phoneWatch(waitedMs: Long, anyWords: Boolean, sameForMs: Long, silentForMs: Long = waitedMs): PhoneWatch = when {
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS + PHONE_GRACE_MS -> if (anyWords) PhoneWatch.Take else PhoneWatch.GiveUp
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS -> PhoneWatch.Finish
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS + PHONE_GRACE_MS -> PhoneWatch.GiveUp
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS -> if (silentForMs < waitedMs) PhoneWatch.Finish else PhoneWatch.GiveUp
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS + PHONE_GRACE_MS -> PhoneWatch.Take
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS && silentForMs >= EndOfSpeech.PAUSE_MS -> PhoneWatch.Finish
|
||||
else -> PhoneWatch.Wait
|
||||
}
|
||||
|
||||
/** Longer than the recogniser's own "no speech" (about five seconds on most): it gets to say so first. */
|
||||
const val PHONE_NOTHING_SAID_MS = 8_000L
|
||||
|
||||
/** How long a recogniser that was asked to stop has to answer. */
|
||||
const val PHONE_GRACE_MS = 2_500L
|
||||
@@ -1,11 +1,16 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresApi
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -15,11 +20,39 @@ import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Who writes down what an app asked the system's recogniser to hear. */
|
||||
enum class Recognise {
|
||||
/** The instance's speech-to-text: the recording is sent to it. */
|
||||
Instance,
|
||||
|
||||
/** The phone's on-device recogniser: nothing leaves the phone through LLeMbas. */
|
||||
OnDevice,
|
||||
|
||||
/** Nobody: the calling app is told there is no recogniser for it now. */
|
||||
Refuse,
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock-screen rule for the system recogniser: nothing goes to the instance while the phone
|
||||
* is [locked], whoever asks. Locked, the on-device recogniser hears it where the phone has one
|
||||
* ([onDevice]); a phone without one answers the app that it cannot.
|
||||
*/
|
||||
fun recogniseWith(locked: Boolean, onDevice: Boolean): Recognise = when {
|
||||
!locked -> Recognise.Instance
|
||||
onDevice -> Recognise.OnDevice
|
||||
else -> Recognise.Refuse
|
||||
}
|
||||
|
||||
/**
|
||||
* 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].
|
||||
* speech-to-text. Listening ends when the caller says stop, at a pause after speech or when
|
||||
* nothing is said ([EndOfSpeech], as in the assistant's sheet), or after [LIMIT_MS].
|
||||
*
|
||||
* Not while the phone is locked ([recogniseWith]): an app over the lock screen gets the phone's
|
||||
* on-device recogniser, or [UNAVAILABLE]. A phone that locks while a recording is being made
|
||||
* sends nothing either.
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -27,31 +60,133 @@ class LembasRecognitionService : RecognitionService() {
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
/** The on-device recogniser hearing a locked phone's request, while it does. */
|
||||
private var phone: SpeechRecognizer? = null
|
||||
|
||||
private fun locked(): Boolean = getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true
|
||||
|
||||
private fun onDevice(): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(this)
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
dropPhone()
|
||||
when (recogniseWith(locked(), onDevice())) {
|
||||
Recognise.Instance -> Unit
|
||||
|
||||
Recognise.OnDevice -> {
|
||||
if (Build.VERSION.SDK_INT >= 31) listenOnDevice(intent, listener)
|
||||
return
|
||||
}
|
||||
|
||||
Recognise.Refuse -> {
|
||||
listener.error(UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
listener.beginningOfSpeech()
|
||||
limit = scope.launch {
|
||||
delay(LIMIT_MS)
|
||||
val ear = EndOfSpeech()
|
||||
var waited = 0L
|
||||
while (waited < LIMIT_MS) {
|
||||
delay(EndOfSpeech.TICK_MS)
|
||||
waited += EndOfSpeech.TICK_MS
|
||||
when (ear.tick(recorder.level.value)) {
|
||||
EndOfSpeech.Verdict.Said -> break
|
||||
|
||||
// Nothing said is nothing sent: silence written down is an invented sentence.
|
||||
EndOfSpeech.Verdict.Nothing -> {
|
||||
silent()
|
||||
return@launch
|
||||
}
|
||||
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's on-device recogniser in LLeMbas's place: what it hears and says goes to the
|
||||
* calling app as it is. Never the system's default recogniser, which is this service.
|
||||
*/
|
||||
@RequiresApi(31)
|
||||
private fun listenOnDevice(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
val made = SpeechRecognizer.createOnDeviceSpeechRecognizer(this)
|
||||
phone = made
|
||||
// The calling app may be gone by the time a word comes: nobody is left to tell.
|
||||
fun tell(say: () -> Unit) {
|
||||
runCatching(say)
|
||||
}
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) = tell { listener.readyForSpeech(params ?: Bundle()) }
|
||||
|
||||
override fun onBeginningOfSpeech() = tell { listener.beginningOfSpeech() }
|
||||
|
||||
override fun onRmsChanged(rmsdB: Float) = tell { listener.rmsChanged(rmsdB) }
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = tell { listener.endOfSpeech() }
|
||||
|
||||
override fun onError(error: Int) {
|
||||
dropPhone()
|
||||
tell { listener.error(error) }
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
dropPhone()
|
||||
tell { listener.results(results ?: Bundle()) }
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) = tell { listener.partialResults(partialResults ?: Bundle()) }
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
},
|
||||
)
|
||||
made.startListening(intent?.let { Intent(it) } ?: Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH))
|
||||
}
|
||||
|
||||
private fun dropPhone() {
|
||||
phone?.runCatching {
|
||||
cancel()
|
||||
destroy()
|
||||
}
|
||||
phone = null
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
phone?.let {
|
||||
it.stopListening()
|
||||
return
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
dropPhone()
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
/** Nobody spoke: the caller is told so, and nothing is written down. */
|
||||
private fun silent() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
scope.launch {
|
||||
recorder.stop()
|
||||
listener.error(SpeechRecognizer.ERROR_SPEECH_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun finish() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
@@ -59,6 +194,11 @@ class LembasRecognitionService : RecognitionService() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
// The phone locked while it listened: the recording goes nowhere.
|
||||
if (locked()) {
|
||||
listener.error(UNAVAILABLE)
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
if (text.isBlank()) {
|
||||
@@ -73,11 +213,19 @@ class LembasRecognitionService : RecognitionService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
dropPhone()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
|
||||
/**
|
||||
* What a calling app is told when nothing may hear it now: the recogniser is busy, which
|
||||
* is the error an app takes as "not now, try again" rather than as its own mistake or a
|
||||
* missing permission.
|
||||
*/
|
||||
const val UNAVAILABLE = SpeechRecognizer.ERROR_RECOGNIZER_BUSY
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Telling the app's own intents from anybody's. [AssistActivity] is exported -- Android's
|
||||
* `ACTION_ASSIST` and a headset's voice button must reach it -- so any app can start it with any
|
||||
* action and any extras. What only the app's own parts may ask for (open listening, continue the
|
||||
* last chat, turn the screen on, take a handed-over question) is therefore honoured only on an
|
||||
* intent that carries the app's own mark: a random value made once on this phone and kept in the
|
||||
* app's private storage. The widget's and the shortcuts' intents carry it inside a
|
||||
* `PendingIntent` or a shortcut, which no other app can read.
|
||||
*/
|
||||
object OwnIntents {
|
||||
private const val STORE = "own_intents"
|
||||
private const val KEY = "mark"
|
||||
private const val EXTRA_MARK = "eu.llembas.android.OWN"
|
||||
|
||||
@Volatile
|
||||
private var cached: String? = null
|
||||
|
||||
private fun mark(context: Context): String = cached ?: synchronized(this) {
|
||||
cached ?: run {
|
||||
val store = context.applicationContext.getSharedPreferences(STORE, Context.MODE_PRIVATE)
|
||||
val kept = store.getString(KEY, null) ?: newMark().also { store.edit().putString(KEY, it).apply() }
|
||||
cached = kept
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
private fun newMark(): String = ByteArray(24).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
|
||||
/** [intent], marked as the app's own. */
|
||||
fun own(context: Context, intent: Intent): Intent = intent.putExtra(EXTRA_MARK, mark(context))
|
||||
|
||||
/** Whether [intent] was made by the app itself. */
|
||||
fun isOwn(context: Context, intent: Intent?): Boolean = sameMark(runCatching { intent?.getStringExtra(EXTRA_MARK) }.getOrNull(), mark(context))
|
||||
|
||||
/** Compared in full, whatever differs: how long it takes says nothing about where. */
|
||||
internal fun sameMark(given: String?, kept: String): Boolean {
|
||||
if (given == null || given.length != kept.length) return false
|
||||
var differs = 0
|
||||
for (i in kept.indices) differs = differs or (given[i].code xor kept[i].code)
|
||||
return differs == 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A question on its way from one sheet to the other -- the assistant's own sheet hands what was
|
||||
* typed or heard over the lock screen to [AssistActivity], which can ask Android to unlock. It
|
||||
* never travels in the intent: an intent's extras are whatever its sender says, and a question
|
||||
* found there would be asked on the account for any app that put it there. The question waits
|
||||
* here, in the app's own memory; the intent carries only the ticket, good once.
|
||||
*/
|
||||
object AssistHandOff {
|
||||
private var ticket: String? = null
|
||||
private var waiting: Held? = null
|
||||
|
||||
/** Leave [question] here; the ticket to put on the intent. */
|
||||
@Synchronized
|
||||
fun leave(question: Held): String {
|
||||
val made = ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
ticket = made
|
||||
waiting = question
|
||||
return made
|
||||
}
|
||||
|
||||
/** The question left under [given], once; nothing for any other ticket, or none. */
|
||||
@Synchronized
|
||||
fun take(given: String?): Held? {
|
||||
val kept = ticket ?: return null
|
||||
if (given == null || !OwnIntents.sameMark(given, kept)) return null
|
||||
val question = waiting
|
||||
ticket = null
|
||||
waiting = null
|
||||
return question
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,31 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioDeviceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioManager
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaPlayer
|
||||
import android.media.MediaRecorder
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresPermission
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -31,9 +46,22 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
private var record: AudioRecord? = null
|
||||
private var job: Job? = null
|
||||
private val pcm = ByteArrayOutputStream()
|
||||
private val _level = MutableStateFlow(0f)
|
||||
|
||||
/** How loud the last moment was, 0..1 (RMS of the samples): the sheet's meter and its ear for silence. */
|
||||
val level: StateFlow<Float> = _level.asStateFlow()
|
||||
|
||||
val recording: Boolean get() = record != null
|
||||
|
||||
/** What has been said so far, as a WAV file, without stopping: for words shown as they come. */
|
||||
fun snapshot(): ByteArray = pcm.toByteArray().let { if (it.isEmpty()) it else wav(it) }
|
||||
|
||||
/** How many seconds have been recorded. */
|
||||
val seconds: Float get() = pcm.size() / (RATE * 2f)
|
||||
|
||||
/** The microphone to prefer -- a headset's, while one is the route ([HeadsetRoute]). */
|
||||
var preferred: AudioDeviceInfo? = null
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
@@ -47,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
maxOf(min, RATE),
|
||||
)
|
||||
record = audio
|
||||
preferred?.let { audio.setPreferredDevice(it) }
|
||||
audio.startRecording()
|
||||
job = scope.launch(Dispatchers.IO) {
|
||||
val buffer = ByteArray(maxOf(min, 4096))
|
||||
@@ -54,6 +83,7 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
val read = audio.read(buffer, 0, buffer.size)
|
||||
if (read > 0) {
|
||||
pcm.write(buffer, 0, read)
|
||||
_level.value = rms(buffer, read)
|
||||
} else if (read < 0) {
|
||||
break
|
||||
}
|
||||
@@ -71,15 +101,44 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
job?.cancel()
|
||||
job?.join()
|
||||
audio.release()
|
||||
_level.value = 0f
|
||||
val body = pcm.toByteArray()
|
||||
pcm.reset()
|
||||
return if (body.isEmpty()) body else wav(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and keep nothing, at once and without a coroutine: for when the scope that would
|
||||
* run [stop] is already cancelled (the sheet is going), and the microphone must still be
|
||||
* let go.
|
||||
*/
|
||||
fun stopNow() {
|
||||
val audio = record ?: return
|
||||
record = null
|
||||
job?.cancel()
|
||||
// Stop returns the blocked `read`; the loop then sees it is cancelled, or reads an error.
|
||||
runCatching { audio.stop() }
|
||||
runCatching { audio.release() }
|
||||
_level.value = 0f
|
||||
pcm.reset()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
|
||||
|
||||
/** The loudness of [length] bytes of 16-bit little-endian samples, 0..1. */
|
||||
fun rms(buffer: ByteArray, length: Int): Float {
|
||||
val samples = length / 2
|
||||
if (samples == 0) return 0f
|
||||
var sum = 0.0
|
||||
for (i in 0 until samples) {
|
||||
val sample = ((buffer[i * 2 + 1].toInt() shl 8) or (buffer[i * 2].toInt() and 0xFF)).toShort() / 32768.0
|
||||
sum += sample * sample
|
||||
}
|
||||
return kotlin.math.sqrt(sum / samples).toFloat().coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
fun wav(pcm: ByteArray): ByteArray {
|
||||
val header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN).apply {
|
||||
put("RIFF".toByteArray())
|
||||
@@ -101,15 +160,21 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Speech out: the instance's text-to-speech, played once. */
|
||||
/** Speech out: the instance's text-to-speech, played once. [playing] is true while it speaks. */
|
||||
class Speaker(private val context: Context) {
|
||||
private var player: MediaPlayer? = null
|
||||
private val _playing = MutableStateFlow(false)
|
||||
val playing: StateFlow<Boolean> = _playing.asStateFlow()
|
||||
|
||||
private var ended: CompletableDeferred<Boolean>? = null
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
|
||||
}
|
||||
val done = CompletableDeferred<Boolean>()
|
||||
ended = done
|
||||
player = MediaPlayer().apply {
|
||||
setAudioAttributes(
|
||||
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
|
||||
@@ -120,10 +185,19 @@ class Speaker(private val context: Context) {
|
||||
it.release()
|
||||
file.delete()
|
||||
player = null
|
||||
_playing.value = false
|
||||
done.complete(true)
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
}
|
||||
_playing.value = true
|
||||
}
|
||||
|
||||
/** Play [mp3] and wait: true when it was heard to the end, false when it was stopped. */
|
||||
suspend fun playToEnd(mp3: ByteArray): Boolean {
|
||||
play(mp3)
|
||||
return ended?.await() ?: false
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
@@ -132,5 +206,189 @@ class Speaker(private val context: Context) {
|
||||
release()
|
||||
}
|
||||
player = null
|
||||
_playing.value = false
|
||||
ended?.complete(false)
|
||||
ended = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A headset's microphone for the assistant, while one is connected: a Bluetooth headset is
|
||||
* made the communication device (Android 12+), so the sheet hears the headset and answers into
|
||||
* it, as a call would; a wired headset's microphone is the default anyway. [release] gives the
|
||||
* route back. Nothing happens without a headset.
|
||||
*/
|
||||
class HeadsetRoute(context: Context) {
|
||||
private val audio = context.getSystemService(AudioManager::class.java)
|
||||
private var engaged = false
|
||||
|
||||
/** The headset's microphone, if there is one -- made the route first where that is needed. */
|
||||
fun microphone(): AudioDeviceInfo? {
|
||||
val inputs = audio?.getDevices(AudioManager.GET_DEVICES_INPUTS).orEmpty()
|
||||
val wired = inputs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
|
||||
if (wired != null) return wired
|
||||
if (Build.VERSION.SDK_INT < 31 || audio == null) return null
|
||||
val headset = audio.availableCommunicationDevices.firstOrNull {
|
||||
it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET
|
||||
} ?: return null
|
||||
if (!engaged) engaged = runCatching { audio.setCommunicationDevice(headset) }.getOrDefault(false)
|
||||
return inputs.firstOrNull { it.type == headset.type } ?: headset
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (engaged && Build.VERSION.SDK_INT >= 31) runCatching { audio?.clearCommunicationDevice() }
|
||||
engaged = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [heard] is the person ending a spoken conversation: one of [phrases] ("stop", "that's
|
||||
* all", in the app's language), alone or with a word or two around it ("stop please", "ok
|
||||
* that's all"). A longer sentence that happens to hold "stop" is a question, not an ending.
|
||||
*/
|
||||
fun isStopPhrase(heard: String, phrases: List<String>): Boolean {
|
||||
val said = words(heard)
|
||||
if (said.isEmpty()) return false
|
||||
return phrases.map(::words).filter { it.isNotEmpty() }.any { phrase ->
|
||||
said.size <= phrase.size + 2 && said.windowed(phrase.size).any { it == phrase }
|
||||
}
|
||||
}
|
||||
|
||||
private fun words(text: String): List<String> = text.lowercase()
|
||||
.replace(Regex("[\\u2019']"), "")
|
||||
.split(Regex("[^\\p{L}\\p{N}]+"))
|
||||
.filter { it.isNotBlank() }
|
||||
|
||||
/**
|
||||
* Speech in through the phone's own recogniser, for Settings › Voice input › Phone: words as
|
||||
* they are said ([start]'s `onPartial`), and the end of speech found by the recogniser.
|
||||
*
|
||||
* While LLeMbas is the digital assistant the *system's* default recogniser is LLeMbas's own
|
||||
* ([LembasRecognitionService]), so this never asks for the default: it takes the on-device
|
||||
* recogniser (Android 12+), else another installed app's. No Google library is linked; a
|
||||
* phone without any recogniser simply has none to offer ([available]).
|
||||
*/
|
||||
class PhoneRecognizer(private val context: Context) {
|
||||
private var recognizer: SpeechRecognizer? = null
|
||||
|
||||
/** [onActive]: a sign that somebody is speaking -- "speech began", or a loud level -- for a recogniser that shows no words meanwhile. */
|
||||
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit, onActive: () -> Unit = {}) {
|
||||
stop()
|
||||
startWith(onDevice(context), Heard(onPartial, onLevel, onResult, onFail, onActive))
|
||||
}
|
||||
|
||||
private class Heard(
|
||||
val onPartial: (String) -> Unit,
|
||||
val onLevel: (Float) -> Unit,
|
||||
val onResult: (String) -> Unit,
|
||||
val onFail: (Int) -> Unit,
|
||||
val onActive: () -> Unit,
|
||||
)
|
||||
|
||||
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
|
||||
private fun startWith(onDevice: Boolean, to: Heard) {
|
||||
val other = component(context)
|
||||
val made = when {
|
||||
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
|
||||
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
|
||||
else -> return to.onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
}
|
||||
recognizer = made
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) {}
|
||||
|
||||
override fun onBeginningOfSpeech() = to.onActive()
|
||||
|
||||
// About -2 dB in silence to 10 dB speaking: the meter's 0..1.
|
||||
override fun onRmsChanged(rmsdB: Float) {
|
||||
val level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f)
|
||||
to.onLevel(level)
|
||||
if (level >= LOUD) to.onActive()
|
||||
}
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = to.onLevel(0f)
|
||||
|
||||
override fun onError(error: Int) {
|
||||
// The on-device recogniser lacks this language: another app's may have it.
|
||||
if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) {
|
||||
stop()
|
||||
startWith(false, to)
|
||||
return
|
||||
}
|
||||
stop()
|
||||
to.onFail(error)
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
|
||||
stop()
|
||||
to.onResult(text)
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
|
||||
?.takeIf { it.isNotBlank() }?.let(to.onPartial)
|
||||
}
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
},
|
||||
)
|
||||
made.startListening(
|
||||
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
|
||||
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
|
||||
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
|
||||
// How long a silence ends it: a hint, which not every recogniser takes -- the
|
||||
// sheet keeps its own watch as well (phoneWatch).
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName),
|
||||
)
|
||||
}
|
||||
|
||||
/** Stop listening now; what was heard comes to `onResult`. */
|
||||
fun finish() {
|
||||
recognizer?.stopListening()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
recognizer?.runCatching {
|
||||
cancel()
|
||||
destroy()
|
||||
}
|
||||
recognizer = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
// SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED and ERROR_LANGUAGE_UNAVAILABLE (API 31).
|
||||
private const val LANGUAGE_NOT_SUPPORTED = 12
|
||||
private const val LANGUAGE_UNAVAILABLE = 13
|
||||
|
||||
/** Half of the meter: a level that is a voice, not a room. */
|
||||
private const val LOUD = 0.5f
|
||||
|
||||
private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
|
||||
|
||||
/** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */
|
||||
fun component(context: Context): ComponentName? = context.packageManager
|
||||
.queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0)
|
||||
.map { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) }
|
||||
.firstOrNull { it.packageName != context.packageName }
|
||||
|
||||
/** Whether this phone has a recogniser of its own to offer. */
|
||||
fun available(context: Context): Boolean = onDevice(context) || component(context) != null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Which recogniser Settings › Voice input means, for the assistant and the chat's microphone
|
||||
* alike: the phone's when it was chosen and the phone has one, or when the instance said it has
|
||||
* no speech-to-text ([instanceStt] false; null is "not known", which leaves the choice as set).
|
||||
*/
|
||||
fun usePhoneRecognizer(wanted: String, phoneHas: Boolean, instanceStt: Boolean?): Boolean = when {
|
||||
!phoneHas -> false
|
||||
wanted == Prefs.VOICE_PHONE -> true
|
||||
else -> instanceStt == false
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -66,9 +67,60 @@ private val INSTANCES = stringPreferencesKey("instances")
|
||||
private val ACTIVE = stringPreferencesKey("active")
|
||||
private val PREFS = stringPreferencesKey("prefs")
|
||||
|
||||
/** What the person chose in Settings, for this phone. */
|
||||
/**
|
||||
* What the person chose in Settings, for this phone. [language]: "" the account's language (the
|
||||
* default), "system" the phone's, or a language's code -- see [eu.llembas.android.AppLanguage].
|
||||
* [accountLanguage] is the account's language as the instance in use last said it.
|
||||
*
|
||||
* The assistant's: [voiceInput] `lembas` (the instance's speech-to-text) or `phone` (the phone's
|
||||
* recogniser); [assistantListens] whether it opens listening; [assistantModel] the model it
|
||||
* starts chats on ("" the account's default); and the last chat it made, which its sheet
|
||||
* offers to continue ([lastAssistChat], its first question, when).
|
||||
*/
|
||||
@Serializable
|
||||
data class Prefs(val theme: String = "", val assistantTemporary: Boolean = false, val readAloudSpoken: Boolean = true)
|
||||
data class Prefs(
|
||||
val theme: String = "",
|
||||
val assistantTemporary: Boolean = false,
|
||||
val readAloudSpoken: Boolean = true,
|
||||
val language: String = "",
|
||||
val accountLanguage: String = "",
|
||||
val voiceInput: String = VOICE_LEMBAS,
|
||||
val assistantListens: Boolean = true,
|
||||
/** After a spoken answer is read aloud, listen again: a spoken conversation. */
|
||||
val assistantConversation: Boolean = true,
|
||||
/** Listen for a wake word on the phone (WakeWordService). Off until the person turns it on. */
|
||||
val wakeWord: Boolean = false,
|
||||
/** Which of WakePhrases.all, as `greeting_name`; an id that is no phrase any more reads as the default. */
|
||||
val wakePhrase: String = "hey_assistant",
|
||||
/** WakeSensitivity's id: low, normal or high. */
|
||||
val wakeSensitivity: String = "normal",
|
||||
/** What happened the last times the wake word was heard (WakeLog): shown in Settings, nothing of the account in it. */
|
||||
val wakeLog: List<WakeAttempt> = emptyList(),
|
||||
/** Listen only while the screen is on. */
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
/** The assistant may read the notifications when asked (with Android's notification access). */
|
||||
val notificationSummaries: Boolean = false,
|
||||
/** Phone actions' navigation app: "" whichever is installed, "google", "osmand", or "ask". */
|
||||
val navApp: String = "",
|
||||
/** Ask OsmAnd for the phone's position and the route's destination (allowed inside OsmAnd first). */
|
||||
val osmandInfo: Boolean = false,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
val lastAssistAt: Long = 0,
|
||||
/** Settings › About: look for new versions (null: on in a beta, off in a release). */
|
||||
val updateCheck: Boolean? = null,
|
||||
/** ... and include betas (null: on in a beta, off in a release). */
|
||||
val updateBetas: Boolean? = null,
|
||||
val updateCheckedAt: Long = 0,
|
||||
/** The last version a notification announced, so it is announced once. */
|
||||
val updateNotified: String = "",
|
||||
) {
|
||||
companion object {
|
||||
const val VOICE_LEMBAS = "lembas"
|
||||
const val VOICE_PHONE = "phone"
|
||||
}
|
||||
}
|
||||
|
||||
class InstanceStore(private val context: Context) {
|
||||
private val listSerializer = ListSerializer(Instance.serializer())
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package eu.llembas.android.notify
|
||||
|
||||
/** One notification, as the question carries it. */
|
||||
data class Notice(val app: String, val title: String, val text: String, val at: Long)
|
||||
|
||||
/**
|
||||
* Notification summaries, the half every build has: how the notifications are written into a
|
||||
* question, and when a question asks for them. Reading them is [NotificationAccess]'s, which only
|
||||
* the `notifications` build can do.
|
||||
*/
|
||||
object NotificationReader {
|
||||
/** The notifications as the question's attachment of text: one block per notification. */
|
||||
fun asText(notices: List<Notice>, now: Long = System.currentTimeMillis()): String = notices.joinToString("\n\n") { n ->
|
||||
val minutes = ((now - n.at) / 60_000).coerceAtLeast(0)
|
||||
val ago = if (minutes < 60) "${minutes}m ago" else "${minutes / 60}h ago"
|
||||
listOf("[${n.app} · $ago] ${n.title}".trim(), n.text).filter { it.isNotBlank() }.joinToString("\n")
|
||||
}.take(MAX_CHARS)
|
||||
|
||||
/**
|
||||
* Whether a question asks about the notifications: one of [phrases] (in the app's language,
|
||||
* "my notifications" and the like) is in it.
|
||||
*/
|
||||
fun asksAbout(question: String, phrases: List<String>): Boolean {
|
||||
val q = question.lowercase()
|
||||
return phrases.map { it.trim().lowercase() }.any { it.isNotEmpty() && it in q }
|
||||
}
|
||||
|
||||
private const val MAX_CHARS = 12_000
|
||||
}
|
||||
@@ -17,6 +17,7 @@ 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.api.safeId
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -98,19 +99,22 @@ object Notifications {
|
||||
const val EXTRA_CHAT = "eu.llembas.android.CHAT"
|
||||
const val EXTRA_INSTANCE = "eu.llembas.android.INSTANCE"
|
||||
|
||||
const val EXTRA_SCHEDULE = "eu.llembas.android.SCHEDULE"
|
||||
const val EXTRA_RUN = "eu.llembas.android.RUN"
|
||||
const val EXTRA_REPORT = "eu.llembas.android.REPORT"
|
||||
|
||||
/** Whether [kind] is about a chat: a finished reply (which older payloads leave unnamed) or a question or an approval. */
|
||||
fun chatKind(kind: String): Boolean = kind == "" || kind == "reply" || kind == "ask"
|
||||
|
||||
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/") }
|
||||
if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload)
|
||||
if (payload.kind == ReportNotice.KIND) return report(context, instance, payload)
|
||||
// A kind this app does not know -- a newer server's -- is not guessed at: no notification.
|
||||
if (!chatKind(payload.kind)) return
|
||||
val chatId = safeId(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 open = opener(context, instance, id, chatId = chatId)
|
||||
val channel = when (payload.kind) {
|
||||
"ask" -> LembasApp.CHANNEL_ASKS
|
||||
else -> LembasApp.CHANNEL_REPLIES
|
||||
@@ -126,14 +130,152 @@ object Notifications {
|
||||
// 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.
|
||||
// need the card itself, so they stay in the app. Either answer asks for the phone to be
|
||||
// unlocked first (Android 12+): a locked phone in somebody else's hand must not say yes
|
||||
// to a command -- nor no to a run that waits on it, a scheduled one included.
|
||||
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))
|
||||
builder.addAction(unlocked(context.getString(R.string.card_allow_once), answer(context, instance, chatId, payload.interactionId, "allow", id)))
|
||||
builder.addAction(unlocked(context.getString(R.string.card_deny), answer(context, instance, chatId, payload.interactionId, "deny", id)))
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(id, builder.build())
|
||||
}
|
||||
|
||||
/**
|
||||
* A scheduled run's result or failure, on its own channel, built from the server's payload
|
||||
* alone ([ScheduledNotice]). Unlocked: the task's name and the result's first lines, as the
|
||||
* server cut them (BigTextStyle opens them). On the lock screen only the public version: the
|
||||
* app's name and "A scheduled task has a result." (or failed) -- nothing from the account, so
|
||||
* the server's `public` (which names the task) is not used. A tap and Open go to the run;
|
||||
* Run again starts it again, once the phone is unlocked; Pause is there when offered.
|
||||
*/
|
||||
private fun scheduled(context: Context, instance: String, payload: PushPayload) {
|
||||
val notice = ScheduledNotice.from(payload) ?: return
|
||||
val channel = if (notice.failed) LembasApp.CHANNEL_SCHEDULED_FAILURES else LembasApp.CHANNEL_SCHEDULED
|
||||
val fixed = context.getString(if (notice.failed) R.string.scheduled_failed_public else R.string.scheduled_result_public)
|
||||
val open = opener(context, instance, notice.id, chatId = null, scheduleId = notice.scheduleId, runId = notice.runId)
|
||||
// The lock screen gets nothing from the account (Working-notes rule 5): the app's name
|
||||
// and a fixed sentence, never the task's name the server offers in `public`.
|
||||
val public = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.app_name))
|
||||
.setContentText(fixed)
|
||||
.build()
|
||||
val title = notice.title.ifBlank { payload.title.ifBlank { context.getString(R.string.scheduled) } }
|
||||
val body = notice.body.ifBlank { payload.body.ifBlank { fixed } }
|
||||
val builder = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(title)
|
||||
.setContentText(body)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(if (notice.failed) Notification.CATEGORY_ERROR else Notification.CATEGORY_STATUS)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
.setPublicVersion(public)
|
||||
if (notice.open) builder.addAction(0, notice.label("open", context.getString(R.string.viewer_open)), open)
|
||||
if (notice.runAgain) {
|
||||
val again = scheduleAction(context, instance, notice.scheduleId, notice.id, ScheduleActionReceiver.RUN_AGAIN)
|
||||
builder.addAction(unlocked(notice.label("run_again", context.getString(R.string.schedule_run_again)), again))
|
||||
}
|
||||
if (notice.pause) {
|
||||
val pause = scheduleAction(context, instance, notice.scheduleId, notice.id, ScheduleActionReceiver.PAUSE)
|
||||
builder.addAction(0, notice.label("pause", context.getString(R.string.schedule_pause)), pause)
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(notice.id, builder.build())
|
||||
}
|
||||
|
||||
/**
|
||||
* A report was filed (spec 3.8.0): what a scheduled task has to tell, on the Reports channel.
|
||||
* Unlocked: the report's title and its summary. On the lock screen only the public version:
|
||||
* the app's name and "New report" -- nothing from the account (Working-notes rule 5). A tap
|
||||
* and Open go to the report; Mark read marks it, once the phone is unlocked. A run that
|
||||
* filed no report sends nothing, so there is nothing to show for it; a failed run still has
|
||||
* its own notification ([scheduled]).
|
||||
*/
|
||||
private fun report(context: Context, instance: String, payload: PushPayload) {
|
||||
val notice = ReportNotice.from(payload) ?: return
|
||||
NotificationManagerCompat.from(context).notify(notice.id, reportNotification(context, instance, notice))
|
||||
}
|
||||
|
||||
/** The report's notification, apart from posting it, so a test can read both of its faces. */
|
||||
fun reportNotification(context: Context, instance: String, notice: ReportNotice): Notification {
|
||||
val fixed = context.getString(R.string.report_new_public)
|
||||
val open = opener(context, instance, notice.id, chatId = null, reportId = notice.reportId)
|
||||
// A report the model called important goes on a channel of its own that may come up over
|
||||
// what is on screen: on Android 8 and later the channel decides that, not the notification.
|
||||
val channel = if (notice.high) LembasApp.CHANNEL_REPORTS_HIGH else LembasApp.CHANNEL_REPORTS
|
||||
val public = NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.app_name))
|
||||
.setContentText(fixed)
|
||||
.build()
|
||||
val read = PendingIntent.getBroadcast(
|
||||
context,
|
||||
("read" + notice.reportId).hashCode(),
|
||||
Intent(context, ReportActionReceiver::class.java)
|
||||
.putExtra("instance", instance)
|
||||
.putExtra("report", notice.reportId)
|
||||
.putExtra("notification", notice.id),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
return NotificationCompat.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(notice.title.ifBlank { fixed })
|
||||
.setContentText(notice.summary)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(notice.summary))
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(open)
|
||||
.setCategory(Notification.CATEGORY_STATUS)
|
||||
.setPriority(if (notice.high) NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||
.setPublicVersion(public)
|
||||
.addAction(0, context.getString(R.string.viewer_open), open)
|
||||
.addAction(unlocked(context.getString(R.string.report_mark_read), read))
|
||||
.build()
|
||||
}
|
||||
|
||||
/** The report was read or deleted in the app: its notification has nothing left to say. */
|
||||
fun reportSeen(context: Context, reportId: String) {
|
||||
NotificationManagerCompat.from(context).cancel(ReportNotice.notificationId(reportId))
|
||||
}
|
||||
|
||||
/** A notification action Android runs only once the phone is unlocked. */
|
||||
private fun unlocked(title: String, intent: PendingIntent): NotificationCompat.Action =
|
||||
NotificationCompat.Action.Builder(0, title, intent).setAuthenticationRequired(true).build()
|
||||
|
||||
private fun opener(
|
||||
context: Context,
|
||||
instance: String,
|
||||
id: Int,
|
||||
chatId: String?,
|
||||
scheduleId: String? = null,
|
||||
runId: String? = null,
|
||||
reportId: String? = null,
|
||||
): PendingIntent = 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_SCHEDULE, scheduleId)
|
||||
.putExtra(EXTRA_RUN, runId)
|
||||
.putExtra(EXTRA_REPORT, reportId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun scheduleAction(context: Context, instance: String, schedule: String, notification: Int, action: String): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
(action + schedule).hashCode(),
|
||||
Intent(context, ScheduleActionReceiver::class.java)
|
||||
.putExtra("instance", instance)
|
||||
.putExtra("schedule", schedule)
|
||||
.putExtra("action", action)
|
||||
.putExtra("notification", notification),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun answer(context: Context, instance: String, chat: String, card: String, verdict: String, notification: Int): PendingIntent =
|
||||
PendingIntent.getBroadcast(
|
||||
context,
|
||||
@@ -170,3 +312,49 @@ class CardActionReceiver : BroadcastReceiver() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A report's Mark read, from its notification. */
|
||||
class ReportActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
val instance = intent.getStringExtra("instance") ?: return pending.finish()
|
||||
val report = intent.getStringExtra("report") ?: return pending.finish()
|
||||
background.launch {
|
||||
try {
|
||||
// A report that is gone is as good as read; the notification goes either way.
|
||||
Push.instance(context, instance)?.let { found -> runCatching { context.lembas.instances.clientFor(found).readReport(report) } }
|
||||
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A scheduled task's Pause or Run again, from its notification. */
|
||||
class ScheduleActionReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
val pending = goAsync()
|
||||
val instance = intent.getStringExtra("instance") ?: return pending.finish()
|
||||
val schedule = intent.getStringExtra("schedule") ?: return pending.finish()
|
||||
val action = intent.getStringExtra("action") ?: PAUSE
|
||||
background.launch {
|
||||
try {
|
||||
Push.instance(context, instance)?.let { found ->
|
||||
val client = context.lembas.instances.clientFor(found)
|
||||
// A failure (gone, busy) is the server's to say on the run page; the
|
||||
// notification goes either way, and a new run sends its own.
|
||||
runCatching { if (action == RUN_AGAIN) client.runScheduleNow(schedule) else client.pauseSchedule(schedule, true) }
|
||||
}
|
||||
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PAUSE = "pause"
|
||||
const val RUN_AGAIN = "run_again"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.safeId
|
||||
|
||||
/**
|
||||
* What a filed report's push asks the app to show (harness spec 3.8.0, `reports.md` §4:
|
||||
* notifications come from the report, not from the run). [title] and [summary] are a model's
|
||||
* words about the person's own things: for an unlocked phone only. The lock screen gets the
|
||||
* app's fixed words and nothing else. A payload without the id falls back to its `url`
|
||||
* (`/reports/{id}`), as a browser would open it.
|
||||
*/
|
||||
data class ReportNotice(val reportId: String, val title: String, val summary: String, val high: Boolean) {
|
||||
/** One notification per report: a later push about the same report replaces it. */
|
||||
val id: Int get() = notificationId(reportId)
|
||||
|
||||
companion object {
|
||||
const val KIND = "report"
|
||||
|
||||
/** The notification of the report with this id: what is cancelled once the report is read or deleted in the app. */
|
||||
fun notificationId(reportId: String): Int = "report:$reportId".hashCode()
|
||||
|
||||
fun from(payload: PushPayload): ReportNotice? {
|
||||
if (payload.kind != KIND) return null
|
||||
// Only an id that looks like one: it becomes part of a route and of an address.
|
||||
val id = safeId(payload.reportId?.takeIf { it.isNotBlank() } ?: fromUrl(payload.url)) ?: return null
|
||||
// The report's own words are in the payload's `notification` (the payload's top is
|
||||
// what an older client would show: the app's name and "New report"). A payload
|
||||
// without one is read by its top.
|
||||
val words = payload.notification
|
||||
return ReportNotice(
|
||||
reportId = id,
|
||||
title = words?.title ?: payload.title,
|
||||
summary = words?.body ?: payload.body,
|
||||
high = (words?.importance?.ifBlank { null } ?: payload.importance) == "high",
|
||||
)
|
||||
}
|
||||
|
||||
/** `/reports/{id}` → the id; null for anything else. */
|
||||
fun fromUrl(url: String): String? {
|
||||
if (!url.startsWith("/reports/")) return null
|
||||
return url.removePrefix("/reports/").substringBefore('?').substringBefore('/').takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.safeId
|
||||
|
||||
/**
|
||||
* What a scheduled run's push asks the app to show, read from the server's payload alone
|
||||
* (services/schedule/notify.py `payload`): the schedule and the run it is about, whether it
|
||||
* failed, the actions the server offers, and -- from a server that sends its `notification` --
|
||||
* the words: [title] and [body] (the result's first lines) for an unlocked phone, and the
|
||||
* actions' [labels]. [publicTitle] / [publicBody] are read but not shown: they name the task,
|
||||
* and the lock screen gets nothing from the account. A payload without ids falls back to its `url` (`/scheduled/{schedule}?run={run}`),
|
||||
* as a browser would open it.
|
||||
*/
|
||||
data class ScheduledNotice(
|
||||
val scheduleId: String,
|
||||
val runId: String?,
|
||||
val failed: Boolean,
|
||||
/** The server asks whether to pause it (it failed several times in a row). */
|
||||
val askPause: Boolean,
|
||||
val open: Boolean,
|
||||
val pause: Boolean,
|
||||
val runAgain: Boolean = false,
|
||||
/** Empty when the server sent no `notification`: the app's fixed sentences are used then. */
|
||||
val title: String = "",
|
||||
val body: String = "",
|
||||
val publicTitle: String = "",
|
||||
val publicBody: String = "",
|
||||
val labels: Map<String, String> = emptyMap(),
|
||||
) {
|
||||
/** One notification per run: a later push about the same run replaces it. */
|
||||
val id: Int get() = "scheduled:${runId ?: scheduleId}".hashCode()
|
||||
|
||||
/** The server's label for [action] in the owner's language, or [fallback]. */
|
||||
fun label(action: String, fallback: String): String = labels[action]?.takeIf { it.isNotBlank() } ?: fallback
|
||||
|
||||
companion object {
|
||||
const val KIND_RESULT = "schedule"
|
||||
const val KIND_FAILED = "schedule_failed"
|
||||
|
||||
fun from(payload: PushPayload): ScheduledNotice? {
|
||||
if (payload.kind != KIND_RESULT && payload.kind != KIND_FAILED) return null
|
||||
val (urlSchedule, urlRun) = fromUrl(payload.url)
|
||||
// Only ids that look like ids: they become parts of a route and of an address.
|
||||
val schedule = safeId(payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule) ?: return null
|
||||
val run = safeId(payload.runId?.takeIf { it.isNotBlank() } ?: urlRun)
|
||||
val failed = payload.kind == KIND_FAILED
|
||||
val words = payload.notification
|
||||
val ask = words?.ask?.takeIf { it.isNotBlank() } ?: payload.ask
|
||||
val askPause = ask == "pause"
|
||||
// The notification's own actions first; an older payload named none: Open always,
|
||||
// Pause for a failure.
|
||||
val actions = words?.actions?.takeIf { it.isNotEmpty() }
|
||||
?: payload.actions.ifEmpty { if (failed) listOf("open", "pause") else listOf("open") }
|
||||
return ScheduledNotice(
|
||||
scheduleId = schedule,
|
||||
runId = run,
|
||||
failed = failed,
|
||||
askPause = askPause,
|
||||
open = "open" in actions,
|
||||
pause = "pause" in actions || askPause,
|
||||
runAgain = "run_again" in actions,
|
||||
title = words?.title.orEmpty(),
|
||||
body = words?.body.orEmpty(),
|
||||
publicTitle = words?.public?.title.orEmpty(),
|
||||
publicBody = words?.public?.body.orEmpty(),
|
||||
labels = words?.labels.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** `/scheduled/{schedule}?run={run}` → the two ids; nulls for anything else. */
|
||||
fun fromUrl(url: String): Pair<String?, String?> {
|
||||
if (!url.startsWith("/scheduled/")) return null to null
|
||||
val rest = url.removePrefix("/scheduled/")
|
||||
val schedule = rest.substringBefore('?').substringBefore('/').takeIf { it.isNotBlank() }
|
||||
val run = rest.substringAfter('?', "").split('&').firstOrNull { it.startsWith("run=") }?.removePrefix("run=")?.takeIf { it.isNotBlank() }
|
||||
return schedule to run
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,110 +1,142 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Context
|
||||
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.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
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.
|
||||
* "Ask LLeMbas" in any app's share menu: text, a link, a picture or files. A sheet over the app
|
||||
* it came from says what came in, takes a line of what to do with it, and sends it to a new chat
|
||||
* or to the last chat the assistant made; files are uploaded first and bound to that message, as
|
||||
* the composer's are. The chat then opens in the app. A new chat made here becomes the
|
||||
* assistant's last chat, so the next share can follow it.
|
||||
*/
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private val failure = mutableStateOf<String?>(null)
|
||||
class ShareActivity :
|
||||
ComponentActivity(),
|
||||
ShareActions {
|
||||
private val state = MutableStateFlow(ShareState())
|
||||
private var uris: List<Uri> = emptyList()
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
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 text = listOfNotNull(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString())
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.joinToString("\n\n")
|
||||
.trim()
|
||||
state.update { it.copy(text = text, files = uris.map { uri -> SharedFile(nameOf(uri), (contentResolver.getType(uri) ?: "").startsWith("image/")) }) }
|
||||
lifecycleScope.launch {
|
||||
val store = lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
state.update {
|
||||
it.copy(
|
||||
signedIn = store.current() != null,
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
}
|
||||
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)) }
|
||||
}
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val shown by state.collectAsState()
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel() = finish()
|
||||
|
||||
override fun send(ask: String, toLast: Boolean) {
|
||||
if (state.value.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val store = lembas.instances
|
||||
val api = store.client() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
val now = state.value
|
||||
val into = if (toLast) now.last?.chatId else null
|
||||
val files = uris.map { uri ->
|
||||
val bytes = withContext(Dispatchers.IO) { contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) }
|
||||
api.upload(nameOf(uri), contentResolver.getType(uri) ?: "application/octet-stream", bytes, into).id
|
||||
}
|
||||
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
|
||||
val chatId = if (into != null) {
|
||||
api.sendMessage(into, message, files)
|
||||
into
|
||||
} else {
|
||||
val prefs = store.prefs.first()
|
||||
// The assistant's model while the instance still has it; a model that is
|
||||
// gone is not asked for (the instance's default answers instead).
|
||||
val chosen = prefs.assistantModel
|
||||
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true
|
||||
val made = api.createChat(message, files, model = chosen.takeIf { it.isNotBlank() && !gone })
|
||||
store.savePrefs {
|
||||
it.copy(
|
||||
lastAssistChat = made.chat.id,
|
||||
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
|
||||
lastAssistAt = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
made.chat.id
|
||||
}
|
||||
startActivity(
|
||||
Intent(this@ShareActivity, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, chatId),
|
||||
)
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
// The last chat deleted since: it is not offered again.
|
||||
if (e is ApiException && e.status == 404 && toLast) {
|
||||
lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
state.update { it.copy(last = null) }
|
||||
}
|
||||
state.update { it.copy(sending = false, error = explain(e)) }
|
||||
}
|
||||
}
|
||||
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 = explain(e)
|
||||
}
|
||||
}
|
||||
private fun nameOf(uri: Uri): String = runCatching {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
}.getOrNull() ?: uri.lastPathSegment ?: "shared"
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
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.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
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.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** One shared file, as the sheet names it. */
|
||||
data class SharedFile(val name: String, val image: Boolean)
|
||||
|
||||
/** What was shared, where it may go, and how sending it went. */
|
||||
data class ShareState(
|
||||
val signedIn: Boolean = true,
|
||||
val text: String = "",
|
||||
val files: List<SharedFile> = emptyList(),
|
||||
/** The last chat the assistant made, offered as the other place to send it. */
|
||||
val last: LastAssist? = null,
|
||||
val sending: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** What the share sheet can do; nothing by default, for the screenshot tests. */
|
||||
interface ShareActions {
|
||||
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
|
||||
fun send(ask: String, toLast: Boolean) {}
|
||||
|
||||
fun cancel() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, or the
|
||||
* last chat the assistant made -- and Send. Rows of unknown height stack; the two choices are
|
||||
* whole-row tap targets of at least 56 dp.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var ask by remember { mutableStateOf("") }
|
||||
var toLast by remember { mutableStateOf(false) }
|
||||
val last = state.last
|
||||
|
||||
Column(handle.fillMaxWidth()) {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {
|
||||
Box(Modifier.size(width = 36.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp)))
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.share_label),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
|
||||
)
|
||||
if (state.sending) {
|
||||
val bar = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp)
|
||||
if (LocalInspectionMode.current) LinearProgressIndicator(progress = { 0.4f }, modifier = bar) else LinearProgressIndicator(bar)
|
||||
}
|
||||
}
|
||||
|
||||
if (!state.signedIn) {
|
||||
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.Center) {
|
||||
Text(stringResource(R.string.assist_signed_out), style = MaterialTheme.typography.bodyLarge)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(
|
||||
Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
// What came in.
|
||||
if (state.text.isNotBlank()) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
state.text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 6,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
state.files.forEach { file ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
if (file.image) Icons.Filled.Image else Icons.AutoMirrored.Filled.InsertDriveFile,
|
||||
contentDescription = null,
|
||||
tint = palette.accent,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(file.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
// What to do with it.
|
||||
TextField(
|
||||
value = ask,
|
||||
onValueChange = { ask = it },
|
||||
placeholder = { Text(stringResource(R.string.share_ask_hint)) },
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = palette.surfaceRaised,
|
||||
unfocusedContainerColor = palette.surfaceRaised,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
enabled = !state.sending,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
|
||||
// Where it goes.
|
||||
if (last != null) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast, enabled = !state.sending) { toLast = false }
|
||||
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
|
||||
toLast =
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 12.dp, end = 16.dp, top = 4.dp, bottom = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.sending) R.string.share_sending else R.string.send)) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Destination(icon: ImageVector, title: String, detail: String?, selected: Boolean, enabled: Boolean, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.selectable(selected = selected, enabled = enabled, role = Role.RadioButton, onClick = onClick)
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(icon, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
detail?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
RadioButton(selected = selected, onClick = null, enabled = enabled)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The message a share sends: the person's own words (or the default request) first, then what was
|
||||
* shared, so the model reads the request before the material.
|
||||
*/
|
||||
fun shareMessage(ask: String, shared: String, fallback: String): String {
|
||||
val request = ask.trim().ifBlank { fallback }
|
||||
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.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.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.DirectoryEntry
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Choosing a folder on a linked computer: the last listing the device gave ([listing]; null
|
||||
* before the first, or where there never was one), the path in the field ([typed]: where the
|
||||
* walk is, or what the person wrote -- the way in that always works), and the sentence for a
|
||||
* listing that could not be had, or that came with one ([error]). [edited]: the person wrote in
|
||||
* the field since the device was last asked, so its answer does not write over them.
|
||||
* [failed]: the last question got no listing.
|
||||
*/
|
||||
data class PickerState(
|
||||
val listing: DeviceDirectory? = null,
|
||||
val loading: Boolean = false,
|
||||
val typed: String = "",
|
||||
val error: String? = null,
|
||||
val edited: Boolean = false,
|
||||
val failed: Boolean = false,
|
||||
)
|
||||
|
||||
/** The most subdirectories shown; a device that names more is cut there. */
|
||||
const val PICKER_ENTRIES = 500
|
||||
|
||||
/** The longest a device's own words are kept: a name, a reason, a sentence. */
|
||||
const val PICKER_WORDS = 300
|
||||
|
||||
private fun String.kept(): String = if (length > PICKER_WORDS) take(PICKER_WORDS) + "…" else this
|
||||
|
||||
/**
|
||||
* A listing as the picker holds it: each path once (the rows are keyed by it), at most
|
||||
* [PICKER_ENTRIES] of them, and the device's words -- names, reasons, a model's name -- cut to
|
||||
* a length that cannot push the controls away.
|
||||
*/
|
||||
fun DeviceDirectory.bounded(): DeviceDirectory = copy(
|
||||
reason = reason.kept(),
|
||||
error = error.kept(),
|
||||
model = model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) },
|
||||
entries = entries.filter { it.path.isNotEmpty() }.distinctBy { it.path }.take(PICKER_ENTRIES).map { entry ->
|
||||
entry.copy(name = entry.name.kept(), reason = entry.reason.kept(), model = entry.model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) })
|
||||
},
|
||||
)
|
||||
|
||||
/** The device is being asked: what is typed from now on is the person's, newer than the answer. */
|
||||
fun PickerState.asking(): PickerState = copy(loading = true, error = null, edited = false)
|
||||
|
||||
/**
|
||||
* The device's answer. A listing is shown ([bounded]) and the field follows it -- unless the
|
||||
* person wrote in the field while the device was answering, or the listing is the places,
|
||||
* which have no path: then the field keeps what it has. A listing may come with a sentence
|
||||
* (part of it could not be read): it is shown with it. No listing -- the device is away, too
|
||||
* old, silent or said no -- leaves the last listing and the typed path where they were, with
|
||||
* the server's sentence ([fallback] where it sent none).
|
||||
*/
|
||||
fun PickerState.took(answer: DeviceDirectory, fallback: String = ""): PickerState = when {
|
||||
answer.listed -> copy(
|
||||
listing = answer.bounded(),
|
||||
loading = false,
|
||||
failed = false,
|
||||
error = answer.error.kept().ifBlank { null },
|
||||
typed = if (edited) typed else answer.path.ifEmpty { typed },
|
||||
)
|
||||
|
||||
else -> copy(loading = false, failed = true, error = answer.error.kept().ifBlank { fallback })
|
||||
}
|
||||
|
||||
/** The device could not be asked at all ([said]: why): as an answer without a listing. */
|
||||
fun PickerState.unanswered(said: String): PickerState = copy(loading = false, failed = true, error = said.kept())
|
||||
|
||||
/**
|
||||
* Where "up" leads from the listing shown: the parent, the places (`""`) from a directory that
|
||||
* has none, or null at the places themselves and where nothing is listed -- there the picker
|
||||
* closes instead.
|
||||
*/
|
||||
val PickerState.up: String?
|
||||
get() = listing?.takeIf { !it.places }?.parent
|
||||
|
||||
/**
|
||||
* Where Back leads: up a level, or null to close -- at the top, and after a question that got
|
||||
* no listing (the device went away mid-walk), where "up" would only ask it again for ever.
|
||||
*/
|
||||
val PickerState.back: String?
|
||||
get() = if (failed) null else up
|
||||
|
||||
/**
|
||||
* Whether the path in the field may be chosen: something is written, and it is not the listed
|
||||
* directory the device said it would open no session in. A path the device was never asked
|
||||
* about may be chosen: the instance checks it when it is used.
|
||||
*/
|
||||
val PickerState.canChoose: Boolean
|
||||
get() = typed.isNotBlank() && !refusedHere
|
||||
|
||||
/** The field holds the listed directory, and the device will not open a session there. */
|
||||
val PickerState.refusedHere: Boolean
|
||||
get() = listing?.let { !it.places && !it.accepted && it.path == typed.trim() } == true
|
||||
|
||||
interface PickerActions {
|
||||
fun open(path: String) {}
|
||||
fun typed(text: String) {}
|
||||
fun choose() {}
|
||||
fun back() {}
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory picker over whatever asked for it: [load] asks the device for a path (`""`:
|
||||
* its places), [onPick] is given the chosen path. It opens at [initial], or at the places.
|
||||
* Back goes up a level, and closes at the top.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> DeviceDirectory, onPick: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(PickerState(typed = initial.trim(), loading = true)) }
|
||||
var reading by remember { mutableStateOf<Job?>(null) }
|
||||
val fallback = stringResource(R.string.directory_no_listing)
|
||||
val read: (String) -> Unit = { path ->
|
||||
reading?.cancel()
|
||||
state = state.asking()
|
||||
reading = scope.launch {
|
||||
try {
|
||||
val answer = load(path)
|
||||
// Applied to the state as it is now: `took` leaves what was typed meanwhile.
|
||||
state = state.took(answer, fallback)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.unanswered(context.explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { read(initial.trim()) }
|
||||
val actions = object : PickerActions {
|
||||
override fun open(path: String) = read(path)
|
||||
|
||||
override fun typed(text: String) {
|
||||
state = state.copy(typed = text, edited = true)
|
||||
}
|
||||
|
||||
override fun choose() {
|
||||
if (state.canChoose) onPick(state.typed.trim())
|
||||
}
|
||||
|
||||
override fun back() {
|
||||
val up = state.back
|
||||
if (up == null) onDismiss() else read(up)
|
||||
}
|
||||
|
||||
override fun close() = onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = actions::back, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
DirectoryPickerContent(title, state, actions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker, drawn from its state: where the walk is, the model last used there, the
|
||||
* subdirectories (a row is 56 dp; its name gives, the model beside it keeps to a third), and at
|
||||
* the foot the path as text with Choose -- which is all there is when the device lists nothing.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPickerContent(title: String, state: PickerState, actions: PickerActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val listing = state.listing
|
||||
Surface(color = palette.bg, contentColor = palette.ink, modifier = modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
Text(title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(horizontal = 12.dp).size(20.dp))
|
||||
IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) }
|
||||
}
|
||||
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
listing?.path?.ifEmpty { null } ?: stringResource(R.string.directory_places),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontFamily = if (listing?.places == false) FontFamily.Monospace else null,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
listing?.model?.let {
|
||||
Text(
|
||||
stringResource(R.string.directory_last_used, it.label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (listing != null && !listing.places && !listing.accepted) {
|
||||
Text(
|
||||
listing.reason.ifBlank { stringResource(R.string.directory_refused) },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxWidth().weight(1f).padding(top = 8.dp)) {
|
||||
// The way out of a directory, and -- where nothing is listed -- the way to the places.
|
||||
if (listing?.places != true) {
|
||||
item(key = "up") {
|
||||
val places = listing == null || listing.parent.isEmpty()
|
||||
EntryRow(
|
||||
name = stringResource(if (places) R.string.directory_all_places else R.string.directory_up),
|
||||
icon = { Icon(Icons.Filled.ArrowUpward, contentDescription = null, tint = palette.inkMuted) },
|
||||
onClick = { actions.open(listing?.parent.orEmpty()) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (listing != null && listing.entries.isEmpty() && !state.loading) {
|
||||
item(key = "empty") {
|
||||
Text(
|
||||
stringResource(if (listing.places) R.string.directory_no_places else R.string.directory_empty),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(listing?.entries.orEmpty(), key = { "d:" + it.path }) { entry -> Entry(entry, onOpen = { actions.open(entry.path) }) }
|
||||
}
|
||||
HorizontalDivider(color = palette.border)
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
value = state.typed,
|
||||
onValueChange = actions::typed,
|
||||
singleLine = true,
|
||||
label = { Text(stringResource(R.string.directory_path)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = actions::close, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Button(onClick = actions::choose, enabled = state.canChoose, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.directory_choose))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A subdirectory: its name, why no session opens in it where none does, and the model last used in it. */
|
||||
@Composable
|
||||
private fun Entry(entry: DirectoryEntry, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
EntryRow(
|
||||
name = entry.name.ifBlank { entry.path },
|
||||
note = if (entry.accepted) null else entry.reason.ifBlank { stringResource(R.string.directory_not_trusted) },
|
||||
model = entry.model?.label,
|
||||
icon = {
|
||||
Icon(
|
||||
if (entry.accepted) Icons.Filled.Folder else Icons.Filled.FolderOff,
|
||||
contentDescription = null,
|
||||
tint = if (entry.accepted) palette.accent else palette.inkFaint,
|
||||
)
|
||||
},
|
||||
onClick = onOpen,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(name: String, icon: @Composable () -> Unit, onClick: () -> Unit, note: String? = null, model: String? = null) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { icon() }
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
note?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) }
|
||||
}
|
||||
model?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = 120.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
|
||||
/**
|
||||
* Syntax highlighting for code that is only read: the file viewer and a reply's code blocks.
|
||||
*
|
||||
* A small scanner of the app's own, not a library: what it has to tell apart is few -- comments,
|
||||
* strings, numbers, keywords, type names, and a markup language's tags -- and a highlighter that
|
||||
* is a parser of its own (Prism4j, which needs an annotation processor and has not moved since
|
||||
* 2019; or a WebView, which the app does not have) would be more to trust than the result is worth.
|
||||
* It never runs anything and never fails: a language it does not know, or text it does not
|
||||
* follow, is simply drawn plain. The colours are the theme's tokens, so it follows Shire and
|
||||
* Moria like everything else.
|
||||
*
|
||||
* The languages are the server's (`show`'s `language`, from the file's extension) and a fence's
|
||||
* info string in a reply (```kotlin), with the usual short names.
|
||||
*/
|
||||
enum class TokenKind { Comment, Text, Number, Keyword, Type, Tag, Attribute }
|
||||
|
||||
data class Token(val start: Int, val end: Int, val kind: TokenKind)
|
||||
|
||||
/** How one language is read: the scanner's few settings. */
|
||||
private data class Spec(
|
||||
val keywords: Set<String> = emptySet(),
|
||||
val lineComments: List<String> = emptyList(),
|
||||
val blockComments: List<Pair<String, String>> = emptyList(),
|
||||
/** String delimiters, longest first (""" before "). */
|
||||
val strings: List<String> = listOf("\"", "'"),
|
||||
val ignoreCase: Boolean = false,
|
||||
/** A capitalised identifier is a type (Kotlin, Java, Swift, Rust...). */
|
||||
val capitalisedTypes: Boolean = false,
|
||||
/** `<tag attr="...">`: markup (XML, HTML, Vue and Svelte templates). */
|
||||
val markup: Boolean = false,
|
||||
/** `key:` / `key =` at a line's start is the key (YAML, TOML). */
|
||||
val keys: Boolean = false,
|
||||
/** `$name` / `${...}` variables (shells, PHP). */
|
||||
val dollarVariables: Boolean = false,
|
||||
)
|
||||
|
||||
private fun words(text: String): Set<String> = text.split(' ').filter { it.isNotBlank() }.toSet()
|
||||
|
||||
private val C_FAMILY = words(
|
||||
"if else for while do switch case default break continue return goto sizeof typedef struct union enum " +
|
||||
"static const extern volatile register inline void char short int long float double signed unsigned " +
|
||||
"auto true false NULL nullptr",
|
||||
)
|
||||
private val CPP = C_FAMILY + words(
|
||||
"class namespace template typename public private protected virtual override final new delete this " +
|
||||
"using operator friend explicit constexpr noexcept try catch throw bool std",
|
||||
)
|
||||
private val JAVA = words(
|
||||
"abstract assert boolean break byte case catch char class const continue default do double else enum " +
|
||||
"extends final finally float for goto if implements import instanceof int interface long native new " +
|
||||
"package private protected public return short static strictfp super switch synchronized this throw " +
|
||||
"throws transient try void volatile while true false null var record sealed permits yield",
|
||||
)
|
||||
private val KOTLIN = words(
|
||||
"as break class continue do else false for fun if in interface is null object package return super this " +
|
||||
"throw true try typealias typeof val var when while by catch constructor delegate dynamic field file " +
|
||||
"finally get import init param property receiver set setparam where actual abstract annotation " +
|
||||
"companion const crossinline data enum expect external final infix inline inner internal lateinit " +
|
||||
"noinline open operator out override private protected public reified sealed suspend tailrec vararg value",
|
||||
)
|
||||
private val JS = words(
|
||||
"break case catch class const continue debugger default delete do else export extends finally for " +
|
||||
"function if import in instanceof new return super switch this throw try typeof var void while with " +
|
||||
"yield let static async await of true false null undefined from as get set",
|
||||
)
|
||||
private val TS = JS + words(
|
||||
"interface type enum implements declare namespace module public private protected readonly abstract " +
|
||||
"keyof infer is never unknown any string number boolean symbol bigint object satisfies",
|
||||
)
|
||||
private val PYTHON = words(
|
||||
"False None True and as assert async await break class continue def del elif else except finally for " +
|
||||
"from global if import in is lambda nonlocal not or pass raise return try while with yield match case self",
|
||||
)
|
||||
private val RUST = words(
|
||||
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match " +
|
||||
"mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
|
||||
)
|
||||
private val GO = words(
|
||||
"break case chan const continue default defer else fallthrough for func go goto if import interface map " +
|
||||
"package range return select struct switch type var true false nil iota",
|
||||
)
|
||||
private val RUBY = words(
|
||||
"BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in module " +
|
||||
"next nil not or redo rescue retry return self super then true undef unless until when while yield require",
|
||||
)
|
||||
private val PHP = words(
|
||||
"abstract and array as break callable case catch class clone const continue declare default do echo else " +
|
||||
"elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach " +
|
||||
"function global goto if implements include instanceof insteadof interface isset list match namespace new " +
|
||||
"or print private protected public readonly require return static switch throw trait try unset use var " +
|
||||
"while yield true false null",
|
||||
)
|
||||
private val SWIFT = words(
|
||||
"associatedtype class deinit enum extension fileprivate func import init inout internal let open operator " +
|
||||
"private protocol public rethrows static struct subscript typealias var break case continue default defer " +
|
||||
"do else fallthrough for guard if in repeat return switch where while as catch false is nil super self Self " +
|
||||
"throw throws true try async await some any",
|
||||
)
|
||||
private val CSHARP = words(
|
||||
"abstract as base bool break byte case catch char checked class const continue decimal default delegate do " +
|
||||
"double else enum event explicit extern false finally fixed float for foreach goto if implicit in int " +
|
||||
"interface internal is lock long namespace new null object operator out override params private protected " +
|
||||
"public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true " +
|
||||
"try typeof uint ulong unchecked unsafe ushort using virtual void volatile while var async await record",
|
||||
)
|
||||
private val DART = words(
|
||||
"abstract as assert async await break case catch class const continue covariant default deferred do dynamic " +
|
||||
"else enum export extends extension external factory false final finally for get if implements import in " +
|
||||
"interface is late library mixin new null on operator part required rethrow return set show static super " +
|
||||
"switch sync this throw true try typedef var void while with yield",
|
||||
)
|
||||
private val ZIG = words(
|
||||
"addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue " +
|
||||
"defer else enum errdefer error export extern fn for if inline noalias nosuspend noinline opaque or orelse " +
|
||||
"packed pub resume return linksection struct suspend switch test threadlocal try union unreachable usingnamespace " +
|
||||
"var volatile while true false null undefined",
|
||||
)
|
||||
private val SHELL = words(
|
||||
"if then else elif fi case esac for select while until do done in function return exit local export " +
|
||||
"readonly declare set unset shift source echo cd test true false",
|
||||
)
|
||||
private val SQL = words(
|
||||
"select from where and or not insert into values update set delete create table drop alter add index view " +
|
||||
"join left right inner outer full on as group by order having limit offset union all distinct case when then " +
|
||||
"else end null is in like between exists primary key foreign references default unique check begin commit " +
|
||||
"rollback transaction with returning asc desc count sum avg min max integer text real blob varchar",
|
||||
)
|
||||
private val LUA = words(
|
||||
"and break do else elseif end false for function goto if in local nil not or repeat return then true until while",
|
||||
)
|
||||
private val CSS = words("important inherit initial unset none auto")
|
||||
private val LITERALS = words("true false null yes no on off")
|
||||
private val DOCKER = words(
|
||||
"FROM RUN CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS",
|
||||
)
|
||||
|
||||
private val C_LIKE = Spec(lineComments = listOf("//"), blockComments = listOf("/*" to "*/"))
|
||||
|
||||
private val SPECS: Map<String, Spec> = buildMap {
|
||||
val js = C_LIKE.copy(keywords = JS, strings = listOf("\"", "'", "`"))
|
||||
val ts = C_LIKE.copy(keywords = TS, strings = listOf("\"", "'", "`"), capitalisedTypes = true)
|
||||
put("javascript", js)
|
||||
put("jsx", js)
|
||||
put("typescript", ts)
|
||||
put("tsx", ts)
|
||||
put("json", Spec(keywords = LITERALS, strings = listOf("\"")))
|
||||
put("python", Spec(keywords = PYTHON, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
|
||||
put("rust", C_LIKE.copy(keywords = RUST, strings = listOf("\""), capitalisedTypes = true))
|
||||
put("go", C_LIKE.copy(keywords = GO, strings = listOf("\"", "`", "'")))
|
||||
put("ruby", Spec(keywords = RUBY, lineComments = listOf("#"), strings = listOf("\"", "'"), capitalisedTypes = true))
|
||||
put("php", C_LIKE.copy(keywords = PHP, lineComments = listOf("//", "#"), dollarVariables = true, ignoreCase = true))
|
||||
put("java", C_LIKE.copy(keywords = JAVA, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
|
||||
put("kotlin", C_LIKE.copy(keywords = KOTLIN, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
|
||||
put("swift", C_LIKE.copy(keywords = SWIFT, strings = listOf("\"\"\"", "\""), capitalisedTypes = true))
|
||||
put("c", C_LIKE.copy(keywords = C_FAMILY))
|
||||
put("cpp", C_LIKE.copy(keywords = CPP, capitalisedTypes = true))
|
||||
put("csharp", C_LIKE.copy(keywords = CSHARP, capitalisedTypes = true))
|
||||
put("dart", C_LIKE.copy(keywords = DART, strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
|
||||
put("zig", C_LIKE.copy(keywords = ZIG, strings = listOf("\"", "'")))
|
||||
val shell = Spec(keywords = SHELL, lineComments = listOf("#"), dollarVariables = true)
|
||||
put("bash", shell)
|
||||
put("fish", shell)
|
||||
put("css", C_LIKE.copy(keywords = CSS, lineComments = emptyList()))
|
||||
put("scss", C_LIKE.copy(keywords = CSS, dollarVariables = true))
|
||||
put("sql", Spec(keywords = SQL, lineComments = listOf("--"), blockComments = listOf("/*" to "*/"), strings = listOf("'", "\""), ignoreCase = true))
|
||||
put("yaml", Spec(keywords = LITERALS, lineComments = listOf("#"), keys = true))
|
||||
put("toml", Spec(keywords = LITERALS, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), keys = true))
|
||||
// Text between tags is prose: an apostrophe in it is not a string. Attribute values are read by markup().
|
||||
val markup = Spec(blockComments = listOf("<!--" to "-->"), strings = emptyList(), markup = true)
|
||||
put("xml", markup)
|
||||
put("html", markup)
|
||||
put("vue", markup)
|
||||
put("svelte", markup)
|
||||
put("lua", Spec(keywords = LUA, lineComments = listOf("--"), blockComments = listOf("--[[" to "]]"), strings = listOf("\"", "'")))
|
||||
put("dockerfile", Spec(keywords = DOCKER, lineComments = listOf("#")))
|
||||
put("makefile", Spec(lineComments = listOf("#"), dollarVariables = true, keys = true))
|
||||
}
|
||||
|
||||
/** A fence's short names for the server's language names. */
|
||||
private val ALIASES = mapOf(
|
||||
"js" to "javascript", "mjs" to "javascript", "cjs" to "javascript", "ts" to "typescript", "py" to "python",
|
||||
"python3" to "python", "rs" to "rust", "golang" to "go", "rb" to "ruby", "kt" to "kotlin", "kts" to "kotlin",
|
||||
"c++" to "cpp", "cc" to "cpp", "hpp" to "cpp", "h" to "c", "cs" to "csharp", "c#" to "csharp", "sh" to "bash",
|
||||
"shell" to "bash", "zsh" to "bash", "console" to "bash", "yml" to "yaml", "svg" to "xml", "htm" to "html",
|
||||
"docker" to "dockerfile", "make" to "makefile", "jsonc" to "json", "json5" to "json", "postgres" to "sql",
|
||||
"postgresql" to "sql", "sqlite" to "sql", "mysql" to "sql",
|
||||
)
|
||||
|
||||
/** Whether [language] is one this highlighter reads. */
|
||||
fun highlights(language: String): Boolean = specOf(language) != null
|
||||
|
||||
private fun specOf(language: String): Spec? {
|
||||
val name = language.trim().lowercase()
|
||||
return SPECS[name] ?: ALIASES[name]?.let { SPECS[it] }
|
||||
}
|
||||
|
||||
/** Larger than this is drawn plain: a megabyte of spans costs more than it helps. */
|
||||
const val HIGHLIGHT_MAX_CHARS = 400_000
|
||||
|
||||
/** The tokens of [text] read as [language]: empty for a language not known, or a text too large. */
|
||||
fun tokenize(text: String, language: String): List<Token> {
|
||||
val spec = specOf(language) ?: return emptyList()
|
||||
if (text.length > HIGHLIGHT_MAX_CHARS) return emptyList()
|
||||
return Scanner(text, spec).run()
|
||||
}
|
||||
|
||||
private class Scanner(private val s: String, private val spec: Spec) {
|
||||
private val out = mutableListOf<Token>()
|
||||
private var i = 0
|
||||
private var lineStart = true
|
||||
|
||||
fun run(): List<Token> {
|
||||
while (i < s.length) {
|
||||
val c = s[i]
|
||||
if (c == '\n') {
|
||||
lineStart = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (c == ' ' || c == '\t') {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
val atLineStart = lineStart
|
||||
lineStart = false
|
||||
if (block() || line() || (spec.markup && markup()) || string() || (spec.keys && atLineStart && key()) ||
|
||||
(spec.dollarVariables && variable()) || number() || word()
|
||||
) {
|
||||
continue
|
||||
}
|
||||
i++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun add(start: Int, end: Int, kind: TokenKind) {
|
||||
if (end > start) out += Token(start, end, kind)
|
||||
}
|
||||
|
||||
private fun block(): Boolean {
|
||||
for ((open, close) in spec.blockComments) {
|
||||
if (s.startsWith(open, i)) {
|
||||
val end = s.indexOf(close, i + open.length).let { if (it < 0) s.length else it + close.length }
|
||||
add(i, end, TokenKind.Comment)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun line(): Boolean {
|
||||
for (mark in spec.lineComments) {
|
||||
// `#` in a shell word ("a#b") or `$#` is not a comment; one after a space or at a line's start is.
|
||||
if (s.startsWith(mark, i) && (mark != "#" || i == 0 || s[i - 1].isWhitespace())) {
|
||||
val end = s.indexOf('\n', i).let { if (it < 0) s.length else it }
|
||||
add(i, end, TokenKind.Comment)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun string(): Boolean {
|
||||
for (quote in spec.strings) {
|
||||
if (!s.startsWith(quote, i)) continue
|
||||
// A single-character quote ends at the line's end if it is not closed: a stray
|
||||
// apostrophe ("don't" in a comment-less shell line) colours one line, not the file.
|
||||
var j = i + quote.length
|
||||
while (j < s.length) {
|
||||
if (s[j] == '\\' && quote.length == 1) {
|
||||
j += 2
|
||||
continue
|
||||
}
|
||||
if (s.startsWith(quote, j)) {
|
||||
j += quote.length
|
||||
break
|
||||
}
|
||||
if (s[j] == '\n' && quote.length == 1 && quote != "`") break
|
||||
j++
|
||||
}
|
||||
val end = j.coerceAtMost(s.length)
|
||||
add(i, end, TokenKind.Text)
|
||||
i = end
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun number(): Boolean {
|
||||
val c = s[i]
|
||||
if (!c.isDigit() && !(c == '.' && i + 1 < s.length && s[i + 1].isDigit())) return false
|
||||
if (i > 0 && (s[i - 1].isLetterOrDigit() || s[i - 1] == '_')) return false
|
||||
var j = i
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '.' || s[j] == '_')) j++
|
||||
add(i, j, TokenKind.Number)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
private fun word(): Boolean {
|
||||
val c = s[i]
|
||||
if (!c.isLetter() && c != '_' && c != '@') return false
|
||||
var j = i + 1
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
|
||||
val word = s.substring(i, j)
|
||||
val bare = word.removePrefix("@")
|
||||
when {
|
||||
word.startsWith("@") && word.length > 1 -> add(i, j, TokenKind.Attribute)
|
||||
|
||||
(if (spec.ignoreCase) bare.lowercase() in spec.keywords || bare in spec.keywords else bare in spec.keywords) ->
|
||||
add(i, j, TokenKind.Keyword)
|
||||
|
||||
spec.capitalisedTypes && bare.first().isUpperCase() && bare.any { it.isLowerCase() } -> add(i, j, TokenKind.Type)
|
||||
}
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
private fun variable(): Boolean {
|
||||
if (s[i] != '$' || i + 1 >= s.length) return false
|
||||
var j = i + 1
|
||||
if (s[j] == '{') {
|
||||
j = s.indexOf('}', j).let { if (it < 0) s.length else it + 1 }
|
||||
} else {
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
|
||||
}
|
||||
if (j == i + 1) return false
|
||||
add(i, j, TokenKind.Attribute)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
|
||||
/** `key:` (YAML) or `key =` (TOML, Make) as a line's first word. */
|
||||
private fun key(): Boolean {
|
||||
var j = i
|
||||
if (s[j] == '-' && j + 1 < s.length && s[j + 1] == ' ') return false
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "_-.[]\"'")) j++
|
||||
if (j == i) return false
|
||||
var k = j
|
||||
while (k < s.length && s[k] == ' ') k++
|
||||
if (k < s.length && (s[k] == ':' || s[k] == '=') && (k + 1 >= s.length || s[k + 1] != '=')) {
|
||||
add(i, j, TokenKind.Type)
|
||||
i = j
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** `<tag attr="value">` and `</tag>`: the tag's name, its attributes' names, the values as strings. */
|
||||
private fun markup(): Boolean {
|
||||
if (s[i] != '<' || i + 1 >= s.length) return false
|
||||
var j = i + 1
|
||||
if (s[j] == '/' || s[j] == '?' || s[j] == '!') j++
|
||||
val nameStart = j
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:.")) j++
|
||||
if (j == nameStart) return false
|
||||
add(nameStart, j, TokenKind.Tag)
|
||||
while (j < s.length && s[j] != '>') {
|
||||
when {
|
||||
s[j] == '"' || s[j] == '\'' -> {
|
||||
val q = s[j]
|
||||
val end = s.indexOf(q, j + 1).let { if (it < 0) s.length else it + 1 }
|
||||
add(j, end, TokenKind.Text)
|
||||
j = end
|
||||
}
|
||||
|
||||
s[j].isLetter() -> {
|
||||
val a = j
|
||||
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:@.")) j++
|
||||
add(a, j, TokenKind.Attribute)
|
||||
}
|
||||
|
||||
s[j] == '\n' -> {
|
||||
j++
|
||||
}
|
||||
|
||||
else -> j++
|
||||
}
|
||||
}
|
||||
i = (j + 1).coerceAtMost(s.length)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/** The theme's colour for each kind of token. */
|
||||
fun tokenStyle(kind: TokenKind, palette: Palette): SpanStyle = when (kind) {
|
||||
TokenKind.Comment -> SpanStyle(color = palette.inkFaint, fontStyle = FontStyle.Italic)
|
||||
TokenKind.Text -> SpanStyle(color = palette.success)
|
||||
TokenKind.Number -> SpanStyle(color = palette.warning)
|
||||
TokenKind.Keyword -> SpanStyle(color = palette.accent)
|
||||
TokenKind.Type -> SpanStyle(color = palette.leaf)
|
||||
TokenKind.Tag -> SpanStyle(color = palette.accent)
|
||||
TokenKind.Attribute -> SpanStyle(color = palette.warning)
|
||||
}
|
||||
|
||||
/** [text] with its [tokens] in the theme's colours; the rest in [plain]. */
|
||||
fun highlighted(text: String, tokens: List<Token>, palette: Palette, plain: Color = palette.ink): AnnotatedString = buildAnnotatedString {
|
||||
append(text)
|
||||
addStyle(SpanStyle(color = plain), 0, text.length)
|
||||
for (token in tokens) addStyle(tokenStyle(token.kind, palette), token.start, token.end.coerceAtMost(text.length))
|
||||
}
|
||||
|
||||
/** [text] as [language], highlighted -- or plain, when the language is not one it reads. */
|
||||
fun highlight(text: String, language: String, palette: Palette): AnnotatedString = highlighted(text, tokenize(text, language), palette)
|
||||
@@ -9,6 +9,7 @@ import android.util.TypedValue
|
||||
import android.widget.TextView
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
@@ -56,18 +57,33 @@ fun markwon(context: Context, codeBg: Int, link: Int): Markwon = Markwon.builder
|
||||
)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* [markdown] drawn by Markwon in a TextView. With [onLongPress] the text is not selectable: a
|
||||
* long press is the message's menu instead (which offers Select text); without it, as in the
|
||||
* activity panel's room, the text selects as usual.
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null) {
|
||||
fun MarkdownText(markdown: String, modifier: Modifier = Modifier, color: Color? = null, onLongPress: (() -> Unit)? = 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()) }
|
||||
val longPress = rememberUpdatedState(onLongPress)
|
||||
val pressable = onLongPress != null
|
||||
AndroidView(
|
||||
modifier = modifier,
|
||||
factory = { ctx ->
|
||||
TextView(ctx).apply {
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
|
||||
setTextIsSelectable(true)
|
||||
setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
|
||||
setLineSpacing(0f, 1.2f)
|
||||
if (pressable) {
|
||||
setOnLongClickListener {
|
||||
longPress.value?.invoke()
|
||||
true
|
||||
}
|
||||
} else {
|
||||
setTextIsSelectable(true)
|
||||
}
|
||||
movementMethod = LinkMovementMethod.getInstance()
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
/**
|
||||
* A reply's markdown in the pieces the transcript draws differently: prose (Markwon, in a
|
||||
* TextView) and fenced code blocks (their own box, with the language and a Copy button). Only
|
||||
* a fence at the start of a line (at most three spaces in, as CommonMark has it) is taken out;
|
||||
* anything deeper -- a fence inside a list item -- stays in the prose for Markwon to draw.
|
||||
*
|
||||
* A fence that is not closed yet runs to the end: while a reply is being written, the code it
|
||||
* is in the middle of is already a code block, not markdown that changes shape when it closes.
|
||||
*
|
||||
* **A page** (harness spec 3.8.0, `pages.md`: a whole HTML document in an `html-view` fence) is
|
||||
* not drawn on a phone and its source is never shown as the answer. Which fence is a page is the
|
||||
* server's to say: a block is one only in a reply written while pages were offered, and the
|
||||
* server then puts the one line `[page: Title]` in its place in the text it gives a client that
|
||||
* draws no pages. That line is what becomes [Segment.Page]. A fence is taken for a page here
|
||||
* only where the caller says pages are being written ([splitFences]' `pages`: the open step of
|
||||
* a reply as it streams, which the server has not turned into text yet); anywhere else an
|
||||
* `html-view` fence is the code block it is.
|
||||
*/
|
||||
sealed interface Segment {
|
||||
data class Prose(val markdown: String) : Segment
|
||||
|
||||
data class Code(val language: String, val code: String, val closed: Boolean = true) : Segment
|
||||
|
||||
data class Page(val title: String, val closed: Boolean = true) : Segment
|
||||
}
|
||||
|
||||
/** `pages.fence`: the fence's word, exact. */
|
||||
private const val PAGE_FENCE = "html-view"
|
||||
|
||||
/** `pages.title_max`. */
|
||||
private const val PAGE_TITLE_MAX = 80
|
||||
|
||||
private val PAGE_OPENING = Regex("^ {0,3}(?:`{3,}|~{3,})$PAGE_FENCE(?:\\s+(.*))?$")
|
||||
|
||||
/** `pages.projection`, on a line of its own. */
|
||||
private val PAGE_LINE = Regex("^\\s*\\[page: (.*)]\\s*$")
|
||||
|
||||
/** A page's title as written: white space collapsed, cut to the spec's length; empty when it has none. */
|
||||
private fun pageTitle(raw: String?): String = raw.orEmpty().trim().replace(Regex("\\s+"), " ").take(PAGE_TITLE_MAX)
|
||||
|
||||
/**
|
||||
* A reply's text with every page replaced by the spec's one line, `[page: Title]`: what Copy,
|
||||
* Share and read-aloud take, so a page's source never leaves as "the answer". [untitled] names
|
||||
* a page without a title.
|
||||
*/
|
||||
fun pageProjection(markdown: String, untitled: String, pages: Boolean = false): String = splitFences(markdown, pages).joinToString("\n\n") { segment ->
|
||||
when (segment) {
|
||||
is Segment.Prose -> segment.markdown
|
||||
is Segment.Code -> "```${segment.language}\n${segment.code}\n```"
|
||||
is Segment.Page -> "[page: ${segment.title.ifBlank { untitled }}]"
|
||||
}
|
||||
}
|
||||
|
||||
private val OPENING = Regex("^ {0,3}(`{3,}|~{3,})\\s*([^`\\s]*).*$")
|
||||
|
||||
fun splitFences(markdown: String, pages: Boolean = false): List<Segment> {
|
||||
val out = mutableListOf<Segment>()
|
||||
val prose = StringBuilder()
|
||||
val lines = markdown.split("\n")
|
||||
var i = 0
|
||||
|
||||
fun flushProse() {
|
||||
val text = prose.toString().trim('\n')
|
||||
if (text.isNotBlank()) out += Segment.Prose(text)
|
||||
prose.clear()
|
||||
}
|
||||
|
||||
while (i < lines.size) {
|
||||
val open = OPENING.matchEntire(lines[i])
|
||||
if (open == null) {
|
||||
val page = PAGE_LINE.matchEntire(lines[i])
|
||||
if (page != null) {
|
||||
flushProse()
|
||||
out += Segment.Page(pageTitle(page.groupValues[1]))
|
||||
} else {
|
||||
prose.append(lines[i]).append('\n')
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
flushProse()
|
||||
val fence = open.groupValues[1]
|
||||
val language = open.groupValues[2]
|
||||
val page = if (pages) PAGE_OPENING.matchEntire(lines[i]) else null
|
||||
val closing = Regex("^ {0,3}${Regex.escape(fence.substring(0, 1))}{${fence.length},}\\s*$")
|
||||
val code = mutableListOf<String>()
|
||||
i++
|
||||
var closed = false
|
||||
while (i < lines.size) {
|
||||
if (closing.matches(lines[i])) {
|
||||
closed = true
|
||||
i++
|
||||
break
|
||||
}
|
||||
code += lines[i]
|
||||
i++
|
||||
}
|
||||
out += if (page != null) Segment.Page(pageTitle(page.groupValues[1]), closed) else Segment.Code(language, code.joinToString("\n"), closed)
|
||||
}
|
||||
flushProse()
|
||||
return out
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -77,8 +78,9 @@ fun ModelAvatar(model: ModelInfo?, fallbackName: String, size: Dp = 24.dp, modif
|
||||
val palette = LocalPalette.current
|
||||
val path = model?.image
|
||||
var image by remember(path) { mutableStateOf(path?.let { ModelImages.cached(it) }) }
|
||||
val still = LocalInspectionMode.current
|
||||
LaunchedEffect(path) {
|
||||
if (path != null && image == null) image = ModelImages.load(context, path)
|
||||
if (path != null && image == null && !still) image = ModelImages.load(context, path)
|
||||
}
|
||||
Box(modifier.size(size).clip(CircleShape).background(palette.accentSoft), contentAlignment = Alignment.Center) {
|
||||
val shown = image
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.res.Resources
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Progress
|
||||
import eu.llembas.android.api.ProgressWords
|
||||
import eu.llembas.android.api.elapsed
|
||||
import eu.llembas.android.api.progressLine
|
||||
import eu.llembas.android.api.progressText
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** The progress texts' resources, by the spec's key (`progress.<key>` with `.` as `_`). */
|
||||
private val PROGRESS_STRINGS = mapOf(
|
||||
"queued" to R.string.progress_queued,
|
||||
"queued_ahead" to R.string.progress_queued_ahead,
|
||||
"waiting_for_model" to R.string.progress_waiting_for_model,
|
||||
"loading_model" to R.string.progress_loading_model,
|
||||
"reading_prompt" to R.string.progress_reading_prompt,
|
||||
"reading_prompt_bare" to R.string.progress_reading_prompt_bare,
|
||||
"thinking" to R.string.progress_thinking,
|
||||
"writing" to R.string.progress_writing,
|
||||
"writing_bare" to R.string.progress_writing_bare,
|
||||
"running_tool" to R.string.progress_running_tool,
|
||||
"running_tool_bare" to R.string.progress_running_tool_bare,
|
||||
"waiting_for_person" to R.string.progress_waiting_for_person,
|
||||
"waiting_for_subagents" to R.string.progress_waiting_for_subagents,
|
||||
"compacting" to R.string.progress_compacting,
|
||||
"retrying" to R.string.progress_retrying,
|
||||
"stopped" to R.string.progress_stopped,
|
||||
"stopped_reason" to R.string.progress_stopped_reason,
|
||||
"failed" to R.string.progress_failed,
|
||||
"reason_busy" to R.string.progress_reason_busy,
|
||||
"reason_slots" to R.string.progress_reason_slots,
|
||||
"reason_group" to R.string.progress_reason_group,
|
||||
"what_approval" to R.string.progress_what_approval,
|
||||
"what_approval_bare" to R.string.progress_what_approval_bare,
|
||||
"what_question" to R.string.progress_what_question,
|
||||
"what_plan" to R.string.progress_what_plan,
|
||||
"stopped_reason_person" to R.string.progress_stopped_person,
|
||||
"stopped_reason_steps" to R.string.progress_stopped_steps,
|
||||
"stopped_reason_budget" to R.string.progress_stopped_budget,
|
||||
"line" to R.string.progress_line,
|
||||
)
|
||||
|
||||
/** [ProgressWords] from the app's string resources, in the app's language. */
|
||||
fun progressWords(resources: Resources): ProgressWords = ProgressWords { key, args ->
|
||||
PROGRESS_STRINGS[key]?.let { id -> if (args.isEmpty()) resources.getString(id) else resources.getString(id, *args) }
|
||||
}
|
||||
|
||||
/** The end of a progress line: the shared `progress.line` separator and [clock], without the text before it. */
|
||||
fun progressClock(resources: Resources, clock: String): String = resources.getString(R.string.progress_line, "", clock)
|
||||
|
||||
/** The clock a progress line ticks by: now, again on every whole second. */
|
||||
@Composable
|
||||
fun rememberTick(): Long {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(Unit) {
|
||||
while (true) {
|
||||
now = System.currentTimeMillis()
|
||||
delay(1000L - now % 1000L)
|
||||
}
|
||||
}
|
||||
return now
|
||||
}
|
||||
|
||||
/** In a preview or a screenshot the clock stands still, this long after the phase began. */
|
||||
private const val STILL_ELAPSED = 65_000L
|
||||
|
||||
/**
|
||||
* The progress line to draw for [progress] (`{{text}} · {{elapsed}}`), ticking once a second;
|
||||
* or the text alone with [withElapsed] false, where a line has no room (a list's row). Null
|
||||
* when there is no progress, or it is a phase this app does not know: draw `status` then.
|
||||
*/
|
||||
@Composable
|
||||
fun progressLineOf(progress: Progress?, withElapsed: Boolean = true): String? {
|
||||
progress ?: return null
|
||||
val resources = LocalContext.current.resources
|
||||
val locale = LocalConfiguration.current.locales[0]
|
||||
val words = remember(resources, locale) { progressWords(resources) }
|
||||
// Under inspection (previews, screenshots) nothing may animate forever, and a shot must be
|
||||
// the same every time.
|
||||
val now = if (LocalInspectionMode.current) progress.since + STILL_ELAPSED else rememberTick()
|
||||
return if (withElapsed) progressLine(progress, words, now, locale) else progressText(progress, words, now, locale)
|
||||
}
|
||||
|
||||
/**
|
||||
* What a reply is doing, one line: the progress text, then `· elapsed` (`progress.line`) kept
|
||||
* whole at the end while the text gives way (two lines, then an ellipsis) -- on a phone a long
|
||||
* reason must not push the clock off. [status], the free text, when there is no progress this
|
||||
* app can draw. Nothing at all when neither says anything.
|
||||
*/
|
||||
@Composable
|
||||
fun ProgressStatus(progress: Progress?, status: String, style: TextStyle, color: Color, modifier: Modifier = Modifier) {
|
||||
val text = progressLineOf(progress, withElapsed = false)
|
||||
if (text == null) {
|
||||
if (status.isNotBlank()) Text(status, style = style, color = color, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = modifier)
|
||||
return
|
||||
}
|
||||
val clock = progress?.takeUnless { it.phase in Progress.NO_ELAPSED }?.let { p ->
|
||||
val now = if (LocalInspectionMode.current) p.since + STILL_ELAPSED else rememberTick()
|
||||
elapsed(now - p.since)
|
||||
}
|
||||
Row(modifier, verticalAlignment = Alignment.Top) {
|
||||
Text(text, style = style, color = color, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
|
||||
// The clock after the shared separator: `progress.line` (`{{text}} · {{elapsed}}`) with
|
||||
// the text left out, so the separator is the spec's and not a copy of it.
|
||||
if (clock != null) Text(progressClock(LocalContext.current.resources, clock), style = style, color = color, maxLines = 1, softWrap = false)
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
@@ -32,7 +31,9 @@ import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Groups
|
||||
import androidx.compose.material.icons.filled.StopCircle
|
||||
import androidx.compose.material.icons.filled.SmartToy
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
@@ -40,12 +41,14 @@ import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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
|
||||
@@ -60,6 +63,7 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
@@ -72,10 +76,15 @@ import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentDetail
|
||||
import eu.llembas.android.api.ActivityTeam
|
||||
import eu.llembas.android.api.AgentTurn
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ContextUse
|
||||
import eu.llembas.android.api.Output
|
||||
import eu.llembas.android.api.RoomMessage
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.TreeAgent
|
||||
import eu.llembas.android.api.TreeLogic
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.explain
|
||||
@@ -84,9 +93,12 @@ import eu.llembas.android.ui.theme.Palette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// --- The strip above the composer ---------------------------------------------------------
|
||||
// --- The summary chip above the composer --------------------------------------------------
|
||||
|
||||
/** What runs in the background, in one line ("3 agents working · 1 queued"), opening the panel. */
|
||||
/**
|
||||
* What runs in the background, in one line ("2 running · 1 queued · 4 finished"), opening the
|
||||
* activity sheet. Only while anything runs: finished work alone is no reason for a line.
|
||||
*/
|
||||
@Composable
|
||||
fun ActivityStrip(summary: ActivitySummary, onOpen: () -> Unit) {
|
||||
val counts = ActivityLogic.stripCounts(summary)
|
||||
@@ -96,8 +108,10 @@ fun ActivityStrip(summary: ActivitySummary, onOpen: () -> Unit) {
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
color = palette.surfaceRaised,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp).heightIn(min = 48.dp),
|
||||
contentColor = palette.ink,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
border = androidx.compose.foundation.BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp).heightIn(min = 48.dp),
|
||||
) {
|
||||
Row(Modifier.padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Bolt, contentDescription = null, tint = palette.accent, modifier = Modifier.size(18.dp))
|
||||
@@ -115,7 +129,7 @@ fun ActivityStrip(summary: ActivitySummary, onOpen: () -> Unit) {
|
||||
|
||||
@Composable
|
||||
private fun stateCount(state: String, n: Int): String = when (state) {
|
||||
"working" -> if (n == 1) stringResource(R.string.agents_one_working) else stringResource(R.string.agents_n_working, n.toString())
|
||||
"working" -> stringResource(R.string.tasks_n_running, n.toString())
|
||||
"queued" -> stringResource(R.string.agents_n_queued, n.toString())
|
||||
"waiting" -> stringResource(R.string.agents_n_waiting, n.toString())
|
||||
else -> stringResource(R.string.agents_n_finished, n.toString())
|
||||
@@ -131,7 +145,14 @@ private fun stateWord(state: String): String = when (state) {
|
||||
else -> stringResource(R.string.agent_state_error)
|
||||
}
|
||||
|
||||
/** The state's dot, in the web panel's colours: accent working, warning waiting, success done. */
|
||||
@Composable
|
||||
private fun kindWord(agent: ActivityAgent): String = when {
|
||||
agent.kind == "member" -> stringResource(R.string.task_member)
|
||||
agent.type == "command" -> stringResource(R.string.task_command)
|
||||
else -> stringResource(R.string.task_subagent)
|
||||
}
|
||||
|
||||
/** The state's colour, in the web panel's: accent working, warning waiting, success done. */
|
||||
private fun stateColour(palette: Palette, state: String): Color = when (state) {
|
||||
"working" -> palette.accent
|
||||
"queued", "waiting" -> palette.warning
|
||||
@@ -167,32 +188,45 @@ private fun categoryName(key: String): String = when (key) {
|
||||
else -> key
|
||||
}
|
||||
|
||||
// --- The panel ------------------------------------------------------------------------------
|
||||
// --- The sheet ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The chat's activity, full screen: Context, Outputs, Background tasks (with the team's room)
|
||||
* and Plan -- the web's activity panel, from `GET /chats/{chat}/activity`. Kept current by the
|
||||
* events route through the view model; without it, read again every few seconds while open.
|
||||
* Everything an agent wrote is a model's words: names, roles and briefs as plain text, the
|
||||
* room and replies through [MarkdownText]'s untrusted rules.
|
||||
* What the activity sheet asks of the chat. Every action has a do-nothing default, so the
|
||||
* screenshot tests draw the sheet with fake data and nothing behind it.
|
||||
*/
|
||||
interface ActivityActions {
|
||||
fun stop(agent: ActivityAgent) {}
|
||||
fun read(agent: ActivityAgent) {}
|
||||
fun readSubagent(agent: TreeAgent) {}
|
||||
fun openFile(path: String) {}
|
||||
fun compact() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat's activity as a sheet over it, from the top bar's button or the strip: Context,
|
||||
* Outputs, Background tasks, the team's Room and Plan -- the web's side panel, from
|
||||
* `GET /chats/{chat}/activity`. Kept current by the events route through the view model;
|
||||
* without it, read again every few seconds while open. A chat not made yet has nothing to
|
||||
* show but says so in each section. Stopping anything asks first.
|
||||
*/
|
||||
@Composable
|
||||
fun ActivityPanel(chatId: String, state: ChatState, model: ChatViewModel, canOpenFiles: Boolean, onClose: () -> Unit) {
|
||||
val activity = state.activity
|
||||
fun ActivityPanel(chatId: String?, state: ChatState, model: ChatViewModel, canOpenFiles: Boolean, onClose: () -> Unit) {
|
||||
val live by rememberUpdatedState(state.activityLive)
|
||||
var now by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
var stopping by remember { mutableStateOf<ActivityAgent?>(null) }
|
||||
var reading by remember { mutableStateOf<ActivityAgent?>(null) }
|
||||
var readingSubagent by remember { mutableStateOf<TreeAgent?>(null) }
|
||||
var viewing by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
LaunchedEffect(chatId) {
|
||||
if (chatId == null) return@LaunchedEffect
|
||||
model.panel(true)
|
||||
var ticks = 0
|
||||
while (true) {
|
||||
delay(1_000)
|
||||
now = SystemClock.elapsedRealtime()
|
||||
ticks++
|
||||
// Without the events route, the panel reads itself again: cheaply, every 5 s.
|
||||
// Without the events route, the sheet reads itself again: cheaply, every 5 s.
|
||||
if (!live && ticks % 5 == 0) model.loadActivity(context = false)
|
||||
}
|
||||
}
|
||||
@@ -201,54 +235,49 @@ fun ActivityPanel(chatId: String, state: ChatState, model: ChatViewModel, canOpe
|
||||
model.panel(false)
|
||||
onClose()
|
||||
}
|
||||
Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.activity)) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
if (activity == null) {
|
||||
Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Scaffold
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.padding(padding).fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item { Section(stringResource(R.string.activity_context)) { ContextSection(activity.context) } }
|
||||
item {
|
||||
Section(stringResource(R.string.activity_outputs), count = activity.outputs.size.takeIf { it > 0 }) {
|
||||
OutputsSection(activity.outputs, canOpenFiles) { viewing = it }
|
||||
}
|
||||
}
|
||||
item {
|
||||
Section(stringResource(R.string.activity_tasks)) {
|
||||
TasksSection(activity, state.activityAt, now, onStop = { stopping = it }, onRead = { reading = it })
|
||||
}
|
||||
}
|
||||
ActivityLogic.plan(activity.plan)?.let { plan ->
|
||||
item { Section(stringResource(R.string.mode_plan)) { PlanBody(plan) } }
|
||||
}
|
||||
}
|
||||
val actions = object : ActivityActions {
|
||||
override fun stop(agent: ActivityAgent) {
|
||||
stopping = agent
|
||||
}
|
||||
|
||||
override fun read(agent: ActivityAgent) {
|
||||
reading = agent
|
||||
}
|
||||
|
||||
override fun readSubagent(agent: TreeAgent) {
|
||||
readingSubagent = agent
|
||||
}
|
||||
|
||||
override fun openFile(path: String) {
|
||||
if (canOpenFiles) viewing = path
|
||||
}
|
||||
|
||||
override fun compact() = model.compact()
|
||||
}
|
||||
ModalBottomSheet(onDismissRequest = close, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
ActivityContent(
|
||||
activity = if (chatId == null) Activity() else state.activity,
|
||||
readAt = state.activityAt,
|
||||
now = now,
|
||||
actions = actions,
|
||||
canCompact = chatId != null && !state.running,
|
||||
compacting = state.compacting,
|
||||
canOpenFiles = canOpenFiles,
|
||||
tree = state.tree,
|
||||
onClose = close,
|
||||
)
|
||||
}
|
||||
|
||||
stopping?.let { agent ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { stopping = null },
|
||||
title = { Text(stringResource(R.string.agent_stop, agent.name)) },
|
||||
title = { Text(stringResource(R.string.agent_stop, ActivityLogic.title(agent))) },
|
||||
text = {
|
||||
Text(
|
||||
if (agent.kind == "member") {
|
||||
stringResource(R.string.agent_stop_member_confirm, agent.name)
|
||||
} else {
|
||||
stringResource(R.string.agent_stop_confirm, agent.name)
|
||||
stringResource(R.string.agent_stop_confirm, ActivityLogic.title(agent))
|
||||
},
|
||||
)
|
||||
},
|
||||
@@ -261,13 +290,83 @@ fun ActivityPanel(chatId: String, state: ChatState, model: ChatViewModel, canOpe
|
||||
dismissButton = { TextButton(onClick = { stopping = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
reading?.let { agent -> AgentConversation(chatId, agent, onClose = { reading = null }) }
|
||||
if (chatId != null) reading?.let { agent -> AgentConversation(chatId, agent, onClose = { reading = null }) }
|
||||
if (chatId != null) readingSubagent?.let { agent -> SubagentConversation(chatId, agent, onClose = { readingSubagent = null }) }
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
/** A heading that folds its section away, open to begin with. */
|
||||
/**
|
||||
* The sheet as it is drawn, from its facts alone: what the screenshot tests render. [activity]
|
||||
* null is still being read; [now] and [readAt] are the clock that elapsed time counts on;
|
||||
* [unfolded] opens the first task and the finished ones, for the screenshots to see them.
|
||||
*/
|
||||
@Composable
|
||||
private fun Section(title: String, count: Int? = null, content: @Composable () -> Unit) {
|
||||
fun ActivityContent(
|
||||
activity: Activity?,
|
||||
readAt: Long,
|
||||
now: Long,
|
||||
actions: ActivityActions,
|
||||
canCompact: Boolean = true,
|
||||
compacting: Boolean = false,
|
||||
canOpenFiles: Boolean = true,
|
||||
unfolded: Boolean = false,
|
||||
tree: SubagentTree? = null,
|
||||
onClose: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(start = 16.dp, end = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(stringResource(R.string.activity), style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close), tint = palette.inkMuted) }
|
||||
}
|
||||
if (activity == null) {
|
||||
Box(Modifier.fillMaxWidth().height(240.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Column
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxWidth(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp),
|
||||
) {
|
||||
item {
|
||||
Section(stringResource(R.string.activity_context)) {
|
||||
ContextSection(activity.context, canCompact, compacting, actions::compact)
|
||||
}
|
||||
}
|
||||
if (activity.outputs.isNotEmpty()) {
|
||||
item {
|
||||
Section(stringResource(R.string.activity_outputs), count = activity.outputs.size) {
|
||||
OutputsSection(activity.outputs, canOpenFiles, actions::openFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
// 3.4.0: the subagents as a reduced list, each opening its conversation read-only;
|
||||
// the Tasks section then holds the background jobs, the members being in the list.
|
||||
val shownTree = tree?.takeIf { TreeLogic.hasSubagents(it) }
|
||||
if (shownTree != null) {
|
||||
item {
|
||||
Section(stringResource(R.string.team_agents), count = shownTree.agents.count { !it.isMain }.takeIf { it > 0 }) {
|
||||
SubagentList(shownTree, actions::readSubagent)
|
||||
}
|
||||
}
|
||||
}
|
||||
val tasks = if (shownTree != null) activity.copy(agents = activity.agents.filter { it.kind != "member" }, team = null) else activity
|
||||
item { Section(stringResource(R.string.activity_tasks)) { TasksSection(tasks, readAt, now, actions, unfolded) } }
|
||||
activity.team?.let { team ->
|
||||
item { Section(stringResource(R.string.team_room), count = team.room.size.takeIf { it > 0 }) { RoomSection(team) } }
|
||||
}
|
||||
ActivityLogic.plan(activity.plan)?.let { plan ->
|
||||
item { Section(stringResource(R.string.mode_plan), divider = false) { PlanBody(plan) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A heading that folds its section away, open to begin with, with an optional count beside it. */
|
||||
@Composable
|
||||
private fun Section(title: String, count: Int? = null, divider: Boolean = true, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(title) { mutableStateOf(true) }
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
@@ -280,85 +379,120 @@ private fun Section(title: String, count: Int? = null, content: @Composable () -
|
||||
Icon(if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = palette.inkFaint)
|
||||
}
|
||||
if (open) content()
|
||||
HorizontalDivider(Modifier.padding(top = 8.dp), color = palette.border)
|
||||
if (divider) HorizontalDivider(Modifier.padding(top = 12.dp), color = palette.border)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Empty(text: String) {
|
||||
Text(text, style = MaterialTheme.typography.bodySmall, color = LocalPalette.current.inkMuted)
|
||||
Text(text, style = MaterialTheme.typography.bodySmall, color = LocalPalette.current.inkMuted, modifier = Modifier.padding(bottom = 4.dp))
|
||||
}
|
||||
|
||||
// --- Context --------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The reference's Context: "N% used" and used / window on one line, the segmented bar, one row
|
||||
* per category (swatch, name, tokens, per cent), then how far auto-compact is and the button
|
||||
* that compacts now.
|
||||
*/
|
||||
@Composable
|
||||
private fun ContextSection(context: ContextUse?) {
|
||||
private fun ContextSection(context: ContextUse?, canCompact: Boolean, compacting: Boolean, onCompact: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
if (context == null) {
|
||||
Empty(stringResource(R.string.activity_not_measured))
|
||||
return
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
val pct = context.percent
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
if (context == null) {
|
||||
Empty(stringResource(R.string.activity_not_measured))
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
val pct = context.percent
|
||||
Text(
|
||||
if (pct != null) stringResource(R.string.activity_used, ActivityLogic.percent(pct)) else ActivityLogic.compactTokens(context.used),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
if (context.limit > 0) {
|
||||
"${ActivityLogic.compactTokens(context.used)} / ${ActivityLogic.compactTokens(context.limit)}"
|
||||
} else {
|
||||
stringResource(R.string.activity_window_unknown)
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
val parts = ActivityLogic.barParts(context)
|
||||
if (parts.isNotEmpty()) {
|
||||
// One segment per category, by its tokens; the rest of the window is the bar's own
|
||||
// background. Weights, so the segments always fill exactly the bar's width.
|
||||
Row(Modifier.fillMaxWidth().height(6.dp).clip(RoundedCornerShape(3.dp)).background(palette.surfaceRaised)) {
|
||||
parts.forEach { part -> Box(Modifier.weight(part.tokens.toFloat()).fillMaxHeight().background(categoryColour(palette, part.key))) }
|
||||
val rest = (context.limit - parts.sumOf { it.tokens }).coerceAtLeast(0)
|
||||
if (rest > 0) Spacer(Modifier.weight(rest.toFloat()))
|
||||
}
|
||||
}
|
||||
// Each row a fixed grid: swatch, the name that gives, two number columns of their own
|
||||
// width -- the numbers line up whatever the names say in which language. The columns
|
||||
// are as wide as five of their own figures, so large type widens them with it.
|
||||
val figures = MaterialTheme.typography.bodySmall.fontSize * 4.6f
|
||||
val column = with(LocalDensity.current) { figures.toDp() }
|
||||
context.categories.forEach { part ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 22.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(10.dp).clip(RoundedCornerShape(2.dp)).background(categoryColour(palette, part.key)))
|
||||
Text(
|
||||
categoryName(part.key),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
|
||||
)
|
||||
Text(
|
||||
ActivityLogic.compactTokens(part.tokens),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
textAlign = TextAlign.End,
|
||||
maxLines = 1,
|
||||
modifier = Modifier.width(column),
|
||||
)
|
||||
Text(
|
||||
part.percent?.let { "${ActivityLogic.percent(it)}%" } ?: "—",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
textAlign = TextAlign.End,
|
||||
maxLines = 1,
|
||||
modifier = Modifier.padding(start = 4.dp).width(column),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
if (pct != null) stringResource(R.string.activity_used, ActivityLogic.percent(pct)) else ActivityLogic.compactTokens(context.used),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
stringResource(if (context.measured) R.string.activity_measured else R.string.activity_estimated) + " " +
|
||||
stringResource(R.string.activity_tools_offered, context.toolsCount.toString()),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
// How far automatic compaction is, and the button. The words give; the button keeps its
|
||||
// own size whatever the sentence says in which language.
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
val until = context?.let { ActivityLogic.untilAutoCompact(it) }
|
||||
Text(
|
||||
if (context.limit > 0) {
|
||||
"${ActivityLogic.compactTokens(context.used)} / ${ActivityLogic.compactTokens(context.limit)}"
|
||||
} else {
|
||||
stringResource(R.string.activity_window_unknown)
|
||||
when {
|
||||
context == null -> ""
|
||||
until != null -> stringResource(R.string.activity_until_compact, ActivityLogic.compactTokens(until))
|
||||
context.autoCompact == false || context.threshold <= 0 -> stringResource(R.string.activity_compact_off)
|
||||
else -> ""
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.weight(1f).padding(end = 8.dp),
|
||||
)
|
||||
}
|
||||
val parts = ActivityLogic.barParts(context)
|
||||
if (parts.isNotEmpty()) {
|
||||
// One segment per category, by its tokens; the rest of the window is the bar's own
|
||||
// background. Weights, so the segments always fill exactly the bar's width.
|
||||
Row(Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)).background(palette.surfaceRaised)) {
|
||||
parts.forEach { part -> Box(Modifier.weight(part.tokens.toFloat()).fillMaxHeight().background(categoryColour(palette, part.key))) }
|
||||
val rest = (context.limit - parts.sumOf { it.tokens }).coerceAtLeast(0)
|
||||
if (rest > 0) Spacer(Modifier.weight(rest.toFloat()))
|
||||
// The server says when there is nothing to summarise yet (`compactable`); an older
|
||||
// one does not, and then its refusal says it in words.
|
||||
OutlinedButton(onClick = onCompact, enabled = canCompact && !compacting && context != null && context.compactable != false) {
|
||||
if (compacting) {
|
||||
CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text(stringResource(R.string.activity_compact))
|
||||
}
|
||||
}
|
||||
// Each row a fixed grid: swatch, the name that gives, two number columns of their own
|
||||
// width -- the numbers line up whatever the names say in which language.
|
||||
context.categories.forEach { part ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(10.dp).clip(RoundedCornerShape(2.dp)).background(categoryColour(palette, part.key)))
|
||||
Text(
|
||||
categoryName(part.key),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
|
||||
)
|
||||
Text(
|
||||
ActivityLogic.compactTokens(part.tokens),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(56.dp),
|
||||
)
|
||||
Text(
|
||||
part.percent?.let { "${ActivityLogic.percent(it)}%" } ?: "—",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(56.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(if (context.measured) R.string.activity_measured else R.string.activity_estimated) + " " +
|
||||
stringResource(R.string.activity_tools_offered, context.toolsCount.toString()),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,10 +501,6 @@ private fun ContextSection(context: ContextUse?) {
|
||||
@Composable
|
||||
private fun OutputsSection(outputs: List<Output>, canOpen: Boolean, onOpen: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
if (outputs.isEmpty()) {
|
||||
Empty(stringResource(R.string.outputs_empty))
|
||||
return
|
||||
}
|
||||
Column {
|
||||
outputs.forEach { out ->
|
||||
Row(
|
||||
@@ -405,8 +535,13 @@ private fun OutputsSection(outputs: List<Output>, canOpen: Boolean, onOpen: (Str
|
||||
|
||||
// --- Background tasks -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Subagents, a team's members and background commands, as the reference has them: "Running N"
|
||||
* with a card per task (elapsed and a stop each, those under it folded into "N under it"),
|
||||
* then "Finished N" folded away.
|
||||
*/
|
||||
@Composable
|
||||
private fun TasksSection(activity: Activity, readAt: Long, now: Long, onStop: (ActivityAgent) -> Unit, onRead: (ActivityAgent) -> Unit) {
|
||||
private fun TasksSection(activity: Activity, readAt: Long, now: Long, actions: ActivityActions, unfolded: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val team = activity.team
|
||||
if (activity.agents.isEmpty() && team == null) {
|
||||
@@ -414,14 +549,8 @@ private fun TasksSection(activity: Activity, readAt: Long, now: Long, onStop: (A
|
||||
return
|
||||
}
|
||||
val (live, ended) = ActivityLogic.split(activity.agents)
|
||||
var showEnded by rememberSaveable { mutableStateOf(false) }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
val counts = ActivityLogic.stripCounts(activity.summary)
|
||||
Text(
|
||||
if (counts.isEmpty()) stringResource(R.string.tasks_none_running) else counts.map { (s, n) -> stateCount(s, n) }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
var showEnded by rememberSaveable { mutableStateOf(unfolded) }
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
team?.let { t ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Groups, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp))
|
||||
@@ -433,48 +562,118 @@ private fun TasksSection(activity: Activity, readAt: Long, now: Long, onStop: (A
|
||||
}
|
||||
if (t.goal.isNotBlank()) Text(t.goal, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
ActivityLogic.flatten(live).forEach { AgentRow(it, readAt, now, onStop, onRead) }
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.tasks_running), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
Text(live.size.toString(), style = MaterialTheme.typography.labelLarge, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
if (live.isEmpty()) Empty(stringResource(R.string.tasks_none_running))
|
||||
live.forEachIndexed { i, task -> TaskCard(task, readAt, now, actions, unfolded && i == 0) }
|
||||
if (ended.isNotEmpty()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { showEnded = !showEnded },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(if (showEnded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = palette.inkFaint)
|
||||
Icon(
|
||||
if (showEnded) Icons.Filled.ExpandMore else Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.agents_n_finished, ended.size.toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
stringResource(R.string.tasks_finished),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
Text(ended.size.toString(), style = MaterialTheme.typography.labelLarge, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
if (showEnded) ActivityLogic.flatten(ended).forEach { AgentRow(it, readAt, now, onStop, onRead) }
|
||||
if (showEnded) ended.forEach { TaskCard(it, readAt, now, actions, unfolded = false) }
|
||||
}
|
||||
team?.let { t ->
|
||||
Text(stringResource(R.string.team_room), style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 12.dp))
|
||||
if (t.room.isEmpty()) Empty(stringResource(R.string.room_empty)) else t.room.forEach { RoomEntry(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** One top-level task as a card of its own, with the tasks under it inside, folded. */
|
||||
@Composable
|
||||
private fun TaskCard(agent: ActivityAgent, readAt: Long, now: Long, actions: ActivityActions, unfolded: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
var nestedOpen by rememberSaveable(agent.kind, agent.id, "nested") { mutableStateOf(unfolded) }
|
||||
Surface(
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(vertical = 2.dp)) {
|
||||
TaskRow(agent, readAt, now, actions, unfolded)
|
||||
val under = ActivityLogic.descendants(agent)
|
||||
if (under > 0) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 40.dp).clickable { nestedOpen = !nestedOpen }.padding(start = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (nestedOpen) Icons.Filled.ExpandMore else Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.tasks_nested, under.toString()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 4.dp),
|
||||
)
|
||||
}
|
||||
if (nestedOpen) ActivityLogic.flatten(agent.children).forEach { TaskRow(it, readAt, now, actions, unfolded = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent: a fixed row (state dot, what it is -- the part that gives, cut not wrapped --,
|
||||
* elapsed time in a column of its own width, the stop button at its tap size), indented by
|
||||
* its depth in the tree; tapped, it opens to its brief, model, latest step and what it is
|
||||
* writing, and the way into its conversation.
|
||||
* One task: a fixed row (chevron, kind icon, what it is -- the part that gives, cut not
|
||||
* wrapped --, elapsed time in a column of its own width, the stop square at its tap size),
|
||||
* indented by its depth; tapped, it opens to its brief, model, latest step and live text, and
|
||||
* the way into its conversation.
|
||||
*/
|
||||
@Composable
|
||||
private fun AgentRow(agent: ActivityAgent, readAt: Long, now: Long, onStop: (ActivityAgent) -> Unit, onRead: (ActivityAgent) -> Unit) {
|
||||
private fun TaskRow(agent: ActivityAgent, readAt: Long, now: Long, actions: ActivityActions, unfolded: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(agent.kind, agent.id) { mutableStateOf(false) }
|
||||
var open by rememberSaveable(agent.kind, agent.id) { mutableStateOf(unfolded) }
|
||||
Column(Modifier.fillMaxWidth().padding(start = (16 * agent.depth.coerceIn(0, 4)).dp)) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = !open },
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = !open }.padding(start = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(stateColour(palette, agent.state)))
|
||||
Icon(
|
||||
if (open) Icons.Filled.ExpandMore else Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Icon(
|
||||
when {
|
||||
agent.kind == "member" -> Icons.Filled.Groups
|
||||
agent.type == "command" -> Icons.Filled.Terminal
|
||||
else -> Icons.Filled.SmartToy
|
||||
},
|
||||
contentDescription = kindWord(agent),
|
||||
tint = stateColour(palette, agent.state),
|
||||
modifier = Modifier.padding(start = 4.dp).size(18.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f).padding(horizontal = 8.dp)) {
|
||||
Text(agent.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (agent.role.isNotBlank()) {
|
||||
Text(agent.role, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(ActivityLogic.title(agent), style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val sub = listOfNotNull(
|
||||
if (agent.kind == "member") agent.role.ifBlank { null } else null,
|
||||
if (agent.isActive) null else stateWord(agent.state),
|
||||
)
|
||||
if (sub.isNotEmpty()) {
|
||||
Text(
|
||||
sub.joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
@@ -485,23 +684,40 @@ private fun AgentRow(agent: ActivityAgent, readAt: Long, now: Long, onStop: (Act
|
||||
modifier = Modifier.width(64.dp),
|
||||
)
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
if (agent.stoppable) {
|
||||
IconButton(onClick = { onStop(agent) }) {
|
||||
Icon(Icons.Filled.StopCircle, contentDescription = stringResource(R.string.agent_stop, agent.name), tint = palette.inkMuted)
|
||||
if (agent.stoppable && agent.isActive) {
|
||||
IconButton(onClick = { actions.stop(agent) }) {
|
||||
Box(
|
||||
Modifier.size(24.dp).clip(RoundedCornerShape(6.dp)).background(palette.surfaceActive),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Stop,
|
||||
contentDescription = stringResource(R.string.agent_stop, ActivityLogic.title(agent)),
|
||||
tint = palette.ink,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (open) {
|
||||
Column(Modifier.padding(start = 16.dp, bottom = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Column(Modifier.padding(start = 34.dp, end = 12.dp, bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
val facts = listOfNotNull(
|
||||
kindWord(agent),
|
||||
stateWord(agent.state),
|
||||
agent.agent.ifBlank { null },
|
||||
agent.model.ifBlank { null },
|
||||
if (agent.steps > 0) stringResource(R.string.agent_steps, agent.steps.toString(), agent.tools.toString()) else null,
|
||||
)
|
||||
Text(facts.joinToString(" · "), style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
|
||||
if (agent.brief.isNotBlank()) Text(agent.brief, style = MaterialTheme.typography.bodySmall)
|
||||
if (agent.brief.isNotBlank() && agent.brief != ActivityLogic.title(agent)) {
|
||||
Text(
|
||||
agent.brief,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = if (agent.type == "command") FontFamily.Monospace else null,
|
||||
)
|
||||
}
|
||||
agent.step?.let { step ->
|
||||
Text(
|
||||
listOf(step.label.ifBlank { step.tool }, step.title).filter { it.isNotBlank() }.joinToString(" "),
|
||||
@@ -516,7 +732,7 @@ private fun AgentRow(agent: ActivityAgent, readAt: Long, now: Long, onStop: (Act
|
||||
Text(agent.text, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = 6, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (agent.transcript) {
|
||||
OutlinedButton(onClick = { onRead(agent) }) {
|
||||
OutlinedButton(onClick = { actions.read(agent) }) {
|
||||
Icon(Icons.Filled.Visibility, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Text(stringResource(R.string.agent_open_conversation), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
@@ -526,6 +742,13 @@ private fun AgentRow(agent: ActivityAgent, readAt: Long, now: Long, onStop: (Act
|
||||
}
|
||||
}
|
||||
|
||||
// --- The room -------------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun RoomSection(team: ActivityTeam) {
|
||||
if (team.room.isEmpty()) Empty(stringResource(R.string.room_empty)) else Column { team.room.forEach { RoomEntry(it) } }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RoomEntry(entry: RoomMessage) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -561,22 +784,57 @@ private fun RoomEntry(entry: RoomMessage) {
|
||||
/** What a background agent was told and said: `GET /chats/{chat}/agents/{kind}/{id}`, re-read while it works. */
|
||||
@Composable
|
||||
private fun AgentConversation(chatId: String, agent: ActivityAgent, onClose: () -> Unit) {
|
||||
val state = stateWord(agent.state)
|
||||
ConversationDialog(
|
||||
name = agent.name,
|
||||
facts = listOf(state, agent.model),
|
||||
key = agent.kind + "/" + agent.id,
|
||||
onClose = onClose,
|
||||
) { api ->
|
||||
val detail = api.agent(chatId, agent.kind, agent.id)
|
||||
Conversation(detail.transcript, detail.agent.isActive)
|
||||
}
|
||||
}
|
||||
|
||||
/** A tree subagent's conversation (spec 3.4.0 §11), read-only, followed while it runs. */
|
||||
@Composable
|
||||
private fun SubagentConversation(chatId: String, agent: TreeAgent, onClose: () -> Unit) {
|
||||
ConversationDialog(
|
||||
name = "${agent.name} (${agent.id})",
|
||||
facts = listOf(treeStateWord(agent.state), agent.position, agent.model),
|
||||
key = "tree/" + agent.id,
|
||||
onClose = onClose,
|
||||
) { api ->
|
||||
val read = api.subagentTranscript(chatId, agent.id)
|
||||
Conversation(read.turns, read.state !in TreeLogic.ENDED)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a conversation dialog draws: the turns, and whether to read them again (it still runs). */
|
||||
private class Conversation(val turns: List<AgentTurn>, val running: Boolean)
|
||||
|
||||
/**
|
||||
* An agent's conversation, full screen and read-only: read with [load], again every 3 s while
|
||||
* it runs. Nobody types into it.
|
||||
*/
|
||||
@Composable
|
||||
private fun ConversationDialog(name: String, facts: List<String>, key: String, onClose: () -> Unit, load: suspend (ApiClient) -> Conversation) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var detail by remember { mutableStateOf<AgentDetail?>(null) }
|
||||
var detail by remember { mutableStateOf<Conversation?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(agent.kind, agent.id) {
|
||||
LaunchedEffect(key) {
|
||||
val api = context.lembas.instances.client() ?: return@LaunchedEffect
|
||||
while (true) {
|
||||
try {
|
||||
detail = api.agent(chatId, agent.kind, agent.id)
|
||||
detail = load(api)
|
||||
error = null
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
error = context.explain(e)
|
||||
}
|
||||
if (detail?.agent?.isActive != true) break
|
||||
if (detail?.running != true) break
|
||||
delay(3_000)
|
||||
}
|
||||
}
|
||||
@@ -587,20 +845,20 @@ private fun AgentConversation(chatId: String, agent: ActivityAgent, onClose: ()
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(agent.name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val now = detail?.agent ?: agent
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
listOf(stateWord(now.state), now.model).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
facts.filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
val turns = detail?.transcript
|
||||
val turns = detail?.turns
|
||||
when {
|
||||
turns == null && error != null -> Box(Modifier.padding(padding).fillMaxSize().padding(32.dp), contentAlignment = Alignment.Center) {
|
||||
Text(error.orEmpty(), color = palette.inkMuted, textAlign = TextAlign.Center)
|
||||
|
||||
@@ -51,86 +51,17 @@ import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.took
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
private val Rounded = RoundedCornerShape(10.dp)
|
||||
private val Rounded = RoundedCornerShape(12.dp)
|
||||
|
||||
/** The person's own turn: their words as typed (never markdown), and what they attached. */
|
||||
/** A reply's steps, as the transcript draws them ([StepsCompact]); the assistant's sheet uses it. */
|
||||
@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)
|
||||
}
|
||||
}
|
||||
}
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null) = StepsCompact(steps, modifier, onShow)
|
||||
|
||||
/**
|
||||
* A reply's steps, in the order they happened: the same table of contents the web page draws.
|
||||
* [onShow] opens a `show` card's file; without it (the assistant's sheet) the card only names it.
|
||||
*/
|
||||
@Composable
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null) {
|
||||
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, onShow = onShow) }
|
||||
"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) {
|
||||
internal fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
"shell" -> Icons.Filled.Terminal
|
||||
"edit" -> Icons.Filled.Edit
|
||||
"read" -> Icons.AutoMirrored.Filled.Article
|
||||
@@ -167,7 +98,8 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
|
||||
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 },
|
||||
// The one short title; a call without one is named as a person reads the tool.
|
||||
call.block.title.ifBlank { call.block.label.ifBlank { call.name } },
|
||||
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
maxLines = if (open) 6 else 1,
|
||||
@@ -177,6 +109,10 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
|
||||
call.block.chips.forEach { chip ->
|
||||
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
// How long a finished call took (display.md §2); a running or a denied one shows none.
|
||||
call.took()?.let { took ->
|
||||
Text(took, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
call.purpose?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
@@ -250,21 +186,3 @@ private fun ShowCardRow(show: ShowCard, depth: Int, onShow: ((ShowCard) -> Unit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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))
|
||||
}
|
||||
@@ -58,6 +58,7 @@ fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
}
|
||||
when (card.kind) {
|
||||
"approval" -> Approval(card, onAnswer)
|
||||
"phone_action" -> PhoneCard(card, onAnswer)
|
||||
"plan" -> PlanCard(card, onAnswer)
|
||||
else -> Questions(card, onAnswer)
|
||||
}
|
||||
@@ -72,21 +73,40 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
var refusing by remember { mutableStateOf(false) }
|
||||
Text(stringResource(R.string.card_approval), style = MaterialTheme.typography.titleMedium)
|
||||
card.items.forEach { item ->
|
||||
// A subagent asks, not the chat's own turn: said first, as the page says it.
|
||||
val subagent = item.subagent
|
||||
if (subagent != null) {
|
||||
Text(
|
||||
stringResource(R.string.card_subagent_asks, subagent.name, subagent.id, subagent.position.ifBlank { "—" }),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.accent,
|
||||
)
|
||||
} else if (item.job.isNotBlank()) {
|
||||
Text(stringResource(R.string.card_asker, item.job), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
}
|
||||
// `title` is the heading ("Run a command"); `detail` is the thing itself, the command.
|
||||
if (item.title.isNotBlank()) Text(item.title, style = MaterialTheme.typography.titleSmall)
|
||||
if (item.purpose.isNotBlank()) {
|
||||
Text(stringResource(R.string.card_it_says, item.purpose), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (item.editable) {
|
||||
OutlinedTextField(
|
||||
value = edits[item.key] ?: item.title,
|
||||
value = edits[item.key] ?: item.detail,
|
||||
onValueChange = { edits[item.key] = it },
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
|
||||
label = { Text(stringResource(R.string.card_change_before)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Text(item.title, fontFamily = FontFamily.Monospace)
|
||||
if (approvalTexts(listOf(item), edits).isNotEmpty()) {
|
||||
Text(stringResource(R.string.card_edit_runs), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
} else if (item.detail.isNotBlank()) {
|
||||
Text(item.detail, 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)
|
||||
if (item.reason.isNotBlank()) Text(item.reason, 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 }
|
||||
// A corrected command goes with an allow, never with a refusal, and only when it was corrected.
|
||||
val texts = approvalTexts(card.items, edits)
|
||||
if (refusing) {
|
||||
OutlinedTextField(
|
||||
value = reason,
|
||||
@@ -101,14 +121,32 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
} 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))
|
||||
// Only where the request offers it: a call that may only ever be allowed once has none.
|
||||
if (offersAlways(card)) {
|
||||
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)) }
|
||||
// The spec's four actions (display.md §5): Deny at once, or with the person's words to the model.
|
||||
TextButton(onClick = { onAnswer(CardAnswer(verdict = "deny")) }) { Text(stringResource(R.string.card_deny)) }
|
||||
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny_reason)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What an approval's allow sends in `texts`: the box of each `editable` item whose text differs
|
||||
* from the item's `detail` (the command it was offered with). An untouched box sends nothing, so
|
||||
* the server runs what the model asked for; a cleared box is no correction either.
|
||||
*/
|
||||
fun approvalTexts(items: List<CardItem>, edits: Map<String, String>): Map<String, String> = items
|
||||
.filter { it.editable }
|
||||
.mapNotNull { item ->
|
||||
val edited = edits[item.key]?.trim() ?: return@mapNotNull null
|
||||
if (edited.isEmpty() || edited == item.detail.trim()) null else item.key to edited
|
||||
}
|
||||
.toMap()
|
||||
|
||||
@Composable
|
||||
private fun Questions(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -171,20 +209,11 @@ private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String
|
||||
@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,
|
||||
@@ -194,15 +223,27 @@ private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
)
|
||||
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
|
||||
} else {
|
||||
// Approve together with the mode the work continues in (display.md §5), where the
|
||||
// session may choose one; otherwise Approve alone. And Revise.
|
||||
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)) }
|
||||
if (item.modeChoice) {
|
||||
Button(onClick = { onAnswer(planApproval(item, "edit")) }) { Text(stringResource(R.string.plan_approve_edit)) }
|
||||
OutlinedButton(onClick = { onAnswer(planApproval(item, "manual")) }) { Text(stringResource(R.string.plan_approve_manual)) }
|
||||
} else {
|
||||
Button(onClick = { onAnswer(planApproval(item, null)) }) { Text(stringResource(R.string.plan_approve)) }
|
||||
}
|
||||
TextButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an approval card offers "Always allow": only when every call on it may be remembered (`always`). */
|
||||
internal fun offersAlways(card: Card): Boolean = card.items.isNotEmpty() && card.items.all { it.always }
|
||||
|
||||
/** A plan's approval as the server reads it: allow, and the mode to continue in where one was chosen. */
|
||||
internal fun planApproval(item: CardItem, mode: String?): CardAnswer =
|
||||
CardAnswer(verdict = "allow", choices = if (item.modeChoice && mode != null) mapOf(item.key to listOf(mode)) else emptyMap())
|
||||
|
||||
/** A plan's phases and tasks, ticked as the reply works through them. */
|
||||
@Composable
|
||||
fun PlanBody(plan: Plan) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,7 @@ import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentSubagents
|
||||
import eu.llembas.android.api.AgentTarget
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.ApiClient
|
||||
@@ -19,18 +20,26 @@ 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.ChatDetail
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.MessagePage
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StartModel
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.Turn
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
@@ -48,6 +57,8 @@ data class ChatState(
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
/** For a new agent chat: the devices linked right now, which it can run on. */
|
||||
val devices: List<LinkedDevice> = emptyList(),
|
||||
/** For a new agent chat: the instance's address, which `lembas login` is given to link a computer. */
|
||||
val instanceBase: String = "",
|
||||
val pending: List<Attachment> = emptyList(),
|
||||
val uploading: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
@@ -61,20 +72,196 @@ data class ChatState(
|
||||
val activityAt: Long = 0,
|
||||
/** The strip's counts, from the events route (or the first read). */
|
||||
val summary: ActivitySummary? = null,
|
||||
/** Whether this chat may have a team: the server's word for a chat that exists. */
|
||||
/** Whether this chat is offered subagents: the activity's word for a chat that exists. */
|
||||
val teamOffered: Boolean = false,
|
||||
/** The instance's cap on a chat's subagents, from the models list; null from an older server. */
|
||||
val modelsCap: Int? = null,
|
||||
/** Whether the events route is followed; without it an open panel polls. */
|
||||
val activityLive: Boolean = false,
|
||||
/** A Compact asked for from the activity sheet and not answered yet. */
|
||||
val compacting: Boolean = false,
|
||||
/** What a chat not made yet will be made with: chosen in the top bar and the tune sheet. */
|
||||
val draft: Draft = Draft(),
|
||||
/** The instance makes pictures for this person (`/me` `services.images`). */
|
||||
val imagesOffered: Boolean = false,
|
||||
/** The subagent tree (spec 3.4.0) from this chat's last `tree` frame; null until one came. */
|
||||
val tree: SubagentTree? = null,
|
||||
/** For a new agent chat: whether it may have subagents, and whether its device runs them. */
|
||||
val agentSubagents: AgentSubagents? = null,
|
||||
/**
|
||||
* For a new agent chat: the model it starts on in the chosen device and folder when the
|
||||
* person picks none (spec 3.9.0) -- the folder's usual model, as the instance asked the
|
||||
* device. Shown, never sent and never kept: the instance does the same on its own.
|
||||
*/
|
||||
val start: StartModel? = null,
|
||||
/** What `@` offers for the word being typed: the server's files, earlier attachments and pages, or an agent chat's device's files. */
|
||||
val mentions: List<Mention> = emptyList(),
|
||||
/** The message this app sent last, by its id: what the transcript shows whoever has scrolled where. */
|
||||
val lastSent: String? = null,
|
||||
/** The model picked for this open chat, by its ref: which of two models with one id the chat is on. */
|
||||
val picked: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* The choices for a chat its first message makes. Nothing here is sent until then; an open
|
||||
* chat changes at once instead (`PATCH`), as the web page's controls do.
|
||||
*/
|
||||
data class Draft(
|
||||
val model: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: AgentsSetting? = null,
|
||||
val plan: Boolean = false,
|
||||
val agentMode: String = "edit",
|
||||
val device: String? = null,
|
||||
val directory: String = "",
|
||||
/** The next message asks for a picture (`force_tool: image_generate`); cleared once sent. */
|
||||
val image: Boolean = false,
|
||||
)
|
||||
|
||||
/** The one tool a message may force (the server's `FORCEABLE_TOOLS`): make a picture. */
|
||||
const val IMAGE_TOOL = "image_generate"
|
||||
|
||||
/**
|
||||
* The model in force: the chat's, else the one chosen for the new chat, else the folder's usual
|
||||
* one (a new agent chat's, where the person still has it), else the default. A model the
|
||||
* person picked is never set aside by the folder's.
|
||||
*/
|
||||
val ChatState.modelId: String?
|
||||
get() = chatModel ?: draft.model ?: folderModel ?: models.firstOrNull { it.default }?.key ?: models.firstOrNull()?.key
|
||||
|
||||
/**
|
||||
* An open chat's model. The chat says its model's id, which two connections may share; the one
|
||||
* picked here ([ChatState.picked], a ref) says which of them, for as long as the chat is still
|
||||
* on a model of that id.
|
||||
*/
|
||||
val ChatState.chatModel: String?
|
||||
get() {
|
||||
val served = chat?.model?.ifBlank { null } ?: return null
|
||||
return picked?.takeIf { models.named(it)?.id == served } ?: served
|
||||
}
|
||||
|
||||
/** The folder's usual model for a chat not made yet, when it is one of the models offered here. */
|
||||
val ChatState.folderModel: String?
|
||||
get() = start?.takeIf { chat == null }?.let { models.named(it.key) ?: models.named(it.model) }?.key
|
||||
|
||||
val ChatState.modelInfo: ModelInfo? get() = models.named(modelId)
|
||||
|
||||
/** The thinking level in force, by the model's levels; null for a model with no choice. */
|
||||
val ChatState.level: String?
|
||||
get() = modelInfo?.takeIf { it.levelControl != "none" }?.level(if (chat == null) draft.effort else chat.effort?.ifBlank { null })
|
||||
|
||||
/**
|
||||
* Whether the Subagents setting is shown (plan rule 4): the chat's own word for a chat that
|
||||
* exists (`subagents.offered`, else the activity's), the model's for a new one.
|
||||
*/
|
||||
fun ChatState.offersTeam(agent: Boolean): Boolean = when {
|
||||
chat != null -> chat.subagents?.offered ?: teamOffered
|
||||
|
||||
// A new agent chat: the server's word for agent chats (spec 3.4.0 §14), never a guess.
|
||||
agent -> agentSubagents?.offered == true
|
||||
|
||||
else -> modelInfo?.mayHaveTeam == true
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether subagents need a model the person names in the chat: the chat's own serves one
|
||||
* request at a time. The setting then says so; there is no default to fall back on.
|
||||
*/
|
||||
val ChatState.subagentsNamedOnly: Boolean
|
||||
get() = (if (chat != null) chat.subagents?.namedOnly else modelInfo?.subagents?.namedOnly) ?: false
|
||||
|
||||
/** The most subagents a chat may have here: the chat's cap, else the instance's, else the spec's. */
|
||||
val ChatState.subagentsCap: Int
|
||||
get() = (chat?.subagents?.cap ?: modelsCap ?: AgentsSetting.CAP).coerceAtLeast(1)
|
||||
|
||||
/** The team's size in force. */
|
||||
val ChatState.agents: AgentsSetting get() = chat?.agents ?: draft.agents ?: AgentsSetting()
|
||||
|
||||
/** Whether a reply is being written right now. */
|
||||
val ChatState.running: Boolean get() = live != null && live.finished == null
|
||||
|
||||
/** The linked device a new agent chat runs on: the chosen one, else the first. */
|
||||
val ChatState.device: LinkedDevice? get() = devices.firstOrNull { it.id == draft.device } ?: devices.firstOrNull()
|
||||
|
||||
/**
|
||||
* An older [page], read before the message [before], put above the transcript. Only while
|
||||
* [before] is still the first row -- a transcript read again meanwhile has moved, and the page
|
||||
* no longer belongs above it -- and never a row twice: the list's rows are keyed by id, and a
|
||||
* key drawn twice ends the app.
|
||||
*/
|
||||
fun ChatState.withOlder(before: String, page: MessagePage): ChatState {
|
||||
if (messages.firstOrNull()?.id != before) return this
|
||||
val have = messages.mapTo(HashSet()) { it.id }
|
||||
return copy(messages = page.messages.distinctBy { it.id }.filterNot { it.id in have } + messages, more = page.more)
|
||||
}
|
||||
|
||||
/**
|
||||
* The stream of the reply [messageId] closed without a `done`. What was written stays in view:
|
||||
* the transcript as the server has it now ([reread]), or -- where that could not be read -- the
|
||||
* row with the steps the stream had shown, closed, and how it ended where the stream said so.
|
||||
* Nothing is live after it. A reply another stream is being followed for is left alone.
|
||||
*/
|
||||
fun ChatState.closedUnfinished(messageId: String, reread: ChatDetail?): ChatState {
|
||||
val was = live?.takeIf { it.messageId == messageId }
|
||||
if (live != null && was == null) return this
|
||||
if (reread != null) return copy(chat = reread.chat, messages = reread.messages, more = reread.more, live = null)
|
||||
if (was == null || was.shown.isEmpty()) return copy(live = null)
|
||||
val kept = was.shown.map { it.copy(open = false) }
|
||||
return copy(
|
||||
live = null,
|
||||
messages = messages.map { if (it.id == messageId) it.copy(steps = kept, progress = it.progress ?: was.end) else it },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* What the chat screen asks of its model. Every action has a do-nothing default, so the
|
||||
* screenshot tests draw the screen with fake data and no server behind it.
|
||||
*/
|
||||
interface ChatActions {
|
||||
fun send(text: String) {}
|
||||
fun stop() {}
|
||||
fun regenerate(message: Message) {}
|
||||
fun edit(message: Message, text: String) {}
|
||||
fun continueChat() {}
|
||||
fun executePlan() {}
|
||||
fun answer(card: Card, answer: CardAnswer) {}
|
||||
fun change(key: String, value: String?) {}
|
||||
|
||||
/** A new agent chat with no computer linked: read the linked devices again. */
|
||||
fun recheckDevices() {}
|
||||
|
||||
/** A new agent chat's device, asked for a directory (`""`: its places), for the folder picker. */
|
||||
suspend fun directories(path: String): DeviceDirectory = DeviceDirectory()
|
||||
fun setAgents(agents: AgentsSetting) {}
|
||||
fun updateDraft(change: (Draft) -> Draft) {}
|
||||
fun attach(uris: List<Uri>) {}
|
||||
|
||||
/** The `@` word being typed ([query]; null: none) -- what it offers comes to the state's `mentions`. */
|
||||
fun suggest(query: String?) {}
|
||||
|
||||
/** Attach what an `@` entry names: an earlier attachment, a file of the tree, or a page. */
|
||||
fun mention(item: Mention) {}
|
||||
fun unattach(attachment: Attachment) {}
|
||||
fun photoTarget(): Uri? = null
|
||||
fun rename(title: String) {}
|
||||
fun delete(then: () -> Unit) {}
|
||||
fun older() {}
|
||||
fun clearUnsent() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
class ChatViewModel(app: Application) :
|
||||
AndroidViewModel(app),
|
||||
ChatActions {
|
||||
private val _state = MutableStateFlow(ChatState())
|
||||
val state = _state.asStateFlow()
|
||||
private var following: Job? = null
|
||||
|
||||
/** Whether this screen makes an agent chat (until its first message makes it). */
|
||||
private var agentChat = false
|
||||
private var api: ApiClient? = null
|
||||
|
||||
private suspend fun api(): ApiClient = api ?: getApplication<Application>().lembas.instances.client()?.also { api = it }
|
||||
@@ -83,25 +270,69 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private fun fail(e: Throwable) {
|
||||
// A follow that was replaced by a newer one is cancelled, not failed: nothing to say.
|
||||
if (e is CancellationException) return
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = false) }
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e), loading = false, uploading = uploads > 0) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun clearUnsent() = _state.update { it.copy(unsent = null) }
|
||||
override fun clearUnsent() = _state.update { it.copy(unsent = null) }
|
||||
|
||||
fun rename(title: String) = change("title", title.trim())
|
||||
override fun updateDraft(change: (Draft) -> Draft) {
|
||||
val before = _state.value.let { it.device?.id to it.draft.directory }
|
||||
_state.update { it.copy(draft = change(it.draft)) }
|
||||
val after = _state.value.let { it.device?.id to it.draft.directory }
|
||||
// Another computer or another folder: its Subagents fact and its usual model are read again.
|
||||
if (agentChat && _state.value.chat == null && after != before) readAgentFacts()
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat's facts for the device and folder chosen now: whether it may have
|
||||
* subagents, and the model it starts on there. An older server says neither; an answer for
|
||||
* a choice that has changed meanwhile is dropped.
|
||||
*/
|
||||
private fun readAgentFacts() {
|
||||
val device = _state.value.device?.id
|
||||
val directory = _state.value.draft.directory
|
||||
// What was read for another device or folder is not this one's.
|
||||
_state.update { it.copy(start = null) }
|
||||
viewModelScope.launch {
|
||||
val list = runCatching { api().agentModelList(device, directory) }.getOrNull()
|
||||
_state.update {
|
||||
if (it.device?.id == device &&
|
||||
it.draft.directory == directory
|
||||
) {
|
||||
it.copy(agentSubagents = list?.agentSubagents, start = list?.start)
|
||||
} else {
|
||||
it
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun directories(path: String): DeviceDirectory {
|
||||
// No computer linked: there is nothing to list, and the typed path is what remains.
|
||||
val device = _state.value.device ?: return DeviceDirectory(code = "device_not_linked")
|
||||
return api().deviceDirectories(device.id, path)
|
||||
}
|
||||
|
||||
override fun rename(title: String) = change("title", title.trim())
|
||||
|
||||
/** Open a chat, or (no id) get a new one ready: an agent chat also needs the linked devices. */
|
||||
fun open(chatId: String?, agent: Boolean = false) {
|
||||
agentChat = agent
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
_state.update { it.copy(loading = chatId != null || agent, error = null) }
|
||||
val models = runCatching { client.models(chatId) }.getOrDefault(emptyList())
|
||||
_state.update { it.copy(loading = chatId != null || agent, error = null, tree = null) }
|
||||
val list = runCatching { client.modelList(chatId) }.getOrNull()
|
||||
val models = list?.models.orEmpty()
|
||||
_state.update { it.copy(modelsCap = list?.subagentsCap) }
|
||||
if (!agent) runCatching { client.me() }.onSuccess { me -> _state.update { it.copy(imagesOffered = me.hasImages) } }
|
||||
if (chatId == null) {
|
||||
val devices = if (agent) client.devices() else emptyList()
|
||||
_state.update { it.copy(models = models, devices = devices, loading = false) }
|
||||
val base = if (agent) getApplication<Application>().lembas.instances.current()?.base.orEmpty() else ""
|
||||
_state.update { it.copy(models = models, devices = devices, instanceBase = base, loading = false) }
|
||||
if (agent) readAgentFacts()
|
||||
return@launch
|
||||
}
|
||||
val detail = client.chat(chatId)
|
||||
@@ -112,7 +343,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
// Whether a team is offered and what runs in the background: the cheap read,
|
||||
// without the context count. A server without the panel has no answer.
|
||||
runCatching { client.activity(chatId, context = false) }.onSuccess { a ->
|
||||
_state.update { it.copy(teamOffered = a.teamOffered, summary = a.summary) }
|
||||
_state.update { it.copy(teamOffered = a.subagentsOffered ?: a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
@@ -120,12 +351,28 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
fun older() {
|
||||
override fun recheckDevices() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true) }
|
||||
try {
|
||||
val devices = api().devices()
|
||||
_state.update { it.copy(devices = devices, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var olderRead: Job? = null
|
||||
|
||||
/** The page before the first row. One read at a time: a second tap while one is under way is not a second page. */
|
||||
override fun older() {
|
||||
if (olderRead?.isActive == true) return
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
olderRead = viewModelScope.launch {
|
||||
runCatching { api().messages(chat.id, first.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(messages = page.messages + it.messages, more = page.more) } }
|
||||
.onSuccess { page -> _state.update { it.withOlder(first.id, page) } }
|
||||
.onFailure(::fail)
|
||||
}
|
||||
}
|
||||
@@ -136,13 +383,47 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
following?.cancel()
|
||||
following = viewModelScope.launch {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
// Set at `done`, which is the end of the reply: from then on the stream is followed
|
||||
// only for the name a model may still give the chat (the `title` frame).
|
||||
var ended: LiveReply? = null
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s -> s.copy(live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)) }
|
||||
val before = ended
|
||||
if (before != null) {
|
||||
val named = before.apply(frame.event, frame.data)
|
||||
ended = named
|
||||
if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) }
|
||||
return@collect
|
||||
}
|
||||
val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
val finished = live.finished
|
||||
if (finished == null) {
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
_state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) }
|
||||
return@collect
|
||||
}
|
||||
ended = live
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
live = null,
|
||||
tree = live.tree ?: s.tree,
|
||||
messages = s.messages.map { if (it.id == finished.id) finished else it },
|
||||
chat = s.chat?.let { c -> live.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 -- and that reply is
|
||||
// followed instead of this stream's tail.
|
||||
live.next?.let { next ->
|
||||
refresh()
|
||||
follow(next)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// After `done` only the name was still to come: nothing to say, nothing to redo.
|
||||
if (ended != null) return@launch
|
||||
fail(e)
|
||||
// The reply goes on on the server; what it has written so far is read back
|
||||
// rather than left half-drawn.
|
||||
@@ -150,20 +431,20 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
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)
|
||||
// The stream closed without a `done`: the row is gone on the server, or it ended some
|
||||
// way the stream did not tell. The transcript is read again, so what was written is
|
||||
// still there; where it cannot be read, what the stream had shown stays.
|
||||
if (ended == null) {
|
||||
val reread = try {
|
||||
api().chat(chat.id)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
_state.update { it.closedUnfinished(messageId, reread) }
|
||||
// Another reply is being written there (a queued turn): that one is followed.
|
||||
reread?.live?.takeIf { it != messageId }?.let { follow(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,28 +458,42 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
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))
|
||||
s.copy(
|
||||
messages = s.messages.filterNot { m -> m.id == turn.message?.id || m.id == turn.reply?.id } + listOfNotNull(turn.message, turn.reply),
|
||||
lastSent = turn.message?.id ?: s.lastSent,
|
||||
)
|
||||
}
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun send(
|
||||
text: String,
|
||||
model: String? = null,
|
||||
mode: String? = null,
|
||||
effort: String? = null,
|
||||
temporary: Boolean = false,
|
||||
agent: AgentTarget? = null,
|
||||
agents: AgentsSetting? = null,
|
||||
) {
|
||||
/**
|
||||
* Send [text] (and what is attached). A chat that does not exist yet is made by it, with the
|
||||
* draft's choices -- each only where the model offers it.
|
||||
*/
|
||||
override fun send(text: String) {
|
||||
val now = _state.value
|
||||
val draft = now.draft
|
||||
val newAgent = agentChat && now.chat == null
|
||||
val model = draft.model
|
||||
val mode = when {
|
||||
newAgent -> draft.agentMode
|
||||
draft.plan -> "plan"
|
||||
else -> null
|
||||
}
|
||||
val effort = draft.effort?.takeIf { picked -> now.modelInfo?.offered?.contains(picked) == true }
|
||||
val agent = if (newAgent) now.device?.let { AgentTarget(it.id, draft.directory) } else null
|
||||
val agents = draft.agents
|
||||
val temporary = false
|
||||
val attached = _state.value.pending
|
||||
val files = attached.map { it.id }
|
||||
if (text.isBlank() && files.isEmpty()) return
|
||||
// A picture, asked for from + (not in an agent chat, which runs on a computer).
|
||||
val picture = draft.image && now.imagesOffered && !agentChat
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val client = api()
|
||||
val chat = _state.value.chat
|
||||
_state.update { it.copy(pending = emptyList()) }
|
||||
_state.update { it.copy(pending = emptyList(), draft = it.draft.copy(image = false)) }
|
||||
if (chat == null) {
|
||||
val made = client.createChat(
|
||||
text,
|
||||
@@ -209,47 +504,48 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
mode = mode,
|
||||
agent = agent,
|
||||
agents = agents,
|
||||
forceTool = if (picture) IMAGE_TOOL else null,
|
||||
)
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply)) }
|
||||
_state.update { it.copy(chat = made.chat, messages = listOfNotNull(made.message, made.reply), lastSent = made.message?.id) }
|
||||
made.reply?.let { follow(it.id) }
|
||||
} else {
|
||||
took(client.sendMessage(chat.id, text, files))
|
||||
took(client.sendMessage(chat.id, text, files, forceTool = if (picture) IMAGE_TOOL else null))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Nothing was sent: the words and the attachments go back to the composer.
|
||||
_state.update { it.copy(pending = attached + it.pending, unsent = text) }
|
||||
_state.update { it.copy(pending = attached + it.pending, unsent = text, draft = it.draft.copy(image = picture || it.draft.image)) }
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
override 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 ->
|
||||
override 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 ->
|
||||
override 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)) }
|
||||
override fun continueChat() = control { api, chat -> took(api.continueChat(chat.id)) }
|
||||
|
||||
fun executePlan() = control { api, chat ->
|
||||
override fun executePlan() = control { api, chat ->
|
||||
took(api.executePlan(chat.id))
|
||||
refresh()
|
||||
}
|
||||
|
||||
fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
override fun answer(card: Card, answer: CardAnswer) = control { api, chat ->
|
||||
try {
|
||||
api.answer(chat.id, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
@@ -261,18 +557,20 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_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 ->
|
||||
override 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) }
|
||||
_state.update { it.copy(chat = updated, picked = if (key == "model") value else it.picked) }
|
||||
// Another model may serve one request at a time, or more: whether a team is offered
|
||||
// follows it.
|
||||
if (key == "model") {
|
||||
runCatching { api.activity(chat.id, context = false) }.onSuccess { r -> _state.update { it.copy(teamOffered = r.teamOffered) } }
|
||||
runCatching { api.activity(chat.id, context = false) }.onSuccess { r ->
|
||||
_state.update { it.copy(teamOffered = r.subagentsOffered ?: r.teamOffered) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The team's size, both ends; the server refuses a pair outside its bounds in its words. */
|
||||
fun setAgents(agents: AgentsSetting) = control { api, chat ->
|
||||
override fun setAgents(agents: AgentsSetting) = control { api, chat ->
|
||||
val updated = api.setAgents(chat.id, agents)
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
@@ -291,7 +589,7 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
if (_state.value.summary == null) {
|
||||
// A chat its first message just made: whether a team is offered, read once.
|
||||
runCatching { client.activity(chat.id, context = false) }.onSuccess { a ->
|
||||
_state.update { it.copy(teamOffered = a.teamOffered, summary = a.summary) }
|
||||
_state.update { it.copy(teamOffered = a.subagentsOffered ?: a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -329,9 +627,12 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
activity = if (context) read else read.copy(context = s.activity?.context),
|
||||
activityAt = SystemClock.elapsedRealtime(),
|
||||
summary = read.summary,
|
||||
teamOffered = read.teamOffered,
|
||||
teamOffered = read.subagentsOffered ?: read.teamOffered,
|
||||
)
|
||||
}
|
||||
// The tree (spec 3.4.0), for a sheet opened when no reply streams it; an older
|
||||
// server answers 404 and the Tasks section stands for it.
|
||||
runCatching { api().tree(chat.id) }.getOrNull()?.tree?.let { tree -> _state.update { it.copy(tree = tree) } }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
@@ -344,15 +645,46 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
loadActivity(context = false)
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
/** Compact the chat now; the transcript and the sheet are read again for what it changed. */
|
||||
fun compact() {
|
||||
val chat = _state.value.chat ?: return
|
||||
if (_state.value.compacting) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(compacting = true) }
|
||||
try {
|
||||
api().compact(chat.id)
|
||||
refresh()
|
||||
loadActivity()
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
} finally {
|
||||
_state.update { it.copy(compacting = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun delete(then: () -> Unit) = control { api, chat ->
|
||||
api.deleteChat(chat.id)
|
||||
then()
|
||||
}
|
||||
|
||||
fun attach(uris: List<Uri>) {
|
||||
/** How many uploads and attachings are under way: `uploading` holds until the last has ended. */
|
||||
private var uploads = 0
|
||||
|
||||
private fun uploadBegins() {
|
||||
uploads++
|
||||
_state.update { it.copy(uploading = true) }
|
||||
}
|
||||
|
||||
private fun uploadEnds() {
|
||||
uploads = (uploads - 1).coerceAtLeast(0)
|
||||
_state.update { it.copy(uploading = uploads > 0) }
|
||||
}
|
||||
|
||||
override fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
uploadBegins()
|
||||
try {
|
||||
val resolver = getApplication<Application>().contentResolver
|
||||
for (uri in uris) {
|
||||
@@ -371,7 +703,57 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
_state.update { it.copy(uploading = false) }
|
||||
uploadEnds()
|
||||
}
|
||||
}
|
||||
|
||||
private var suggesting: Job? = null
|
||||
|
||||
override fun suggest(query: String?) {
|
||||
suggesting?.cancel()
|
||||
if (query == null) {
|
||||
if (_state.value.mentions.isNotEmpty()) _state.update { it.copy(mentions = emptyList()) }
|
||||
return
|
||||
}
|
||||
suggesting = viewModelScope.launch {
|
||||
// Asked once the typing pauses, not at every letter.
|
||||
delay(MENTION_PAUSE_MS)
|
||||
val where = _state.value.let { Triple(it.chat?.id, it.device?.id, it.draft.directory) }
|
||||
val found = try {
|
||||
offered(query)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older server, or a device that cannot answer: nothing is offered.
|
||||
emptyList()
|
||||
}
|
||||
// Another computer or folder was chosen meanwhile: these were its files, not this one's.
|
||||
_state.update { if (Triple(it.chat?.id, it.device?.id, it.draft.directory) == where) it.copy(mentions = found) else it }
|
||||
}
|
||||
}
|
||||
|
||||
/** An agent chat's `@` is its device's files (the device reads them); a chat's is the server's. */
|
||||
private suspend fun offered(query: String): List<Mention> {
|
||||
val now = _state.value
|
||||
val chat = now.chat
|
||||
if (chat?.kind == "agent" || (chat == null && agentChat)) {
|
||||
val device = chat?.device?.tokenId ?: now.device?.id ?: return emptyList()
|
||||
return api().deviceFiles(device, query, chatId = chat?.id, cwd = now.draft.directory).files.mapNotNull { it.asMention() }.take(MENTION_LIMIT)
|
||||
}
|
||||
return api().mentions(query, chat?.id).items.take(MENTION_LIMIT)
|
||||
}
|
||||
|
||||
override fun mention(item: Mention) {
|
||||
_state.update { it.copy(mentions = emptyList()) }
|
||||
viewModelScope.launch {
|
||||
uploadBegins()
|
||||
try {
|
||||
val stored = api().attachFrom(item, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
uploadEnds()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,14 +763,14 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
* Where the camera writes a photo for the composer: a file in the app's cache, shared with
|
||||
* the camera app through the FileProvider for exactly this one capture.
|
||||
*/
|
||||
fun photoTarget(): Uri {
|
||||
override fun photoTarget(): Uri {
|
||||
val app = getApplication<Application>()
|
||||
val dir = File(app.cacheDir, "camera").apply { mkdirs() }
|
||||
val file = File(dir, "photo-${System.currentTimeMillis()}.jpg")
|
||||
return FileProvider.getUriForFile(app, photoAuthority, file)
|
||||
}
|
||||
|
||||
fun unattach(attachment: Attachment) {
|
||||
override fun unattach(attachment: Attachment) {
|
||||
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
|
||||
}
|
||||
|
||||
@@ -402,4 +784,8 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val MENTION_PAUSE_MS = 250L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.PickVisualMediaRequest
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
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.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Brush
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.PhotoCamera
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material.icons.filled.UploadFile
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.RangeSlider
|
||||
import androidx.compose.material3.SliderDefaults
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
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.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private val Field = RoundedCornerShape(28.dp)
|
||||
|
||||
/** The agent modes, as the web page offers them, in the order of how much the model may do. */
|
||||
val AGENT_MODES = listOf("manual", "edit", "auto", "plan")
|
||||
|
||||
@Composable
|
||||
fun modeName(mode: String): String = when (mode) {
|
||||
"manual" -> stringResource(R.string.mode_manual)
|
||||
"edit" -> stringResource(R.string.mode_edit)
|
||||
"auto" -> stringResource(R.string.mode_auto)
|
||||
"plan" -> stringResource(R.string.mode_plan)
|
||||
else -> mode.replaceFirstChar { it.uppercase() }
|
||||
}
|
||||
|
||||
/** A level's name: `off` and `default` in words, an effort as the model calls it. */
|
||||
@Composable
|
||||
fun levelName(level: String): String = when (level) {
|
||||
"off" -> stringResource(R.string.level_off)
|
||||
"default" -> stringResource(R.string.level_default)
|
||||
else -> level
|
||||
}
|
||||
|
||||
/**
|
||||
* The words on the tune button: what is set, briefly ("Thinking · Plan", "high · Agents 1–4"),
|
||||
* or nothing when all is as it starts.
|
||||
*/
|
||||
@Composable
|
||||
fun tuneSummary(state: ChatState, agent: Boolean): String {
|
||||
val parts = mutableListOf<String>()
|
||||
val info = state.modelInfo
|
||||
val level = state.level
|
||||
if (info != null && level != null) {
|
||||
when (info.levelControl) {
|
||||
"switch" -> if (level != "off") parts += stringResource(R.string.thinking)
|
||||
"slider" -> parts += levelName(level)
|
||||
}
|
||||
}
|
||||
val chat = state.chat
|
||||
when {
|
||||
agent || chat?.isAgent == true -> parts += modeName(chat?.mode?.ifBlank { null } ?: state.draft.agentMode)
|
||||
(chat == null && state.draft.plan) || chat?.mode == "plan" -> parts += stringResource(R.string.mode_plan)
|
||||
}
|
||||
// The team only once someone chose its size: the default says nothing worth repeating.
|
||||
val chosenTeam = state.chat?.agents ?: state.draft.agents
|
||||
if (state.offersTeam(agent) && chosenTeam != null && chosenTeam.max > 1) {
|
||||
parts += stringResource(R.string.team_chip, state.agents.min.toString(), state.agents.max.toString())
|
||||
}
|
||||
return parts.joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer: one rounded field with the attachments above the words and the controls
|
||||
* under them -- attach (+), the tune button (thinking, team, mode), the microphone, and Send,
|
||||
* which becomes Stop while a reply is being written and nothing new is typed. The controls'
|
||||
* row is a shared track: every icon keeps its 48 dp, the tune button's words give.
|
||||
*/
|
||||
@SuppressLint("MissingPermission")
|
||||
@Composable
|
||||
fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: () -> Unit, modifier: Modifier = Modifier, initial: String = "") {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var text by rememberSaveable { mutableStateOf(initial) }
|
||||
var attachMenu by remember { mutableStateOf(false) }
|
||||
var listening by remember { mutableStateOf(false) }
|
||||
var photo by remember { mutableStateOf<Uri?>(null) }
|
||||
val recorder = remember { Recorder(scope) }
|
||||
val phone = remember { PhoneRecognizer(context) }
|
||||
// What was typed before the phone's recogniser began: its words go after it as they come.
|
||||
var before by remember { mutableStateOf("") }
|
||||
DisposableEffect(Unit) { onDispose { phone.stop() } }
|
||||
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { actions.attach(it) }
|
||||
val pickPhotos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { actions.attach(it) }
|
||||
val takePhoto = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { taken ->
|
||||
photo?.let { if (taken) actions.attach(listOf(it)) }
|
||||
photo = null
|
||||
}
|
||||
|
||||
// Settings › Voice input decides, as it does for the assistant: the instance's speech-to-text
|
||||
// (record, then written down when the person stops) or the phone's recogniser (words as they
|
||||
// are said, the end found by the recogniser).
|
||||
fun startListening() {
|
||||
scope.launch {
|
||||
val wanted = runCatching { context.lembas.instances.prefs.first().voiceInput }.getOrDefault(Prefs.VOICE_LEMBAS)
|
||||
if (usePhoneRecognizer(wanted, PhoneRecognizer.available(context), instanceStt = null)) {
|
||||
before = text
|
||||
listening = true
|
||||
phone.start(
|
||||
onPartial = { words -> if (listening) text = (before + " " + words).trim() },
|
||||
onLevel = {},
|
||||
onResult = { words ->
|
||||
listening = false
|
||||
text = (before + " " + words).trim()
|
||||
},
|
||||
onFail = {
|
||||
listening = false
|
||||
text = before
|
||||
},
|
||||
)
|
||||
} else {
|
||||
recorder.start()
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
}
|
||||
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) startListening()
|
||||
}
|
||||
// A message the server did not take comes back here, so nothing typed is lost.
|
||||
LaunchedEffect(state.unsent) {
|
||||
state.unsent?.let {
|
||||
if (text.isBlank()) text = it
|
||||
actions.clearUnsent()
|
||||
}
|
||||
}
|
||||
// A suggestion from the empty chat lands here (a new value each tap).
|
||||
LaunchedEffect(initial) { if (initial.isNotBlank()) text = initial }
|
||||
// Asked again when the words change -- and when the computer or the folder does: an
|
||||
// agent chat's `@` is that folder's files.
|
||||
LaunchedEffect(text, state.chat?.id, state.device?.id, state.draft.directory) { actions.suggest(mentionQuery(text)) }
|
||||
val newAgent = agent && state.chat == null
|
||||
val canSend = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || state.device != null)
|
||||
val summary = tuneSummary(state, agent)
|
||||
|
||||
Surface(
|
||||
shape = Field,
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
if (state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 4.dp))
|
||||
if (state.draft.image) {
|
||||
// The next message asks for a picture: said where it is typed, and undone here.
|
||||
InputChip(
|
||||
selected = true,
|
||||
onClick = { actions.updateDraft { it.copy(image = false) } },
|
||||
label = { Text(stringResource(R.string.image_generate)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Brush, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove), modifier = Modifier.size(18.dp)) },
|
||||
modifier = Modifier.padding(start = 12.dp, top = 8.dp).heightIn(min = 40.dp),
|
||||
)
|
||||
}
|
||||
if (state.pending.isNotEmpty()) {
|
||||
Row(
|
||||
Modifier.horizontalScroll(rememberScrollState()).padding(start = 12.dp, end = 12.dp, top = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
state.pending.forEach { a ->
|
||||
Box {
|
||||
AttachmentTile(a, side = 64.dp)
|
||||
Box(
|
||||
Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(2.dp)
|
||||
.size(22.dp)
|
||||
.clip(CircleShape)
|
||||
.background(palette.ink)
|
||||
.clickable { actions.unattach(a) },
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.remove),
|
||||
tint = palette.surface,
|
||||
modifier = Modifier.size(14.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// What `@` offers for the word being typed, above the words: a tap attaches it (the
|
||||
// server's files, earlier attachments, pages) or completes it (a device's file).
|
||||
if (state.mentions.isNotEmpty() && mentionQuery(text) != null) {
|
||||
MentionList(state.mentions) { item ->
|
||||
if (item.kind == MENTION_DEVICE) {
|
||||
text = withMention(text, item.path)
|
||||
} else {
|
||||
text = withoutMention(text)
|
||||
actions.mention(item)
|
||||
}
|
||||
actions.suggest(null)
|
||||
}
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = {
|
||||
Text(
|
||||
stringResource(
|
||||
if (listening) {
|
||||
R.string.listening
|
||||
} else if (agent) {
|
||||
R.string.composer_hint_agent
|
||||
} else {
|
||||
R.string.composer_hint
|
||||
},
|
||||
),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = Color.Transparent,
|
||||
unfocusedContainerColor = Color.Transparent,
|
||||
disabledContainerColor = Color.Transparent,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
disabledIndicatorColor = Color.Transparent,
|
||||
),
|
||||
textStyle = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 8,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth().padding(start = 4.dp, end = 6.dp, bottom = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box {
|
||||
IconButton(onClick = { attachMenu = true }) {
|
||||
Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.attach), tint = palette.inkMuted)
|
||||
}
|
||||
DropdownMenu(expanded = attachMenu, onDismissRequest = { attachMenu = false }) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.attach_take_photo)) },
|
||||
onClick = {
|
||||
attachMenu = false
|
||||
actions.photoTarget()?.also { photo = it }?.let { takePhoto.launch(it) }
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.attach_choose_photos)) },
|
||||
onClick = {
|
||||
attachMenu = false
|
||||
pickPhotos.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.UploadFile, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.attach_choose_files)) },
|
||||
onClick = {
|
||||
attachMenu = false
|
||||
pickFiles.launch("*/*")
|
||||
},
|
||||
)
|
||||
// A picture made by the instance: the next message (or the one that makes
|
||||
// the chat) asks for it. Not in an agent chat, which runs on a computer.
|
||||
if (state.imagesOffered && !agent) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.Brush, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.image_generate)) },
|
||||
onClick = {
|
||||
attachMenu = false
|
||||
actions.updateDraft { it.copy(image = true) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The tune button: the icon, and what is set in a few words. It sits in the one
|
||||
// part of the row that gives, so the icons after it keep their place.
|
||||
Box(Modifier.weight(1f), contentAlignment = Alignment.CenterStart) {
|
||||
Surface(
|
||||
onClick = onTune,
|
||||
shape = RoundedCornerShape(50),
|
||||
color = if (summary.isEmpty()) Color.Transparent else palette.accentSoft,
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 36.dp).padding(horizontal = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Filled.Tune,
|
||||
contentDescription = stringResource(R.string.tune),
|
||||
tint = if (summary.isEmpty()) palette.inkMuted else palette.accent,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
if (summary.isNotEmpty()) {
|
||||
Text(
|
||||
summary,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.ink,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
if (listening && !recorder.recording) {
|
||||
// The phone's recogniser: stop, and its last words come to onResult.
|
||||
phone.finish()
|
||||
} else 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) {
|
||||
startListening()
|
||||
} else {
|
||||
askMic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
}) {
|
||||
Icon(
|
||||
if (listening) Icons.Filled.Stop else Icons.Filled.Mic,
|
||||
contentDescription = stringResource(R.string.dictate),
|
||||
tint = if (listening) palette.danger else palette.inkMuted,
|
||||
)
|
||||
}
|
||||
if (state.running && text.isBlank() && state.pending.isEmpty()) {
|
||||
IconButton(
|
||||
onClick = actions::stop,
|
||||
colors = IconButtonDefaults.iconButtonColors(containerColor = palette.ink, contentColor = palette.surface),
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
|
||||
}
|
||||
} else {
|
||||
IconButton(
|
||||
enabled = canSend,
|
||||
onClick = {
|
||||
actions.send(text)
|
||||
text = ""
|
||||
},
|
||||
colors = IconButtonDefaults.iconButtonColors(
|
||||
containerColor = palette.accent,
|
||||
contentColor = palette.accentInk,
|
||||
disabledContainerColor = palette.surfaceActive,
|
||||
disabledContentColor = palette.inkFaint,
|
||||
),
|
||||
) {
|
||||
Icon(Icons.Filled.ArrowUpward, contentDescription = stringResource(R.string.send))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `@` list: at most a few rows in view, the rest scrolled to. A row is 48 dp; its name
|
||||
* gives, and where it is (a path, a kind) is one quiet line under it.
|
||||
*/
|
||||
@Composable
|
||||
private fun MentionList(items: List<Mention>, onPick: (Mention) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 216.dp).verticalScroll(rememberScrollState()).padding(top = 8.dp)) {
|
||||
items.take(MENTION_LIMIT).forEach { item ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { onPick(item) }.heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
when (item.kind) {
|
||||
"url" -> Icons.Filled.Link
|
||||
"attachment" -> Icons.Filled.AttachFile
|
||||
else -> if (item.detail.endsWith("/")) Icons.Filled.Folder else Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
item.name.ifBlank {
|
||||
item.path.ifBlank { item.url }
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (item.detail.isNotBlank() && item.detail != item.name) {
|
||||
Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- The tune sheet --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* What can be tuned for this chat, and only what its model and kind offer: how hard the model
|
||||
* thinks (a switch for on or off, choices for several levels), the team's size, and the mode
|
||||
* (Plan first for a chat, the agent's mode for an agent chat). A new agent chat also chooses
|
||||
* its device and folder here.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun TuneContent(state: ChatState, actions: ChatActions, agent: Boolean, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val chat = state.chat
|
||||
val info = state.modelInfo
|
||||
val level = state.level
|
||||
val newAgent = agent && chat == null
|
||||
var askDirectory by remember { mutableStateOf(false) }
|
||||
Column(modifier.fillMaxWidth().padding(bottom = 24.dp)) {
|
||||
Text(stringResource(R.string.tune), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp))
|
||||
|
||||
if (newAgent) {
|
||||
TuneHeader(stringResource(R.string.agent_device))
|
||||
if (state.devices.isEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.agent_no_device),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 24.dp),
|
||||
)
|
||||
} else {
|
||||
DeviceChoices(state.devices, state.device) { id -> actions.updateDraft { it.copy(device = id) } }
|
||||
}
|
||||
TuneRow(
|
||||
title = stringResource(R.string.agent_directory),
|
||||
subtitle = state.draft.directory.ifBlank { stringResource(R.string.agent_directory_hint) },
|
||||
onClick = { askDirectory = true },
|
||||
leading = { Icon(Icons.Filled.Folder, contentDescription = null, tint = palette.inkMuted) },
|
||||
)
|
||||
}
|
||||
|
||||
if (info != null && level != null) {
|
||||
when (info.levelControl) {
|
||||
"switch" -> TuneRow(
|
||||
title = stringResource(R.string.thinking_switch),
|
||||
subtitle = stringResource(R.string.thinking_switch_hint),
|
||||
onClick = { pickLevel(actions, chat == null, if (level == "off") info.onLevel else "off") },
|
||||
trailing = {
|
||||
Switch(checked = level != "off", onCheckedChange = { on -> pickLevel(actions, chat == null, if (on) info.onLevel else "off") })
|
||||
},
|
||||
)
|
||||
|
||||
"slider" -> {
|
||||
TuneHeader(stringResource(R.string.effort))
|
||||
FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
info.offered.forEach { option ->
|
||||
FilterChip(
|
||||
selected = option == level,
|
||||
onClick = { pickLevel(actions, chat == null, option) },
|
||||
label = { Text(levelName(option)) },
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state.offersTeam(agent)) {
|
||||
TuneHeader(stringResource(R.string.team_agents))
|
||||
Text(
|
||||
stringResource(R.string.team_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 24.dp),
|
||||
)
|
||||
if (chat == null && agent && state.agentSubagents?.deviceRuns == false) {
|
||||
// The chosen computer's CLI is older than subagents: the setting would go nowhere.
|
||||
Text(
|
||||
stringResource(R.string.subagents_device_cannot),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
if (state.subagentsNamedOnly) {
|
||||
// The chat's model serves one request at a time: no default to fall back on.
|
||||
Text(
|
||||
stringResource(R.string.subagents_named_only),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
val cap = state.subagentsCap
|
||||
val now = state.agents.let { AgentsSetting(it.min.coerceIn(1, cap), it.max.coerceIn(1, cap)) }
|
||||
// An instance that allows only one has nothing to choose between.
|
||||
if (cap > 1) {
|
||||
AgentsRange(now, cap, Modifier.padding(horizontal = 24.dp)) { setTeam(actions, chat == null, it) }
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
newAgent || chat?.isAgent == true -> {
|
||||
TuneHeader(stringResource(R.string.agent_mode))
|
||||
val current = chat?.mode?.ifBlank { null } ?: if (chat == null) state.draft.agentMode else "edit"
|
||||
FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
AGENT_MODES.forEach { m ->
|
||||
FilterChip(
|
||||
selected = m == current,
|
||||
onClick = { if (chat == null) actions.updateDraft { it.copy(agentMode = m) } else actions.change("mode", m) },
|
||||
label = { Text(modeName(m)) },
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
val on = if (chat == null) state.draft.plan else chat.mode == "plan"
|
||||
TuneRow(
|
||||
title = stringResource(R.string.plan_first),
|
||||
subtitle = stringResource(R.string.plan_first_hint),
|
||||
onClick = { setPlan(actions, chat == null, !on) },
|
||||
trailing = { Switch(checked = on, onCheckedChange = { setPlan(actions, chat == null, it) }) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (askDirectory) {
|
||||
DirectoryPicker(
|
||||
title = stringResource(R.string.agent_directory),
|
||||
initial = state.draft.directory,
|
||||
load = actions::directories,
|
||||
onPick = { path ->
|
||||
actions.updateDraft { it.copy(directory = path) }
|
||||
askDirectory = false
|
||||
},
|
||||
onDismiss = { askDirectory = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun pickLevel(actions: ChatActions, draft: Boolean, level: String) {
|
||||
if (draft) actions.updateDraft { it.copy(effort = level) } else actions.change("effort", level)
|
||||
}
|
||||
|
||||
private fun setTeam(actions: ChatActions, draft: Boolean, agents: AgentsSetting) {
|
||||
if (draft) actions.updateDraft { it.copy(agents = agents) } else actions.setAgents(agents)
|
||||
}
|
||||
|
||||
private fun setPlan(actions: ChatActions, draft: Boolean, on: Boolean) {
|
||||
if (draft) actions.updateDraft { it.copy(plan = on) } else actions.change("mode", if (on) "plan" else "")
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TuneHeader(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = LocalPalette.current.accent,
|
||||
modifier = Modifier.padding(start = 24.dp, end = 24.dp, top = 20.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** A row of the sheet: words that give, and a control that keeps its size. */
|
||||
@Composable
|
||||
private fun TuneRow(
|
||||
title: String,
|
||||
subtitle: String? = null,
|
||||
onClick: () -> Unit,
|
||||
leading: (@Composable () -> Unit)? = null,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 64.dp).padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (leading != null) {
|
||||
leading()
|
||||
Spacer(Modifier.width(16.dp))
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
if (trailing != null) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
trailing()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun DeviceChoices(devices: List<LinkedDevice>, current: LinkedDevice?, onPick: (String) -> Unit) {
|
||||
FlowRow(Modifier.padding(horizontal = 24.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
devices.forEach { d ->
|
||||
FilterChip(
|
||||
selected = d.id == current?.id,
|
||||
onClick = { onPick(d.id) },
|
||||
label = { Text(listOf(d.name, d.host).filter { it.isNotBlank() }.distinct().joinToString(" · "), maxLines = 1) },
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Subagents setting: one slider with two thumbs, Min and Max, from 1 to the instance's
|
||||
* [cap], in whole agents. The numbers count the chat's own agent, as the server does
|
||||
* (`agents {min, max}`, the lead included): 1 is the agent alone. The values sit on a row of
|
||||
* their own above the slider, so nothing beside them moves when a number grows a digit.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun AgentsRange(value: AgentsSetting, cap: Int, modifier: Modifier = Modifier, onChange: (AgentsSetting) -> Unit) {
|
||||
var shown by remember(value.min, value.max) { mutableStateOf(value.min.toFloat()..value.max.toFloat()) }
|
||||
val min = Math.round(shown.start).coerceIn(1, cap)
|
||||
val max = Math.round(shown.endInclusive).coerceIn(min, cap)
|
||||
val minLabel = stringResource(R.string.team_min)
|
||||
val maxLabel = stringResource(R.string.team_max)
|
||||
val startSource = remember { MutableInteractionSource() }
|
||||
val endSource = remember { MutableInteractionSource() }
|
||||
Column(modifier.padding(top = 8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.team_range, min.toString(), max.toString()),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
RangeSlider(
|
||||
value = shown,
|
||||
// Whole agents: each thumb lands on a number as it moves, with no tick per value,
|
||||
// which at a cap of 32 would be a row of noise.
|
||||
onValueChange = { r -> shown = Math.round(r.start).toFloat()..Math.round(r.endInclusive).toFloat() },
|
||||
onValueChangeFinished = { onChange(AgentsSetting(min, max)) },
|
||||
valueRange = 1f..cap.toFloat(),
|
||||
startInteractionSource = startSource,
|
||||
endInteractionSource = endSource,
|
||||
startThumb = {
|
||||
SliderDefaults.Thumb(interactionSource = startSource, modifier = Modifier.semantics { contentDescription = minLabel })
|
||||
},
|
||||
endThumb = {
|
||||
SliderDefaults.Thumb(interactionSource = endSource, modifier = Modifier.semantics { contentDescription = maxLabel })
|
||||
},
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.Message
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/*
|
||||
* Whether a list keeps to its end while something is written into it. The rule, the same for the
|
||||
* chat's transcript and the assistant's sheet: the view follows only while the person is at the
|
||||
* end; once they have scrolled away it stays exactly where they are, and coming back to the end
|
||||
* takes the following up again. Nothing here knows Compose, so the tests read it as it is.
|
||||
*/
|
||||
|
||||
/** What happened to the transcript's rows between two draws. */
|
||||
enum class TranscriptChange {
|
||||
/** Nothing to follow: no rows, or the same rows. */
|
||||
None,
|
||||
|
||||
/** A chat shown for the first time, or another chat in the same place. */
|
||||
Opened,
|
||||
|
||||
/** A message this app just sent is new at the end: sending always shows what was sent. */
|
||||
Sent,
|
||||
|
||||
/** New rows at the end that the person did not write: a reply, the queue's next turn. */
|
||||
Appended,
|
||||
|
||||
/** An older page was put in front; the end has not moved. */
|
||||
Older,
|
||||
|
||||
/** Rows changed in place: a finished reply for the one being written, a transcript read again. */
|
||||
Changed,
|
||||
}
|
||||
|
||||
/**
|
||||
* What changed from [before] to [after]. [before] is null when this draw is the first one this
|
||||
* list makes; [restored] then says the list had rows before (a rotation, a return to the
|
||||
* screen), so its place is the one it kept, not a chat being opened. [sent] is the id of the
|
||||
* message this app sent last: only that one is "sent". The person's row arriving from
|
||||
* elsewhere -- written on the page or another device while this chat is open here -- is a row
|
||||
* like a reply's, and does not pull a reader down.
|
||||
*/
|
||||
fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boolean = false, sent: String? = null): TranscriptChange {
|
||||
if (after.isEmpty()) return TranscriptChange.None
|
||||
if (before == null) return if (restored) TranscriptChange.Changed else TranscriptChange.Opened
|
||||
val known = before.mapTo(HashSet()) { it.id }
|
||||
val firstKept = after.indexOfFirst { it.id in known }
|
||||
if (firstKept < 0) return TranscriptChange.Opened
|
||||
val added = after.subList(after.indexOfLast { it.id in known } + 1, after.size)
|
||||
return when {
|
||||
sent != null && added.any { it.id == sent } -> TranscriptChange.Sent
|
||||
added.isNotEmpty() -> TranscriptChange.Appended
|
||||
firstKept > 0 -> TranscriptChange.Older
|
||||
before == after -> TranscriptChange.None
|
||||
else -> TranscriptChange.Changed
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the view goes to the end after [change], given whether it was [following]. Opening a
|
||||
* chat and sending a message always do; an older page never does; everything else -- and a reply
|
||||
* growing, a keyboard opening -- only for a person who is at the end already.
|
||||
*/
|
||||
fun movesToEnd(change: TranscriptChange, following: Boolean): Boolean = when (change) {
|
||||
TranscriptChange.Opened, TranscriptChange.Sent -> true
|
||||
TranscriptChange.None, TranscriptChange.Older -> false
|
||||
TranscriptChange.Appended, TranscriptChange.Changed -> following
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the view follows, once a scroll has come to rest [distance] pixels short of the end.
|
||||
* Within [slack] counts as the end: a line that arrived while the list was settling must not
|
||||
* read as "scrolled away".
|
||||
*/
|
||||
fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack
|
||||
|
||||
/**
|
||||
* The row that keeps its place when an older page arrives while the list stands at its very
|
||||
* top: the first row there was before, by its place in [after]. Null when it is gone.
|
||||
*/
|
||||
fun keptRow(before: List<Message>, after: List<Message>): Int? {
|
||||
val first = before.firstOrNull() ?: return null
|
||||
return after.indexOfFirst { it.id == first.id }.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* A scroll this app makes for the person ([scroll]: to the end, as the reply grows). A finger
|
||||
* on the list takes it over, and Compose ends the scroll by cancelling it -- which, left
|
||||
* alone, would also end whatever follower called it, for good. So that cancellation is taken
|
||||
* here, and only that one: when the follower itself is cancelled, it still ends.
|
||||
*/
|
||||
suspend fun yielding(scroll: suspend () -> Unit) {
|
||||
try {
|
||||
scroll()
|
||||
} catch (e: CancellationException) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.LruCache
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Icon
|
||||
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.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* The pictures the instance made, fetched the one way the app fetches a chat's files: by
|
||||
* attachment id, from the instance it is signed in to, with its token. There is no URL to
|
||||
* follow -- a model's words can name an address, but never a picture this draws -- and nothing
|
||||
* bigger than [MAX_BYTES] is decoded.
|
||||
*/
|
||||
private object Pictures {
|
||||
/** Longest edge decoded: enough for a phone held either way, small enough to keep a few. */
|
||||
private const val EDGE = 1600
|
||||
private const val MAX_BYTES = 24 * 1024 * 1024
|
||||
private val cache = LruCache<String, ImageBitmap>(8)
|
||||
private val failed = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id.isBlank() || id in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES }
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
return image
|
||||
}
|
||||
|
||||
private suspend fun decode(bytes: ByteArray): ImageBitmap? = withContext(Dispatchers.Default) {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
|
||||
var sample = 1
|
||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= EDGE) sample *= 2
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A picture `image_generate` made, in the reply: as wide as the reply allows (at most 480 dp),
|
||||
* its height from the size the server said, so the transcript does not jump when it arrives. A
|
||||
* tap shows it on its own, whole, on the page's ground; a tap or Back closes it.
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val still = LocalInspectionMode.current
|
||||
var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) }
|
||||
var whole by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(image.id) { if (bitmap == null && !still) bitmap = Pictures.load(context, image.id) }
|
||||
val ratio = if (image.width > 0 && image.height > 0) image.width.toFloat() / image.height else 1f
|
||||
val shape = RoundedCornerShape(16.dp)
|
||||
val described = stringResource(R.string.image_generated)
|
||||
Box(
|
||||
modifier
|
||||
.widthIn(max = 480.dp)
|
||||
.fillMaxWidth()
|
||||
.aspectRatio(ratio.coerceIn(0.25f, 4f))
|
||||
.clip(shape)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, shape)
|
||||
.then(if (bitmap != null) Modifier.clickable { whole = true } else Modifier),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
val shown = bitmap
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
}
|
||||
val shown = bitmap
|
||||
if (whole && shown != null) {
|
||||
Dialog(onDismissRequest = { whole = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Box(Modifier.fillMaxSize().background(palette.bg).clickable { whole = false }, contentAlignment = Alignment.Center) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.DeviceFile
|
||||
import eu.llembas.android.api.Mention
|
||||
|
||||
// The composer's `@`: what is being asked for is the `@word` the text ends with. The field's
|
||||
// cursor is not followed -- a mention is offered for what is typed last, which is where typing
|
||||
// on a phone is.
|
||||
|
||||
/** A file on a linked device, as the `@` list holds it beside the server's kinds: put into the text as `@path`, never attached. */
|
||||
const val MENTION_DEVICE = "device"
|
||||
|
||||
/**
|
||||
* The `@` word [text] ends with, without the `@` (empty right after it), or null when it ends
|
||||
* with none: the `@` must open a word (so an e-mail address is not one), and the word holds no
|
||||
* space yet.
|
||||
*/
|
||||
fun mentionQuery(text: String): String? {
|
||||
val at = text.lastIndexOf('@')
|
||||
if (at < 0 || (at > 0 && !text[at - 1].isWhitespace())) return null
|
||||
return text.substring(at + 1).takeIf { word -> word.none { it.isWhitespace() } }
|
||||
}
|
||||
|
||||
/** [text] without the `@word` it ends with: what stays when the mention became an attachment. */
|
||||
fun withoutMention(text: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@'))
|
||||
|
||||
/** [text] with the `@word` it ends with made `@path` and a space: a device's file, which the device reads. */
|
||||
fun withMention(text: String, path: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@')) + "@" + path + " "
|
||||
|
||||
/** The most entries the `@` list shows. */
|
||||
const val MENTION_LIMIT = 50
|
||||
|
||||
/** The longest path a device's file may have to be offered. */
|
||||
const val MENTION_PATH = 512
|
||||
|
||||
/**
|
||||
* A device's file as an entry of the `@` list: its name, and its path as the detail. Null for
|
||||
* one that is not offered: its path goes into the message as it is, so a path with a line
|
||||
* break or another control character in it -- which the one-line row would not show -- or one
|
||||
* too long to be a path is left out.
|
||||
*/
|
||||
fun DeviceFile.asMention(): Mention? {
|
||||
if (path.isBlank() || path.length > MENTION_PATH || path.any { it.isISOControl() }) return null
|
||||
val shown = name.filterNot { it.isISOControl() }.take(MENTION_PATH).ifBlank { path }
|
||||
return Mention(kind = MENTION_DEVICE, path = path, name = shown, detail = if (kind == "dir") "$path/" else path)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** A context window in the way people say it: 8K, 128K, 1M. */
|
||||
fun compactContext(tokens: Int): String = when {
|
||||
tokens >= 1_000_000 && tokens % 1_000_000 == 0 -> "${tokens / 1_000_000}M"
|
||||
tokens >= 1_000_000 -> "%.1fM".format(tokens / 1_000_000.0)
|
||||
else -> "${Math.round(tokens / 1024.0)}K"
|
||||
}
|
||||
|
||||
/** What a model can do, in a few words for the picker: sees images, uses tools, its window. */
|
||||
@Composable
|
||||
fun modelNotes(model: ModelInfo): String = buildList {
|
||||
if (model.vision) add(stringResource(R.string.model_sees_images))
|
||||
if (model.tools) add(stringResource(R.string.model_uses_tools))
|
||||
if (model.context > 0) add(stringResource(R.string.model_context, compactContext(model.context)))
|
||||
}.joinToString(" · ")
|
||||
|
||||
/** How the model thinks, for the picker: a switch, or its levels by name; null for one level. */
|
||||
@Composable
|
||||
fun modelLevels(model: ModelInfo): String? = when (model.levelControl) {
|
||||
"switch" -> stringResource(R.string.model_thinking_switchable)
|
||||
"slider" -> stringResource(R.string.model_levels, model.offered.map { levelName(it) }.joinToString(", "))
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The top bar's title: the model's picture and name, and a caret that says it opens; under it,
|
||||
* smaller, the chat's title once it has one. The name gives before the caret does.
|
||||
*/
|
||||
@Composable
|
||||
fun ModelTitle(model: ModelInfo?, fallback: String, subtitle: String?, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(onClick = onClick, shape = RoundedCornerShape(12.dp), color = Color.Transparent) {
|
||||
Row(Modifier.heightIn(min = 48.dp).padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
ModelAvatar(model, fallback, size = 28.dp)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(Modifier.weight(1f, fill = false)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
model?.name?.ifBlank { null } ?: fallback,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Icon(Icons.Filled.ArrowDropDown, contentDescription = stringResource(R.string.model_choose), tint = palette.inkMuted)
|
||||
}
|
||||
subtitle?.let {
|
||||
Text(it, style = MaterialTheme.typography.labelMedium, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The model picker (a bottom sheet's content): each model with its picture, its name, what it
|
||||
* can do and how it thinks; the one in use is ticked. Rows are at least 72 dp and their words
|
||||
* wrap rather than overflow.
|
||||
*/
|
||||
@Composable
|
||||
fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (String) -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
stringResource(R.string.model_choose),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
)
|
||||
LazyColumn(Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
|
||||
// By its ref: two connections may serve one id, and a row is its own key.
|
||||
val inUse = models.named(current)?.key
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m ->
|
||||
val chosen = m.key == inUse
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(m.key) }
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
ModelAvatar(m, m.id, size = 44.dp)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(m.titleAmong(models), style = MaterialTheme.typography.titleMedium)
|
||||
modelNotes(m).takeIf { it.isNotEmpty() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
}
|
||||
modelLevels(m)?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
if (chosen) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Icon(
|
||||
Icons.Filled.CheckCircle,
|
||||
contentDescription = stringResource(R.string.model_in_use),
|
||||
tint = palette.accent,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.KeyguardManager
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
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.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.R
|
||||
import eu.llembas.android.actions.ActionRunner
|
||||
import eu.llembas.android.actions.Args
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.PhoneResult
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
/** The actions a map app carries out. */
|
||||
val NAV_ACTIONS = setOf("navigate", "add_stop", "search_nearby", "stop_navigation")
|
||||
|
||||
/** What the card shows of a phone card while it is being carried out. */
|
||||
data class PhoneCardState(val running: Boolean = false, val locked: Boolean = false, val error: String? = null)
|
||||
|
||||
/**
|
||||
* A `phone_action` card (spec 3.6.0) with the phone behind it: Do it carries the action out
|
||||
* ([ActionRunner]) and answers what happened -- done, or failed and why; Cancel answers declined.
|
||||
* Never while the phone is locked: Do it says to unlock first. Used by the chat's card sheet and
|
||||
* by the assistant's sheet alike.
|
||||
*/
|
||||
@Composable
|
||||
fun PhoneCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val prefs by context.lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val installed = remember { NavApp.installedApps(context) }
|
||||
var state by remember(card.id) { mutableStateOf(PhoneCardState()) }
|
||||
val item = card.items.firstOrNull() ?: return
|
||||
val phone = item.phone ?: JsonObject(emptyMap())
|
||||
PhoneCardContent(
|
||||
phone = phone,
|
||||
navApps = installed,
|
||||
chosen = NavApp.chosen(prefs.navApp, installed),
|
||||
state = state,
|
||||
onDo = { app ->
|
||||
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) {
|
||||
state = state.copy(locked = true)
|
||||
return@PhoneCardContent
|
||||
}
|
||||
state = PhoneCardState(running = true)
|
||||
scope.launch {
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val outcome = ActionRunner.run(context, action, Args(phone), app, askOsmAnd = prefs.osmandInfo)
|
||||
state = PhoneCardState(error = outcome.message.takeIf { outcome.status.wire == "failed" })
|
||||
onAnswer(CardAnswer(result = PhoneResult(outcome.status.wire, outcome.message)))
|
||||
}
|
||||
},
|
||||
onDecline = { onAnswer(CardAnswer(result = PhoneResult("declined"))) },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The card from its state alone (what the screenshot tests draw): the phone's icon and "Do this
|
||||
* on your phone?", the model's one line ([phone]'s `summary`), how it will be done and its facts,
|
||||
* the map app to use when Settings leaves it open ([chosen] null, more than one installed), and
|
||||
* Cancel / Do it -- each at least 48 dp, the line above them free to wrap.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun PhoneCardContent(
|
||||
phone: JsonObject,
|
||||
navApps: List<NavApp>,
|
||||
chosen: NavApp?,
|
||||
state: PhoneCardState,
|
||||
onDo: (NavApp?) -> Unit = {},
|
||||
onDecline: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val summary = (phone["summary"] as? JsonPrimitive)?.content.orEmpty().ifBlank { action }
|
||||
val nav = action in NAV_ACTIONS
|
||||
var picked by remember(chosen) { mutableStateOf(chosen ?: navApps.singleOrNull()) }
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.PhoneAndroid, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(stringResource(R.string.action_card_title), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
}
|
||||
Text(summary, style = MaterialTheme.typography.titleMedium)
|
||||
Text(howLine(action, picked), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
phoneFacts(phone).takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (nav && chosen == null && navApps.size > 1) {
|
||||
Text(stringResource(R.string.nav_app_pick), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
navApps.forEach { app ->
|
||||
FilterChip(
|
||||
selected = picked == app,
|
||||
onClick = { picked = app },
|
||||
label = { Text(stringResource(if (app == NavApp.OsmAnd) R.string.nav_app_osmand else R.string.nav_app_google)) },
|
||||
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft),
|
||||
modifier = Modifier.heightIn(min = 40.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nav && picked == NavApp.GoogleMaps && action in setOf("add_stop", "stop_navigation")) {
|
||||
Text(
|
||||
stringResource(if (action == "add_stop") R.string.action_google_add_stop else R.string.action_google_no_stop),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
)
|
||||
}
|
||||
when {
|
||||
state.locked -> Text(stringResource(R.string.action_unlock), style = MaterialTheme.typography.bodyMedium, color = palette.warning)
|
||||
|
||||
state.error != null -> Text(
|
||||
stringResource(R.string.action_failed, state.error),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.danger,
|
||||
)
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = onDecline, enabled = !state.running, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { onDo(picked) },
|
||||
enabled = !state.running && (!nav || picked != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.running) R.string.action_running else R.string.action_do)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How the action will be done, in a sentence: which kind of app, and what is left to the person. */
|
||||
@Composable
|
||||
private fun howLine(action: String, app: NavApp?): String = when (action) {
|
||||
"alarm", "timer" -> stringResource(R.string.action_line_clock)
|
||||
|
||||
"calendar_event" -> stringResource(R.string.action_line_calendar)
|
||||
|
||||
"sms_draft", "email_draft" -> stringResource(R.string.action_line_draft)
|
||||
|
||||
"dial" -> stringResource(R.string.action_line_dial)
|
||||
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" ->
|
||||
stringResource(
|
||||
R.string.action_line_map,
|
||||
stringResource(
|
||||
if (app ==
|
||||
NavApp.OsmAnd
|
||||
) {
|
||||
R.string.nav_app_osmand
|
||||
} else if (app == NavApp.GoogleMaps) {
|
||||
R.string.nav_app_google
|
||||
} else {
|
||||
R.string.nav_app
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
"media", "torch" -> stringResource(R.string.action_line_now)
|
||||
|
||||
"settings_panel" -> stringResource(R.string.action_line_settings)
|
||||
|
||||
"automation_intent" -> stringResource(R.string.action_line_automation)
|
||||
|
||||
else -> stringResource(R.string.action_line_open)
|
||||
}
|
||||
|
||||
/**
|
||||
* The action's facts as one line, values only, in the order the spec lists the fields: what the
|
||||
* person checks before Do it ("07:00 · mon tue wed thu fri · Work"). A place is its name and,
|
||||
* when it has one, what the map app will search, or its coordinates.
|
||||
*/
|
||||
fun phoneFacts(phone: JsonObject): String {
|
||||
fun place(e: JsonElement?): String? {
|
||||
val o = e as? JsonObject ?: return (e as? JsonPrimitive)?.content
|
||||
val name = (o["name"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val query = (o["query"] as? JsonPrimitive)?.content.orEmpty()
|
||||
val lat = (o["lat"] as? JsonPrimitive)?.content
|
||||
val lon = (o["lon"] as? JsonPrimitive)?.content
|
||||
val where = query.ifBlank { if (lat != null && lon != null) "$lat, $lon" else "" }
|
||||
return listOf(name, where).filter { it.isNotBlank() }.distinct().let {
|
||||
if (it.size == 2) "${it[0]} (${it[1]})" else it.firstOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
fun value(key: String, e: JsonElement?): String? = when {
|
||||
e == null -> null
|
||||
key in setOf("destination", "stop") -> place(e)
|
||||
key == "stops" -> (e as? JsonArray)?.mapNotNull { place(it) }?.joinToString(" → ")?.ifBlank { null }
|
||||
e is JsonArray -> e.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(" ").ifBlank { null }
|
||||
e is JsonObject -> e.entries.joinToString(", ") { (k, v) -> "$k=${(v as? JsonPrimitive)?.content.orEmpty()}" }.ifBlank { null }
|
||||
e is JsonPrimitive -> e.content.takeIf { it.isNotBlank() && it != "false" && it != "true" }
|
||||
else -> null
|
||||
}
|
||||
return FACT_ORDER.mapNotNull { key -> value(key, phone[key]) }.joinToString(" · ")
|
||||
}
|
||||
|
||||
private val FACT_ORDER = listOf(
|
||||
"time", "days", "seconds", "label", "title", "start", "end", "location", "to", "cc", "subject", "number",
|
||||
"stops", "stop", "destination", "mode", "query", "near", "app", "url", "command", "panel", "task", "values",
|
||||
)
|
||||
@@ -0,0 +1,69 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.Stable
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.Speaker
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* A reply read aloud by the instance's text-to-speech (`/v1/audio/speech`), the same voice the
|
||||
* assistant answers in. One at a time: another reply's Read aloud stops the first. [available]
|
||||
* only when the instance says it has text-to-speech (`/api/v2/me` services), so a phone never
|
||||
* shows a button that can only fail.
|
||||
*/
|
||||
@Stable
|
||||
class ReadAloud(private val context: Context, private val scope: CoroutineScope, private val onError: (String) -> Unit) {
|
||||
private val speaker = Speaker(context)
|
||||
private var job: Job? = null
|
||||
|
||||
var available by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** The message being read (or fetched to be read), else null. */
|
||||
var reading by mutableStateOf<String?>(null)
|
||||
private set
|
||||
|
||||
suspend fun load() {
|
||||
available = runCatching { context.lembas.instances.client()?.me()?.hasTextToSpeech == true }.getOrDefault(false)
|
||||
}
|
||||
|
||||
fun toggle(messageId: String, markdown: String) {
|
||||
if (reading == messageId) return stop()
|
||||
stop()
|
||||
reading = messageId
|
||||
job = scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return@launch
|
||||
speaker.play(api.speech(AssistController.plain(markdown)))
|
||||
speaker.playing.first { !it }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
onError(context.explain(e))
|
||||
} finally {
|
||||
if (reading == messageId) reading = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
job?.cancel()
|
||||
job = null
|
||||
speaker.stop()
|
||||
reading = null
|
||||
}
|
||||
}
|
||||
|
||||
/** Provided by the chat; null where nothing can read aloud (the screenshots, a run's page). */
|
||||
val LocalReadAloud = compositionLocalOf<ReadAloud?> { null }
|
||||
@@ -0,0 +1,139 @@
|
||||
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.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.TreeAgent
|
||||
import eu.llembas.android.api.TreeLogic
|
||||
import eu.llembas.android.api.TreeRow
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
|
||||
/**
|
||||
* The subagents as Android shows them (harness spec 3.4.0, `subagents.md` §12, the reduced
|
||||
* list): each row its name and id, its position, its state, what it is doing now (the progress
|
||||
* text, without the clock -- a row has no room) and how full its context is. The main agent
|
||||
* first; ended subagents after the live ones, dimmed, with how each ended. A subagent's row opens
|
||||
* its conversation, read-only ([onOpen]); the main agent's conversation is the chat itself.
|
||||
*/
|
||||
@Composable
|
||||
fun SubagentList(tree: SubagentTree, onOpen: (TreeAgent) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.team_size, tree.size.toString(), tree.max.toString()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
TreeLogic.rows(tree).forEach { row -> TreeRowItem(row, onOpen) }
|
||||
if (tree.openSlots > 0) {
|
||||
Text(
|
||||
stringResource(R.string.tree_open_slots, tree.openSlots.toString()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(start = 16.dp, top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One row, two lines on a fixed frame: the name and position give way (cut, not wrapped) to the
|
||||
* state word; the progress text gives way to the context percentage in a column of its own width.
|
||||
*/
|
||||
@Composable
|
||||
private fun TreeRowItem(row: TreeRow, onOpen: (TreeAgent) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val agent = row.agent
|
||||
val opens = !agent.isMain
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 48.dp)
|
||||
.then(if (opens) Modifier.clickable { onOpen(agent) } else Modifier)
|
||||
.alpha(if (row.ended) 0.6f else 1f)
|
||||
.padding(start = (16 * row.depth.coerceIn(0, 4)).dp, top = 6.dp, bottom = 6.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
val title = if (agent.isMain) agent.name else "${agent.name} (${agent.id})"
|
||||
Text(
|
||||
listOf(title, agent.position).filter { it.isNotBlank() }.joinToString(" — "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
treeStateWord(agent.state),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = treeStateColour(palette, agent.state),
|
||||
maxLines = 1,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
val doing = if (row.ended) null else progressLineOf(agent.progress, withElapsed = false)
|
||||
val percent = agent.contextPercent
|
||||
if (doing != null || percent != null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
doing.orEmpty(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
percent?.let { stringResource(R.string.tree_context, it.toString()) }.orEmpty(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
textAlign = TextAlign.End,
|
||||
maxLines = 1,
|
||||
modifier = Modifier.width(88.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The state's word (`loop.json` `team.read.states`), the main agent's and every subagent's. */
|
||||
@Composable
|
||||
internal fun treeStateWord(state: String): String = when (state) {
|
||||
"working" -> stringResource(R.string.tree_state_working)
|
||||
"waiting" -> stringResource(R.string.tree_state_waiting)
|
||||
"finished" -> stringResource(R.string.tree_state_finished)
|
||||
"idle" -> stringResource(R.string.tree_state_idle)
|
||||
"paused" -> stringResource(R.string.tree_state_paused)
|
||||
"done" -> stringResource(R.string.tree_state_done)
|
||||
"out_of_context" -> stringResource(R.string.tree_state_out_of_context)
|
||||
"stopped" -> stringResource(R.string.tree_state_stopped)
|
||||
else -> state
|
||||
}
|
||||
|
||||
private fun treeStateColour(palette: Palette, state: String): Color = when (state) {
|
||||
"working" -> palette.accent
|
||||
"waiting", "paused" -> palette.warning
|
||||
"done", "finished" -> palette.success
|
||||
"out_of_context" -> palette.danger
|
||||
else -> palette.inkFaint
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.LruCache
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
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.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
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.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeUp
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.Web
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
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.alpha
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
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.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.ending
|
||||
import eu.llembas.android.api.shownMarkdown
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.Segment
|
||||
import eu.llembas.android.ui.highlight
|
||||
import eu.llembas.android.ui.pageProjection
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.splitFences
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** Copies a text to the clipboard (and says so where Android does not). Provided by the chat. */
|
||||
val LocalCopy = compositionLocalOf<(String) -> Unit> { {} }
|
||||
|
||||
private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomStart = 20.dp, bottomEnd = 20.dp)
|
||||
private val Block = RoundedCornerShape(12.dp)
|
||||
private val Pill = RoundedCornerShape(50)
|
||||
|
||||
/**
|
||||
* The person's turn: their words in a bubble on the right (never markdown), what they attached
|
||||
* above it as thumbnails. A long press offers Copy and, where the turn can still change, Edit.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Column(modifier.fillMaxWidth().padding(start = 48.dp), horizontalAlignment = Alignment.End) {
|
||||
if (message.attachments.isNotEmpty()) {
|
||||
Row(
|
||||
Modifier.horizontalScroll(rememberScrollState()).padding(bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
message.attachments.forEach { AttachmentTile(it, side = 96.dp) }
|
||||
}
|
||||
}
|
||||
if (!message.text.isNullOrBlank()) {
|
||||
Box {
|
||||
Text(
|
||||
message.text,
|
||||
color = palette.ink,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier
|
||||
.clip(Bubble)
|
||||
.background(palette.bubbleUser)
|
||||
.combinedClickable(onClick = {}, onLongClick = { menu = true })
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.copy_message)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
copy(message.text)
|
||||
},
|
||||
)
|
||||
if (canEdit) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.Edit, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.edit)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
onEdit()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
// The server's queued progress ("Queued, 2 ahead · 12s") where it sends one.
|
||||
Text(
|
||||
progressLineOf(message.progress) ?: stringResource(R.string.queued),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(top = 4.dp, end = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A line the server wrote in the person's place (a schedule's instruction, what opens a report's
|
||||
* conversation): a quiet note across the width, a few lines of it -- never the person's bubble,
|
||||
* and never markdown.
|
||||
*/
|
||||
@Composable
|
||||
fun MachineNote(text: String, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
if (text.isBlank()) return
|
||||
Text(
|
||||
text.trim(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 4,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = modifier.fillMaxWidth().padding(horizontal = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's turn, full width and without a bubble: its steps (thinking and tools folded into
|
||||
* chips that open), its words as markdown, and under it Copy, Regenerate and what it cost. While
|
||||
* it is being written, a quiet pulse says so. A long press on the words offers the same, and
|
||||
* Select text.
|
||||
*/
|
||||
@Composable
|
||||
fun AssistantMessage(
|
||||
message: Message,
|
||||
steps: List<Step>,
|
||||
writing: Boolean,
|
||||
canRegenerate: Boolean,
|
||||
onRegenerate: () -> Unit,
|
||||
onShow: ((ShowCard) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
val readAloud = LocalReadAloud.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var selecting by remember { mutableStateOf(false) }
|
||||
val words = replyText(message.copy(steps = steps))
|
||||
Column(modifier.fillMaxWidth()) {
|
||||
Box {
|
||||
StepsCompact(steps, onShow = onShow, onLongPress = { menu = true })
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.copy_message)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
copy(words)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.SelectAll, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.select_text)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
selecting = true
|
||||
},
|
||||
)
|
||||
if (canRegenerate) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.Refresh, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.regenerate)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
onRegenerate()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (writing) {
|
||||
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
|
||||
} else {
|
||||
// How a reply that did not finish ended (display.md §4): the progress text alone --
|
||||
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
|
||||
// the error colour, a stop muted. Nothing else says it a second time.
|
||||
message.ending()?.let { end ->
|
||||
Text(
|
||||
progressLineOf(end, withElapsed = false) ?: message.error.orEmpty(),
|
||||
color = if (end.phase == "failed") palette.danger else palette.inkMuted,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
}
|
||||
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
|
||||
if (words.isNotBlank()) {
|
||||
IconButton(onClick = { copy(words) }) {
|
||||
Icon(
|
||||
Icons.Filled.ContentCopy,
|
||||
contentDescription = stringResource(R.string.copy_message),
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (readAloud != null && words.isNotBlank()) {
|
||||
val reading = readAloud.reading == message.id
|
||||
IconButton(onClick = { readAloud.toggle(message.id, words) }) {
|
||||
Icon(
|
||||
if (reading) Icons.Filled.Stop else Icons.AutoMirrored.Filled.VolumeUp,
|
||||
contentDescription = stringResource(if (reading) R.string.assist_stop_reading else R.string.assist_read_aloud),
|
||||
tint = if (reading) palette.accent else palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (canRegenerate) {
|
||||
IconButton(onClick = onRegenerate) {
|
||||
Icon(
|
||||
Icons.Filled.Refresh,
|
||||
contentDescription = stringResource(R.string.regenerate),
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
footLine(message)?.let { line ->
|
||||
Text(
|
||||
line,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(start = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (selecting) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { selecting = false },
|
||||
confirmButton = { TextButton(onClick = { selecting = false }) { Text(stringResource(R.string.close)) } },
|
||||
text = {
|
||||
SelectionContainer(Modifier.heightIn(max = 480.dp).verticalScroll(rememberScrollState())) {
|
||||
Text(words, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A reply's own words, as the person would copy them: its text steps, in order. */
|
||||
fun replyText(message: Message): String = pageProjection(
|
||||
message.steps.mapNotNull { step ->
|
||||
when (step.kind) {
|
||||
"text" -> step.shownMarkdown
|
||||
"page" -> "[page: ${step.title.orEmpty()}]"
|
||||
else -> null
|
||||
}
|
||||
}.joinToString("\n\n").ifBlank { message.text.orEmpty() },
|
||||
untitled = PAGE_UNTITLED,
|
||||
)
|
||||
|
||||
/** `pages.untitled`, for the text that is copied or read aloud (the card says it in the app's language). */
|
||||
private const val PAGE_UNTITLED = "Page"
|
||||
|
||||
/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */
|
||||
private fun footLine(message: Message): String? {
|
||||
val m = message.metrics ?: return message.model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return message.model
|
||||
return 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")
|
||||
}.joinToString(" · ").ifBlank { null }
|
||||
}
|
||||
|
||||
/** Three dots that breathe, and (before the first word) the loading line beside them. */
|
||||
@Composable
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) {
|
||||
val palette = LocalPalette.current
|
||||
// Still in a preview or a screenshot, where an animation that never ends never lets the
|
||||
// picture be taken.
|
||||
val still = LocalInspectionMode.current
|
||||
val pulse = rememberInfiniteTransition(label = "writing")
|
||||
Row(modifier.heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
repeat(3) { i ->
|
||||
val alpha = if (still) {
|
||||
listOf(1f, 0.6f, 0.3f)[i]
|
||||
} else {
|
||||
pulse.animateFloat(
|
||||
initialValue = 0.25f,
|
||||
targetValue = 1f,
|
||||
animationSpec = infiniteRepeatable(tween(600, delayMillis = i * 150), RepeatMode.Reverse),
|
||||
label = "dot$i",
|
||||
).value
|
||||
}
|
||||
Box(Modifier.padding(end = 4.dp).size(8.dp).alpha(alpha).clip(CircleShape).background(palette.accent))
|
||||
}
|
||||
if (withLine) {
|
||||
Text(
|
||||
stringResource(R.string.loading_line),
|
||||
color = palette.inkFaint,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply's steps in the order they happened. Prose is markdown; thinking and each round of
|
||||
* tools are one chip that opens; a `show` card stays in view, because it is something put in
|
||||
* front of the person.
|
||||
*/
|
||||
@Composable
|
||||
fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((ShowCard) -> Unit)? = null, onLongPress: (() -> Unit)? = null) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
// By its place in the reply, not by its turn in this loop: a chip the person
|
||||
// opened is the same chip when its step closes and others come after it.
|
||||
"thinking" -> key(step.index, step.kind) { ThinkingChip(step) }
|
||||
|
||||
// A closed step's pages are the server's to name (its `text`); in the step still
|
||||
// being written a page's fence is a page already, not source scrolling by.
|
||||
"text" -> RichMarkdown(step.shownMarkdown, onLongPress = onLongPress, pages = step.open)
|
||||
|
||||
// A page the server took out of the text as a step of its own: the same card.
|
||||
"page" -> PageCard(step.title.orEmpty())
|
||||
|
||||
"tools" -> ToolsChip(step, onShow)
|
||||
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Markdown with its fenced code taken out into [CodeBlock]s, each with its own Copy. */
|
||||
@Composable
|
||||
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null, pages: Boolean = false) {
|
||||
val segments = remember(markdown, pages) { splitFences(markdown, pages) }
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
segments.forEach { segment ->
|
||||
when (segment) {
|
||||
is Segment.Prose -> MarkdownText(segment.markdown, modifier = Modifier.fillMaxWidth(), onLongPress = onLongPress)
|
||||
is Segment.Code -> CodeBlock(segment.language, segment.code)
|
||||
is Segment.Page -> PageCard(segment.title)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A page in an answer (harness spec 3.8.0, `pages.md`): not drawn on a phone -- no web view, and
|
||||
* never its source. One quiet card says that there is one, by its title, and where it can be
|
||||
* seen. The title is a model's: plain text.
|
||||
*/
|
||||
@Composable
|
||||
fun PageCard(title: String, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
modifier.fillMaxWidth().clip(Block).border(1.dp, palette.border, Block).padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Web, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
stringResource(R.string.page_note, title.ifBlank { stringResource(R.string.page_untitled) }),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.ink,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(stringResource(R.string.page_where), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A code block: its language and Copy above, the code below in its own sideways scroller. */
|
||||
@Composable
|
||||
fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
Column(modifier.fillMaxWidth().clip(Block).background(palette.codeBg).border(1.dp, palette.codeBorder, Block)) {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
language.ifBlank { stringResource(R.string.code) },
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(onClick = { copy(code) }) {
|
||||
Icon(
|
||||
Icons.Filled.ContentCopy,
|
||||
contentDescription = stringResource(R.string.copy_code),
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = palette.codeBorder)
|
||||
// The fence's language in the theme's colours (ui/Highlight.kt); plain when it names none it reads.
|
||||
val shown = remember(code, language, palette) { highlight(code, language, palette) }
|
||||
Text(
|
||||
shown,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 13.sp,
|
||||
lineHeight = 19.sp,
|
||||
color = palette.ink,
|
||||
softWrap = false,
|
||||
modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(14.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A chip that opens: the icon, one line, and a chevron; [content] below when open. */
|
||||
@Composable
|
||||
private fun FoldChip(
|
||||
open: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
leading: @Composable () -> Unit,
|
||||
label: String,
|
||||
monospace: Boolean = false,
|
||||
tint: androidx.compose.ui.graphics.Color? = null,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Surface(onClick = onToggle, shape = Pill, color = palette.surfaceRaised, border = androidx.compose.foundation.BorderStroke(1.dp, palette.border)) {
|
||||
Row(Modifier.padding(start = 10.dp, end = 8.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(18.dp), contentAlignment = Alignment.Center) { leading() }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontFamily = if (monospace) FontFamily.Monospace else null,
|
||||
color = tint ?: palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
Icon(
|
||||
if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.padding(start = 4.dp).size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
AnimatedVisibility(open) { Box(Modifier.padding(top = 8.dp)) { content() } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThinkingChip(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
// Open only because the person opened it, and then it stays open: the step closing (the
|
||||
// thinking is over, the words begin) is not a reason to fold away what somebody is reading.
|
||||
var open by rememberSaveable(step.index) { mutableStateOf(false) }
|
||||
val label = if (step.open) stringResource(R.string.thinking) + "…" else stringResource(R.string.thought) + (step.label?.let { " $it" } ?: "")
|
||||
FoldChip(
|
||||
open = open,
|
||||
onToggle = { open = !open },
|
||||
leading = { Icon(Icons.Filled.Psychology, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(18.dp)) },
|
||||
label = label,
|
||||
) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 24.dp)) {
|
||||
Box(Modifier.width(2.dp).heightIn(min = 24.dp).background(palette.border))
|
||||
Text(
|
||||
step.text.orEmpty(),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One round of tools as one chip: a single call by its title ("bake --slow"), several by their
|
||||
* count. Open, each call is its block (command, change, output). A `show` card and a picture
|
||||
* the instance made are drawn apart, always in view.
|
||||
*/
|
||||
@Composable
|
||||
private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) {
|
||||
val palette = LocalPalette.current
|
||||
val (shows, calls) = step.calls.partition { it.show != null && it.status != "error" && it.error.isNullOrEmpty() }
|
||||
if (calls.isNotEmpty()) {
|
||||
var open by rememberSaveable(step.index, calls.firstOrNull()?.id) { mutableStateOf(false) }
|
||||
val failed = calls.any { it.status == "error" || !it.error.isNullOrEmpty() }
|
||||
val running = calls.any { it.status == "running" || it.status == "pending" }
|
||||
val single = calls.singleOrNull()
|
||||
val label = single?.let { it.block.title.ifBlank { it.name } } ?: stringResource(R.string.tools_used, calls.size.toString())
|
||||
FoldChip(
|
||||
open = open,
|
||||
onToggle = { open = !open },
|
||||
leading = {
|
||||
if (running) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(14.dp))
|
||||
} else {
|
||||
Icon(
|
||||
iconFor(single?.block?.kind ?: "tool"),
|
||||
contentDescription = null,
|
||||
tint = if (failed) palette.danger else palette.inkFaint,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
},
|
||||
label = label,
|
||||
monospace = single?.block?.kind == "shell",
|
||||
tint = if (failed) palette.danger else null,
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { calls.forEach { ToolCallBlock(it, onShow = onShow) } }
|
||||
}
|
||||
}
|
||||
shows.forEach { call -> ToolCallBlock(call, onShow = onShow) }
|
||||
// A picture the instance made stays in view, like a `show` card: it is the answer.
|
||||
step.calls.mapNotNull { call -> call.image?.takeIf { it.id.isNotBlank() && call.status != "error" && call.error.isNullOrEmpty() } }
|
||||
.forEach { GeneratedPicture(it) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Steered(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(start = 24.dp))
|
||||
}
|
||||
|
||||
// --- Attachments ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Attached pictures, fetched once with the token and kept small in memory; a picture that could
|
||||
* not be read is not asked for again until the app starts anew.
|
||||
*/
|
||||
private object Thumbnails {
|
||||
private const val SIDE = 320
|
||||
private val cache = LruCache<String, ImageBitmap>(32)
|
||||
private val failed = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
return image
|
||||
}
|
||||
|
||||
private suspend fun decode(bytes: ByteArray): ImageBitmap? = withContext(Dispatchers.Default) {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
|
||||
var sample = 1
|
||||
while (minOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= SIDE) sample *= 2
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })?.asImageBitmap()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An attachment as a square tile of [side]: a picture as its thumbnail, anything else as its
|
||||
* kind's icon and its name. The tile's size is fixed, so a row of them lines up whatever the
|
||||
* names.
|
||||
*/
|
||||
@Composable
|
||||
fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Box(modifier.size(side).clip(Block).background(palette.surfaceRaised).border(1.dp, palette.border, Block), contentAlignment = Alignment.Center) {
|
||||
if (attachment.image) {
|
||||
var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) }
|
||||
val still = LocalInspectionMode.current
|
||||
LaunchedEffect(attachment.id) { if (image == null && !still) image = Thumbnails.load(context, attachment.id) }
|
||||
val shown = image
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = attachment.name, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = attachment.name, tint = palette.inkFaint)
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
attachment.name,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = side - 16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,264 +0,0 @@
|
||||
@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.Folder
|
||||
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.TextButton
|
||||
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.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
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.LifecycleResumeEffect
|
||||
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.api.Doorstep
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
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"
|
||||
|
||||
/** Why this instance is refused, once it was asked what it is; null while it fits. */
|
||||
private var refused: Int? = null
|
||||
private var checked = false
|
||||
|
||||
/**
|
||||
* Read the list. [quiet] is the reload on coming back to the screen: the rows already shown
|
||||
* stay without a spinner, and only a change replaces them.
|
||||
*/
|
||||
fun load(kind: String, quiet: Boolean = false) {
|
||||
val switched = kind != this.kind
|
||||
this.kind = kind
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = !quiet || switched, error = null, chats = if (switched) emptyList() else it.chats) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
// An instance signed in to before it was downgraded, or by 0.1 against a 1.x
|
||||
// server, is refused here as at sign-in. Unreachable is not refused: the chat
|
||||
// list's own error says that better.
|
||||
if (!checked) {
|
||||
runCatching { Doorstep().discover(api.base) }.onSuccess {
|
||||
checked = true
|
||||
refused = refusal(fit(it))
|
||||
}
|
||||
}
|
||||
refused?.let { said ->
|
||||
_state.value = ChatsState(error = getApplication<Application>().getString(said))
|
||||
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 = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 = getApplication<Application>().explain(e)) }
|
||||
load(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatsScreen(
|
||||
onOpen: (String) -> Unit,
|
||||
onNew: () -> Unit,
|
||||
onNewAgent: () -> Unit,
|
||||
onSettings: () -> Unit,
|
||||
onFiles: () -> Unit,
|
||||
model: ChatsViewModel = viewModel(),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
val kind = if (tab == 0) "chat" else "agent"
|
||||
// Read again each time the list comes back into view -- from a chat, from another app --
|
||||
// so a new chat, a new title or a finished reply's dot is there without a pull.
|
||||
var shown by remember { mutableStateOf(false) }
|
||||
LifecycleResumeEffect(kind) {
|
||||
model.load(kind, quiet = shown)
|
||||
shown = true
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
IconButton(onClick = onFiles) {
|
||||
Icon(Icons.Filled.Folder, contentDescription = stringResource(R.string.files))
|
||||
}
|
||||
IconButton(onClick = onSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = if (tab == 0) onNew else onNewAgent,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(if (tab == 0) R.string.new_chat else R.string.new_agent_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 {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
// The sentence gives; the button keeps its size.
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = { model.load(kind) }) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.chats.isEmpty() && !state.loading && state.error == null) {
|
||||
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,188 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.Unarchive
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Modifier
|
||||
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 eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
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
|
||||
|
||||
/** The archived chats (`GET /api/v2/chats?archived=true`), newest first, a page at a time. */
|
||||
class ArchivedViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(archived = true)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(archived = true, before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Back among the chats: the web UI's Restore chat. [then] refreshes the drawer's list. */
|
||||
fun restore(chat: Chat, then: () -> Unit) {
|
||||
_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", false) })
|
||||
}.onSuccess { then() }
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
load()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface ArchivedActions {
|
||||
fun open(chat: Chat) {}
|
||||
fun restore(chat: Chat) {}
|
||||
fun more() {}
|
||||
fun reload() {}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ArchivedScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onRestored: () -> Unit, model: ArchivedViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(Unit) { model.load() }
|
||||
ArchivedContent(
|
||||
state,
|
||||
object : ArchivedActions {
|
||||
override fun open(chat: Chat) = onOpen(chat.id)
|
||||
|
||||
override fun restore(chat: Chat) = model.restore(chat, onRestored)
|
||||
|
||||
override fun more() = model.more()
|
||||
|
||||
override fun reload() = model.load()
|
||||
},
|
||||
onBack,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The archived chats: each opens as it is, and Restore puts it back among the chats. A row is
|
||||
* the title (which gives) and the restore button (which keeps its 48 dp).
|
||||
*/
|
||||
@Composable
|
||||
fun ArchivedContent(state: ChatsState, actions: ArchivedActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(stringResource(R.string.archived)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading && state.chats.isNotEmpty(), onRefresh = actions::reload, modifier = Modifier.padding(padding)) {
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
state.error?.let { error ->
|
||||
item {
|
||||
ListItem(
|
||||
headlineContent = { Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium) },
|
||||
trailingContent = { TextButton(onClick = actions::reload) { Text(stringResource(R.string.retry)) } },
|
||||
colors = ListItemDefaults.colors(containerColor = palette.bg),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.chats.isEmpty() && !state.loading && state.error == null) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp)) {
|
||||
Text(stringResource(R.string.archived_none), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(state.chats, key = { it.id }) { chat ->
|
||||
ListItem(
|
||||
headlineContent = {
|
||||
Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
leadingContent = if (chat.kind == "agent") {
|
||||
{ Icon(Icons.Filled.Terminal, contentDescription = null, tint = palette.inkMuted) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
trailingContent = {
|
||||
IconButton(onClick = { actions.restore(chat) }) {
|
||||
Icon(Icons.Filled.Unarchive, contentDescription = stringResource(R.string.archived_restore), tint = palette.accent)
|
||||
}
|
||||
},
|
||||
colors = ListItemDefaults.colors(containerColor = palette.bg),
|
||||
modifier = Modifier.clickable { actions.open(chat) },
|
||||
)
|
||||
HorizontalDivider(color = palette.border, modifier = Modifier.padding(start = 16.dp))
|
||||
}
|
||||
if (state.more) {
|
||||
item { LaunchedEffect(state.chats.size) { actions.more() } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Folder
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
/** A folder in the drawer, [depth] levels in, with the chats filed in it that are shown. */
|
||||
data class FolderGroup(val folder: Folder, val depth: Int, val chats: List<Chat>)
|
||||
|
||||
/**
|
||||
* The drawer's list in its sections, as the web's sidebar has them: the pinned chats (wherever
|
||||
* they are filed), the folders as a tree with their chats, then the unfiled chats of today, the
|
||||
* earlier ones, and the agent chats (which run on a linked computer) on their own. Each keeps
|
||||
* the server's order, newest first.
|
||||
*/
|
||||
data class ChatGroups(
|
||||
val today: List<Chat> = emptyList(),
|
||||
val earlier: List<Chat> = emptyList(),
|
||||
val agents: List<Chat> = emptyList(),
|
||||
val pinned: List<Chat> = emptyList(),
|
||||
val folders: List<FolderGroup> = emptyList(),
|
||||
) {
|
||||
/** Nothing to show: no chat in any section (a collapsed folder may hold some, so it counts). */
|
||||
val isEmpty: Boolean get() =
|
||||
today.isEmpty() && earlier.isEmpty() && agents.isEmpty() && pinned.isEmpty() && folders.all { it.chats.isEmpty() && !it.folder.collapsed }
|
||||
}
|
||||
|
||||
/** The day a chat was last written in, where the phone is; null when the server did not say. */
|
||||
fun Chat.day(zone: ZoneId): LocalDate? = (updatedAt ?: createdAt)?.let { stamp ->
|
||||
runCatching { OffsetDateTime.parse(stamp).atZoneSameInstant(zone).toLocalDate() }.getOrNull()
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders as the tree they are, each after its parent and siblings in the server's
|
||||
* `position` order, with its depth. A folder whose parent is not in the list counts as a top
|
||||
* one, so nothing is lost.
|
||||
*/
|
||||
fun folderTree(folders: List<Folder>): List<Pair<Folder, Int>> {
|
||||
val ids = folders.map { it.id }.toSet()
|
||||
val children = folders.groupBy { it.parentId?.takeIf { p -> p in ids } }
|
||||
val out = mutableListOf<Pair<Folder, Int>>()
|
||||
val seen = mutableSetOf<String>()
|
||||
fun walk(parent: String?, depth: Int) {
|
||||
children[parent].orEmpty().sortedBy { it.position }.forEach { f ->
|
||||
if (seen.add(f.id)) {
|
||||
out += f to depth
|
||||
walk(f.id, depth + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(null, 0)
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Split [chats] for the drawer, keeping those whose title holds [query] (any case; blank keeps
|
||||
* all). A chat without a date counts as earlier; one filed in a folder the list does not have
|
||||
* counts as unfiled. A collapsed folder hides its chats and the folders inside it; while
|
||||
* searching, folders without a match are left out and none is collapsed.
|
||||
*/
|
||||
fun groupChats(chats: List<Chat>, query: String, today: LocalDate, zone: ZoneId, folders: List<Folder> = emptyList()): ChatGroups {
|
||||
val wanted = query.trim()
|
||||
val searching = wanted.isNotEmpty()
|
||||
val shown = if (!searching) chats else chats.filter { it.title.contains(wanted, ignoreCase = true) }
|
||||
val (pinned, rest) = shown.partition { it.pinned }
|
||||
val ids = folders.map { it.id }.toSet()
|
||||
val (filed, unfiled) = rest.partition { it.folderId != null && it.folderId in ids }
|
||||
val byFolder = filed.groupBy { it.folderId }
|
||||
val groups = mutableListOf<FolderGroup>()
|
||||
var hiddenBelow: Int? = null
|
||||
for ((folder, depth) in folderTree(folders)) {
|
||||
if (hiddenBelow != null && depth > hiddenBelow) continue
|
||||
hiddenBelow = null
|
||||
val own = byFolder[folder.id].orEmpty()
|
||||
if (searching) {
|
||||
if (own.isNotEmpty()) groups += FolderGroup(folder, depth, own)
|
||||
continue
|
||||
}
|
||||
groups += FolderGroup(folder, depth, if (folder.collapsed) emptyList() else own)
|
||||
if (folder.collapsed) hiddenBelow = depth
|
||||
}
|
||||
val (agents, plain) = unfiled.partition { it.isAgent }
|
||||
val (now, before) = plain.partition { it.day(zone) == today }
|
||||
return ChatGroups(today = now, earlier = before, agents = agents, pinned = pinned, folders = groups)
|
||||
}
|
||||
|
||||
/**
|
||||
* A search hit's snippet with its [marks] drawn in [style]. The ranges are the server's; one that
|
||||
* runs past the text (it counts characters, not UTF-16 units) is cut to fit, and a broken one is
|
||||
* left out, so a bad range never throws.
|
||||
*/
|
||||
fun markedSnippet(snippet: String, marks: List<List<Int>>, style: SpanStyle): AnnotatedString = buildAnnotatedString {
|
||||
append(snippet)
|
||||
marks.forEach { range ->
|
||||
val start = range.getOrNull(0)?.coerceIn(0, snippet.length) ?: return@forEach
|
||||
val end = range.getOrNull(1)?.coerceIn(start, snippet.length) ?: return@forEach
|
||||
if (end > start) addStyle(style, start, end)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListScope
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DriveFileRenameOutline
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Inventory2
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.PushPin
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalDrawerSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
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.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.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ReportsFrame
|
||||
import eu.llembas.android.api.SearchHit
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
data class ChatsState(
|
||||
val chats: List<Chat> = emptyList(),
|
||||
val more: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The person's chat folders (`GET /folders`); empty where they have none. */
|
||||
val folders: List<Folder> = emptyList(),
|
||||
/** Chats whose messages hold the search words (`GET /search?in=chats`), and the words asked. */
|
||||
val found: List<SearchHit> = emptyList(),
|
||||
val foundFor: String = "",
|
||||
/** How many reports are unread: the badge on Reports. */
|
||||
val unreadReports: Int = 0,
|
||||
/** Whether the instance has Reports at all: one before 2.0.0-beta.12 has no such page to open. */
|
||||
val reports: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The events route's `reports` frame, as the drawer takes it: the badge is the server's count
|
||||
* of the unread, and an instance that sends the frame has Reports. Anything else it carries
|
||||
* (the newest report) is not the drawer's. A frame that cannot be read changes nothing.
|
||||
*/
|
||||
fun ChatsState.reported(data: String): ChatsState {
|
||||
val frame = runCatching { LembasJson.decodeFromString(ReportsFrame.serializer(), data) }.getOrNull() ?: return this
|
||||
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
|
||||
}
|
||||
|
||||
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
/** Why this instance is refused, once it was asked what it is; null while it fits. */
|
||||
private var refused: Int? = null
|
||||
private var checked = false
|
||||
|
||||
/** Read the list; the rows already shown stay while it is read again. */
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
// An instance signed in to before it was downgraded is refused here as at
|
||||
// sign-in. Unreachable is not refused: the list's own error says that better.
|
||||
if (!checked) {
|
||||
runCatching { Doorstep().discover(api.base) }.onSuccess {
|
||||
checked = true
|
||||
refused = refusal(fit(it))
|
||||
}
|
||||
}
|
||||
refused?.let { said ->
|
||||
_state.value = ChatsState(error = getApplication<Application>().getString(said))
|
||||
return@launch
|
||||
}
|
||||
val told = reportsTold
|
||||
val page = api.chats()
|
||||
// Folders are a side dish: the chats show without them if they cannot be read.
|
||||
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
|
||||
// So is the count of unread reports: an instance before Reports simply has none.
|
||||
val unread = runCatching { api.unreadReports() }
|
||||
// No such route (404, 405): no Reports. Any other trouble leaves what was known.
|
||||
val refused = (unread.exceptionOrNull() as? ApiException)?.status
|
||||
val has = if (unread.isSuccess) {
|
||||
true
|
||||
} else if (refused == 404 || refused == 405) {
|
||||
false
|
||||
} else {
|
||||
_state.value.reports
|
||||
}
|
||||
// The events route may have said the count while this was being read: its
|
||||
// word is the newer one, and a slow read does not write over it.
|
||||
val newer = reportsTold != told
|
||||
_state.value = ChatsState(
|
||||
chats = page.chats,
|
||||
more = page.more,
|
||||
folders = folders,
|
||||
unreadReports = if (newer) _state.value.unreadReports else unread.getOrDefault(_state.value.unreadReports),
|
||||
reports = has || (newer && _state.value.reports),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the person's events route while the app is in front, for its `reports` frame: the
|
||||
* badge on Reports moves when a report arrives or is read anywhere, not only when the drawer
|
||||
* opens. Runs until cancelled. An older server has no such route, or no such frame: the
|
||||
* badge is then what the drawer's own read said.
|
||||
*/
|
||||
suspend fun watchReports() {
|
||||
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return
|
||||
try {
|
||||
frames.collect { frame ->
|
||||
// An instance this app refuses shows its refusal and nothing else.
|
||||
if (frame.event == "reports" && refused == null) {
|
||||
reportsTold++
|
||||
_state.update { it.reported(frame.data) }
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the count is read when the drawer opens, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
|
||||
private var reportsTold = 0
|
||||
|
||||
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(before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 = getApplication<Application>().explain(e)) }
|
||||
load()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var searching: Job? = null
|
||||
|
||||
/**
|
||||
* Search the chats' messages on the instance for [query], once typing pauses: the title
|
||||
* filter is the phone's own, this finds the words inside. Under two characters, nothing.
|
||||
*/
|
||||
fun search(query: String) {
|
||||
searching?.cancel()
|
||||
val q = query.trim()
|
||||
if (q.length < 2) {
|
||||
_state.update { it.copy(found = emptyList(), foundFor = "") }
|
||||
return
|
||||
}
|
||||
searching = viewModelScope.launch {
|
||||
delay(SEARCH_PAUSE_MS)
|
||||
// A failure leaves the title filter alone; the search is the extra.
|
||||
runCatching { getApplication<Application>().lembas.instances.client()?.search(q, within = "chats") }
|
||||
.getOrNull()
|
||||
?.let { found -> _state.update { it.copy(found = found.hits("chats"), foundFor = q) } }
|
||||
}
|
||||
}
|
||||
|
||||
/** Pinned chats stay at the top of the list, wherever they are filed (the web's Pin). */
|
||||
fun pin(chat: Chat, pinned: Boolean) = changeChat(chat.copy(pinned = pinned), buildJsonObject { put("pinned", pinned) })
|
||||
|
||||
/** File [chat] in [folderId], or take it out of its folder with null. */
|
||||
fun move(chat: Chat, folderId: String?) = changeChat(chat.copy(folderId = folderId), buildJsonObject { put("folder_id", folderId) })
|
||||
|
||||
private fun changeChat(changed: Chat, body: JsonObject) {
|
||||
_state.update { s -> s.copy(chats = s.chats.map { if (it.id == changed.id) changed else it }) }
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().lembas.instances.client()?.updateChat(changed.id, body) }
|
||||
.onFailure { e -> failed(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/** A new folder at the top, and [then] the chat to file in it, if any. */
|
||||
fun newFolder(name: String, then: Chat? = null) {
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val folder = api.createFolder(name)
|
||||
_state.update { it.copy(folders = it.folders + folder) }
|
||||
if (then != null) move(then, folder.id)
|
||||
}.onFailure { e -> failed(e) }
|
||||
}
|
||||
}
|
||||
|
||||
fun renameFolder(folder: Folder, name: String) = changeFolder(folder.copy(name = name), buildJsonObject { put("name", name) })
|
||||
|
||||
/** Open or fold a folder; the server keeps it, so the web's sidebar folds the same. */
|
||||
fun toggleFolder(folder: Folder) = changeFolder(folder.copy(collapsed = !folder.collapsed), buildJsonObject { put("collapsed", !folder.collapsed) })
|
||||
|
||||
private fun changeFolder(changed: Folder, body: JsonObject) {
|
||||
_state.update { s -> s.copy(folders = s.folders.map { if (it.id == changed.id) changed else it }) }
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().lembas.instances.client()?.updateFolder(changed.id, body) }
|
||||
.onFailure { e -> failed(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/** The folder and those inside it go; their chats stay, in no folder (the server's rule). */
|
||||
fun deleteFolder(folder: Folder) {
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().lembas.instances.client()?.deleteFolder(folder.id) }
|
||||
.onSuccess { load() }
|
||||
.onFailure { e -> failed(e) }
|
||||
}
|
||||
}
|
||||
|
||||
/** A refusal is the server's sentence; the list is read again so it shows what is true. */
|
||||
private fun failed(e: Throwable) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
private const val SEARCH_PAUSE_MS = 400L
|
||||
|
||||
/** Where the drawer can go, besides a chat. */
|
||||
interface DrawerActions {
|
||||
fun newChat() {}
|
||||
fun newAgentChat() {}
|
||||
fun open(chatId: String) {}
|
||||
fun archive(chat: Chat) {}
|
||||
fun pin(chat: Chat, pinned: Boolean) {}
|
||||
fun move(chat: Chat, folderId: String?) {}
|
||||
fun newFolder(name: String, then: Chat?) {}
|
||||
fun renameFolder(folder: Folder, name: String) {}
|
||||
fun toggleFolder(folder: Folder) {}
|
||||
fun deleteFolder(folder: Folder) {}
|
||||
fun files() {}
|
||||
fun scheduled() {}
|
||||
fun reports() {}
|
||||
fun archived() {}
|
||||
fun memory() {}
|
||||
fun settings() {}
|
||||
fun more() {}
|
||||
fun retry() {}
|
||||
fun search(query: String) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The navigation drawer: New chat (and New folder) at the top, search, Files, Scheduled,
|
||||
* Archived and Memory, then the chats -- the pinned ones, the folders as a tree with theirs, then today's,
|
||||
* the earlier ones and the agent chats -- and Settings with the account at the foot. A long press
|
||||
* on a chat offers Pin, Move to folder and Archive; on a folder, Rename and Delete.
|
||||
*/
|
||||
@Composable
|
||||
fun DrawerContent(
|
||||
state: ChatsState,
|
||||
current: String?,
|
||||
account: String,
|
||||
actions: DrawerActions,
|
||||
modifier: Modifier = Modifier,
|
||||
today: LocalDate = LocalDate.now(),
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
initialQuery: String = "",
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var query by rememberSaveable { mutableStateOf(initialQuery) }
|
||||
LaunchedEffect(query) { actions.search(query) }
|
||||
val groups = remember(state.chats, state.folders, query, today) { groupChats(state.chats, query, today, zone, state.folders) }
|
||||
// The one dialog open at a time: a chat to file, a folder to name (new or renamed), one to delete.
|
||||
var moving by remember { mutableStateOf<Chat?>(null) }
|
||||
var naming by remember { mutableStateOf<FolderNaming?>(null) }
|
||||
var deleting by remember { mutableStateOf<Folder?>(null) }
|
||||
val chatActions = remember(actions) {
|
||||
ChatRowActions(open = actions::open, archive = actions::archive, pin = actions::pin, move = { moving = it })
|
||||
}
|
||||
ModalDrawerSheet(modifier = modifier, drawerContainerColor = palette.surface, drawerShape = RoundedCornerShape(topEnd = 24.dp, bottomEnd = 24.dp)) {
|
||||
Column(Modifier.fillMaxHeight()) {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 24.dp, end = 8.dp, top = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
IconButton(onClick = { naming = FolderNaming() }) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.folder_new))
|
||||
}
|
||||
IconButton(onClick = actions::newChat) { Icon(Icons.Filled.EditNote, contentDescription = stringResource(R.string.new_chat)) }
|
||||
}
|
||||
TextField(
|
||||
value = query,
|
||||
onValueChange = { query = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.chats_search)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||
trailingIcon = {
|
||||
if (query.isNotEmpty()) {
|
||||
IconButton(onClick = { query = "" }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear)) }
|
||||
}
|
||||
},
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
colors = TextFieldDefaults.colors(
|
||||
focusedContainerColor = palette.surfaceRaised,
|
||||
unfocusedContainerColor = palette.surfaceRaised,
|
||||
focusedIndicatorColor = Color.Transparent,
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
LazyColumn(Modifier.weight(1f)) {
|
||||
item { DrawerItem(Icons.Filled.EditNote, stringResource(R.string.new_chat), onClick = actions::newChat) }
|
||||
item { DrawerItem(Icons.Filled.Terminal, stringResource(R.string.new_agent_chat), onClick = actions::newAgentChat) }
|
||||
item { DrawerItem(Icons.Filled.Folder, stringResource(R.string.files), onClick = actions::files) }
|
||||
if (state.reports) {
|
||||
item { DrawerItem(Icons.Filled.Summarize, stringResource(R.string.reports), badge = state.unreadReports, onClick = actions::reports) }
|
||||
}
|
||||
item { DrawerItem(Icons.Filled.Schedule, stringResource(R.string.scheduled), onClick = actions::scheduled) }
|
||||
item { DrawerItem(Icons.Filled.Inventory2, stringResource(R.string.archived), onClick = actions::archived) }
|
||||
item { DrawerItem(Icons.Filled.Psychology, stringResource(R.string.memory), onClick = actions::memory) }
|
||||
item { HorizontalDivider(color = palette.border, modifier = Modifier.padding(horizontal = 28.dp, vertical = 8.dp)) }
|
||||
state.error?.let { error ->
|
||||
item {
|
||||
Row(Modifier.fillMaxWidth().padding(start = 28.dp, end = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(error, color = palette.danger, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = actions::retry) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
section(R.string.chats_pinned, groups.pinned, current, chatActions, key = "pinned")
|
||||
groups.folders.forEach { group ->
|
||||
item(key = "f${group.folder.id}") {
|
||||
FolderItem(
|
||||
group.folder,
|
||||
group.depth,
|
||||
onToggle = { actions.toggleFolder(group.folder) },
|
||||
onRename = { naming = FolderNaming(group.folder) },
|
||||
onDelete = { deleting = group.folder },
|
||||
)
|
||||
}
|
||||
items(group.chats, key = { "f${group.folder.id}/${it.id}" }) { chat ->
|
||||
ChatItem(chat, chat.id == current, chatActions, indent = 16 * (group.depth + 1))
|
||||
}
|
||||
}
|
||||
section(R.string.chats_today, groups.today, current, chatActions)
|
||||
section(R.string.chats_earlier, groups.earlier, current, chatActions)
|
||||
section(R.string.chats_agents, groups.agents, current, chatActions)
|
||||
// What the instance found inside the messages, for the words in the box now.
|
||||
val inMessages = if (query.isNotBlank() && state.foundFor == query.trim()) state.found.filter { it.id != null } else emptyList()
|
||||
if (inMessages.isNotEmpty()) {
|
||||
item(key = "hfound") {
|
||||
Text(
|
||||
stringResource(R.string.chats_found_in_messages),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
items(inMessages, key = { "s${it.id}" }) { hit -> FoundItem(hit, onOpen = { actions.open(hit.id!!) }) }
|
||||
}
|
||||
if (groups.isEmpty && inMessages.isEmpty() && !state.loading && state.error == null) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(if (query.isBlank()) R.string.empty_chats else R.string.chats_none_found),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 28.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.more && query.isBlank()) {
|
||||
item { LaunchedEffect(state.chats.size) { actions.more() } }
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = palette.border)
|
||||
DrawerItem(Icons.Filled.Settings, stringResource(R.string.settings), subtitle = account.ifBlank { null }, onClick = actions::settings)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
}
|
||||
}
|
||||
moving?.let { chat ->
|
||||
MoveDialog(
|
||||
chat,
|
||||
state.folders,
|
||||
onPick = { folder ->
|
||||
moving = null
|
||||
actions.move(chat, folder)
|
||||
},
|
||||
onNewFolder = {
|
||||
moving = null
|
||||
naming = FolderNaming(then = chat)
|
||||
},
|
||||
onDismiss = { moving = null },
|
||||
)
|
||||
}
|
||||
naming?.let { asked ->
|
||||
FolderNameDialog(
|
||||
asked.folder?.name.orEmpty(),
|
||||
title = if (asked.folder != null) R.string.folder_rename else R.string.folder_new,
|
||||
onSave = { name ->
|
||||
naming = null
|
||||
if (asked.folder != null) actions.renameFolder(asked.folder, name) else actions.newFolder(name, asked.then)
|
||||
},
|
||||
onDismiss = { naming = null },
|
||||
)
|
||||
}
|
||||
deleting?.let { folder ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleting = null },
|
||||
text = { Text(stringResource(R.string.folder_delete_confirm, folder.name)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
deleting = null
|
||||
actions.deleteFolder(folder)
|
||||
}) { Text(stringResource(R.string.folder_delete), color = LocalPalette.current.danger) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A chat found by its words: its title, and the snippet with the matched words marked (plain
|
||||
* text -- a snippet can be model output).
|
||||
*/
|
||||
@Composable
|
||||
private fun FoundItem(hit: SearchHit, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val marked = remember(hit.snippet, hit.marks, palette) {
|
||||
markedSnippet(hit.snippet, hit.marks, SpanStyle(color = palette.ink, fontWeight = FontWeight.SemiBold, background = palette.accentSoft))
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp)
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.clickable(onClick = onOpen)
|
||||
.heightIn(min = 48.dp)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(
|
||||
hit.title.ifBlank { stringResource(R.string.new_chat) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (hit.snippet.isNotBlank()) {
|
||||
Text(marked, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A folder to name: [folder] to rename, or a new one (into which [then] is filed, if given). */
|
||||
private data class FolderNaming(val folder: Folder? = null, val then: Chat? = null)
|
||||
|
||||
/** What a chat's row can do: open it, and from its long-press menu Pin, Move to folder, Archive. */
|
||||
private class ChatRowActions(val open: (String) -> Unit, val archive: (Chat) -> Unit, val pin: (Chat, Boolean) -> Unit, val move: (Chat) -> Unit)
|
||||
|
||||
private fun LazyListScope.section(title: Int, chats: List<Chat>, current: String?, actions: ChatRowActions, key: String = "c") {
|
||||
if (chats.isEmpty()) return
|
||||
item(key = "h$title") {
|
||||
Text(
|
||||
stringResource(title),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = LocalPalette.current.inkFaint,
|
||||
modifier = Modifier.padding(start = 28.dp, end = 28.dp, top = 12.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
items(chats, key = { "$key${it.id}" }) { chat -> ChatItem(chat, chat.id == current, actions) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder's row: its name (which gives), indented by its depth, and a chevron that says whether
|
||||
* it is open. A tap folds or opens it; a long press offers Rename folder and Delete folder.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun FolderItem(folder: Folder, depth: Int, onToggle: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box(Modifier.fillMaxWidth().padding(start = 12.dp + (16 * depth).dp, end = 12.dp)) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(28.dp))
|
||||
.combinedClickable(onClick = onToggle, onLongClick = { menu = true })
|
||||
.heightIn(min = 48.dp)
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
folder.name,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Icon(
|
||||
if (folder.collapsed) Icons.Filled.ExpandMore else Icons.Filled.ExpandLess,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.DriveFileRenameOutline, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.folder_rename)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
onRename()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.Delete, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.folder_delete)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
onDelete()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Move to folder: No folder, every folder as its tree, and New folder at the foot. */
|
||||
@Composable
|
||||
private fun MoveDialog(chat: Chat, folders: List<Folder>, onPick: (String?) -> Unit, onNewFolder: () -> Unit, onDismiss: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val tree = remember(folders) { folderTree(folders) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.folder_move)) },
|
||||
text = {
|
||||
LazyColumn {
|
||||
item { PickRow(stringResource(R.string.folder_none), depth = 0, chosen = chat.folderId == null) { onPick(null) } }
|
||||
items(tree, key = { it.first.id }) { (folder, depth) ->
|
||||
PickRow(folder.name, depth, chosen = chat.folderId == folder.id) { onPick(folder.id) }
|
||||
}
|
||||
item {
|
||||
TextButton(onClick = onNewFolder, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = null, tint = palette.accent)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.folder_new))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PickRow(label: String, depth: Int, chosen: Boolean, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(12.dp))
|
||||
.background(if (chosen) palette.accentSoft else Color.Transparent)
|
||||
.clickable(onClick = onClick)
|
||||
.heightIn(min = 48.dp)
|
||||
.padding(start = 8.dp + (16 * depth).dp, end = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Folder, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
/** New folder / Rename folder: one line, saved only with a name. */
|
||||
@Composable
|
||||
private fun FolderNameDialog(initial: String, title: Int, onSave: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(initial) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(title)) },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
singleLine = true,
|
||||
label = { Text(stringResource(R.string.folder_name)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onSave(name.trim()) }, enabled = name.isNotBlank()) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, badge: Int = 0, onClick: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
color = Color.Transparent,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 52.dp).padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(icon, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(22.dp))
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
}
|
||||
// A count of what is new: the words give, the badge keeps its size.
|
||||
if (badge > 0) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Box(Modifier.background(palette.accent, RoundedCornerShape(50)).padding(horizontal = 8.dp, vertical = 2.dp)) {
|
||||
Text(if (badge > 99) "99+" else badge.toString(), style = MaterialTheme.typography.labelMedium, color = palette.bg, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One chat: its title (which gives), and a dot for news or for a reply being written. */
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
private fun ChatItem(chat: Chat, selected: Boolean, actions: ChatRowActions, indent: Int = 0) {
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
Box(Modifier.fillMaxWidth().padding(start = 12.dp + indent.dp, end = 12.dp)) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(28.dp))
|
||||
.background(if (selected) palette.accentSoft else Color.Transparent)
|
||||
.combinedClickable(onClick = { actions.open(chat.id) }, onLongClick = { menu = true })
|
||||
.heightIn(min = 48.dp)
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
chat.title.ifBlank { stringResource(R.string.new_chat) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = if (selected) palette.ink else palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (chat.unread || chat.running) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(if (chat.running) palette.leaf else palette.accent))
|
||||
}
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.PushPin, contentDescription = null) },
|
||||
text = { Text(stringResource(if (chat.pinned) R.string.chat_unpin else R.string.chat_pin)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
actions.pin(chat, !chat.pinned)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.AutoMirrored.Filled.DriveFileMove, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.folder_move)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
actions.move(chat)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
leadingIcon = { Icon(Icons.Filled.Archive, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.archive)) },
|
||||
onClick = {
|
||||
menu = false
|
||||
actions.archive(chat)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.memory
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.SmartToy
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.ListItemDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
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.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
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.DataGroup
|
||||
import eu.llembas.android.api.Memory
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class MemoryState(
|
||||
val memories: List<Memory> = emptyList(),
|
||||
val groups: List<DataGroup> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** The person's memories (`/api/v2/memories`): read, added, changed and forgotten. */
|
||||
class MemoryViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(MemoryState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val list = api.memories()
|
||||
_state.value = MemoryState(memories = list.memories, groups = list.groups)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun add(content: String, groupId: String?) = act { api ->
|
||||
val made = api.addMemory(content, groupId)
|
||||
_state.update { it.copy(memories = listOf(made) + it.memories) }
|
||||
}
|
||||
|
||||
fun edit(memory: Memory, content: String) = act { api ->
|
||||
val changed = api.editMemory(memory.id, content)
|
||||
_state.update { s -> s.copy(memories = s.memories.map { if (it.id == changed.id) changed else it }) }
|
||||
}
|
||||
|
||||
fun forget(memory: Memory) = act { api ->
|
||||
api.forgetMemory(memory.id)
|
||||
_state.update { s -> s.copy(memories = s.memories.filterNot { it.id == memory.id }) }
|
||||
}
|
||||
|
||||
/** One change; a refusal (a limit, an empty text, one already gone) is the server's sentence. */
|
||||
private fun act(change: suspend (eu.llembas.android.api.ApiClient) -> Unit) {
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
_state.update { it.copy(error = null) }
|
||||
change(api)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface MemoryActions {
|
||||
fun add(content: String, groupId: String?) {}
|
||||
fun edit(memory: Memory, content: String) {}
|
||||
fun forget(memory: Memory) {}
|
||||
fun reload() {}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun MemoryScreen(onBack: () -> Unit, model: MemoryViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(Unit) { model.load() }
|
||||
MemoryContent(
|
||||
state,
|
||||
object : MemoryActions {
|
||||
override fun add(content: String, groupId: String?) = model.add(content, groupId)
|
||||
|
||||
override fun edit(memory: Memory, content: String) = model.edit(memory, content)
|
||||
|
||||
override fun forget(memory: Memory) = model.forget(memory)
|
||||
|
||||
override fun reload() = model.load()
|
||||
},
|
||||
onBack,
|
||||
)
|
||||
}
|
||||
|
||||
/** What the dialog is for: a new memory ([memory] null), or changing one. */
|
||||
private data class Editing(val memory: Memory? = null)
|
||||
|
||||
/**
|
||||
* Memory, as Settings › Memory on the web: what models remember about you, newest first. A row
|
||||
* is the text (plain, never markdown: a model may have written it), with a mark when a model
|
||||
* did and the data group when there is more than one. A tap edits or forgets it; Add remembers
|
||||
* something new.
|
||||
*/
|
||||
@Composable
|
||||
fun MemoryContent(state: MemoryState, actions: MemoryActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
var editing by remember { mutableStateOf<Editing?>(null) }
|
||||
val manyGroups = state.groups.size > 1
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(stringResource(R.string.memory)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = { editing = Editing() },
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.memory_remember)) },
|
||||
containerColor = palette.accent,
|
||||
contentColor = palette.accentInk,
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading && state.memories.isNotEmpty(), onRefresh = actions::reload, modifier = Modifier.padding(padding)) {
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.memory_intro),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
state.error?.let { error ->
|
||||
item {
|
||||
ListItem(
|
||||
headlineContent = { Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium) },
|
||||
trailingContent = { TextButton(onClick = actions::reload) { Text(stringResource(R.string.retry)) } },
|
||||
colors = ListItemDefaults.colors(containerColor = palette.bg),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (state.memories.isEmpty() && !state.loading && state.error == null) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(24.dp)) {
|
||||
Text(stringResource(R.string.memory_none), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(state.memories, key = { it.id }) { memory ->
|
||||
ListItem(
|
||||
headlineContent = { Text(memory.content, maxLines = 4, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (manyGroups) {
|
||||
{ Text(memory.dataGroup.name, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
trailingContent = if (memory.byModel) {
|
||||
{ Icon(Icons.Filled.SmartToy, contentDescription = stringResource(R.string.memory_by_model), tint = palette.inkFaint) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
colors = ListItemDefaults.colors(containerColor = palette.bg),
|
||||
modifier = Modifier.clickable { editing = Editing(memory) }.heightIn(min = 48.dp),
|
||||
)
|
||||
HorizontalDivider(color = palette.border, modifier = Modifier.padding(start = 16.dp))
|
||||
}
|
||||
// Room under the last row for the button over it.
|
||||
item { Box(Modifier.heightIn(min = 88.dp)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
editing?.let { asked ->
|
||||
MemoryDialog(
|
||||
asked.memory,
|
||||
groups = if (manyGroups) state.groups else emptyList(),
|
||||
onSave = { content, group ->
|
||||
editing = null
|
||||
if (asked.memory != null) actions.edit(asked.memory, content) else actions.add(content, group)
|
||||
},
|
||||
onForget = {
|
||||
editing = null
|
||||
asked.memory?.let(actions::forget)
|
||||
},
|
||||
onDismiss = { editing = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A memory's text in one box. New: Remember, and the data group when there is a choice. An
|
||||
* existing one: Save and Forget.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun MemoryDialog(memory: Memory?, groups: List<DataGroup>, onSave: (String, String?) -> Unit, onForget: () -> Unit, onDismiss: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
var text by remember { mutableStateOf(memory?.content.orEmpty()) }
|
||||
var group by remember { mutableStateOf(groups.firstOrNull()?.id) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(if (memory == null) R.string.memory_remember else R.string.memory)) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
label = { Text(stringResource(R.string.memory_label)) },
|
||||
placeholder = { Text(stringResource(R.string.memory_hint)) },
|
||||
minLines = 2,
|
||||
maxLines = 8,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
if (memory == null && groups.isNotEmpty()) {
|
||||
Text(stringResource(R.string.memory_group), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
groups.forEach { g ->
|
||||
FilterChip(selected = group == g.id, onClick = { group = g.id }, label = { Text(g.name) })
|
||||
}
|
||||
}
|
||||
}
|
||||
if (memory != null) {
|
||||
TextButton(onClick = onForget, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.memory_forget), color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { onSave(text.trim(), group) }, enabled = text.isNotBlank()) {
|
||||
Text(stringResource(if (memory == null) R.string.memory_remember else R.string.save))
|
||||
}
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
@file:OptIn(ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.reports
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
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.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
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.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Reply
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DoneAll
|
||||
import androidx.compose.material.icons.filled.PriorityHigh
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.SwipeToDismissBoxValue
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.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.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
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.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Report
|
||||
import eu.llembas.android.api.sortedReports
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.pageProjection
|
||||
import eu.llembas.android.ui.scheduled.BackBar
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
private suspend fun Application.api(): ApiClient = lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
/** A server without the reports routes answers 404 (or 405): it is older, not broken. */
|
||||
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
|
||||
|
||||
// --- The list --------------------------------------------------------------------------------
|
||||
|
||||
data class ReportsState(
|
||||
val reports: List<Report> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The instance is older than Reports: said plainly, instead of an error. */
|
||||
val unsupported: Boolean = false,
|
||||
)
|
||||
|
||||
class ReportsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ReportsState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val reports = getApplication<Application>().api().reports()
|
||||
_state.value = ReportsState(reports = sortedReports(reports))
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
it.copy(loading = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication<Application>().explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Read: it stays in the list, among those read. A failure is put right by reading the list again. */
|
||||
fun markRead(report: Report) {
|
||||
_state.update { s -> s.copy(reports = sortedReports(s.reports.map { if (it.id == report.id) it.copy(unread = false) else it })) }
|
||||
Notifications.reportSeen(getApplication(), report.id)
|
||||
viewModelScope.launch { runCatching { getApplication<Application>().api().readReport(report.id) }.onFailure { fail(it) } }
|
||||
}
|
||||
|
||||
fun delete(report: Report) {
|
||||
_state.update { s -> s.copy(reports = s.reports.filterNot { it.id == report.id }) }
|
||||
Notifications.reportSeen(getApplication(), report.id)
|
||||
viewModelScope.launch { runCatching { getApplication<Application>().api().deleteReport(report.id) }.onFailure { fail(it) } }
|
||||
}
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
||||
interface ReportsActions {
|
||||
fun open(report: Report) {}
|
||||
fun markRead(report: Report) {}
|
||||
fun delete(report: Report) {}
|
||||
fun reload() {}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ReportsScreen(onBack: () -> Unit, onOpen: (String) -> Unit, model: ReportsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
// Read again each time the page comes up: a report opened and read is no longer bold on the way back.
|
||||
LaunchedEffect(Unit) { model.load() }
|
||||
ReportsContent(
|
||||
state,
|
||||
object : ReportsActions {
|
||||
override fun open(report: Report) = onOpen(report.id)
|
||||
|
||||
override fun markRead(report: Report) = model.markRead(report)
|
||||
|
||||
override fun delete(report: Report) = model.delete(report)
|
||||
|
||||
override fun reload() = model.load()
|
||||
},
|
||||
onBack,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports: what scheduled tasks had to tell. The unread first; each row its title, the task it
|
||||
* came from and when, with a mark where the model called it important. Pull to read the list
|
||||
* again; swipe a row one way to mark it read, the other to delete it (which asks once).
|
||||
*/
|
||||
@Composable
|
||||
fun ReportsContent(state: ReportsState, actions: ReportsActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
var deleting by remember { mutableStateOf<Report?>(null) }
|
||||
deleting?.let { report ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleting = null },
|
||||
title = { Text(stringResource(R.string.report_delete_title)) },
|
||||
text = { Text(stringResource(R.string.report_delete_line, report.title.ifBlank { stringResource(R.string.report_untitled) })) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
deleting = null
|
||||
actions.delete(report)
|
||||
}) { Text(stringResource(R.string.delete), color = palette.danger) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
Scaffold(containerColor = palette.bg, topBar = { BackBar(stringResource(R.string.reports), onBack) }) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
state.error?.let { error ->
|
||||
item {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = actions::reload) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.reports.isEmpty() && !state.loading && state.error == null) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(if (state.unsupported) R.string.reports_unsupported else R.string.reports_none),
|
||||
color = palette.inkMuted,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.reports, key = { it.id }) { report ->
|
||||
ReportRow(report, onOpen = { actions.open(report) }, onRead = { actions.markRead(report) }, onDelete = { deleting = report })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One report in the list. Swiping never removes the row by itself: towards the end marks it read,
|
||||
* towards the start asks whether to delete it, and either way the row comes back to rest.
|
||||
*/
|
||||
@Composable
|
||||
private fun ReportRow(report: Report, onOpen: () -> Unit, onRead: () -> Unit, onDelete: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val swipe = rememberSwipeToDismissBoxState(
|
||||
confirmValueChange = { to ->
|
||||
when (to) {
|
||||
SwipeToDismissBoxValue.StartToEnd -> if (report.unread) onRead()
|
||||
SwipeToDismissBoxValue.EndToStart -> onDelete()
|
||||
SwipeToDismissBoxValue.Settled -> Unit
|
||||
}
|
||||
false
|
||||
},
|
||||
)
|
||||
SwipeToDismissBox(
|
||||
state = swipe,
|
||||
enableDismissFromStartToEnd = report.unread,
|
||||
backgroundContent = {
|
||||
val deletes = swipe.dismissDirection == SwipeToDismissBoxValue.EndToStart
|
||||
Row(
|
||||
Modifier.fillMaxSize().background(
|
||||
if (deletes) palette.dangerSoft else palette.surfaceActive,
|
||||
RoundedCornerShape(16.dp),
|
||||
).padding(horizontal = 20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = if (deletes) Arrangement.End else Arrangement.Start,
|
||||
) {
|
||||
Icon(
|
||||
if (deletes) Icons.Filled.Delete else Icons.Filled.DoneAll,
|
||||
contentDescription = stringResource(if (deletes) R.string.delete else R.string.report_mark_read),
|
||||
tint = if (deletes) palette.danger else palette.inkMuted,
|
||||
)
|
||||
}
|
||||
},
|
||||
) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.background(palette.surfaceRaised, RoundedCornerShape(16.dp))
|
||||
.clickable(onClick = onOpen)
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
// The unread dot's place is kept for a read row too, so the titles start on one line.
|
||||
Box(Modifier.padding(top = 6.dp).size(10.dp).background(if (report.unread) palette.accent else palette.surfaceRaised, CircleShape))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
report.title.ifBlank { stringResource(R.string.report_untitled) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = if (report.unread) FontWeight.SemiBold else FontWeight.Normal,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
ReportFacts(report)
|
||||
if (report.summary.isNotBlank()) {
|
||||
Text(report.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (report.high) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.Filled.PriorityHigh,
|
||||
contentDescription = stringResource(R.string.report_important),
|
||||
tint = palette.warning,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a report's title: the task it came from, and when. */
|
||||
@Composable
|
||||
private fun ReportFacts(report: Report) {
|
||||
val palette = LocalPalette.current
|
||||
val facts = listOfNotNull(report.from.ifBlank { null }, ScheduleLogic.moment(report.created)).joinToString(" · ")
|
||||
if (facts.isNotBlank()) Text(facts, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
// --- One report ------------------------------------------------------------------------------
|
||||
|
||||
data class ReportState(val report: Report? = null, val loading: Boolean = true, val error: String? = null, val replying: Boolean = false)
|
||||
|
||||
class ReportViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ReportState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
/** Read the report, and mark it read: opening it is reading it. */
|
||||
fun load(id: String) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().api()
|
||||
val report = api.report(id)
|
||||
_state.value = ReportState(report = report.copy(unread = false), loading = false)
|
||||
// Read here: its notification, if one is still up, goes.
|
||||
Notifications.reportSeen(getApplication(), id)
|
||||
if (report.unread) runCatching { api.readReport(id) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reply: the server continues the report as a conversation and says which chat it is. */
|
||||
fun reply(then: (chat: String, title: String) -> Unit) {
|
||||
val report = _state.value.report ?: return
|
||||
// A reply that was begun before goes on in its chat: nothing is asked of the server.
|
||||
report.chatId?.let { return then(it, report.title) }
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(replying = true, error = null) }
|
||||
try {
|
||||
val chat = getApplication<Application>().api().replyToReport(report.id) ?: throw ApiException(502, "")
|
||||
_state.update { it.copy(replying = false) }
|
||||
then(chat, report.title)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(replying = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ReportScreen(id: String, onBack: () -> Unit, onReply: (chat: String, title: String) -> Unit, model: ReportViewModel = viewModel(key = "report-$id")) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(id) { model.load(id) }
|
||||
ReportContent(
|
||||
state,
|
||||
onBack = onBack,
|
||||
onRetry = { model.load(id) },
|
||||
onReply = { model.reply(onReply) },
|
||||
onShare = { report ->
|
||||
val send = Intent(
|
||||
Intent.ACTION_SEND,
|
||||
).setType("text/plain").putExtra(Intent.EXTRA_SUBJECT, report.title).putExtra(Intent.EXTRA_TEXT, shareText(report))
|
||||
runCatching { context.startActivity(Intent.createChooser(send, null)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** What Share hands over: the title, then the report as text -- a page in it as its one line, never its source. */
|
||||
fun shareText(report: Report): String {
|
||||
// The server's own text of the body where it sends one; else the same made here.
|
||||
val text = report.text?.trim()?.ifBlank { null } ?: pageProjection(report.body.orEmpty(), untitled = "Page")
|
||||
return listOf(report.title, text).filter { it.isNotBlank() }.joinToString("\n\n")
|
||||
}
|
||||
|
||||
/**
|
||||
* A report, read as a page: its title, where it came from and when, then the body -- Markdown a
|
||||
* model wrote, drawn as the chat draws a reply (untrusted: no images, no HTML; a page in it is a
|
||||
* card, not a page). Reply stays at the foot; Share is in the bar.
|
||||
*/
|
||||
@Composable
|
||||
fun ReportContent(state: ReportState, onBack: () -> Unit = {}, onRetry: () -> Unit = {}, onReply: () -> Unit = {}, onShare: (Report) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val report = state.report
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
BackBar(stringResource(R.string.report), onBack) {
|
||||
if (report !=
|
||||
null
|
||||
) {
|
||||
IconButton(onClick = { onShare(report) }) { Icon(Icons.Filled.Share, contentDescription = stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (report != null) {
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().padding(16.dp)) {
|
||||
Button(onClick = onReply, enabled = !state.replying, modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
|
||||
if (state.replying) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
} else {
|
||||
Icon(Icons.AutoMirrored.Filled.Reply, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.report_reply))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
state.error?.let { error ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
if (report == null) TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
|
||||
}
|
||||
}
|
||||
if (report == null) {
|
||||
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
} else {
|
||||
Row(verticalAlignment = Alignment.Top) {
|
||||
Text(
|
||||
report.title.ifBlank { stringResource(R.string.report_untitled) },
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (report.high) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.Filled.PriorityHigh, contentDescription = stringResource(R.string.report_important), tint = palette.warning)
|
||||
}
|
||||
}
|
||||
ReportFacts(report)
|
||||
// The server's own text of the body, where each page is its one line; else the body.
|
||||
RichMarkdown((report.text?.ifBlank { null } ?: report.body.orEmpty()).ifBlank { report.summary })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
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 androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
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.ApiException
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.chat.LocalCopy
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class RunState(val title: String = "", val result: RunResult? = null, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(RunState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
/** The run and its result; the schedule's title too, for the bar (without it, "Scheduled"). */
|
||||
fun open(schedule: String, run: String) {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
val result = api.scheduleRun(schedule, run)
|
||||
val title = runCatching { api.schedule(schedule).title }.getOrDefault("")
|
||||
_state.update { it.copy(result = result, title = title, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RunScreen(
|
||||
scheduleId: String,
|
||||
runId: String,
|
||||
onBack: () -> Unit,
|
||||
onOpenChat: (String) -> Unit,
|
||||
onOpenReport: (String) -> Unit = {},
|
||||
model: RunViewModel = viewModel(key = "run-$scheduleId-$runId"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(runId) {
|
||||
model.open(scheduleId, runId)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
RunContent(state, onBack = onBack, onOpenChat = onOpenChat, onOpenReport = onOpenReport)
|
||||
}
|
||||
|
||||
/**
|
||||
* One run, where a notification's tap lands: its status and when, the model and why, and the
|
||||
* result in full -- Markdown a model wrote, drawn by the app's Markwon (no images, no HTML,
|
||||
* links only outside) -- or why there is none. Open its chat goes on from there.
|
||||
*/
|
||||
@Composable
|
||||
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}, onOpenReport: (String) -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val copy: (String) -> Unit = remember(context) {
|
||||
{ text -> context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text)) }
|
||||
}
|
||||
val result = state.result
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = { BackBar(state.title.ifBlank { stringResource(R.string.scheduled) }, onBack) },
|
||||
) { padding ->
|
||||
if (result == null) {
|
||||
Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
|
||||
if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) }
|
||||
}
|
||||
return@Scaffold
|
||||
}
|
||||
val run = result.run
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
StatusChip(run.status, run.missed, run.waitingFor)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
ScheduleLogic.moment(run.finishedAt ?: run.startedAt ?: run.dueAt) ?: "—",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
RunFacts(run, withPreview = false)
|
||||
// What the run filed for the person, when it filed anything.
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
}
|
||||
Header(stringResource(R.string.run_result))
|
||||
val text = result.text
|
||||
if (text.isNullOrBlank()) {
|
||||
Text(stringResource(R.string.run_no_text), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
} else {
|
||||
RichMarkdown(text)
|
||||
}
|
||||
run.chatId?.let { chat ->
|
||||
FilledTonalButton(onClick = { onOpenChat(chat) }, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(top = 8.dp)) {
|
||||
Text(stringResource(R.string.run_open_chat))
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.heightIn(min = 24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
/** How a run's status is drawn: its colour family, not its words. */
|
||||
enum class Tone { Good, Quiet, Bad, Waiting, Neutral }
|
||||
|
||||
object ScheduleLogic {
|
||||
fun tone(status: String): Tone = when (status) {
|
||||
"ok" -> Tone.Good
|
||||
"silent", "unchanged" -> Tone.Quiet
|
||||
"failed", "missed" -> Tone.Bad
|
||||
"waiting", "running" -> Tone.Waiting
|
||||
else -> Tone.Neutral
|
||||
}
|
||||
|
||||
/**
|
||||
* A moment the server named (ISO 8601 with an offset), where the phone is, short:
|
||||
* "Tue 10 Mar, 08:00". Null for nothing or for something that is not a time.
|
||||
*/
|
||||
fun moment(iso: String?, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): String? {
|
||||
if (iso.isNullOrBlank()) return null
|
||||
val at = runCatching { OffsetDateTime.parse(iso).atZoneSameInstant(zone) }.getOrNull() ?: return null
|
||||
return DateTimeFormatter.ofPattern("EEE d MMM, HH:mm", locale).format(at)
|
||||
}
|
||||
|
||||
/** At most [n] upcoming runs, as the preview lists them; unreadable ones are left out. */
|
||||
fun upcoming(runs: List<String>, n: Int = 5, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> =
|
||||
runs.mapNotNull { moment(it, zone, locale) }.take(n)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,169 @@
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
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.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CheckboxDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
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.LifecycleResumeEffect
|
||||
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.ApiException
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.SchedulingModels
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
data class ModelsState(val models: SchedulingModels? = null, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class SchedulingModelsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ModelsState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private suspend fun api() = getApplication<Application>().lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val models = api().schedulingModels()
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Tick or untick one; the server keeps the person's narrowing and answers the whole list. */
|
||||
fun toggle(model: SchedulingModel) {
|
||||
val now = _state.value.models ?: return
|
||||
val chosen = SchedulingLogic.toggled(now.models, model.id) ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val saved = api().chooseSchedulingModels(chosen)
|
||||
_state.update { it.copy(models = saved, error = null) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The narrowing a tick makes, pure so it can be tested. */
|
||||
object SchedulingLogic {
|
||||
/**
|
||||
* The ids to send after ticking or unticking [id]: in the list's order; empty when every
|
||||
* one is ticked (the server's "no narrowing"). Null when it would untick the last one --
|
||||
* scheduled work needs at least one model.
|
||||
*/
|
||||
fun toggled(models: List<SchedulingModel>, id: String): List<String>? {
|
||||
val chosen = models.filter { if (it.id == id) !it.chosen else it.chosen }.map { it.id }
|
||||
return when {
|
||||
chosen.isEmpty() -> null
|
||||
chosen.size == models.size -> emptyList()
|
||||
else -> chosen
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SchedulingModelsScreen(onBack: () -> Unit, model: SchedulingModelsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
SchedulingModelsContent(state, onBack = onBack, onToggle = model::toggle, onRetry = model::load)
|
||||
}
|
||||
|
||||
/**
|
||||
* The models scheduled tasks run on, in the order they are tried -- each with whether it is free
|
||||
* now or busy (the server's words) -- and a tick for the person's own narrowing of the list.
|
||||
*/
|
||||
@Composable
|
||||
fun SchedulingModelsContent(state: ModelsState, onBack: () -> Unit = {}, onToggle: (SchedulingModel) -> Unit = {}, onRetry: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
val models = state.models?.models.orEmpty()
|
||||
Scaffold(containerColor = palette.bg, topBar = { BackBar(stringResource(R.string.schedule_models), onBack) }) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = onRetry, modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
if (models.isEmpty() && state.error != null) {
|
||||
Message(state.error, retry = onRetry)
|
||||
return@PullToRefreshBox
|
||||
}
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 32.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.schedule_models_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 4.dp, end = 4.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } }
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModelRow(model: SchedulingModel, onToggle: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onToggle,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 64.dp).padding(start = 4.dp, end = 16.dp, top = 8.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Checkbox(
|
||||
checked = model.chosen,
|
||||
onCheckedChange = { onToggle() },
|
||||
colors = CheckboxDefaults.colors(checkedColor = palette.accent, checkmarkColor = palette.accentInk, uncheckedColor = palette.inkMuted),
|
||||
)
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(model.name.ifBlank { model.id }, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val (line, tone) = if (model.free) {
|
||||
stringResource(R.string.model_free) to palette.success
|
||||
} else {
|
||||
stringResource(R.string.model_busy, model.busy.orEmpty()).trimEnd(' ', ':') to palette.inkMuted
|
||||
}
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -23,6 +23,20 @@ private fun scheme(p: Palette, dark: Boolean): ColorScheme {
|
||||
onPrimaryContainer = p.ink,
|
||||
secondary = p.leaf,
|
||||
onSecondary = p.inkInverse,
|
||||
// Every slot Material reads for a tonal fill, a selected chip, a slider's track or a
|
||||
// snackbar is a token too: otherwise Material's own purple shows through.
|
||||
secondaryContainer = p.accentSoft,
|
||||
onSecondaryContainer = p.ink,
|
||||
tertiary = p.leaf,
|
||||
onTertiary = p.inkInverse,
|
||||
tertiaryContainer = p.successSoft,
|
||||
onTertiaryContainer = p.ink,
|
||||
surfaceTint = p.accent,
|
||||
inverseSurface = p.ink,
|
||||
inverseOnSurface = p.bg,
|
||||
inversePrimary = p.accentHover,
|
||||
surfaceBright = p.surfaceRaised,
|
||||
surfaceDim = p.bgSunken,
|
||||
background = p.bg,
|
||||
onBackground = p.ink,
|
||||
surface = p.surface,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.5. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.14. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -38,13 +38,16 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
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.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
@@ -61,7 +64,11 @@ import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.highlight
|
||||
import eu.llembas.android.ui.highlights
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
@@ -74,15 +81,15 @@ private const val MARKDOWN_MAX_CHARS = 200_000
|
||||
private sealed interface Loaded {
|
||||
data object Loading : Loaded
|
||||
|
||||
/** [kind]: what the server said the file is, when it is only known once it came. */
|
||||
data class Text(val text: String, val kind: String? = null) : Loaded
|
||||
/** [kind], [language]: what the server said the file is, when it is only known once it came. */
|
||||
data class Text(val text: String, val kind: String? = null, val language: String? = null) : Loaded
|
||||
|
||||
/** [unavailable]: this server has no door for the app to read the file through. */
|
||||
data class Failed(val message: String, val unavailable: Boolean = false) : Loaded
|
||||
}
|
||||
|
||||
/** What the viewer's title and body need to know before the text comes. */
|
||||
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String)
|
||||
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String, val language: String = "")
|
||||
|
||||
/**
|
||||
* What a `show` card opens: the file, full screen, read-only, as the chat sees it now.
|
||||
@@ -97,7 +104,7 @@ private data class Viewed(val name: String, val path: String, val line: Int, val
|
||||
@Composable
|
||||
fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(show.name, show.path, show.line, show.viewKind),
|
||||
file = Viewed(show.name, show.path, show.line, show.viewKind, show.language),
|
||||
key = chatId to show,
|
||||
webUrl = { it.webViewer(chatId, show) },
|
||||
load = { api, _ -> Loaded.Text(api.shownText(chatId, show)) },
|
||||
@@ -120,7 +127,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit) {
|
||||
val file = api.fileContent(path)
|
||||
val withheld = file.withheld
|
||||
when {
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind)
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind, file.language)
|
||||
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
|
||||
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
|
||||
@@ -217,15 +224,20 @@ private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load:
|
||||
}
|
||||
}
|
||||
|
||||
is Loaded.Text -> Body(now.kind ?: file.kind, file.line, now.text)
|
||||
is Loaded.Text -> FileBody(now.kind ?: file.kind, now.language ?: file.language, file.line, now.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file's text as the viewer draws it, from these alone (what the screenshot tests draw):
|
||||
* Markdown rendered, anything else as numbered lines -- code in the theme's colours when its
|
||||
* [language] is one [highlight] reads. Read-only either way.
|
||||
*/
|
||||
@Composable
|
||||
private fun Body(kind: String, line: Int, text: String) {
|
||||
fun FileBody(kind: String, language: String, line: Int, text: String) {
|
||||
val palette = LocalPalette.current
|
||||
if (kind == "markdown" && text.length <= MARKDOWN_MAX_CHARS) {
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
|
||||
@@ -247,7 +259,7 @@ private fun Body(kind: String, line: Int, text: String) {
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
Lines(text, line)
|
||||
Lines(text, line, language)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -258,12 +270,14 @@ private fun Body(kind: String, line: Int, text: String) {
|
||||
* text rather than under the numbers.
|
||||
*/
|
||||
@Composable
|
||||
private fun Lines(text: String, line: Int) {
|
||||
private fun Lines(text: String, line: Int, language: String) {
|
||||
val palette = LocalPalette.current
|
||||
val rows = remember(text) {
|
||||
val split = text.split('\n')
|
||||
if (split.size > 1 && split.last().isEmpty()) split.dropLast(1) else split
|
||||
val plain = remember(text) { linesOf(AnnotatedString(text)) }
|
||||
// Highlighted off the main thread: a long file shows plain for a moment, then in colour.
|
||||
val coloured by produceState<List<AnnotatedString>?>(null, text, language, palette) {
|
||||
if (highlights(language)) value = withContext(Dispatchers.Default) { linesOf(highlight(text, language, palette)) }
|
||||
}
|
||||
val rows = coloured ?: if (LocalInspectionMode.current && highlights(language)) linesOf(highlight(text, language, palette)) else plain
|
||||
val style = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
@@ -286,12 +300,27 @@ private fun Lines(text: String, line: Int) {
|
||||
) {
|
||||
Text((i + 1).toString(), style = style.copy(color = palette.inkFaint), textAlign = TextAlign.End, modifier = Modifier.width(gutter))
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(row.ifEmpty { " " }, style = style, modifier = Modifier.weight(1f))
|
||||
Text(if (row.isEmpty()) AnnotatedString(" ") else row, style = style, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** [text]'s lines, each with its own spans; a final newline makes no empty last line. */
|
||||
private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
|
||||
val out = mutableListOf<AnnotatedString>()
|
||||
var start = 0
|
||||
while (true) {
|
||||
val end = text.text.indexOf('\n', start)
|
||||
if (end < 0) {
|
||||
if (start < text.length || out.isEmpty()) out += text.subSequence(start, text.length)
|
||||
return out
|
||||
}
|
||||
out += text.subSequence(start, end)
|
||||
start = end + 1
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
package eu.llembas.android.update
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Notification
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.LembasApp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AppsInfo
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import okhttp3.Request
|
||||
|
||||
/** A version as the releases name it: `1.2.3`, or `1.2.3-beta.4`, which sorts below `1.2.3`. */
|
||||
data class AppVersion(val major: Int, val minor: Int, val patch: Int, val beta: Int?) : Comparable<AppVersion> {
|
||||
val isBeta: Boolean get() = beta != null
|
||||
|
||||
override fun compareTo(other: AppVersion): Int = compareValuesBy(
|
||||
this,
|
||||
other,
|
||||
{ it.major },
|
||||
{ it.minor },
|
||||
{ it.patch },
|
||||
// A release sorts above every beta of itself.
|
||||
{ it.beta ?: Int.MAX_VALUE },
|
||||
)
|
||||
|
||||
override fun toString(): String = "$major.$minor.$patch" + (beta?.let { "-beta.$it" } ?: "")
|
||||
|
||||
companion object {
|
||||
private val SHAPE = Regex("""^v?(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?$""")
|
||||
|
||||
/**
|
||||
* A tag or a version name; a test build's `-debug…` is left off first. Anything else
|
||||
* (`-rc.1`, a typo) is not a version this check knows, and is never offered.
|
||||
*/
|
||||
fun parse(text: String): AppVersion? {
|
||||
val match = SHAPE.matchEntire(text.trim().substringBefore("-debug")) ?: return null
|
||||
val (a, b, c, beta) = match.destructured
|
||||
return AppVersion(a.toInt(), b.toInt(), c.toInt(), beta.takeIf { it.isNotEmpty() }?.toInt())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One of GitHub's releases, as far as the check needs it. */
|
||||
@Serializable
|
||||
data class PublicRelease(
|
||||
@SerialName("tag_name") val tag: String,
|
||||
val prerelease: Boolean = false,
|
||||
val draft: Boolean = false,
|
||||
@SerialName("html_url") val page: String = "",
|
||||
)
|
||||
|
||||
/** A newer release to tell the person about: its version and the page its APKs are on. */
|
||||
data class UpdateOffer(val version: AppVersion, val page: String)
|
||||
|
||||
/** What a check found. */
|
||||
sealed interface UpdateResult {
|
||||
data class Newer(val offer: UpdateOffer) : UpdateResult
|
||||
|
||||
data object Current : UpdateResult
|
||||
|
||||
data object Unreachable : UpdateResult
|
||||
}
|
||||
|
||||
/**
|
||||
* The update check: the release the instance recommends (`GET /api/v2/apps`), which knows what
|
||||
* speaks its API; from a server without that, the public releases of the app on GitHub, read
|
||||
* over plain HTTPS -- no
|
||||
* Google service, no account, nothing sent but the request itself. It runs when the app starts,
|
||||
* at most once a day and only while Settings › About › *Look for new versions* is on (on by
|
||||
* default in a beta, off in a release), and when the person taps *Check for an update*. A newer
|
||||
* release becomes a notification that opens its page, where the APKs are; installing stays the
|
||||
* person's step (or F-Droid's, or Obtainium's).
|
||||
*
|
||||
* Betas are offered to a beta, or to anyone who turned *Include betas* on.
|
||||
*/
|
||||
class ReleaseCheck(private val context: Context) {
|
||||
suspend fun check(): UpdateResult = withContext(Dispatchers.IO) {
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val installed = AppVersion.parse(BuildConfig.VERSION_NAME) ?: return@withContext UpdateResult.Current
|
||||
// The instance first: it knows which release speaks its /api/v2. Only a server without
|
||||
// the route (or none signed in, or none reachable) leaves it to GitHub's list.
|
||||
val server = runCatching { context.lembas.instances.client()?.apps() }.getOrNull()
|
||||
if (server != null) {
|
||||
return@withContext recommended(server, installed, prefs.offersBetas(installed.isBeta))
|
||||
?.let { UpdateResult.Newer(it) } ?: UpdateResult.Current
|
||||
}
|
||||
try {
|
||||
val releases = SharedHttp.newCall(
|
||||
Request.Builder().url(RELEASES).header("Accept", "application/vnd.github+json").build(),
|
||||
).await().use {
|
||||
if (!it.isSuccessful) return@withContext UpdateResult.Unreachable
|
||||
LembasJson.decodeFromString(ListSerializer(PublicRelease.serializer()), it.body!!.string())
|
||||
}
|
||||
newest(releases, installed, prefs.offersBetas(installed.isBeta))
|
||||
?.let { UpdateResult.Newer(it) } ?: UpdateResult.Current
|
||||
} catch (e: Exception) {
|
||||
UpdateResult.Unreachable
|
||||
}
|
||||
}
|
||||
|
||||
/** On start: once a day at most, when the setting is on; a release is announced once. */
|
||||
suspend fun daily(now: Long = System.currentTimeMillis()) {
|
||||
val store = context.lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
val installed = AppVersion.parse(BuildConfig.VERSION_NAME) ?: return
|
||||
if (!prefs.checksUpdates(installed.isBeta) || !due(prefs.updateCheckedAt, now)) return
|
||||
val found = check()
|
||||
if (found == UpdateResult.Unreachable) return
|
||||
store.savePrefs { it.copy(updateCheckedAt = now) }
|
||||
val offer = (found as? UpdateResult.Newer)?.offer ?: return
|
||||
if (offer.version.toString() == prefs.updateNotified) return
|
||||
notify(offer)
|
||||
store.savePrefs { it.copy(updateNotified = offer.version.toString()) }
|
||||
}
|
||||
|
||||
fun notify(offer: UpdateOffer) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
val page = PendingIntent.getActivity(
|
||||
context,
|
||||
NOTIFICATION,
|
||||
open(offer.page),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
val text = context.getString(R.string.update_notice_text)
|
||||
val notice = NotificationCompat.Builder(context, LembasApp.CHANNEL_UPDATES)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.update_notice_title, offer.version.toString()))
|
||||
.setContentText(text)
|
||||
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
|
||||
.setContentIntent(page)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(Notification.CATEGORY_RECOMMENDATION)
|
||||
// Nothing from the account: the app's version is fine on a locked screen.
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.build()
|
||||
NotificationManagerCompat.from(context).notify(NOTIFICATION, notice)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val REPOSITORY = "https://github.com/LLeMbas/LLeMbas-Android"
|
||||
const val RELEASES = "https://api.github.com/repos/LLeMbas/LLeMbas-Android/releases?per_page=30"
|
||||
private const val DAY_MS = 24L * 60 * 60 * 1000
|
||||
private const val NOTIFICATION = 0x11e4
|
||||
|
||||
/** The newest release later than [installed] that may be offered; drafts never are. */
|
||||
fun newest(releases: List<PublicRelease>, installed: AppVersion, betas: Boolean): UpdateOffer? = releases
|
||||
.asSequence()
|
||||
.filter { !it.draft }
|
||||
.mapNotNull { r -> AppVersion.parse(r.tag)?.let { it to r } }
|
||||
// A pre-release is a beta whatever its tag says, and a beta tag is one whatever GitHub says.
|
||||
.filter { (v, r) -> betas || (!v.isBeta && !r.prerelease) }
|
||||
.filter { (v, _) -> v > installed }
|
||||
.maxByOrNull { (v, _) -> v }
|
||||
?.let { (v, r) -> UpdateOffer(v, r.page.ifBlank { "$REPOSITORY/releases/tag/${r.tag}" }) }
|
||||
|
||||
/**
|
||||
* The server's recommendation, when it is newer than [installed] and may be offered: a
|
||||
* beta only with [betas]. None recommended (null) is no offer -- the server knows no
|
||||
* Android release that speaks its API, so none is pushed.
|
||||
*/
|
||||
fun recommended(info: AppsInfo, installed: AppVersion, betas: Boolean): UpdateOffer? {
|
||||
val app = info.android ?: return null
|
||||
val version = AppVersion.parse(app.version) ?: return null
|
||||
if (version.isBeta && !betas) return null
|
||||
if (version <= installed) return null
|
||||
val tag = app.tag.ifBlank { "v$version" }
|
||||
return UpdateOffer(version, app.page.takeIf { it.startsWith("https://") } ?: "$REPOSITORY/releases/tag/$tag")
|
||||
}
|
||||
|
||||
fun due(last: Long, now: Long): Boolean = last <= 0 || now - last >= DAY_MS || now < last
|
||||
|
||||
fun open(url: String): Intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
}
|
||||
|
||||
/** *Look for new versions*: as chosen, else on in a beta and off in a release. */
|
||||
fun Prefs.checksUpdates(installedIsBeta: Boolean): Boolean = updateCheck ?: installedIsBeta
|
||||
|
||||
/** *Include betas*: as chosen, else on in a beta and off in a release. */
|
||||
fun Prefs.offersBetas(installedIsBeta: Boolean): Boolean = updateBetas ?: installedIsBeta
|
||||
@@ -10,9 +10,12 @@ import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AppRelease
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.Serializable
|
||||
@@ -20,9 +23,34 @@ 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). */
|
||||
/** One APK of a release: where it is and its SHA-256. */
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "")
|
||||
data class LatestFile(val url: String, val sha256: String)
|
||||
|
||||
/**
|
||||
* What llembas.eu says the newest release is (`site/android/latest.json`, written at release):
|
||||
* the standard APK as [url] and [sha256], and the `notifications` build's (the same app with the
|
||||
* notification listener) as [notifications] when the release has one.
|
||||
*/
|
||||
@Serializable
|
||||
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "", val notifications: LatestFile? = null) {
|
||||
/**
|
||||
* The file this build updates itself to: its own kind, never the other. A `notifications`
|
||||
* build that installed the standard APK would lose its listener without a word (same id,
|
||||
* same key: Android takes it), so without its own file it installs nothing.
|
||||
*/
|
||||
fun fileFor(notificationsBuild: Boolean): LatestFile? = if (notificationsBuild) notifications else LatestFile(url, sha256)
|
||||
|
||||
/**
|
||||
* The same, with what the instance says of the release it recommends (`GET /api/v2/apps`,
|
||||
* its entry's `notifications` build) for a manifest that names no notifications file -- but
|
||||
* only when both speak of the same version, and the address is https.
|
||||
*/
|
||||
fun fileFor(notificationsBuild: Boolean, recommended: AppRelease?): LatestFile? = fileFor(notificationsBuild)
|
||||
?: recommended?.takeIf { notificationsBuild && it.version == version }?.notifications
|
||||
?.takeIf { it.url.startsWith("https://") && it.sha256.isNotBlank() }
|
||||
?.let { LatestFile(it.url, it.sha256) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The `full` build updates itself, as LLeMbas Desktop does: the manifest on the website names
|
||||
@@ -47,12 +75,20 @@ class Updater(private val context: Context) {
|
||||
)
|
||||
return@withContext context.getString(R.string.update_allow_installs)
|
||||
}
|
||||
// Its own kind: from the manifest, else from the instance's recommendation of the same release.
|
||||
val recommended = if (NotificationAccess.AVAILABLE && latest.notifications == null) {
|
||||
runCatching { context.lembas.instances.client()?.apps()?.android }.getOrNull()
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val file = latest.fileFor(NotificationAccess.AVAILABLE, recommended)
|
||||
?: return@withContext context.getString(R.string.update_notifications_manual)
|
||||
val apk = File(context.cacheDir, "update.apk")
|
||||
SharedHttp.newCall(Request.Builder().url(latest.url).build()).await().use { response ->
|
||||
SharedHttp.newCall(Request.Builder().url(file.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()) {
|
||||
if (sha256(apk) != file.sha256.lowercase()) {
|
||||
apk.delete()
|
||||
return@withContext context.getString(R.string.update_bad_file)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.content.Context
|
||||
import eu.llembas.android.R
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
/** One word of a wake phrase: its [id], how it is written for the person, and its spelling in the model's [pieces]. */
|
||||
data class WakeWord(val id: String, val words: String, val pieces: String)
|
||||
|
||||
/**
|
||||
* A wake phrase: a greeting and a name ("Hey Assistant"). What the person says ([words]), the
|
||||
* engine's spelling of it ([tokens], the model's BPE pieces -- generated with its `bpe.model` by
|
||||
* `scripts/gen-wake-phrases.py`, since the phone has no tokenizer), and the [id] Settings keeps.
|
||||
*
|
||||
* Only words from [WakeWords] can be chosen: an open-vocabulary spotter hears any phrase it can
|
||||
* spell, but one it was never trained to hear (a made-up name) has to be repeated until it lands,
|
||||
* and a free text box would invite one that fires on every other sentence. English only: the
|
||||
* model is trained on English speech.
|
||||
*/
|
||||
data class WakePhrase(val greeting: WakeWord, val name: WakeWord) {
|
||||
val id: String get() = "${greeting.id}_${name.id}"
|
||||
val words: String get() = "${greeting.words} ${name.words}"
|
||||
val tokens: String get() = "${greeting.pieces} ${name.pieces}"
|
||||
}
|
||||
|
||||
object WakePhrases {
|
||||
/** "Hey Assistant". */
|
||||
val default: WakePhrase = WakePhrase(WakeWords.greetings.first { it.id == "hey" }, WakeWords.names.first { it.id == "assistant" })
|
||||
|
||||
val all: List<WakePhrase> = WakeWords.greetings.flatMap { greeting -> WakeWords.names.map { WakePhrase(greeting, it) } }
|
||||
|
||||
/**
|
||||
* The phrase Settings saved as [id] (`greeting_name`). An id that is no longer a phrase --
|
||||
* the "Lembas" ones of the first wake word, which the model could not hear -- is the default.
|
||||
*/
|
||||
fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default
|
||||
}
|
||||
|
||||
/**
|
||||
* How easily the phrase is taken as heard: Settings › Wake word › Sensitivity.
|
||||
*
|
||||
* The engine has two numbers per keyword (sherpa-onnx's keyword-spotting documentation): a
|
||||
* boosting score that keeps the phrase's path alive in the search ([boost], larger is easier),
|
||||
* and a trigger threshold, the least probability the heard pieces must reach ([threshold], 0 to
|
||||
* 1, lower is easier). Normal is the engine's own default threshold with the boost its
|
||||
* documentation uses for a two-word phrase; Low takes that documentation's stricter example
|
||||
* (0.35), High goes as far below the default as Low goes above it. Starting values: nobody has
|
||||
* measured them on a phone yet.
|
||||
*/
|
||||
enum class WakeSensitivity(val id: String, val boost: Float, val threshold: Float) {
|
||||
Low("low", 1.0f, 0.35f),
|
||||
Normal("normal", 1.5f, 0.25f),
|
||||
High("high", 2.0f, 0.15f),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun byId(id: String): WakeSensitivity = entries.firstOrNull { it.id == id } ?: Normal
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine, as the service sees it: 16 kHz mono samples in, the phrase out when it was heard.
|
||||
* Everything happens on the phone; [accept] neither records nor sends anything.
|
||||
*/
|
||||
interface WakeDetector {
|
||||
/** Feed [samples] (-1..1); true when the wake word ended in them. */
|
||||
fun accept(samples: FloatArray): Boolean
|
||||
|
||||
fun release()
|
||||
}
|
||||
|
||||
/** The microphone, as the listener sees it: 16 kHz mono samples, already recording when it is made. */
|
||||
interface WakeMicrophone {
|
||||
/** Fill [into]; how many samples were read, or a negative number when the microphone failed. */
|
||||
fun read(into: ShortArray): Int
|
||||
|
||||
fun close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
|
||||
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
|
||||
* can overlap for a moment when one hands over to the other.
|
||||
*
|
||||
* The wake word's own hold is apart from the count: when the word is heard the microphone is
|
||||
* the sheet's for a few seconds ([holdFor]), whether or not a sheet then says it is up. It ends
|
||||
* by itself on a scope that outlives the service, so a service that is destroyed in those
|
||||
* seconds cannot leave the wake word "paused while the assistant is open" for good.
|
||||
*/
|
||||
object AssistPresence {
|
||||
private val sheets = MutableStateFlow(0)
|
||||
private val held = MutableStateFlow(0L)
|
||||
private val holds = AtomicLong(0)
|
||||
private val _open = MutableStateFlow(0)
|
||||
val open: StateFlow<Int> = _open.asStateFlow()
|
||||
|
||||
private val process = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
private fun count() {
|
||||
_open.value = sheets.value + if (held.value != 0L) 1 else 0
|
||||
}
|
||||
|
||||
fun shown() {
|
||||
sheets.update { it + 1 }
|
||||
count()
|
||||
}
|
||||
|
||||
fun hidden() {
|
||||
sheets.update { (it - 1).coerceAtLeast(0) }
|
||||
count()
|
||||
}
|
||||
|
||||
/** The word was heard: the microphone is the sheet's for [millis], then the hold lets go by itself. */
|
||||
fun holdFor(millis: Long, scope: CoroutineScope = process) {
|
||||
// Each hold has a number of its own, never used twice, so an old one cannot end a newer one.
|
||||
val mine = holds.incrementAndGet()
|
||||
held.value = mine
|
||||
count()
|
||||
scope.launch {
|
||||
try {
|
||||
delay(millis)
|
||||
} finally {
|
||||
// Only the newest hold lets go; an older one that ends later changes nothing.
|
||||
if (held.compareAndSet(mine, 0L)) count()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** No hold is left standing: the wake-word service starts from what the sheets say alone. */
|
||||
fun release() {
|
||||
held.value = 0L
|
||||
count()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
|
||||
object AppVisibility {
|
||||
private val started = AtomicInteger(0)
|
||||
val visible: Boolean get() = started.get() > 0
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Why listening for the wake word is paused, or [None]: what the notification and Settings say.
|
||||
* [Silent] is the one the listener finds out itself: the microphone is open but gives no sound at
|
||||
* all, which is what Android hands a background app while a call or another recorder has it, or
|
||||
* while the phone's microphone switch is off.
|
||||
*/
|
||||
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone, Silent }
|
||||
|
||||
/**
|
||||
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
|
||||
* microphone), never in battery saver (the person asked the phone to spare power), and -- when
|
||||
* Settings says so, the default -- only while the screen is on.
|
||||
*/
|
||||
fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, sheetOpen: Boolean, micAllowed: Boolean): WakePause = when {
|
||||
!micAllowed -> WakePause.NoMicrophone
|
||||
sheetOpen -> WakePause.Assistant
|
||||
batterySaver -> WakePause.BatterySaver
|
||||
screenOnly && !screenOn -> WakePause.ScreenOff
|
||||
else -> WakePause.None
|
||||
}
|
||||
|
||||
/** What went wrong: this build has no engine, the model's files, the engine itself, or the microphone. */
|
||||
enum class WakeFailure { NoEngine, Model, Engine, Microphone }
|
||||
|
||||
/** A failure with its kind, so the notification and Settings can say it in plain words. */
|
||||
class WakeError(val why: WakeFailure, cause: Throwable? = null, message: String? = cause?.message) : Exception(message, cause) {
|
||||
/** The technical half, for Settings and the log: the exception's name and what it said. */
|
||||
val detail: String
|
||||
get() = listOfNotNull(cause?.javaClass?.simpleName, message?.takeIf { it.isNotBlank() }).joinToString(": ").take(DETAIL_MAX)
|
||||
|
||||
private companion object {
|
||||
const val DETAIL_MAX = 200
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the wake word is doing, the one truth the service, its notification and Settings all read
|
||||
* ([WakeStatus.state]). [Failed] carries the plain reason and the technical [Failed.detail];
|
||||
* nothing here is ever a guess from the settings alone.
|
||||
*/
|
||||
sealed interface WakeState {
|
||||
/** Not running: turned off, or the phone stopped the service. */
|
||||
data object Off : WakeState
|
||||
|
||||
/** Running, loading the engine. */
|
||||
data object Starting : WakeState
|
||||
|
||||
/** The microphone is open and the engine hears it, for these words. */
|
||||
data class Listening(val phrase: String) : WakeState
|
||||
|
||||
data class Paused(val why: WakePause) : WakeState
|
||||
|
||||
data class Failed(val why: WakeFailure, val detail: String = "") : WakeState
|
||||
}
|
||||
|
||||
/**
|
||||
* "Test the wake word" (Settings): until [until] (the phone's elapsed time, in ms) a heard phrase
|
||||
* is counted in [heard] instead of opening the assistant. A deadline, not a switch, so a test
|
||||
* nobody ends cannot leave the wake word deaf.
|
||||
*/
|
||||
data class WakeTrial(val until: Long = 0, val heard: Int = 0)
|
||||
|
||||
/**
|
||||
* The wake word's state for the whole process: written by the service, read by everything else.
|
||||
*
|
||||
* A service instance writes with the token [begin] gave it, and only the newest token's writes
|
||||
* count: an old instance on its way out (its loop ending after Settings turned the wake word off
|
||||
* and on again) cannot write its "off" over the new one's state.
|
||||
*/
|
||||
object WakeStatus {
|
||||
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
|
||||
val state: StateFlow<WakeState> = _state.asStateFlow()
|
||||
|
||||
private val _trial = MutableStateFlow(WakeTrial())
|
||||
val trial: StateFlow<WakeTrial> = _trial.asStateFlow()
|
||||
|
||||
private val _retries = MutableStateFlow(0)
|
||||
|
||||
/** Counts up each time somebody asks for a retry now ([retryNow]). */
|
||||
val retries: StateFlow<Int> = _retries.asStateFlow()
|
||||
|
||||
private val generation = AtomicInteger(0)
|
||||
|
||||
/** A new writer takes over: its token, which makes every older one's writes count for nothing. */
|
||||
fun begin(): Int = generation.incrementAndGet()
|
||||
|
||||
/** [now], if [token] is still the newest writer's. */
|
||||
fun set(token: Int, now: WakeState) {
|
||||
synchronized(generation) {
|
||||
if (token == generation.get()) _state.value = now
|
||||
}
|
||||
}
|
||||
|
||||
/** [now], said by the app itself, outside any service instance: not started and why, turned off. */
|
||||
fun set(now: WakeState) {
|
||||
synchronized(generation) { _state.value = now }
|
||||
}
|
||||
|
||||
/** Try again now, instead of when the back-off says: the person tapped the failure. */
|
||||
fun retryNow() = _retries.update { it + 1 }
|
||||
|
||||
/** Start a test at [now]: the next [TRIAL_MS] of heard phrases are counted, not acted on. */
|
||||
fun startTrial(now: Long) {
|
||||
_trial.value = WakeTrial(until = now + TRIAL_MS)
|
||||
}
|
||||
|
||||
/** The phrase was heard at [now]: true when a test took it, so the assistant stays shut. */
|
||||
fun heardInTrial(now: Long): Boolean {
|
||||
var taken = false
|
||||
_trial.update { trial ->
|
||||
taken = now < trial.until
|
||||
if (taken) trial.copy(heard = trial.heard + 1) else trial
|
||||
}
|
||||
return taken
|
||||
}
|
||||
|
||||
const val TRIAL_MS = 10_000L
|
||||
}
|
||||
|
||||
/**
|
||||
* One [attempt] in plain words, a line each: when and for which phrase; what was tried and how it
|
||||
* went (Android's own words where it refused); what was done instead; and, where the assistant
|
||||
* could not be used, what Android had said of it -- whether LLeMbas held the role, and when the
|
||||
* service was connected and disconnected in this run of the app.
|
||||
*/
|
||||
fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> {
|
||||
fun time(at: Long): String = DateTimeFormatter.ofPattern("EEE d MMM, HH:mm:ss", locale).format(Instant.ofEpochMilli(at).atZone(zone))
|
||||
val lines = mutableListOf("${time(attempt.at)} · “${attempt.phrase}”")
|
||||
lines += when (attempt.outcome) {
|
||||
WakeAttempt.OUT_OPENED -> context.getString(R.string.wake_out_opened)
|
||||
WakeAttempt.OUT_TESTED -> context.getString(R.string.wake_out_tested)
|
||||
WakeAttempt.OUT_NO_SHEET -> context.getString(R.string.wake_out_no_sheet)
|
||||
WakeAttempt.OUT_REFUSED -> context.getString(R.string.wake_out_refused, attempt.detail)
|
||||
else -> context.getString(R.string.wake_out_not_connected)
|
||||
}
|
||||
when (attempt.fallback) {
|
||||
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
|
||||
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
|
||||
}
|
||||
if (attempt.outcome == WakeAttempt.OUT_TESTED) return lines
|
||||
if (attempt.sheetMs >= 0) lines += context.getString(R.string.wake_sheet_ms, attempt.sheetMs.toString())
|
||||
if (attempt.outcome == WakeAttempt.OUT_OPENED) return lines
|
||||
// Why the assistant's own way was not there, from what Android itself said at that moment.
|
||||
lines += when {
|
||||
!attempt.assistant -> context.getString(R.string.wake_role_not_held)
|
||||
!attempt.recognizers -> context.getString(R.string.wake_no_recognizers)
|
||||
!attempt.active -> context.getString(R.string.wake_not_active)
|
||||
else -> context.getString(R.string.wake_role_held)
|
||||
}
|
||||
if (attempt.waited) lines += context.getString(R.string.wake_waited)
|
||||
if (attempt.showFailed) lines += context.getString(R.string.wake_show_failed)
|
||||
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
|
||||
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
|
||||
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
|
||||
// The rest as it was noted, for whoever looks for the cause: names and values, not a sentence.
|
||||
lines += listOf(
|
||||
"screen=${if (attempt.screenOn) "on" else "off"}",
|
||||
"locked=${attempt.locked}",
|
||||
"visible=${attempt.visible}",
|
||||
"created=${if (attempt.createdAt == 0L) "-" else time(attempt.createdAt)}",
|
||||
"destroyed=${if (attempt.destroyedAt == 0L) "-" else time(attempt.destroyedAt)}",
|
||||
"prepared=${attempt.prepared}",
|
||||
).joinToString(" ")
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* What the service's notification says the moment Android starts it (again): what is true --
|
||||
* [current], while its loop is [running]; "starting" for a service that has only just begun.
|
||||
* Never a phrase by default.
|
||||
*/
|
||||
fun wakeStateAtStart(running: Boolean, current: WakeState): WakeState = if (running && current != WakeState.Off) current else WakeState.Starting
|
||||
|
||||
/**
|
||||
* [state] in plain words: the notification's title and Settings' line. A failure names what
|
||||
* failed and that it is tried again; it never claims to listen while it does not.
|
||||
*/
|
||||
fun wakeTitle(context: Context, state: WakeState): String = when (state) {
|
||||
WakeState.Off -> context.getString(R.string.wake_off)
|
||||
|
||||
WakeState.Starting -> context.getString(R.string.wake_starting)
|
||||
|
||||
is WakeState.Listening -> context.getString(R.string.wake_listening_for, state.phrase)
|
||||
|
||||
is WakeState.Paused -> context.getString(
|
||||
when (state.why) {
|
||||
WakePause.None -> R.string.wake_starting
|
||||
WakePause.ScreenOff -> R.string.wake_paused_screen
|
||||
WakePause.BatterySaver -> R.string.wake_paused_battery
|
||||
WakePause.Assistant -> R.string.wake_paused_assistant
|
||||
WakePause.NoMicrophone -> R.string.wake_paused_microphone
|
||||
WakePause.Silent -> R.string.wake_paused_silent
|
||||
},
|
||||
)
|
||||
|
||||
is WakeState.Failed -> context.getString(
|
||||
when (state.why) {
|
||||
WakeFailure.NoEngine -> R.string.wake_failed_no_engine
|
||||
WakeFailure.Model -> R.string.wake_failed_model
|
||||
WakeFailure.Engine -> R.string.wake_failed_engine
|
||||
WakeFailure.Microphone -> R.string.wake_failed_microphone
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** The notification's second line: the promise while it listens, else nothing more to say. */
|
||||
fun wakeLine(context: Context, state: WakeState): String? = when (state) {
|
||||
is WakeState.Listening -> context.getString(R.string.wake_notification_line)
|
||||
is WakeState.Failed -> if (state.why == WakeFailure.NoEngine) null else context.getString(R.string.wake_failed_line)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine's keywords file for [phrase]: its pieces, `:` the boosting score, `#` the trigger
|
||||
* threshold, then `@` and the id the engine answers with (sherpa-onnx's syntax; no space after
|
||||
* `:` or `#`). A phrase of fewer than five pieces is short enough to turn up inside other speech,
|
||||
* so it has to be a little surer ([SHORT_PHRASE_STRICTER]).
|
||||
*/
|
||||
fun wakeKeywords(phrase: WakePhrase, sensitivity: WakeSensitivity = WakeSensitivity.Normal): String {
|
||||
val short = phrase.tokens.split(' ').size < SHORT_PHRASE_PIECES
|
||||
val threshold = sensitivity.threshold + if (short) SHORT_PHRASE_STRICTER else 0f
|
||||
// Locale.ROOT: a decimal comma would not be a number to the engine.
|
||||
return String.format(Locale.ROOT, "%s :%.1f #%.2f @%s\n", phrase.tokens, sensitivity.boost, threshold, phrase.id)
|
||||
}
|
||||
|
||||
private const val SHORT_PHRASE_PIECES = 5
|
||||
private const val SHORT_PHRASE_STRICTER = 0.05f
|
||||
|
||||
/**
|
||||
* Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece
|
||||
* and its number per line): the engine ends the whole app on a piece it does not know, so it is
|
||||
* never handed one.
|
||||
*/
|
||||
fun checkKeywords(keywords: String, tokens: String) {
|
||||
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
|
||||
for (line in keywords.lineSequence().filter { it.isNotBlank() }) {
|
||||
val unknown = line.split(' ').filter { it.isNotEmpty() && it[0] !in ":#@" }.firstOrNull { it !in known }
|
||||
if (unknown != null) throw WakeError(WakeFailure.Engine, message = "the model has no piece \"$unknown\"")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's files, out of the APK's assets into [dir], where the engine reads them as files.
|
||||
* Copied by stream ([open] is `AssetManager.open`), so it works however the APK stores them, and
|
||||
* keyed by the assets' `version` (a hash of the pinned model, written by
|
||||
* `scripts/fetch-wakeword.py`): a new model replaces the old one, and a copy that was cut short
|
||||
* has no marker and is made again.
|
||||
*/
|
||||
fun unpackWakeModel(open: (String) -> InputStream, dir: File, files: List<String>) {
|
||||
val version = open("version").use { it.readBytes().decodeToString().trim() }
|
||||
val marker = File(dir, "version")
|
||||
if (marker.isFile && marker.readText() == version && files.all { File(dir, it).length() > 0 }) return
|
||||
if (!dir.isDirectory && !dir.mkdirs()) throw IOException("cannot make ${dir.name}")
|
||||
marker.delete()
|
||||
for (name in files) {
|
||||
val part = File(dir, "$name.part")
|
||||
open(name).use { input -> part.outputStream().use { input.copyTo(it) } }
|
||||
if (part.length() == 0L) throw IOException("$name is empty")
|
||||
val target = File(dir, name)
|
||||
target.delete()
|
||||
if (!part.renameTo(target)) throw IOException("cannot write $name")
|
||||
}
|
||||
marker.writeText(version)
|
||||
}
|
||||
|
||||
/** How long to wait before the next try after the [attempt]-th failure in a row: 2 s, 5 s, 15 s, 1 min, then every 5 min. */
|
||||
fun wakeBackoff(attempt: Int): Long = listOf(2_000L, 5_000L, 15_000L, 60_000L).getOrElse(attempt) { 300_000L }
|
||||
@@ -0,0 +1,207 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineDispatcher
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
|
||||
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
|
||||
|
||||
/**
|
||||
* The listening itself, apart from Android so it can be tested: follows the plans, keeps one
|
||||
* engine and one microphone, and says every change of state through [say].
|
||||
*
|
||||
* Nothing fails silently. An engine that does not load, a microphone that does not start or
|
||||
* stops giving samples: each is a [WakeState.Failed] with its reason, logged, and tried again
|
||||
* after [backoff]. And the engine is never released while a loop may still be feeding it: a new
|
||||
* plan first cancels the old loop and waits for it to end ([cancelAndJoin]), then the engine is
|
||||
* swapped, on the one coroutine that owns it.
|
||||
*/
|
||||
class WakeListener(
|
||||
private val say: (WakeState) -> Unit,
|
||||
private val engine: (keywords: String) -> WakeDetector,
|
||||
private val microphone: () -> WakeMicrophone,
|
||||
private val heard: suspend (WakePhrase) -> Unit,
|
||||
private val work: CoroutineDispatcher = Dispatchers.IO,
|
||||
private val backoff: (attempt: Int) -> Long = ::wakeBackoff,
|
||||
private val log: (String, Throwable) -> Unit = { _, _ -> },
|
||||
) {
|
||||
@Volatile private var detector: WakeDetector? = null
|
||||
|
||||
@Volatile private var detectorFor: String? = null
|
||||
|
||||
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
|
||||
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
|
||||
// Where a heard word is answered: beside the listening, so a pause does not cancel the answer.
|
||||
val answers = this
|
||||
var hearing: Job? = null
|
||||
try {
|
||||
plans.distinctUntilChanged().collect { plan ->
|
||||
hearing?.cancelAndJoin()
|
||||
hearing = null
|
||||
if (plan.pause != WakePause.None) {
|
||||
say(WakeState.Paused(plan.pause))
|
||||
} else {
|
||||
hearing = launch { hear(plan) { phrase -> answers.launch { heard(phrase) } } }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
withContext(NonCancellable) {
|
||||
hearing?.cancelAndJoin()
|
||||
release()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
runCatching { detector?.release() }
|
||||
detector = null
|
||||
detectorFor = null
|
||||
}
|
||||
|
||||
private val nudges = MutableStateFlow(0)
|
||||
|
||||
/** How many samples the last stretch of listening heard before it ended. */
|
||||
@Volatile private var listened = 0L
|
||||
|
||||
/** Try again now rather than when the back-off says: somebody asked. The count of failures starts over. */
|
||||
fun retryNow() = nudges.update { it + 1 }
|
||||
|
||||
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
|
||||
private suspend fun hear(plan: WakePlan, heardIt: (WakePhrase) -> Unit) {
|
||||
var failures = 0
|
||||
while (true) {
|
||||
try {
|
||||
listened = 0
|
||||
listen(plan)
|
||||
failures = 0
|
||||
// Handed to the caller's scope, not run here: answering the word usually pauses
|
||||
// the listening (the sheet takes the microphone), which cancels this very loop --
|
||||
// and must not cancel the answer with it.
|
||||
heardIt(plan.phrase)
|
||||
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
|
||||
delay(HEARD_REST_MS)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
log("wake word: ${e.why}: ${e.detail}", e)
|
||||
say(WakeState.Failed(e.why, e.detail))
|
||||
// A build without an engine does not grow one: nothing to try again.
|
||||
if (e.why == WakeFailure.NoEngine) return
|
||||
// It had been listening well for a while: this is a new trouble, not the old one again.
|
||||
if (listened >= STEADY_SAMPLES) failures = 0
|
||||
val seen = nudges.value
|
||||
val asked = withTimeoutOrNull(backoff(failures++)) { nudges.first { it != seen } } != null
|
||||
if (asked) failures = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One stretch of listening: returns when the word was heard, throws a [WakeError] when something failed. */
|
||||
private suspend fun listen(plan: WakePlan) {
|
||||
val spotter = engineFor(plan)
|
||||
try {
|
||||
withContext(work) {
|
||||
// Opened and closed on this one thread, so a cancellation cannot leave it open.
|
||||
val mic = try {
|
||||
microphone()
|
||||
} catch (e: Exception) {
|
||||
throw WakeError(WakeFailure.Microphone, e)
|
||||
}
|
||||
try {
|
||||
say(WakeState.Listening(plan.phrase.words))
|
||||
val chunk = ShortArray(CHUNK)
|
||||
var empty = 0
|
||||
var silent = 0
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val read = mic.read(chunk)
|
||||
if (read < 0) throw WakeError(WakeFailure.Microphone, message = "the microphone stopped (error $read)")
|
||||
if (read == 0) {
|
||||
if (++empty > EMPTY_READS) throw WakeError(WakeFailure.Microphone, message = "the microphone gives no samples")
|
||||
continue
|
||||
}
|
||||
empty = 0
|
||||
listened += read
|
||||
val samples = FloatArray(read)
|
||||
var sound = false
|
||||
for (i in 0 until read) {
|
||||
if (chunk[i] != 0.toShort()) sound = true
|
||||
samples[i] = chunk[i] / 32768f
|
||||
}
|
||||
// Exact silence for seconds is not a quiet room: Android gives a background
|
||||
// app zeros while another app has the microphone or its switch is off.
|
||||
if (sound) {
|
||||
if (silent >= SILENT_SAMPLES) say(WakeState.Listening(plan.phrase.words))
|
||||
silent = 0
|
||||
} else if (silent < SILENT_SAMPLES) {
|
||||
silent += read
|
||||
if (silent >= SILENT_SAMPLES) say(WakeState.Paused(WakePause.Silent))
|
||||
}
|
||||
if (spotter.accept(samples)) break
|
||||
}
|
||||
} finally {
|
||||
runCatching { mic.close() }
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
// The engine threw while hearing: it is not trusted again, a new one is made.
|
||||
release()
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
}
|
||||
}
|
||||
|
||||
/** The engine for [plan]'s keywords: the one there is, or a new one once the old is released. */
|
||||
private suspend fun engineFor(plan: WakePlan): WakeDetector {
|
||||
detector?.takeIf { detectorFor == plan.keywords }?.let { return it }
|
||||
release()
|
||||
say(WakeState.Starting)
|
||||
return try {
|
||||
// Kept the moment it exists, so a cancellation while it loads cannot lose it unreleased.
|
||||
withContext(work) {
|
||||
engine(plan.keywords).also {
|
||||
detector = it
|
||||
detectorFor = plan.keywords
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: WakeError) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
// A missing native library is an Error, not an Exception: it is a failure to show all the same.
|
||||
throw WakeError(WakeFailure.Engine, e)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
|
||||
/** A tenth of a second at a time. */
|
||||
private const val CHUNK = RATE / 10
|
||||
private const val EMPTY_READS = 50
|
||||
private const val SILENT_SAMPLES = RATE * 5
|
||||
private const val HEARD_REST_MS = 1_500L
|
||||
|
||||
/** Half a minute of sound taken in: the microphone and the engine work. */
|
||||
private const val STEADY_SAMPLES = RATE * 30L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
/**
|
||||
* What happened the last times the wake word was heard: kept (the last [WAKE_LOG_SIZE], in the
|
||||
* phone's settings) and shown in Settings › Wake word, because "it heard me and nothing opened"
|
||||
* cannot be put right without knowing which step said no. Nothing of the account is in it: the
|
||||
* phrase, clock times, and Android's own words where it refused.
|
||||
*/
|
||||
@Serializable
|
||||
data class WakeAttempt(
|
||||
/** When the phrase was heard (wall clock, ms). */
|
||||
val at: Long = 0,
|
||||
val phrase: String = "",
|
||||
/** What was tried first: a [WakeWay]'s id. */
|
||||
val way: String = "",
|
||||
/** How that went: one of the `OUT_…` words. */
|
||||
val outcome: String = "",
|
||||
/** Android's own words when it refused: the exception's class and message. */
|
||||
val detail: String = "",
|
||||
/** What was done instead, when the first way did not open the sheet: `activity`, `notification` or nothing. */
|
||||
val fallback: String = "",
|
||||
/** Whether Android said LLeMbas holds the assistant role at that moment. */
|
||||
val assistant: Boolean = false,
|
||||
/** When Android last connected the assistant service in this run of the app, and last disconnected it; 0: never. */
|
||||
val readyAt: Long = 0,
|
||||
val shutdownAt: Long = 0,
|
||||
/** Set afterwards, when the service was not connected and Android connected it later. */
|
||||
val connectedLater: Long = 0,
|
||||
/**
|
||||
* Whether Android itself said LLeMbas's service is its active voice-interaction service
|
||||
* (`VoiceInteractionService.isActiveService`). The role can be held without it: Android then
|
||||
* opens the assistant as an ordinary screen on a long press, and keeps no connection that
|
||||
* could open it from the background.
|
||||
*/
|
||||
val active: Boolean = false,
|
||||
/** Whether the phone has voice recognisers at all (`FEATURE_VOICE_RECOGNIZERS`): without it Android runs no voice-interaction service. */
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
/** Whether one of the app's own screens was showing. */
|
||||
val visible: Boolean = false,
|
||||
/** How long the sheet took to say it was up, in ms; -1 when none came. */
|
||||
val sheetMs: Long = -1,
|
||||
/** When the assistant service was last made and destroyed in this run of the app; 0: never. */
|
||||
val createdAt: Long = 0,
|
||||
val destroyedAt: Long = 0,
|
||||
/** Whether the wake waited for Android to connect the service (it was active but not connected yet). */
|
||||
val waited: Boolean = false,
|
||||
/** What Android told the service about this show (API 34+): it prepared one, or it failed. */
|
||||
val prepared: Boolean = false,
|
||||
val showFailed: Boolean = false,
|
||||
) {
|
||||
companion object {
|
||||
/** The sheet came up. */
|
||||
const val OUT_OPENED = "opened"
|
||||
|
||||
/** Android was asked and did not refuse, but no sheet came up in time. */
|
||||
const val OUT_NO_SHEET = "no_sheet"
|
||||
|
||||
/** The assistant service was not connected (`LembasAssistService.current` was null). */
|
||||
const val OUT_NOT_CONNECTED = "not_connected"
|
||||
|
||||
/** Android refused, with [detail]. */
|
||||
const val OUT_REFUSED = "refused"
|
||||
|
||||
/** A test in Settings took the word: nothing was to open. */
|
||||
const val OUT_TESTED = "tested"
|
||||
}
|
||||
}
|
||||
|
||||
const val WAKE_LOG_SIZE = 5
|
||||
|
||||
/** [log] with [attempt] put first, cut to the last [WAKE_LOG_SIZE]. */
|
||||
fun wakeLogAdd(log: List<WakeAttempt>, attempt: WakeAttempt): List<WakeAttempt> = (listOf(attempt) + log).take(WAKE_LOG_SIZE)
|
||||
|
||||
/**
|
||||
* Android connected the assistant service at [now]: the newest attempt that found it not
|
||||
* connected, and has not been answered yet, is told so. Anything else is left as it is.
|
||||
*/
|
||||
fun wakeLogConnected(log: List<WakeAttempt>, now: Long): List<WakeAttempt> {
|
||||
val newest = log.firstOrNull() ?: return log
|
||||
if (newest.outcome != WakeAttempt.OUT_NOT_CONNECTED || newest.connectedLater != 0L || now < newest.at) return log
|
||||
return listOf(newest.copy(connectedLater = now)) + log.drop(1)
|
||||
}
|
||||
|
||||
/** The ways the assistant may be opened when the word was heard, in the order they are worth trying. */
|
||||
enum class WakeWay(val id: String) {
|
||||
/** The assistant service is connected and the screen is on: it shows its sheet, from anywhere. */
|
||||
Session("session"),
|
||||
|
||||
/**
|
||||
* The assistant service is connected and the screen is off: a session's window turns no
|
||||
* screen on, so the sheet's activity is started through the service instead (Android lets an
|
||||
* app whose service the system has bound start one), and the activity turns the screen on.
|
||||
*/
|
||||
AssistantActivity("assistant_activity"),
|
||||
|
||||
/** No connected assistant service, but the app is on screen: the sheet's activity may start. */
|
||||
Activity("activity"),
|
||||
|
||||
/**
|
||||
* Neither: Android blocks an activity started from the background, and says nothing when it
|
||||
* does -- so it is not relied on, and a notification to tap is posted.
|
||||
*/
|
||||
Notification("notification"),
|
||||
|
||||
// A further way (answering by voice without a sheet) would be one more entry here, chosen in
|
||||
// [wakeWay] and carried out where the others are.
|
||||
}
|
||||
|
||||
/** The first way to try, from what is true at that moment. */
|
||||
fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay = when {
|
||||
connected && screenOn -> WakeWay.Session
|
||||
connected -> WakeWay.AssistantActivity
|
||||
appVisible -> WakeWay.Activity
|
||||
else -> WakeWay.Notification
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant service's life in this run of the app, as Android told it: when it was made,
|
||||
* connected (`onReady`), disconnected (`onShutdown`) and destroyed, what Android said of the last
|
||||
* show it was asked for, and when a sheet last came up. Written by the assistant service, the
|
||||
* session and the sheet's activity; read when the word is heard.
|
||||
*/
|
||||
object AssistLink {
|
||||
@Volatile var createdAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var destroyedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var readyAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var shutdownAt = 0L
|
||||
private set
|
||||
|
||||
/** On the phone's elapsed clock: when Android last said it prepares to show a session, and when one failed to show. */
|
||||
@Volatile var preparedAt = 0L
|
||||
private set
|
||||
|
||||
@Volatile var showFailedAt = 0L
|
||||
private set
|
||||
|
||||
private val _shown = MutableStateFlow(0L)
|
||||
|
||||
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
|
||||
val shown: StateFlow<Long> = _shown.asStateFlow()
|
||||
|
||||
private val _connected = MutableStateFlow(false)
|
||||
|
||||
/** Whether Android has the assistant service connected right now. */
|
||||
val connected: StateFlow<Boolean> = _connected.asStateFlow()
|
||||
|
||||
fun created(now: Long) {
|
||||
createdAt = now
|
||||
}
|
||||
|
||||
fun destroyed(now: Long) {
|
||||
destroyedAt = now
|
||||
}
|
||||
|
||||
fun ready(now: Long) {
|
||||
readyAt = now
|
||||
_connected.value = true
|
||||
}
|
||||
|
||||
fun shutdown(now: Long) {
|
||||
shutdownAt = now
|
||||
_connected.value = false
|
||||
}
|
||||
|
||||
fun prepared(elapsed: Long) {
|
||||
preparedAt = elapsed
|
||||
}
|
||||
|
||||
fun showFailed(elapsed: Long) {
|
||||
showFailedAt = elapsed
|
||||
}
|
||||
|
||||
fun sheetShown(elapsed: Long) {
|
||||
_shown.value = elapsed
|
||||
}
|
||||
}
|
||||
|
||||
/** What is true of the phone and the assistant at the moment the phrase is heard. */
|
||||
data class WakeFacts(
|
||||
/** The assistant service is connected (`LembasAssistService.current` is there). */
|
||||
val connected: Boolean,
|
||||
/** Android says the service is its active voice-interaction service. */
|
||||
val active: Boolean,
|
||||
/** LLeMbas holds the assistant role. */
|
||||
val role: Boolean,
|
||||
val recognizers: Boolean = true,
|
||||
val screenOn: Boolean = true,
|
||||
val locked: Boolean = false,
|
||||
val visible: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Opening the assistant when the phrase was heard, apart from Android so that the order of what
|
||||
* is tried -- and what is written down about it -- can be tested.
|
||||
*
|
||||
* 1. The assistant's own way, where its service is connected ([wakeWay]). When Android says the
|
||||
* service is active but has not connected it yet, a moment is waited for the connection.
|
||||
* 2. "Opened" only once a sheet says it is up ([sheetCame]).
|
||||
* 3. Otherwise the sheet's activity -- relied on only where Android will start it: the service is
|
||||
* connected (a bound service lets the whole app start activities) or the app is on screen. A
|
||||
* session that was only slow is given a second wait first, so there are never two sheets.
|
||||
* 4. Otherwise a notification to tap.
|
||||
*
|
||||
* [open] returns what happened, for the record.
|
||||
*/
|
||||
class WakeOpener(
|
||||
private val facts: () -> WakeFacts,
|
||||
/** Wait up to the given ms for Android to connect the service; whether it did. */
|
||||
private val awaitConnected: suspend (Long) -> Boolean,
|
||||
/** Ask the connected service to show its sheet; throws what Android throws. */
|
||||
private val showSession: () -> Unit,
|
||||
/** Start the sheet's activity; throws what Android throws. */
|
||||
private val startActivity: () -> Unit,
|
||||
/** Wait up to the given ms for a sheet to say it is up; how long it took, or null. */
|
||||
private val sheetCame: suspend (Long) -> Long?,
|
||||
private val notify: (WakeAttempt) -> Unit,
|
||||
/** What Android said of the show since it was asked: prepared, failed. */
|
||||
private val showSignals: () -> Pair<Boolean, Boolean> = { false to false },
|
||||
private val now: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
suspend fun open(phrase: String, link: WakeAttempt = WakeAttempt()): WakeAttempt {
|
||||
var seen = facts()
|
||||
var waited = false
|
||||
if (!seen.connected && seen.active) {
|
||||
// Android's own assistant, only not connected at this instant: it may be on its way.
|
||||
waited = true
|
||||
if (awaitConnected(CONNECT_WAIT_MS)) seen = facts().copy(connected = true)
|
||||
}
|
||||
val way = wakeWay(seen.connected, seen.screenOn, seen.visible)
|
||||
var attempt = link.copy(
|
||||
at = now(),
|
||||
phrase = phrase,
|
||||
way = way.id,
|
||||
assistant = seen.role,
|
||||
active = seen.active,
|
||||
recognizers = seen.recognizers,
|
||||
screenOn = seen.screenOn,
|
||||
locked = seen.locked,
|
||||
visible = seen.visible,
|
||||
waited = waited,
|
||||
)
|
||||
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
|
||||
val refused = runCatching { if (way == WakeWay.Session) showSession() else startActivity() }.exceptionOrNull()
|
||||
val took = if (refused == null) sheetCame(SHEET_WAIT_MS) else null
|
||||
val (prepared, failed) = showSignals()
|
||||
attempt = attempt.copy(prepared = prepared, showFailed = failed)
|
||||
if (took != null) return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = took)
|
||||
attempt = if (refused != null) {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = describe(refused))
|
||||
} else {
|
||||
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
|
||||
}
|
||||
// The activity was the way that just did not come up: starting it a second time is no fallback.
|
||||
if (way == WakeWay.AssistantActivity && refused == null) return notified(attempt)
|
||||
// A session Android did not refuse may only be slow: a second wait, before anything
|
||||
// else is put on screen beside it.
|
||||
if (refused == null) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { late -> return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = SHEET_WAIT_MS + late) }
|
||||
}
|
||||
} else {
|
||||
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
|
||||
}
|
||||
// The sheet's activity. Android blocks one started from the background without a word,
|
||||
// so it counts only where it may start -- and only once it says it is up.
|
||||
val started = runCatching { startActivity() }.isSuccess
|
||||
if (started && (seen.connected || seen.visible)) {
|
||||
sheetCame(SHEET_WAIT_MS)?.let { took -> return attempt.copy(fallback = WakeWay.Activity.id, sheetMs = took) }
|
||||
}
|
||||
return notified(attempt)
|
||||
}
|
||||
|
||||
private fun notified(attempt: WakeAttempt): WakeAttempt {
|
||||
val told = attempt.copy(fallback = WakeWay.Notification.id)
|
||||
notify(told)
|
||||
return told
|
||||
}
|
||||
|
||||
private fun describe(e: Throwable): String = listOfNotNull(e.javaClass.simpleName, e.message?.takeIf { it.isNotBlank() }).joinToString(": ").take(200)
|
||||
|
||||
companion object {
|
||||
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
|
||||
const val SHEET_WAIT_MS = 2_500L
|
||||
|
||||
/** How long Android is given to connect a service it says is active. */
|
||||
const val CONNECT_WAIT_MS = 1_000L
|
||||
|
||||
/** The longest an attempt can take: the connection, three waits for a sheet, and a margin. The microphone is held that long. */
|
||||
const val ATTEMPT_MAX_MS = CONNECT_WAIT_MS + 3 * SHEET_WAIT_MS + 1_500L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
package eu.llembas.android.wake
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioRecord
|
||||
import android.media.MediaRecorder
|
||||
import android.os.Bundle
|
||||
import android.os.PowerManager
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.takeWhile
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
|
||||
*
|
||||
* A `microphone` foreground service with its notification up the whole time it runs -- Android
|
||||
* lets an app hear the microphone in the background only that way, and only once the person has
|
||||
* started it from the app. The audio goes to the on-device engine ([WakeEngine]) in memory and
|
||||
* nowhere else; it is not kept, and nothing is sent anywhere until the word is heard. Then the
|
||||
* microphone is let go and the assistant opens, listening, as the power button would open it.
|
||||
*
|
||||
* It pauses itself (the notification says why) while the assistant's sheet is up, in battery
|
||||
* saver, and -- unless Settings says otherwise -- while the screen is off; it goes on once the
|
||||
* reason is gone. It cannot start itself at boot (Android forbids a microphone service there):
|
||||
* [WakeBootReceiver] posts "tap to listen again" instead.
|
||||
*/
|
||||
class WakeWordService : LifecycleService() {
|
||||
private val screenOn = MutableStateFlow(true)
|
||||
private val batterySaver = MutableStateFlow(false)
|
||||
private val mayRecord = MutableStateFlow(true)
|
||||
private var following: Job? = null
|
||||
private var watching: Job? = null
|
||||
|
||||
/** This instance's right to write the state (WakeStatus.begin). */
|
||||
private var token = 0
|
||||
|
||||
/** The newest start Android has delivered: what the service stops itself by, so a start still on its way is not stopped. */
|
||||
private var lastStart = 0
|
||||
|
||||
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
|
||||
private var keepState = false
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_SCREEN_ON -> {
|
||||
screenOn.value = true
|
||||
mayRecord.value = micAllowed(this@WakeWordService)
|
||||
}
|
||||
|
||||
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
|
||||
|
||||
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
channel(this)
|
||||
screenOn.value = power().isInteractive
|
||||
batterySaver.value = power().isPowerSaveMode
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
receiver,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
// Every start counts, Stop's too: the service stops itself by the newest one it was given.
|
||||
lastStart = startId
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
// Stop is the setting going off; the loop sees it and ends the service on the path
|
||||
// that has shown its notification first (follow). The service is stopped from here
|
||||
// only when nothing is running in it, and only if no newer start is on its way
|
||||
// (stopSelf(startId)): stopping under a pending foreground start closes the app.
|
||||
lifecycleScope.launch {
|
||||
lembas.instances.savePrefs { it.copy(wakeWord = false) }
|
||||
if (following?.isActive != true) stopSelf(startId)
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
mayRecord.value = micAllowed(this)
|
||||
val running = following?.isActive == true
|
||||
// The notification first: Android stops a foreground service that is slow to show one.
|
||||
// It says what is true now -- "starting" for a service that just began, and on every
|
||||
// later start (the app opens) whatever the state already is; never a phrase by default.
|
||||
val now = wakeStateAtStart(running, WakeStatus.state.value)
|
||||
try {
|
||||
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
||||
} catch (e: Exception) {
|
||||
// Android refuses a microphone service without the permission, or from the background.
|
||||
Log.w(TAG, "wake word: the service could not start", e)
|
||||
keepState = true
|
||||
WakeStatus.set(
|
||||
if (mayRecord.value) {
|
||||
WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail)
|
||||
} else {
|
||||
WakeState.Paused(WakePause.NoMicrophone)
|
||||
},
|
||||
)
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
// It is listening again: "tap to listen again" (after a restart) has nothing left to say.
|
||||
manager.cancel(WakeBootReceiver.RESUME_ID)
|
||||
if (!running) {
|
||||
keepState = false
|
||||
// This instance writes the state from here; an older one's last words count for nothing.
|
||||
token = WakeStatus.begin()
|
||||
// And it starts from what the sheets say: no hold of an earlier instance is left standing.
|
||||
AssistPresence.release()
|
||||
WakeStatus.set(token, now)
|
||||
following = lifecycleScope.launch { follow() }
|
||||
}
|
||||
if (watching == null) {
|
||||
// The one place the notification is written: from the state, whenever it changes.
|
||||
watching = lifecycleScope.launch {
|
||||
WakeStatus.state.collect { state ->
|
||||
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
|
||||
}
|
||||
}
|
||||
// A tap on the failure in Settings: try now, not when the back-off says.
|
||||
lifecycleScope.launch { WakeStatus.retries.drop(1).collect { listener.retryNow() } }
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private val listener by lazy {
|
||||
WakeListener(
|
||||
say = { WakeStatus.set(token, it) },
|
||||
engine = { keywords -> WakeEngine.create(this, keywords) },
|
||||
microphone = { PhoneMicrophone() },
|
||||
// A test in Settings takes the word; otherwise the assistant opens.
|
||||
heard = { phrase ->
|
||||
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
|
||||
val tested = WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED)
|
||||
wakeScope.launch { record(this@WakeWordService, tested) }
|
||||
} else {
|
||||
wake(phrase)
|
||||
}
|
||||
},
|
||||
log = { message, cause -> Log.w(TAG, message, cause) },
|
||||
)
|
||||
}
|
||||
|
||||
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
|
||||
private suspend fun follow() {
|
||||
val mine = token
|
||||
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
|
||||
if (!prefs.wakeWord) {
|
||||
null
|
||||
} else {
|
||||
val phrase = WakePhrases.byId(prefs.wakePhrase)
|
||||
WakePlan(phrase, wakeKeywords(phrase, WakeSensitivity.byId(prefs.wakeSensitivity)), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
|
||||
}
|
||||
}
|
||||
try {
|
||||
listener.follow(plans.takeWhile { it != null }.filterNotNull())
|
||||
} finally {
|
||||
// After the loop has ended, so nothing it said on its way out is left standing --
|
||||
// and only if no newer writer has taken over meanwhile.
|
||||
if (!keepState) WakeStatus.set(mine, WakeState.Off)
|
||||
}
|
||||
// Not if a newer start is already on its way: that one finds the loop ended and begins it again.
|
||||
stopSelf(lastStart)
|
||||
}
|
||||
|
||||
/**
|
||||
* The word was heard: the assistant opens listening ([WakeOpener] decides how and checks that
|
||||
* it did), and what was tried and how it went is written down ([WakeAttempt], kept in the
|
||||
* settings and shown in Settings › Wake word), because a silent "no" here looks to the
|
||||
* person like a wake word that does not work.
|
||||
*
|
||||
* It runs on the app's own scope, never inside the listening loop: the hold below pauses
|
||||
* the listener, which cancels the loop that heard the word -- and a wake that ran in that
|
||||
* loop was cancelled by its own first step. One at a time: a word heard while the last one
|
||||
* is still being answered is let go.
|
||||
*/
|
||||
private fun wake(phrase: WakePhrase) {
|
||||
if (waking?.isActive == true) return
|
||||
// The microphone is the sheet's from here, for as long as the attempt can take; once it
|
||||
// is over, for a moment more, and then for as long as a sheet says it is up.
|
||||
AssistPresence.holdFor(WakeOpener.ATTEMPT_MAX_MS)
|
||||
waking = wakeScope.launch {
|
||||
try {
|
||||
val asked = SystemClock.elapsedRealtime()
|
||||
val opener = WakeOpener(
|
||||
facts = { wakeFacts(this@WakeWordService) },
|
||||
awaitConnected = { ms -> withTimeoutOrNull(ms) { AssistLink.connected.first { it } } != null },
|
||||
showSession = {
|
||||
val assistant = LembasAssistService.current ?: error("the assistant service is not connected")
|
||||
assistant.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0)
|
||||
},
|
||||
// Through the assistant service where it is connected (the same permission either way: Android lets
|
||||
// the whole app start activities while it holds the service bound).
|
||||
startActivity = { (LembasAssistService.current ?: this@WakeWordService).startActivity(AssistActivity.woken(this@WakeWordService)) },
|
||||
sheetCame = { ms ->
|
||||
withTimeoutOrNull(ms) { AssistLink.shown.first { it >= asked } }?.let { (it - asked).coerceAtLeast(0) }
|
||||
},
|
||||
notify = { attempt ->
|
||||
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this@WakeWordService, attempt.assistant))
|
||||
},
|
||||
showSignals = { (AssistLink.preparedAt >= asked) to (AssistLink.showFailedAt >= asked) },
|
||||
)
|
||||
val link = WakeAttempt(
|
||||
createdAt = AssistLink.createdAt,
|
||||
destroyedAt = AssistLink.destroyedAt,
|
||||
readyAt = AssistLink.readyAt,
|
||||
shutdownAt = AssistLink.shutdownAt,
|
||||
)
|
||||
record(this@WakeWordService, opener.open(phrase.words, link))
|
||||
} finally {
|
||||
AssistPresence.holdFor(SHEET_GRACE_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var waking: Job? = null
|
||||
|
||||
private fun power() = getSystemService(PowerManager::class.java)
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(receiver) }
|
||||
// The scope ends with the service: the listener's loop is joined and its engine released
|
||||
// on the way out (WakeListener.follow), not here under a loop that may still run.
|
||||
if (!keepState) WakeStatus.set(token, WakeState.Off)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL = "wake_word"
|
||||
const val CHANNEL_HEARD = "wake_heard"
|
||||
private const val NOTIFICATION_ID = 7001
|
||||
const val HEARD_ID = 7002
|
||||
private const val SHEET_GRACE_MS = 3_000L
|
||||
|
||||
/** `PackageManager.FEATURE_VOICE_RECOGNIZERS`, which the SDK does not name for apps: without it Android runs no voice-interaction service. */
|
||||
private const val FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers"
|
||||
|
||||
/** The app's own scope: a wake and its record outlive the listening loop, and the service too. */
|
||||
private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
|
||||
/** What is true at this moment, for the opener and the record. */
|
||||
fun wakeFacts(context: Context): WakeFacts = WakeFacts(
|
||||
connected = LembasAssistService.current != null,
|
||||
active = LembasAssistService.isActive(context),
|
||||
role = LembasAssistService.holdsRole(context),
|
||||
recognizers = context.packageManager.hasSystemFeature(FEATURE_VOICE_RECOGNIZERS),
|
||||
screenOn = context.getSystemService(PowerManager::class.java).isInteractive,
|
||||
locked = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked,
|
||||
visible = AppVisibility.visible,
|
||||
)
|
||||
|
||||
/**
|
||||
* Write [attempt] down: in the log under a fixed tag, and first among the last few in the
|
||||
* settings. Not cancellable: what happened is kept whatever ends meanwhile.
|
||||
*/
|
||||
suspend fun record(context: Context, attempt: WakeAttempt) = withContext(NonCancellable) {
|
||||
Log.i(TAG, "wake word heard: $attempt")
|
||||
runCatching { context.lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
|
||||
Unit
|
||||
}
|
||||
private const val TAG = "LLeMbasWake"
|
||||
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
|
||||
|
||||
/**
|
||||
* Start listening, or say why not. Only from the app on screen: Android allows a
|
||||
* microphone service from there, and only with the microphone permission -- without it
|
||||
* the service is not started at all, and the state says so.
|
||||
*/
|
||||
fun start(context: Context) {
|
||||
if (!WakeEngine.AVAILABLE) return WakeStatus.set(WakeState.Failed(WakeFailure.NoEngine))
|
||||
if (!micAllowed(context)) return WakeStatus.set(WakeState.Paused(WakePause.NoMicrophone))
|
||||
try {
|
||||
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "wake word: the service could not be started", e)
|
||||
WakeStatus.set(WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wake word was turned off. The service is not stopped from outside: it ends itself
|
||||
* when it sees the setting, after it has shown its notification -- stopping it under a
|
||||
* foreground start that is still on its way closes the app. The state is "off" at once.
|
||||
*/
|
||||
fun stop() {
|
||||
WakeStatus.set(WakeState.Off)
|
||||
}
|
||||
|
||||
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
|
||||
|
||||
fun channel(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java).createNotificationChannels(
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
|
||||
// "Heard you. Tap to ask.": it must come up over what is on screen, or the word was for nothing.
|
||||
NotificationChannel(CHANNEL_HEARD, context.getString(R.string.channel_wake_heard), NotificationManager.IMPORTANCE_HIGH),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
|
||||
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
|
||||
*/
|
||||
fun wakeHeardNotification(context: Context, assistant: Boolean = false): Notification {
|
||||
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_heard))
|
||||
// Why it is a notification and not the sheet, in fixed words: LLeMbas is not the phone's
|
||||
// assistant -- or it is, and could not open by itself this time (Settings says which step said no).
|
||||
.setContentText(context.getString(if (assistant) R.string.wake_heard_could_not else R.string.wake_heard_line))
|
||||
.setContentIntent(ask)
|
||||
.setAutoCancel(true)
|
||||
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setTimeoutAfter(HEARD_TIMEOUT_MS)
|
||||
.build()
|
||||
}
|
||||
|
||||
/** A minute: a "tap to ask" nobody tapped is no longer an answer to anything. */
|
||||
private const val HEARD_TIMEOUT_MS = 60_000L
|
||||
|
||||
/**
|
||||
* The persistent notification, from [state] alone: what the wake word is doing in plain words
|
||||
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
|
||||
*/
|
||||
fun wakeNotification(context: Context, state: WakeState): Notification {
|
||||
val stop = PendingIntent.getService(
|
||||
context,
|
||||
2,
|
||||
Intent(context, WakeWordService::class.java).setAction(WakeWordService.ACTION_STOP),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val open = PendingIntent.getActivity(context, 3, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
|
||||
return NotificationCompat.Builder(context, WakeWordService.CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(wakeTitle(context, state))
|
||||
.setContentText(wakeLine(context, state))
|
||||
.setOngoing(true)
|
||||
.setSilent(true)
|
||||
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(open)
|
||||
.addAction(0, context.getString(R.string.wake_stop), stop)
|
||||
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
|
||||
.build()
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's microphone at 16 kHz, recording from the moment it is made -- or an exception that
|
||||
* says what did not work. Android reports none of this by throwing: a recorder that could not be
|
||||
* opened is merely "uninitialized", and one that did not start merely "stopped".
|
||||
*/
|
||||
@android.annotation.SuppressLint("MissingPermission")
|
||||
private class PhoneMicrophone : WakeMicrophone {
|
||||
private val audio: AudioRecord
|
||||
|
||||
init {
|
||||
val rate = WakeListener.RATE
|
||||
val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
|
||||
check(min > 0) { "the phone cannot record at 16 kHz" }
|
||||
audio = AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate))
|
||||
try {
|
||||
check(audio.state == AudioRecord.STATE_INITIALIZED) { "the microphone could not be opened" }
|
||||
audio.startRecording()
|
||||
check(audio.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "recording did not start; another app may have the microphone" }
|
||||
} catch (e: Exception) {
|
||||
audio.release()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
override fun read(into: ShortArray): Int = audio.read(into, 0, into.size)
|
||||
|
||||
override fun close() {
|
||||
runCatching { audio.stop() }
|
||||
audio.release()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After a restart: Android does not let a microphone service start at boot, so a wake word that
|
||||
* was on says "tap to listen again" -- the tap opens the app, which starts it.
|
||||
*/
|
||||
class WakeBootReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
|
||||
val pending = goAsync()
|
||||
CoroutineScope(Dispatchers.Default).launch {
|
||||
try {
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
if (!prefs.wakeWord || !WakeEngine.AVAILABLE) return@launch
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return@launch
|
||||
WakeWordService.channel(context)
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
4,
|
||||
Intent(context, MainActivity::class.java).putExtra(EXTRA_RESUME, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
context.getSystemService(NotificationManager::class.java).notify(
|
||||
RESUME_ID,
|
||||
NotificationCompat.Builder(context, WakeWordService.CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.wake_resume))
|
||||
.setContentText(context.getString(R.string.wake_resume_line))
|
||||
.setContentIntent(open)
|
||||
.setAutoCancel(true)
|
||||
.build(),
|
||||
)
|
||||
} finally {
|
||||
pending.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** On MainActivity's intent: start listening for the wake word again. */
|
||||
const val EXTRA_RESUME = "eu.llembas.android.WAKE_RESUME"
|
||||
const val RESUME_ID = 7003
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Generated by scripts/gen-wake-phrases.py from the model's bpe.model. Do not edit: edit the lists there.
|
||||
package eu.llembas.android.wake
|
||||
|
||||
/**
|
||||
* The words a wake phrase is made of -- a greeting and a name -- each with its spelling in the
|
||||
* model's BPE pieces (`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01`). English, as the
|
||||
* model is.
|
||||
*
|
||||
* Left out, because the tokenizer can only spell them out letter by letter:
|
||||
* Elizabeth (▁E LI Z A B E TH)
|
||||
* Benjamin (▁BE N J A M IN)
|
||||
*/
|
||||
object WakeWords {
|
||||
val greetings = listOf(
|
||||
WakeWord("hey", "Hey", "▁HE Y"),
|
||||
WakeWord("ok", "OK", "▁OKAY"),
|
||||
WakeWord("hello", "Hello", "▁HE LL O"),
|
||||
)
|
||||
|
||||
val names = listOf(
|
||||
WakeWord("assistant", "Assistant", "▁AS S IST ANT"),
|
||||
WakeWord("computer", "Computer", "▁COMP U TER"),
|
||||
WakeWord("google", "Google", "▁GO O G LE"),
|
||||
WakeWord("victoria", "Victoria", "▁VI C T OR IA"),
|
||||
WakeWord("samantha", "Samantha", "▁SA MAN TH A"),
|
||||
WakeWord("jessica", "Jessica", "▁JE S S IC A"),
|
||||
WakeWord("amanda", "Amanda", "▁A MAN D A"),
|
||||
WakeWord("olivia", "Olivia", "▁O LI VI A"),
|
||||
WakeWord("oliver", "Oliver", "▁O LI VER"),
|
||||
WakeWord("sebastian", "Sebastian", "▁SE B AS T IAN"),
|
||||
WakeWord("jonathan", "Jonathan", "▁JO N A TH AN"),
|
||||
WakeWord("alexander", "Alexander", "▁A LE X AN DER"),
|
||||
WakeWord("christopher", "Christopher", "▁ CH R IST O PH ER"),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package eu.llembas.android.widget
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.content.pm.ShortcutManager
|
||||
import android.graphics.drawable.Icon
|
||||
import android.widget.RemoteViews
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
|
||||
/**
|
||||
* The home-screen widget: a bar that opens the assistant's sheet (Ask), the sheet listening (the
|
||||
* microphone), or the sheet at the last chat the assistant made. Nothing on it comes from the
|
||||
* account, so it never needs updating and shows nothing private wherever it is placed.
|
||||
*/
|
||||
class AskWidget : AppWidgetProvider() {
|
||||
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
|
||||
val views = RemoteViews(context.packageName, R.layout.widget_ask).apply {
|
||||
setOnClickPendingIntent(R.id.widget_ask, open(context, REQUEST_ASK, Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST)))
|
||||
setOnClickPendingIntent(R.id.widget_mic, open(context, REQUEST_LISTEN, AssistActivity.listening(context)))
|
||||
setOnClickPendingIntent(R.id.widget_last, open(context, REQUEST_CONTINUE, AssistActivity.continuing(context)))
|
||||
}
|
||||
ids.forEach { manager.updateAppWidget(it, views) }
|
||||
}
|
||||
|
||||
private fun open(context: Context, request: Int, intent: Intent): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
request,
|
||||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_ASK = 1
|
||||
private const val REQUEST_LISTEN = 2
|
||||
private const val REQUEST_CONTINUE = 3
|
||||
|
||||
/**
|
||||
* Give every placed widget its buttons again. Nothing on it changes -- but the intents
|
||||
* behind the buttons carry the app's own mark ([eu.llembas.android.assist.OwnIntents]),
|
||||
* and a widget placed by an older version has buttons without it.
|
||||
*/
|
||||
fun refresh(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context) ?: return
|
||||
val ids = runCatching { manager.getAppWidgetIds(ComponentName(context, AskWidget::class.java)) }.getOrNull() ?: return
|
||||
if (ids.isNotEmpty()) AskWidget().onUpdate(context, manager, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The launcher icon's long-press shortcuts: Ask, Speak and the last assistant chat. Published from
|
||||
* code rather than `shortcuts.xml`, because a static shortcut names the package, and the test
|
||||
* build's is `….debug`; and so their labels follow the app's language.
|
||||
*/
|
||||
object Shortcuts {
|
||||
fun publish(context: Context) {
|
||||
val manager = context.getSystemService(ShortcutManager::class.java) ?: return
|
||||
val shortcuts = listOf(
|
||||
shortcut(
|
||||
context,
|
||||
"ask",
|
||||
R.string.tile_ask,
|
||||
R.string.tile_ask,
|
||||
R.drawable.ic_shortcut_ask,
|
||||
Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST),
|
||||
),
|
||||
shortcut(context, "speak", R.string.widget_speak, R.string.widget_speak, R.drawable.ic_shortcut_mic, AssistActivity.listening(context)),
|
||||
shortcut(context, "continue", R.string.shortcut_last, R.string.assist_continue, R.drawable.ic_shortcut_history, AssistActivity.continuing(context)),
|
||||
)
|
||||
runCatching { manager.dynamicShortcuts = shortcuts }
|
||||
}
|
||||
|
||||
private fun shortcut(context: Context, id: String, short: Int, long: Int, icon: Int, intent: Intent): ShortcutInfo = ShortcutInfo.Builder(context, id)
|
||||
.setShortLabel(context.getString(short))
|
||||
.setLongLabel(context.getString(long))
|
||||
.setIcon(Icon.createWithResource(context, icon))
|
||||
.setIntent(intent)
|
||||
.build()
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="48dp" android:height="48dp"
|
||||
android:viewportWidth="48" android:viewportHeight="48">
|
||||
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
|
||||
<group android:translateX="12" android:translateY="12">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
|
||||
</group>
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_ink_muted" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp" android:height="24dp"
|
||||
android:viewportWidth="24" android:viewportHeight="24">
|
||||
<path android:fillColor="@color/token_accent_ink" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The widget's bar, in the theme's colours (values*/tokens.xml). -->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="@color/token_surface" />
|
||||
<stroke android:width="1dp" android:color="@color/token_border" />
|
||||
<corners android:radius="28dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
|
||||
<solid android:color="@color/token_accent" />
|
||||
</shape>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The home-screen widget: Ask (the sheet), the microphone (the sheet, listening) and the last
|
||||
assistant chat. It shows nothing from the account (no chat title, no model), so nothing
|
||||
of it is private wherever the launcher shows it. Every part keeps a fixed size except the
|
||||
Ask label, which gives. -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/widget_root"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@drawable/widget_background"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="56dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="4dp">
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/widget_ask"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_weight="1"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:layout_width="24dp"
|
||||
android:layout_height="24dp"
|
||||
android:importantForAccessibility="no"
|
||||
android:src="@drawable/ic_widget_ask" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="12dp"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:text="@string/widget_hint"
|
||||
android:textColor="@color/token_ink_muted"
|
||||
android:textSize="16sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/widget_last"
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp"
|
||||
android:contentDescription="@string/assist_continue"
|
||||
android:padding="12dp"
|
||||
android:src="@drawable/ic_widget_history" />
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/widget_mic"
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="2dp"
|
||||
android:background="@drawable/widget_mic_background"
|
||||
android:contentDescription="@string/widget_speak"
|
||||
android:padding="12dp"
|
||||
android:src="@drawable/ic_widget_mic" />
|
||||
</LinearLayout>
|
||||
@@ -14,10 +14,7 @@
|
||||
<string name="signin_too_old">Tato instance používá starší LLeMbas. Tato aplikace potřebuje LLeMbas 2.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">Zatím žádné konverzace s agentem. Spusťte jednu tlačítkem Nová konverzace s agentem na zařízení propojeném s touto instancí.</string>
|
||||
<string name="new_agent_chat">Nová konverzace s agentem</string>
|
||||
<string name="agent_device">Zařízení</string>
|
||||
<string name="agent_no_device">Právě není propojené žádné zařízení. Spusťte `lembas service` na počítači přihlášeném k této instanci a vraťte se.</string>
|
||||
@@ -26,6 +23,28 @@
|
||||
<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="archived">Archivované</string>
|
||||
<string name="archived_restore">Obnovit konverzaci</string>
|
||||
<string name="archived_none">Žádné archivované konverzace.</string>
|
||||
<string name="memory">Paměť</string>
|
||||
<string name="memory_intro">Co si o vás modely pamatují</string>
|
||||
<string name="memory_none">Zatím nic. Model, který má nástroj paměti, sem přidá záznam, když mu řeknete něco, co stojí za uchování.</string>
|
||||
<string name="memory_remember">Zapamatovat</string>
|
||||
<string name="memory_label">Co říká tento záznam v paměti</string>
|
||||
<string name="memory_hint">Něco, co stojí za zapamatování</string>
|
||||
<string name="memory_group">Datová skupina</string>
|
||||
<string name="memory_forget">Zapomenout</string>
|
||||
<string name="memory_by_model">Model</string>
|
||||
<string name="chats_pinned">Připnuté konverzace</string>
|
||||
<string name="chat_pin">Připnout konverzaci</string>
|
||||
<string name="chat_unpin">Odepnout konverzaci</string>
|
||||
<string name="folder_move">Přesunout do složky</string>
|
||||
<string name="folder_none">Bez složky</string>
|
||||
<string name="folder_new">Nová složka</string>
|
||||
<string name="folder_name">Název složky</string>
|
||||
<string name="folder_rename">Přejmenovat složku</string>
|
||||
<string name="folder_delete">Smazat složku</string>
|
||||
<string name="folder_delete_confirm">Smazat složku „%1$s“? Konverzace v ní zůstanou.</string>
|
||||
<string name="delete">Smazat</string>
|
||||
<string name="edit">Upravit</string>
|
||||
<string name="regenerate">Vygenerovat znovu</string>
|
||||
@@ -43,6 +62,8 @@
|
||||
<string name="attach_take_photo">Vyfotit</string>
|
||||
<string name="attach_choose_photos">Vybrat fotky</string>
|
||||
<string name="attach_choose_files">Vybrat soubory</string>
|
||||
<string name="image_generate">Generovat obrázky</string>
|
||||
<string name="image_generated">Vygenerovaný obrázek</string>
|
||||
<string name="copy_message">Zkopírovat zprávu</string>
|
||||
<string name="copied">Zkopírováno.</string>
|
||||
<string name="rename_chat">Přejmenovat konverzaci</string>
|
||||
@@ -79,11 +100,18 @@
|
||||
<string name="ctx_since">Od poslední odpovědi</string>
|
||||
<string name="ctx_buffer">Rezerva na zhuštění</string>
|
||||
<string name="ctx_free">Volné místo</string>
|
||||
<string name="outputs_empty">V tomto chatu se zatím nezapsal žádný soubor.</string>
|
||||
<string name="tasks_empty">Na pozadí nic neběží. Pomocníci, příkazy a členové týmu se tu zobrazí, dokud pracují.</string>
|
||||
<string name="tasks_empty">Na pozadí nic neběží. Podagenti, příkazy a členové týmu se tu ukážou, dokud pracují.</string>
|
||||
<string name="tasks_none_running">Nic neběží.</string>
|
||||
<string name="agents_one_working">1 agent pracuje</string>
|
||||
<string name="agents_n_working">Pracující agenti: %1$s</string>
|
||||
<string name="tasks_running">Běží</string>
|
||||
<string name="tasks_finished">Dokončeno</string>
|
||||
<string name="tasks_n_running">Běží: %1$s</string>
|
||||
<string name="tasks_nested">Pod ním: %1$s</string>
|
||||
<string name="task_subagent">Podagent</string>
|
||||
<string name="task_command">Příkaz</string>
|
||||
<string name="task_member">Člen týmu</string>
|
||||
<string name="activity_until_compact">%1$s do automatického shrnutí</string>
|
||||
<string name="activity_compact_off">Automatické shrnutí je vypnuté.</string>
|
||||
<string name="activity_compact">Shrnout</string>
|
||||
<string name="agents_n_queued">Ve frontě: %1$s</string>
|
||||
<string name="agents_n_waiting">Čeká: %1$s</string>
|
||||
<string name="agents_n_finished">Dokončeno: %1$s</string>
|
||||
@@ -100,28 +128,208 @@
|
||||
<string name="agent_stop_confirm">Zastavit %1$s? Co dosud udělal, zůstane.</string>
|
||||
<string name="agent_nothing_yet">Zatím nic neřekl.</string>
|
||||
<string name="agent_machine">Od systému</string>
|
||||
<string name="team_size">Tým: %1$s z %2$s agentů</string>
|
||||
<string name="team_size">Tým: %1$s z %2$s podagentů</string>
|
||||
<string name="team_room">Místnost</string>
|
||||
<string name="room_empty">V místnosti zatím nikdo nic neřekl.</string>
|
||||
<string name="room_report">hlášení</string>
|
||||
<string name="team_agents">Agenti</string>
|
||||
<string name="team_fewest">Nejméně</string>
|
||||
<string name="team_most">Nejvíce</string>
|
||||
<string name="team_hint">Včetně vlastního agenta. Při více než jednom může přidat členy, kteří dělají práci, zatímco je vede.</string>
|
||||
<string name="team_chip">Agenti %1$s–%2$s</string>
|
||||
<string name="team_agents">Podagenti</string>
|
||||
<string name="team_min">Min</string>
|
||||
<string name="team_max">Max</string>
|
||||
<string name="team_range">Min %1$s · Max %2$s</string>
|
||||
<string name="team_hint">Čísla počítají i vlastního agenta tohoto chatu: 1 je agent sám, bez podagentů, a Max 4 je agent a až 3 podagenti, které vede.</string>
|
||||
<string name="team_chip">Podagenti: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Tento model obslouží jen jeden požadavek najednou: podagenti potřebují jiný model, na jiném serveru, pojmenovaný v chatu.</string>
|
||||
<string name="thinking_switch">Přemýšlet před odpovědí</string>
|
||||
<string name="effort_level">Náročnost: %1$s</string>
|
||||
<string name="level_off">vypnuto</string>
|
||||
<string name="level_default">výchozí</string>
|
||||
<string name="chats_open">Otevřít chaty</string>
|
||||
<string name="chats_search">Hledat v chatech</string>
|
||||
<string name="chats_today">Dnes</string>
|
||||
<string name="chats_earlier">Dříve</string>
|
||||
<string name="chats_agents">Chaty s agentem</string>
|
||||
<string name="chats_found_in_messages">Ve zprávách</string>
|
||||
<string name="chats_none_found">Žádný chat to nemá v názvu.</string>
|
||||
<string name="clear">Vymazat</string>
|
||||
<string name="composer_hint_agent">Řekněte agentovi, co má udělat</string>
|
||||
<string name="tune">Možnosti</string>
|
||||
<string name="effort">Úsilí</string>
|
||||
<string name="thinking_switch_hint">Pomalejší a lepší u těžkých otázek.</string>
|
||||
<string name="plan_first">Nejdřív plán</string>
|
||||
<string name="plan_first_hint">Model napíše plán, který schválíte, než začne jednat.</string>
|
||||
<string name="agent_mode">Režim</string>
|
||||
<string name="agent_greeting">Co má agent udělat?</string>
|
||||
<string name="agent_runs_on">Běží na %1$s, ve složce %2$s</string>
|
||||
<string name="agent_directory_default">jeho první složka</string>
|
||||
<string name="kind_chat">Konverzace</string>
|
||||
<string name="kind_agent">Agentní konverzace</string>
|
||||
<string name="kind_chat_line">Mluvte s modelem: otázky, psaní, soubory, které přiložíte.</string>
|
||||
<string name="kind_agent_line">Pracuje na počítači, který jste propojili: čte, zapisuje a spouští příkazy ve složce.</string>
|
||||
<string name="agent_link_title">Nejdřív propojte počítač</string>
|
||||
<string name="agent_link_lede">Agentní konverzace běží na počítači s LLeMbas CLI, které je přihlášené k této instanci a připojené. Teď není připojené žádné.</string>
|
||||
<string name="agent_link_install">Nainstalujte na něj LLeMbas CLI:</string>
|
||||
<string name="agent_link_login">Přihlaste ho k této instanci a schvalte kód, který ukáže, v prohlížeči, který se otevře:</string>
|
||||
<string name="agent_link_service">Aby na něm odsud běžely agentní konverzace, povolte to v jeho konfiguraci (~/.config/lembas/config.yaml) a spusťte službu:</string>
|
||||
<string name="agent_link_dials_out">Připojuje se sám k této instanci; na vašem počítači nic nenaslouchá. O tom, které adresáře a režimy může práce na dálku použít, rozhoduje on, ať se tu žádá cokoli.</string>
|
||||
<string name="agent_link_check">Zkontrolovat znovu</string>
|
||||
<string name="model_choose">Vyberte model</string>
|
||||
<string name="model_in_use">Používá se</string>
|
||||
<string name="model_sees_images">Vidí obrázky</string>
|
||||
<string name="model_uses_tools">Používá nástroje</string>
|
||||
<string name="model_context">kontext %1$s</string>
|
||||
<string name="model_thinking_switchable">Přemýšlení zapnout či vypnout</string>
|
||||
<string name="model_levels">Úsilí: %1$s</string>
|
||||
<string name="code">Kód</string>
|
||||
<string name="copy_code">Zkopírovat kód</string>
|
||||
<string name="select_text">Vybrat text</string>
|
||||
<string name="tools_used">Použité nástroje: %1$s</string>
|
||||
<string name="suggest_explain">Vysvětli</string>
|
||||
<string name="suggest_explain_line">jak něco funguje, jednoduše</string>
|
||||
<string name="suggest_write">Napiš</string>
|
||||
<string name="suggest_write_line">e-mail, poznámku nebo příspěvek</string>
|
||||
<string name="suggest_plan">Naplánuj</string>
|
||||
<string name="suggest_plan_line">výlet, týden nebo projekt</string>
|
||||
<string name="suggest_check">Zkontroluj</string>
|
||||
<string name="suggest_check_line">text, chyby a tón</string>
|
||||
<string name="instance_in_use">Používá se</string>
|
||||
<string name="notification_settings">Nastavení oznámení</string>
|
||||
<string name="notification_settings_hint">Které druhy přicházejí a jak: odpovědi, otázky, výsledky a selhání naplánovaných úloh.</string>
|
||||
<string name="scheduled">Naplánováno</string>
|
||||
<string name="scheduled_empty">Nic není naplánováno. Požádejte o něco, co se má stát každé ráno, nebo jednou příští týden.</string>
|
||||
<string name="scheduled_unsupported">Tato instance zatím naplánované úlohy nenabízí. Přijdou s novějším LLeMbas na serveru.</string>
|
||||
<string name="schedule_new">Nový plán</string>
|
||||
<string name="schedule_edit">Upravit plán</string>
|
||||
<string name="schedule_next">Příště: %1$s</string>
|
||||
<string name="schedule_paused">Pozastaveno</string>
|
||||
<string name="schedule_pause">Pozastavit</string>
|
||||
<string name="schedule_resume">Pokračovat</string>
|
||||
<string name="schedule_run_now">Spustit teď</string>
|
||||
<string name="schedule_started">Spuštěno. Výsledek se objeví v historii.</string>
|
||||
<string name="schedule_next_runs">Příští spuštění</string>
|
||||
<string name="schedule_history">Historie</string>
|
||||
<string name="schedule_no_runs">Zatím neběžel.</string>
|
||||
<string name="schedule_model">Model: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Smazat tento plán? Jeho dřívější výsledky zůstanou ve svých chatech.</string>
|
||||
<string name="schedule_words_hint">Řekněte vlastními slovy kdy a co. Než se cokoli uloží, uvidíte, jak to bylo pochopeno.</string>
|
||||
<string name="schedule_words_example">Každý pracovní den v 7:30 shrň zprávy o obnovitelné energii</string>
|
||||
<string name="schedule_preview">Náhled</string>
|
||||
<string name="schedule_understood">Pochopeno jako</string>
|
||||
<string name="notify_always">Dá vědět pokaždé</string>
|
||||
<string name="notify_matters">Dá vědět, když na tom záleží</string>
|
||||
<string name="notify_never">Nedá vědět nikdy</string>
|
||||
<string name="run_ok">Hotovo</string>
|
||||
<string name="run_silent">Nic nového</string>
|
||||
<string name="run_unchanged">Beze změny</string>
|
||||
<string name="schedule_computer">Počítač</string>
|
||||
<string name="schedule_computer_away">teď není propojený</string>
|
||||
<string name="schedule_watching">Jen když se tato stránka změní</string>
|
||||
<string name="schedule_watching_command">Jen když se změní výstup tohoto příkazu</string>
|
||||
<string name="run_failed">Selhalo</string>
|
||||
<string name="run_missed">Zmeškáno ×%1$s</string>
|
||||
<string name="run_skipped">Vynecháno</string>
|
||||
<string name="run_waiting">Čeká na model</string>
|
||||
<string name="run_waiting_computer">Čeká na počítač</string>
|
||||
<string name="run_running">Běží</string>
|
||||
<string name="run_model_instead">%1$s, místo %2$s</string>
|
||||
<string name="run_retry_at">Zkusí to znovu v %1$s</string>
|
||||
<string name="run_result">Výsledek</string>
|
||||
<string name="run_no_text">Tento běh nezanechal žádný text.</string>
|
||||
<string name="run_open_chat">Otevřít jeho konverzaci</string>
|
||||
<string name="mode_fresh">Pokaždé nový chat</string>
|
||||
<string name="mode_continue">Jeden chat, který roste</string>
|
||||
<string name="schedule_models">Modely pro naplánované úlohy</string>
|
||||
<string name="schedule_models_hint">Naplánované úlohy vezmou první z nich, který je volný, v tomto pořadí. Zrušte zaškrtnutí, chcete-li některý vynechat.</string>
|
||||
<string name="model_free">Teď volný</string>
|
||||
<string name="model_busy">Zaneprázdněný: %1$s</string>
|
||||
<string name="channel_scheduled">Výsledky naplánovaných úloh</string>
|
||||
<string name="channel_scheduled_failures">Selhání naplánovaných úloh</string>
|
||||
<string name="scheduled_result_public">Naplánovaná úloha má výsledek.</string>
|
||||
<string name="scheduled_failed_public">Naplánovaná úloha selhala.</string>
|
||||
<string name="page_note">Tato odpověď obsahuje stránku: %1$s</string>
|
||||
<string name="page_where">Zobrazíte ji na webu nebo v aplikaci LLeMbas Desktop.</string>
|
||||
<string name="page_untitled">Stránka</string>
|
||||
<string name="reports">Zprávy</string>
|
||||
<string name="report">Zpráva</string>
|
||||
<string name="reports_none">Zatím žádné zprávy. Naplánovaná úloha ji napíše, když vám má co říct.</string>
|
||||
<string name="reports_unsupported">Na této instanci běží LLeMbas, který Zprávy ještě nemá.</string>
|
||||
<string name="report_untitled">Zpráva bez názvu</string>
|
||||
<string name="report_delete_title">Smazat tuto zprávu?</string>
|
||||
<string name="report_delete_line">Zpráva „%1$s“ se smaže natrvalo, i s rozhovorem o ní.</string>
|
||||
<string name="report_mark_read">Označit jako přečtené</string>
|
||||
<string name="report_important">Důležité</string>
|
||||
<string name="report_share">Sdílet</string>
|
||||
<string name="report_reply">Odpovědět</string>
|
||||
<string name="report_chat_title">Zpráva: %1$s</string>
|
||||
<string name="notify_when">Kdy dát vědět</string>
|
||||
<string name="notify_every_run">Při každém běhu</string>
|
||||
<string name="notify_every_run_line">Model napíše zprávu pokaždé, i když nic nenašel.</string>
|
||||
<string name="notify_when_option">Když…</string>
|
||||
<string name="notify_when_line">Model napíše zprávu jen tehdy, když platí tohle.</string>
|
||||
<string name="notify_when_label">Když co?</string>
|
||||
<string name="notify_when_default">něco vyžaduje moji pozornost</string>
|
||||
<string name="notify_never_option">Nikdy</string>
|
||||
<string name="notify_never_line">Žádné zprávy: běhy zůstanou jen v historii úlohy.</string>
|
||||
<string name="notify_when_words">Dá vědět, když: %1$s</string>
|
||||
<string name="run_open_report">Otevřít její zprávu</string>
|
||||
<string name="channel_reports">Zprávy</string>
|
||||
<string name="channel_reports_high">Důležité zprávy</string>
|
||||
<string name="report_new_public">Nová zpráva</string>
|
||||
<string name="schedule_run_again">Spustit znovu</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_allow_always">Vždy povolit</string>
|
||||
<string name="card_deny">Zamítnout</string>
|
||||
<string name="card_deny_reason">Zamítnout a říct proč</string>
|
||||
<string name="plan_approve_edit">Schválit, pokračovat v režimu Upravit</string>
|
||||
<string name="plan_approve_manual">Schválit, pokračovat v režimu Ručně</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="progress_queued">Ve frontě</string>
|
||||
<string name="progress_queued_ahead">Ve frontě: před ním %1$s</string>
|
||||
<string name="progress_waiting_for_model">Čeká se na %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Načítá se %1$s</string>
|
||||
<string name="progress_reading_prompt">Čte se výzva: %1$s / %2$s tokenů (%3$s %%)</string>
|
||||
<string name="progress_reading_prompt_bare">Čte se výzva</string>
|
||||
<string name="progress_thinking">Přemýšlí</string>
|
||||
<string name="progress_writing">Píše: %1$s tok/s</string>
|
||||
<string name="progress_writing_bare">Píše</string>
|
||||
<string name="progress_running_tool">Spouští %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Spouští %1$s</string>
|
||||
<string name="progress_waiting_for_person">Čeká na vás: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Čeká na podagenty: pracuje %1$s</string>
|
||||
<string name="progress_compacting">Shrnuje se konverzace</string>
|
||||
<string name="progress_retrying">Nový pokus za %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Zastaveno</string>
|
||||
<string name="progress_stopped_reason">Zastaveno: %1$s</string>
|
||||
<string name="progress_failed">Selhalo: %1$s</string>
|
||||
<string name="progress_reason_busy">vyřizuje jeden požadavek najednou a právě vyřizuje jiný</string>
|
||||
<string name="progress_reason_slots">všechny jeho sloty jsou obsazené</string>
|
||||
<string name="progress_reason_group">jeho server má teď načtený jiný model</string>
|
||||
<string name="progress_what_approval">povolit %1$s?</string>
|
||||
<string name="progress_what_approval_bare">povolení</string>
|
||||
<string name="progress_what_question">otázka</string>
|
||||
<string name="progress_what_plan">plán</string>
|
||||
<string name="progress_stopped_person">vámi</string>
|
||||
<string name="progress_stopped_steps">limit kroků</string>
|
||||
<string name="progress_stopped_budget">rozpočet</string>
|
||||
<string name="tree_state_working">pracuje</string>
|
||||
<string name="tree_state_waiting">čeká na volný slot</string>
|
||||
<string name="tree_state_finished">dokončený</string>
|
||||
<string name="tree_state_idle">nečinný</string>
|
||||
<string name="tree_state_paused">pozastavený: plný kontext</string>
|
||||
<string name="tree_state_done">hotovo</string>
|
||||
<string name="tree_state_out_of_context">bez kontextu</string>
|
||||
<string name="tree_state_stopped">zastaveno</string>
|
||||
<string name="tree_context">kontext %1$s%%</string>
|
||||
<string name="tree_open_slots">Volná místa: %1$s</string>
|
||||
<string name="subagents_device_cannot">Počítač, na kterém tato konverzace běží, nespouští podagenty: aktualizujte na něm LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s se ptá:</string>
|
||||
<string name="card_subagent_asks">Podagent %1$s (%2$s), %3$s, se ptá:</string>
|
||||
<string name="card_it_says">Model uvádí: %1$s</string>
|
||||
<string name="card_change_before">Upravit to před spuštěním</string>
|
||||
<string name="card_edit_runs">Povolením se spustí to, co je v poli. Znovu se to neporovnává s pravidly této konverzace — napsali jste to vy.</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>
|
||||
@@ -146,6 +354,13 @@
|
||||
<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_language">Jazyk</string>
|
||||
<string name="language_hint">Jen rozhraní. Modely odpovídají v jazyce, ve kterém jim píšete, bez ohledu na toto nastavení.</string>
|
||||
<string name="language_account">Stejný jako můj účet</string>
|
||||
<string name="language_account_is">Stejný jako můj účet: %1$s</string>
|
||||
<string name="language_account_unknown">Z vaší instance zatím nenačteno</string>
|
||||
<string name="language_phone">Jazyk telefonu</string>
|
||||
<string name="language_phone_is">Jazyk telefonu: %1$s</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>
|
||||
@@ -157,6 +372,9 @@
|
||||
<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_model">Model asistenta</string>
|
||||
<string name="assistant_model_default">Výchozí model instance</string>
|
||||
<string name="assistant_model_default_line">Model, se kterým začínají vaše nové konverzace. Je-li na mluvenou otázku příliš pomalý, vyberte níže rychlejší.</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>
|
||||
@@ -168,11 +386,223 @@
|
||||
<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="update_checking">Kontroluje se…</string>
|
||||
<string name="update_available">Je k dispozici %1$s. Klepnutím otevřete stránku vydání.</string>
|
||||
<string name="update_install">Nainstalovat %1$s</string>
|
||||
<string name="update_auto">Hledat nové verze</string>
|
||||
<string name="update_auto_line">Nejvýš jednou denně, při spuštění, se aplikace zeptá vaší instance, které vydání k ní patří (u starší instance si přečte seznam vydání na GitHubu), a upozorněním vám dá vědět, když je k dispozici novější. Nic o vás se nikam jinam neposílá. Ve verzi beta zapnuto, jinak vypnuto.</string>
|
||||
<string name="update_betas">Včetně beta verzí</string>
|
||||
<string name="update_betas_line">Nabízet i testovací verze, nejen vydání. Zapnuto, když je tato aplikace sama beta.</string>
|
||||
<string name="channel_updates">Aktualizace aplikace</string>
|
||||
<string name="update_notice_title">LLeMbas pro Android %1$s</string>
|
||||
<string name="update_notice_text">Je k dispozici novější verze. Klepnutím otevřete stránku vydání.</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="assist_use_screen">Použít obrazovku</string>
|
||||
<string name="assist_screen_both">S vaší další otázkou půjde text obrazovky a snímek obrazovky.</string>
|
||||
<string name="assist_screen_text">S vaší další otázkou půjde text obrazovky.</string>
|
||||
<string name="assist_screen_shot">S vaší další otázkou půjde snímek obrazovky.</string>
|
||||
<string name="assist_quick_summarise">Shrnout</string>
|
||||
<string name="assist_quick_summarise_prompt">Shrň, co je na mé obrazovce.</string>
|
||||
<string name="assist_quick_translate">Přeložit</string>
|
||||
<string name="assist_quick_translate_prompt">Přelož, co je na mé obrazovce, do češtiny.</string>
|
||||
<string name="assist_quick_explain">Vysvětlit</string>
|
||||
<string name="assist_quick_explain_prompt">Vysvětli, co je na mé obrazovce.</string>
|
||||
<string name="assist_continue">Pokračovat v poslední konverzaci</string>
|
||||
<string name="assist_help">Podržením tlačítka napájení otevřete asistenta nad libovolnou aplikací; nebo použijte dlaždici v Rychlém nastavení.</string>
|
||||
<string name="assist_connecting">Připojování…</string>
|
||||
<string name="assist_offline">%1$s není dostupná</string>
|
||||
<string name="assist_no_model">Žádný model</string>
|
||||
<string name="assist_voice_reply_on">Hlasová odpověď je zapnutá</string>
|
||||
<string name="assist_voice_reply_off">Hlasová odpověď je vypnutá</string>
|
||||
<string name="assist_read_aloud">Přečíst nahlas</string>
|
||||
<string name="assist_stop_reading">Přestat číst</string>
|
||||
<string name="assist_answer_in_app">Tato odpověď čeká na vaše rozhodnutí: otevřete ji v aplikaci.</string>
|
||||
<string name="assist_send_now">Odeslat, co jsem řekl</string>
|
||||
<string name="assist_say_it">Řekněte to a odmlčte se</string>
|
||||
<string name="assist_type">Raději psát</string>
|
||||
<string name="assist_writing_down">Zapisuji, co jste řekli…</string>
|
||||
<string name="assist_unlock_to_send">Odemknout a odeslat</string>
|
||||
<string name="assist_question_heard">Otázka zaznamenána</string>
|
||||
<string name="assist_recording_waits_line">Telefon je zamčený. Vaše otázka čeká v tomto telefonu jako nahrávka; nic se neodeslalo. Po odemknutí se odešle vaší instanci, která ji přepíše a odpoví.</string>
|
||||
<string name="assist_locked_line">Telefon je zamčený. Dokud ho neodemknete, nic se neodešle a žádná odpověď se nezobrazí.</string>
|
||||
<string name="assist_conversation">Rozhovor</string>
|
||||
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
|
||||
<string name="assist_conversation_end">Ukončit</string>
|
||||
<string name="assist_stop_words">stop|dost|to je vše|to je všechno|konec|nashledanou|díky to je vše|zrušit|stop stop</string>
|
||||
<string name="assistant_conversation">Pokračovat v mluveném rozhovoru</string>
|
||||
<string name="assistant_conversation_line">Po přečtení mluvené odpovědi asistent znovu poslouchá — dokud neřeknete „stop“, neklepnete na Ukončit nebo pár sekund nic neřeknete. Funguje i se sluchátky.</string>
|
||||
<string name="experimental">Experimentální</string>
|
||||
<string name="wake_experimental_line">Novinka, zatím vyzkoušená jen na několika telefonech. Může frázi přeslechnout, spustit se omylem, nebo vás uslyšet a asistenta přesto neotevřít.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimentální: samočinné poslouchání po otevření asistenta, rozpoznání, že jste domluvili, a mluvený rozhovor jsou nové a zatím nefungují dobře na každém telefonu. Napsat otázku a tlačítko mikrofonu fungují vždy.</string>
|
||||
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Asistent › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
|
||||
<string name="channel_wake">Budicí slovo</string>
|
||||
<string name="wake_word">Budicí slovo</string>
|
||||
<string name="wake_word_listen">Naslouchat budicímu slovu</string>
|
||||
<string name="wake_word_line">Ve výchozím stavu vypnuto. Řekněte frázi a asistent se otevře a poslouchá, nad jakoukoli aplikací na obrazovce.</string>
|
||||
<string name="wake_word_unavailable">V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má.</string>
|
||||
<string name="wake_phrase_line">Tohle říkáte, potom krátká pauza: platí, až když zmlknete. Anglicky, ať je aplikace v jakémkoli jazyce: modul zná jen anglickou řeč.</string>
|
||||
<string name="wake_greeting">Oslovení</string>
|
||||
<string name="wake_name">Jméno</string>
|
||||
<string name="wake_name_google_line">Ozve se i telefon nebo reproduktor Google poblíž.</string>
|
||||
<string name="wake_sensitivity">Citlivost</string>
|
||||
<string name="wake_sensitivity_low">Nízká</string>
|
||||
<string name="wake_sensitivity_low_line">Omylem se spustí nejméně často. Frázi možná budete muset říct zřetelněji nebo dvakrát.</string>
|
||||
<string name="wake_sensitivity_normal">Normální</string>
|
||||
<string name="wake_sensitivity_normal_line">Vlastní nastavení modulu.</string>
|
||||
<string name="wake_sensitivity_high">Vysoká</string>
|
||||
<string name="wake_sensitivity_high_line">Slyší vás nejsnáze, i z větší dálky. Omylem se spustí častěji.</string>
|
||||
<string name="wake_test">Vyzkoušet budicí slovo</string>
|
||||
<string name="wake_test_line">Deset sekund ukazuje, zda je vaši frázi slyšet, bez otevření asistenta.</string>
|
||||
<string name="wake_test_say">Teď řekněte „%1$s“ a udělejte pauzu…</string>
|
||||
<string name="wake_test_heard">Slyšel jsem ji</string>
|
||||
<string name="wake_test_missed">Za deset sekund jsem ji neslyšel. Zkuste to blíž k telefonu, ve chvíli většího ticha nebo s vyšší citlivostí.</string>
|
||||
<string name="wake_test_off">Nejdřív zapněte budicí slovo.</string>
|
||||
<string name="wake_screen_only">Jen při zapnuté obrazovce</string>
|
||||
<string name="wake_screen_only_line">Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie.</string>
|
||||
<string name="wake_battery">Nechat běžet na pozadí</string>
|
||||
<string name="wake_battery_line">Některé telefony (Samsung, Xiaomi, Huawei, OnePlus a další) kvůli baterii zastavují aplikace na pozadí, a s nimi i budicí slovo. Zde vyjměte LLeMbas z optimalizace baterie; dontkillmyapp.com vysvětluje nastavení vašeho telefonu.</string>
|
||||
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět oznámení. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.</string>
|
||||
<string name="wake_listening_for">Naslouchám frázi „%1$s“</string>
|
||||
<string name="wake_off">Budicí slovo neposlouchá</string>
|
||||
<string name="wake_tap_to_start">Klepnutím ho znovu spustíte. Pokud se Android zeptá, povolte mikrofon.</string>
|
||||
<string name="wake_starting">Budicí slovo se spouští…</string>
|
||||
<string name="wake_paused_silent">Budicí slovo nic neslyší: mikrofon používá jiná aplikace, nebo je v telefonu vypnutý</string>
|
||||
<string name="wake_failed_no_engine">Budicí slovo nefunguje: toto sestavení nemá modul</string>
|
||||
<string name="wake_failed_model">Budicí slovo nefunguje: jeho model se v tomto telefonu nepodařilo rozbalit</string>
|
||||
<string name="wake_failed_engine">Budicí slovo nefunguje: modul se nespustil</string>
|
||||
<string name="wake_failed_microphone">Budicí slovo nefunguje: mikrofon se nespustil</string>
|
||||
<string name="wake_failed_line">Neposlouchá. Zkusí to znovu samo.</string>
|
||||
<string name="wake_notification_line">Dokud ji neřeknete, nic neopustí telefon.</string>
|
||||
<string name="wake_paused_screen">Budicí slovo pozastaveno: obrazovka je zhasnutá</string>
|
||||
<string name="wake_paused_battery">Budicí slovo pozastaveno: je zapnutý úsporný režim</string>
|
||||
<string name="wake_paused_assistant">Budicí slovo je pozastaveno, dokud je asistent otevřený</string>
|
||||
<string name="wake_paused_microphone">Budicí slovo pozastaveno: LLeMbas nemá povolený mikrofon</string>
|
||||
<string name="wake_stop">Přestat naslouchat</string>
|
||||
<string name="wake_heard">Slyšel jsem vás. Klepněte a ptejte se.</string>
|
||||
<string name="channel_wake_heard">Budicí slovo zaznělo</string>
|
||||
<string name="wake_heard_line">LLeMbas se umí sám otevřít nad jinými aplikacemi jen jako aplikace digitálního asistenta v telefonu.</string>
|
||||
<string name="wake_not_assistant">LLeMbas není aplikací digitálního asistenta</string>
|
||||
<string name="wake_not_assistant_line">Budicí slovo proto nemůže otevřít asistenta nad jinými aplikacemi: dostanete oznámení, na které klepnete. Chcete-li otevírat hlasem kdekoli, klepněte sem a vyberte LLeMbas jako aplikaci digitálního asistenta.</string>
|
||||
<string name="wake_last">Poslední probuzení</string>
|
||||
<string name="wake_last_none">Frázi zatím neslyšel.</string>
|
||||
<string name="wake_out_opened">Otevřel asistenta.</string>
|
||||
<string name="wake_out_no_sheet">Požádal Android o otevření asistenta; neodmítl, ale panel se neobjevil.</string>
|
||||
<string name="wake_out_not_connected">Android neměl LLeMbas připojený jako asistenta, proto panel nemohl otevřít.</string>
|
||||
<string name="wake_out_refused">Android odmítl otevřít asistenta: %1$s</string>
|
||||
<string name="wake_out_activity">Místo toho ho otevřel jako obrazovku aplikace.</string>
|
||||
<string name="wake_out_notification">Místo toho poslal oznámení, na které je třeba klepnout.</string>
|
||||
<string name="wake_out_tested">Slyšeno při zkoušce: nebylo co otevírat.</string>
|
||||
<string name="wake_role_held">LLeMbas byl aplikací digitálního asistenta.</string>
|
||||
<string name="wake_role_not_held">LLeMbas nebyl aplikací digitálního asistenta.</string>
|
||||
<string name="wake_link_never">Android od spuštění aplikace asistenta nepřipojil.</string>
|
||||
<string name="wake_link_ready">Android připojil asistenta v %1$s.</string>
|
||||
<string name="wake_link_shutdown">Android ho odpojil v %1$s.</string>
|
||||
<string name="wake_link_later">Android ho znovu připojil v %1$s.</string>
|
||||
<string name="wake_sheet_ms">Panel se zobrazil po %1$s ms.</string>
|
||||
<string name="wake_no_recognizers">Tento telefon nemá rozpoznávače hlasu, proto na něm Android nespouští službu hlasového asistenta.</string>
|
||||
<string name="wake_not_active">LLeMbas byl vybrán jako aplikace digitálního asistenta, ale Android ho nepoužíval jako hlasového asistenta.</string>
|
||||
<string name="wake_waited">Chvíli čekal, až ho Android připojí.</string>
|
||||
<string name="wake_show_failed">Android oznámil, že panel asistenta nedokázal zobrazit.</string>
|
||||
<string name="wake_assistant_inactive">Android právě nepoužívá LLeMbas jako hlasového asistenta</string>
|
||||
<string name="wake_assistant_inactive_line">Vyberte LLeMbas jako aplikaci digitálního asistenta znovu: klepněte sem, zvolte jinou aplikaci a potom LLeMbas. Do té doby ho dlouhé stisknutí otevírá jako běžnou obrazovku a budicí slovo může poslat jen oznámení.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas je asistent, ale Android ho právě nemá připojeného</string>
|
||||
<string name="wake_assistant_unbound_line">Dokud ho nepřipojí, budicí slovo nemůže panel otevřít samo. Klepnutím otevřete systémové nastavení asistenta: vyberte jinou aplikaci a potom znovu LLeMbas, tím se připojí.</string>
|
||||
<string name="wake_heard_could_not">Nepodařilo se otevřít samo — klepněte a ptejte se</string>
|
||||
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
|
||||
<string name="wake_resume_line">Telefon se restartoval. Klepnutím znovu spustíte naslouchání.</string>
|
||||
<string name="assist_notifications">Shrnout má oznámení</string>
|
||||
<string name="assist_notifications_prompt">Shrň moje oznámení: co potřebuje mou pozornost?</string>
|
||||
<string name="assist_notifications_phrases">moje oznámení|má oznámení|mých oznámení|moje notifikace</string>
|
||||
<string name="notification_summaries">Shrnutí oznámení</string>
|
||||
<string name="notification_summaries_switch">Dovolit asistentovi číst má oznámení, když o to požádám</string>
|
||||
<string name="notification_summaries_line">Řekněte „shrň moje oznámení“, nebo klepněte na tlačítko v asistentovi.</string>
|
||||
<string name="notification_summaries_unavailable">V tomto sestavení není. Čtení oznámení vyžaduje sestavení LLeMbas „notifications“, protože Google Play Protect blokuje instalaci aplikace mimo Obchod Play, která je umí číst. Je to stejná aplikace se stejným podpisem: na stránce vydání se soubor končící na -notifications.apk nainstaluje přes tuto.</string>
|
||||
<string name="update_notifications_manual">Toto je sestavení „notifications“: aktualizaci nainstalujte ze stránky vydání, soubor končící na -notifications.apk.</string>
|
||||
<string name="notification_access">Přístup k oznámením</string>
|
||||
<string name="notification_access_on">Uděleno. Přepínač Androidu je v systémovém nastavení.</string>
|
||||
<string name="notification_access_off">Zatím neuděleno. Klepnutím otevřete přepínač Androidu pro LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Ve výchozím stavu vypnuto. Když požádáte, text oznámení, která jsou v telefonu právě teď (aplikace, název, text), půjde s touto jedinou otázkou na vaši instanci a její model. Dřív se nic nečte, aplikace si nic neponechá a při zamčeném telefonu se nečte nic. Přístup k oznámením v Androidu dovolí aplikaci vidět každé oznámení, proto je na vás, zda ho dáte a zase vezmete.</string>
|
||||
<string name="nav_app">Navigační aplikace</string>
|
||||
<string name="nav_app_auto">Ta, která je nainstalovaná</string>
|
||||
<string name="nav_app_google">Mapy Google</string>
|
||||
<string name="nav_app_osmand">OsmAnd</string>
|
||||
<string name="nav_app_ask">Pokaždé se zeptat</string>
|
||||
<string name="nav_app_not_installed">Není nainstalovaná</string>
|
||||
<string name="osmand_info">Ptát se OsmAnd na trasu</string>
|
||||
<string name="osmand_info_line">Umožní „přidat zastávku“ a hledání v okolí i u trasy nastavené přímo v OsmAnd: LLeMbas se OsmAnd zeptá, kde jste a kam trasa vede. Nejdřív LLeMbas povolte v OsmAnd (připojené aplikace, s polohou); OsmAnd dá vědět, pokud povoleno není.</string>
|
||||
<string name="phone_actions_line">Model může nabídnout, že v telefonu něco udělá — nastaví budík, přidá událost, připraví zprávu, spustí trasu. Nic se nestane, dokud neklepnete na Provést na jeho kartě, a nikdy při zamčeném telefonu. Mapy Google spustí trasu s několika zastávkami, ale do běžící trasy zastávku nepřidají ani je nelze zastavit; OsmAnd to umí.</string>
|
||||
<string name="action_card_title">Udělat to v telefonu?</string>
|
||||
<string name="action_do">Provést</string>
|
||||
<string name="action_running">Provádím…</string>
|
||||
<string name="action_unlock">Nejdřív odemkněte telefon, pak klepněte na Provést.</string>
|
||||
<string name="action_failed">Nepovedlo se: %1$s</string>
|
||||
<string name="nav_app_pick">Ve které mapové aplikaci?</string>
|
||||
<string name="action_google_add_stop">Mapy Google nepřidají zastávku do běžící trasy: spustí trasu znovu, přes zastávku.</string>
|
||||
<string name="action_google_no_stop">Mapy Google nelze zastavit zvenčí: trasu ukončete v nich.</string>
|
||||
<string name="action_line_clock">Nastaví to aplikace Hodiny.</string>
|
||||
<string name="action_line_calendar">Otevře se kalendář s vyplněnou událostí; uložíte ji vy.</string>
|
||||
<string name="action_line_draft">Otevře koncept; odešlete ho sami.</string>
|
||||
<string name="action_line_dial">Otevře se vytáčení s číslem; hovor zahájíte vy.</string>
|
||||
<string name="action_line_map">Trasu převezme %1$s.</string>
|
||||
<string name="action_line_now">Stane se hned.</string>
|
||||
<string name="action_line_settings">Otevře nastavení; změníte ho vy.</string>
|
||||
<string name="action_line_automation">Spustí vaši automatizaci (Tasker, pokud není uvedena jiná aplikace).</string>
|
||||
<string name="action_line_open">Otevře to.</string>
|
||||
<string name="assist_recogniser_failed">Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup.</string>
|
||||
<string name="assistant_listens">Začít poslouchat, když se asistent otevře</string>
|
||||
<string name="voice_input">Hlasový vstup</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Převod řeči na text vaší instance, přes server. Nahrávka jde na vaši instanci a nikam jinam.</string>
|
||||
<string name="voice_input_phone">Telefon (Google nebo systémový)</string>
|
||||
<string name="voice_input_phone_line">Vlastní rozpoznávání řeči v telefonu. Slova se objevují, jak mluvíte; nahrávka jde tam, kam ji to rozpoznávání pošle.</string>
|
||||
<string name="voice_input_phone_none">Tento telefon nemá vlastní rozpoznávání řeči.</string>
|
||||
<string name="voice_input_hint">Používá ho asistent i mikrofon v konverzaci. S LLeMbas asistent ukazuje slova s malým zpožděním a pauza je odešle, konverzace je zapíše, když přestanete; s rozpoznáváním v telefonu se objevují, jak mluvíte.</string>
|
||||
<string name="share_sending">Odesílá se do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Podívejte se na tohle.</string>
|
||||
<string name="share_ask_hint">Co s tím má LLeMbas udělat? (nepovinné)</string>
|
||||
<string name="widget_hint">Zeptejte se na cokoli</string>
|
||||
<string name="directory_places">Místa na tomto zařízení</string>
|
||||
<string name="directory_last_used">Naposledy zde použitý: %1$s. Nový chat v této složce začne na něm, pokud nevyberete jiný.</string>
|
||||
<string name="directory_refused">Zařízení tu relaci neotevře.</string>
|
||||
<string name="directory_up">O úroveň výš</string>
|
||||
<string name="directory_all_places">Všechna místa</string>
|
||||
<string name="directory_not_trusted">Na zařízení není důvěryhodné</string>
|
||||
<string name="directory_empty">Nejsou tu žádné složky.</string>
|
||||
<string name="directory_no_places">Toto zařízení nenabízí žádné složky: jeho vzdálené kořeny jsou prázdné nebo chybějí.</string>
|
||||
<string name="directory_browse">Procházet</string>
|
||||
<string name="directory_path">Úplná cesta</string>
|
||||
<string name="directory_choose">Vybrat</string>
|
||||
<string name="directory_no_listing">Adresáře tohoto zařízení teď nelze vypsat. Napište cestu níže.</string>
|
||||
<string name="model">Model</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Konverzace</string>
|
||||
<string name="schedule_chat_line">Běží na tomto serveru jako chat: s nástroji serveru (vyhledávání, vaše soubory zde, paměť) a na modelu určeném pro plánování.</string>
|
||||
<string name="schedule_agentic">Agentní</string>
|
||||
<string name="schedule_agentic_line">Běží na jednom z vašich počítačů, v jedné složce na něm, jako agent: s nástroji agenta na tom počítači — jeho soubory a jeho shellem — v rámci vlastních omezení počítače. Patří k tomu počítači a složce.</string>
|
||||
<string name="schedule_agentic_unavailable">Žádný z vašich počítačů teď nepřijímá naplánovanou práci. Propojte některý a zapněte „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nepřijímá plánovanou práci</string>
|
||||
<string name="schedule_computer_hint">Počítač to musí povolit: „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). Když v čase spuštění není propojen, spuštění na něj počká; pokud se nevrátí, než čas spuštění uplyne, spuštění se zaznamená jako zmeškané a dozvíte se o tom.</string>
|
||||
<string name="schedule_computer_gone">počítač, který už není přihlášen</string>
|
||||
<string name="schedule_folder">Složka na počítači</string>
|
||||
<string name="schedule_agent_mode">Režim</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, pokud nezvolíte jinak; Auto spouští příkazy bez ptaní. Počítač ho může snížit.</string>
|
||||
<string name="schedule_approval_wait">Schválení čeká (minuty)</string>
|
||||
<string name="schedule_approval_wait_hint">Příkaz, který spuštění potřebuje schválit, přijde do telefonu jako karta. Pokud do té doby nebude zodpovězen, počítá se jako zamítnutý.</string>
|
||||
<string name="schedule_watch_command_hint">Volitelné, na počítači. Spustí se ve složce před každým spuštěním; když je jeho výstup stejný jako minule, spuštění tam skončí. Příkaz, na který by se režim ptal, se odmítne.</string>
|
||||
<string name="schedule_watch_timeout">Příkaz může trvat (sekundy)</string>
|
||||
<string name="schedule_watch_timeout_hint">Pak se zastaví a spuštění selže.</string>
|
||||
<string name="schedule_chat_drops_watch">Tato úloha sleduje příkaz na svém počítači. Jako úloha typu Chat už ne: spustí se pokaždé.</string>
|
||||
<string name="schedule_folder_model">Obvyklý model složky</string>
|
||||
<string name="schedule_folder_model_hint">Obvyklý model složky je ten, který jste v té složce na tom počítači použili naposledy — počítač si ho pamatuje a každé spuštění se ho na něj zeptá — nebo váš výchozí model, pokud žádný není. Model vybraný zde je modelem spuštění, ať je model složky jakýkoli. Spuštění nikdy nemění model složky.</string>
|
||||
<string name="schedule_first_free_model">První volný z vašich modelů pro plánování</string>
|
||||
<string name="run_model_directory">obvyklý model složky</string>
|
||||
<string name="run_model_default">váš výchozí model</string>
|
||||
<string name="run_model_session">vlastní model konverzace</string>
|
||||
<string name="widget_speak">Mluvit</string>
|
||||
<string name="widget_description">Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.</string>
|
||||
<string name="shortcut_last">Poslední chat</string>
|
||||
</resources>
|
||||
@@ -14,10 +14,7 @@
|
||||
<string name="signin_too_old">Auf dieser Instanz läuft ein älteres LLeMbas. Diese App braucht LLeMbas 2.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">Noch keine Agent-Chats. Starten Sie einen mit „Neuer Agent-Chat“ auf einem Gerät, das mit dieser Instanz verknüpft ist.</string>
|
||||
<string name="new_agent_chat">Neuer Agent-Chat</string>
|
||||
<string name="agent_device">Gerät</string>
|
||||
<string name="agent_no_device">Gerade ist kein Gerät verknüpft. Starten Sie `lembas service` auf einem Computer, der bei dieser Instanz angemeldet ist, und kommen Sie dann zurück.</string>
|
||||
@@ -26,6 +23,28 @@
|
||||
<string name="empty_chat">Worüber sprechen wir?</string>
|
||||
<string name="loading_line">Lembas wird gebacken…</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
<string name="archived">Archiviert</string>
|
||||
<string name="archived_restore">Chat wiederherstellen</string>
|
||||
<string name="archived_none">Keine archivierten Chats.</string>
|
||||
<string name="memory">Gedächtnis</string>
|
||||
<string name="memory_intro">Was sich Modelle über Sie merken</string>
|
||||
<string name="memory_none">Noch nichts. Ein Modell mit dem Gedächtniswerkzeug ergänzt dies, wenn Sie ihm etwas Merkenswertes sagen.</string>
|
||||
<string name="memory_remember">Merken</string>
|
||||
<string name="memory_label">Was diese Erinnerung besagt</string>
|
||||
<string name="memory_hint">Etwas Merkenswertes</string>
|
||||
<string name="memory_group">Datengruppe</string>
|
||||
<string name="memory_forget">Vergessen</string>
|
||||
<string name="memory_by_model">Modell</string>
|
||||
<string name="chats_pinned">Angeheftete Chats</string>
|
||||
<string name="chat_pin">Chat anheften</string>
|
||||
<string name="chat_unpin">Chat loslösen</string>
|
||||
<string name="folder_move">In Ordner verschieben</string>
|
||||
<string name="folder_none">Kein Ordner</string>
|
||||
<string name="folder_new">Neuer Ordner</string>
|
||||
<string name="folder_name">Ordnername</string>
|
||||
<string name="folder_rename">Ordner umbenennen</string>
|
||||
<string name="folder_delete">Ordner löschen</string>
|
||||
<string name="folder_delete_confirm">Den Ordner „%1$s“ löschen? Die Chats darin bleiben erhalten.</string>
|
||||
<string name="delete">Löschen</string>
|
||||
<string name="edit">Bearbeiten</string>
|
||||
<string name="regenerate">Neu generieren</string>
|
||||
@@ -43,6 +62,8 @@
|
||||
<string name="attach_take_photo">Foto aufnehmen</string>
|
||||
<string name="attach_choose_photos">Fotos auswählen</string>
|
||||
<string name="attach_choose_files">Dateien auswählen</string>
|
||||
<string name="image_generate">Bilder generieren</string>
|
||||
<string name="image_generated">Das generierte Bild</string>
|
||||
<string name="copy_message">Nachricht kopieren</string>
|
||||
<string name="copied">Kopiert.</string>
|
||||
<string name="rename_chat">Chat umbenennen</string>
|
||||
@@ -79,11 +100,18 @@
|
||||
<string name="ctx_since">Seit der letzten Antwort</string>
|
||||
<string name="ctx_buffer">Puffer für die Verdichtung</string>
|
||||
<string name="ctx_free">Freier Platz</string>
|
||||
<string name="outputs_empty">In diesem Chat wurde noch keine Datei geschrieben.</string>
|
||||
<string name="tasks_empty">Im Hintergrund läuft nichts. Helfer, Befehle und die Mitglieder eines Teams erscheinen hier, solange sie arbeiten.</string>
|
||||
<string name="tasks_empty">Im Hintergrund läuft nichts. Subagenten, Befehle und die Mitglieder eines Teams erscheinen hier, solange sie arbeiten.</string>
|
||||
<string name="tasks_none_running">Nichts läuft.</string>
|
||||
<string name="agents_one_working">1 Agent arbeitet</string>
|
||||
<string name="agents_n_working">%1$s Agenten arbeiten</string>
|
||||
<string name="tasks_running">Läuft</string>
|
||||
<string name="tasks_finished">Beendet</string>
|
||||
<string name="tasks_n_running">%1$s laufen</string>
|
||||
<string name="tasks_nested">%1$s darunter</string>
|
||||
<string name="task_subagent">Subagent</string>
|
||||
<string name="task_command">Befehl</string>
|
||||
<string name="task_member">Teammitglied</string>
|
||||
<string name="activity_until_compact">%1$s bis zum automatischen Zusammenfassen</string>
|
||||
<string name="activity_compact_off">Automatisches Zusammenfassen ist aus.</string>
|
||||
<string name="activity_compact">Zusammenfassen</string>
|
||||
<string name="agents_n_queued">%1$s in der Warteschlange</string>
|
||||
<string name="agents_n_waiting">%1$s warten</string>
|
||||
<string name="agents_n_finished">%1$s beendet</string>
|
||||
@@ -100,28 +128,208 @@
|
||||
<string name="agent_stop_confirm">%1$s stoppen? Was bisher getan wurde, bleibt.</string>
|
||||
<string name="agent_nothing_yet">Noch nichts gesagt.</string>
|
||||
<string name="agent_machine">Vom System</string>
|
||||
<string name="team_size">Team: %1$s von %2$s Agenten</string>
|
||||
<string name="team_size">Team: %1$s von %2$s Subagenten</string>
|
||||
<string name="team_room">Raum</string>
|
||||
<string name="room_empty">Im Raum wurde noch nichts gesagt.</string>
|
||||
<string name="room_report">Bericht</string>
|
||||
<string name="team_agents">Agenten</string>
|
||||
<string name="team_fewest">Mindestens</string>
|
||||
<string name="team_most">Höchstens</string>
|
||||
<string name="team_hint">Der eigene Agent eingeschlossen. Bei mehr als einem kann er Mitglieder hinzufügen, die die Arbeit machen, während er sie leitet.</string>
|
||||
<string name="team_chip">Agenten %1$s–%2$s</string>
|
||||
<string name="team_agents">Subagenten</string>
|
||||
<string name="team_min">Min</string>
|
||||
<string name="team_max">Max</string>
|
||||
<string name="team_range">Min %1$s · Max %2$s</string>
|
||||
<string name="team_hint">Die Zahlen zählen den eigenen Agenten dieses Chats mit: 1 ist der Agent allein, ohne Subagenten, und Max 4 ist der Agent mit bis zu 3 Subagenten, die er leitet.</string>
|
||||
<string name="team_chip">Subagenten: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Dieses Modell beantwortet nur eine Anfrage auf einmal: Subagenten brauchen ein anderes Modell auf einem anderen Server, im Chat genannt.</string>
|
||||
<string name="thinking_switch">Vor der Antwort nachdenken</string>
|
||||
<string name="effort_level">Denkaufwand: %1$s</string>
|
||||
<string name="level_off">aus</string>
|
||||
<string name="level_default">Standard</string>
|
||||
<string name="chats_open">Chats öffnen</string>
|
||||
<string name="chats_search">Chats durchsuchen</string>
|
||||
<string name="chats_today">Heute</string>
|
||||
<string name="chats_earlier">Früher</string>
|
||||
<string name="chats_agents">Agenten-Chats</string>
|
||||
<string name="chats_found_in_messages">In den Nachrichten</string>
|
||||
<string name="chats_none_found">Kein Chat hat das im Titel.</string>
|
||||
<string name="clear">Leeren</string>
|
||||
<string name="composer_hint_agent">Sag dem Agenten, was er tun soll</string>
|
||||
<string name="tune">Optionen</string>
|
||||
<string name="effort">Aufwand</string>
|
||||
<string name="thinking_switch_hint">Langsamer, und besser bei schwierigen Fragen.</string>
|
||||
<string name="plan_first">Erst planen</string>
|
||||
<string name="plan_first_hint">Das Modell schreibt einen Plan, den du genehmigst, bevor es handelt.</string>
|
||||
<string name="agent_mode">Modus</string>
|
||||
<string name="agent_greeting">Was soll der Agent tun?</string>
|
||||
<string name="agent_runs_on">Läuft auf %1$s, in %2$s</string>
|
||||
<string name="agent_directory_default">seinem ersten Ordner</string>
|
||||
<string name="kind_chat">Chat</string>
|
||||
<string name="kind_agent">Agent-Chat</string>
|
||||
<string name="kind_chat_line">Mit einem Modell sprechen: Fragen, Texte, Dateien, die Sie anhängen.</string>
|
||||
<string name="kind_agent_line">Arbeitet auf einem verknüpften Computer: liest, schreibt und führt Befehle in einem Ordner aus.</string>
|
||||
<string name="agent_link_title">Zuerst einen Computer verknüpfen</string>
|
||||
<string name="agent_link_lede">Agent-Chats laufen auf einem Rechner mit der LLeMbas CLI, die bei dieser Instanz angemeldet und verknüpft ist. Derzeit ist keiner verknüpft.</string>
|
||||
<string name="agent_link_install">Installieren Sie die LLeMbas CLI darauf:</string>
|
||||
<string name="agent_link_login">Melden Sie ihn bei dieser Instanz an und bestätigen Sie den angezeigten Code im Browser, der sich öffnet:</string>
|
||||
<string name="agent_link_service">Um von hier aus Agent-Chats darauf auszuführen, erlauben Sie es in ihrer Konfiguration (~/.config/lembas/config.yaml) und starten Sie den Dienst:</string>
|
||||
<string name="agent_link_dials_out">Sie verbindet sich von selbst mit dieser Instanz; auf Ihrem Rechner lauscht nichts. Sie entscheidet, welche Verzeichnisse und Modi Fernarbeit nutzen darf, egal was hier verlangt wird.</string>
|
||||
<string name="agent_link_check">Erneut prüfen</string>
|
||||
<string name="model_choose">Modell wählen</string>
|
||||
<string name="model_in_use">In Verwendung</string>
|
||||
<string name="model_sees_images">Sieht Bilder</string>
|
||||
<string name="model_uses_tools">Nutzt Werkzeuge</string>
|
||||
<string name="model_context">%1$s Kontext</string>
|
||||
<string name="model_thinking_switchable">Nachdenken an oder aus</string>
|
||||
<string name="model_levels">Aufwand: %1$s</string>
|
||||
<string name="code">Code</string>
|
||||
<string name="copy_code">Code kopieren</string>
|
||||
<string name="select_text">Text auswählen</string>
|
||||
<string name="tools_used">%1$s Werkzeuge genutzt</string>
|
||||
<string name="suggest_explain">Erkläre</string>
|
||||
<string name="suggest_explain_line">einfach, wie etwas funktioniert</string>
|
||||
<string name="suggest_write">Schreibe</string>
|
||||
<string name="suggest_write_line">eine E-Mail, eine Notiz oder einen Beitrag</string>
|
||||
<string name="suggest_plan">Plane</string>
|
||||
<string name="suggest_plan_line">eine Reise, eine Woche oder ein Projekt</string>
|
||||
<string name="suggest_check">Prüfe</string>
|
||||
<string name="suggest_check_line">einen Text auf Fehler und Ton</string>
|
||||
<string name="instance_in_use">In Verwendung</string>
|
||||
<string name="notification_settings">Benachrichtigungseinstellungen</string>
|
||||
<string name="notification_settings_hint">Welche Arten ankommen und wie: Antworten, Fragen, geplante Ergebnisse und Fehler.</string>
|
||||
<string name="scheduled">Geplant</string>
|
||||
<string name="scheduled_empty">Nichts ist geplant. Bitte um etwas, das jeden Morgen geschehen soll, oder einmal nächste Woche.</string>
|
||||
<string name="scheduled_unsupported">Diese Instanz bietet noch keine geplanten Aufgaben. Sie kommen mit einem neueren LLeMbas auf dem Server.</string>
|
||||
<string name="schedule_new">Neuer Zeitplan</string>
|
||||
<string name="schedule_edit">Zeitplan bearbeiten</string>
|
||||
<string name="schedule_next">Nächstes Mal: %1$s</string>
|
||||
<string name="schedule_paused">Pausiert</string>
|
||||
<string name="schedule_pause">Pausieren</string>
|
||||
<string name="schedule_resume">Fortsetzen</string>
|
||||
<string name="schedule_run_now">Jetzt ausführen</string>
|
||||
<string name="schedule_started">Gestartet. Das Ergebnis erscheint im Verlauf.</string>
|
||||
<string name="schedule_next_runs">Nächste Läufe</string>
|
||||
<string name="schedule_history">Verlauf</string>
|
||||
<string name="schedule_no_runs">Er ist noch nicht gelaufen.</string>
|
||||
<string name="schedule_model">Modell: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Diesen Zeitplan löschen? Seine bisherigen Ergebnisse bleiben in ihren Chats.</string>
|
||||
<string name="schedule_words_hint">Sag in eigenen Worten, wann und was. Bevor etwas gespeichert wird, siehst du, wie es verstanden wurde.</string>
|
||||
<string name="schedule_words_example">Jeden Werktag um 7:30 die Nachrichten über erneuerbare Energie zusammenfassen</string>
|
||||
<string name="schedule_preview">Vorschau</string>
|
||||
<string name="schedule_understood">Verstanden als</string>
|
||||
<string name="notify_always">Meldet sich jedes Mal</string>
|
||||
<string name="notify_matters">Meldet sich, wenn es wichtig ist</string>
|
||||
<string name="notify_never">Meldet sich nie</string>
|
||||
<string name="run_ok">Fertig</string>
|
||||
<string name="run_silent">Nichts Neues</string>
|
||||
<string name="run_unchanged">Unverändert</string>
|
||||
<string name="schedule_computer">Computer</string>
|
||||
<string name="schedule_computer_away">gerade nicht verbunden</string>
|
||||
<string name="schedule_watching">Nur wenn sich diese Seite ändert</string>
|
||||
<string name="schedule_watching_command">Nur wenn sich die Ausgabe dieses Befehls ändert</string>
|
||||
<string name="run_failed">Fehlgeschlagen</string>
|
||||
<string name="run_missed">Verpasst ×%1$s</string>
|
||||
<string name="run_skipped">Übersprungen</string>
|
||||
<string name="run_waiting">Wartet auf ein Modell</string>
|
||||
<string name="run_waiting_computer">Wartet auf den Computer</string>
|
||||
<string name="run_running">Läuft</string>
|
||||
<string name="run_model_instead">%1$s statt %2$s</string>
|
||||
<string name="run_retry_at">Neuer Versuch um %1$s</string>
|
||||
<string name="run_result">Ergebnis</string>
|
||||
<string name="run_no_text">Dieser Lauf hat keinen Text hinterlassen.</string>
|
||||
<string name="run_open_chat">Seinen Chat öffnen</string>
|
||||
<string name="mode_fresh">Jedes Mal ein neuer Chat</string>
|
||||
<string name="mode_continue">Ein Chat, der wächst</string>
|
||||
<string name="schedule_models">Modelle für geplante Aufgaben</string>
|
||||
<string name="schedule_models_hint">Geplante Aufgaben nehmen das erste davon, das frei ist, in dieser Reihenfolge. Entfernen Sie den Haken, um eines auszulassen.</string>
|
||||
<string name="model_free">Jetzt frei</string>
|
||||
<string name="model_busy">Belegt: %1$s</string>
|
||||
<string name="channel_scheduled">Geplante Ergebnisse</string>
|
||||
<string name="channel_scheduled_failures">Geplante Fehler</string>
|
||||
<string name="scheduled_result_public">Eine geplante Aufgabe hat ein Ergebnis.</string>
|
||||
<string name="scheduled_failed_public">Eine geplante Aufgabe ist fehlgeschlagen.</string>
|
||||
<string name="page_note">Diese Antwort hat eine Seite: %1$s</string>
|
||||
<string name="page_where">Öffne sie im Web oder in LLeMbas Desktop, um sie zu sehen.</string>
|
||||
<string name="page_untitled">Seite</string>
|
||||
<string name="reports">Berichte</string>
|
||||
<string name="report">Bericht</string>
|
||||
<string name="reports_none">Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie dir etwas zu sagen hat.</string>
|
||||
<string name="reports_unsupported">Auf dieser Instanz läuft ein LLeMbas, das noch keine Berichte hat.</string>
|
||||
<string name="report_untitled">Bericht ohne Titel</string>
|
||||
<string name="report_delete_title">Diesen Bericht löschen?</string>
|
||||
<string name="report_delete_line">„%1$s“ wird endgültig gelöscht, samt der Unterhaltung darüber.</string>
|
||||
<string name="report_mark_read">Als gelesen markieren</string>
|
||||
<string name="report_important">Wichtig</string>
|
||||
<string name="report_share">Teilen</string>
|
||||
<string name="report_reply">Antworten</string>
|
||||
<string name="report_chat_title">Bericht: %1$s</string>
|
||||
<string name="notify_when">Benachrichtigen, wenn</string>
|
||||
<string name="notify_every_run">Bei jedem Lauf</string>
|
||||
<string name="notify_every_run_line">Das Modell schreibt jedes Mal einen Bericht, auch wenn nichts gefunden wurde.</string>
|
||||
<string name="notify_when_option">Wenn…</string>
|
||||
<string name="notify_when_line">Das Modell schreibt nur dann einen Bericht, wenn das zutrifft.</string>
|
||||
<string name="notify_when_label">Wenn was?</string>
|
||||
<string name="notify_when_default">etwas braucht meine Aufmerksamkeit</string>
|
||||
<string name="notify_never_option">Nie</string>
|
||||
<string name="notify_never_line">Keine Berichte: Läufe bleiben nur im Verlauf der Aufgabe.</string>
|
||||
<string name="notify_when_words">Meldet sich, wenn: %1$s</string>
|
||||
<string name="run_open_report">Zugehörigen Bericht öffnen</string>
|
||||
<string name="channel_reports">Berichte</string>
|
||||
<string name="channel_reports_high">Wichtige Berichte</string>
|
||||
<string name="report_new_public">Neuer Bericht</string>
|
||||
<string name="schedule_run_again">Erneut ausführen</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_allow_always">Immer erlauben</string>
|
||||
<string name="card_deny">Ablehnen</string>
|
||||
<string name="card_deny_reason">Ablehnen und begründen</string>
|
||||
<string name="plan_approve_edit">Bestätigen, weiter im Modus Bearbeiten</string>
|
||||
<string name="plan_approve_manual">Bestätigen, weiter im Modus Manuell</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="progress_queued">In der Warteschlange</string>
|
||||
<string name="progress_queued_ahead">In der Warteschlange: %1$s davor</string>
|
||||
<string name="progress_waiting_for_model">Warte auf %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Lade %1$s</string>
|
||||
<string name="progress_reading_prompt">Lese den Prompt: %1$s / %2$s Tokens (%3$s %%)</string>
|
||||
<string name="progress_reading_prompt_bare">Lese den Prompt</string>
|
||||
<string name="progress_thinking">Denkt nach</string>
|
||||
<string name="progress_writing">Schreibe: %1$s Tok/s</string>
|
||||
<string name="progress_writing_bare">Schreibe</string>
|
||||
<string name="progress_running_tool">Führe %1$s aus: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Führe %1$s aus</string>
|
||||
<string name="progress_waiting_for_person">Wartet auf dich: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Wartet auf Subagenten: %1$s laufen</string>
|
||||
<string name="progress_compacting">Verdichte das Gespräch</string>
|
||||
<string name="progress_retrying">Neuer Versuch in %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Angehalten</string>
|
||||
<string name="progress_stopped_reason">Gestoppt: %1$s</string>
|
||||
<string name="progress_failed">Fehlgeschlagen: %1$s</string>
|
||||
<string name="progress_reason_busy">es bedient eine Anfrage auf einmal und beantwortet gerade eine andere</string>
|
||||
<string name="progress_reason_slots">alle seine Plätze sind belegt</string>
|
||||
<string name="progress_reason_group">sein Server hält gerade ein anderes Modell</string>
|
||||
<string name="progress_what_approval">%1$s erlauben?</string>
|
||||
<string name="progress_what_approval_bare">eine Freigabe</string>
|
||||
<string name="progress_what_question">eine Frage</string>
|
||||
<string name="progress_what_plan">den Plan</string>
|
||||
<string name="progress_stopped_person">von dir</string>
|
||||
<string name="progress_stopped_steps">Schrittlimit</string>
|
||||
<string name="progress_stopped_budget">Budget</string>
|
||||
<string name="tree_state_working">arbeitet</string>
|
||||
<string name="tree_state_waiting">wartet auf einen Platz</string>
|
||||
<string name="tree_state_finished">fertig</string>
|
||||
<string name="tree_state_idle">untätig</string>
|
||||
<string name="tree_state_paused">pausiert: Kontext voll</string>
|
||||
<string name="tree_state_done">fertig</string>
|
||||
<string name="tree_state_out_of_context">Kontext erschöpft</string>
|
||||
<string name="tree_state_stopped">angehalten</string>
|
||||
<string name="tree_context">%1$s%% Kontext</string>
|
||||
<string name="tree_open_slots">Freie Plätze: %1$s</string>
|
||||
<string name="subagents_device_cannot">Der Computer, auf dem dieser Chat läuft, führt keine Subagenten aus: aktualisiere dort das LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s fragt:</string>
|
||||
<string name="card_subagent_asks">Subagent %1$s (%2$s), %3$s, fragt:</string>
|
||||
<string name="card_it_says">Es sagt: %1$s</string>
|
||||
<string name="card_change_before">Vor dem Ausführen ändern</string>
|
||||
<string name="card_edit_runs">Erlauben führt aus, was im Feld steht. Es wird nicht erneut gegen die Regeln dieses Chats geprüft — Sie haben es eingegeben.</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>
|
||||
@@ -146,6 +354,13 @@
|
||||
<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_language">Sprache</string>
|
||||
<string name="language_hint">Nur die Oberfläche. Modelle antworten in der Sprache, in der Sie ihnen schreiben, egal was hier steht.</string>
|
||||
<string name="language_account">Wie mein Konto</string>
|
||||
<string name="language_account_is">Wie mein Konto: %1$s</string>
|
||||
<string name="language_account_unknown">Noch nicht von Ihrer Instanz gelesen</string>
|
||||
<string name="language_phone">Sprache des Telefons</string>
|
||||
<string name="language_phone_is">Sprache des Telefons: %1$s</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>
|
||||
@@ -157,6 +372,9 @@
|
||||
<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_model">Modell des Assistenten</string>
|
||||
<string name="assistant_model_default">Standard der Instanz</string>
|
||||
<string name="assistant_model_default_line">Das Modell, mit dem deine neuen Chats beginnen. Ist es für eine gesprochene Frage zu langsam, wähle unten ein schnelleres.</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>
|
||||
@@ -168,11 +386,223 @@
|
||||
<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="update_checking">Wird geprüft…</string>
|
||||
<string name="update_available">%1$s ist verfügbar. Tippen Sie, um die Release-Seite zu öffnen.</string>
|
||||
<string name="update_install">%1$s installieren</string>
|
||||
<string name="update_auto">Nach neuen Versionen suchen</string>
|
||||
<string name="update_auto_line">Höchstens einmal am Tag, beim Start, fragt die App Ihre Instanz, welches Release zu ihr passt (bei einer älteren Instanz: die Liste der Releases auf GitHub), und meldet per Benachrichtigung, wenn es ein neueres gibt. Nichts über Sie wird anderswohin gesendet. In einer Beta standardmäßig an, sonst aus.</string>
|
||||
<string name="update_betas">Betas einbeziehen</string>
|
||||
<string name="update_betas_line">Auch Testversionen anbieten, nicht nur Releases. Standardmäßig an, wenn diese App selbst eine Beta ist.</string>
|
||||
<string name="channel_updates">App-Updates</string>
|
||||
<string name="update_notice_title">LLeMbas für Android %1$s</string>
|
||||
<string name="update_notice_text">Eine neuere Version ist verfügbar. Tippen Sie, um die Release-Seite zu öffnen.</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="assist_use_screen">Bildschirm verwenden</string>
|
||||
<string name="assist_screen_both">Der Text des Bildschirms und ein Screenshot gehen mit Ihrer nächsten Frage mit.</string>
|
||||
<string name="assist_screen_text">Der Text des Bildschirms geht mit Ihrer nächsten Frage mit.</string>
|
||||
<string name="assist_screen_shot">Ein Screenshot geht mit Ihrer nächsten Frage mit.</string>
|
||||
<string name="assist_quick_summarise">Zusammenfassen</string>
|
||||
<string name="assist_quick_summarise_prompt">Fasse zusammen, was auf meinem Bildschirm ist.</string>
|
||||
<string name="assist_quick_translate">Übersetzen</string>
|
||||
<string name="assist_quick_translate_prompt">Übersetze, was auf meinem Bildschirm ist, ins Deutsche.</string>
|
||||
<string name="assist_quick_explain">Erklären</string>
|
||||
<string name="assist_quick_explain_prompt">Erkläre, was auf meinem Bildschirm ist.</string>
|
||||
<string name="assist_continue">Letzten Chat fortsetzen</string>
|
||||
<string name="assist_help">Halten Sie die Ein-/Aus-Taste, um den Assistenten über jeder App zu öffnen, oder nutzen Sie die Kachel in den Schnelleinstellungen.</string>
|
||||
<string name="assist_connecting">Verbinden…</string>
|
||||
<string name="assist_offline">%1$s ist nicht erreichbar</string>
|
||||
<string name="assist_no_model">Kein Modell</string>
|
||||
<string name="assist_voice_reply_on">Sprachantwort ist an</string>
|
||||
<string name="assist_voice_reply_off">Sprachantwort ist aus</string>
|
||||
<string name="assist_read_aloud">Vorlesen</string>
|
||||
<string name="assist_stop_reading">Vorlesen beenden</string>
|
||||
<string name="assist_answer_in_app">Diese Antwort wartet auf Ihre Entscheidung: öffnen Sie sie in der App.</string>
|
||||
<string name="assist_send_now">Gesagtes senden</string>
|
||||
<string name="assist_say_it">Sprechen Sie, dann kurz Pause</string>
|
||||
<string name="assist_type">Lieber tippen</string>
|
||||
<string name="assist_writing_down">Ihr Gesagtes wird aufgeschrieben…</string>
|
||||
<string name="assist_unlock_to_send">Entsperren und senden</string>
|
||||
<string name="assist_question_heard">Frage aufgenommen</string>
|
||||
<string name="assist_recording_waits_line">Das Telefon ist gesperrt. Deine Frage wartet als Aufnahme auf diesem Telefon; es wurde nichts gesendet. Nach dem Entsperren geht sie an deine Instanz, die sie aufschreibt und beantwortet.</string>
|
||||
<string name="assist_locked_line">Das Telefon ist gesperrt. Bis du es entsperrst, wird nichts gesendet und keine Antwort angezeigt.</string>
|
||||
<string name="assist_conversation">Im Gespräch</string>
|
||||
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sag „Stopp“, um zu beenden.</string>
|
||||
<string name="assist_conversation_end">Beenden</string>
|
||||
<string name="assist_stop_words">stopp|stop|das wars|das war\'s|das ist alles|genug|ende|tschüss|auf wiedersehen|danke das wars|abbrechen</string>
|
||||
<string name="assistant_conversation">Ein gesprochenes Gespräch fortführen</string>
|
||||
<string name="assistant_conversation_line">Nachdem eine gesprochene Antwort vorgelesen wurde, hört der Assistent wieder zu — bis du „Stopp“ sagst, auf Beenden tippst oder ein paar Sekunden nichts sagst. Funktioniert mit einem Headset.</string>
|
||||
<string name="experimental">Experimentell</string>
|
||||
<string name="wake_experimental_line">Neu und bisher nur auf wenigen Telefonen erprobt. Es kann den Satz überhören, versehentlich starten oder dich hören und den Assistenten trotzdem nicht öffnen.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimentell: Das selbstständige Zuhören beim Öffnen des Assistenten, das Erkennen, wann du fertig gesprochen hast, und das gesprochene Gespräch sind neu und funktionieren noch nicht auf jedem Telefon gut. Eine Frage tippen und die Mikrofontaste funktionieren immer.</string>
|
||||
<string name="assist_wake_word_hint">Kein Aktivierungswort, außer du willst eines: Einstellungen › Assistent › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
|
||||
<string name="channel_wake">Aktivierungswort</string>
|
||||
<string name="wake_word">Aktivierungswort</string>
|
||||
<string name="wake_word_listen">Auf ein Aktivierungswort hören</string>
|
||||
<string name="wake_word_line">Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.</string>
|
||||
<string name="wake_word_unavailable">Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.</string>
|
||||
<string name="wake_phrase_line">Das sagst du, dann eine kurze Pause: Es zählt, sobald du aufhörst. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache.</string>
|
||||
<string name="wake_greeting">Anrede</string>
|
||||
<string name="wake_name">Name</string>
|
||||
<string name="wake_name_google_line">Ein Google-Telefon oder -Lautsprecher in der Nähe antwortet ebenfalls.</string>
|
||||
<string name="wake_sensitivity">Empfindlichkeit</string>
|
||||
<string name="wake_sensitivity_low">Niedrig</string>
|
||||
<string name="wake_sensitivity_low_line">Startet am seltensten versehentlich. Du musst den Satz vielleicht deutlicher oder zweimal sagen.</string>
|
||||
<string name="wake_sensitivity_normal">Normal</string>
|
||||
<string name="wake_sensitivity_normal_line">Die eigene Einstellung der Engine.</string>
|
||||
<string name="wake_sensitivity_high">Hoch</string>
|
||||
<string name="wake_sensitivity_high_line">Hört dich am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich.</string>
|
||||
<string name="wake_test">Aktivierungswort testen</string>
|
||||
<string name="wake_test_line">Zeigt zehn Sekunden lang, ob dein Satz gehört wird, ohne den Assistenten zu öffnen.</string>
|
||||
<string name="wake_test_say">Sag jetzt „%1$s“, dann eine Pause…</string>
|
||||
<string name="wake_test_heard">Gehört</string>
|
||||
<string name="wake_test_missed">In zehn Sekunden nicht gehört. Versuch es näher am Telefon, in einem ruhigeren Moment oder mit höherer Empfindlichkeit.</string>
|
||||
<string name="wake_test_off">Schalte zuerst das Aktivierungswort ein.</string>
|
||||
<string name="wake_screen_only">Nur bei eingeschaltetem Bildschirm</string>
|
||||
<string name="wake_screen_only_line">Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet.</string>
|
||||
<string name="wake_battery">Im Hintergrund laufen lassen</string>
|
||||
<string name="wake_battery_line">Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nimm LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen deines Telefons.</string>
|
||||
<string name="wake_word_privacy">Vor dem Wort verlässt nichts das Telefon. Der Ton des Mikrofons geht nur an die Aktivierungswort-Engine auf dem Telefon und wird nicht gespeichert; die Benachrichtigung bleibt sichtbar, solange es zuhört. Die Sätze sind englisch; die Engine ist sherpa-onnx (Open Source).</string>
|
||||
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.</string>
|
||||
<string name="wake_listening_for">Hört auf „%1$s“</string>
|
||||
<string name="wake_off">Das Aktivierungswort hört nicht zu</string>
|
||||
<string name="wake_tap_to_start">Tippe, um es wieder zu starten. Wenn Android fragt, erlaube das Mikrofon.</string>
|
||||
<string name="wake_starting">Aktivierungswort wird gestartet…</string>
|
||||
<string name="wake_paused_silent">Aktivierungswort hört nichts: Eine andere App hat das Mikrofon, oder das Mikrofon des Telefons ist ausgeschaltet</string>
|
||||
<string name="wake_failed_no_engine">Aktivierungswort funktioniert nicht: Dieser Build hat keine Engine</string>
|
||||
<string name="wake_failed_model">Aktivierungswort funktioniert nicht: Sein Modell konnte auf diesem Telefon nicht entpackt werden</string>
|
||||
<string name="wake_failed_engine">Aktivierungswort funktioniert nicht: Die Engine ist nicht gestartet</string>
|
||||
<string name="wake_failed_microphone">Aktivierungswort funktioniert nicht: Das Mikrofon ist nicht gestartet</string>
|
||||
<string name="wake_failed_line">Es hört nicht zu. Es versucht es von selbst erneut.</string>
|
||||
<string name="wake_notification_line">Bis du es sagst, verlässt nichts das Telefon.</string>
|
||||
<string name="wake_paused_screen">Aktivierungswort pausiert: Bildschirm aus</string>
|
||||
<string name="wake_paused_battery">Aktivierungswort pausiert: Energiesparmodus ist an</string>
|
||||
<string name="wake_paused_assistant">Aktivierungswort pausiert, solange der Assistent offen ist</string>
|
||||
<string name="wake_paused_microphone">Aktivierungswort pausiert: LLeMbas darf das Mikrofon nicht verwenden</string>
|
||||
<string name="wake_stop">Nicht mehr zuhören</string>
|
||||
<string name="wake_heard">Gehört. Tippe, um zu fragen.</string>
|
||||
<string name="channel_wake_heard">Aktivierungswort gehört</string>
|
||||
<string name="wake_heard_line">LLeMbas kann sich nur als App für den digitalen Assistenten des Telefons selbst über anderen Apps öffnen.</string>
|
||||
<string name="wake_not_assistant">LLeMbas ist nicht die App für den digitalen Assistenten</string>
|
||||
<string name="wake_not_assistant_line">Deshalb kann das Aktivierungswort den Assistenten nicht über anderen Apps öffnen: Du bekommst eine Benachrichtigung zum Antippen. Um überall per Stimme zu öffnen, tippe hier und wähle LLeMbas als App für den digitalen Assistenten.</string>
|
||||
<string name="wake_last">Letztes Aufwecken</string>
|
||||
<string name="wake_last_none">Der Satz wurde noch nicht gehört.</string>
|
||||
<string name="wake_out_opened">Assistent geöffnet.</string>
|
||||
<string name="wake_out_no_sheet">Android wurde gebeten, den Assistenten zu öffnen; es hat nicht abgelehnt, aber es kam kein Blatt.</string>
|
||||
<string name="wake_out_not_connected">Android hatte LLeMbas nicht als Assistenten verbunden, daher ließ sich das Blatt nicht öffnen.</string>
|
||||
<string name="wake_out_refused">Android hat das Öffnen des Assistenten abgelehnt: %1$s</string>
|
||||
<string name="wake_out_activity">Stattdessen als Bildschirm der App geöffnet.</string>
|
||||
<string name="wake_out_notification">Stattdessen eine Benachrichtigung zum Antippen gesendet.</string>
|
||||
<string name="wake_out_tested">In einem Test gehört: Es war nichts zu öffnen.</string>
|
||||
<string name="wake_role_held">LLeMbas war die App für den digitalen Assistenten.</string>
|
||||
<string name="wake_role_not_held">LLeMbas war nicht die App für den digitalen Assistenten.</string>
|
||||
<string name="wake_link_never">Android hatte den Assistenten seit dem Start der App nicht verbunden.</string>
|
||||
<string name="wake_link_ready">Android hatte den Assistenten um %1$s verbunden.</string>
|
||||
<string name="wake_link_shutdown">Android hatte ihn um %1$s getrennt.</string>
|
||||
<string name="wake_link_later">Android hat ihn um %1$s wieder verbunden.</string>
|
||||
<string name="wake_sheet_ms">Das Blatt war nach %1$s ms da.</string>
|
||||
<string name="wake_no_recognizers">Dieses Telefon hat keine Spracherkenner, daher führt Android darauf keinen Sprachassistenten-Dienst aus.</string>
|
||||
<string name="wake_not_active">LLeMbas war als App für den digitalen Assistenten gewählt, aber Android nutzte es nicht als Sprachassistenten.</string>
|
||||
<string name="wake_waited">Kurz gewartet, bis Android ihn verbindet.</string>
|
||||
<string name="wake_show_failed">Android meldete, dass es das Blatt des Assistenten nicht anzeigen konnte.</string>
|
||||
<string name="wake_assistant_inactive">Android nutzt LLeMbas gerade nicht als Sprachassistenten</string>
|
||||
<string name="wake_assistant_inactive_line">Wähle LLeMbas erneut als App für den digitalen Assistenten: Tippe hier, wähle eine andere App und dann LLeMbas. Bis dahin öffnet langes Drücken es als gewöhnlichen Bildschirm, und das Aktivierungswort kann nur eine Benachrichtigung senden.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas ist der Assistent, aber Android hat ihn gerade nicht verbunden</string>
|
||||
<string name="wake_assistant_unbound_line">Solange das so ist, kann das Aktivierungswort das Blatt nicht selbst öffnen. Tippe für die Assistenten-Einstellung des Systems: Eine andere App und dann wieder LLeMbas zu wählen verbindet ihn.</string>
|
||||
<string name="wake_heard_could_not">Ließ sich nicht selbst öffnen — tippe, um zu fragen</string>
|
||||
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
|
||||
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.</string>
|
||||
<string name="assist_notifications">Meine Benachrichtigungen zusammenfassen</string>
|
||||
<string name="assist_notifications_prompt">Fasse meine Benachrichtigungen zusammen: Was braucht meine Aufmerksamkeit?</string>
|
||||
<string name="assist_notifications_phrases">meine benachrichtigungen|meinen benachrichtigungen|meiner benachrichtigungen</string>
|
||||
<string name="notification_summaries">Zusammenfassungen der Benachrichtigungen</string>
|
||||
<string name="notification_summaries_switch">Den Assistenten meine Benachrichtigungen lesen lassen, wenn ich frage</string>
|
||||
<string name="notification_summaries_line">Sag „fasse meine Benachrichtigungen zusammen“ oder tippe auf den Chip im Assistenten.</string>
|
||||
<string name="notification_summaries_unavailable">Nicht in diesem Build. Das Lesen von Benachrichtigungen braucht den „notifications“-Build von LLeMbas, weil Google Play Protect die Installation einer App von außerhalb des Play Store blockiert, die sie lesen kann. Es ist dieselbe App mit derselben Signatur: Auf der Release-Seite lässt sich die Datei, die auf -notifications.apk endet, über diese installieren.</string>
|
||||
<string name="update_notifications_manual">Dies ist der „notifications“-Build: Installiere das Update von der Release-Seite, die Datei, die auf -notifications.apk endet.</string>
|
||||
<string name="notification_access">Zugriff auf Benachrichtigungen</string>
|
||||
<string name="notification_access_on">Erteilt. Der Schalter dafür ist in den Android-Einstellungen.</string>
|
||||
<string name="notification_access_off">Noch nicht erteilt. Tippe, um den Android-Schalter für LLeMbas zu öffnen.</string>
|
||||
<string name="notification_summaries_privacy">Standardmäßig aus. Wenn du fragst, geht der Text der Benachrichtigungen, die gerade auf deinem Telefon sind (App, Titel, Text), mit dieser einen Frage an deine Instanz und ihr Modell. Vorher wird nichts gelesen, die App behält nichts davon, und bei gesperrtem Telefon wird nichts gelesen. Der Benachrichtigungszugriff von Android lässt eine App jede Benachrichtigung sehen; ihn zu erteilen und zu entziehen liegt bei dir.</string>
|
||||
<string name="nav_app">Navigations-App</string>
|
||||
<string name="nav_app_auto">Die installierte</string>
|
||||
<string name="nav_app_google">Google Maps</string>
|
||||
<string name="nav_app_osmand">OsmAnd</string>
|
||||
<string name="nav_app_ask">Jedes Mal fragen</string>
|
||||
<string name="nav_app_not_installed">Nicht installiert</string>
|
||||
<string name="osmand_info">OsmAnd nach der Route fragen</string>
|
||||
<string name="osmand_info_line">Damit „Zwischenstopp hinzufügen“ und die Suche in der Nähe auch mit einer in OsmAnd geplanten Route gehen: LLeMbas fragt OsmAnd, wo du bist und wohin die Route führt. Erlaube LLeMbas zuerst in OsmAnd (verbundene Apps, mit Standort); OsmAnd sagt Bescheid, wenn es nicht erlaubt ist.</string>
|
||||
<string name="phone_actions_line">Ein Modell kann anbieten, etwas auf diesem Telefon zu tun — einen Wecker stellen, einen Termin eintragen, eine Nachricht entwerfen, eine Route starten. Nichts passiert, bevor du auf seiner Karte auf Ausführen tippst, und nie bei gesperrtem Telefon. Google Maps startet eine Route mit ein paar Stopps, kann aber keinen in eine laufende Route einfügen und nicht angehalten werden; OsmAnd kann das.</string>
|
||||
<string name="action_card_title">Das auf deinem Telefon tun?</string>
|
||||
<string name="action_do">Ausführen</string>
|
||||
<string name="action_running">Wird ausgeführt…</string>
|
||||
<string name="action_unlock">Entsperre zuerst das Telefon und tippe dann auf Ausführen.</string>
|
||||
<string name="action_failed">Hat nicht geklappt: %1$s</string>
|
||||
<string name="nav_app_pick">Mit welcher Karten-App?</string>
|
||||
<string name="action_google_add_stop">Google Maps kann keinen Stopp in eine laufende Route einfügen: Es startet die Route neu, über den Stopp.</string>
|
||||
<string name="action_google_no_stop">Google Maps lässt sich nicht von außen anhalten: Beende die Route dort.</string>
|
||||
<string name="action_line_clock">Die Uhr-App stellt es ein.</string>
|
||||
<string name="action_line_calendar">Der Kalender öffnet sich mit dem ausgefüllten Termin; du speicherst ihn.</string>
|
||||
<string name="action_line_draft">Öffnet einen Entwurf; du sendest ihn selbst.</string>
|
||||
<string name="action_line_dial">Die Telefon-App öffnet sich mit der Nummer; du rufst an.</string>
|
||||
<string name="action_line_map">%1$s übernimmt die Route.</string>
|
||||
<string name="action_line_now">Passiert sofort.</string>
|
||||
<string name="action_line_settings">Öffnet die Einstellung; du änderst sie.</string>
|
||||
<string name="action_line_automation">Startet deine Automatisierung (Tasker, wenn keine andere App genannt ist).</string>
|
||||
<string name="action_line_open">Öffnet es.</string>
|
||||
<string name="assist_recogniser_failed">Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.</string>
|
||||
<string name="assistant_listens">Beim Öffnen des Assistenten zuhören</string>
|
||||
<string name="voice_input">Spracheingabe</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Die Spracherkennung Ihrer Instanz, über den Server. Die Aufnahme geht an Ihre Instanz und nirgendwo sonst hin.</string>
|
||||
<string name="voice_input_phone">Telefon (Google oder das System)</string>
|
||||
<string name="voice_input_phone_line">Die eigene Spracherkennung des Telefons. Die Wörter erscheinen beim Sprechen; die Aufnahme geht dorthin, wohin diese Erkennung sie schickt.</string>
|
||||
<string name="voice_input_phone_none">Dieses Telefon hat keine eigene Spracherkennung.</string>
|
||||
<string name="voice_input_hint">Wird vom Assistenten und vom Mikrofon im Chat genutzt. Mit LLeMbas zeigt der Assistent die Wörter einen Moment später, und eine Pause sendet sie, ein Chat schreibt sie auf, wenn Sie aufhören; mit der Erkennung des Telefons erscheinen sie beim Sprechen.</string>
|
||||
<string name="share_sending">Wird an LLeMbas gesendet…</string>
|
||||
<string name="share_default_prompt">Schauen Sie sich das an.</string>
|
||||
<string name="share_ask_hint">Was soll LLeMbas damit tun? (optional)</string>
|
||||
<string name="widget_hint">Frag mich alles</string>
|
||||
<string name="directory_places">Orte auf diesem Gerät</string>
|
||||
<string name="directory_last_used">Hier zuletzt verwendet: %1$s. Ein neuer Chat in diesem Verzeichnis beginnt damit, sofern Sie kein anderes wählen.</string>
|
||||
<string name="directory_refused">Das Gerät öffnet hier keine Sitzung.</string>
|
||||
<string name="directory_up">Eine Ebene höher</string>
|
||||
<string name="directory_all_places">Alle Orte</string>
|
||||
<string name="directory_not_trusted">Auf dem Gerät nicht vertrauenswürdig</string>
|
||||
<string name="directory_empty">Hier gibt es keine Ordner.</string>
|
||||
<string name="directory_no_places">Dieses Gerät bietet keine Ordner an: Seine Remote-Wurzeln sind leer oder fehlen.</string>
|
||||
<string name="directory_browse">Durchsuchen</string>
|
||||
<string name="directory_path">Ein vollständiger Pfad</string>
|
||||
<string name="directory_choose">Auswählen</string>
|
||||
<string name="directory_no_listing">Die Verzeichnisse dieses Geräts können gerade nicht aufgelistet werden. Geben Sie den Pfad unten ein.</string>
|
||||
<string name="model">Modell</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Läuft auf diesem Server wie ein Chat: mit den Werkzeugen des Servers (Suche, Ihre Dateien hier, Gedächtnis) und auf einem Planungsmodell.</string>
|
||||
<string name="schedule_agentic">Agentisch</string>
|
||||
<string name="schedule_agentic_line">Läuft auf einem Ihrer Computer, in einem Ordner dort, als Agent: mit den Werkzeugen des Agenten auf diesem Computer — seinen Dateien und seiner Shell — innerhalb der eigenen Grenzen des Computers. Er gehört zu diesem Computer und Ordner.</string>
|
||||
<string name="schedule_agentic_unavailable">Keiner Ihrer Computer nimmt jetzt geplante Arbeit an. Verbinden Sie einen und schalten Sie „Accept scheduled work“ in seinem LLeMbas CLI ein (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nimmt keine geplante Arbeit an</string>
|
||||
<string name="schedule_computer_hint">Der Computer muss es erlauben: „Accept scheduled work“ in seinem LLeMbas CLI (lembas service scheduled on). Ist er zur Zeit eines Laufs nicht verbunden, wartet der Lauf auf ihn; ist er nicht zurück, bevor die Zeit des Laufs vorbei ist, wird der Lauf als verpasst vermerkt und Sie erfahren es.</string>
|
||||
<string name="schedule_computer_gone">ein Computer, der nicht mehr angemeldet ist</string>
|
||||
<string name="schedule_folder">Ordner auf dem Computer</string>
|
||||
<string name="schedule_agent_mode">Modus</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, sofern Sie nichts anderes wählen; Auto führt Befehle ohne Nachfrage aus. Der Computer kann ihn herabsetzen.</string>
|
||||
<string name="schedule_approval_wait">Eine Genehmigung wartet (Minuten)</string>
|
||||
<string name="schedule_approval_wait_hint">Ein Befehl, den der Lauf genehmigt braucht, kommt als Karte auf Ihr Telefon. Bis dahin unbeantwortet, gilt er als abgelehnt.</string>
|
||||
<string name="schedule_watch_command_hint">Optional, auf dem Computer. Läuft vor jedem Lauf im Ordner; ist seine Ausgabe dieselbe wie beim letzten Mal, endet der Lauf dort. Ein Befehl, bei dem der Modus nachfragen würde, wird abgelehnt.</string>
|
||||
<string name="schedule_watch_timeout">Der Befehl darf dauern (Sekunden)</string>
|
||||
<string name="schedule_watch_timeout_hint">Danach wird er gestoppt, und der Lauf schlägt fehl.</string>
|
||||
<string name="schedule_chat_drops_watch">Diese Aufgabe überwacht einen Befehl auf ihrem Computer. Als Chat-Aufgabe tut sie das nicht mehr: Sie läuft jedes Mal.</string>
|
||||
<string name="schedule_folder_model">Das übliche Modell des Ordners</string>
|
||||
<string name="schedule_folder_model_hint">Das übliche Modell des Ordners ist das, das Sie in diesem Ordner auf diesem Computer zuletzt verwendet haben — der Computer merkt es sich, und jeder Lauf fragt ihn danach — oder Ihr Standardmodell, wo es keines gibt. Ein hier gewähltes Modell ist das des Laufs, was auch immer das des Ordners ist. Ein Lauf ändert das Modell des Ordners nie.</string>
|
||||
<string name="schedule_first_free_model">Das erste freie Ihrer Modelle für geplante Aufgaben</string>
|
||||
<string name="run_model_directory">das übliche Modell des Ordners</string>
|
||||
<string name="run_model_default">Ihr Standardmodell</string>
|
||||
<string name="run_model_session">das eigene Modell der Unterhaltung</string>
|
||||
<string name="widget_speak">Sprechen</string>
|
||||
<string name="widget_description">Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.</string>
|
||||
<string name="shortcut_last">Letzter Chat</string>
|
||||
</resources>
|
||||
@@ -14,10 +14,7 @@
|
||||
<string name="signin_too_old">Esta instancia usa una versión anterior de LLeMbas. Esta aplicación necesita LLeMbas 2.0 o 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">Aún no hay chats de agente. Inicie uno con Nuevo chat de agente, en un dispositivo vinculado a esta instancia.</string>
|
||||
<string name="new_agent_chat">Nuevo chat de agente</string>
|
||||
<string name="agent_device">Dispositivo</string>
|
||||
<string name="agent_no_device">Ahora no hay ningún dispositivo vinculado. Inicie `lembas service` en un ordenador con sesión iniciada en esta instancia y vuelva.</string>
|
||||
@@ -26,6 +23,28 @@
|
||||
<string name="empty_chat">¿De qué hablamos?</string>
|
||||
<string name="loading_line">Horneando lembas…</string>
|
||||
<string name="archive">Archivar</string>
|
||||
<string name="archived">Archivados</string>
|
||||
<string name="archived_restore">Restaurar chat</string>
|
||||
<string name="archived_none">No hay chats archivados.</string>
|
||||
<string name="memory">Memoria</string>
|
||||
<string name="memory_intro">Lo que los modelos recuerdan de usted</string>
|
||||
<string name="memory_none">Todavía nada. Un modelo con la herramienta de memoria añade algo aquí cuando usted le cuenta algo que vale la pena conservar.</string>
|
||||
<string name="memory_remember">Recordar</string>
|
||||
<string name="memory_label">Qué dice esta memoria</string>
|
||||
<string name="memory_hint">Algo que vale la pena recordar</string>
|
||||
<string name="memory_group">Grupo de datos</string>
|
||||
<string name="memory_forget">Olvidar</string>
|
||||
<string name="memory_by_model">Modelo</string>
|
||||
<string name="chats_pinned">Chats fijados</string>
|
||||
<string name="chat_pin">Fijar chat</string>
|
||||
<string name="chat_unpin">Dejar de fijar el chat</string>
|
||||
<string name="folder_move">Mover a carpeta</string>
|
||||
<string name="folder_none">Sin carpeta</string>
|
||||
<string name="folder_new">Nueva carpeta</string>
|
||||
<string name="folder_name">Nombre de la carpeta</string>
|
||||
<string name="folder_rename">Renombrar carpeta</string>
|
||||
<string name="folder_delete">Eliminar carpeta</string>
|
||||
<string name="folder_delete_confirm">¿Eliminar la carpeta «%1$s»? Los chats que contiene se conservan.</string>
|
||||
<string name="delete">Eliminar</string>
|
||||
<string name="edit">Editar</string>
|
||||
<string name="regenerate">Regenerar</string>
|
||||
@@ -43,6 +62,8 @@
|
||||
<string name="attach_take_photo">Hacer una foto</string>
|
||||
<string name="attach_choose_photos">Elegir fotos</string>
|
||||
<string name="attach_choose_files">Elegir archivos</string>
|
||||
<string name="image_generate">Generar imágenes</string>
|
||||
<string name="image_generated">La imagen generada</string>
|
||||
<string name="copy_message">Copiar mensaje</string>
|
||||
<string name="copied">Copiado.</string>
|
||||
<string name="rename_chat">Renombrar chat</string>
|
||||
@@ -79,11 +100,18 @@
|
||||
<string name="ctx_since">Desde la última respuesta</string>
|
||||
<string name="ctx_buffer">Reserva para la compactación</string>
|
||||
<string name="ctx_free">Espacio libre</string>
|
||||
<string name="outputs_empty">Todavía no se ha escrito ningún archivo en este chat.</string>
|
||||
<string name="tasks_empty">No hay nada en segundo plano. Los ayudantes, los comandos y los miembros de un equipo aparecen aquí mientras trabajan.</string>
|
||||
<string name="tasks_empty">No hay nada en segundo plano. Los subagentes, los comandos y los miembros de un equipo aparecen aquí mientras trabajan.</string>
|
||||
<string name="tasks_none_running">Nada en marcha.</string>
|
||||
<string name="agents_one_working">1 agente trabajando</string>
|
||||
<string name="agents_n_working">%1$s agentes trabajando</string>
|
||||
<string name="tasks_running">En ejecución</string>
|
||||
<string name="tasks_finished">Terminadas</string>
|
||||
<string name="tasks_n_running">%1$s en curso</string>
|
||||
<string name="tasks_nested">%1$s debajo</string>
|
||||
<string name="task_subagent">Subagente</string>
|
||||
<string name="task_command">Comando</string>
|
||||
<string name="task_member">Miembro del equipo</string>
|
||||
<string name="activity_until_compact">%1$s hasta la compactación automática</string>
|
||||
<string name="activity_compact_off">La compactación automática está desactivada.</string>
|
||||
<string name="activity_compact">Compactar</string>
|
||||
<string name="agents_n_queued">%1$s en cola</string>
|
||||
<string name="agents_n_waiting">%1$s esperando</string>
|
||||
<string name="agents_n_finished">%1$s terminados</string>
|
||||
@@ -100,28 +128,208 @@
|
||||
<string name="agent_stop_confirm">¿Detener %1$s? Lo que ha hecho hasta ahora se queda.</string>
|
||||
<string name="agent_nothing_yet">Todavía no ha dicho nada.</string>
|
||||
<string name="agent_machine">Del sistema</string>
|
||||
<string name="team_size">Equipo: %1$s de %2$s agentes</string>
|
||||
<string name="team_size">Equipo: %1$s de %2$s subagentes</string>
|
||||
<string name="team_room">Sala</string>
|
||||
<string name="room_empty">Todavía no se ha dicho nada en la sala.</string>
|
||||
<string name="room_report">informe</string>
|
||||
<string name="team_agents">Agentes</string>
|
||||
<string name="team_fewest">Mínimo</string>
|
||||
<string name="team_most">Máximo</string>
|
||||
<string name="team_hint">Su propio agente incluido. Con más de uno, puede añadir miembros que hagan el trabajo mientras los dirige.</string>
|
||||
<string name="team_chip">Agentes %1$s–%2$s</string>
|
||||
<string name="team_agents">Subagentes</string>
|
||||
<string name="team_min">Mín</string>
|
||||
<string name="team_max">Máx</string>
|
||||
<string name="team_range">Mín %1$s · Máx %2$s</string>
|
||||
<string name="team_hint">Los números cuentan el propio agente de este chat: 1 es el agente solo, sin subagentes, y Máx 4 es el agente y hasta 3 subagentes que dirige.</string>
|
||||
<string name="team_chip">Subagentes: Mín %1$s · Máx %2$s</string>
|
||||
<string name="subagents_named_only">Este modelo atiende una sola petición a la vez: los subagentes necesitan otro modelo, en otro servidor, nombrado en el chat.</string>
|
||||
<string name="thinking_switch">Razonar antes de responder</string>
|
||||
<string name="effort_level">Esfuerzo: %1$s</string>
|
||||
<string name="level_off">desactivado</string>
|
||||
<string name="level_default">predeterminado</string>
|
||||
<string name="chats_open">Abrir los chats</string>
|
||||
<string name="chats_search">Buscar chats</string>
|
||||
<string name="chats_today">Hoy</string>
|
||||
<string name="chats_earlier">Antes</string>
|
||||
<string name="chats_agents">Chats de agente</string>
|
||||
<string name="chats_found_in_messages">En los mensajes</string>
|
||||
<string name="chats_none_found">Ningún chat lo tiene en el título.</string>
|
||||
<string name="clear">Borrar</string>
|
||||
<string name="composer_hint_agent">Dile al agente qué hacer</string>
|
||||
<string name="tune">Opciones</string>
|
||||
<string name="effort">Esfuerzo</string>
|
||||
<string name="thinking_switch_hint">Más lento, y mejor con preguntas difíciles.</string>
|
||||
<string name="plan_first">Primero un plan</string>
|
||||
<string name="plan_first_hint">El modelo escribe un plan que apruebas antes de que actúe.</string>
|
||||
<string name="agent_mode">Modo</string>
|
||||
<string name="agent_greeting">¿Qué debe hacer el agente?</string>
|
||||
<string name="agent_runs_on">Se ejecuta en %1$s, en %2$s</string>
|
||||
<string name="agent_directory_default">su primera carpeta</string>
|
||||
<string name="kind_chat">Chat</string>
|
||||
<string name="kind_agent">Chat de agente</string>
|
||||
<string name="kind_chat_line">Hable con un modelo: preguntas, textos, los archivos que adjunte.</string>
|
||||
<string name="kind_agent_line">Trabaja en un ordenador que haya vinculado: lee, escribe y ejecuta comandos en una carpeta.</string>
|
||||
<string name="agent_link_title">Primero vincule un ordenador</string>
|
||||
<string name="agent_link_lede">Los chats de agente se ejecutan en una máquina con la LLeMbas CLI, con sesión iniciada en esta instancia y vinculada. Ahora no hay ninguna vinculada.</string>
|
||||
<string name="agent_link_install">Instale en ella la LLeMbas CLI:</string>
|
||||
<string name="agent_link_login">Inicie sesión en esta instancia y apruebe el código que muestra en el navegador que se abre:</string>
|
||||
<string name="agent_link_service">Para ejecutar chats de agente en ella desde aquí, permítalo en su configuración (~/.config/lembas/config.yaml) e inicie el servicio:</string>
|
||||
<string name="agent_link_dials_out">Se conecta ella misma a esta instancia; nada escucha en su máquina. Es ella la que decide qué carpetas y modos puede usar el trabajo remoto, se pida lo que se pida aquí.</string>
|
||||
<string name="agent_link_check">Comprobar de nuevo</string>
|
||||
<string name="model_choose">Elegir un modelo</string>
|
||||
<string name="model_in_use">En uso</string>
|
||||
<string name="model_sees_images">Ve imágenes</string>
|
||||
<string name="model_uses_tools">Usa herramientas</string>
|
||||
<string name="model_context">contexto de %1$s</string>
|
||||
<string name="model_thinking_switchable">Razonamiento sí o no</string>
|
||||
<string name="model_levels">Esfuerzo: %1$s</string>
|
||||
<string name="code">Código</string>
|
||||
<string name="copy_code">Copiar código</string>
|
||||
<string name="select_text">Seleccionar texto</string>
|
||||
<string name="tools_used">Usó %1$s herramientas</string>
|
||||
<string name="suggest_explain">Explica</string>
|
||||
<string name="suggest_explain_line">cómo funciona algo, con palabras sencillas</string>
|
||||
<string name="suggest_write">Escribe</string>
|
||||
<string name="suggest_write_line">un correo, una nota o una publicación</string>
|
||||
<string name="suggest_plan">Planifica</string>
|
||||
<string name="suggest_plan_line">un viaje, una semana o un proyecto</string>
|
||||
<string name="suggest_check">Revisa</string>
|
||||
<string name="suggest_check_line">un texto: errores y tono</string>
|
||||
<string name="instance_in_use">En uso</string>
|
||||
<string name="notification_settings">Ajustes de notificaciones</string>
|
||||
<string name="notification_settings_hint">Qué tipos llegan y cómo: respuestas, preguntas, resultados y fallos programados.</string>
|
||||
<string name="scheduled">Programado</string>
|
||||
<string name="scheduled_empty">No hay nada programado. Pide algo que ocurra cada mañana, o una vez la semana que viene.</string>
|
||||
<string name="scheduled_unsupported">Esta instancia aún no ofrece tareas programadas. Llegan con un LLeMbas más reciente en el servidor.</string>
|
||||
<string name="schedule_new">Nueva programación</string>
|
||||
<string name="schedule_edit">Editar programación</string>
|
||||
<string name="schedule_next">Próxima: %1$s</string>
|
||||
<string name="schedule_paused">En pausa</string>
|
||||
<string name="schedule_pause">Pausar</string>
|
||||
<string name="schedule_resume">Reanudar</string>
|
||||
<string name="schedule_run_now">Ejecutar ahora</string>
|
||||
<string name="schedule_started">Iniciado. El resultado aparece en su historial.</string>
|
||||
<string name="schedule_next_runs">Próximas ejecuciones</string>
|
||||
<string name="schedule_history">Historial</string>
|
||||
<string name="schedule_no_runs">Aún no se ha ejecutado.</string>
|
||||
<string name="schedule_model">Modelo: %1$s</string>
|
||||
<string name="schedule_delete_confirm">¿Eliminar esta programación? Sus resultados anteriores se quedan en sus chats.</string>
|
||||
<string name="schedule_words_hint">Di cuándo y qué, con tus palabras. Verás lo que se entendió antes de guardar nada.</string>
|
||||
<string name="schedule_words_example">Cada día laborable a las 7:30, resume las noticias sobre energías renovables</string>
|
||||
<string name="schedule_preview">Vista previa</string>
|
||||
<string name="schedule_understood">Entendido como</string>
|
||||
<string name="notify_always">Avisa siempre</string>
|
||||
<string name="notify_matters">Avisa cuando importa</string>
|
||||
<string name="notify_never">No avisa nunca</string>
|
||||
<string name="run_ok">Hecho</string>
|
||||
<string name="run_silent">Nada nuevo</string>
|
||||
<string name="run_unchanged">Sin cambios</string>
|
||||
<string name="schedule_computer">Ordenador</string>
|
||||
<string name="schedule_computer_away">no vinculado ahora</string>
|
||||
<string name="schedule_watching">Solo cuando esta página cambie</string>
|
||||
<string name="schedule_watching_command">Solo cuando cambie la salida de este comando</string>
|
||||
<string name="run_failed">Fallidos</string>
|
||||
<string name="run_missed">Perdida ×%1$s</string>
|
||||
<string name="run_skipped">Omitida</string>
|
||||
<string name="run_waiting">Esperando un modelo</string>
|
||||
<string name="run_waiting_computer">Esperando al ordenador</string>
|
||||
<string name="run_running">En ejecución</string>
|
||||
<string name="run_model_instead">%1$s, en lugar de %2$s</string>
|
||||
<string name="run_retry_at">Lo intenta de nuevo a las %1$s</string>
|
||||
<string name="run_result">Resultado</string>
|
||||
<string name="run_no_text">Esta ejecución no dejó texto.</string>
|
||||
<string name="run_open_chat">Abrir su chat</string>
|
||||
<string name="mode_fresh">Un chat nuevo cada vez</string>
|
||||
<string name="mode_continue">Un chat que crece</string>
|
||||
<string name="schedule_models">Modelos para tareas programadas</string>
|
||||
<string name="schedule_models_hint">Las tareas programadas toman el primero de estos que esté libre, en este orden. Desmarque uno para dejarlo fuera.</string>
|
||||
<string name="model_free">Libre ahora</string>
|
||||
<string name="model_busy">Ocupado: %1$s</string>
|
||||
<string name="channel_scheduled">Resultados programados</string>
|
||||
<string name="channel_scheduled_failures">Fallos programados</string>
|
||||
<string name="scheduled_result_public">Una tarea programada tiene un resultado.</string>
|
||||
<string name="scheduled_failed_public">Una tarea programada falló.</string>
|
||||
<string name="page_note">Esta respuesta tiene una página: %1$s</string>
|
||||
<string name="page_where">Ábrela en la web o en LLeMbas Desktop para verla.</string>
|
||||
<string name="page_untitled">Página</string>
|
||||
<string name="reports">Informes</string>
|
||||
<string name="report">Informe</string>
|
||||
<string name="reports_none">Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirte.</string>
|
||||
<string name="reports_unsupported">Esta instancia ejecuta un LLeMbas que todavía no tiene Informes.</string>
|
||||
<string name="report_untitled">Informe sin título</string>
|
||||
<string name="report_delete_title">¿Eliminar este informe?</string>
|
||||
<string name="report_delete_line">«%1$s» se elimina para siempre, junto con la conversación sobre él.</string>
|
||||
<string name="report_mark_read">Marcar como leído</string>
|
||||
<string name="report_important">Importante</string>
|
||||
<string name="report_share">Compartir</string>
|
||||
<string name="report_reply">Responder</string>
|
||||
<string name="report_chat_title">Informe: %1$s</string>
|
||||
<string name="notify_when">Avisar cuando</string>
|
||||
<string name="notify_every_run">En cada ejecución</string>
|
||||
<string name="notify_every_run_line">El modelo escribe un informe cada vez, también cuando no ha encontrado nada.</string>
|
||||
<string name="notify_when_option">Cuando…</string>
|
||||
<string name="notify_when_line">El modelo escribe un informe solo cuando esto se cumple.</string>
|
||||
<string name="notify_when_label">¿Cuando qué?</string>
|
||||
<string name="notify_when_default">algo necesita mi atención</string>
|
||||
<string name="notify_never_option">Nunca</string>
|
||||
<string name="notify_never_line">Sin informes: las ejecuciones quedan solo en el historial de la tarea.</string>
|
||||
<string name="notify_when_words">Avisa cuando: %1$s</string>
|
||||
<string name="run_open_report">Abrir su informe</string>
|
||||
<string name="channel_reports">Informes</string>
|
||||
<string name="channel_reports_high">Informes importantes</string>
|
||||
<string name="report_new_public">Informe nuevo</string>
|
||||
<string name="schedule_run_again">Ejecutar de nuevo</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_allow_always">Permitir siempre</string>
|
||||
<string name="card_deny">Denegar</string>
|
||||
<string name="card_deny_reason">Denegar y decir por qué</string>
|
||||
<string name="plan_approve_edit">Aprobar y continuar en Editar</string>
|
||||
<string name="plan_approve_manual">Aprobar y continuar en Manual</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="progress_queued">En cola</string>
|
||||
<string name="progress_queued_ahead">En cola: %1$s por delante</string>
|
||||
<string name="progress_waiting_for_model">Esperando a %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Cargando %1$s</string>
|
||||
<string name="progress_reading_prompt">Leyendo el prompt: %1$s / %2$s tokens (%3$s %%)</string>
|
||||
<string name="progress_reading_prompt_bare">Leyendo el prompt</string>
|
||||
<string name="progress_thinking">Pensando</string>
|
||||
<string name="progress_writing">Escribiendo: %1$s tok/s</string>
|
||||
<string name="progress_writing_bare">Escribiendo</string>
|
||||
<string name="progress_running_tool">Ejecutando %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Ejecutando %1$s</string>
|
||||
<string name="progress_waiting_for_person">Esperándote: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Esperando a los subagentes: %1$s en marcha</string>
|
||||
<string name="progress_compacting">Compactando la conversación</string>
|
||||
<string name="progress_retrying">Reintento en %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Detenido</string>
|
||||
<string name="progress_stopped_reason">Detenido: %1$s</string>
|
||||
<string name="progress_failed">Error: %1$s</string>
|
||||
<string name="progress_reason_busy">atiende una petición a la vez y está respondiendo otra</string>
|
||||
<string name="progress_reason_slots">todas sus plazas están ocupadas</string>
|
||||
<string name="progress_reason_group">su servidor tiene ahora otro modelo</string>
|
||||
<string name="progress_what_approval">¿permitir %1$s?</string>
|
||||
<string name="progress_what_approval_bare">una aprobación</string>
|
||||
<string name="progress_what_question">una pregunta</string>
|
||||
<string name="progress_what_plan">el plan</string>
|
||||
<string name="progress_stopped_person">por ti</string>
|
||||
<string name="progress_stopped_steps">límite de pasos</string>
|
||||
<string name="progress_stopped_budget">presupuesto</string>
|
||||
<string name="tree_state_working">trabajando</string>
|
||||
<string name="tree_state_waiting">esperando una plaza</string>
|
||||
<string name="tree_state_finished">terminado</string>
|
||||
<string name="tree_state_idle">inactivo</string>
|
||||
<string name="tree_state_paused">en pausa: contexto lleno</string>
|
||||
<string name="tree_state_done">terminado</string>
|
||||
<string name="tree_state_out_of_context">sin contexto</string>
|
||||
<string name="tree_state_stopped">detenido</string>
|
||||
<string name="tree_context">%1$s%% de contexto</string>
|
||||
<string name="tree_open_slots">Plazas libres: %1$s</string>
|
||||
<string name="subagents_device_cannot">El ordenador en el que se ejecuta este chat no ejecuta subagentes: actualiza allí LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s pregunta:</string>
|
||||
<string name="card_subagent_asks">El subagente %1$s (%2$s), %3$s, pregunta:</string>
|
||||
<string name="card_it_says">Dice: %1$s</string>
|
||||
<string name="card_change_before">Cambiar esto antes de que se ejecute</string>
|
||||
<string name="card_edit_runs">Permitir ejecuta lo que hay en el cuadro. No se vuelve a comprobar con las reglas de este chat: lo ha escrito usted.</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>
|
||||
@@ -146,6 +354,13 @@
|
||||
<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_language">Idioma</string>
|
||||
<string name="language_hint">Solo la interfaz. Los modelos responden en el idioma en el que usted les escribe, diga lo que diga esto.</string>
|
||||
<string name="language_account">Igual que mi cuenta</string>
|
||||
<string name="language_account_is">Igual que mi cuenta: %1$s</string>
|
||||
<string name="language_account_unknown">Aún no se ha leído de su instancia</string>
|
||||
<string name="language_phone">Idioma del teléfono</string>
|
||||
<string name="language_phone_is">Idioma del teléfono: %1$s</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>
|
||||
@@ -157,6 +372,9 @@
|
||||
<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_model">Modelo del asistente</string>
|
||||
<string name="assistant_model_default">Predeterminado de la instancia</string>
|
||||
<string name="assistant_model_default_line">El modelo con el que empiezan tus chats nuevos. Si es demasiado lento para una pregunta hablada, elige abajo uno más rápido.</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>
|
||||
@@ -168,11 +386,223 @@
|
||||
<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="update_checking">Comprobando…</string>
|
||||
<string name="update_available">%1$s está disponible. Toque para abrir su página de publicación.</string>
|
||||
<string name="update_install">Instalar %1$s</string>
|
||||
<string name="update_auto">Buscar nuevas versiones</string>
|
||||
<string name="update_auto_line">Como mucho una vez al día, al iniciarse, la aplicación pregunta a su instancia qué versión le corresponde (con una instancia más antigua, lee la lista de versiones en GitHub) y le avisa con una notificación cuando hay una más reciente. No se envía nada sobre usted a ningún otro sitio. Activado por defecto en una beta; si no, desactivado.</string>
|
||||
<string name="update_betas">Incluir betas</string>
|
||||
<string name="update_betas_line">Ofrecer también versiones de prueba, no solo publicaciones. Activado por defecto cuando esta aplicación es una beta.</string>
|
||||
<string name="channel_updates">Actualizaciones de la aplicación</string>
|
||||
<string name="update_notice_title">LLeMbas para Android %1$s</string>
|
||||
<string name="update_notice_text">Hay una versión más reciente. Toque para abrir su página de publicación.</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="assist_use_screen">Usar la pantalla</string>
|
||||
<string name="assist_screen_both">El texto de la pantalla y una captura irán con su próxima pregunta.</string>
|
||||
<string name="assist_screen_text">El texto de la pantalla irá con su próxima pregunta.</string>
|
||||
<string name="assist_screen_shot">Una captura de pantalla irá con su próxima pregunta.</string>
|
||||
<string name="assist_quick_summarise">Resumir</string>
|
||||
<string name="assist_quick_summarise_prompt">Resume lo que hay en mi pantalla.</string>
|
||||
<string name="assist_quick_translate">Traducir</string>
|
||||
<string name="assist_quick_translate_prompt">Traduce al español lo que hay en mi pantalla.</string>
|
||||
<string name="assist_quick_explain">Explicar</string>
|
||||
<string name="assist_quick_explain_prompt">Explica lo que hay en mi pantalla.</string>
|
||||
<string name="assist_continue">Continuar el último chat</string>
|
||||
<string name="assist_help">Mantenga pulsado el botón de encendido para abrir el asistente sobre cualquier app, o use el mosaico de Ajustes rápidos.</string>
|
||||
<string name="assist_connecting">Conectando…</string>
|
||||
<string name="assist_offline">No se puede contactar con %1$s</string>
|
||||
<string name="assist_no_model">Sin modelo</string>
|
||||
<string name="assist_voice_reply_on">Respuesta por voz activada</string>
|
||||
<string name="assist_voice_reply_off">Respuesta por voz desactivada</string>
|
||||
<string name="assist_read_aloud">Leer en voz alta</string>
|
||||
<string name="assist_stop_reading">Dejar de leer</string>
|
||||
<string name="assist_answer_in_app">Esta respuesta espera su decisión: ábrala en la app.</string>
|
||||
<string name="assist_send_now">Enviar lo que he dicho</string>
|
||||
<string name="assist_say_it">Dígalo y haga una pausa</string>
|
||||
<string name="assist_type">Escribir en su lugar</string>
|
||||
<string name="assist_writing_down">Escribiendo lo que ha dicho…</string>
|
||||
<string name="assist_unlock_to_send">Desbloquear para enviar</string>
|
||||
<string name="assist_question_heard">Pregunta oída</string>
|
||||
<string name="assist_recording_waits_line">El teléfono está bloqueado. Tu pregunta espera en este teléfono como grabación; no se ha enviado nada. Al desbloquear se envía a tu instancia para transcribirla y responderla.</string>
|
||||
<string name="assist_locked_line">El teléfono está bloqueado. Hasta que lo desbloquees no se envía nada ni se muestra ninguna respuesta.</string>
|
||||
<string name="assist_conversation">En conversación</string>
|
||||
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Di «para» para terminar.</string>
|
||||
<string name="assist_conversation_end">Terminar</string>
|
||||
<string name="assist_stop_words">para|stop|basta|eso es todo|ya está|adiós|terminar|fin|gracias eso es todo|cancelar</string>
|
||||
<string name="assistant_conversation">Mantener una conversación hablada</string>
|
||||
<string name="assistant_conversation_line">Después de leer en voz alta una respuesta hablada, el asistente vuelve a escuchar, hasta que digas «para», toques Terminar o no digas nada durante unos segundos. Funciona con auriculares.</string>
|
||||
<string name="experimental">Experimental</string>
|
||||
<string name="wake_experimental_line">Nuevo y probado por ahora en pocos teléfonos. Puede no oír la frase, activarse por error u oírte y aun así no abrir el asistente.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimental: escuchar por sí solo al abrir el asistente, notar cuándo has terminado de hablar y la conversación hablada son nuevos y todavía no funcionan bien en todos los teléfonos. Escribir una pregunta y el botón del micrófono funcionan siempre.</string>
|
||||
<string name="assist_wake_word_hint">Sin palabra de activación salvo que quieras una: Ajustes › Asistente › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
|
||||
<string name="channel_wake">Palabra de activación</string>
|
||||
<string name="wake_word">Palabra de activación</string>
|
||||
<string name="wake_word_listen">Escuchar una palabra de activación</string>
|
||||
<string name="wake_word_line">Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.</string>
|
||||
<string name="wake_word_unavailable">No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.</string>
|
||||
<string name="wake_phrase_line">Lo que dices, y después una pausa breve: cuenta cuando te callas. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa.</string>
|
||||
<string name="wake_greeting">Saludo</string>
|
||||
<string name="wake_name">Nombre</string>
|
||||
<string name="wake_name_google_line">Un teléfono o altavoz de Google cercano también responderá.</string>
|
||||
<string name="wake_sensitivity">Sensibilidad</string>
|
||||
<string name="wake_sensitivity_low">Baja</string>
|
||||
<string name="wake_sensitivity_low_line">Es la que menos se activa por error. Puede que tengas que decir la frase con más claridad, o dos veces.</string>
|
||||
<string name="wake_sensitivity_normal">Normal</string>
|
||||
<string name="wake_sensitivity_normal_line">El ajuste propio del motor.</string>
|
||||
<string name="wake_sensitivity_high">Alta</string>
|
||||
<string name="wake_sensitivity_high_line">Te oye con más facilidad, también desde más lejos. Se activa por error más a menudo.</string>
|
||||
<string name="wake_test">Probar la palabra de activación</string>
|
||||
<string name="wake_test_line">Durante diez segundos muestra si se oye tu frase, sin abrir el asistente.</string>
|
||||
<string name="wake_test_say">Di «%1$s» ahora y haz una pausa…</string>
|
||||
<string name="wake_test_heard">Oída</string>
|
||||
<string name="wake_test_missed">No se ha oído en diez segundos. Prueba más cerca del teléfono, en un momento más tranquilo o con más sensibilidad.</string>
|
||||
<string name="wake_test_off">Activa primero la palabra de activación.</string>
|
||||
<string name="wake_screen_only">Solo con la pantalla encendida</string>
|
||||
<string name="wake_screen_only_line">Desactivado: también escucha con la pantalla apagada, con más gasto de batería.</string>
|
||||
<string name="wake_battery">Dejar que funcione en segundo plano</string>
|
||||
<string name="wake_battery_line">Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluye aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de tu teléfono.</string>
|
||||
<string name="wake_word_privacy">Nada sale del teléfono antes de la palabra. El sonido del micrófono va solo al motor de palabra de activación del teléfono y no se guarda; la notificación se mantiene mientras escucha. Las frases están en inglés; el motor es sherpa-onnx (código abierto).</string>
|
||||
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.</string>
|
||||
<string name="wake_listening_for">Escuchando «%1$s»</string>
|
||||
<string name="wake_off">La palabra de activación no está escuchando</string>
|
||||
<string name="wake_tap_to_start">Toca para iniciarla de nuevo. Si Android pregunta, permite el micrófono.</string>
|
||||
<string name="wake_starting">Iniciando la palabra de activación…</string>
|
||||
<string name="wake_paused_silent">La palabra de activación no oye nada: otra app tiene el micrófono, o el micrófono del teléfono está apagado</string>
|
||||
<string name="wake_failed_no_engine">La palabra de activación no funciona: esta versión no tiene motor</string>
|
||||
<string name="wake_failed_model">La palabra de activación no funciona: no se pudo desempaquetar su modelo en este teléfono</string>
|
||||
<string name="wake_failed_engine">La palabra de activación no funciona: el motor no se inició</string>
|
||||
<string name="wake_failed_microphone">La palabra de activación no funciona: el micrófono no se inició</string>
|
||||
<string name="wake_failed_line">No está escuchando. Lo intenta de nuevo por sí sola.</string>
|
||||
<string name="wake_notification_line">Nada sale del teléfono hasta que lo digas.</string>
|
||||
<string name="wake_paused_screen">Palabra de activación en pausa: la pantalla está apagada</string>
|
||||
<string name="wake_paused_battery">Palabra de activación en pausa: ahorro de batería activado</string>
|
||||
<string name="wake_paused_assistant">Palabra de activación en pausa mientras el asistente está abierto</string>
|
||||
<string name="wake_paused_microphone">Palabra de activación en pausa: LLeMbas no tiene permiso para usar el micrófono</string>
|
||||
<string name="wake_stop">Dejar de escuchar</string>
|
||||
<string name="wake_heard">Te he oído. Toca para preguntar.</string>
|
||||
<string name="channel_wake_heard">Palabra de activación oída</string>
|
||||
<string name="wake_heard_line">LLeMbas solo puede abrirse por sí mismo sobre otras apps si es la app de asistente digital del teléfono.</string>
|
||||
<string name="wake_not_assistant">LLeMbas no es la app de asistente digital</string>
|
||||
<string name="wake_not_assistant_line">Por eso la palabra de activación no puede abrir el asistente sobre otras apps: recibes una notificación que tocar. Para abrir con la voz en cualquier parte, toca aquí y elige LLeMbas como app de asistente digital.</string>
|
||||
<string name="wake_last">Última activación</string>
|
||||
<string name="wake_last_none">Todavía no ha oído la frase.</string>
|
||||
<string name="wake_out_opened">Abrió el asistente.</string>
|
||||
<string name="wake_out_no_sheet">Pidió a Android que abriera el asistente; no se negó, pero no apareció el panel.</string>
|
||||
<string name="wake_out_not_connected">Android no tenía LLeMbas conectado como asistente, así que no pudo abrir el panel.</string>
|
||||
<string name="wake_out_refused">Android se negó a abrir el asistente: %1$s</string>
|
||||
<string name="wake_out_activity">En su lugar lo abrió como una pantalla de la app.</string>
|
||||
<string name="wake_out_notification">En su lugar envió una notificación para tocar.</string>
|
||||
<string name="wake_out_tested">Oída en una prueba: no había nada que abrir.</string>
|
||||
<string name="wake_role_held">LLeMbas era la app de asistente digital.</string>
|
||||
<string name="wake_role_not_held">LLeMbas no era la app de asistente digital.</string>
|
||||
<string name="wake_link_never">Android no había conectado el asistente desde que se inició la app.</string>
|
||||
<string name="wake_link_ready">Android había conectado el asistente a las %1$s.</string>
|
||||
<string name="wake_link_shutdown">Android lo había desconectado a las %1$s.</string>
|
||||
<string name="wake_link_later">Android volvió a conectarlo a las %1$s.</string>
|
||||
<string name="wake_sheet_ms">El panel apareció tras %1$s ms.</string>
|
||||
<string name="wake_no_recognizers">Este teléfono no tiene reconocedores de voz, así que Android no ejecuta en él ningún servicio de asistente de voz.</string>
|
||||
<string name="wake_not_active">LLeMbas estaba elegido como app de asistente digital, pero Android no lo usaba como asistente de voz.</string>
|
||||
<string name="wake_waited">Esperó un momento a que Android lo conectara.</string>
|
||||
<string name="wake_show_failed">Android dijo que no pudo mostrar el panel del asistente.</string>
|
||||
<string name="wake_assistant_inactive">Android no está usando LLeMbas como asistente de voz ahora mismo</string>
|
||||
<string name="wake_assistant_inactive_line">Elige de nuevo LLeMbas como app de asistente digital: toca aquí, elige otra app y luego LLeMbas. Hasta entonces la pulsación larga lo abre como una pantalla normal y la palabra de activación solo puede enviar una notificación.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas es el asistente, pero Android no lo tiene conectado ahora mismo</string>
|
||||
<string name="wake_assistant_unbound_line">Hasta que lo conecte, la palabra de activación no puede abrir el panel por sí sola. Toca para ir al ajuste del asistente del sistema: elegir otra app y luego LLeMbas de nuevo lo conecta.</string>
|
||||
<string name="wake_heard_could_not">No pudo abrirse por sí solo: toca para preguntar</string>
|
||||
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
|
||||
<string name="wake_resume_line">El teléfono se reinició. Toca para volver a escuchar.</string>
|
||||
<string name="assist_notifications">Resumir mis notificaciones</string>
|
||||
<string name="assist_notifications_prompt">Resume mis notificaciones: ¿qué necesita mi atención?</string>
|
||||
<string name="assist_notifications_phrases">mis notificaciones</string>
|
||||
<string name="notification_summaries">Resúmenes de notificaciones</string>
|
||||
<string name="notification_summaries_switch">Dejar que el asistente lea mis notificaciones cuando lo pida</string>
|
||||
<string name="notification_summaries_line">Pide «resume mis notificaciones» o toca el botón en el asistente.</string>
|
||||
<string name="notification_summaries_unavailable">No en esta versión. Leer notificaciones requiere la versión «notifications» de LLeMbas, porque Google Play Protect bloquea la instalación de una app de fuera de Play Store que pueda leerlas. Es la misma app con la misma firma: en la página de la versión, el archivo que termina en -notifications.apk se instala sobre esta.</string>
|
||||
<string name="update_notifications_manual">Esta es la versión «notifications»: instala la actualización desde su página, el archivo que termina en -notifications.apk.</string>
|
||||
<string name="notification_access">Acceso a notificaciones</string>
|
||||
<string name="notification_access_on">Concedido. El interruptor de Android está en los ajustes del sistema.</string>
|
||||
<string name="notification_access_off">Aún no concedido. Toca para abrir el interruptor de Android para LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Desactivado por defecto. Cuando lo pides, el texto de las notificaciones que hay ahora en tu teléfono (app, título, texto) va con esa única pregunta a tu instancia y su modelo. No se lee nada antes, la app no guarda nada y no se lee nada con el teléfono bloqueado. El acceso a notificaciones de Android permite a una app ver todas las notificaciones; darlo y retirarlo es cosa tuya.</string>
|
||||
<string name="nav_app">App de navegación</string>
|
||||
<string name="nav_app_auto">La que esté instalada</string>
|
||||
<string name="nav_app_google">Google Maps</string>
|
||||
<string name="nav_app_osmand">OsmAnd</string>
|
||||
<string name="nav_app_ask">Preguntar cada vez</string>
|
||||
<string name="nav_app_not_installed">No instalada</string>
|
||||
<string name="osmand_info">Preguntar a OsmAnd por la ruta</string>
|
||||
<string name="osmand_info_line">Permite «añadir una parada» y buscar cerca de ti con una ruta creada en el propio OsmAnd: LLeMbas pregunta a OsmAnd dónde estás y adónde va la ruta. Primero permite LLeMbas en OsmAnd (apps conectadas, con ubicación); OsmAnd te avisa si no está permitido.</string>
|
||||
<string name="phone_actions_line">Un modelo puede ofrecer hacer cosas en este teléfono: poner una alarma, añadir un evento, redactar un mensaje, iniciar una ruta. No pasa nada hasta que tocas Hacerlo en su tarjeta, y nunca con el teléfono bloqueado. Google Maps inicia una ruta con unas pocas paradas, pero no puede añadir una a una ruta en curso ni detenerse a petición; OsmAnd sí.</string>
|
||||
<string name="action_card_title">¿Hacer esto en tu teléfono?</string>
|
||||
<string name="action_do">Hacerlo</string>
|
||||
<string name="action_running">Haciéndolo…</string>
|
||||
<string name="action_unlock">Desbloquea primero el teléfono y luego toca Hacerlo.</string>
|
||||
<string name="action_failed">No funcionó: %1$s</string>
|
||||
<string name="nav_app_pick">¿Con qué app de mapas?</string>
|
||||
<string name="action_google_add_stop">Google Maps no puede añadir una parada a una ruta en curso: vuelve a iniciar la ruta, pasando por la parada.</string>
|
||||
<string name="action_google_no_stop">A Google Maps no se le puede pedir que pare: termina la ruta allí.</string>
|
||||
<string name="action_line_clock">La app de reloj lo programa.</string>
|
||||
<string name="action_line_calendar">El calendario se abre con el evento rellenado; tú lo guardas.</string>
|
||||
<string name="action_line_draft">Abre un borrador; lo envías tú.</string>
|
||||
<string name="action_line_dial">El marcador se abre con el número; tú haces la llamada.</string>
|
||||
<string name="action_line_map">%1$s se encarga de la ruta.</string>
|
||||
<string name="action_line_now">Ocurre al instante.</string>
|
||||
<string name="action_line_settings">Abre el ajuste; tú lo cambias.</string>
|
||||
<string name="action_line_automation">Ejecuta tu automatización (Tasker salvo que se indique otra app).</string>
|
||||
<string name="action_line_open">Lo abre.</string>
|
||||
<string name="assist_recogniser_failed">El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.</string>
|
||||
<string name="assistant_listens">Empezar a escuchar al abrir el asistente</string>
|
||||
<string name="voice_input">Entrada de voz</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">La conversión de voz a texto de su instancia, a través del servidor. La grabación va a su instancia y a ningún otro sitio.</string>
|
||||
<string name="voice_input_phone">Teléfono (Google o el del sistema)</string>
|
||||
<string name="voice_input_phone_line">El reconocimiento de voz del propio teléfono. Las palabras aparecen mientras habla; la grabación va adonde ese reconocimiento la envíe.</string>
|
||||
<string name="voice_input_phone_none">Este teléfono no tiene reconocimiento de voz propio.</string>
|
||||
<string name="voice_input_hint">La usan el asistente y el micrófono de un chat. Con LLeMbas el asistente muestra las palabras un momento después y una pausa las envía, y un chat las escribe cuando usted para; con el reconocimiento del teléfono aparecen mientras habla.</string>
|
||||
<string name="share_sending">Enviando a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Échele un vistazo a esto.</string>
|
||||
<string name="share_ask_hint">¿Qué debe hacer LLeMbas con esto? (opcional)</string>
|
||||
<string name="widget_hint">Pregunta lo que quieras</string>
|
||||
<string name="directory_places">Lugares de este dispositivo</string>
|
||||
<string name="directory_last_used">Último usado aquí: %1$s. Un chat nuevo en este directorio empieza con él salvo que elija otro.</string>
|
||||
<string name="directory_refused">El dispositivo no abrirá una sesión aquí.</string>
|
||||
<string name="directory_up">Subir un nivel</string>
|
||||
<string name="directory_all_places">Todos los lugares</string>
|
||||
<string name="directory_not_trusted">No es de confianza en el dispositivo</string>
|
||||
<string name="directory_empty">Aquí no hay carpetas.</string>
|
||||
<string name="directory_no_places">Este dispositivo no ofrece carpetas: sus raíces remotas están vacías o no existen.</string>
|
||||
<string name="directory_browse">Examinar</string>
|
||||
<string name="directory_path">Una ruta completa</string>
|
||||
<string name="directory_choose">Elegir</string>
|
||||
<string name="directory_no_listing">Ahora no se pueden listar las carpetas de este dispositivo. Escriba la ruta abajo.</string>
|
||||
<string name="model">Modelo</string>
|
||||
<string name="schedule_type">Tipo</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Se ejecuta en este servidor, como un chat: con las herramientas del servidor (búsqueda, sus archivos aquí, memoria) y en un modelo de programación.</string>
|
||||
<string name="schedule_agentic">Agéntico</string>
|
||||
<string name="schedule_agentic_line">Se ejecuta en uno de sus ordenadores, en una carpeta de él, como agente: con las herramientas del agente en ese ordenador — sus archivos y su shell — dentro de los límites propios del ordenador. Pertenece a ese ordenador y a esa carpeta.</string>
|
||||
<string name="schedule_agentic_unavailable">Ninguno de sus ordenadores acepta trabajo programado ahora. Vincule uno y active «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">no acepta trabajo programado</string>
|
||||
<string name="schedule_computer_hint">El ordenador debe permitirlo: «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on). Si no está vinculado en el momento de una ejecución, la ejecución lo espera; si no ha vuelto antes de que pase su hora, la ejecución se registra como perdida y se le avisa.</string>
|
||||
<string name="schedule_computer_gone">un ordenador que ya no tiene sesión iniciada</string>
|
||||
<string name="schedule_folder">Carpeta en el ordenador</string>
|
||||
<string name="schedule_agent_mode">Modo</string>
|
||||
<string name="schedule_agent_mode_hint">Edit salvo que elijas otro; Auto ejecuta comandos sin preguntar. El ordenador puede rebajarlo.</string>
|
||||
<string name="schedule_approval_wait">Una aprobación espera (minutos)</string>
|
||||
<string name="schedule_approval_wait_hint">Un comando que la ejecución necesita aprobar llega a tu teléfono como tarjeta. Sin respuesta para entonces, cuenta como denegado.</string>
|
||||
<string name="schedule_watch_command_hint">Opcional, en el ordenador. Se ejecuta en la carpeta antes de cada ejecución; cuando su salida es la misma que la última vez, la ejecución se detiene ahí. Se rechaza un comando por el que el modo preguntaría.</string>
|
||||
<string name="schedule_watch_timeout">El comando puede tardar (segundos)</string>
|
||||
<string name="schedule_watch_timeout_hint">Después se detiene y la ejecución falla.</string>
|
||||
<string name="schedule_chat_drops_watch">Esta tarea vigila un comando en su ordenador. Como tarea de tipo Chat ya no lo hace: se ejecuta siempre.</string>
|
||||
<string name="schedule_folder_model">El modelo habitual de la carpeta</string>
|
||||
<string name="schedule_folder_model_hint">El modelo habitual de la carpeta es el último que usó en esa carpeta de ese ordenador — el ordenador lo recuerda y cada ejecución se lo pregunta — o su modelo predeterminado donde no hay ninguno. Un modelo elegido aquí es el de la ejecución, sea cual sea el de la carpeta. Una ejecución nunca cambia el modelo de la carpeta.</string>
|
||||
<string name="schedule_first_free_model">El primero libre de sus modelos para programación</string>
|
||||
<string name="run_model_directory">el modelo habitual de la carpeta</string>
|
||||
<string name="run_model_default">su modelo predeterminado</string>
|
||||
<string name="run_model_session">el modelo propio de la conversación</string>
|
||||
<string name="widget_speak">Hablar</string>
|
||||
<string name="widget_description">Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.</string>
|
||||
<string name="shortcut_last">Último chat</string>
|
||||
</resources>
|
||||
@@ -14,10 +14,7 @@
|
||||
<string name="signin_too_old">Cette instance utilise une version plus ancienne de LLeMbas. Cette application nécessite LLeMbas 2.0 ou plus récent.</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">Pas encore de conversation d\'agent. Démarrez-en une avec Nouvelle conversation d\'agent, sur un appareil associé à cette instance.</string>
|
||||
<string name="new_agent_chat">Nouvelle conversation d\'agent</string>
|
||||
<string name="agent_device">Appareil</string>
|
||||
<string name="agent_no_device">Aucun appareil n\'est associé pour l\'instant. Lancez `lembas service` sur un ordinateur connecté à cette instance, puis revenez.</string>
|
||||
@@ -26,6 +23,28 @@
|
||||
<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="archived">Archivées</string>
|
||||
<string name="archived_restore">Restaurer la conversation</string>
|
||||
<string name="archived_none">Aucune conversation archivée.</string>
|
||||
<string name="memory">Mémoire</string>
|
||||
<string name="memory_intro">Ce que les modèles retiennent de vous</string>
|
||||
<string name="memory_none">Rien pour l\'instant. Un modèle disposant de l\'outil de mémoire ajoute ici ce que vous lui dites qui vaut la peine d\'être retenu.</string>
|
||||
<string name="memory_remember">Retenir</string>
|
||||
<string name="memory_label">Ce que dit ce souvenir</string>
|
||||
<string name="memory_hint">Quelque chose qui vaut la peine d\'être retenu</string>
|
||||
<string name="memory_group">Groupe de données</string>
|
||||
<string name="memory_forget">Oublier</string>
|
||||
<string name="memory_by_model">Modèle</string>
|
||||
<string name="chats_pinned">Discussions épinglées</string>
|
||||
<string name="chat_pin">Épingler la discussion</string>
|
||||
<string name="chat_unpin">Désépingler la discussion</string>
|
||||
<string name="folder_move">Déplacer vers un dossier</string>
|
||||
<string name="folder_none">Aucun dossier</string>
|
||||
<string name="folder_new">Nouveau dossier</string>
|
||||
<string name="folder_name">Nom du dossier</string>
|
||||
<string name="folder_rename">Renommer le dossier</string>
|
||||
<string name="folder_delete">Supprimer le dossier</string>
|
||||
<string name="folder_delete_confirm">Supprimer le dossier « %1$s » ? Les conversations qu\'il contient sont conservées.</string>
|
||||
<string name="delete">Supprimer</string>
|
||||
<string name="edit">Modifier</string>
|
||||
<string name="regenerate">Régénérer</string>
|
||||
@@ -43,6 +62,8 @@
|
||||
<string name="attach_take_photo">Prendre une photo</string>
|
||||
<string name="attach_choose_photos">Choisir des photos</string>
|
||||
<string name="attach_choose_files">Choisir des fichiers</string>
|
||||
<string name="image_generate">Générer des images</string>
|
||||
<string name="image_generated">L\'image générée</string>
|
||||
<string name="copy_message">Copier le message</string>
|
||||
<string name="copied">Copié.</string>
|
||||
<string name="rename_chat">Renommer la conversation</string>
|
||||
@@ -79,11 +100,18 @@
|
||||
<string name="ctx_since">Depuis la dernière réponse</string>
|
||||
<string name="ctx_buffer">Réserve de compactage</string>
|
||||
<string name="ctx_free">Espace libre</string>
|
||||
<string name="outputs_empty">Aucun fichier n’a encore été écrit dans cette conversation.</string>
|
||||
<string name="tasks_empty">Rien ne tourne en arrière-plan. Les assistants, les commandes et les membres d’une équipe s’affichent ici pendant qu’ils travaillent.</string>
|
||||
<string name="tasks_empty">Rien ne tourne en arrière-plan. Les sous-agents, les commandes et les membres d\'une équipe apparaissent ici pendant qu\'ils travaillent.</string>
|
||||
<string name="tasks_none_running">Rien en cours.</string>
|
||||
<string name="agents_one_working">1 agent au travail</string>
|
||||
<string name="agents_n_working">%1$s agents au travail</string>
|
||||
<string name="tasks_running">En cours</string>
|
||||
<string name="tasks_finished">Terminées</string>
|
||||
<string name="tasks_n_running">%1$s en cours</string>
|
||||
<string name="tasks_nested">%1$s en dessous</string>
|
||||
<string name="task_subagent">Sous-agent</string>
|
||||
<string name="task_command">Commande</string>
|
||||
<string name="task_member">Membre de l\'équipe</string>
|
||||
<string name="activity_until_compact">%1$s avant le compactage automatique</string>
|
||||
<string name="activity_compact_off">Le compactage automatique est désactivé.</string>
|
||||
<string name="activity_compact">Compacter</string>
|
||||
<string name="agents_n_queued">%1$s en file d’attente</string>
|
||||
<string name="agents_n_waiting">%1$s en attente</string>
|
||||
<string name="agents_n_finished">%1$s terminés</string>
|
||||
@@ -100,28 +128,208 @@
|
||||
<string name="agent_stop_confirm">Arrêter %1$s ? Ce qu’il a déjà fait reste.</string>
|
||||
<string name="agent_nothing_yet">Rien de dit pour l’instant.</string>
|
||||
<string name="agent_machine">Du système</string>
|
||||
<string name="team_size">Équipe : %1$s agents sur %2$s</string>
|
||||
<string name="team_size">Équipe : %1$s sur %2$s sous-agents</string>
|
||||
<string name="team_room">Salle</string>
|
||||
<string name="room_empty">Rien n’a encore été dit dans la salle.</string>
|
||||
<string name="room_report">rapport</string>
|
||||
<string name="team_agents">Agents</string>
|
||||
<string name="team_fewest">Au moins</string>
|
||||
<string name="team_most">Au plus</string>
|
||||
<string name="team_hint">Son propre agent compris. Au-delà d’un, il peut ajouter des membres qui font le travail pendant qu’il les dirige.</string>
|
||||
<string name="team_chip">Agents %1$s–%2$s</string>
|
||||
<string name="team_agents">Sous-agents</string>
|
||||
<string name="team_min">Min</string>
|
||||
<string name="team_max">Max</string>
|
||||
<string name="team_range">Min %1$s · Max %2$s</string>
|
||||
<string name="team_hint">Les nombres comptent l\'agent de ce chat : 1, c\'est l\'agent seul, sans sous-agents, et Max 4, l\'agent et jusqu\'à 3 sous-agents qu\'il dirige.</string>
|
||||
<string name="team_chip">Sous-agents: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Ce modèle ne traite qu\'une requête à la fois : les sous-agents ont besoin d\'un autre modèle, sur un autre serveur, nommé dans le chat.</string>
|
||||
<string name="thinking_switch">Réfléchir avant de répondre</string>
|
||||
<string name="effort_level">Effort : %1$s</string>
|
||||
<string name="level_off">désactivé</string>
|
||||
<string name="level_default">par défaut</string>
|
||||
<string name="chats_open">Ouvrir les discussions</string>
|
||||
<string name="chats_search">Rechercher dans les discussions</string>
|
||||
<string name="chats_today">Aujourd’hui</string>
|
||||
<string name="chats_earlier">Plus tôt</string>
|
||||
<string name="chats_agents">Discussions d’agent</string>
|
||||
<string name="chats_found_in_messages">Dans les messages</string>
|
||||
<string name="chats_none_found">Aucune discussion ne l’a dans son titre.</string>
|
||||
<string name="clear">Effacer</string>
|
||||
<string name="composer_hint_agent">Dites à l’agent quoi faire</string>
|
||||
<string name="tune">Options</string>
|
||||
<string name="effort">Effort</string>
|
||||
<string name="thinking_switch_hint">Plus lent, et meilleur sur les questions difficiles.</string>
|
||||
<string name="plan_first">D’abord un plan</string>
|
||||
<string name="plan_first_hint">Le modèle rédige un plan que vous approuvez avant qu’il agisse.</string>
|
||||
<string name="agent_mode">Mode</string>
|
||||
<string name="agent_greeting">Que doit faire l’agent ?</string>
|
||||
<string name="agent_runs_on">S’exécute sur %1$s, dans %2$s</string>
|
||||
<string name="agent_directory_default">son premier dossier</string>
|
||||
<string name="kind_chat">Conversation</string>
|
||||
<string name="kind_agent">Conversation d\'agent</string>
|
||||
<string name="kind_chat_line">Parlez avec un modèle : questions, rédaction, les fichiers que vous joignez.</string>
|
||||
<string name="kind_agent_line">Travaille sur un ordinateur que vous avez lié : lit, écrit et lance des commandes dans un dossier.</string>
|
||||
<string name="agent_link_title">Liez d’abord un ordinateur</string>
|
||||
<string name="agent_link_lede">Les conversations d\'agent s\'exécutent sur une machine dotée de la LLeMbas CLI, connectée à cette instance et reliée. Aucune n\'est reliée pour le moment.</string>
|
||||
<string name="agent_link_install">Installez-y la LLeMbas CLI :</string>
|
||||
<string name="agent_link_login">Connectez-le à cette instance et approuvez le code qu’il affiche dans le navigateur qui s’ouvre :</string>
|
||||
<string name="agent_link_service">Pour y exécuter des conversations d\'agent depuis ici, autorisez-le dans sa configuration (~/.config/lembas/config.yaml) et démarrez le service :</string>
|
||||
<string name="agent_link_dials_out">Elle se connecte d\'elle-même à cette instance ; rien n\'écoute sur votre machine. C\'est elle qui décide quels répertoires et quels modes le travail à distance peut utiliser, quoi qu\'on demande ici.</string>
|
||||
<string name="agent_link_check">Vérifier à nouveau</string>
|
||||
<string name="model_choose">Choisir un modèle</string>
|
||||
<string name="model_in_use">Utilisé</string>
|
||||
<string name="model_sees_images">Voit les images</string>
|
||||
<string name="model_uses_tools">Utilise des outils</string>
|
||||
<string name="model_context">contexte de %1$s</string>
|
||||
<string name="model_thinking_switchable">Réflexion activable</string>
|
||||
<string name="model_levels">Effort : %1$s</string>
|
||||
<string name="code">Code</string>
|
||||
<string name="copy_code">Copier le code</string>
|
||||
<string name="select_text">Sélectionner le texte</string>
|
||||
<string name="tools_used">%1$s outils utilisés</string>
|
||||
<string name="suggest_explain">Explique</string>
|
||||
<string name="suggest_explain_line">simplement comment quelque chose fonctionne</string>
|
||||
<string name="suggest_write">Rédige</string>
|
||||
<string name="suggest_write_line">un e-mail, une note ou un billet</string>
|
||||
<string name="suggest_plan">Planifie</string>
|
||||
<string name="suggest_plan_line">un voyage, une semaine ou un projet</string>
|
||||
<string name="suggest_check">Relis</string>
|
||||
<string name="suggest_check_line">un texte : fautes et ton</string>
|
||||
<string name="instance_in_use">Utilisée</string>
|
||||
<string name="notification_settings">Réglages des notifications</string>
|
||||
<string name="notification_settings_hint">Quels types arrivent, et comment : réponses, questions, résultats et échecs planifiés.</string>
|
||||
<string name="scheduled">Planifié</string>
|
||||
<string name="scheduled_empty">Rien n’est planifié. Demandez quelque chose chaque matin, ou une fois la semaine prochaine.</string>
|
||||
<string name="scheduled_unsupported">Cette instance ne propose pas encore de tâches planifiées. Elles arrivent avec un LLeMbas plus récent sur le serveur.</string>
|
||||
<string name="schedule_new">Nouvelle planification</string>
|
||||
<string name="schedule_edit">Modifier la planification</string>
|
||||
<string name="schedule_next">Prochaine : %1$s</string>
|
||||
<string name="schedule_paused">En pause</string>
|
||||
<string name="schedule_pause">Mettre en pause</string>
|
||||
<string name="schedule_resume">Reprendre</string>
|
||||
<string name="schedule_run_now">Exécuter maintenant</string>
|
||||
<string name="schedule_started">Lancé. Le résultat apparaît dans l’historique.</string>
|
||||
<string name="schedule_next_runs">Prochaines exécutions</string>
|
||||
<string name="schedule_history">Historique</string>
|
||||
<string name="schedule_no_runs">Elle ne s’est pas encore exécutée.</string>
|
||||
<string name="schedule_model">Modèle : %1$s</string>
|
||||
<string name="schedule_delete_confirm">Supprimer cette planification ? Ses résultats passés restent dans leurs discussions.</string>
|
||||
<string name="schedule_words_hint">Dites quand et quoi, avec vos mots. Vous verrez ce qui a été compris avant tout enregistrement.</string>
|
||||
<string name="schedule_words_example">Chaque jour ouvré à 7 h 30, résume l’actualité des énergies renouvelables</string>
|
||||
<string name="schedule_preview">Aperçu</string>
|
||||
<string name="schedule_understood">Compris comme</string>
|
||||
<string name="notify_always">Prévient à chaque fois</string>
|
||||
<string name="notify_matters">Prévient quand c’est important</string>
|
||||
<string name="notify_never">Ne prévient jamais</string>
|
||||
<string name="run_ok">Terminé</string>
|
||||
<string name="run_silent">Rien de neuf</string>
|
||||
<string name="run_unchanged">Inchangé</string>
|
||||
<string name="schedule_computer">Ordinateur</string>
|
||||
<string name="schedule_computer_away">non relié pour l’instant</string>
|
||||
<string name="schedule_watching">Seulement quand cette page change</string>
|
||||
<string name="schedule_watching_command">Seulement quand la sortie de cette commande change</string>
|
||||
<string name="run_failed">Échecs</string>
|
||||
<string name="run_missed">Manquée ×%1$s</string>
|
||||
<string name="run_skipped">Sautée</string>
|
||||
<string name="run_waiting">En attente d’un modèle</string>
|
||||
<string name="run_waiting_computer">En attente de l’ordinateur</string>
|
||||
<string name="run_running">En cours</string>
|
||||
<string name="run_model_instead">%1$s, au lieu de %2$s</string>
|
||||
<string name="run_retry_at">Nouvel essai à %1$s</string>
|
||||
<string name="run_result">Résultat</string>
|
||||
<string name="run_no_text">Cette exécution n’a laissé aucun texte.</string>
|
||||
<string name="run_open_chat">Ouvrir sa conversation</string>
|
||||
<string name="mode_fresh">Une nouvelle discussion à chaque fois</string>
|
||||
<string name="mode_continue">Une discussion qui s’allonge</string>
|
||||
<string name="schedule_models">Modèles pour les tâches planifiées</string>
|
||||
<string name="schedule_models_hint">Les tâches planifiées prennent le premier de ces modèles qui est libre, dans cet ordre. Décochez-en un pour l’écarter.</string>
|
||||
<string name="model_free">Libre maintenant</string>
|
||||
<string name="model_busy">Occupé : %1$s</string>
|
||||
<string name="channel_scheduled">Résultats planifiés</string>
|
||||
<string name="channel_scheduled_failures">Échecs planifiés</string>
|
||||
<string name="scheduled_result_public">Une tâche planifiée a un résultat.</string>
|
||||
<string name="scheduled_failed_public">Une tâche planifiée a échoué.</string>
|
||||
<string name="page_note">Cette réponse contient une page : %1$s</string>
|
||||
<string name="page_where">Ouvrez-la sur le web ou dans LLeMbas Desktop pour la voir.</string>
|
||||
<string name="page_untitled">Page</string>
|
||||
<string name="reports">Rapports</string>
|
||||
<string name="report">Rapport</string>
|
||||
<string name="reports_none">Pas encore de rapport. Une tâche planifiée en rédige un quand elle a quelque chose à vous dire.</string>
|
||||
<string name="reports_unsupported">Cette instance utilise un LLeMbas qui n’a pas encore les Rapports.</string>
|
||||
<string name="report_untitled">Rapport sans titre</string>
|
||||
<string name="report_delete_title">Supprimer ce rapport ?</string>
|
||||
<string name="report_delete_line">« %1$s » est supprimé définitivement, avec la conversation à son sujet.</string>
|
||||
<string name="report_mark_read">Marquer comme lu</string>
|
||||
<string name="report_important">Important</string>
|
||||
<string name="report_share">Partager</string>
|
||||
<string name="report_reply">Répondre</string>
|
||||
<string name="report_chat_title">Rapport : %1$s</string>
|
||||
<string name="notify_when">Prévenir quand</string>
|
||||
<string name="notify_every_run">À chaque exécution</string>
|
||||
<string name="notify_every_run_line">Le modèle rédige un rapport à chaque fois, même quand rien n’a été trouvé.</string>
|
||||
<string name="notify_when_option">Quand…</string>
|
||||
<string name="notify_when_line">Le modèle ne rédige un rapport que si ceci est vrai.</string>
|
||||
<string name="notify_when_label">Quand quoi ?</string>
|
||||
<string name="notify_when_default">quelque chose demande mon attention</string>
|
||||
<string name="notify_never_option">Jamais</string>
|
||||
<string name="notify_never_line">Aucun rapport : les exécutions restent seulement dans l’historique de la tâche.</string>
|
||||
<string name="notify_when_words">Prévient quand : %1$s</string>
|
||||
<string name="run_open_report">Ouvrir son rapport</string>
|
||||
<string name="channel_reports">Rapports</string>
|
||||
<string name="channel_reports_high">Rapports importants</string>
|
||||
<string name="report_new_public">Nouveau rapport</string>
|
||||
<string name="schedule_run_again">Relancer</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_allow_always">Toujours autoriser</string>
|
||||
<string name="card_deny">Refuser</string>
|
||||
<string name="card_deny_reason">Refuser, et dire pourquoi</string>
|
||||
<string name="plan_approve_edit">Approuver, continuer en mode Modifier</string>
|
||||
<string name="plan_approve_manual">Approuver, continuer en mode Manuel</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="progress_queued">En file d’attente</string>
|
||||
<string name="progress_queued_ahead">En file d’attente : %1$s avant</string>
|
||||
<string name="progress_waiting_for_model">En attente de %1$s : %2$s</string>
|
||||
<string name="progress_loading_model">Chargement de %1$s</string>
|
||||
<string name="progress_reading_prompt">Lecture du prompt : %1$s / %2$s jetons (%3$s %%)</string>
|
||||
<string name="progress_reading_prompt_bare">Lecture du prompt</string>
|
||||
<string name="progress_thinking">Réflexion</string>
|
||||
<string name="progress_writing">Écriture : %1$s jetons/s</string>
|
||||
<string name="progress_writing_bare">Écriture</string>
|
||||
<string name="progress_running_tool">Exécution de %1$s : %2$s</string>
|
||||
<string name="progress_running_tool_bare">Exécution de %1$s</string>
|
||||
<string name="progress_waiting_for_person">En attente de vous : %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">En attente des sous-agents : %1$s en cours</string>
|
||||
<string name="progress_compacting">Compactage de la conversation</string>
|
||||
<string name="progress_retrying">Nouvel essai dans %1$s s : %2$s</string>
|
||||
<string name="progress_stopped">Arrêté</string>
|
||||
<string name="progress_stopped_reason">Arrêté : %1$s</string>
|
||||
<string name="progress_failed">Échec : %1$s</string>
|
||||
<string name="progress_reason_busy">il traite une requête à la fois et en traite une autre</string>
|
||||
<string name="progress_reason_slots">tous ses emplacements sont occupés</string>
|
||||
<string name="progress_reason_group">son serveur a maintenant un autre modèle chargé</string>
|
||||
<string name="progress_what_approval">autoriser %1$s ?</string>
|
||||
<string name="progress_what_approval_bare">une approbation</string>
|
||||
<string name="progress_what_question">une question</string>
|
||||
<string name="progress_what_plan">le plan</string>
|
||||
<string name="progress_stopped_person">par vous</string>
|
||||
<string name="progress_stopped_steps">limite d’étapes</string>
|
||||
<string name="progress_stopped_budget">budget</string>
|
||||
<string name="tree_state_working">au travail</string>
|
||||
<string name="tree_state_waiting">attend une place</string>
|
||||
<string name="tree_state_finished">terminé</string>
|
||||
<string name="tree_state_idle">inactif</string>
|
||||
<string name="tree_state_paused">en pause : contexte plein</string>
|
||||
<string name="tree_state_done">terminé</string>
|
||||
<string name="tree_state_out_of_context">contexte épuisé</string>
|
||||
<string name="tree_state_stopped">arrêté</string>
|
||||
<string name="tree_context">%1$s%% du contexte</string>
|
||||
<string name="tree_open_slots">Places libres : %1$s</string>
|
||||
<string name="subagents_device_cannot">L’ordinateur sur lequel tourne cette conversation n’exécute pas de sous-agents : mettez-y à jour LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s demande :</string>
|
||||
<string name="card_subagent_asks">Le sous-agent %1$s (%2$s), %3$s, demande :</string>
|
||||
<string name="card_it_says">Il dit : %1$s</string>
|
||||
<string name="card_change_before">Modifier ceci avant l\'exécution</string>
|
||||
<string name="card_edit_runs">Autoriser exécute ce qui se trouve dans le champ. Ce n\'est pas revérifié par rapport aux règles de cette conversation — c\'est vous qui l\'avez saisi.</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>
|
||||
@@ -146,6 +354,13 @@
|
||||
<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_language">Langue</string>
|
||||
<string name="language_hint">L\'interface uniquement. Les modèles répondent dans la langue dans laquelle vous leur écrivez, quoi qu\'indique ce réglage.</string>
|
||||
<string name="language_account">Comme mon compte</string>
|
||||
<string name="language_account_is">Comme mon compte : %1$s</string>
|
||||
<string name="language_account_unknown">Pas encore lue sur votre instance</string>
|
||||
<string name="language_phone">Langue du téléphone</string>
|
||||
<string name="language_phone_is">Langue du téléphone : %1$s</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>
|
||||
@@ -157,6 +372,9 @@
|
||||
<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_model">Modèle de l’assistant</string>
|
||||
<string name="assistant_model_default">Modèle par défaut de l’instance</string>
|
||||
<string name="assistant_model_default_line">Le modèle avec lequel commencent vos nouvelles discussions. S’il est trop lent pour une question orale, choisissez-en un plus rapide ci-dessous.</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>
|
||||
@@ -168,11 +386,223 @@
|
||||
<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="update_checking">Vérification…</string>
|
||||
<string name="update_available">%1$s est disponible. Touchez pour ouvrir sa page de publication.</string>
|
||||
<string name="update_install">Installer %1$s</string>
|
||||
<string name="update_auto">Rechercher de nouvelles versions</string>
|
||||
<string name="update_auto_line">Au plus une fois par jour, au démarrage, l’application demande à votre instance quelle version lui correspond (avec une instance plus ancienne, elle lit la liste des versions sur GitHub) et vous prévient par une notification lorsqu’il en existe une plus récente. Rien sur vous n’est envoyé ailleurs. Activé par défaut dans une bêta, désactivé sinon.</string>
|
||||
<string name="update_betas">Inclure les bêtas</string>
|
||||
<string name="update_betas_line">Proposer aussi les versions de test, pas seulement les publications. Activé par défaut quand cette application est elle-même une bêta.</string>
|
||||
<string name="channel_updates">Mises à jour de l’application</string>
|
||||
<string name="update_notice_title">LLeMbas pour Android %1$s</string>
|
||||
<string name="update_notice_text">Une version plus récente est disponible. Touchez pour ouvrir sa page de publication.</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="assist_use_screen">Utiliser l’écran</string>
|
||||
<string name="assist_screen_both">Le texte de l’écran et une capture accompagneront votre prochaine question.</string>
|
||||
<string name="assist_screen_text">Le texte de l’écran accompagnera votre prochaine question.</string>
|
||||
<string name="assist_screen_shot">Une capture d’écran accompagnera votre prochaine question.</string>
|
||||
<string name="assist_quick_summarise">Résumer</string>
|
||||
<string name="assist_quick_summarise_prompt">Résume ce qui est sur mon écran.</string>
|
||||
<string name="assist_quick_translate">Traduire</string>
|
||||
<string name="assist_quick_translate_prompt">Traduis en français ce qui est sur mon écran.</string>
|
||||
<string name="assist_quick_explain">Expliquer</string>
|
||||
<string name="assist_quick_explain_prompt">Explique ce qui est sur mon écran.</string>
|
||||
<string name="assist_continue">Reprendre la dernière conversation</string>
|
||||
<string name="assist_help">Maintenez le bouton marche/arrêt pour ouvrir l’assistant par-dessus n’importe quelle app, ou utilisez la tuile des Réglages rapides.</string>
|
||||
<string name="assist_connecting">Connexion…</string>
|
||||
<string name="assist_offline">%1$s est injoignable</string>
|
||||
<string name="assist_no_model">Aucun modèle</string>
|
||||
<string name="assist_voice_reply_on">Réponse vocale activée</string>
|
||||
<string name="assist_voice_reply_off">Réponse vocale désactivée</string>
|
||||
<string name="assist_read_aloud">Lire à voix haute</string>
|
||||
<string name="assist_stop_reading">Arrêter la lecture</string>
|
||||
<string name="assist_answer_in_app">Cette réponse attend votre décision : ouvrez-la dans l’app.</string>
|
||||
<string name="assist_send_now">Envoyer ce que j’ai dit</string>
|
||||
<string name="assist_say_it">Dites-le, puis marquez une pause</string>
|
||||
<string name="assist_type">Taper plutôt</string>
|
||||
<string name="assist_writing_down">Transcription de ce que vous avez dit…</string>
|
||||
<string name="assist_unlock_to_send">Déverrouiller pour envoyer</string>
|
||||
<string name="assist_question_heard">Question entendue</string>
|
||||
<string name="assist_recording_waits_line">Le téléphone est verrouillé. Votre question attend sur ce téléphone sous forme d’enregistrement ; rien n’a été envoyé. Au déverrouillage, elle est envoyée à votre instance pour être transcrite et recevoir une réponse.</string>
|
||||
<string name="assist_locked_line">Le téléphone est verrouillé. Rien n’est envoyé et aucune réponse n’est affichée tant que vous ne l’avez pas déverrouillé.</string>
|
||||
<string name="assist_conversation">En conversation</string>
|
||||
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
|
||||
<string name="assist_conversation_end">Terminer</string>
|
||||
<string name="assist_stop_words">stop|arrête|c\'est tout|ça suffit|au revoir|fin|terminé|merci c\'est tout|annuler</string>
|
||||
<string name="assistant_conversation">Poursuivre une conversation orale</string>
|
||||
<string name="assistant_conversation_line">Après la lecture d’une réponse orale, l’assistant écoute à nouveau — jusqu’à ce que vous disiez « stop », touchiez Terminer ou ne disiez rien pendant quelques secondes. Fonctionne avec un casque.</string>
|
||||
<string name="experimental">Expérimental</string>
|
||||
<string name="wake_experimental_line">Nouveau, et essayé sur peu de téléphones pour l’instant. Il peut ne pas entendre la phrase, se déclencher par erreur, ou vous entendre sans pour autant ouvrir l’assistant.</string>
|
||||
<string name="assistant_voice_experimental_line">Expérimental : l’écoute automatique à l’ouverture de l’assistant, la détection de la fin de votre phrase et la conversation orale sont nouvelles et ne fonctionnent pas encore bien sur tous les téléphones. Écrire une question et le bouton du micro fonctionnent toujours.</string>
|
||||
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Assistant › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
|
||||
<string name="channel_wake">Mot d’activation</string>
|
||||
<string name="wake_word">Mot d’activation</string>
|
||||
<string name="wake_word_listen">Écouter un mot d’activation</string>
|
||||
<string name="wake_word_line">Désactivé par défaut. Dites la phrase et l’assistant s’ouvre en écoute, par-dessus l’app à l’écran.</string>
|
||||
<string name="wake_word_unavailable">Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un.</string>
|
||||
<string name="wake_phrase_line">Ce que vous dites, puis une courte pause : cela compte dès que vous vous taisez. En anglais, quelle que soit la langue de l’app : le moteur ne connaît que la parole anglaise.</string>
|
||||
<string name="wake_greeting">Salutation</string>
|
||||
<string name="wake_name">Nom</string>
|
||||
<string name="wake_name_google_line">Un téléphone ou une enceinte Google à proximité répondra aussi.</string>
|
||||
<string name="wake_sensitivity">Sensibilité</string>
|
||||
<string name="wake_sensitivity_low">Faible</string>
|
||||
<string name="wake_sensitivity_low_line">Se déclenche le moins souvent par erreur. Vous devrez peut-être dire la phrase plus distinctement, ou deux fois.</string>
|
||||
<string name="wake_sensitivity_normal">Normale</string>
|
||||
<string name="wake_sensitivity_normal_line">Le réglage propre au moteur.</string>
|
||||
<string name="wake_sensitivity_high">Élevée</string>
|
||||
<string name="wake_sensitivity_high_line">Vous entend le plus facilement, même de plus loin. Se déclenche plus souvent par erreur.</string>
|
||||
<string name="wake_test">Tester le mot d’activation</string>
|
||||
<string name="wake_test_line">Pendant dix secondes, indique si votre phrase est entendue, sans ouvrir l’assistant.</string>
|
||||
<string name="wake_test_say">Dites « %1$s » maintenant, puis faites une pause…</string>
|
||||
<string name="wake_test_heard">Entendu</string>
|
||||
<string name="wake_test_missed">Pas entendu en dix secondes. Essayez plus près du téléphone, dans un moment plus calme ou avec une sensibilité plus élevée.</string>
|
||||
<string name="wake_test_off">Activez d’abord le mot d’activation.</string>
|
||||
<string name="wake_screen_only">Seulement écran allumé</string>
|
||||
<string name="wake_screen_only_line">Désactivé : il écoute aussi écran éteint, au prix de plus de batterie.</string>
|
||||
<string name="wake_battery">Le laisser tourner en arrière-plan</string>
|
||||
<string name="wake_battery_line">Certains téléphones (Samsung, Xiaomi, Huawei, OnePlus et d’autres) arrêtent les apps en arrière-plan pour économiser la batterie, et le mot d’activation avec. Exemptez ici LLeMbas de l’optimisation de la batterie ; dontkillmyapp.com explique les réglages de votre téléphone.</string>
|
||||
<string name="wake_word_privacy">Rien ne quitte le téléphone avant le mot. Le son du micro ne va qu’au moteur de mot d’activation du téléphone et n’est pas conservé ; la notification reste affichée tant qu’il écoute. Les phrases sont en anglais ; le moteur est sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Cela consomme de la batterie : le micro reste allumé et le processeur du téléphone examine chaque instant de son, sans la puce basse consommation de l’assistant intégré. Il se met en pause en économie de batterie, quand l’assistant est ouvert et, sauf si vous le changez, écran éteint. Après un redémarrage, touchez sa notification pour le relancer.</string>
|
||||
<string name="wake_listening_for">À l’écoute de « %1$s »</string>
|
||||
<string name="wake_off">Le mot d’activation n’écoute pas</string>
|
||||
<string name="wake_tap_to_start">Touchez pour le relancer. Si Android le demande, autorisez le micro.</string>
|
||||
<string name="wake_starting">Démarrage du mot d’activation…</string>
|
||||
<string name="wake_paused_silent">Le mot d’activation n’entend rien : une autre app utilise le micro, ou le micro du téléphone est coupé</string>
|
||||
<string name="wake_failed_no_engine">Le mot d’activation ne fonctionne pas : cette version n’a pas de moteur</string>
|
||||
<string name="wake_failed_model">Le mot d’activation ne fonctionne pas : son modèle n’a pas pu être décompressé sur ce téléphone</string>
|
||||
<string name="wake_failed_engine">Le mot d’activation ne fonctionne pas : le moteur n’a pas démarré</string>
|
||||
<string name="wake_failed_microphone">Le mot d’activation ne fonctionne pas : le micro n’a pas démarré</string>
|
||||
<string name="wake_failed_line">Il n’écoute pas. Il réessaie de lui-même.</string>
|
||||
<string name="wake_notification_line">Rien ne quitte le téléphone avant que vous le disiez.</string>
|
||||
<string name="wake_paused_screen">Mot d’activation en pause : écran éteint</string>
|
||||
<string name="wake_paused_battery">Mot d’activation en pause : économiseur de batterie activé</string>
|
||||
<string name="wake_paused_assistant">Mot d’activation en pause pendant que l’assistant est ouvert</string>
|
||||
<string name="wake_paused_microphone">Mot d’activation en pause : LLeMbas n’est pas autorisé à utiliser le micro</string>
|
||||
<string name="wake_stop">Arrêter l’écoute</string>
|
||||
<string name="wake_heard">Entendu. Touchez pour demander.</string>
|
||||
<string name="channel_wake_heard">Mot d’activation entendu</string>
|
||||
<string name="wake_heard_line">LLeMbas ne peut s’ouvrir de lui-même par-dessus d’autres apps que s’il est l’assistant numérique du téléphone.</string>
|
||||
<string name="wake_not_assistant">LLeMbas n’est pas l’application d’assistant numérique</string>
|
||||
<string name="wake_not_assistant_line">Le mot d’activation ne peut donc pas ouvrir l’assistant par-dessus d’autres apps : vous recevez une notification à toucher. Pour ouvrir à la voix partout, touchez ici et choisissez LLeMbas comme application d’assistant numérique.</string>
|
||||
<string name="wake_last">Dernier réveil</string>
|
||||
<string name="wake_last_none">Il n’a pas encore entendu la phrase.</string>
|
||||
<string name="wake_out_opened">A ouvert l’assistant.</string>
|
||||
<string name="wake_out_no_sheet">A demandé à Android d’ouvrir l’assistant ; il n’a pas refusé, mais aucun panneau n’est apparu.</string>
|
||||
<string name="wake_out_not_connected">Android n’avait pas connecté LLeMbas comme assistant, le panneau n’a donc pas pu s’ouvrir.</string>
|
||||
<string name="wake_out_refused">Android a refusé d’ouvrir l’assistant : %1$s</string>
|
||||
<string name="wake_out_activity">L’a ouvert à la place comme un écran de l’app.</string>
|
||||
<string name="wake_out_notification">A envoyé à la place une notification à toucher.</string>
|
||||
<string name="wake_out_tested">Entendu pendant un test : il n’y avait rien à ouvrir.</string>
|
||||
<string name="wake_role_held">LLeMbas était l’application d’assistant numérique.</string>
|
||||
<string name="wake_role_not_held">LLeMbas n’était pas l’application d’assistant numérique.</string>
|
||||
<string name="wake_link_never">Android n’avait pas connecté l’assistant depuis le démarrage de l’app.</string>
|
||||
<string name="wake_link_ready">Android avait connecté l’assistant à %1$s.</string>
|
||||
<string name="wake_link_shutdown">Android l’avait déconnecté à %1$s.</string>
|
||||
<string name="wake_link_later">Android l’a reconnecté à %1$s.</string>
|
||||
<string name="wake_sheet_ms">Le panneau était affiché après %1$s ms.</string>
|
||||
<string name="wake_no_recognizers">Ce téléphone n’a pas de reconnaissance vocale, Android n’y exécute donc aucun service d’assistant vocal.</string>
|
||||
<string name="wake_not_active">LLeMbas était choisi comme application d’assistant numérique, mais Android ne l’utilisait pas comme assistant vocal.</string>
|
||||
<string name="wake_waited">A attendu un instant qu’Android le connecte.</string>
|
||||
<string name="wake_show_failed">Android a indiqué qu’il n’avait pas pu afficher le panneau de l’assistant.</string>
|
||||
<string name="wake_assistant_inactive">Android n’utilise pas LLeMbas comme assistant vocal pour l’instant</string>
|
||||
<string name="wake_assistant_inactive_line">Choisissez de nouveau LLeMbas comme application d’assistant numérique : touchez ici, prenez une autre app, puis LLeMbas. D’ici là, l’appui long l’ouvre comme un écran ordinaire et le mot d’activation ne peut qu’envoyer une notification.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas est l’assistant, mais Android ne l’a pas connecté pour l’instant</string>
|
||||
<string name="wake_assistant_unbound_line">Tant que ce n’est pas fait, le mot d’activation ne peut pas ouvrir le panneau de lui-même. Touchez pour le réglage de l’assistant du système : choisir une autre app puis de nouveau LLeMbas le reconnecte.</string>
|
||||
<string name="wake_heard_could_not">N’a pas pu s’ouvrir de lui-même — touchez pour demander</string>
|
||||
<string name="wake_resume">Écouter à nouveau le mot d’activation</string>
|
||||
<string name="wake_resume_line">Le téléphone a redémarré. Touchez pour reprendre l’écoute.</string>
|
||||
<string name="assist_notifications">Résumer mes notifications</string>
|
||||
<string name="assist_notifications_prompt">Résume mes notifications : qu’est-ce qui demande mon attention ?</string>
|
||||
<string name="assist_notifications_phrases">mes notifications</string>
|
||||
<string name="notification_summaries">Résumés des notifications</string>
|
||||
<string name="notification_summaries_switch">Laisser l’assistant lire mes notifications quand je le demande</string>
|
||||
<string name="notification_summaries_line">Demandez « résume mes notifications », ou touchez la puce dans l’assistant.</string>
|
||||
<string name="notification_summaries_unavailable">Pas dans cette version. Lire les notifications demande la version « notifications » de LLeMbas, car Google Play Protect bloque l’installation d’une app hors du Play Store capable de les lire. C’est la même app avec la même signature : sur la page de la version, le fichier se terminant par -notifications.apk s’installe par-dessus celle-ci.</string>
|
||||
<string name="update_notifications_manual">Ceci est la version « notifications » : installez la mise à jour depuis sa page, le fichier se terminant par -notifications.apk.</string>
|
||||
<string name="notification_access">Accès aux notifications</string>
|
||||
<string name="notification_access_on">Accordé. L’interrupteur d’Android est dans les paramètres du système.</string>
|
||||
<string name="notification_access_off">Pas encore accordé. Touchez pour ouvrir l’interrupteur d’Android pour LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Désactivé par défaut. Quand vous le demandez, le texte des notifications présentes sur votre téléphone (app, titre, texte) part avec cette seule question vers votre instance et son modèle. Rien n’est lu avant, l’app n’en garde rien, et rien n’est lu téléphone verrouillé. L’accès aux notifications d’Android permet à une app de voir toutes les notifications : c’est à vous de l’accorder et de le retirer.</string>
|
||||
<string name="nav_app">App de navigation</string>
|
||||
<string name="nav_app_auto">Celle qui est installée</string>
|
||||
<string name="nav_app_google">Google Maps</string>
|
||||
<string name="nav_app_osmand">OsmAnd</string>
|
||||
<string name="nav_app_ask">Demander à chaque fois</string>
|
||||
<string name="nav_app_not_installed">Non installée</string>
|
||||
<string name="osmand_info">Demander l’itinéraire à OsmAnd</string>
|
||||
<string name="osmand_info_line">Permet « ajouter un arrêt » et la recherche à proximité avec un itinéraire créé dans OsmAnd même : LLeMbas demande à OsmAnd où vous êtes et où va l’itinéraire. Autorisez d’abord LLeMbas dans OsmAnd (apps connectées, avec la position) ; OsmAnd vous prévient sinon.</string>
|
||||
<string name="phone_actions_line">Un modèle peut proposer de faire des choses sur ce téléphone : régler une alarme, ajouter un événement, rédiger un message, lancer un itinéraire. Rien ne se passe tant que vous ne touchez pas Le faire sur sa carte, et jamais téléphone verrouillé. Google Maps lance un itinéraire avec quelques arrêts mais ne peut ni en ajouter à un itinéraire en cours ni être arrêté ; OsmAnd le peut.</string>
|
||||
<string name="action_card_title">Faire ceci sur votre téléphone ?</string>
|
||||
<string name="action_do">Le faire</string>
|
||||
<string name="action_running">En cours…</string>
|
||||
<string name="action_unlock">Déverrouillez d’abord le téléphone, puis touchez Le faire.</string>
|
||||
<string name="action_failed">Cela n’a pas marché : %1$s</string>
|
||||
<string name="nav_app_pick">Avec quelle app de cartes ?</string>
|
||||
<string name="action_google_add_stop">Google Maps ne peut pas ajouter d’arrêt à un itinéraire en cours : il relance l’itinéraire, par l’arrêt.</string>
|
||||
<string name="action_google_no_stop">On ne peut pas dire à Google Maps d’arrêter : terminez l’itinéraire dans l’app.</string>
|
||||
<string name="action_line_clock">L’app Horloge le règle.</string>
|
||||
<string name="action_line_calendar">Le calendrier s’ouvre avec l’événement rempli ; vous l’enregistrez.</string>
|
||||
<string name="action_line_draft">Ouvre un brouillon ; vous l’envoyez vous-même.</string>
|
||||
<string name="action_line_dial">Le clavier s’ouvre avec le numéro ; vous lancez l’appel.</string>
|
||||
<string name="action_line_map">%1$s prend l’itinéraire.</string>
|
||||
<string name="action_line_now">Se fait aussitôt.</string>
|
||||
<string name="action_line_settings">Ouvre le réglage ; vous le changez.</string>
|
||||
<string name="action_line_automation">Lance votre automatisation (Tasker sauf si une autre app est nommée).</string>
|
||||
<string name="action_line_open">L’ouvre.</string>
|
||||
<string name="assist_recogniser_failed">La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale.</string>
|
||||
<string name="assistant_listens">Écouter dès l’ouverture de l’assistant</string>
|
||||
<string name="voice_input">Saisie vocale</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">La transcription de votre instance, via le serveur. L’enregistrement va à votre instance et nulle part ailleurs.</string>
|
||||
<string name="voice_input_phone">Téléphone (Google ou celui du système)</string>
|
||||
<string name="voice_input_phone_line">La reconnaissance vocale du téléphone. Les mots apparaissent pendant que vous parlez ; l’enregistrement va là où cette reconnaissance l’envoie.</string>
|
||||
<string name="voice_input_phone_none">Ce téléphone n’a pas de reconnaissance vocale propre.</string>
|
||||
<string name="voice_input_hint">Utilisée par l’assistant et par le micro d’une conversation. Avec LLeMbas, l’assistant affiche les mots avec un léger décalage et une pause les envoie, et une conversation les écrit quand vous vous arrêtez ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez.</string>
|
||||
<string name="share_sending">Envoi à LLeMbas…</string>
|
||||
<string name="share_default_prompt">Jetez un œil à ceci.</string>
|
||||
<string name="share_ask_hint">Que doit en faire LLeMbas ? (facultatif)</string>
|
||||
<string name="widget_hint">Posez une question</string>
|
||||
<string name="directory_places">Emplacements sur cet appareil</string>
|
||||
<string name="directory_last_used">Dernier utilisé ici : %1$s. Une nouvelle conversation dans ce dossier commence avec lui, sauf si vous en choisissez un autre.</string>
|
||||
<string name="directory_refused">L\'appareil n\'ouvrira pas de session ici.</string>
|
||||
<string name="directory_up">Remonter d\'un niveau</string>
|
||||
<string name="directory_all_places">Tous les emplacements</string>
|
||||
<string name="directory_not_trusted">Non approuvé sur l\'appareil</string>
|
||||
<string name="directory_empty">Aucun dossier ici.</string>
|
||||
<string name="directory_no_places">Cet appareil ne propose aucun dossier : ses racines distantes sont vides ou absentes.</string>
|
||||
<string name="directory_browse">Parcourir</string>
|
||||
<string name="directory_path">Un chemin complet</string>
|
||||
<string name="directory_choose">Choisir</string>
|
||||
<string name="directory_no_listing">Les dossiers de cet appareil ne peuvent pas être listés pour le moment. Saisissez le chemin ci-dessous.</string>
|
||||
<string name="model">Modèle</string>
|
||||
<string name="schedule_type">Type</string>
|
||||
<string name="schedule_chat">Conversation</string>
|
||||
<string name="schedule_chat_line">S\'exécute sur ce serveur, comme une conversation : avec les outils du serveur (recherche, vos fichiers ici, mémoire) et sur un modèle de planification.</string>
|
||||
<string name="schedule_agentic">Agentique</string>
|
||||
<string name="schedule_agentic_line">S\'exécute sur l\'un de vos ordinateurs, dans un dossier de celui-ci, en tant qu\'agent : avec les outils de l\'agent sur cet ordinateur — ses fichiers et son shell — dans les limites propres à l\'ordinateur. Elle appartient à cet ordinateur et à ce dossier.</string>
|
||||
<string name="schedule_agentic_unavailable">Aucun de vos ordinateurs n\'accepte de travail planifié pour l\'instant. Reliez-en un et activez « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">n’accepte pas le travail planifié</string>
|
||||
<string name="schedule_computer_hint">L\'ordinateur doit l\'autoriser : « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on). S\'il n\'est pas relié au moment d\'une exécution, l\'exécution l\'attend ; s\'il n\'est pas revenu avant que son heure soit passée, l\'exécution est enregistrée comme manquée et vous en êtes informé.</string>
|
||||
<string name="schedule_computer_gone">un ordinateur qui n’est plus connecté</string>
|
||||
<string name="schedule_folder">Dossier sur l’ordinateur</string>
|
||||
<string name="schedule_agent_mode">Mode</string>
|
||||
<string name="schedule_agent_mode_hint">Edit sauf choix contraire ; Auto exécute les commandes sans demander. L’ordinateur peut l’abaisser.</string>
|
||||
<string name="schedule_approval_wait">Une approbation attend (minutes)</string>
|
||||
<string name="schedule_approval_wait_hint">Une commande que l’exécution doit faire approuver arrive sur votre téléphone sous forme de carte. Sans réponse d’ici là, elle compte comme refusée.</string>
|
||||
<string name="schedule_watch_command_hint">Facultatif, sur l’ordinateur. Exécutée dans le dossier avant chaque exécution ; quand sa sortie est la même que la dernière fois, l’exécution s’arrête là. Une commande pour laquelle le mode demanderait est refusée.</string>
|
||||
<string name="schedule_watch_timeout">La commande peut durer (secondes)</string>
|
||||
<string name="schedule_watch_timeout_hint">Arrêtée au-delà ; l’exécution échoue alors.</string>
|
||||
<string name="schedule_chat_drops_watch">Cette tâche surveille une commande sur son ordinateur. En tâche de type Chat, elle ne le fait plus : elle s’exécute à chaque fois.</string>
|
||||
<string name="schedule_folder_model">Le modèle habituel du dossier</string>
|
||||
<string name="schedule_folder_model_hint">Le modèle habituel du dossier est celui que vous avez utilisé en dernier dans ce dossier sur cet ordinateur — l\'ordinateur s\'en souvient et chaque exécution le lui demande — ou votre modèle par défaut s\'il n\'y en a pas. Un modèle choisi ici est celui de l\'exécution, quel que soit celui du dossier. Une exécution ne change jamais le modèle du dossier.</string>
|
||||
<string name="schedule_first_free_model">Le premier libre de vos modèles de planification</string>
|
||||
<string name="run_model_directory">le modèle habituel du dossier</string>
|
||||
<string name="run_model_default">votre modèle par défaut</string>
|
||||
<string name="run_model_session">le modèle propre à la conversation</string>
|
||||
<string name="widget_speak">Parler</string>
|
||||
<string name="widget_description">Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.</string>
|
||||
<string name="shortcut_last">Dernière discussion</string>
|
||||
</resources>
|
||||
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user