Compare commits
65
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||
|
|
f3b78be5ab
|
||
|
|
665ac44e5c
|
||
|
|
960e9e3c63
|
||
|
|
9c13d7766d
|
||
|
|
41dd3c893c
|
||
|
|
f4891ba402
|
||
|
|
a342f23ef9
|
||
|
|
2fd692dd7b
|
||
|
|
3afe01ce52
|
||
|
|
9abff4f170
|
||
|
|
0c5aa4d45f
|
||
|
|
ac0c1c58e0
|
||
|
|
c6438f60db
|
||
|
|
fd1af60dbb
|
||
|
|
052d0a3894
|
No files matched your search
@@ -2,7 +2,7 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, dev]
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
@@ -29,12 +29,13 @@ jobs:
|
||||
distribution: temurin
|
||||
java-version: 17
|
||||
|
||||
- name: ktlint (signature-checked)
|
||||
# ktlint 1.8.0 from Maven Central: the same jar the signed GitHub release wraps in a
|
||||
# shell header (checked byte for byte), from a host that does not 504 on release assets.
|
||||
- name: ktlint (hash-pinned)
|
||||
run: |
|
||||
curl -sSfL -o ktlint https://github.com/pinterest/ktlint/releases/download/1.8.0/ktlint
|
||||
echo "a3fd620207d5c40da6ca789b95e7f823c54e854b7fade7f613e91096a3706d75 ktlint" | sha256sum -c
|
||||
chmod +x ktlint
|
||||
./ktlint "app/src/**/*.kt" "*.kts" "app/*.kts"
|
||||
curl -sSfL --retry 5 --retry-all-errors -o ktlint.jar https://repo1.maven.org/maven2/com/pinterest/ktlint/ktlint-cli/1.8.0/ktlint-cli-1.8.0-all.jar
|
||||
echo "369ad2b789f95a011f807e1fcb690ccef80bd7cd014fd139e73ae82dcc0baeab ktlint.jar" | sha256sum -c
|
||||
java -jar ktlint.jar "app/src/**/*.kt" "*.kts" "app/*.kts"
|
||||
|
||||
- uses: gradle/actions/wrapper-validation@v4
|
||||
|
||||
@@ -47,12 +48,32 @@ jobs:
|
||||
run: ./gradlew --no-daemon lintFullDebug
|
||||
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.
|
||||
- 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"
|
||||
(cd test-builds && sha256sum *.apk > SHA256SUMS)
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: llembas-android-debug
|
||||
path: app/build/outputs/apk/*/debug/*.apk
|
||||
name: llembas-android-debug-${{ github.run_number }}
|
||||
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:
|
||||
|
||||
@@ -73,4 +73,7 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
git tag -l --format='%(contents)' "$TAG" | sed '/-----BEGIN SSH SIGNATURE-----/,$d' > notes.md
|
||||
gh release create "$TAG" --verify-tag --title "LLeMbas for Android $VERSION" --notes-file notes.md dist/*
|
||||
# A `-beta.N` tag is a pre-release: never "Latest", never what /releases/latest hands out.
|
||||
pre=""
|
||||
case "$TAG" in *-*) pre="--prerelease" ;; esac
|
||||
gh release create "$TAG" --verify-tag $pre --title "LLeMbas for Android $VERSION" --notes-file notes.md dist/*
|
||||
@@ -8,6 +8,8 @@ local.properties
|
||||
# A release key never goes in the repository (CI writes it from secrets)
|
||||
*.jks
|
||||
*.keystore
|
||||
# ...except the public test key debug builds are signed with (see app/build.gradle.kts)
|
||||
!/app/test-debug.keystore
|
||||
# IDEs
|
||||
.idea/
|
||||
*.iml
|
||||
|
||||
+305
-1
@@ -3,7 +3,311 @@
|
||||
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
|
||||
is in alpha and releases come off `main`.
|
||||
|
||||
## [Unreleased]
|
||||
## [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
|
||||
sizes).
|
||||
|
||||
### Added
|
||||
|
||||
- **New agent chat**, on the Agents tab: pick one of the devices linked right now (a computer
|
||||
running `lembas service`), optionally a folder on it, and the mode (Manual, Edit, Auto, Plan),
|
||||
and the first message starts the chat there. With no device linked, the screen says how to
|
||||
link one. An open agent chat's mode can be changed from the same chip.
|
||||
- **Photos**: the attach button offers Take a photo (the camera app, no camera permission for
|
||||
LLeMbas itself), Choose photos (Android's photo picker) and Choose files.
|
||||
- **Copy** a reply or one of your messages with the copy button under it.
|
||||
- **Rename chat** in the chat's menu.
|
||||
- **Try again** beside an error on the chat list.
|
||||
- **Test builds for every change**: each push to `dev` leaves an installable APK on the CI run,
|
||||
signed with a public test key so a newer test build installs over an older one. The version
|
||||
in Settings › About carries the run's number.
|
||||
- **The activity panel**: the lightning button in a chat, or the line above the message box
|
||||
("3 agents working · 1 queued"), opens a full-screen view of what the chat is doing --
|
||||
**Context** (how much of the model's window is used, a bar and the breakdown by category),
|
||||
**Outputs** (the files the chat and its agents wrote, with lines added and removed; tap one to
|
||||
read it), **Background tasks** (every helper, command and team member as a tree, with its
|
||||
state, how long it has run, its model, its latest step and what it is writing; open its whole
|
||||
conversation read-only, or stop it after a confirmation; finished ones folded under "N
|
||||
finished"), the team's **Room** and the **Plan**. It keeps itself current while it is open.
|
||||
- **Agents, fewest and most**, in the chat's chips where the model can run a team: how many
|
||||
agents the chat's team may have, its own included (1 to 4 to begin with). Set it before the
|
||||
first message or change it in an open chat.
|
||||
- **Model pictures**: the model picker and the chat's title show each model's picture from the
|
||||
instance, or its initial where it has none.
|
||||
|
||||
### Changed
|
||||
|
||||
- A beta (`vX.Y.Z-beta.N`) is published on GitHub as a pre-release by itself.
|
||||
- **The chat list is read again whenever you come back to it**, from a chat or another app, so a
|
||||
new chat, a new title or a finished reply shows without pulling to refresh.
|
||||
- **A reply being written stays in view**: the chat follows it to the end, unless you have
|
||||
scrolled up to read, and picks up again once you scroll back down.
|
||||
- **An instance that cannot be reached says so in one sentence** -- no network, an address that
|
||||
only resolves at home, a server that is down -- instead of a raw network error, everywhere:
|
||||
sign-in, the chats, a chat, Files, the viewer, the assistant and Share.
|
||||
- The effort chosen for a **new** chat is now sent with its first message (it was lost until the
|
||||
chat existed).
|
||||
- **The effort control is the model's own**: none for a model with one level, a **Think before
|
||||
answering** chip that switches thinking on and off for a model that offers exactly that, and
|
||||
the effort picker for more levels. "Off" is offered only by a model that can really switch
|
||||
thinking off. A chat started without a choice starts at the model's start level.
|
||||
- Requires the beta.5 `/api/v2` of LLeMbas 2.0 for the panel, the team size, the Thinking switch
|
||||
and the pictures; against an older 2.0 beta the app keeps the effort picker and the jobs chips.
|
||||
- The agent mode "Manual" is translated, and "Plan" no longer reads as a price plan in German,
|
||||
French and Hungarian.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A message that could not be sent is not lost**: its words and attachments go back into the
|
||||
composer, with the reason.
|
||||
- Leaving a chat while a reply was streaming could show a "cancelled" error on the next one.
|
||||
- When the server refused the stream of a reply (the chat deleted elsewhere, the sign-in
|
||||
revoked), the half-drawn reply stayed on screen; the chat is now read again.
|
||||
|
||||
- **Pinned to LLeMbas server 2.0.0-beta.4**: the contract, the theme and the strings come from that
|
||||
release. Nothing a person sees changes; the server's API is the same as in beta.1.
|
||||
|
||||
## [1.0.0-beta.1] — 2026-11-03
|
||||
|
||||
For LLeMbas server 2.0, and only for it.
|
||||
|
||||
### Added
|
||||
|
||||
- **The file viewer.** When the model shows a file (the `show` tool, in a chat or from a linked
|
||||
device), the reply carries a card with the file's name and path; Open shows it full screen,
|
||||
read-only, at the line it named. Markdown is rendered with the same limits as a reply (no
|
||||
images, no HTML, links open in the browser for http, https and mailto only); code and text are
|
||||
numbered lines; a long Markdown file is shown as text. **HTML is never rendered in the app**:
|
||||
it is shown as its source, and "Open in the browser" opens the web viewer, which draws it in
|
||||
its sealed frame. Copy takes the whole file.
|
||||
- **Files**: the person's own files, read-only, from the folder button beside Settings. Browse
|
||||
the tree as the web UI's explorer shows it (folders first, back goes up one), and open a file
|
||||
in the same viewer as a shown one, under the same rules. A file the server does not hand over
|
||||
as text -- an image, a binary, anything over 1 MB -- says why, and offers the web UI's viewer.
|
||||
- **A server older than 2.0 is refused** with a sentence, at sign-in and for an instance signed
|
||||
in to before: the device-link protocol must be 3 or newer, and the app API 2.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The server's contract is pinned to LLeMbas 2.0** (`dev`): no canvas, chats without knowledge
|
||||
bases. Theme and strings are generated from the same commit; `gen-strings.py` takes a server
|
||||
ref, as the other two scripts do. Selected text uses the web UI's `--selection` tint.
|
||||
- **The app reads app API 2**, the server 2.0's: a server that still says 1 (a 2.0 build from
|
||||
before the show route and the files) is refused as too old, one that says 3 as too new.
|
||||
- **A shown file is fetched from the server's own route**, `GET /api/v2/chats/{chat}/show`
|
||||
(`?node=&version=` for a file in the tree, `?shown=` for a device's copy), and a file that is
|
||||
not text says so in the server's words. The contract now carries the server's `show` cards and
|
||||
the files routes, and the tests read those instead of a hand-written card.
|
||||
- CI also runs on pushes to `dev`.
|
||||
|
||||
### Removed
|
||||
|
||||
- **The Reports notification channel**: LLeMbas 2.0 has no reports. The channel is deleted on
|
||||
first start.
|
||||
|
||||
## [0.1.0] — unreleased
|
||||
|
||||
|
||||
@@ -17,7 +17,15 @@ digital assistant -- hold the power button and ask.
|
||||
|
||||
Download the APK from the [latest release](https://github.com/LLeMbas/LLeMbas-Android/releases/latest)
|
||||
and check it against `SHA256SUMS`. The `full` APK updates itself from llembas.eu; the `-fdroid`
|
||||
one does not. Android 10 or newer; the instance must run LLeMbas server 1.7.0 or newer.
|
||||
one does not. Android 10 or newer; the instance must run LLeMbas server 2.0 or newer (an older
|
||||
one is refused at sign-in, with a sentence saying so).
|
||||
|
||||
**Test builds.** Every push to `dev` builds a debug APK: open the newest green run under
|
||||
[Actions](https://github.com/LLeMbas/LLeMbas-Android/actions/workflows/ci.yml), download the
|
||||
`llembas-android-debug-N` artifact (GitHub asks you to be signed in), unzip it and install the APK that does
|
||||
not end in `-fdroid`. It is a separate app ("eu.llembas.android.debug") beside a released one,
|
||||
signed with a public test key kept in this repository, so each test build installs over the one
|
||||
before it -- and anyone could sign one, so take test builds only from this repository's runs.
|
||||
|
||||
If your instance uses a certificate from your own certificate authority, install that CA on the
|
||||
phone first (Settings › Security › Encryption & credentials › Install a certificate › CA
|
||||
@@ -40,13 +48,14 @@ preinstalled assistant; no app from outside can use it.
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is the usual
|
||||
`./gradlew assembleFullDebug` with JDK 17 and the Android SDK.
|
||||
|
||||
Three things are generated from the server and pinned, each with a lock file CI checks:
|
||||
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:
|
||||
|
||||
| What | Script | From the server |
|
||||
|---|---|---|
|
||||
| `ui/theme/Tokens.kt` | `scripts/fetch-tokens.py <server-ref>` | `tokens.css` |
|
||||
| `contract/*.json` | `scripts/fetch-contract.py <server-ref>` | `tests/fixtures/api_v2/` |
|
||||
| `res/values*/strings.xml` | `scripts/gen-strings.py` | the translation catalogues |
|
||||
| `res/values*/strings.xml` | `scripts/gen-strings.py <server-ref>` | the translation catalogues |
|
||||
|
||||
The icons come from the server's pixel leaf (`scripts/gen-icons.py`).
|
||||
|
||||
|
||||
+42
-5
@@ -1,3 +1,4 @@
|
||||
import java.time.Duration
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
@@ -28,14 +29,28 @@ android {
|
||||
minSdk = 29
|
||||
targetSdk = 36
|
||||
// The one source of the version. versionCode is derived from it, so the two cannot
|
||||
// drift: 0.1.0 -> 100, 1.2.3 -> 10203.
|
||||
versionName = "0.1.0"
|
||||
versionCode = versionName!!.split(".").map { it.toInt() }.let { (a, b, c) ->
|
||||
a * 10000 + b * 100 + c
|
||||
// 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.6"
|
||||
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
|
||||
((a * 10000 + b * 100 + c) * 100) + pre
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
// Debug builds are signed with a *public* test key that lives in the repository, so the
|
||||
// APK every CI run uploads installs over the one before it (a runner's own debug key is
|
||||
// new each run, and Android refuses an update from a different signer). It signs only
|
||||
// the `.debug` application id, never a release, and it is no secret: anyone can sign
|
||||
// with it, so install a debug build only from this repository's CI.
|
||||
getByName("debug") {
|
||||
storeFile = file("test-debug.keystore")
|
||||
storePassword = "android"
|
||||
keyAlias = "androiddebugkey"
|
||||
keyPassword = "android"
|
||||
}
|
||||
releaseKey?.let { key ->
|
||||
create("release") {
|
||||
storeFile = file(key.getProperty("file"))
|
||||
@@ -55,7 +70,9 @@ android {
|
||||
}
|
||||
debug {
|
||||
applicationIdSuffix = ".debug"
|
||||
versionNameSuffix = "-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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +107,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 {
|
||||
@@ -128,4 +160,9 @@ dependencies {
|
||||
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)
|
||||
}
|
||||
@@ -11,6 +11,10 @@
|
||||
<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>
|
||||
</queries>
|
||||
|
||||
<application
|
||||
@@ -20,6 +24,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">
|
||||
@@ -123,5 +128,21 @@
|
||||
<receiver
|
||||
android:name=".push.CardActionReceiver"
|
||||
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"
|
||||
android:authorities="${applicationId}.files"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -18,15 +18,23 @@ class LembasApp : Application() {
|
||||
listOf(
|
||||
NotificationChannel(CHANNEL_REPLIES, getString(R.string.channel_replies), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH),
|
||||
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_LOW),
|
||||
),
|
||||
NotificationChannel(CHANNEL_SCHEDULED, getString(R.string.channel_scheduled), NotificationManager.IMPORTANCE_DEFAULT),
|
||||
NotificationChannel(CHANNEL_SCHEDULED_FAILURES, getString(R.string.channel_scheduled_failures), 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.
|
||||
manager.deleteNotificationChannel("reports")
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_REPLIES = "replies"
|
||||
const val CHANNEL_ASKS = "asks"
|
||||
const val CHANNEL_REPORTS = "reports"
|
||||
const val CHANNEL_SCHEDULED = "scheduled_results"
|
||||
const val CHANNEL_SCHEDULED_FAILURES = "scheduled_failures"
|
||||
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,7 +11,10 @@ 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
|
||||
@@ -18,31 +22,61 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
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.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
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.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.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 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)
|
||||
|
||||
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
|
||||
) {
|
||||
@@ -56,60 +90,237 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 }
|
||||
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
|
||||
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
|
||||
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
|
||||
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
|
||||
if (chat == null && schedule == null) return
|
||||
opening.value = Opening(chat, schedule, run, instance)
|
||||
// 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() }
|
||||
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.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") },
|
||||
onSettings = { nav.navigate("settings") },
|
||||
)
|
||||
}
|
||||
composable("new") {
|
||||
ChatScreen(
|
||||
chatId = null,
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpened = { id ->
|
||||
nav.navigate("chat/$id") { popUpTo("new") { inclusive = true } }
|
||||
},
|
||||
)
|
||||
}
|
||||
composable("chat/{id}") { entry ->
|
||||
ChatScreen(chatId = entry.arguments?.getString("id"), onBack = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { nav.navigate("add") })
|
||||
}
|
||||
// Signing in to one more instance makes it the one in use, which starts a
|
||||
// fresh navigation for it (the `key` above).
|
||||
composable("add") { SignInScreen(onDone = { nav.popBackStack("chats", inclusive = false) }) }
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
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("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") },
|
||||
)
|
||||
}
|
||||
composable("schedule/{id}/run/{run}") { e ->
|
||||
RunScreen(
|
||||
e.arguments?.getString("id").orEmpty(),
|
||||
e.arguments?.getString("run").orEmpty(),
|
||||
onBack = { nav.popBackStack() },
|
||||
onOpenChat = { top("chat/$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,107 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The activity panel's arithmetic, apart from the screen so the tests can hold it: the numbers
|
||||
* are written as the server writes them (`compact_tokens`, `jobs.duration`), and the strip's
|
||||
* line counts what the web's strip counts.
|
||||
*/
|
||||
object ActivityLogic {
|
||||
/** A token count at a glance: 950, 14.2k, 180k, 1.54M (the server's `compact_tokens`). */
|
||||
fun compactTokens(value: Int): String {
|
||||
val n = value.coerceAtLeast(0)
|
||||
return when {
|
||||
n < 1000 -> n.toString()
|
||||
n < 100_000 -> trim(String.format(Locale.ROOT, "%.1f", n / 1000.0)) + "k"
|
||||
n < 1_000_000 -> "${Math.round(n / 1000.0)}k"
|
||||
else -> trim(String.format(Locale.ROOT, "%.2f", n / 1_000_000.0)) + "M"
|
||||
}
|
||||
}
|
||||
|
||||
private fun trim(number: String): String = if ('.' in number) number.trimEnd('0').trimEnd('.') else number
|
||||
|
||||
/** A duration as both the server and the CLI write it: `5s`, `1m 05s`, `2h 03m`. */
|
||||
fun duration(seconds: Long): String {
|
||||
val total = seconds.coerceAtLeast(0)
|
||||
if (total < 60) return "${total}s"
|
||||
val minutes = total / 60
|
||||
val rest = total % 60
|
||||
if (minutes < 60) return String.format(Locale.ROOT, "%dm %02ds", minutes, rest)
|
||||
return String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
|
||||
}
|
||||
|
||||
/**
|
||||
* How long an agent has run now: the server's count when it was read, plus the time since
|
||||
* for one that is still going. A queued one has not started, and an ended one has stopped
|
||||
* counting.
|
||||
*/
|
||||
fun elapsed(agent: ActivityAgent, readAtMillis: Long, nowMillis: Long): Long {
|
||||
val going = agent.state == "working" || agent.state == "waiting"
|
||||
val since = if (going) ((nowMillis - readAtMillis) / 1000).coerceAtLeast(0) else 0
|
||||
return agent.seconds + since
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>> {
|
||||
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 subagents under it, in tree order, for drawing as rows. */
|
||||
fun flatten(agents: List<ActivityAgent>): List<ActivityAgent> = agents.flatMap { listOf(it) + flatten(it.children) }
|
||||
|
||||
/**
|
||||
* The context's bar: one segment per category with tokens, `free` left out (it is the
|
||||
* empty end of the bar). Nothing at all when the window is unknown.
|
||||
*/
|
||||
fun barParts(context: ContextUse): List<ContextPart> {
|
||||
if (context.limit <= 0) return emptyList()
|
||||
return context.categories.filter { it.key != "free" && it.tokens > 0 }
|
||||
}
|
||||
|
||||
/** The plan the panel shows, read leniently: a plan that does not parse is no plan. */
|
||||
fun plan(json: JsonObject?): Plan? = json?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
|
||||
|
||||
/** A percentage as the server writes it: one decimal, none when it is whole. */
|
||||
fun percent(value: Double): String = trim(String.format(Locale.ROOT, "%.1f", value))
|
||||
}
|
||||
@@ -25,6 +25,9 @@ import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlin.coroutines.resumeWithException
|
||||
|
||||
/** Where a new agent chat runs: a linked device ([LinkedDevice.id]) and a folder on it. */
|
||||
data class AgentTarget(val device: String, val directory: String = "")
|
||||
|
||||
/** A refusal from the server, in its own words (`{"detail": "…"}`). */
|
||||
class ApiException(val status: Int, message: String) : IOException(message)
|
||||
|
||||
@@ -97,6 +100,11 @@ class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
||||
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
|
||||
}
|
||||
|
||||
private fun agentsJson(agents: AgentsSetting) = buildJsonObject {
|
||||
put("min", agents.min)
|
||||
put("max", agents.max)
|
||||
}
|
||||
|
||||
internal fun detail(response: Response): String {
|
||||
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
val said = runCatching {
|
||||
@@ -136,10 +144,58 @@ 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?): ModelList =
|
||||
get("/models?kind=agent" + deviceId?.let { "&device=" + java.net.URLEncoder.encode(it, "UTF-8") }.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")
|
||||
|
||||
/** 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
|
||||
|
||||
/** The token revokes itself (`lembas logout`'s route). */
|
||||
@@ -168,6 +224,9 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
temporary: Boolean = false,
|
||||
effort: String? = null,
|
||||
mode: String? = null,
|
||||
agent: AgentTarget? = null,
|
||||
agents: AgentsSetting? = null,
|
||||
forceTool: String? = null,
|
||||
): NewChat = send(
|
||||
"POST",
|
||||
"/chats",
|
||||
@@ -177,21 +236,36 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
model?.let { put("model", it) }
|
||||
effort?.let { put("effort", it) }
|
||||
mode?.let { put("mode", it) }
|
||||
agents?.let { put("agents", agentsJson(it)) }
|
||||
put("temporary", temporary)
|
||||
forceTool?.let { put("force_tool", it) }
|
||||
// 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.
|
||||
agent?.let {
|
||||
put("kind", "agent")
|
||||
put("device", it.device)
|
||||
if (it.directory.isNotBlank()) put("directory", it.directory.trim())
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
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) }
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun updateChat(chatId: String, changes: JsonObject): Chat = send<ChatEnvelope>("PATCH", "/chats/$chatId", changes).chat
|
||||
|
||||
/** The team's size, both ends at once: the server checks the pair (422 outside its bounds). */
|
||||
suspend fun setAgents(chatId: String, agents: AgentsSetting): Chat = updateChat(chatId, buildJsonObject { put("agents", agentsJson(agents)) })
|
||||
|
||||
suspend fun deleteChat(chatId: String) = empty(authed("$v2/chats/$chatId").delete().build())
|
||||
|
||||
suspend fun stop(chatId: String, messageId: String) =
|
||||
@@ -211,6 +285,124 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
empty(authed("$v2/chats/$chatId/interactions/$cardId").post(body).build())
|
||||
}
|
||||
|
||||
// --- The activity panel, background agents and the team -----------------------------------
|
||||
|
||||
/** Everything the panel shows; `context = false` leaves out the costly context count. */
|
||||
suspend fun activity(chatId: String, context: Boolean = true): Activity = get<ActivityEnvelope>("/chats/$chatId/activity?context=$context").activity
|
||||
|
||||
/** The events route: an `activity` frame whenever the panel's facts change. */
|
||||
fun activityEvents(chatId: String): Request = authed("$v2/chats/$chatId/activity/events").header("Accept", "text/event-stream").build()
|
||||
|
||||
/** 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): Schedule {
|
||||
val body = buildJsonObject {
|
||||
put("title", compiled.title)
|
||||
put("instruction", compiled.instruction)
|
||||
put("rule", compiled.rule)
|
||||
put("target", compiled.target)
|
||||
if (id == null) put("request", words)
|
||||
}
|
||||
return if (id == null) {
|
||||
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
|
||||
} else {
|
||||
send<ScheduleEnvelope>("PATCH", "/schedules/${segment(id)}", body).schedule
|
||||
}
|
||||
}
|
||||
|
||||
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 --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A model's picture, with the token: only a path under the instance's own
|
||||
* `/api/v2/models/images/` is fetched -- a list that named anything else, another host
|
||||
* included, gets the initial instead. At most [IMAGE_MAX_BYTES]; null when there is none.
|
||||
*/
|
||||
suspend fun modelImage(path: String): ByteArray? = withContext(Dispatchers.IO) {
|
||||
val url = modelImageUrl(base, path) ?: return@withContext null
|
||||
http.newCall(authed(url).header("Accept", "image/*").get().build()).await().use {
|
||||
if (!it.isSuccessful) return@use null
|
||||
val body = it.body ?: return@use null
|
||||
if (body.contentLength() > IMAGE_MAX_BYTES) return@use null
|
||||
val bytes = body.source().use { source ->
|
||||
source.request(IMAGE_MAX_BYTES + 1)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, IMAGE_MAX_BYTES + 1))
|
||||
}
|
||||
bytes.takeIf { b -> b.size <= IMAGE_MAX_BYTES }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Attachments -------------------------------------------------------------------------
|
||||
suspend fun upload(name: String, mime: String, bytes: ByteArray, chatId: String? = null): Attachment {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
@@ -227,6 +419,62 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
}
|
||||
}
|
||||
|
||||
// --- What a `show` card opens -------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The text of a file a `show` card named, as the chat sees it now:
|
||||
* `GET /api/v2/chats/{chat}/show?node=<node_id>&version=<version_id>` for a file in the tree,
|
||||
* `?shown=<shown_id>` for the copy a linked device sent ([ShowCard.query]). The server rebuilds
|
||||
* the chat's view and checks the path again, so a grant taken away since takes the file away
|
||||
* too (404, in the server's words). `text/plain; charset=utf-8`, at most 1 MB: above it a 413,
|
||||
* and a 415 for a file that is not text. Always plain text -- an HTML file is its source, and
|
||||
* the app never asks for a page to render.
|
||||
*/
|
||||
suspend fun shownText(chatId: String, show: ShowCard): String = withContext(Dispatchers.IO) {
|
||||
val url = "$v2/chats/$chatId/show".toHttpUrl().newBuilder()
|
||||
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
|
||||
.build()
|
||||
http.newCall(authed(url.toString()).header("Accept", "text/plain").get().build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
val body = it.body!!
|
||||
// The server shows at most 1 MB; anything much larger is not a file it meant.
|
||||
if (body.contentLength() > SHOWN_MAX_BYTES) throw ApiException(413, "")
|
||||
val bytes = body.source().use { source ->
|
||||
source.request(SHOWN_MAX_BYTES + 1)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, SHOWN_MAX_BYTES + 1))
|
||||
}
|
||||
if (bytes.size > SHOWN_MAX_BYTES) throw ApiException(413, "")
|
||||
bytes.toString(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
// --- The person's files ------------------------------------------------------------------
|
||||
|
||||
/** A directory, as the person may see it (no chat's grants): `GET /api/v2/files?path=`. */
|
||||
suspend fun files(path: String = "/"): FileListing {
|
||||
val url = "$v2/files".toHttpUrl().newBuilder().addQueryParameter("path", path).build()
|
||||
return call(authed(url.toString()).get().build(), FileListing.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* A file's text: `GET /api/v2/files/content?path=`. A file the server will not hand over as
|
||||
* text (not text, over 1 MB) is not an error: it comes back with `withheld` saying why.
|
||||
*/
|
||||
suspend fun fileContent(path: String): FileContent {
|
||||
val url = "$v2/files/content".toHttpUrl().newBuilder().addQueryParameter("path", path).build()
|
||||
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
||||
}
|
||||
|
||||
/** A file of the tree in the web UI's own viewer (`/files/view`), for what the app does not draw. */
|
||||
fun webFile(path: String): String = "$base/files/view".toHttpUrl().newBuilder().addQueryParameter("path", path).build().toString()
|
||||
|
||||
/** The same file in the web UI's viewer, which renders HTML in its sealed frame. */
|
||||
fun webViewer(chatId: String, show: ShowCard): String = "$base/chat/$chatId/show".toHttpUrl().newBuilder()
|
||||
.apply { show.query.forEach { (k, v) -> addQueryParameter(k, v) } }
|
||||
.apply { if (show.line > 0) addQueryParameter("line", show.line.toString()) }
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
@@ -265,6 +513,25 @@ 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 {
|
||||
/** 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
|
||||
|
||||
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
||||
|
||||
/** A model's picture is small; anything larger is not one. */
|
||||
const val IMAGE_MAX_BYTES = 2_000_000L
|
||||
|
||||
private const val IMAGE_PATH = "/api/v2/models/images/"
|
||||
|
||||
/** The picture's URL on [base], or null for a path that is not one of the instance's pictures. */
|
||||
fun modelImageUrl(base: String, path: String?): String? {
|
||||
if (path.isNullOrBlank() || !path.startsWith(IMAGE_PATH)) return null
|
||||
val name = path.removePrefix(IMAGE_PATH)
|
||||
if (name.isEmpty() || !name.all { it.isLetterOrDigit() || it == '.' || it == '_' || it == '-' } || name.startsWith(".")) return null
|
||||
return "$base$IMAGE_PATH$name"
|
||||
}
|
||||
|
||||
/** One path segment, escaped: an agent's name or a job's id is a model's choice. */
|
||||
fun segment(value: String): String = java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
/**
|
||||
* The app API this app reads: 2, the server's 2.0 (no canvas, no `knowledge_bases`, the `show`
|
||||
* card and its route, and the person's files). A server with a newer one is told about, not
|
||||
* guessed at; one with an older one is refused, because 1 has neither the show route nor the
|
||||
* files this app opens -- a 2.0 `dev` server from before the files routes still said 1.
|
||||
*/
|
||||
const val APP_API = 2
|
||||
|
||||
/**
|
||||
* The device-link protocol of LLeMbas 2.0. This app is built for 2.0 -- the file tree, the
|
||||
* access levels, the `show` card -- and a 1.x server (protocol 1 or 2) is refused with a
|
||||
* sentence rather than half-working. The protocol, not the version string, is the test: a
|
||||
* server's `dev` branch says 1.7.x until its first beta, and the protocol is what 2.0 raised on
|
||||
* purpose so that old clients can tell.
|
||||
*/
|
||||
const val MIN_PROTOCOL = 3
|
||||
|
||||
/** Whether this app can work with a server, from its discovery document. */
|
||||
enum class ServerFit { FITS, NOT_LEMBAS, TOO_OLD, TOO_NEW }
|
||||
|
||||
fun fit(found: Discovery): ServerFit {
|
||||
val protocol = maxOf(found.protocol, found.protocols.maxOrNull() ?: 0)
|
||||
return when {
|
||||
found.service != "lembas" -> ServerFit.NOT_LEMBAS
|
||||
protocol < MIN_PROTOCOL || found.appApi < APP_API || "app" !in found.scopes -> ServerFit.TOO_OLD
|
||||
found.appApi > APP_API -> ServerFit.TOO_NEW
|
||||
else -> ServerFit.FITS
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,12 @@ 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,
|
||||
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. */
|
||||
@@ -45,16 +49,18 @@ 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 { copy(status = it.text, progress = it.progress) } ?: 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 = "")
|
||||
copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "", progress = null)
|
||||
} ?: this
|
||||
|
||||
"close" -> copy(closed = true)
|
||||
|
||||
@@ -27,6 +27,9 @@ data class Discovery(
|
||||
val version: String = "",
|
||||
val name: String = "",
|
||||
@SerialName("base_url") val baseUrl: String = "",
|
||||
/** The device link's protocol: 3 from LLeMbas 2.0 on, which is what this app needs. */
|
||||
val protocol: Int = 0,
|
||||
val protocols: List<Int> = emptyList(),
|
||||
@SerialName("app_api") val appApi: Int = 0,
|
||||
val login: Login = Login(),
|
||||
val scopes: List<String> = emptyList(),
|
||||
@@ -69,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(
|
||||
@@ -78,15 +101,166 @@ data class ModelInfo(
|
||||
val vision: Boolean = false,
|
||||
val tools: Boolean = false,
|
||||
val efforts: List<String> = emptyList(),
|
||||
/** Whether the model's server stops thinking when asked: only then is `off` a level. */
|
||||
@SerialName("thinking_switch") val thinkingSwitch: Boolean = false,
|
||||
/** The levels a chat offers, in order (harness spec 3.2.0): `off` first when switchable. */
|
||||
val levels: List<String> = emptyList(),
|
||||
/** The level a chat starts at when none was chosen. */
|
||||
val effort: String = "",
|
||||
/** How the level is chosen: `none`, `switch` (Thinking on or off) or `slider`. */
|
||||
val control: String = "",
|
||||
/** How many requests the model's server answers at once; null for no stated limit. */
|
||||
val parallel: Int? = null,
|
||||
val context: Int = 0,
|
||||
/** 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,
|
||||
) {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
val offered: List<String> get() = levels.ifEmpty { if (efforts.isEmpty()) emptyList() else listOf("off") + efforts }
|
||||
|
||||
/** Which control the composer draws, by the server's word or, from an older one, by the count. */
|
||||
val levelControl: String
|
||||
get() = control.takeIf { it in CONTROLS } ?: when {
|
||||
offered.size <= 1 -> "none"
|
||||
offered.size == 2 && "off" in offered -> "switch"
|
||||
else -> "slider"
|
||||
}
|
||||
|
||||
/** The level in force: [chosen] when this model offers it, else its start level. */
|
||||
fun level(chosen: String?): String =
|
||||
chosen?.takeIf { it in offered } ?: effort.takeIf { it in offered } ?: offered.firstOrNull { it != "off" } ?: offered.firstOrNull().orEmpty()
|
||||
|
||||
/** For the Thinking switch: the level that is "on" (the one that is not `off`). */
|
||||
val onLevel: String get() = offered.firstOrNull { it != "off" } ?: effort
|
||||
|
||||
/**
|
||||
* 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() = 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 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,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 ModelList(val models: List<ModelInfo> = emptyList())
|
||||
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 Folder(val id: String, val name: String = "", @SerialName("parent_id") val parentId: String? = null, val kind: String = "", val position: Int = 0)
|
||||
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 = "")
|
||||
|
||||
@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())
|
||||
@@ -115,15 +289,30 @@ data class Chat(
|
||||
val mode: String = "",
|
||||
val effort: String? = null,
|
||||
val device: Device? = null,
|
||||
/** An agent chat's session on its device (`lembas -s <id>` continues it); null until opened. */
|
||||
@SerialName("device_session_id") val deviceSessionId: String? = null,
|
||||
@SerialName("parent_chat_id") val parentChatId: String? = null,
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@SerialName("system_prompt") val systemPrompt: String? = null,
|
||||
val plan: JsonObject? = null,
|
||||
/** 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"
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
companion object {
|
||||
/** The spec's default cap; an instance may set it lower, and then refuses past it (422). */
|
||||
const val CAP = 32
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@@ -191,9 +380,99 @@ data class ToolCall(
|
||||
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
|
||||
* chat's own tree names its node and version; a file a linked device sent names the copy the
|
||||
* server kept (`shown_id`), with the tree's two ids empty.
|
||||
*/
|
||||
@Serializable
|
||||
data class ShowCard(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
/** `markdown`, `code`, `text` or `html`; anything else is read as `text`. */
|
||||
val kind: String = "text",
|
||||
val language: String = "",
|
||||
val line: Int = 0,
|
||||
@SerialName("node_id") val nodeId: String = "",
|
||||
@SerialName("version_id") val versionId: String = "",
|
||||
val sha: String = "",
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val source: String = "",
|
||||
@SerialName("shown_id") val shownId: String = "",
|
||||
) {
|
||||
/** The kind the viewer draws: an unknown one is plain text, never something richer. */
|
||||
val viewKind: String get() = if (kind in VIEW_KINDS) kind else "text"
|
||||
|
||||
/** Which file, as the server's viewer routes take it: the device's copy, or node and version. */
|
||||
val query: List<Pair<String, String>>
|
||||
get() = if (shownId.isNotEmpty()) listOf("shown" to shownId) else listOf("node" to nodeId, "version" to versionId)
|
||||
|
||||
companion object {
|
||||
val VIEW_KINDS = setOf("markdown", "code", "text", "html")
|
||||
}
|
||||
}
|
||||
|
||||
// --- The person's files (`GET /files`, `GET /files/content`) ----------------------------------
|
||||
|
||||
/** One entry of a directory: `kind` is `file`, `dir` or `mount`. */
|
||||
@Serializable
|
||||
data class FileEntry(
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
) {
|
||||
/** A directory or a mount: something to open as a listing, not in the viewer. */
|
||||
val isFolder: Boolean get() = kind == "dir" || kind == "mount"
|
||||
}
|
||||
|
||||
/** A directory, through the person's own access. `parent` is null at `/`. */
|
||||
@Serializable
|
||||
data class FileListing(val path: String = "/", val parent: String? = null, val entries: List<FileEntry> = emptyList())
|
||||
|
||||
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
|
||||
@Serializable
|
||||
data class Withheld(val reason: String = "", val message: String = "")
|
||||
|
||||
/**
|
||||
* A file's text, as the explorer's viewer reads it. An HTML file is its source, never rendered;
|
||||
* a file that is not text or is over 1 MB has an empty [text] and says why in [withheld].
|
||||
*/
|
||||
@Serializable
|
||||
data class FileContent(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val kind: String = "text",
|
||||
val language: String = "",
|
||||
val sha: String = "",
|
||||
val text: String = "",
|
||||
val withheld: Withheld? = null,
|
||||
) {
|
||||
/** The kind the viewer draws, by the `show` card's rule: anything unknown is plain text. */
|
||||
val viewKind: String get() = if (kind in ShowCard.VIEW_KINDS) kind else "text"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class SteerNote(val id: String = "", val text: String = "")
|
||||
|
||||
@@ -227,6 +506,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"
|
||||
}
|
||||
@@ -261,8 +542,13 @@ data class CardItem(
|
||||
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,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
|
||||
|
||||
@Serializable
|
||||
data class Card(
|
||||
val id: String,
|
||||
@@ -319,8 +605,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())
|
||||
@@ -345,4 +640,207 @@ 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,
|
||||
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`) -------------------------------------
|
||||
|
||||
/** How many background agents are in each state, and the three sums the strip shows. */
|
||||
@Serializable
|
||||
data class ActivitySummary(
|
||||
val queued: Int = 0,
|
||||
val working: Int = 0,
|
||||
val waiting: Int = 0,
|
||||
val done: Int = 0,
|
||||
val stopped: Int = 0,
|
||||
val error: Int = 0,
|
||||
val active: Int = 0,
|
||||
val finished: Int = 0,
|
||||
val total: Int = 0,
|
||||
)
|
||||
|
||||
/** An agent's latest step: the tool it called and on what. */
|
||||
@Serializable
|
||||
data class AgentStep(val tool: String = "", val label: String = "", val title: String = "", val error: Boolean = false, val running: Boolean = false)
|
||||
|
||||
/**
|
||||
* One background agent: a team's member (`kind` member, [id] its name) or a job (`kind` job;
|
||||
* [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
|
||||
data class ActivityAgent(
|
||||
val kind: String = "",
|
||||
val id: String = "",
|
||||
val type: String = "",
|
||||
val name: String = "",
|
||||
val role: String = "",
|
||||
val brief: String = "",
|
||||
val state: String = "",
|
||||
val seconds: Int = 0,
|
||||
val started: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val manager: String? = null,
|
||||
val depth: Int = 0,
|
||||
val lead: Boolean = false,
|
||||
val step: AgentStep? = null,
|
||||
val text: String = "",
|
||||
val steps: Int = 0,
|
||||
val tools: Int = 0,
|
||||
val stoppable: Boolean = false,
|
||||
val transcript: Boolean = false,
|
||||
val children: List<ActivityAgent> = emptyList(),
|
||||
) {
|
||||
/** Still to come back: queued, working or waiting. */
|
||||
val isActive: Boolean get() = state in ACTIVE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "working", "waiting")
|
||||
}
|
||||
}
|
||||
|
||||
/** One message in a team's room. [text] is a model's: rendered as untrusted markdown. */
|
||||
@Serializable
|
||||
data class RoomMessage(
|
||||
val n: Int = 0,
|
||||
val from: String = "",
|
||||
val to: List<String> = emptyList(),
|
||||
val text: String = "",
|
||||
val report: Boolean = false,
|
||||
val created: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ActivityTeam(
|
||||
val min: Int = 1,
|
||||
val max: Int = 1,
|
||||
val size: Int = 0,
|
||||
val goal: String = "",
|
||||
val room: List<RoomMessage> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
)
|
||||
|
||||
/** One category of the context: `messages`, `system`, `memory`, … and `free`. */
|
||||
@Serializable
|
||||
data class ContextPart(val key: String = "", val tokens: Int = 0, val percent: Double? = null)
|
||||
|
||||
@Serializable
|
||||
data class ContextUse(
|
||||
val used: Int = 0,
|
||||
val limit: Int = 0,
|
||||
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(),
|
||||
)
|
||||
|
||||
/** A file the chat or its agents wrote: lines added and removed when known. */
|
||||
@Serializable
|
||||
data class Output(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val writes: Int = 0,
|
||||
val created: Boolean = false,
|
||||
val added: Int? = null,
|
||||
val removed: Int? = null,
|
||||
val at: String = "",
|
||||
)
|
||||
|
||||
/** Everything the activity panel shows. [version] changes whenever any of it but the elapsed time does. */
|
||||
@Serializable
|
||||
data class Activity(
|
||||
val version: String = "",
|
||||
val summary: ActivitySummary = ActivitySummary(),
|
||||
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,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ActivityEnvelope(val activity: Activity)
|
||||
|
||||
/** The events route's frame: what changed is fetched with `GET /activity`. */
|
||||
@Serializable
|
||||
data class ActivityFrame(val version: String = "", val summary: ActivitySummary = ActivitySummary())
|
||||
|
||||
/** A tool call in an agent's conversation: its name and what it was on. */
|
||||
@Serializable
|
||||
data class TurnTool(val name: String = "", val title: String = "", val isError: Boolean = false)
|
||||
|
||||
/** One turn of a background agent's conversation. `machine`: a message the system gave it. */
|
||||
@Serializable
|
||||
data class AgentTurn(
|
||||
val role: String = "",
|
||||
val text: String = "",
|
||||
val machine: Boolean = false,
|
||||
val tools: List<TurnTool> = emptyList(),
|
||||
val error: String = "",
|
||||
val running: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class AgentDetail(val agent: ActivityAgent, val transcript: List<AgentTurn> = emptyList())
|
||||
|
||||
@Serializable
|
||||
data class Stopped(val stopped: List<String> = emptyList())
|
||||
|
||||
/** One agent of a team's tree (`GET /chats/{chat}/team`). */
|
||||
@Serializable
|
||||
data class TeamAgent(
|
||||
val name: String = "",
|
||||
val manager: String? = null,
|
||||
val role: String = "",
|
||||
val state: String = "",
|
||||
val model: String = "",
|
||||
val agent: String = "",
|
||||
val lead: Boolean = false,
|
||||
val depth: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TeamView(
|
||||
val offered: Boolean = false,
|
||||
val min: Int = 1,
|
||||
val max: Int = 1,
|
||||
val size: Int = 0,
|
||||
val parallel: Int? = null,
|
||||
val goal: String = "",
|
||||
val agents: List<TeamAgent> = emptyList(),
|
||||
val room: List<RoomMessage> = emptyList(),
|
||||
val cursor: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TeamEnvelope(val team: TeamView)
|
||||
@@ -0,0 +1,137 @@
|
||||
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 = setOf("stopped", "failed")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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): numbers as integers, a rate with one
|
||||
* decimal in [locale]'s format, `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", "${p.ahead}") 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) {
|
||||
words.text("reading_prompt", "$done", "$total", "${done.toLong() * 100 / total}")
|
||||
} else {
|
||||
words.text("reading_prompt_bare")
|
||||
}
|
||||
}
|
||||
|
||||
"thinking" -> words.text("thinking")
|
||||
|
||||
"writing" -> p.rate?.let { words.text("writing", String.format(locale, "%.1f", it)) } ?: words.text("writing_bare")
|
||||
|
||||
"running_tool" -> {
|
||||
val tool = p.tool ?: return null
|
||||
if (!p.what.isNullOrBlank()) words.text("running_tool", tool, p.what.take(80)) 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", "${p.running ?: 0}")
|
||||
|
||||
"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,226 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
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: [reason] `switched` when it stood in for [switchedFrom], which was busy. */
|
||||
@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 server's own sentence. */
|
||||
@Serializable
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "")
|
||||
|
||||
/**
|
||||
* 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,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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`, `matters` or `never`; [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("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,
|
||||
)
|
||||
|
||||
/** `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. */
|
||||
@Serializable
|
||||
data class ScheduleWatch(val kind: String = "", val target: String = "", @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 = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* 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,
|
||||
)
|
||||
|
||||
/** A run that waits because its computer is not linked (`error.class` `device_away`). */
|
||||
val ScheduleRun.computerAway: Boolean get() = error?.kind == "device_away"
|
||||
@@ -5,6 +5,7 @@ import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import okhttp3.Request
|
||||
import okhttp3.Response
|
||||
import okhttp3.sse.EventSource
|
||||
import okhttp3.sse.EventSourceListener
|
||||
@@ -31,7 +32,7 @@ class StreamClient(private val api: ApiClient) {
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(chatId, messageId).collect { result ->
|
||||
once(api.streamRequest(chatId, messageId)).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
@@ -51,15 +52,45 @@ 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.
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = 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)
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) continue
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
|
||||
private sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
private fun once(chatId: String, messageId: String): Flow<Outcome> = callbackFlow {
|
||||
private fun once(request: Request): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
api.streamRequest(chatId, messageId),
|
||||
request,
|
||||
object : EventSourceListener() {
|
||||
override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
|
||||
trySend(Outcome.Event(Frame(type ?: "message", data)))
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -2,53 +2,56 @@ package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
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
|
||||
|
||||
/**
|
||||
* 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
|
||||
* `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.
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
|
||||
/** 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()
|
||||
}
|
||||
|
||||
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)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
|
||||
val wantsMic = intent.getBooleanExtra(EXTRA_LISTEN, false)
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
if (waiting.isNotBlank()) controller.ask(waiting)
|
||||
locked.value = false
|
||||
if (waiting.isNotBlank()) controller.ask(waiting) else controller.opened(locked = false)
|
||||
}
|
||||
|
||||
override fun onDismissCancelled() = finish()
|
||||
@@ -58,38 +61,35 @@ class AssistActivity : ComponentActivity() {
|
||||
)
|
||||
} else if (waiting.isNotBlank()) {
|
||||
controller.ask(waiting)
|
||||
} else if (wantsMic && !controller.micAllowed()) {
|
||||
mic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
} else {
|
||||
controller.opened(locked = false)
|
||||
}
|
||||
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)
|
||||
},
|
||||
)
|
||||
AssistPanel(
|
||||
controller = controller,
|
||||
locked = locked.value,
|
||||
onUnlockAndAsk = { text ->
|
||||
keyguard.requestDismissKeyguard(
|
||||
this@AssistActivity,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
locked.value = false
|
||||
if (text.isBlank()) controller.opened(locked = false) else controller.ask(text)
|
||||
}
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
finish()
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
finish()
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
onDismiss = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,5 +101,8 @@ class AssistActivity : ComponentActivity() {
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
|
||||
/** Handed over by the session: ask for the microphone, then listen. */
|
||||
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
|
||||
}
|
||||
}
|
||||
@@ -1,127 +1,455 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
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.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
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.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
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
|
||||
}
|
||||
|
||||
/** 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,
|
||||
) {
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == 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() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) : 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 var following: Job? = null
|
||||
private var hearing: Job? = null
|
||||
private var usingPhone = false
|
||||
private var screenText: String? = null
|
||||
private var screenshot: Bitmap? = null
|
||||
private var stt: Boolean? = null
|
||||
private val ready: Job
|
||||
|
||||
init {
|
||||
scope.launch { _state.update { it.copy(signedIn = context.lembas.instances.current() != null) } }
|
||||
ready = scope.launch { load() }
|
||||
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
|
||||
}
|
||||
|
||||
/** The instance, its models and what it offers this account; the choices kept in Settings. */
|
||||
private suspend fun load() {
|
||||
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,
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
val api = instance?.let { store.clientFor(it) } ?: return
|
||||
try {
|
||||
val me = api.me()
|
||||
val models = api.models()
|
||||
stt = me.speechToText
|
||||
val chosen = prefs.assistantModel.takeIf { id -> models.any { it.id == id } }
|
||||
?: me.defaultModel?.takeIf { id -> models.any { it.id == id } }
|
||||
?: models.firstOrNull { it.default }?.id
|
||||
?: models.firstOrNull()?.id
|
||||
_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, the phone is locked (nothing is sent from the lock
|
||||
* screen), or the microphone is not allowed yet (that needs an activity to ask).
|
||||
*/
|
||||
fun opened(locked: Boolean) {
|
||||
scope.launch {
|
||||
ready.join()
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val s = _state.value
|
||||
if (s.signedIn && !locked && prefs.assistantListens && s.canListen && s.empty && !s.listening && micAllowed()) listen()
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
if (image != null) screenshot = image
|
||||
_state.update { it.copy(screenAvailable = screenText != null || screenshot != null) }
|
||||
_state.update { it.copy(screenText = screenText != null, screenshot = image ?: it.screenshot) }
|
||||
}
|
||||
|
||||
fun includeScreen(on: Boolean) = _state.update { it.copy(includeScreen = on) }
|
||||
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")
|
||||
fun listen() {
|
||||
override fun listen() {
|
||||
if (_state.value.listening || !micAllowed()) return
|
||||
speaker.stop()
|
||||
recorder.start()
|
||||
_state.update { it.copy(listening = true, error = null) }
|
||||
}
|
||||
|
||||
/** Stop listening, write down what was said, and ask it. */
|
||||
fun heard() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
_state.update { it.copy(listening = false) }
|
||||
if (wav.isEmpty()) return@launch
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = e.message) }
|
||||
hearing?.cancel()
|
||||
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
|
||||
hearing = scope.launch {
|
||||
usingPhone = phoneEngine()
|
||||
if (usingPhone) {
|
||||
phone.start(
|
||||
onPartial = { words -> _state.update { it.copy(heard = words) } },
|
||||
onLevel = { l -> _state.update { it.copy(level = l) } },
|
||||
onResult = { words ->
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
if (words.isNotBlank()) ask(words, spoken = true)
|
||||
},
|
||||
onFail = { code ->
|
||||
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
|
||||
_state.update {
|
||||
it.copy(
|
||||
listening = false,
|
||||
level = 0f,
|
||||
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean = false) {
|
||||
/**
|
||||
* 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, and not past the first minute.
|
||||
*/
|
||||
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) 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). */
|
||||
private suspend fun untilQuiet(): Boolean {
|
||||
var spoke = false
|
||||
var quietFor = 0L
|
||||
var waited = 0L
|
||||
// The words written down so far are the second ear, for a quiet microphone: words the
|
||||
// instance heard mean speech, and the same words for a while mean it ended.
|
||||
var words = ""
|
||||
var sameWordsFor = 0L
|
||||
while (true) {
|
||||
delay(TICK_MS)
|
||||
waited += TICK_MS
|
||||
val level = recorder.level.value
|
||||
if (level >= SPEAKING) {
|
||||
spoke = true
|
||||
quietFor = 0
|
||||
} else if (level < QUIET) {
|
||||
quietFor += TICK_MS
|
||||
}
|
||||
val heard = _state.value.heard
|
||||
if (heard.isNotBlank()) spoke = true
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += TICK_MS
|
||||
}
|
||||
if (spoke && quietFor >= PAUSE_MS) return true
|
||||
if (sameWordsFor >= SAME_WORDS_MS) return true
|
||||
if (!spoke && waited >= NOTHING_SAID_MS) return false
|
||||
if (waited >= LONGEST_MS) return spoke
|
||||
}
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
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()) ask(text, spoken = true)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop listening and keep nothing: the person would rather type. */
|
||||
override fun type() {
|
||||
hearing?.cancel()
|
||||
hearing = null
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
_state.update { it.copy(listening = false, heard = "", level = 0f) }
|
||||
}
|
||||
|
||||
// --- 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)
|
||||
}
|
||||
|
||||
fun ask(question: String, spoken: Boolean) {
|
||||
if (question.isBlank()) return
|
||||
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) }
|
||||
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()
|
||||
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) }
|
||||
}
|
||||
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 ->
|
||||
// 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, 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())
|
||||
}
|
||||
}
|
||||
}
|
||||
var live = LiveReply(replyId)
|
||||
StreamClient(api).follow(inChat, replyId).collect { frame ->
|
||||
live = live.apply(frame.event, frame.data)
|
||||
_state.update { it.copy(reply = live, busy = live.finished == null) }
|
||||
}
|
||||
val finished = live.finished
|
||||
if (spoken && prefs.readAloudSpoken && finished != null) {
|
||||
val words = finished.steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() }
|
||||
if (words.isNotBlank()) speaker.play(api.speech(plain(words)))
|
||||
_state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.copy(reply = live), busy = live.finished == null) }
|
||||
}
|
||||
if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null) speak(spokenWords(live.finished?.steps.orEmpty()))
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName) }
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) }
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
_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)) }
|
||||
}
|
||||
|
||||
override fun stopReading() = speaker.stop()
|
||||
|
||||
private suspend fun speak(words: String) {
|
||||
if (words.isBlank()) return
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
speaker.play(api.speech(words))
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -130,7 +458,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
fun close() {
|
||||
following?.cancel()
|
||||
hearing?.cancel()
|
||||
speaker.stop()
|
||||
phone.stop()
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
@@ -144,6 +474,21 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
companion object {
|
||||
const val MAX_SCREEN_CHARS = 8_000
|
||||
|
||||
// Listening, for the instance's speech-to-text (the phone's recogniser finds the end of
|
||||
// speech itself). Levels are the RMS of 16-bit samples, 0..1: a room is under 0.01,
|
||||
// a voice near the phone 0.02 and up. Not tuned on many phones: the stop button always works.
|
||||
private const val TICK_MS = 100L
|
||||
private const val SPEAKING = 0.02f
|
||||
private const val QUIET = 0.01f
|
||||
private const val PAUSE_MS = 1_800L
|
||||
private const val SAME_WORDS_MS = 4_500L
|
||||
private const val NOTHING_SAID_MS = 8_000L
|
||||
private const val LONGEST_MS = 120_000L
|
||||
private const val PARTIAL_EVERY_MS = 1_200L
|
||||
|
||||
/** 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
|
||||
.replace(Regex("```[\\s\\S]*?```"), " ")
|
||||
|
||||
@@ -1,120 +1,40 @@
|
||||
@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,
|
||||
) {
|
||||
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,
|
||||
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)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,17 @@ import android.app.assist.AssistStructure
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
import android.service.voice.VoiceInteractionService
|
||||
import android.service.voice.VoiceInteractionSession
|
||||
import android.service.voice.VoiceInteractionSessionService
|
||||
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,6 +24,7 @@ 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 kotlinx.coroutines.CoroutineScope
|
||||
@@ -54,6 +59,7 @@ 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)
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
@@ -62,25 +68,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) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(controller.appIntent())
|
||||
startAssistantActivity(current.value.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("") },
|
||||
onNeedMic = { handOff("", listen = true) },
|
||||
onDismiss = { hide() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -89,16 +108,22 @@ 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
|
||||
controller.opened(locked())
|
||||
}
|
||||
|
||||
/**
|
||||
* 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()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
controller = AssistController(context, scope)
|
||||
current.value = controller
|
||||
registry.currentState = Lifecycle.State.CREATED
|
||||
}
|
||||
|
||||
@@ -119,7 +144,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)
|
||||
@@ -138,14 +163,13 @@ class LembasAssistSession(context: Context) :
|
||||
* which asks Android to unlock first and only then sends it. The microphone's permission
|
||||
* prompt needs an activity too.
|
||||
*/
|
||||
private fun handOff(text: String) {
|
||||
private fun handOff(text: String, listen: Boolean = false) {
|
||||
startAssistantActivity(
|
||||
Intent(context, AssistActivity::class.java)
|
||||
.putExtra(AssistActivity.EXTRA_QUESTION, text)
|
||||
.putExtra(AssistActivity.EXTRA_LISTEN, listen)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
hide()
|
||||
}
|
||||
|
||||
private fun CoroutineScope.isActiveScope(): Boolean = coroutineContext[kotlinx.coroutines.Job]?.isActive == true
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
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.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.History
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Lightbulb
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
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.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.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
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.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.AssistSheetContent(
|
||||
state: AssistUiState,
|
||||
actions: AssistActions,
|
||||
locked: Boolean,
|
||||
handle: Modifier = Modifier,
|
||||
onOpenApp: () -> Unit = {},
|
||||
onSend: (String) -> Unit = actions::ask,
|
||||
onMic: () -> Unit = actions::listen,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val scroll = rememberScrollState()
|
||||
val growth = state.turns.lastOrNull()?.steps?.sumOf { (it.markdown?.length ?: 0) + (it.text?.length ?: 0) } ?: 0
|
||||
LaunchedEffect(state.turns.size, growth) { if (state.turns.isNotEmpty()) scroll.animateScrollTo(scroll.maxValue) }
|
||||
|
||||
// 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),
|
||||
) {
|
||||
if (state.empty) {
|
||||
Starting(state, actions, locked)
|
||||
} else {
|
||||
state.turns.forEachIndexed { i, turn ->
|
||||
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
|
||||
}
|
||||
}
|
||||
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.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.name.ifBlank { model.id }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
trailingIcon = if (model.id == state.modelId) {
|
||||
{ Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = {
|
||||
open = false
|
||||
actions.pickModel(model.id)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
}
|
||||
}
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Text(stringResource(R.string.assist_no_wake_word), 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),
|
||||
)
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
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))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,28 @@
|
||||
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.AudioFormat
|
||||
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.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 +43,19 @@ 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)
|
||||
|
||||
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
|
||||
fun start() {
|
||||
if (record != null) return
|
||||
@@ -54,6 +76,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,6 +94,7 @@ 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)
|
||||
@@ -80,6 +104,18 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
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,9 +137,11 @@ 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()
|
||||
|
||||
suspend fun play(mp3: ByteArray) {
|
||||
stop()
|
||||
@@ -120,10 +158,12 @@ class Speaker(private val context: Context) {
|
||||
it.release()
|
||||
file.delete()
|
||||
player = null
|
||||
_playing.value = false
|
||||
}
|
||||
prepare()
|
||||
start()
|
||||
}
|
||||
_playing.value = true
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
@@ -132,5 +172,120 @@ class Speaker(private val context: Context) {
|
||||
release()
|
||||
}
|
||||
player = null
|
||||
_playing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
|
||||
stop()
|
||||
startWith(onDevice(context), onPartial, onLevel, onResult, onFail)
|
||||
}
|
||||
|
||||
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
|
||||
private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
|
||||
val other = component(context)
|
||||
val made = when {
|
||||
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
|
||||
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
|
||||
else -> return onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
}
|
||||
recognizer = made
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) {}
|
||||
|
||||
override fun onBeginningOfSpeech() {}
|
||||
|
||||
// About -2 dB in silence to 10 dB speaking: the meter's 0..1.
|
||||
override fun onRmsChanged(rmsdB: Float) = onLevel(((rmsdB + 2f) / 12f).coerceIn(0f, 1f))
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = 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, onPartial, onLevel, onResult, onFail)
|
||||
return
|
||||
}
|
||||
stop()
|
||||
onFail(error)
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
|
||||
stop()
|
||||
onResult(text)
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
|
||||
?.takeIf { it.isNotBlank() }?.let(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)
|
||||
.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
|
||||
|
||||
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
|
||||
}
|
||||
@@ -66,9 +66,42 @@ 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,
|
||||
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())
|
||||
|
||||
@@ -98,22 +98,17 @@ 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"
|
||||
|
||||
fun show(context: Context, instance: String, payload: PushPayload) {
|
||||
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
|
||||
if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload)
|
||||
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
|
||||
val id = (chatId ?: payload.url).hashCode()
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
id,
|
||||
Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(EXTRA_CHAT, chatId)
|
||||
.putExtra(EXTRA_INSTANCE, instance),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
val open = opener(context, instance, id, chatId = chatId)
|
||||
val channel = when (payload.kind) {
|
||||
"ask" -> LembasApp.CHANNEL_ASKS
|
||||
"report" -> LembasApp.CHANNEL_REPORTS
|
||||
else -> LembasApp.CHANNEL_REPLIES
|
||||
}
|
||||
val builder = NotificationCompat.Builder(context, channel)
|
||||
@@ -127,14 +122,89 @@ 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 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): 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_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,
|
||||
@@ -171,3 +241,31 @@ class CardActionReceiver : BroadcastReceiver() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,78 @@
|
||||
package eu.llembas.android.push
|
||||
|
||||
import eu.llembas.android.api.PushPayload
|
||||
|
||||
/**
|
||||
* 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)
|
||||
val schedule = payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule ?: return null
|
||||
val run = 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,5 +1,6 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
@@ -22,10 +23,12 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -38,6 +41,8 @@ import kotlinx.coroutines.withContext
|
||||
class ShareActivity : ComponentActivity() {
|
||||
private val failure = mutableStateOf<String?>(null)
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
@@ -103,7 +108,7 @@ class ShareActivity : ComponentActivity() {
|
||||
)
|
||||
finish()
|
||||
} catch (e: Exception) {
|
||||
failure.value = e.message ?: e.javaClass.simpleName
|
||||
failure.value = explain(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import android.content.Context
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import java.net.ConnectException
|
||||
import java.net.NoRouteToHostException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
|
||||
/**
|
||||
* A failure in words a person can act on. The server's refusal is its own sentence; a phone
|
||||
* that cannot reach the instance at all -- no network, a name that does not resolve off the
|
||||
* home network, a server that is down -- is one sentence saying so, rather than
|
||||
* "Unable to resolve host" or "failed to connect to /…:443". A certificate the phone does not
|
||||
* trust keeps its own message: that one names what to fix.
|
||||
*/
|
||||
fun Context.explain(e: Throwable): String = when {
|
||||
e is ApiException -> e.message?.ifBlank { null } ?: getString(R.string.offline)
|
||||
unreachable(e) -> getString(R.string.offline)
|
||||
else -> e.message?.ifBlank { null } ?: e.javaClass.simpleName
|
||||
}
|
||||
|
||||
/** Whether a failure means "the instance cannot be reached" rather than "it said no". */
|
||||
fun unreachable(e: Throwable): Boolean = e is UnknownHostException || e is ConnectException || e is SocketTimeoutException || e is NoRouteToHostException
|
||||
@@ -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,59 @@
|
||||
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.
|
||||
*/
|
||||
sealed interface Segment {
|
||||
data class Prose(val markdown: String) : Segment
|
||||
|
||||
data class Code(val language: String, val code: String, val closed: Boolean = true) : Segment
|
||||
}
|
||||
|
||||
private val OPENING = Regex("^ {0,3}(`{3,}|~{3,})\\s*([^`\\s]*).*$")
|
||||
|
||||
fun splitFences(markdown: String): 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) {
|
||||
prose.append(lines[i]).append('\n')
|
||||
i++
|
||||
continue
|
||||
}
|
||||
flushProse()
|
||||
val fence = open.groupValues[1]
|
||||
val language = open.groupValues[2]
|
||||
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 += Segment.Code(language, code.joinToString("\n"), closed)
|
||||
}
|
||||
flushProse()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
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.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.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.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
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Models' pictures, fetched once with the token and kept small in memory. A picture that
|
||||
* failed is not asked for again until the app starts anew; the initial stands in for it.
|
||||
*/
|
||||
private object ModelImages {
|
||||
private const val SIDE = 128
|
||||
private val cache = LruCache<String, ImageBitmap>(48)
|
||||
private val failed = mutableSetOf<String>()
|
||||
|
||||
fun cached(path: String): ImageBitmap? = cache.get(path)
|
||||
|
||||
suspend fun load(context: Context, path: String): ImageBitmap? {
|
||||
cache.get(path)?.let { return it }
|
||||
if (path in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.modelImage(path) }.getOrNull()
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += path else cache.put(path, image)
|
||||
return image
|
||||
}
|
||||
|
||||
/** Decoded at about [SIDE] pixels a side: an avatar, not the original. */
|
||||
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
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)?.asImageBitmap()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A model's picture in a circle, as the web UI shows it beside the model's name: the picture
|
||||
* the instance has for it, or its initial on the theme's soft accent when there is none (or
|
||||
* while it loads, or when it could not be read).
|
||||
*/
|
||||
@Composable
|
||||
fun ModelAvatar(model: ModelInfo?, fallbackName: String, size: Dp = 24.dp, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
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 && !still) image = ModelImages.load(context, path)
|
||||
}
|
||||
Box(modifier.size(size).clip(CircleShape).background(palette.accentSoft), contentAlignment = Alignment.Center) {
|
||||
val shown = image
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else {
|
||||
val name = model?.name?.ifBlank { null } ?: fallbackName
|
||||
Text(
|
||||
name.trim().firstOrNull()?.uppercase() ?: "?",
|
||||
color = palette.ink,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = with(LocalDensity.current) { (size * 0.5f).toSp() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
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 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 spec's separator, `progress.line`'s " · ", before the clock.
|
||||
if (clock != null) Text(" · $clock", style = style, color = color, maxLines = 1, softWrap = false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,919 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
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.fillMaxHeight
|
||||
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.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.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.automirrored.filled.NoteAdd
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
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.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
|
||||
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
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
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.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
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.Activity
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
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
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// --- The summary chip above the composer --------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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)
|
||||
if (counts.isEmpty()) return
|
||||
val palette = LocalPalette.current
|
||||
val words = counts.map { (state, n) -> stateCount(state, n) }
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
color = palette.surfaceRaised,
|
||||
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))
|
||||
Text(
|
||||
words.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 8.dp),
|
||||
)
|
||||
Icon(Icons.AutoMirrored.Filled.KeyboardArrowRight, contentDescription = stringResource(R.string.activity_open), tint = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun stateCount(state: String, n: Int): String = when (state) {
|
||||
"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())
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun stateWord(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.agent_state_queued)
|
||||
"working" -> stringResource(R.string.agent_state_working)
|
||||
"waiting" -> stringResource(R.string.agent_state_waiting)
|
||||
"done" -> stringResource(R.string.agent_state_done)
|
||||
"stopped" -> stringResource(R.string.agent_state_stopped)
|
||||
else -> stringResource(R.string.agent_state_error)
|
||||
}
|
||||
|
||||
@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
|
||||
"done" -> palette.success
|
||||
"error" -> palette.danger
|
||||
else -> palette.inkFaint
|
||||
}
|
||||
|
||||
/** A context category's colour, as the web's `activity-context__seg--*` maps them to tokens. */
|
||||
private fun categoryColour(palette: Palette, key: String): Color = when (key) {
|
||||
"messages" -> palette.accent
|
||||
"system" -> palette.inkMuted
|
||||
"memory" -> palette.warning
|
||||
"instructions" -> palette.success
|
||||
"tools" -> palette.ink
|
||||
"mcp_tools" -> palette.danger
|
||||
"since" -> palette.inkFaint
|
||||
"buffer" -> palette.borderStrong
|
||||
else -> palette.border
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun categoryName(key: String): String = when (key) {
|
||||
"messages" -> stringResource(R.string.ctx_messages)
|
||||
"system" -> stringResource(R.string.ctx_system)
|
||||
"memory" -> stringResource(R.string.ctx_memory)
|
||||
"instructions" -> stringResource(R.string.ctx_instructions)
|
||||
"tools" -> stringResource(R.string.ctx_tools)
|
||||
"mcp_tools" -> stringResource(R.string.ctx_mcp_tools)
|
||||
"since" -> stringResource(R.string.ctx_since)
|
||||
"buffer" -> stringResource(R.string.ctx_buffer)
|
||||
"free" -> stringResource(R.string.ctx_free)
|
||||
else -> key
|
||||
}
|
||||
|
||||
// --- The sheet ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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 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(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 sheet reads itself again: cheaply, every 5 s.
|
||||
if (!live && ticks % 5 == 0) model.loadActivity(context = false)
|
||||
}
|
||||
}
|
||||
|
||||
val close = {
|
||||
model.panel(false)
|
||||
onClose()
|
||||
}
|
||||
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, 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, ActivityLogic.title(agent))
|
||||
},
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.stopAgent(agent)
|
||||
stopping = null
|
||||
}) { Text(stringResource(R.string.stop)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { stopping = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
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 }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
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()) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = !open },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
count?.let { Text(it.toString(), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted, modifier = Modifier.padding(end = 8.dp)) }
|
||||
Icon(if (open) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, contentDescription = null, tint = palette.inkFaint)
|
||||
}
|
||||
if (open) content()
|
||||
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, 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?, canCompact: Boolean, compacting: Boolean, onCompact: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
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(
|
||||
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(
|
||||
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),
|
||||
)
|
||||
// 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Outputs --------------------------------------------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun OutputsSection(outputs: List<Output>, canOpen: Boolean, onOpen: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column {
|
||||
outputs.forEach { out ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable(enabled = canOpen && out.path.isNotBlank()) { onOpen(out.path) },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
if (out.created) Icons.AutoMirrored.Filled.NoteAdd else Icons.Filled.Description,
|
||||
contentDescription = null,
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Column(Modifier.weight(1f).padding(horizontal = 8.dp)) {
|
||||
Text(out.name.ifBlank { out.path }, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
out.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (out.added != null) {
|
||||
Text("+${out.added}", style = MaterialTheme.typography.labelMedium, color = palette.success)
|
||||
Text(" −${out.removed ?: 0}", style = MaterialTheme.typography.labelMedium, color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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, actions: ActivityActions, unfolded: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val team = activity.team
|
||||
if (activity.agents.isEmpty() && team == null) {
|
||||
Empty(stringResource(R.string.tasks_empty))
|
||||
return
|
||||
}
|
||||
val (live, ended) = ActivityLogic.split(activity.agents)
|
||||
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))
|
||||
Text(
|
||||
stringResource(R.string.team_size, t.size.toString(), t.max.toString()),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
if (t.goal.isNotBlank()) Text(t.goal, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
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.ExpandMore else Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
)
|
||||
Text(
|
||||
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) ended.forEach { TaskCard(it, readAt, now, actions, unfolded = false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 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 TaskRow(agent: ActivityAgent, readAt: Long, now: Long, actions: ActivityActions, unfolded: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
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 }.padding(start = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
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(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(
|
||||
ActivityLogic.duration(ActivityLogic.elapsed(agent, readAt, now)),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
textAlign = TextAlign.End,
|
||||
modifier = Modifier.width(64.dp),
|
||||
)
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
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 = 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() && 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(" "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = if (step.error) palette.danger else palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (agent.text.isNotBlank()) {
|
||||
Text(agent.text, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = 6, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (agent.transcript) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
|
||||
// A report is marked as on the web: a bar of the accent down its side.
|
||||
Box(Modifier.width(3.dp).heightIn(min = 24.dp).background(if (entry.report) palette.accent else Color.Transparent))
|
||||
Column(Modifier.weight(1f).padding(start = 8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"#${entry.n} ${entry.from} → ${entry.to.joinToString(", ")}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (entry.report) {
|
||||
Text(
|
||||
stringResource(R.string.room_report),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.accentInk,
|
||||
modifier = Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp)).background(palette.accent).padding(horizontal = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
MarkdownText(entry.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- One agent's conversation, read-only ------------------------------------------------------
|
||||
|
||||
/** 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<Conversation?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(key) {
|
||||
val api = context.lembas.instances.client() ?: return@LaunchedEffect
|
||||
while (true) {
|
||||
try {
|
||||
detail = load(api)
|
||||
error = null
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
error = context.explain(e)
|
||||
}
|
||||
if (detail?.running != true) break
|
||||
delay(3_000)
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
facts.filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
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)
|
||||
}
|
||||
|
||||
turns == null -> Box(Modifier.padding(padding).fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.padding(padding).fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (turns.isEmpty()) item { Empty(stringResource(R.string.agent_nothing_yet)) }
|
||||
items(turns) { turn ->
|
||||
if (turn.role == "user") {
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(
|
||||
RoundedCornerShape(8.dp),
|
||||
).background(if (turn.machine) palette.surfaceRaised else palette.bubbleUser).padding(12.dp),
|
||||
) {
|
||||
if (turn.machine) {
|
||||
Text(
|
||||
stringResource(R.string.agent_machine),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
Text(turn.text, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
} else {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
turn.tools.forEach { tool ->
|
||||
Text(
|
||||
listOf(tool.name, tool.title).filter { it.isNotBlank() }.joinToString(" "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = if (tool.isError) palette.danger else palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (turn.text.isNotBlank()) MarkdownText(turn.text)
|
||||
if (turn.error.isNotBlank()) Text(turn.error, style = MaterialTheme.typography.bodySmall, color = palette.danger)
|
||||
if (turn.running) {
|
||||
Text(
|
||||
stringResource(R.string.loading_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,9 +28,11 @@ import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -46,85 +48,19 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
private val Rounded = RoundedCornerShape(10.dp)
|
||||
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. */
|
||||
@Composable
|
||||
fun Steps(steps: List<Step>, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> Thinking(step)
|
||||
"text" -> MarkdownText(step.markdown.orEmpty(), modifier = Modifier.fillMaxWidth())
|
||||
"tools" -> step.calls.forEach { ToolCallBlock(it) }
|
||||
"steer" -> step.messages.forEach { Steered(it.text) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Thinking(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
Column(
|
||||
Modifier.fillMaxWidth().background(palette.bgSunken, Rounded).clickable { open = !open }.padding(10.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Psychology, contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkFaint)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
stringResource(if (step.open) R.string.thinking else R.string.thought) + (step.label?.let { " $it" } ?: ""),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(open) {
|
||||
Text(step.text.orEmpty(), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, modifier = Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Steered(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(start = 24.dp)) {
|
||||
Text("↳ $text", style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
|
||||
private fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
internal fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
"shell" -> Icons.Filled.Terminal
|
||||
"edit" -> Icons.Filled.Edit
|
||||
"read" -> Icons.AutoMirrored.Filled.Article
|
||||
@@ -140,10 +76,15 @@ private fun iconFor(kind: String): ImageVector = when (kind) {
|
||||
* scroller, so a megabyte of output never becomes the page.
|
||||
*/
|
||||
@Composable
|
||||
fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
|
||||
fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)? = null) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(call.id ?: call.block.title) { mutableStateOf(call.block.kind == "edit") }
|
||||
val failed = call.status == "error" || !call.error.isNullOrEmpty()
|
||||
val shown = call.show
|
||||
if (shown != null && !failed) {
|
||||
ShowCardRow(shown, depth, onShow)
|
||||
return
|
||||
}
|
||||
Column(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -192,26 +133,50 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0) {
|
||||
if (call.truncated) {
|
||||
Text(stringResource(R.string.output_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
call.children?.forEach { ToolCallBlock(it, depth + 1) }
|
||||
call.children?.forEach { ToolCallBlock(it, depth + 1, onShow) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished or failed reply's foot: what it cost, and why it stopped if it did. */
|
||||
/**
|
||||
* A `show` card: the file's name and path, and Open. Nothing of its contents -- the words here
|
||||
* are a path a model chose, drawn as text like everything else. The web page opens a card that
|
||||
* arrives while it is open by itself, beside the conversation, when the screen is wide enough;
|
||||
* a phone's screen is not, so here it waits for a tap.
|
||||
*/
|
||||
@Composable
|
||||
fun ReplyFoot(message: Message) {
|
||||
private fun ShowCardRow(show: ShowCard, depth: Int, onShow: ((ShowCard) -> Unit)?) {
|
||||
val palette = LocalPalette.current
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, style = MaterialTheme.typography.bodySmall)
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = (depth * 16).dp)
|
||||
.background(palette.surfaceRaised, Rounded)
|
||||
.border(1.dp, palette.border, Rounded)
|
||||
.then(if (onShow != null) Modifier.clickable { onShow(show) } else Modifier)
|
||||
.padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp)
|
||||
.heightIn(min = 48.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Visibility, contentDescription = stringResource(R.string.shown), modifier = Modifier.size(18.dp), tint = palette.leaf)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
// The one part that gives: a long path shortens, the button keeps its size.
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(show.name.ifBlank { show.path }, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
show.path + if (show.line > 0) ":${show.line}" else "",
|
||||
fontFamily = FontFamily.Monospace,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (onShow != null) {
|
||||
TextButton(onClick = { onShow(show) }, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.viewer_open))
|
||||
}
|
||||
}
|
||||
}
|
||||
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))
|
||||
}
|
||||
@@ -72,21 +72,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,
|
||||
@@ -109,6 +128,19 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -2,45 +2,56 @@
|
||||
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.Manifest
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.os.Build
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
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.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
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.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyListState
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
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.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.ChatBubbleOutline
|
||||
import androidx.compose.material.icons.filled.Computer
|
||||
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.Menu
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.AssistChip
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.InputChip
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
@@ -49,14 +60,18 @@ import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SheetValue
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
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.rememberCoroutineScope
|
||||
@@ -66,154 +81,273 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
/**
|
||||
* One chat, with its model behind it: the transcript, the composer, and the sheets and panels
|
||||
* that open over them. [chatId] null is a new chat (an agent chat with [agent]); its first
|
||||
* message makes it, and [onOpened] then moves the route to it.
|
||||
*/
|
||||
@Composable
|
||||
fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit = {}, model: ChatViewModel = viewModel(key = chatId ?: "new")) {
|
||||
fun ChatScreen(
|
||||
chatId: String?,
|
||||
onMenu: () -> Unit,
|
||||
onNewChat: () -> Unit,
|
||||
onLeave: () -> Unit,
|
||||
onOpened: (String) -> Unit = {},
|
||||
agent: Boolean = false,
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var activityOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var showing by remember { mutableStateOf<ShowCard?>(null) }
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
val isAgent = agent || state.chat?.isAgent == true
|
||||
|
||||
LaunchedEffect(chatId) { model.open(chatId) }
|
||||
LaunchedEffect(chatId) { model.open(chatId, agent = agent && chatId == null) }
|
||||
// A new chat gets its id from its first message; the route follows, so Back and a
|
||||
// rotation land on the chat rather than on an empty composer.
|
||||
LaunchedEffect(state.chat?.id) { state.chat?.id?.let { if (it != chatId) onOpened(it) } }
|
||||
// The chat's background agents, followed while the screen is in front and not otherwise.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
model.clearError()
|
||||
}
|
||||
}
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
LaunchedEffect(rows.size, live?.shown?.size) {
|
||||
if (rows.isNotEmpty()) list.animateScrollToItem(rows.size - 1)
|
||||
|
||||
// Read aloud on a reply, when the instance has a voice; it stops when the chat is left.
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val readAloud = remember { ReadAloud(context, scope) { said -> scope.launch { snackbar.showSnackbar(said) } } }
|
||||
LaunchedEffect(Unit) { readAloud.load() }
|
||||
DisposableEffect(Unit) { onDispose { readAloud.stop() } }
|
||||
|
||||
CompositionLocalProvider(LocalReadAloud provides readAloud.takeIf { it.available }) {
|
||||
ChatContent(
|
||||
state = state,
|
||||
actions = model,
|
||||
agent = isAgent,
|
||||
snackbar = snackbar,
|
||||
onMenu = onMenu,
|
||||
onNewChat = onNewChat,
|
||||
onLeave = onLeave,
|
||||
onActivity = { activityOpen = true },
|
||||
onShow = { showing = it },
|
||||
onKind = onKind,
|
||||
)
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Text(
|
||||
state.chat?.title?.ifBlank { null } ?: stringResource(R.string.new_chat),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
if (state.chat != null) {
|
||||
IconButton(onClick = { menu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more))
|
||||
if (activityOpen) {
|
||||
// A device's files are on the device: the sheet lists them, the tree cannot open them.
|
||||
ActivityPanel(state.chat?.id, state, model, canOpenFiles = !isAgent, onClose = { activityOpen = false })
|
||||
}
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat as it is drawn, from [state] alone: what the screenshot tests render with fake data.
|
||||
* Everything it does goes through [actions].
|
||||
*/
|
||||
@Composable
|
||||
fun ChatContent(
|
||||
state: ChatState,
|
||||
actions: ChatActions,
|
||||
agent: Boolean,
|
||||
snackbar: SnackbarHostState = remember { SnackbarHostState() },
|
||||
onMenu: () -> Unit = {},
|
||||
onNewChat: () -> Unit = {},
|
||||
onLeave: () -> Unit = {},
|
||||
onActivity: () -> Unit = {},
|
||||
onShow: (ShowCard) -> Unit = {},
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
// A chat opens at its end, where the conversation is, not at its first message.
|
||||
val list = rememberLazyListState(initialFirstVisibleItemIndex = maxOf(0, state.messages.size - 1 + if (state.more) 1 else 0))
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
var tuning by remember { mutableStateOf(false) }
|
||||
var renaming by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var suggestion by remember { mutableStateOf("") }
|
||||
var suggested by remember { mutableIntStateOf(0) }
|
||||
val copy: (String) -> Unit = { text ->
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("LLeMbas", text))
|
||||
// Android 13 and newer say "Copied" themselves.
|
||||
if (Build.VERSION.SDK_INT < 33) scope.launch { snackbar.showSnackbar(context.getString(R.string.copied)) }
|
||||
}
|
||||
val chat = state.chat
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
val info = state.modelInfo
|
||||
|
||||
// To the end when the transcript grows, and while a reply is being written -- but only if
|
||||
// the person is at the end already: reading back up is not interrupted by the next line.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
LaunchedEffect(list.isScrollInProgress) {
|
||||
if (!list.isScrollInProgress) following = !list.canScrollForward
|
||||
}
|
||||
LaunchedEffect(rows.size) { if (rows.isNotEmpty()) list.toEnd() }
|
||||
val growth = live?.let { it.shown.size * 100_000 + (it.tail.text.length + it.tail.thinking.length) } ?: 0
|
||||
LaunchedEffect(growth) { if (growth > 0 && following) list.toEnd() }
|
||||
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) }
|
||||
},
|
||||
title = {
|
||||
ModelTitle(
|
||||
model = info,
|
||||
fallback = state.modelId ?: stringResource(R.string.app_name),
|
||||
subtitle = chat?.title?.ifBlank { null },
|
||||
onClick = { picking = true },
|
||||
)
|
||||
},
|
||||
actions = {
|
||||
// The activity sheet, always within reach: context, background tasks, plan.
|
||||
IconButton(onClick = onActivity) { Icon(Icons.Filled.Bolt, contentDescription = stringResource(R.string.activity_open)) }
|
||||
if (chat != null) {
|
||||
IconButton(onClick = onNewChat) { Icon(Icons.Filled.EditNote, contentDescription = stringResource(R.string.new_chat)) }
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
MenuItem(Icons.Filled.DriveFileRenameOutline, stringResource(R.string.rename_chat)) {
|
||||
menu = false
|
||||
renaming = true
|
||||
}
|
||||
MenuItem(Icons.Filled.PlayArrow, stringResource(R.string.continue_reply)) {
|
||||
menu = false
|
||||
actions.continueChat()
|
||||
}
|
||||
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
|
||||
menu = false
|
||||
actions.change("archived", "true")
|
||||
onLeave()
|
||||
}
|
||||
MenuItem(Icons.Filled.Delete, stringResource(R.string.delete)) {
|
||||
menu = false
|
||||
actions.delete(onLeave)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.continue_reply)) }, onClick = {
|
||||
menu = false
|
||||
model.continueChat()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.archive)) }, onClick = {
|
||||
menu = false
|
||||
model.change("archived", "true")
|
||||
onBack()
|
||||
})
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.delete)) }, onClick = {
|
||||
menu = false
|
||||
model.delete(onBack)
|
||||
})
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(horizontal = 12.dp).padding(bottom = 8.dp)) {
|
||||
if (state.loading) LinearProgressIndicator(Modifier.fillMaxWidth().padding(bottom = 4.dp))
|
||||
if (rows.isEmpty() && chat == null && !agent) {
|
||||
Suggestions {
|
||||
suggestion = it
|
||||
suggested++
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Column(Modifier.background(palette.surface).navigationBarsPadding().imePadding()) {
|
||||
if (state.loading || state.uploading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
live?.plan?.let { plan ->
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
PlanBody(plan)
|
||||
}
|
||||
}
|
||||
state.chat?.plan?.let { _ ->
|
||||
if (live == null && state.chat?.mode == "plan") {
|
||||
TextButton(onClick = { model.executePlan() }, modifier = Modifier.padding(horizontal = 8.dp)) {
|
||||
Text(stringResource(R.string.plan_carry_out))
|
||||
live?.plan?.let { plan ->
|
||||
Surface(
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
) {
|
||||
Column(Modifier.heightIn(max = 180.dp).padding(horizontal = 16.dp, vertical = 8.dp)) { PlanBody(plan) }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (live != null && live.jobs.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()).padding(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
live.jobs.forEach { job ->
|
||||
AssistChip(onClick = {}, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) })
|
||||
if (chat?.plan != null && live == null && chat.mode == "plan") {
|
||||
TextButton(onClick = actions::executePlan) { Text(stringResource(R.string.plan_carry_out)) }
|
||||
}
|
||||
state.summary?.let { summary -> ActivityStrip(summary, onActivity) }
|
||||
// A server without the activity panel: its jobs frame, one chip each, as before.
|
||||
if (state.summary == null && live != null && live.jobs.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
live.jobs.forEach { job ->
|
||||
AssistChip(onClick = {
|
||||
}, label = { Text("${job.id} · ${job.description.ifBlank { job.command }} · ${job.state}", maxLines = 1) })
|
||||
}
|
||||
}
|
||||
}
|
||||
// The 3.4.0 progress line, ticking; the free status text from an older server.
|
||||
if (live != null) {
|
||||
ProgressStatus(
|
||||
live.progress,
|
||||
live.status,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
// A new value each tap, so the same suggestion twice still fills the field.
|
||||
androidx.compose.runtime.key(suggested) {
|
||||
Composer(state, actions, agent, onTune = { tuning = true }, initial = suggestion)
|
||||
}
|
||||
}
|
||||
if (live != null && live.status.isNotBlank()) {
|
||||
Text(live.status, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(horizontal = 16.dp))
|
||||
}
|
||||
Composer(model, state)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (state.more) {
|
||||
item { TextButton(onClick = model::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
if (rows.isEmpty() && !state.loading) {
|
||||
item {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 96.dp), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.empty_chat), color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> Column {
|
||||
UserBubble(message)
|
||||
if (!message.machine && live == null) {
|
||||
TextButton(onClick = { editing = message }, modifier = Modifier.align(Alignment.End)) {
|
||||
Text(stringResource(R.string.edit))
|
||||
}
|
||||
}
|
||||
Greeting(
|
||||
state,
|
||||
agent,
|
||||
onTune = { tuning = true },
|
||||
onKind = onKind.takeIf { chat == null },
|
||||
onRecheck = actions::recheckDevices,
|
||||
modifier = Modifier.padding(padding),
|
||||
)
|
||||
} else {
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp),
|
||||
) {
|
||||
if (state.more) {
|
||||
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
when {
|
||||
message.isUser -> UserMessage(message, canEdit = !message.machine && live == null, onEdit = { editing = message })
|
||||
|
||||
live != null && live.messageId == message.id && live.finished == null -> Column {
|
||||
Steps(live.shown)
|
||||
if (live.shown.isEmpty()) Text(stringResource(R.string.loading_line), color = palette.inkFaint)
|
||||
live.metrics?.let { m -> ReplyFoot(message.copy(metrics = m)) }
|
||||
}
|
||||
live != null && live.messageId == message.id && live.finished == null ->
|
||||
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
|
||||
|
||||
else -> Column {
|
||||
Steps(message.steps)
|
||||
ReplyFoot(message)
|
||||
if (live == null && message == rows.lastOrNull()) {
|
||||
Row {
|
||||
TextButton(onClick = { model.regenerate(message) }) { Text(stringResource(R.string.regenerate)) }
|
||||
}
|
||||
else -> AssistantMessage(
|
||||
message,
|
||||
message.steps,
|
||||
writing = false,
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -221,21 +355,48 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
|
||||
}
|
||||
}
|
||||
|
||||
if (picking) {
|
||||
ModalBottomSheet(onDismissRequest = { picking = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
ModelPickerContent(state.models, state.modelId, onPick = { id ->
|
||||
picking = false
|
||||
if (chat == null) actions.updateDraft { it.copy(model = id) } else actions.change("model", id)
|
||||
})
|
||||
}
|
||||
}
|
||||
if (tuning) {
|
||||
ModalBottomSheet(onDismissRequest = { tuning = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
TuneContent(state, actions, agent)
|
||||
}
|
||||
}
|
||||
|
||||
// A card the reply is waiting on, as a sheet over the chat. One at a time, in the order asked.
|
||||
live?.cards?.firstOrNull()?.let { card ->
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = {},
|
||||
// Not dismissable by a swipe: the reply is stopped until the card is answered, and
|
||||
// a card swiped away would leave it waiting with nothing on screen to say why.
|
||||
sheetState = rememberModalBottomSheetState(
|
||||
skipPartiallyExpanded = true,
|
||||
confirmValueChange = { it != SheetValue.Hidden },
|
||||
),
|
||||
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true, confirmValueChange = { it != SheetValue.Hidden }),
|
||||
) {
|
||||
CardSheet(card) { answer -> model.answer(card, answer) }
|
||||
CardSheet(card) { answer -> actions.answer(card, answer) }
|
||||
}
|
||||
}
|
||||
|
||||
if (renaming) {
|
||||
var title by remember { mutableStateOf(chat?.title.orEmpty()) }
|
||||
AlertDialog(
|
||||
onDismissRequest = { renaming = false },
|
||||
title = { Text(stringResource(R.string.rename_chat)) },
|
||||
text = { OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true, modifier = Modifier.fillMaxWidth()) },
|
||||
confirmButton = {
|
||||
TextButton(enabled = title.isNotBlank(), onClick = {
|
||||
actions.rename(title)
|
||||
renaming = false
|
||||
}) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { renaming = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
@@ -244,7 +405,7 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
|
||||
text = { OutlinedTextField(value = text, onValueChange = { text = it }, modifier = Modifier.fillMaxWidth()) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
model.edit(message, text)
|
||||
actions.edit(message, text)
|
||||
editing = null
|
||||
}) { Text(stringResource(R.string.card_send)) }
|
||||
},
|
||||
@@ -253,135 +414,197 @@ fun ChatScreen(chatId: String?, onBack: () -> Unit, onOpened: (String) -> Unit =
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
@Composable
|
||||
private fun Composer(model: ChatViewModel, state: ChatState) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var text by rememberSaveable { mutableStateOf("") }
|
||||
var chosenModel by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var planMode by rememberSaveable { mutableStateOf(false) }
|
||||
var listening by remember { mutableStateOf(false) }
|
||||
val recorder = remember { Recorder(scope) }
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { model.attach(it) }
|
||||
val askMic = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
}
|
||||
}
|
||||
val chat = state.chat
|
||||
val current = chat?.model ?: chosenModel ?: state.models.firstOrNull { it.default }?.id
|
||||
val running = state.live != null && state.live.finished == null
|
||||
private fun MenuItem(icon: androidx.compose.ui.graphics.vector.ImageVector, text: String, onClick: () -> Unit) {
|
||||
DropdownMenuItem(leadingIcon = { Icon(icon, contentDescription = null) }, text = { Text(text) }, onClick = onClick)
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(8.dp)) {
|
||||
if (state.pending.isNotEmpty()) {
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
state.pending.forEach { a ->
|
||||
InputChip(
|
||||
selected = false,
|
||||
onClick = { model.unattach(a) },
|
||||
label = { Text(a.name, maxLines = 1) },
|
||||
trailingIcon = { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.remove)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
/** To the very end of the transcript: the last row, then down to its foot however tall it is. */
|
||||
private suspend fun LazyListState.toEnd() {
|
||||
val last = layoutInfo.totalItemsCount - 1
|
||||
if (last < 0) return
|
||||
scrollToItem(last)
|
||||
scrollBy(1_000_000f)
|
||||
}
|
||||
|
||||
/**
|
||||
* A new chat's empty page: what kind of chat it is ([onKind], Chat or Agent, one line each), then
|
||||
* the model's picture and a greeting. A new agent chat says where it will run instead, and that
|
||||
* line opens the tune sheet where the device and folder are chosen -- or, with no computer
|
||||
* linked, how to link one: an agent chat runs on a linked LLeMbas CLI and nowhere else.
|
||||
*/
|
||||
@Composable
|
||||
private fun Greeting(
|
||||
state: ChatState,
|
||||
agent: Boolean,
|
||||
onTune: () -> Unit,
|
||||
onKind: ((Boolean) -> Unit)?,
|
||||
onRecheck: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
if (agent && state.devices.isEmpty() && !state.loading) {
|
||||
Column(modifier.fillMaxSize()) {
|
||||
if (onKind != null) KindChoice(agent, onKind, Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
|
||||
LinkComputer(state.instanceBase, onRecheck, Modifier.weight(1f))
|
||||
}
|
||||
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
ModelChip(state.models, current) { id ->
|
||||
if (chat == null) chosenModel = id else model.change("model", id)
|
||||
}
|
||||
val efforts = state.models.firstOrNull { it.id == current }?.efforts.orEmpty()
|
||||
if (efforts.isNotEmpty()) {
|
||||
EffortChip(efforts, chat?.effort) { model.change("effort", it ?: "off") }
|
||||
}
|
||||
if (chat == null || !chat.isAgent) {
|
||||
FilterChip(
|
||||
selected = if (chat == null) planMode else chat.mode == "plan",
|
||||
onClick = {
|
||||
if (chat == null) planMode = !planMode else model.change("mode", if (chat.mode == "plan") "" else "plan")
|
||||
},
|
||||
label = { Text(stringResource(R.string.mode_plan)) },
|
||||
)
|
||||
} else {
|
||||
AssistChip(onClick = {}, label = { Text(chat.mode.replaceFirstChar { it.uppercase() }) })
|
||||
}
|
||||
}
|
||||
Row(verticalAlignment = Alignment.Bottom) {
|
||||
IconButton(onClick = { pick.launch("*/*") }) {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = stringResource(R.string.attach))
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
placeholder = { Text(stringResource(if (listening) R.string.listening else R.string.composer_hint)) },
|
||||
modifier = Modifier.weight(1f).heightIn(max = 200.dp),
|
||||
)
|
||||
IconButton(onClick = {
|
||||
if (listening) {
|
||||
listening = false
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
if (wav.isNotEmpty()) {
|
||||
runCatching { context.lembas.instances.client()?.transcribe(wav) }
|
||||
.onSuccess { heard -> if (!heard.isNullOrBlank()) text = (text + " " + heard).trim() }
|
||||
}
|
||||
return
|
||||
}
|
||||
// One scroll for the choice and the greeting, so a small phone at large type still reaches
|
||||
// both; on a tall one the greeting sits in the middle of what is left.
|
||||
BoxWithConstraints(modifier.fillMaxSize()) {
|
||||
val room = maxHeight
|
||||
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
|
||||
if (onKind != null) KindChoice(agent, onKind, Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
|
||||
Column(
|
||||
Modifier.fillMaxWidth().heightIn(min = room * 0.6f).padding(horizontal = 32.dp, vertical = 16.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
if (agent) {
|
||||
Box(Modifier.size(64.dp).background(palette.accentSoft, RoundedCornerShape(20.dp)), contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.Filled.Terminal, contentDescription = null, tint = palette.accent, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
recorder.start()
|
||||
listening = true
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(stringResource(R.string.agent_greeting), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
val device = state.device
|
||||
val where = when {
|
||||
device == null -> stringResource(R.string.agent_no_device)
|
||||
|
||||
else -> stringResource(
|
||||
R.string.agent_runs_on,
|
||||
device.name.ifBlank { device.host },
|
||||
state.draft.directory.ifBlank { stringResource(R.string.agent_directory_default) },
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onTune) { Text(where, textAlign = TextAlign.Center, color = palette.inkMuted) }
|
||||
} else {
|
||||
askMic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 64.dp)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(stringResource(R.string.empty_chat), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
|
||||
}
|
||||
}) {
|
||||
Icon(if (listening) Icons.Filled.Stop else Icons.Filled.Mic, contentDescription = stringResource(R.string.dictate))
|
||||
}
|
||||
if (running && text.isBlank()) {
|
||||
IconButton(onClick = model::stop) { Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop)) }
|
||||
} else {
|
||||
IconButton(
|
||||
enabled = text.isNotBlank() || state.pending.isNotEmpty(),
|
||||
onClick = {
|
||||
model.send(text, model = chosenModel, mode = if (planMode) "plan" else null)
|
||||
text = ""
|
||||
},
|
||||
) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Chat or Agent, for a chat not made yet: two cards side by side, one line each, on a shared
|
||||
* track -- both as tall as the taller, whatever either says in which language.
|
||||
*/
|
||||
@Composable
|
||||
private fun ModelChip(models: List<ModelInfo>, current: String?, onPick: (String) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(models.firstOrNull { it.id == current }?.name ?: current ?: "—", maxLines = 1) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
models.forEach { m ->
|
||||
DropdownMenuItem(text = { Text(m.name) }, onClick = {
|
||||
open = false
|
||||
onPick(m.id)
|
||||
})
|
||||
}
|
||||
fun KindChoice(agent: Boolean, onKind: (Boolean) -> Unit, modifier: Modifier = Modifier) {
|
||||
Row(modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
KindCard(Icons.Filled.ChatBubbleOutline, stringResource(R.string.kind_chat), stringResource(R.string.kind_chat_line), !agent, Modifier.weight(1f)) {
|
||||
onKind(false)
|
||||
}
|
||||
KindCard(Icons.Filled.Terminal, stringResource(R.string.kind_agent), stringResource(R.string.kind_agent_line), agent, Modifier.weight(1f)) {
|
||||
onKind(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EffortChip(efforts: List<String>, current: String?, onPick: (String?) -> Unit) {
|
||||
var open by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
AssistChip(onClick = { open = true }, label = { Text(current ?: stringResource(R.string.effort_off)) })
|
||||
DropdownMenu(expanded = open, onDismissRequest = { open = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(R.string.effort_off)) }, onClick = {
|
||||
open = false
|
||||
onPick(null)
|
||||
})
|
||||
efforts.forEach { e ->
|
||||
DropdownMenuItem(text = { Text(e) }, onClick = {
|
||||
open = false
|
||||
onPick(e)
|
||||
})
|
||||
private fun KindCard(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
title: String,
|
||||
line: String,
|
||||
selected: Boolean,
|
||||
modifier: Modifier,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
selected = selected,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (selected) palette.accentSoft else palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
border = androidx.compose.foundation.BorderStroke(if (selected) 2.dp else 1.dp, if (selected) palette.accent else palette.border),
|
||||
modifier = modifier.fillMaxHeight().heightIn(min = 48.dp),
|
||||
) {
|
||||
Column(Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(icon, contentDescription = null, tint = if (selected) palette.accent else palette.inkMuted, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, maxLines = 2)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat with no computer linked: what an agent chat needs and the three steps to
|
||||
* link one, each command with Copy -- the web page's own steps -- and Check again.
|
||||
*/
|
||||
@Composable
|
||||
private fun LinkComputer(base: String, onRecheck: () -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
Column(modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 16.dp)) {
|
||||
Box(Modifier.size(56.dp).background(palette.accentSoft, RoundedCornerShape(18.dp)), contentAlignment = Alignment.Center) {
|
||||
Icon(Icons.Filled.Computer, contentDescription = null, tint = palette.accent, modifier = Modifier.size(28.dp))
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(stringResource(R.string.agent_link_title), style = MaterialTheme.typography.headlineSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(stringResource(R.string.agent_link_lede), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
val steps = listOf(
|
||||
stringResource(R.string.agent_link_install) to "curl -fsSL $CLI_INSTALL | bash",
|
||||
stringResource(R.string.agent_link_login) to "lembas login ${base.ifBlank { "https://…" }}",
|
||||
stringResource(R.string.agent_link_service) to "remote:\n enabled: true\n roots: [ ~/projects ]\n\nlembas service install",
|
||||
)
|
||||
steps.forEachIndexed { i, (words, code) ->
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Row {
|
||||
Text("${i + 1}.", style = MaterialTheme.typography.bodyMedium, color = palette.accent, modifier = Modifier.width(24.dp))
|
||||
Text(words, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
Spacer(Modifier.height(6.dp))
|
||||
CodeBlock("sh", code)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(stringResource(R.string.agent_link_dials_out), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onRecheck, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.agent_link_check)) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Where the LLeMbas CLI's installer is: the public release, as the web page gives it. */
|
||||
private const val CLI_INSTALL = "https://github.com/LLeMbas/LLeMbas-CLI/releases/latest/download/get.sh"
|
||||
|
||||
/** The empty chat's suggestions: a sideways row of cards, all one height (the tallest's). */
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun Suggestions(onPick: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val all = listOf(
|
||||
R.string.suggest_explain to R.string.suggest_explain_line,
|
||||
R.string.suggest_write to R.string.suggest_write_line,
|
||||
R.string.suggest_plan to R.string.suggest_plan_line,
|
||||
R.string.suggest_check to R.string.suggest_check_line,
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth().height(IntrinsicSize.Max).horizontalScroll(rememberScrollState()).padding(bottom = 10.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
all.forEach { (title, line) ->
|
||||
val t = stringResource(title)
|
||||
val l = stringResource(line)
|
||||
Surface(
|
||||
onClick = { onPick("$t $l") },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
border = androidx.compose.foundation.BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.width(184.dp).fillMaxHeight(),
|
||||
) {
|
||||
Column(Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Text(t, style = MaterialTheme.typography.titleSmall)
|
||||
Text(l, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,21 +2,35 @@ package eu.llembas.android.ui.chat
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.os.SystemClock
|
||||
import android.provider.OpenableColumns
|
||||
import androidx.core.content.FileProvider
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
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
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.Turn
|
||||
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.flow.MutableStateFlow
|
||||
@@ -26,6 +40,7 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.File
|
||||
|
||||
data class ChatState(
|
||||
val chat: Chat? = null,
|
||||
@@ -33,41 +48,191 @@ data class ChatState(
|
||||
val more: Boolean = false,
|
||||
val live: LiveReply? = null,
|
||||
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,
|
||||
val error: String? = null,
|
||||
/** A message that could not be sent, handed back to the composer once. */
|
||||
val unsent: String? = null,
|
||||
/** A card somebody answered elsewhere first: said once, then cleared. */
|
||||
val notice: String? = null,
|
||||
/** The activity panel's facts, once it has been opened; [activityAt] is when they were read. */
|
||||
val activity: Activity? = null,
|
||||
val activityAt: Long = 0,
|
||||
/** The strip's counts, from the events route (or the first read). */
|
||||
val summary: ActivitySummary? = null,
|
||||
/** 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,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 default. */
|
||||
val ChatState.modelId: String?
|
||||
get() = chat?.model?.ifBlank { null } ?: draft.model ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id
|
||||
|
||||
val ChatState.modelInfo: ModelInfo? get() = models.firstOrNull { it.id == 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()
|
||||
|
||||
/**
|
||||
* 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() {}
|
||||
fun setAgents(agents: AgentsSetting) {}
|
||||
fun updateDraft(change: (Draft) -> Draft) {}
|
||||
fun attach(uris: List<Uri>) {}
|
||||
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 }
|
||||
?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
private fun fail(e: Throwable) {
|
||||
_state.update { it.copy(error = e.message ?: e.javaClass.simpleName, loading = false, uploading = false) }
|
||||
// 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) }
|
||||
}
|
||||
|
||||
fun clearError() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun open(chatId: String?) {
|
||||
override fun clearUnsent() = _state.update { it.copy(unsent = null) }
|
||||
|
||||
override fun updateDraft(change: (Draft) -> Draft) {
|
||||
val before = _state.value.device?.id
|
||||
_state.update { it.copy(draft = change(it.draft)) }
|
||||
if (agentChat && _state.value.chat == null && _state.value.device?.id != before) readAgentFacts()
|
||||
}
|
||||
|
||||
/** A new agent chat's Subagents fact, for the device chosen now; an older server says nothing. */
|
||||
private fun readAgentFacts() {
|
||||
val device = _state.value.device?.id
|
||||
viewModelScope.launch {
|
||||
val facts = runCatching { api().agentModelList(device) }.getOrNull()?.agentSubagents
|
||||
_state.update { if (it.device?.id == device) it.copy(agentSubagents = facts) else it }
|
||||
}
|
||||
}
|
||||
|
||||
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) }
|
||||
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) {
|
||||
_state.update { it.copy(models = models, loading = false) }
|
||||
val devices = if (agent) client.devices() else emptyList()
|
||||
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)
|
||||
@@ -75,13 +240,30 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
it.copy(chat = detail.chat, messages = detail.messages, more = detail.more, models = models, loading = false)
|
||||
}
|
||||
detail.live?.let { follow(it) }
|
||||
// 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.subagentsOffered ?: a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun older() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val first = _state.value.messages.firstOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
@@ -99,10 +281,21 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_state.update { it.copy(live = LiveReply(messageId)) }
|
||||
try {
|
||||
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
|
||||
_state.update { s -> s.copy(live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)) }
|
||||
_state.update { s ->
|
||||
val live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
|
||||
// The tree outlives the reply: kept for the activity sheet once it ends.
|
||||
s.copy(live = live, tree = live.tree ?: s.tree)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
// The reply goes on on the server; what it has written so far is read back
|
||||
// rather than left half-drawn.
|
||||
_state.update { it.copy(live = null) }
|
||||
refresh()
|
||||
return@launch
|
||||
}
|
||||
val ended = _state.value.live
|
||||
_state.update { s ->
|
||||
@@ -136,54 +329,86 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
turn.reply?.let { follow(it.id) }
|
||||
}
|
||||
|
||||
fun send(text: String, model: String? = null, mode: String? = null, effort: String? = null, temporary: Boolean = false) {
|
||||
val files = _state.value.pending.map { it.id }
|
||||
/**
|
||||
* 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, files, model = model, temporary = temporary, effort = effort, mode = mode)
|
||||
val made = client.createChat(
|
||||
text,
|
||||
files,
|
||||
model = model,
|
||||
temporary = temporary,
|
||||
effort = effort,
|
||||
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)) }
|
||||
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, 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) {
|
||||
@@ -195,17 +420,118 @@ 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) }
|
||||
// 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.subagentsOffered ?: r.teamOffered) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The team's size, both ends; the server refuses a pair outside its bounds in its words. */
|
||||
override fun setAgents(agents: AgentsSetting) = control { api, chat ->
|
||||
val updated = api.setAgents(chat.id, agents)
|
||||
_state.update { it.copy(chat = updated) }
|
||||
}
|
||||
|
||||
fun delete(then: () -> Unit) = control { api, chat ->
|
||||
// --- The activity panel ------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Follow the chat's activity while the screen is in front: the events route says when
|
||||
* anything changed, with the strip's counts; an open panel then reads the whole of it
|
||||
* again. Runs until cancelled. A server without the route (or one that refuses it) leaves
|
||||
* the strip to the first read and an open panel to polling.
|
||||
*/
|
||||
suspend fun watchActivity() {
|
||||
val chat = _state.value.chat ?: return
|
||||
val client = runCatching { api() }.getOrNull() ?: return
|
||||
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.subagentsOffered ?: a.teamOffered, summary = a.summary) }
|
||||
}
|
||||
}
|
||||
try {
|
||||
StreamClient(client).watch { client.activityEvents(chat.id) }.collect { frame ->
|
||||
if (frame.event != "activity") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(ActivityFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
val changed = read.version != _state.value.activity?.version
|
||||
_state.update { it.copy(summary = read.summary, activityLive = true) }
|
||||
if (changed && panelOpen) loadActivity()
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the strip and the panel do without the route.
|
||||
} finally {
|
||||
_state.update { it.copy(activityLive = false) }
|
||||
}
|
||||
}
|
||||
|
||||
private var panelOpen = false
|
||||
|
||||
fun panel(open: Boolean) {
|
||||
panelOpen = open
|
||||
if (open) loadActivity()
|
||||
}
|
||||
|
||||
/** Read the panel's facts; [context] false keeps the last count (the costly part). */
|
||||
fun loadActivity(context: Boolean = true) {
|
||||
val chat = _state.value.chat ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val read = api().activity(chat.id, context)
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
activity = if (context) read else read.copy(context = s.activity?.context),
|
||||
activityAt = SystemClock.elapsedRealtime(),
|
||||
summary = read.summary,
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop a background agent (and, for a member, those under it), then read the panel again. */
|
||||
fun stopAgent(agent: ActivityAgent) = control { api, chat ->
|
||||
api.stopAgent(chat.id, agent.kind, agent.id)
|
||||
loadActivity(context = false)
|
||||
}
|
||||
|
||||
/** 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>) {
|
||||
override fun attach(uris: List<Uri>) {
|
||||
if (uris.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(uploading = true) }
|
||||
@@ -221,6 +547,8 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val mime = resolver.getType(uri) ?: "application/octet-stream"
|
||||
val stored = api().upload(name, mime, bytes, _state.value.chat?.id)
|
||||
_state.update { it.copy(pending = it.pending + stored) }
|
||||
// A photo the camera took for this message is the server's now.
|
||||
if (uri.authority == photoAuthority) runCatching { resolver.delete(uri, null, null) }
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
fail(e)
|
||||
@@ -229,7 +557,20 @@ class ChatViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
fun unattach(attachment: Attachment) {
|
||||
private val photoAuthority get() = "${getApplication<Application>().packageName}.files"
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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)
|
||||
}
|
||||
|
||||
override fun unattach(attachment: Attachment) {
|
||||
_state.update { s -> s.copy(pending = s.pending.filterNot { it.id == attachment.id }) }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,681 @@
|
||||
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.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Brush
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
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.OutlinedTextField
|
||||
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.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.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 }
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 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) {
|
||||
var typed by remember { mutableStateOf(state.draft.directory) }
|
||||
androidx.compose.material3.AlertDialog(
|
||||
onDismissRequest = { askDirectory = false },
|
||||
title = { Text(stringResource(R.string.agent_directory)) },
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = typed,
|
||||
onValueChange = { typed = it },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.agent_directory_hint)) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
androidx.compose.material3.TextButton(onClick = {
|
||||
actions.updateDraft { it.copy(directory = typed.trim()) }
|
||||
askDirectory = false
|
||||
}) { Text(stringResource(R.string.save)) }
|
||||
},
|
||||
dismissButton = { androidx.compose.material3.TextButton(onClick = { askDirectory = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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,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,136 @@
|
||||
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.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)) {
|
||||
items(models, key = { it.id }) { m ->
|
||||
val chosen = m.id == current
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(m.id) }
|
||||
.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.name.ifBlank { m.id }, 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,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,584 @@
|
||||
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.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.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.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.Segment
|
||||
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),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
message.error?.let {
|
||||
Text(it, color = palette.danger, 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 =
|
||||
message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() }
|
||||
|
||||
/** 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) {
|
||||
"thinking" -> ThinkingChip(step)
|
||||
"text" -> RichMarkdown(step.markdown.orEmpty(), onLongPress = onLongPress)
|
||||
"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) {
|
||||
val segments = remember(markdown) { splitFences(markdown) }
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
Text(
|
||||
code,
|
||||
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
|
||||
var open by rememberSaveable(step.index, step.open) { 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,214 +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.Settings
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.PrimaryTabRow
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SwipeToDismissBox
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
|
||||
import androidx.compose.material3.rememberSwipeToDismissBoxState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
|
||||
data class ChatsState(val chats: List<Chat> = emptyList(), val more: Boolean = false, val loading: Boolean = false, val error: String? = null)
|
||||
|
||||
class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ChatsState())
|
||||
val state = _state.asStateFlow()
|
||||
private var kind = "chat"
|
||||
|
||||
fun load(kind: String) {
|
||||
this.kind = kind
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client() ?: return@launch
|
||||
val page = api.chats(kind = kind, before = last.id)
|
||||
_state.update { it.copy(chats = it.chats + page.chats, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = e.message) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Out of the way, and reversible: the web UI's Archive. */
|
||||
fun archive(chat: Chat) {
|
||||
_state.update { s -> s.copy(chats = s.chats.filterNot { it.id == chat.id }) }
|
||||
viewModelScope.launch {
|
||||
runCatching {
|
||||
getApplication<Application>().lembas.instances.client()
|
||||
?.updateChat(chat.id, buildJsonObject { put("archived", true) })
|
||||
}.onFailure { e ->
|
||||
_state.update { it.copy(error = e.message) }
|
||||
load(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun ChatsScreen(onOpen: (String) -> Unit, onNew: () -> Unit, onSettings: () -> Unit, model: ChatsViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
val kind = if (tab == 0) "chat" else "agent"
|
||||
LaunchedEffect(kind) { model.load(kind) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.app_name)) },
|
||||
actions = {
|
||||
IconButton(onClick = onSettings) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = stringResource(R.string.settings))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (tab == 0) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNew,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.new_chat)) },
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
PrimaryTabRow(selectedTabIndex = tab) {
|
||||
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.tab_chats)) })
|
||||
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.tab_agents)) })
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.load(kind) }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.chats.isEmpty() && !state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(if (tab == 0) R.string.empty_chats else R.string.empty_agents),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.chats, key = { it.id }) { chat ->
|
||||
ChatRow(chat, onOpen = { onOpen(chat.id) }, onArchive = { model.archive(chat) })
|
||||
HorizontalDivider()
|
||||
}
|
||||
if (state.more) {
|
||||
item {
|
||||
LaunchedEffect(state.chats.size) { model.more() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ChatRow(chat: Chat, onOpen: () -> Unit, onArchive: () -> Unit) {
|
||||
val swipe = rememberSwipeToDismissBoxState()
|
||||
SwipeToDismissBox(state = swipe, onDismiss = { onArchive() }, backgroundContent = {
|
||||
Box(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surfaceContainerHigh).padding(horizontal = 24.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
Text(stringResource(R.string.archive), color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}) {
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (chat.isAgent) Icons.Filled.Terminal else Icons.AutoMirrored.Filled.Chat,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(chat.title.ifBlank { stringResource(R.string.new_chat) }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val line = listOfNotNull(chat.model.ifBlank { null }, chat.device?.directory?.ifBlank { null }).joinToString(" · ")
|
||||
if (line.isNotEmpty()) Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
if (chat.unread || chat.running) {
|
||||
Box(
|
||||
Modifier.size(10.dp).clip(CircleShape).background(
|
||||
if (chat.running) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.primary,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.text.format.Formatter
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
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.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
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.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.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.FileEntry
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.TreeFileViewer
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** One directory of the person's tree, and whether it is on its way. */
|
||||
data class FilesState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* The person's files, read-only: `GET /api/v2/files` as the explorer's listing. The tree is read
|
||||
* as the person, with no chat -- their own access, the same the web UI's explorer draws by.
|
||||
*/
|
||||
class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(FilesState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
private var loading: Job? = null
|
||||
|
||||
/**
|
||||
* Opens a directory. A refusal (a path no longer readable, the server unreachable) keeps the
|
||||
* directory already shown and says why above it, so the way back is never lost.
|
||||
*/
|
||||
fun open(path: String) {
|
||||
loading?.cancel()
|
||||
loading = viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().lembas.instances.client()
|
||||
if (api == null) {
|
||||
_state.update { it.copy(loading = false) }
|
||||
return@launch
|
||||
}
|
||||
val listing = api.files(path)
|
||||
_state.value = FilesState(path = listing.path, parent = listing.parent, entries = listing.entries)
|
||||
} catch (e: Exception) {
|
||||
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun reload() = open(_state.value.path)
|
||||
|
||||
fun up(): Boolean {
|
||||
val parent = _state.value.parent ?: return false
|
||||
open(parent)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
var viewing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(state.path) }
|
||||
|
||||
// Back goes up one directory first, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.parent != null) { model.up() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { if (!model.up()) onBack() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.files), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
if (state.parent == null) stringResource(R.string.files_all) else state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = if (state.parent == null) null else FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let {
|
||||
Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
}
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = { model.reload() }, modifier = Modifier.fillMaxSize()) {
|
||||
if (state.entries.isEmpty() && !state.loading && state.error == null) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
stringResource(R.string.files_empty),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(32.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.entries, key = { it.path }) { entry ->
|
||||
EntryRow(entry) { if (entry.isFolder) model.open(entry.path) else viewing = entry.path }
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable(onClick = onOpen),
|
||||
leadingContent = {
|
||||
Icon(
|
||||
when (entry.kind) {
|
||||
"mount" -> Icons.Filled.FolderShared
|
||||
"dir" -> Icons.Filled.Folder
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(entry.name.ifBlank { entry.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (entry.isFolder) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
val line = listOfNotNull(Formatter.formatShortFileSize(context, entry.size), entry.mime.ifBlank { null }).joinToString(" · ")
|
||||
Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -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,692 @@
|
||||
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.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.Chat
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
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.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 = "",
|
||||
)
|
||||
|
||||
/** 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 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)
|
||||
_state.value = ChatsState(chats = page.chats, more = page.more, folders = folders)
|
||||
} 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(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 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) }
|
||||
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, 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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,149 @@
|
||||
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,
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = {}) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,916 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.scheduled
|
||||
|
||||
import android.app.Application
|
||||
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.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.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.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
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.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Computer
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
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.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
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 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.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.RunsOn
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.ScheduleCompiled
|
||||
import eu.llembas.android.api.ScheduleRun
|
||||
import eu.llembas.android.api.SchedulesFrame
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.computerAway
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** A server without the scheduling routes answers 404 (or 405): it is older, not broken. */
|
||||
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
|
||||
|
||||
private suspend fun Application.api(): ApiClient = lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
|
||||
|
||||
// --- The list --------------------------------------------------------------------------------
|
||||
|
||||
data class ScheduledState(
|
||||
val schedules: List<Schedule> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
val unsupported: Boolean = false,
|
||||
)
|
||||
|
||||
class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ScheduledState())
|
||||
val state = _state.asStateFlow()
|
||||
|
||||
private var live: Job? = null
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
_state.value = ScheduledState(schedules = getApplication<Application>().api().schedules())
|
||||
watch()
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
if (e.unsupported()) {
|
||||
it.copy(
|
||||
loading = false,
|
||||
unsupported = true,
|
||||
)
|
||||
} else {
|
||||
it.copy(loading = false, error = getApplication<Application>().explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The person's events route while the list is on screen: the whole list again whenever it
|
||||
* changes (a run starting, waiting or finishing, a schedule made or paused elsewhere).
|
||||
* Without it the list is what the last read said, and a pull reads it again.
|
||||
*/
|
||||
private fun watch() {
|
||||
if (live?.isActive == true) return
|
||||
live = viewModelScope.launch {
|
||||
val client = runCatching { getApplication<Application>().api() }.getOrNull() ?: return@launch
|
||||
try {
|
||||
StreamClient(client).watch { client.events() }.collect { frame ->
|
||||
if (frame.event != "schedules") return@collect
|
||||
val read = runCatching { LembasJson.decodeFromString(SchedulesFrame.serializer(), frame.data) }.getOrNull() ?: return@collect
|
||||
_state.update { it.copy(schedules = read.schedules) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// An older server, or the stream refused: the list stays as last read.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
|
||||
/** Pause or resume; the switch moves at once and comes back if the server says no. */
|
||||
fun pause(schedule: Schedule, paused: Boolean) {
|
||||
_state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == schedule.id) it.copy(enabled = !paused) else it }) }
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
val saved = getApplication<Application>().api().pauseSchedule(schedule.id, paused)
|
||||
_state.update { s -> s.copy(schedules = s.schedules.map { if (it.id == saved.id) saved else it }) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { s ->
|
||||
s.copy(
|
||||
schedules = s.schedules.map { if (it.id == schedule.id) schedule else it },
|
||||
error = getApplication<Application>().explain(e),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
onPauseOrDispose { model.stop() }
|
||||
}
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scheduled tasks: one card each, with the rule in words, the last run's status and the next
|
||||
* run, and a switch that pauses it. The card's words give; the switch keeps its size.
|
||||
*/
|
||||
@Composable
|
||||
fun ScheduledContent(
|
||||
state: ScheduledState,
|
||||
onBack: () -> Unit = {},
|
||||
onOpen: (String) -> Unit = {},
|
||||
onNew: () -> Unit = {},
|
||||
onModels: () -> Unit = {},
|
||||
onPause: (Schedule, Boolean) -> Unit = { _, _ -> },
|
||||
onRetry: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
BackBar(stringResource(R.string.scheduled), onBack) {
|
||||
if (!state.unsupported) {
|
||||
IconButton(onClick = onModels) { Icon(Icons.Filled.Tune, contentDescription = stringResource(R.string.schedule_models)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
floatingActionButton = {
|
||||
if (!state.unsupported) {
|
||||
ExtendedFloatingActionButton(
|
||||
onClick = onNew,
|
||||
icon = { Icon(Icons.Filled.Add, contentDescription = null) },
|
||||
text = { Text(stringResource(R.string.schedule_new)) },
|
||||
containerColor = palette.accent,
|
||||
contentColor = palette.accentInk,
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = onRetry, modifier = Modifier.fillMaxSize().padding(padding)) {
|
||||
when {
|
||||
state.unsupported -> Message(stringResource(R.string.scheduled_unsupported))
|
||||
|
||||
state.schedules.isEmpty() && state.error != null -> Message(state.error, retry = onRetry)
|
||||
|
||||
state.schedules.isEmpty() && !state.loading -> Message(stringResource(R.string.scheduled_empty))
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 96.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } }
|
||||
items(state.schedules, key = { it.id }) { s -> ScheduleCard(s, onOpen = { onOpen(s.id) }, onPause = { onPause(s, it) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScheduleCard(schedule: Schedule, onOpen: () -> Unit, onPause: (Boolean) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.padding(start = 16.dp, end = 12.dp, top = 14.dp, bottom = 14.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
schedule.title.ifBlank { schedule.instruction },
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
schedule.description?.takeIf { it.isNotBlank() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp)) {
|
||||
val shown = if (schedule.running) "running" else schedule.lastRun?.status
|
||||
shown?.let { StatusChip(it, schedule.lastRun?.missed ?: 0, schedule.lastRun?.waitingFor) }
|
||||
val next = when {
|
||||
schedule.paused -> stringResource(R.string.schedule_paused)
|
||||
else -> ScheduleLogic.moment(schedule.nextRun)?.let { stringResource(R.string.schedule_next, it) }
|
||||
}
|
||||
next?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(start = if (shown != null) 8.dp else 0.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Switch(checked = !schedule.paused, onCheckedChange = { on -> onPause(!on) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A run's status in words, on its tone's soft colour. */
|
||||
@Composable
|
||||
fun StatusChip(status: String, missed: Int = 0, waitingFor: String? = null) {
|
||||
val palette = LocalPalette.current
|
||||
val (ink, soft) = toneColours(palette, ScheduleLogic.tone(status))
|
||||
val words = when (status) {
|
||||
"ok" -> stringResource(R.string.run_ok)
|
||||
"silent" -> stringResource(R.string.run_silent)
|
||||
"unchanged" -> stringResource(R.string.run_unchanged)
|
||||
"failed" -> stringResource(R.string.run_failed)
|
||||
"missed" -> stringResource(R.string.run_missed, maxOf(missed, 1).toString())
|
||||
"skipped" -> stringResource(R.string.run_skipped)
|
||||
"waiting" -> stringResource(if (waitingFor == "device") R.string.run_waiting_computer else R.string.run_waiting)
|
||||
"running" -> stringResource(R.string.run_running)
|
||||
else -> status
|
||||
}
|
||||
Box(Modifier.background(soft, RoundedCornerShape(8.dp)).padding(horizontal = 8.dp, vertical = 3.dp)) {
|
||||
Text(words, style = MaterialTheme.typography.labelMedium, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
private fun toneColours(palette: Palette, tone: Tone): Pair<Color, Color> = when (tone) {
|
||||
Tone.Good -> palette.success to palette.successSoft
|
||||
Tone.Bad -> palette.danger to palette.dangerSoft
|
||||
Tone.Waiting -> palette.warning to palette.warningSoft
|
||||
Tone.Quiet, Tone.Neutral -> palette.inkMuted to palette.surfaceActive
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun BackBar(title: String, onBack: () -> Unit, actions: @Composable () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) } },
|
||||
actions = { actions() },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Message(text: String, retry: (() -> Unit)? = null) {
|
||||
val palette = LocalPalette.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(32.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(48.dp))
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(text, style = MaterialTheme.typography.bodyLarge, color = palette.inkMuted, textAlign = TextAlign.Center)
|
||||
retry?.let { TextButton(onClick = it) { Text(stringResource(R.string.retry)) } }
|
||||
}
|
||||
}
|
||||
|
||||
// --- One schedule -----------------------------------------------------------------------------
|
||||
|
||||
data class ScheduleState(
|
||||
val schedule: Schedule? = null,
|
||||
val runs: List<ScheduleRun> = emptyList(),
|
||||
val more: Boolean = false,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
)
|
||||
|
||||
class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(ScheduleState())
|
||||
val state = _state.asStateFlow()
|
||||
private var id: String? = null
|
||||
|
||||
fun open(id: String) {
|
||||
this.id = id
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val api = getApplication<Application>().api()
|
||||
val schedule = api.schedule(id)
|
||||
val runs = runCatching { api.scheduleRuns(id) }.getOrNull()
|
||||
_state.update { it.copy(schedule = schedule, runs = runs?.runs.orEmpty(), more = runs?.more == true, loading = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun more() {
|
||||
val schedule = _state.value.schedule ?: return
|
||||
val last = _state.value.runs.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().scheduleRuns(schedule.id, last.id) }
|
||||
.onSuccess { page -> _state.update { it.copy(runs = it.runs + page.runs, more = page.more) } }
|
||||
}
|
||||
}
|
||||
|
||||
fun runNow() = act { api, s ->
|
||||
val run = api.runScheduleNow(s.id)
|
||||
_state.update { st ->
|
||||
st.copy(runs = listOf(run) + st.runs.filter { it.id != run.id }, notice = getApplication<Application>().getString(R.string.schedule_started))
|
||||
}
|
||||
}
|
||||
|
||||
fun pause(paused: Boolean) = act { api, s -> _state.update { it.copy(schedule = api.pauseSchedule(s.id, paused)) } }
|
||||
|
||||
fun delete(then: () -> Unit) = act { api, s ->
|
||||
api.deleteSchedule(s.id)
|
||||
then()
|
||||
}
|
||||
|
||||
fun clear() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
private fun act(block: suspend (ApiClient, Schedule) -> Unit) {
|
||||
val schedule = _state.value.schedule ?: return
|
||||
viewModelScope.launch {
|
||||
try {
|
||||
block(getApplication<Application>().api(), schedule)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ScheduleScreen(
|
||||
id: String,
|
||||
onBack: () -> Unit,
|
||||
onEdit: (String) -> Unit,
|
||||
onOpenRun: (String) -> Unit,
|
||||
model: ScheduleViewModel = viewModel(key = "schedule-$id"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val snackbar = remember { SnackbarHostState() }
|
||||
LifecycleResumeEffect(id) {
|
||||
model.open(id)
|
||||
onPauseOrDispose { }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.notice ?: state.error.takeIf { state.schedule != null })?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
model.clear()
|
||||
}
|
||||
}
|
||||
ScheduleContent(
|
||||
state,
|
||||
snackbar = snackbar,
|
||||
onBack = onBack,
|
||||
onEdit = { onEdit(id) },
|
||||
onDelete = { model.delete(onBack) },
|
||||
onRunNow = model::runNow,
|
||||
onPause = model::pause,
|
||||
onOpenRun = { run -> onOpenRun(run.id) },
|
||||
onMore = model::more,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One schedule: what it does and when, Run now and Pause side by side (equal halves), the next
|
||||
* runs, and its history -- each run's status, when, the model that ran it and why, the first
|
||||
* lines of its result; a run opens its result in full.
|
||||
*/
|
||||
@Composable
|
||||
fun ScheduleContent(
|
||||
state: ScheduleState,
|
||||
snackbar: SnackbarHostState = remember { SnackbarHostState() },
|
||||
onBack: () -> Unit = {},
|
||||
onEdit: () -> Unit = {},
|
||||
onDelete: () -> Unit = {},
|
||||
onRunNow: () -> Unit = {},
|
||||
onPause: (Boolean) -> Unit = {},
|
||||
onOpenRun: (ScheduleRun) -> Unit = {},
|
||||
onMore: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val schedule = state.schedule
|
||||
var deleting by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
topBar = {
|
||||
BackBar(schedule?.title?.ifBlank { null } ?: stringResource(R.string.scheduled), onBack) {
|
||||
if (schedule != null) {
|
||||
IconButton(onClick = onEdit) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) }
|
||||
IconButton(onClick = { deleting = true }) { Icon(Icons.Filled.Delete, contentDescription = stringResource(R.string.delete)) }
|
||||
}
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
if (schedule == null) {
|
||||
Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) {
|
||||
if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) }
|
||||
}
|
||||
} else {
|
||||
ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onMore)
|
||||
}
|
||||
}
|
||||
if (deleting) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { deleting = false },
|
||||
title = { Text(stringResource(R.string.schedule_delete_confirm)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
deleting = false
|
||||
onDelete()
|
||||
}) { Text(stringResource(R.string.delete), color = palette.danger) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ScheduleBody(
|
||||
state: ScheduleState,
|
||||
schedule: Schedule,
|
||||
padding: PaddingValues,
|
||||
onRunNow: () -> Unit,
|
||||
onPause: (Boolean) -> Unit,
|
||||
onOpenRun: (ScheduleRun) -> Unit,
|
||||
onMore: () -> Unit,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
LazyColumn(
|
||||
Modifier.fillMaxSize().padding(padding),
|
||||
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
item {
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(schedule.description.orEmpty(), style = MaterialTheme.typography.titleMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium)
|
||||
val facts = listOfNotNull(
|
||||
schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) },
|
||||
modeWords(schedule.mode),
|
||||
notifyWords(schedule.notify),
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(facts.joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
|
||||
}
|
||||
schedule.runsOn?.let { on -> ComputerLine(on, away = schedule.lastRun?.computerAway == true) }
|
||||
schedule.watch?.target?.takeIf { it.isNotBlank() }?.let { url ->
|
||||
Text(
|
||||
stringResource(if (schedule.watch?.kind == "command") R.string.schedule_watching_command else R.string.schedule_watching) + ": " +
|
||||
url,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
FilledTonalButton(onClick = onRunNow, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) {
|
||||
Icon(Icons.Filled.PlayArrow, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.schedule_run_now), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
OutlinedButton(onClick = { onPause(!schedule.paused) }, modifier = Modifier.weight(1f).heightIn(min = 48.dp)) {
|
||||
Icon(if (schedule.paused) Icons.Filled.PlayArrow else Icons.Filled.Pause, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
stringResource(if (schedule.paused) R.string.schedule_resume else R.string.schedule_pause),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val next = ScheduleLogic.upcoming(schedule.nextRuns)
|
||||
if (next.isNotEmpty() && !schedule.paused) {
|
||||
item { Header(stringResource(R.string.schedule_next_runs)) }
|
||||
item {
|
||||
Surface(shape = RoundedCornerShape(16.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 8.dp)) {
|
||||
next.forEach {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item { Header(stringResource(R.string.schedule_history)) }
|
||||
if (state.runs.isEmpty()) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.schedule_no_runs),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }) }
|
||||
if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun notifyWords(notify: String): String? = when (notify) {
|
||||
"always" -> stringResource(R.string.notify_always)
|
||||
"matters" -> stringResource(R.string.notify_matters)
|
||||
"never" -> stringResource(R.string.notify_never)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun modeWords(mode: String): String? = when (mode) {
|
||||
"fresh" -> stringResource(R.string.mode_fresh)
|
||||
"continue" -> stringResource(R.string.mode_continue)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a schedule runs: Computer: its name · the folder there · the mode, and "not linked now"
|
||||
* in the waiting colour when its last run found it away. The folder gives first.
|
||||
*/
|
||||
@Composable
|
||||
private fun ComputerLine(on: RunsOn, away: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Computer, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
val parts = listOfNotNull(
|
||||
stringResource(R.string.schedule_computer) + ": " + on.deviceName.ifBlank { on.device },
|
||||
on.cwd.takeIf { it.isNotBlank() },
|
||||
agentModeWords(on.mode),
|
||||
)
|
||||
Text(parts.joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (away) {
|
||||
Text(
|
||||
on.deviceName.ifBlank { on.device } + ": " + stringResource(R.string.schedule_computer_away),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** A run row's line: the computer's name, and "not linked now" when the run found it away. */
|
||||
@Composable
|
||||
private fun ComputerName(on: RunsOn, away: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Computer, contentDescription = stringResource(R.string.schedule_computer), tint = palette.inkFaint, modifier = Modifier.size(14.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text(
|
||||
on.deviceName.ifBlank {
|
||||
on.device
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (away) {
|
||||
Text(
|
||||
" · " + stringResource(R.string.schedule_computer_away),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun agentModeWords(mode: String): String? = when (mode) {
|
||||
"manual" -> stringResource(R.string.mode_manual)
|
||||
"edit" -> stringResource(R.string.mode_edit)
|
||||
"auto" -> stringResource(R.string.mode_auto)
|
||||
else -> null
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun Header(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = LocalPalette.current.accent,
|
||||
modifier = Modifier.padding(start = 4.dp, top = 16.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A run: its status (a fixed column, so the times line up), when, the model, and the first
|
||||
* lines of its result (model output: plain text, never markup) or why it failed or waits. The
|
||||
* whole row opens the run.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = palette.surfaceRaised,
|
||||
contentColor = palette.ink,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(Modifier.heightIn(min = 64.dp).padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.Top) {
|
||||
Box(Modifier.width(112.dp)) { StatusChip(run.status, run.missed, run.waitingFor) }
|
||||
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(ScheduleLogic.moment(run.startedAt ?: run.dueAt) ?: "—", style = MaterialTheme.typography.bodyMedium)
|
||||
// Which computer the run was for, and whether it was away.
|
||||
runsOn?.let { on -> ComputerName(on, away = run.computerAway) }
|
||||
RunFacts(run, maxLines = 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Under a run's time: the model and why, then the result's first lines, or the trouble. */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
val name = run.model.label
|
||||
val from = run.model.switchedFrom
|
||||
val model = when {
|
||||
name == null -> null
|
||||
run.model.reason == "switched" && from != null -> stringResource(R.string.run_model_instead, name, from)
|
||||
else -> name
|
||||
}
|
||||
model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
// A run under way says what it is doing, in the words every client uses (spec 3.4.0).
|
||||
if (run.status == "waiting" || run.status == "running") {
|
||||
progressLineOf(run.progress)?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
if (run.status == "waiting") {
|
||||
ScheduleLogic.moment(run.retryAt)?.let {
|
||||
Text(stringResource(R.string.run_retry_at, it), style = MaterialTheme.typography.bodySmall, color = palette.warning, maxLines = 1)
|
||||
}
|
||||
}
|
||||
run.error?.text?.takeIf { it.isNotBlank() }?.let {
|
||||
val tone = if (run.status == "waiting") palette.inkMuted else palette.danger
|
||||
Text(it, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (withPreview && run.preview.isNotBlank()) {
|
||||
Text(run.preview, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Create and edit ------------------------------------------------------------------------
|
||||
|
||||
data class EditState(
|
||||
val words: String = "",
|
||||
val compiled: ScheduleCompiled? = null,
|
||||
val compiling: Boolean = false,
|
||||
val saving: Boolean = false,
|
||||
val error: String? = null,
|
||||
val unsupported: Boolean = false,
|
||||
)
|
||||
|
||||
class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(EditState())
|
||||
val state = _state.asStateFlow()
|
||||
private var editing: String? = null
|
||||
private var started = false
|
||||
|
||||
/** Begin: empty for a new schedule, the words a schedule was made from for one being edited. */
|
||||
fun start(id: String?) {
|
||||
if (started) return
|
||||
started = true
|
||||
editing = id
|
||||
if (id == null) return
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
|
||||
_state.update { it.copy(words = s.request.ifBlank { s.instruction }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun words(text: String) = _state.update { it.copy(words = text, compiled = null) }
|
||||
|
||||
/** The server reads the words: the title, the instruction, the rule and the next runs. */
|
||||
fun preview() {
|
||||
val words = _state.value.words.trim()
|
||||
if (words.isEmpty()) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(compiling = true, error = null) }
|
||||
try {
|
||||
val compiled = getApplication<Application>().api().compileSchedule(words)
|
||||
_state.update { it.copy(compiled = compiled, compiling = false) }
|
||||
} catch (e: Exception) {
|
||||
_state.update {
|
||||
it.copy(compiling = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication<Application>().explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun save(then: (String) -> Unit) {
|
||||
val compiled = _state.value.compiled?.takeIf { it.savable } ?: return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(saving = true, error = null) }
|
||||
try {
|
||||
val saved = getApplication<Application>().api().saveSchedule(compiled, _state.value.words.trim(), editing)
|
||||
then(saved.id)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(saving = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ScheduleEditScreen(
|
||||
id: String?,
|
||||
onBack: () -> Unit,
|
||||
onSaved: (String) -> Unit,
|
||||
model: ScheduleEditViewModel = viewModel(key = "schedule-edit-${id ?: "new"}"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(id) { model.start(id) }
|
||||
ScheduleEditContent(state, editing = id != null, onBack = onBack, onWords = model::words, onPreview = model::preview, onSave = { model.save(onSaved) })
|
||||
}
|
||||
|
||||
/**
|
||||
* A schedule in words: the person says when and what, the server reads it, and the preview
|
||||
* shows what it understood -- the title, the rule in words, the instruction, the next five runs
|
||||
* -- before anything is saved. When it could not make out all of it, it says why, and Save
|
||||
* waits for words it can. Save stays at the foot, out of the way of the keyboard.
|
||||
*/
|
||||
@Composable
|
||||
fun ScheduleEditContent(
|
||||
state: EditState,
|
||||
editing: Boolean,
|
||||
onBack: () -> Unit = {},
|
||||
onWords: (String) -> Unit = {},
|
||||
onPreview: () -> Unit = {},
|
||||
onSave: () -> Unit = {},
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = { BackBar(stringResource(if (editing) R.string.schedule_edit else R.string.schedule_new), onBack) },
|
||||
bottomBar = {
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
|
||||
Button(
|
||||
onClick = onSave,
|
||||
enabled = state.compiled?.savable == true && !state.saving,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
OutlinedTextField(
|
||||
value = state.words,
|
||||
onValueChange = onWords,
|
||||
minLines = 3,
|
||||
placeholder = { Text(stringResource(R.string.schedule_words_example)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
FilledTonalButton(
|
||||
onClick = onPreview,
|
||||
enabled = state.words.isNotBlank() && !state.compiling,
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) {
|
||||
if (state.compiling) {
|
||||
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
Text(stringResource(R.string.schedule_preview))
|
||||
}
|
||||
if (state.unsupported) Text(stringResource(R.string.scheduled_unsupported), color = palette.inkMuted)
|
||||
state.error?.let { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) }
|
||||
state.compiled?.let { Understood(it) }
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What the server made of the words. The title and instruction are a model's: plain text. */
|
||||
@Composable
|
||||
private fun Understood(c: ScheduleCompiled) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(stringResource(R.string.schedule_understood), style = MaterialTheme.typography.labelLarge, color = palette.accent)
|
||||
c.reason?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.warning) }
|
||||
if (c.title.isNotBlank()) Text(c.title, style = MaterialTheme.typography.titleMedium)
|
||||
c.description?.takeIf { it.isNotBlank() }?.let { words ->
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Schedule, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(words, style = MaterialTheme.typography.bodyLarge, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
if (c.instruction.isNotBlank()) Text(c.instruction, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
val next = ScheduleLogic.upcoming(c.nextRuns)
|
||||
if (next.isNotEmpty()) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_next_runs),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
next.forEach { Text(it, style = MaterialTheme.typography.bodyMedium) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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, key = { it.id }) { 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,29 +5,55 @@ package eu.llembas.android.ui.settings
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.provider.Settings
|
||||
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.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
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.ArrowBack
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material.icons.automirrored.filled.Logout
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Assistant
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material.icons.filled.Palette
|
||||
import androidx.compose.material.icons.filled.PhoneAndroid
|
||||
import androidx.compose.material.icons.filled.RecordVoiceOver
|
||||
import androidx.compose.material.icons.filled.Science
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material.icons.filled.Timer
|
||||
import androidx.compose.material.icons.filled.Translate
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -37,18 +63,71 @@ import androidx.compose.runtime.rememberCoroutineScope
|
||||
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.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 eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.update.UpdateOffer
|
||||
import eu.llembas.android.update.UpdateResult
|
||||
import eu.llembas.android.update.Updater
|
||||
import eu.llembas.android.update.checksUpdates
|
||||
import eu.llembas.android.update.offersBetas
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
/** What the settings page does; every action has a do-nothing default for the screenshots. */
|
||||
interface SettingsActions {
|
||||
fun use(instance: Instance) {}
|
||||
fun add() {}
|
||||
fun signOut(instance: Instance) {}
|
||||
fun theme(value: String) {}
|
||||
fun language(value: String) {}
|
||||
fun enablePush(instance: Instance) {}
|
||||
fun notificationSettings() {}
|
||||
fun assistantSettings() {}
|
||||
fun assistantTemporary(on: Boolean) {}
|
||||
fun voiceInput(value: String) {}
|
||||
fun assistantListens(on: Boolean) {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
fun installUpdate() {}
|
||||
fun updateCheck(on: Boolean) {}
|
||||
fun updateBetas(on: Boolean) {}
|
||||
}
|
||||
|
||||
/** What the settings page shows. */
|
||||
data class SettingsState(
|
||||
val instances: List<Instance> = emptyList(),
|
||||
val active: Instance? = null,
|
||||
val prefs: Prefs = Prefs(),
|
||||
val hasDistributor: Boolean = false,
|
||||
val pushNote: String? = null,
|
||||
val updateNote: String? = null,
|
||||
/** A newer release the last check found: the row opens its page, the full build can install it. */
|
||||
val updateFound: String? = null,
|
||||
val version: String = "",
|
||||
val selfUpdate: Boolean = false,
|
||||
/** Whether the app itself is a beta: the update settings' defaults follow it. */
|
||||
val beta: Boolean = false,
|
||||
/** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */
|
||||
val phoneRecognizer: Boolean = false,
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -59,10 +138,146 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
|
||||
val beta = remember { AppVersion.parse(BuildConfig.VERSION_NAME)?.isBeta ?: false }
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
val actions = remember {
|
||||
object : SettingsActions {
|
||||
override fun use(instance: Instance) {
|
||||
scope.launch { store.use(instance.id) }
|
||||
}
|
||||
|
||||
override fun add() = onAddInstance()
|
||||
|
||||
override fun signOut(instance: Instance) {
|
||||
scope.launch {
|
||||
Push.disable(context, instance)
|
||||
runCatching { store.clientFor(instance).signOut() }
|
||||
store.remove(instance.id)
|
||||
}
|
||||
}
|
||||
|
||||
override fun theme(value: String) {
|
||||
scope.launch { store.savePrefs { it.copy(theme = value) } }
|
||||
}
|
||||
|
||||
// MainActivity follows the choice: it puts the app in the language at once.
|
||||
override fun language(value: String) {
|
||||
scope.launch { store.savePrefs { it.copy(language = value) } }
|
||||
}
|
||||
|
||||
override fun enablePush(instance: Instance) {
|
||||
(context as? Activity)?.let { activity ->
|
||||
Push.enable(activity, instance) { ok -> pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun notificationSettings() {
|
||||
context.startActivity(
|
||||
Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
|
||||
override fun assistantSettings() {
|
||||
context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
override fun assistantTemporary(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } }
|
||||
}
|
||||
|
||||
override fun voiceInput(value: String) {
|
||||
scope.launch { store.savePrefs { it.copy(voiceInput = value) } }
|
||||
}
|
||||
|
||||
override fun assistantListens(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantListens = on) } }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
|
||||
override fun checkUpdate() {
|
||||
updateNote = context.getString(R.string.update_checking)
|
||||
scope.launch {
|
||||
when (val found = ReleaseCheck(context).check()) {
|
||||
is UpdateResult.Newer -> {
|
||||
updateFound = found.offer
|
||||
updateNote = context.getString(R.string.update_available, found.offer.version.toString())
|
||||
}
|
||||
|
||||
UpdateResult.Current -> {
|
||||
updateFound = null
|
||||
updateNote = context.getString(R.string.update_none)
|
||||
}
|
||||
|
||||
UpdateResult.Unreachable -> updateNote = context.getString(R.string.update_unreachable)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun openRelease() {
|
||||
updateFound?.let { offer -> runCatching { context.startActivity(ReleaseCheck.open(offer.page)) } }
|
||||
}
|
||||
|
||||
// The full build's own installer, for a release (llembas.eu names its APK and hash).
|
||||
override fun installUpdate() {
|
||||
scope.launch { updateNote = Updater(context).checkAndOffer() }
|
||||
}
|
||||
|
||||
override fun updateCheck(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(updateCheck = on) } }
|
||||
}
|
||||
|
||||
override fun updateBetas(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(updateBetas = on) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsContent(
|
||||
SettingsState(
|
||||
instances = instances,
|
||||
active = active,
|
||||
prefs = prefs,
|
||||
hasDistributor = distributors.isNotEmpty(),
|
||||
pushNote = pushNote,
|
||||
updateNote = updateNote,
|
||||
updateFound = updateFound?.version?.toString(),
|
||||
version = BuildConfig.VERSION_NAME,
|
||||
selfUpdate = BuildConfig.SELF_UPDATE,
|
||||
beta = beta,
|
||||
phoneRecognizer = remember { PhoneRecognizer.available(context) },
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings as Material 3 grouped lists: each group a header and one rounded surface of rows,
|
||||
* every row at least 56 dp with its icon, its words (which wrap) and its control (which keeps
|
||||
* its size).
|
||||
*/
|
||||
@Composable
|
||||
fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) {
|
||||
val palette = LocalPalette.current
|
||||
var choosingLanguage by remember { mutableStateOf(false) }
|
||||
if (choosingLanguage) {
|
||||
ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
LanguageChoices(state.prefs, onPick = {
|
||||
choosingLanguage = false
|
||||
actions.language(it)
|
||||
})
|
||||
}
|
||||
}
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
@@ -70,103 +285,348 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Section(stringResource(R.string.settings_instances))
|
||||
instances.forEach { instance ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.use(instance.id) } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = instance.id == active?.id, onClick = { scope.launch { store.use(instance.id) } })
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(instance.name.ifBlank { instance.base })
|
||||
Text(
|
||||
"${instance.email} · ${instance.base}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
LazyColumn(Modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 32.dp)) {
|
||||
item {
|
||||
Group(stringResource(R.string.settings_instances)) {
|
||||
state.instances.forEachIndexed { i, instance ->
|
||||
if (i > 0) Rule()
|
||||
val inUse = instance.id == state.active?.id
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { actions.use(instance) }.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Initial(instance.name.ifBlank { instance.base })
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
instance.name.ifBlank {
|
||||
instance.base
|
||||
},
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
instance.email,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
instance.base,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (inUse) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Icon(Icons.Filled.CheckCircle, contentDescription = stringResource(R.string.instance_in_use), tint = palette.accent)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.instances.isNotEmpty()) Rule()
|
||||
SettingRow(Icons.Filled.Add, stringResource(R.string.add_instance), onClick = actions::add)
|
||||
state.active?.let { current ->
|
||||
Rule()
|
||||
SettingRow(Icons.AutoMirrored.Filled.Logout, stringResource(R.string.sign_out), tint = palette.danger, onClick = {
|
||||
actions.signOut(current)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Group(stringResource(R.string.settings_language)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Translate,
|
||||
languageLabel(state.prefs),
|
||||
subtitle = stringResource(R.string.language_hint),
|
||||
onClick = { choosingLanguage = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
Group(stringResource(R.string.settings_theme)) {
|
||||
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEachIndexed { i, (value, label) ->
|
||||
if (i > 0) Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Palette,
|
||||
stringResource(label),
|
||||
onClick = { actions.theme(value) },
|
||||
trailing = { RadioButton(selected = state.prefs.theme == value, onClick = { actions.theme(value) }) },
|
||||
showIcon = i == 0,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
active?.let { current ->
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch {
|
||||
Push.disable(context, current)
|
||||
runCatching { store.clientFor(current).signOut() }
|
||||
store.remove(current.id)
|
||||
}
|
||||
}) { Text(stringResource(R.string.sign_out)) }
|
||||
OutlinedButton(onClick = onAddInstance) {
|
||||
Text(stringResource(R.string.add_instance))
|
||||
}
|
||||
item {
|
||||
Group(stringResource(R.string.settings_notifications)) {
|
||||
SettingRow(
|
||||
Icons.Filled.NotificationsActive,
|
||||
stringResource(R.string.push_enable),
|
||||
subtitle = state.pushNote ?: stringResource(if (state.hasDistributor) R.string.push_explained else R.string.push_no_distributor),
|
||||
enabled = state.hasDistributor && state.active != null,
|
||||
onClick = { state.active?.let(actions::enablePush) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Notifications,
|
||||
stringResource(R.string.notification_settings),
|
||||
subtitle = stringResource(R.string.notification_settings_hint),
|
||||
onClick = actions::notificationSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_theme))
|
||||
listOf("" to R.string.theme_system, "moria" to R.string.theme_moria, "shire" to R.string.theme_shire).forEach { (value, label) ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { scope.launch { store.savePrefs { it.copy(theme = value) } } },
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = prefs.theme == value, onClick = { scope.launch { store.savePrefs { it.copy(theme = value) } } })
|
||||
Text(stringResource(label))
|
||||
item {
|
||||
Group(stringResource(R.string.settings_assistant)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Assistant,
|
||||
stringResource(R.string.assistant_open_settings),
|
||||
subtitle = stringResource(R.string.assistant_explained),
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Timer,
|
||||
stringResource(R.string.assistant_temporary),
|
||||
onClick = { actions.assistantTemporary(!state.prefs.assistantTemporary) },
|
||||
trailing = { Switch(checked = state.prefs.assistantTemporary, onCheckedChange = actions::assistantTemporary) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Mic,
|
||||
stringResource(R.string.assistant_listens),
|
||||
onClick = { actions.assistantListens(!state.prefs.assistantListens) },
|
||||
trailing = { Switch(checked = state.prefs.assistantListens, onCheckedChange = actions::assistantListens) },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.RecordVoiceOver,
|
||||
stringResource(R.string.assistant_read_aloud),
|
||||
onClick = { actions.readAloud(!state.prefs.readAloudSpoken) },
|
||||
trailing = { Switch(checked = state.prefs.readAloudSpoken, onCheckedChange = actions::readAloud) },
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_notifications))
|
||||
val distributors = remember { Push.distributors(context) }
|
||||
Text(
|
||||
stringResource(if (distributors.isEmpty()) R.string.push_no_distributor else R.string.push_explained),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
active?.let { current ->
|
||||
Button(enabled = distributors.isNotEmpty(), onClick = {
|
||||
(context as? Activity)?.let { activity ->
|
||||
Push.enable(activity, current) { ok ->
|
||||
pushNote = context.getString(if (ok) R.string.push_on else R.string.push_failed)
|
||||
}
|
||||
item {
|
||||
// Which recogniser turns speech into words: the instance's or the phone's -- what
|
||||
// each one is, and where the recording goes, said in the row itself.
|
||||
Group(stringResource(R.string.voice_input)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Dns,
|
||||
stringResource(R.string.voice_input_lembas),
|
||||
subtitle = stringResource(R.string.voice_input_lembas_line),
|
||||
onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) },
|
||||
trailing = {
|
||||
RadioButton(selected = state.prefs.voiceInput != Prefs.VOICE_PHONE, onClick = { actions.voiceInput(Prefs.VOICE_LEMBAS) })
|
||||
},
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.PhoneAndroid,
|
||||
stringResource(R.string.voice_input_phone),
|
||||
subtitle = stringResource(if (state.phoneRecognizer) R.string.voice_input_phone_line else R.string.voice_input_phone_none),
|
||||
enabled = state.phoneRecognizer,
|
||||
onClick = { actions.voiceInput(Prefs.VOICE_PHONE) },
|
||||
trailing = {
|
||||
RadioButton(
|
||||
selected = state.prefs.voiceInput == Prefs.VOICE_PHONE,
|
||||
enabled = state.phoneRecognizer,
|
||||
onClick = { actions.voiceInput(Prefs.VOICE_PHONE) },
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.voice_input_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
item {
|
||||
Group(stringResource(R.string.settings_about)) {
|
||||
SettingRow(Icons.Filled.Info, stringResource(R.string.about_version, state.version), onClick = {})
|
||||
Rule()
|
||||
// A found release: the row opens its page; until then it checks.
|
||||
SettingRow(
|
||||
Icons.Filled.SystemUpdate,
|
||||
stringResource(R.string.update_check),
|
||||
subtitle = state.updateNote,
|
||||
onClick = if (state.updateFound != null) actions::openRelease else actions::checkUpdate,
|
||||
)
|
||||
// The full build installs a release itself; a beta is installed from its page.
|
||||
val found = state.updateFound
|
||||
if (state.selfUpdate && found != null && !found.contains("-")) {
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Download,
|
||||
stringResource(R.string.update_install, found),
|
||||
onClick = actions::installUpdate,
|
||||
)
|
||||
}
|
||||
}) { Text(stringResource(R.string.push_enable)) }
|
||||
}
|
||||
pushNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_assistant))
|
||||
Text(stringResource(R.string.assistant_explained), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Button(onClick = {
|
||||
context.startActivity(Intent(Settings.ACTION_VOICE_INPUT_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}) { Text(stringResource(R.string.assistant_open_settings)) }
|
||||
Text(stringResource(R.string.assistant_samsung), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_temporary), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.assistantTemporary, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } } })
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(stringResource(R.string.assistant_read_aloud), modifier = Modifier.weight(1f))
|
||||
Switch(checked = prefs.readAloudSpoken, onCheckedChange = { on -> scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } } })
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Section(stringResource(R.string.settings_about))
|
||||
Text(stringResource(R.string.about_version, BuildConfig.VERSION_NAME))
|
||||
if (BuildConfig.SELF_UPDATE) {
|
||||
OutlinedButton(onClick = {
|
||||
scope.launch { updateNote = Updater(context).checkAndOffer() }
|
||||
}) { Text(stringResource(R.string.update_check)) }
|
||||
updateNote?.let { Text(it, style = MaterialTheme.typography.bodySmall) }
|
||||
Rule()
|
||||
val checks = state.prefs.checksUpdates(state.beta)
|
||||
SettingRow(
|
||||
Icons.Filled.Update,
|
||||
stringResource(R.string.update_auto),
|
||||
subtitle = stringResource(R.string.update_auto_line),
|
||||
onClick = { actions.updateCheck(!checks) },
|
||||
trailing = { Switch(checked = checks, onCheckedChange = actions::updateCheck) },
|
||||
)
|
||||
Rule()
|
||||
val betas = state.prefs.offersBetas(state.beta)
|
||||
SettingRow(
|
||||
Icons.Filled.Science,
|
||||
stringResource(R.string.update_betas),
|
||||
subtitle = stringResource(R.string.update_betas_line),
|
||||
onClick = { actions.updateBetas(!betas) },
|
||||
trailing = { Switch(checked = betas, onCheckedChange = actions::updateBetas) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Section(title: String) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary)
|
||||
private fun Group(title: String, content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.padding(start = 16.dp, top = 24.dp, bottom = 8.dp),
|
||||
)
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column { content() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Rule() = HorizontalDivider(color = LocalPalette.current.border, modifier = Modifier.padding(start = 56.dp))
|
||||
|
||||
/**
|
||||
* A settings row: an icon in a fixed 24 dp column (or its empty place, so a group's words start
|
||||
* on one line), the words that give, and the control that keeps its size.
|
||||
*/
|
||||
@Composable
|
||||
private fun SettingRow(
|
||||
icon: ImageVector,
|
||||
title: String,
|
||||
onClick: () -> Unit,
|
||||
subtitle: String? = null,
|
||||
tint: Color? = null,
|
||||
enabled: Boolean = true,
|
||||
showIcon: Boolean = true,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val ink = if (!enabled) palette.inkFaint else tint ?: palette.ink
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(enabled = enabled, onClick = onClick)
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
|
||||
if (showIcon) Icon(icon, contentDescription = null, tint = tint ?: palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = ink)
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
if (trailing != null) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
trailing()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** An instance's initial in a circle, where a picture would be. */
|
||||
@Composable
|
||||
private fun Initial(name: String) {
|
||||
val palette = LocalPalette.current
|
||||
Box(Modifier.size(40.dp).clip(CircleShape).background(palette.accentSoft), contentAlignment = Alignment.Center) {
|
||||
Text(name.trim().firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.titleMedium, color = palette.accent)
|
||||
}
|
||||
}
|
||||
|
||||
/** The phone's own language, named in itself: what "Phone language" would show. */
|
||||
private fun phoneLanguage(): String {
|
||||
val locale = android.content.res.Resources.getSystem().configuration.locales[0]
|
||||
return locale.getDisplayName(locale).replaceFirstChar { it.titlecase(locale) }
|
||||
}
|
||||
|
||||
/** The language row's words: what is chosen, and for the account's, which language that is. */
|
||||
@Composable
|
||||
private fun languageLabel(prefs: Prefs): String = when (prefs.language) {
|
||||
AppLanguage.ACCOUNT -> AppLanguage.name(prefs.accountLanguage)?.let { stringResource(R.string.language_account_is, it) }
|
||||
?: stringResource(R.string.language_account)
|
||||
|
||||
AppLanguage.PHONE -> stringResource(R.string.language_phone_is, phoneLanguage())
|
||||
|
||||
else -> AppLanguage.name(prefs.language) ?: stringResource(R.string.language_account)
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings › Language, as a sheet: the account's language (the default), the phone's, then every
|
||||
* language the app has, each named in itself so a person who cannot read the current one still
|
||||
* finds theirs.
|
||||
*/
|
||||
@Composable
|
||||
fun LanguageChoices(prefs: Prefs, onPick: (String) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val choices = buildList {
|
||||
add(
|
||||
Triple(
|
||||
AppLanguage.ACCOUNT,
|
||||
stringResource(R.string.language_account),
|
||||
AppLanguage.name(prefs.accountLanguage) ?: stringResource(R.string.language_account_unknown),
|
||||
),
|
||||
)
|
||||
add(Triple(AppLanguage.PHONE, stringResource(R.string.language_phone), phoneLanguage()))
|
||||
AppLanguage.LANGUAGES.forEach { (code, name) -> add(Triple(code, name, null)) }
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.settings_language),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
choices.forEachIndexed { i, (value, title, subtitle) ->
|
||||
item(key = "lang-$value-$i") {
|
||||
if (i == 2) HorizontalDivider(color = palette.border, modifier = Modifier.padding(vertical = 4.dp))
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(value) }
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge)
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
RadioButton(selected = prefs.language == value, onClick = { onPick(value) })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,8 +43,11 @@ import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.ServerFit
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@@ -60,8 +63,12 @@ sealed interface SignInState {
|
||||
data object Done : SignInState
|
||||
}
|
||||
|
||||
/** The newest API this app reads. A server with a newer one is told about, not guessed at. */
|
||||
const val APP_API = 1
|
||||
/** The sentence for a server this app will not work with, or null when it fits. */
|
||||
fun refusal(fit: ServerFit): Int? = when (fit) {
|
||||
ServerFit.FITS -> null
|
||||
ServerFit.NOT_LEMBAS, ServerFit.TOO_OLD -> R.string.signin_too_old
|
||||
ServerFit.TOO_NEW -> R.string.signin_too_new
|
||||
}
|
||||
|
||||
class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
|
||||
@@ -76,12 +83,8 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
try {
|
||||
val base = normaliseBase(typed)
|
||||
val found = doorstep.discover(base)
|
||||
if (found.service != "lembas" || found.appApi < 1 || "app" !in found.scopes) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_old))
|
||||
return@launch
|
||||
}
|
||||
if (found.appApi > APP_API) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_too_new))
|
||||
refusal(fit(found))?.let { said ->
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
|
||||
return@launch
|
||||
}
|
||||
val device = getApplication<Application>().getString(R.string.device_name)
|
||||
@@ -122,7 +125,7 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
} catch (e: Exception) {
|
||||
_state.value = SignInState.Failed(e.message ?: e.javaClass.simpleName)
|
||||
_state.value = SignInState.Failed(getApplication<Application>().explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
|
||||
import androidx.compose.foundation.text.selection.TextSelectionColors
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
@@ -21,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,
|
||||
@@ -55,6 +71,10 @@ fun LembasTheme(choice: String = "", content: @Composable () -> Unit) {
|
||||
}
|
||||
val palette = if (dark) Moria else Shire
|
||||
CompositionLocalProvider(LocalPalette provides palette) {
|
||||
MaterialTheme(colorScheme = scheme(palette, dark), content = content)
|
||||
MaterialTheme(colorScheme = scheme(palette, dark)) {
|
||||
// The web UI's `--selection`: selected text is a tint you can find, not Material's default.
|
||||
val selection = TextSelectionColors(handleColor = palette.accent, backgroundColor = palette.selection)
|
||||
CompositionLocalProvider(LocalTextSelectionColors provides selection, content = content)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v1.7.0. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.9. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
@@ -20,6 +20,7 @@ data class Palette(
|
||||
val accentHover: Color,
|
||||
val accentInk: Color,
|
||||
val accentSoft: Color,
|
||||
val selection: Color,
|
||||
val leaf: Color,
|
||||
val danger: Color,
|
||||
val dangerSoft: Color,
|
||||
@@ -49,6 +50,7 @@ val Moria = Palette(
|
||||
accentHover = Color(0xFFB4E6F1L),
|
||||
accentInk = Color(0xFF061418L),
|
||||
accentSoft = Color(0x1F8FD8E8L),
|
||||
selection = Color(0x528FD8E8L),
|
||||
leaf = Color(0xFF7EE081L),
|
||||
danger = Color(0xFFF0735FL),
|
||||
dangerSoft = Color(0x21F0735FL),
|
||||
@@ -78,6 +80,7 @@ val Shire = Palette(
|
||||
accentHover = Color(0xFF1F4D30L),
|
||||
accentInk = Color(0xFFF8F3E5L),
|
||||
accentSoft = Color(0x1A285F3CL),
|
||||
selection = Color(0x3D285F3CL),
|
||||
leaf = Color(0xFF3D6B1CL),
|
||||
danger = Color(0xFFA3321FL),
|
||||
dangerSoft = Color(0x1AA3321FL),
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import androidx.compose.foundation.background
|
||||
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.padding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
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.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
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.theme.LocalPalette
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Markdown longer than this is shown as its lines instead. A TextView holding a whole megabyte
|
||||
* of rendered Markdown stalls the phone; the same text as a lazy list of lines does not.
|
||||
*/
|
||||
private const val MARKDOWN_MAX_CHARS = 200_000
|
||||
|
||||
/** Where a file is on its way into the viewer. */
|
||||
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
|
||||
|
||||
/** [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)
|
||||
|
||||
/**
|
||||
* What a `show` card opens: the file, full screen, read-only, as the chat sees it now.
|
||||
*
|
||||
* Everything in it came from a model and is untrusted, as on the web page, so the rules are the
|
||||
* same ones the transcript keeps: Markdown goes through [MarkdownText] (no images, no HTML, links
|
||||
* outside for http, https and mailto only); code and text are drawn as lines, never interpreted.
|
||||
* **HTML is shown as its source, never rendered** -- the app has no WebView, and a page a model
|
||||
* wrote does not get one here. The web UI renders it in its sealed frame (an opaque origin with
|
||||
* no network), and "Open in the browser" goes there.
|
||||
*/
|
||||
@Composable
|
||||
fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(show.name, show.path, show.line, show.viewKind),
|
||||
key = chatId to show,
|
||||
webUrl = { it.webViewer(chatId, show) },
|
||||
load = { api, _ -> Loaded.Text(api.shownText(chatId, show)) },
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree (the Files screen), in the same viewer and under the same rules:
|
||||
* the person's own files are no more trusted than a model's, since a model may have written
|
||||
* them. A file the server withholds (not text, over 1 MB) says why, and offers the web UI.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit) {
|
||||
Viewer(
|
||||
file = Viewed(path.substringAfterLast('/').ifBlank { path }, path, 0, "text"),
|
||||
key = path,
|
||||
webUrl = { it.webFile(path) },
|
||||
load = { api, context ->
|
||||
val file = api.fileContent(path)
|
||||
val withheld = file.withheld
|
||||
when {
|
||||
withheld == null -> Loaded.Text(file.text, file.viewKind)
|
||||
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))
|
||||
}
|
||||
},
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load: suspend (ApiClient, Context) -> Loaded, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var loaded by remember(key) { mutableStateOf<Loaded>(Loaded.Loading) }
|
||||
var web by remember(key) { mutableStateOf<String?>(null) }
|
||||
|
||||
LaunchedEffect(key) {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null) {
|
||||
loaded = Loaded.Failed(context.getString(R.string.assist_signed_out))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web = webUrl(api)
|
||||
loaded = try {
|
||||
load(api, context)
|
||||
} catch (e: ApiException) {
|
||||
when {
|
||||
e.status == 413 -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
|
||||
e.status == 415 -> Loaded.Failed(e.message?.ifBlank { null } ?: context.getString(R.string.viewer_not_text))
|
||||
|
||||
// No such route at all (FastAPI's own "Not Found", or the wrong method): a
|
||||
// server without the app's door to the file. Its own 404 has a sentence.
|
||||
e.status == 405 || (e.status == 404 && e.message == "Not Found") ->
|
||||
Loaded.Failed(context.getString(R.string.viewer_unavailable), unavailable = true)
|
||||
|
||||
else -> Loaded.Failed(e.message ?: context.getString(R.string.viewer_unavailable))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Loaded.Failed(context.explain(e))
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onClose) {
|
||||
Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close))
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(file.name.ifBlank { file.path }, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
file.path + if (file.line > 0) ":${file.line}" else "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
(loaded as? Loaded.Text)?.let { done ->
|
||||
IconButton(onClick = { copy(context, file.name, done.text) }) {
|
||||
Icon(Icons.Filled.ContentCopy, contentDescription = stringResource(R.string.viewer_copy))
|
||||
}
|
||||
}
|
||||
web?.let { url ->
|
||||
IconButton(onClick = { openOutside(context, url) }) {
|
||||
Icon(Icons.AutoMirrored.Filled.OpenInNew, contentDescription = stringResource(R.string.viewer_open_browser))
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when (val now = loaded) {
|
||||
Loaded.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
is Loaded.Failed -> Column(
|
||||
Modifier.align(Alignment.Center).padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(now.message, color = palette.inkMuted, textAlign = TextAlign.Center)
|
||||
web?.let { url ->
|
||||
OutlinedButton(onClick = { openOutside(context, url) }, modifier = Modifier.padding(top = 16.dp)) {
|
||||
Text(stringResource(R.string.viewer_open_browser))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
is Loaded.Text -> Body(now.kind ?: file.kind, file.line, now.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Body(kind: 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)) {
|
||||
MarkdownText(text, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
return
|
||||
}
|
||||
val note = when (kind) {
|
||||
"html" -> R.string.viewer_html_source
|
||||
"markdown" -> R.string.viewer_long_markdown
|
||||
else -> null
|
||||
}
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
note?.let {
|
||||
Text(
|
||||
stringResource(it),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
Lines(text, line)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file as numbered lines, opened at the line the card named. The number column's width is
|
||||
* measured, not guessed: it is the width of the longest number in this file, so every line's
|
||||
* text starts at the same x whatever its number, and a wrapped line continues under its own
|
||||
* text rather than under the numbers.
|
||||
*/
|
||||
@Composable
|
||||
private fun Lines(text: String, line: Int) {
|
||||
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 style = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
val measurer = rememberTextMeasurer()
|
||||
val density = LocalDensity.current
|
||||
val gutter = remember(rows.size, density) {
|
||||
with(density) { measurer.measure("9".repeat(rows.size.toString().length), style).size.width.toDp() }
|
||||
}
|
||||
val state = rememberLazyListState(initialFirstVisibleItemIndex = (line - 1).coerceIn(0, (rows.size - 1).coerceAtLeast(0)))
|
||||
LazyColumn(
|
||||
state = state,
|
||||
modifier = Modifier.fillMaxSize().background(palette.codeBg),
|
||||
contentPadding = PaddingValues(vertical = 8.dp),
|
||||
) {
|
||||
itemsIndexed(rows) { i, row ->
|
||||
val here = line > 0 && i == line - 1
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.then(if (here) Modifier.background(palette.accentSoft) else Modifier)
|
||||
.padding(horizontal = 12.dp),
|
||||
) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
|
||||
}
|
||||
|
||||
/** The web UI's viewer, in the browser (a Custom Tab), where the person's own session is. */
|
||||
private fun openOutside(context: Context, url: String) {
|
||||
val uri = Uri.parse(url)
|
||||
if (uri.scheme?.lowercase() !in setOf("http", "https")) return
|
||||
runCatching { CustomTabsIntent.Builder().build().launchUrl(context, uri) }
|
||||
}
|
||||
@@ -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
|
||||
@@ -37,7 +37,7 @@ class Updater(private val context: Context) {
|
||||
if (!it.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
|
||||
LembasJson.decodeFromString(Latest.serializer(), it.body!!.string())
|
||||
}
|
||||
if (!newer(latest.version, BuildConfig.VERSION_NAME.removeSuffix("-debug"))) {
|
||||
if (!newer(latest.version, BuildConfig.VERSION_NAME.substringBefore("-debug"))) {
|
||||
return@withContext context.getString(R.string.update_none)
|
||||
}
|
||||
if (!context.packageManager.canRequestPackageInstalls()) {
|
||||
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Otevřít v prohlížeči</string>
|
||||
<string name="signin_denied">Přihlášení bylo odmítnuto.</string>
|
||||
<string name="signin_expired">Kód vypršel, než byl schválen. Zkuste to znovu.</string>
|
||||
<string name="signin_too_old">Tato instance ještě nemá rozhraní API pro aplikace. Potřebuje LLeMbas 1.7.0 nebo novější.</string>
|
||||
<string name="signin_too_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">Žádné konverzace s agentem. Spusťte jednu z webového rozhraní na propojeném zařízení.</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>
|
||||
<string name="agent_directory">Složka na zařízení</string>
|
||||
<string name="agent_directory_hint">Prázdné: první složka zařízení</string>
|
||||
<string name="empty_chat">O čem si promluvíme?</string>
|
||||
<string name="loading_line">Pečou se lembasy…</string>
|
||||
<string name="archive">Archivovat</string>
|
||||
<string name="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>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Odeslat</string>
|
||||
<string name="stop">Zastavit</string>
|
||||
<string name="attach">Přiložit soubor</string>
|
||||
<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>
|
||||
<string name="save">Uložit</string>
|
||||
<string name="retry">Zkusit znovu</string>
|
||||
<string name="offline">Instance není dostupná. Zkontrolujte připojení telefonu a to, zda se dostane na adresu instance.</string>
|
||||
<string name="dictate">Diktovat</string>
|
||||
<string name="remove">Odebrat</string>
|
||||
<string name="more">Více</string>
|
||||
<string name="back">Zpět</string>
|
||||
<string name="cancel">Zrušit</string>
|
||||
<string name="close">Zavřít</string>
|
||||
<string name="effort_off">Úsilí: vypnuto</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upravit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Ručně</string>
|
||||
<string name="mode_auto">Automaticky</string>
|
||||
<string name="activity">Aktivita</string>
|
||||
<string name="activity_open">Otevřít panel aktivity</string>
|
||||
<string name="activity_context">Kontext</string>
|
||||
<string name="activity_outputs">Výstupy</string>
|
||||
<string name="activity_tasks">Úlohy na pozadí</string>
|
||||
<string name="activity_used">Využito: %1$s %%</string>
|
||||
<string name="activity_window_unknown">okno neznámé</string>
|
||||
<string name="activity_not_measured">Neměřeno.</string>
|
||||
<string name="activity_measured">Spočítal model při poslední odpovědi; kategorie jsou odhadnuté.</string>
|
||||
<string name="activity_estimated">Odhad: žádná odpověď ještě nebyla spočítána.</string>
|
||||
<string name="activity_tools_offered">Nabízené nástroje: %1$s.</string>
|
||||
<string name="ctx_messages">Zprávy</string>
|
||||
<string name="ctx_system">Systémový pokyn</string>
|
||||
<string name="ctx_memory">Paměť a osobní</string>
|
||||
<string name="ctx_instructions">Soubory s pokyny</string>
|
||||
<string name="ctx_tools">Nástroje</string>
|
||||
<string name="ctx_mcp_tools">Nástroje MCP</string>
|
||||
<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="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="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>
|
||||
<string name="agent_state_queued">ve frontě</string>
|
||||
<string name="agent_state_working">pracuje</string>
|
||||
<string name="agent_state_waiting">čeká</string>
|
||||
<string name="agent_state_done">hotovo</string>
|
||||
<string name="agent_state_stopped">zastaveno</string>
|
||||
<string name="agent_state_error">selhalo</string>
|
||||
<string name="agent_steps">Kroky: %1$s, nástroje: %2$s</string>
|
||||
<string name="agent_open_conversation">Otevřít jeho konverzaci</string>
|
||||
<string name="agent_stop">Zastavit %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Zastavit %1$s a členy pod ním? Opustí tým.</string>
|
||||
<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 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">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="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="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>
|
||||
@@ -54,10 +254,66 @@
|
||||
<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>
|
||||
<string name="plan_carry_out">Provést plán</string>
|
||||
<string name="shown">Zobrazeno</string>
|
||||
<string name="viewer_open">Otevřít</string>
|
||||
<string name="viewer_open_browser">Otevřít v prohlížeči</string>
|
||||
<string name="viewer_copy">Kopírovat</string>
|
||||
<string name="viewer_html_source">Toto je zdrojový kód stránky. Samotnou stránku uvidíte po otevření v prohlížeči.</string>
|
||||
<string name="viewer_long_markdown">Dlouhý soubor, proto je zobrazen jako prostý text.</string>
|
||||
<string name="viewer_unavailable">Tento server zatím aplikaci soubor předat neumí. Otevřete ho v prohlížeči.</string>
|
||||
<string name="viewer_too_large">Tento soubor je příliš velký na zobrazení; zobrazit lze nejvýše 1 MB.</string>
|
||||
<string name="viewer_not_text">Toto není textový soubor, proto se zde nezobrazuje.</string>
|
||||
<string name="files">Soubory</string>
|
||||
<string name="files_all">Všechny soubory</string>
|
||||
<string name="files_empty">Zatím tu nic není. Ani hobití nora.</string>
|
||||
<string name="settings">Nastavení</string>
|
||||
<string name="settings_instances">Instance</string>
|
||||
<string name="sign_out">Odhlásit se</string>
|
||||
@@ -66,6 +322,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>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Nebyl zvolen žádný distributor, takže upozornění jsou stále vypnutá.</string>
|
||||
<string name="channel_replies">Odpovědi</string>
|
||||
<string name="channel_asks">Otázky a schválení</string>
|
||||
<string name="channel_reports">Zprávy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.</string>
|
||||
<string name="assistant_open_settings">Otevřít nastavení asistenta</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<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_no_wake_word">Budicí slovo není: na běžném Androidu je naslouchání budicímu slovu vyhrazeno asistentovi zabudovanému v telefonu.</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_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>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Im Browser öffnen</string>
|
||||
<string name="signin_denied">Die Anmeldung wurde abgelehnt.</string>
|
||||
<string name="signin_expired">Der Code ist abgelaufen, bevor er bestätigt wurde. Versuchen Sie es erneut.</string>
|
||||
<string name="signin_too_old">Diese Instanz hat noch keine App-API. Sie braucht LLeMbas 1.7.0 oder neuer.</string>
|
||||
<string name="signin_too_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">Keine Agent-Chats. Starten Sie einen über die Weboberfläche auf einem verknüpften Gerät.</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>
|
||||
<string name="agent_directory">Ordner auf dem Gerät</string>
|
||||
<string name="agent_directory_hint">Leer: der erste Ordner des Geräts</string>
|
||||
<string name="empty_chat">Worüber sprechen wir?</string>
|
||||
<string name="loading_line">Lembas wird gebacken…</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
<string name="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>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Senden</string>
|
||||
<string name="stop">Stoppen</string>
|
||||
<string name="attach">Datei anhängen</string>
|
||||
<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>
|
||||
<string name="save">Speichern</string>
|
||||
<string name="retry">Erneut versuchen</string>
|
||||
<string name="offline">Die Instanz ist nicht erreichbar. Prüfen Sie die Verbindung des Telefons und ob es die Adresse der Instanz erreicht.</string>
|
||||
<string name="dictate">Diktieren</string>
|
||||
<string name="remove">Entfernen</string>
|
||||
<string name="more">Mehr</string>
|
||||
<string name="back">Zurück</string>
|
||||
<string name="cancel">Abbrechen</string>
|
||||
<string name="close">Schließen</string>
|
||||
<string name="effort_off">Aufwand: aus</string>
|
||||
<string name="mode_plan">Tarif</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Bearbeiten</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Manuell</string>
|
||||
<string name="mode_auto">Automatisch</string>
|
||||
<string name="activity">Aktivität</string>
|
||||
<string name="activity_open">Aktivitätsbereich öffnen</string>
|
||||
<string name="activity_context">Kontext</string>
|
||||
<string name="activity_outputs">Ausgaben</string>
|
||||
<string name="activity_tasks">Hintergrundaufgaben</string>
|
||||
<string name="activity_used">%1$s %% belegt</string>
|
||||
<string name="activity_window_unknown">Fenster unbekannt</string>
|
||||
<string name="activity_not_measured">Nicht gemessen.</string>
|
||||
<string name="activity_measured">Vom Modell bei der letzten Antwort gezählt; die Kategorien sind geschätzt.</string>
|
||||
<string name="activity_estimated">Geschätzt: Noch keine Antwort wurde gezählt.</string>
|
||||
<string name="activity_tools_offered">%1$s Werkzeuge angeboten.</string>
|
||||
<string name="ctx_messages">Nachrichten</string>
|
||||
<string name="ctx_system">Systemprompt</string>
|
||||
<string name="ctx_memory">Gedächtnis und Persönliches</string>
|
||||
<string name="ctx_instructions">Anweisungsdateien</string>
|
||||
<string name="ctx_tools">Werkzeuge</string>
|
||||
<string name="ctx_mcp_tools">MCP-Werkzeuge</string>
|
||||
<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="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="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>
|
||||
<string name="agent_state_queued">in der Warteschlange</string>
|
||||
<string name="agent_state_working">arbeitet</string>
|
||||
<string name="agent_state_waiting">wartet</string>
|
||||
<string name="agent_state_done">fertig</string>
|
||||
<string name="agent_state_stopped">angehalten</string>
|
||||
<string name="agent_state_error">fehlgeschlagen</string>
|
||||
<string name="agent_steps">%1$s Schritte, %2$s Werkzeuge</string>
|
||||
<string name="agent_open_conversation">Seine Unterhaltung öffnen</string>
|
||||
<string name="agent_stop">%1$s stoppen</string>
|
||||
<string name="agent_stop_member_confirm">%1$s und die Mitglieder darunter stoppen? Sie verlassen das Team.</string>
|
||||
<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 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">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="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="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>
|
||||
@@ -54,10 +254,66 @@
|
||||
<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>
|
||||
<string name="plan_carry_out">Plan ausführen</string>
|
||||
<string name="shown">Angezeigt</string>
|
||||
<string name="viewer_open">Öffnen</string>
|
||||
<string name="viewer_open_browser">Im Browser öffnen</string>
|
||||
<string name="viewer_copy">Kopieren</string>
|
||||
<string name="viewer_html_source">Das ist der Quelltext der Seite. Die Seite selbst sehen Sie im Browser.</string>
|
||||
<string name="viewer_long_markdown">Eine lange Datei, daher wird sie als reiner Text angezeigt.</string>
|
||||
<string name="viewer_unavailable">Dieser Server kann die Datei der App noch nicht übergeben. Öffnen Sie sie stattdessen im Browser.</string>
|
||||
<string name="viewer_too_large">Diese Datei ist zu groß zum Anzeigen; höchstens 1 MB kann angezeigt werden.</string>
|
||||
<string name="viewer_not_text">Das ist keine Textdatei, deshalb wird sie hier nicht angezeigt.</string>
|
||||
<string name="files">Dateien</string>
|
||||
<string name="files_all">Alle Dateien</string>
|
||||
<string name="files_empty">Hier ist noch nichts. Nicht einmal eine Hobbithöhle.</string>
|
||||
<string name="settings">Einstellungen</string>
|
||||
<string name="settings_instances">Instanzen</string>
|
||||
<string name="sign_out">Abmelden</string>
|
||||
@@ -66,6 +322,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>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Es wurde kein Distributor gewählt, daher sind die Benachrichtigungen noch ausgeschaltet.</string>
|
||||
<string name="channel_replies">Antworten</string>
|
||||
<string name="channel_asks">Fragen und Bestätigungen</string>
|
||||
<string name="channel_reports">Berichte</string>
|
||||
<string name="settings_assistant">Assistent</string>
|
||||
<string name="assistant_explained">Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.</string>
|
||||
<string name="assistant_open_settings">Assistenten-Einstellungen öffnen</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<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_no_wake_word">Es gibt kein Aktivierungswort: Auf normalem Android ist das Lauschen darauf dem im Telefon eingebauten Assistenten vorbehalten.</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_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>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Abrir en el navegador</string>
|
||||
<string name="signin_denied">El inicio de sesión fue rechazado.</string>
|
||||
<string name="signin_expired">El código caducó antes de ser aprobado. Inténtelo de nuevo.</string>
|
||||
<string name="signin_too_old">Esta instancia aún no tiene API para aplicaciones. Necesita LLeMbas 1.7.0 o una versión posterior.</string>
|
||||
<string name="signin_too_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">No hay chats de agente. Inicie uno desde la interfaz web en un dispositivo vinculado.</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>
|
||||
<string name="agent_directory">Carpeta en el dispositivo</string>
|
||||
<string name="agent_directory_hint">Vacío: la primera carpeta del dispositivo</string>
|
||||
<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>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Enviar</string>
|
||||
<string name="stop">Detener</string>
|
||||
<string name="attach">Adjuntar un archivo</string>
|
||||
<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>
|
||||
<string name="save">Guardar</string>
|
||||
<string name="retry">Reintentar</string>
|
||||
<string name="offline">No se puede acceder a la instancia. Compruebe la conexión del teléfono y que llegue a la dirección de la instancia.</string>
|
||||
<string name="dictate">Dictar</string>
|
||||
<string name="remove">Quitar</string>
|
||||
<string name="more">Más</string>
|
||||
<string name="back">Volver</string>
|
||||
<string name="cancel">Cancelar</string>
|
||||
<string name="close">Cerrar</string>
|
||||
<string name="effort_off">Esfuerzo: desactivado</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Editar</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_auto">Automático</string>
|
||||
<string name="activity">Actividad</string>
|
||||
<string name="activity_open">Abrir el panel de actividad</string>
|
||||
<string name="activity_context">Contexto</string>
|
||||
<string name="activity_outputs">Resultados</string>
|
||||
<string name="activity_tasks">Tareas en segundo plano</string>
|
||||
<string name="activity_used">%1$s %% usado</string>
|
||||
<string name="activity_window_unknown">ventana desconocida</string>
|
||||
<string name="activity_not_measured">Sin medir.</string>
|
||||
<string name="activity_measured">Contado por el modelo en la última respuesta; las categorías son estimaciones.</string>
|
||||
<string name="activity_estimated">Estimado: aún no se ha contado ninguna respuesta.</string>
|
||||
<string name="activity_tools_offered">%1$s herramientas ofrecidas.</string>
|
||||
<string name="ctx_messages">Mensajes</string>
|
||||
<string name="ctx_system">Prompt de sistema</string>
|
||||
<string name="ctx_memory">Memoria y datos personales</string>
|
||||
<string name="ctx_instructions">Archivos de instrucciones</string>
|
||||
<string name="ctx_tools">Herramientas</string>
|
||||
<string name="ctx_mcp_tools">Herramientas MCP</string>
|
||||
<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="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="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>
|
||||
<string name="agent_state_queued">en cola</string>
|
||||
<string name="agent_state_working">trabajando</string>
|
||||
<string name="agent_state_waiting">esperando</string>
|
||||
<string name="agent_state_done">terminado</string>
|
||||
<string name="agent_state_stopped">detenido</string>
|
||||
<string name="agent_state_error">falló</string>
|
||||
<string name="agent_steps">%1$s pasos, %2$s herramientas</string>
|
||||
<string name="agent_open_conversation">Abrir su conversación</string>
|
||||
<string name="agent_stop">Detener %1$s</string>
|
||||
<string name="agent_stop_member_confirm">¿Detener %1$s y a los miembros que dependen de él? Dejan el equipo.</string>
|
||||
<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 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">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="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="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>
|
||||
@@ -54,10 +254,66 @@
|
||||
<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>
|
||||
<string name="plan_carry_out">Llevar a cabo el plan</string>
|
||||
<string name="shown">Mostrado</string>
|
||||
<string name="viewer_open">Abrir</string>
|
||||
<string name="viewer_open_browser">Abrir en el navegador</string>
|
||||
<string name="viewer_copy">Copiar</string>
|
||||
<string name="viewer_html_source">Este es el código fuente de la página. Ábrala en el navegador para ver la página.</string>
|
||||
<string name="viewer_long_markdown">Un archivo largo, por eso se muestra como texto sin formato.</string>
|
||||
<string name="viewer_unavailable">Este servidor todavía no puede entregar el archivo a la aplicación. Ábralo en el navegador.</string>
|
||||
<string name="viewer_too_large">Este archivo es demasiado grande para mostrarlo; se puede mostrar como máximo 1 MB.</string>
|
||||
<string name="viewer_not_text">No es un archivo de texto, así que no se muestra aquí.</string>
|
||||
<string name="files">Archivos</string>
|
||||
<string name="files_all">Todos los archivos</string>
|
||||
<string name="files_empty">Aquí aún no hay nada. Ni siquiera un agujero hobbit.</string>
|
||||
<string name="settings">Ajustes</string>
|
||||
<string name="settings_instances">Instancias</string>
|
||||
<string name="sign_out">Cerrar sesión</string>
|
||||
@@ -66,6 +322,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>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">No se eligió ningún distribuidor, así que las notificaciones siguen desactivadas.</string>
|
||||
<string name="channel_replies">Respuestas</string>
|
||||
<string name="channel_asks">Preguntas y aprobaciones</string>
|
||||
<string name="channel_reports">Informes</string>
|
||||
<string name="settings_assistant">Asistente</string>
|
||||
<string name="assistant_explained">Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.</string>
|
||||
<string name="assistant_open_settings">Abrir los ajustes del asistente</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<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_no_wake_word">No hay palabra de activación: en Android estándar, escucharla está reservado al asistente integrado en el teléfono.</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_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>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Ouvrir dans le navigateur</string>
|
||||
<string name="signin_denied">La connexion a été refusée.</string>
|
||||
<string name="signin_expired">Le code a expiré avant d\'être approuvé. Réessayez.</string>
|
||||
<string name="signin_too_old">Cette instance n\'a pas encore d\'API pour l\'application. Elle nécessite LLeMbas 1.7.0 ou une version plus récente.</string>
|
||||
<string name="signin_too_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">Aucune conversation d\'agent. Démarrez-en une depuis l\'interface web sur un appareil associé.</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>
|
||||
<string name="agent_directory">Dossier sur l\'appareil</string>
|
||||
<string name="agent_directory_hint">Vide : le premier dossier de l\'appareil</string>
|
||||
<string name="empty_chat">De quoi allons-nous parler ?</string>
|
||||
<string name="loading_line">Cuisson des lembas…</string>
|
||||
<string name="archive">Archiver</string>
|
||||
<string name="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>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Envoyer</string>
|
||||
<string name="stop">Arrêter</string>
|
||||
<string name="attach">Joindre un fichier</string>
|
||||
<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>
|
||||
<string name="save">Enregistrer</string>
|
||||
<string name="retry">Réessayer</string>
|
||||
<string name="offline">L\'instance est injoignable. Vérifiez la connexion du téléphone et qu\'il atteint bien l\'adresse de l\'instance.</string>
|
||||
<string name="dictate">Dicter</string>
|
||||
<string name="remove">Retirer</string>
|
||||
<string name="more">Plus</string>
|
||||
<string name="back">Retour</string>
|
||||
<string name="cancel">Annuler</string>
|
||||
<string name="close">Fermer</string>
|
||||
<string name="effort_off">Effort : désactivé</string>
|
||||
<string name="mode_plan">Forfait</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Modifier</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Manuel</string>
|
||||
<string name="mode_auto">Automatique</string>
|
||||
<string name="activity">Activité</string>
|
||||
<string name="activity_open">Ouvrir le panneau d’activité</string>
|
||||
<string name="activity_context">Contexte</string>
|
||||
<string name="activity_outputs">Sorties</string>
|
||||
<string name="activity_tasks">Tâches en arrière-plan</string>
|
||||
<string name="activity_used">%1$s %% utilisés</string>
|
||||
<string name="activity_window_unknown">fenêtre inconnue</string>
|
||||
<string name="activity_not_measured">Non mesuré.</string>
|
||||
<string name="activity_measured">Compté par le modèle lors de la dernière réponse ; les catégories sont estimées.</string>
|
||||
<string name="activity_estimated">Estimation : aucune réponse n’a encore été comptée.</string>
|
||||
<string name="activity_tools_offered">%1$s outils proposés.</string>
|
||||
<string name="ctx_messages">Messages</string>
|
||||
<string name="ctx_system">Prompt système</string>
|
||||
<string name="ctx_memory">Mémoire et informations personnelles</string>
|
||||
<string name="ctx_instructions">Fichiers d’instructions</string>
|
||||
<string name="ctx_tools">Outils</string>
|
||||
<string name="ctx_mcp_tools">Outils MCP</string>
|
||||
<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="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="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>
|
||||
<string name="agent_state_queued">en file d’attente</string>
|
||||
<string name="agent_state_working">au travail</string>
|
||||
<string name="agent_state_waiting">en attente</string>
|
||||
<string name="agent_state_done">terminé</string>
|
||||
<string name="agent_state_stopped">arrêté</string>
|
||||
<string name="agent_state_error">échoué</string>
|
||||
<string name="agent_steps">%1$s étapes, %2$s outils</string>
|
||||
<string name="agent_open_conversation">Ouvrir sa conversation</string>
|
||||
<string name="agent_stop">Arrêter %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Arrêter %1$s et les membres qui en dépendent ? Ils quittent l’équipe.</string>
|
||||
<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 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">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="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="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>
|
||||
@@ -54,10 +254,66 @@
|
||||
<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>
|
||||
<string name="plan_carry_out">Exécuter le plan</string>
|
||||
<string name="shown">Affiché</string>
|
||||
<string name="viewer_open">Ouvrir</string>
|
||||
<string name="viewer_open_browser">Ouvrir dans le navigateur</string>
|
||||
<string name="viewer_copy">Copier</string>
|
||||
<string name="viewer_html_source">Ceci est le code source de la page. Ouvrez-la dans le navigateur pour voir la page elle-même.</string>
|
||||
<string name="viewer_long_markdown">Un fichier long, il est donc affiché en texte brut.</string>
|
||||
<string name="viewer_unavailable">Ce serveur ne peut pas encore transmettre le fichier à l\'application. Ouvrez-le plutôt dans le navigateur.</string>
|
||||
<string name="viewer_too_large">Ce fichier est trop volumineux pour être affiché ; 1 Mo au plus peut être affiché.</string>
|
||||
<string name="viewer_not_text">Ce n\'est pas un fichier texte, il n\'est donc pas affiché ici.</string>
|
||||
<string name="files">Fichiers</string>
|
||||
<string name="files_all">Tous les fichiers</string>
|
||||
<string name="files_empty">Rien ici pour l\'instant. Pas même un trou de hobbit.</string>
|
||||
<string name="settings">Paramètres</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Se déconnecter</string>
|
||||
@@ -66,6 +322,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>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Aucun distributeur n\'a été choisi, les notifications sont donc toujours désactivées.</string>
|
||||
<string name="channel_replies">Réponses</string>
|
||||
<string name="channel_asks">Questions et approbations</string>
|
||||
<string name="channel_reports">Rapports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Faites de LLeMbas l\'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d\'assistance numérique. Maintenir le bouton d\'alimentation, le geste d\'assistance ou le raccourci de l\'écran de verrouillage l\'ouvrira alors par-dessus ce qui est affiché.</string>
|
||||
<string name="assistant_open_settings">Ouvrir les paramètres de l\'assistant</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<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_no_wake_word">Pas de mot d’activation : sur Android standard, l’écoute d’un tel mot est réservée à l’assistant intégré au téléphone.</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_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>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Megnyitás a böngészőben</string>
|
||||
<string name="signin_denied">A bejelentkezést elutasították.</string>
|
||||
<string name="signin_expired">A kód lejárt, mielőtt jóváhagyták volna. Próbálja újra.</string>
|
||||
<string name="signin_too_old">Ennek a példánynak még nincs alkalmazás-API-ja. LLeMbas 1.7.0 vagy újabb verzió szükséges hozzá.</string>
|
||||
<string name="signin_too_old">Ezen a példányon régebbi LLeMbas fut. Ehhez az alkalmazáshoz LLeMbas 2.0 vagy újabb kell.</string>
|
||||
<string name="signin_too_new">Ez a példány újabb alkalmazás-API-t használ, mint ez az alkalmazás. Frissítse az alkalmazást.</string>
|
||||
<string name="new_chat">Új csevegés</string>
|
||||
<string name="tab_chats">Csevegések</string>
|
||||
<string name="tab_agents">Ügynökök</string>
|
||||
<string name="empty_chats">Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.</string>
|
||||
<string name="empty_agents">Nincs ügynök-csevegés. Indítson el egyet a webes felületen egy összekapcsolt eszközön.</string>
|
||||
<string name="new_agent_chat">Új ügynök-csevegés</string>
|
||||
<string name="agent_device">Eszköz</string>
|
||||
<string name="agent_no_device">Jelenleg nincs összekapcsolt eszköz. Indítsa el a `lembas service` parancsot egy ebbe a példányba bejelentkezett számítógépen, majd térjen vissza.</string>
|
||||
<string name="agent_directory">Mappa az eszközön</string>
|
||||
<string name="agent_directory_hint">Üres: az eszköz első mappája</string>
|
||||
<string name="empty_chat">Miről beszéljünk?</string>
|
||||
<string name="loading_line">Lembas sül…</string>
|
||||
<string name="archive">Archiválás</string>
|
||||
<string name="archived">Archivált</string>
|
||||
<string name="archived_restore">Csevegés visszaállítása</string>
|
||||
<string name="archived_none">Nincs archivált csevegés.</string>
|
||||
<string name="memory">Memória</string>
|
||||
<string name="memory_intro">Amit a modellek megjegyeztek Önről</string>
|
||||
<string name="memory_none">Még semmi. A memóriaeszközzel rendelkező modell akkor egészíti ki, amikor valami megjegyzésre érdemeset mond neki.</string>
|
||||
<string name="memory_remember">Megjegyzés</string>
|
||||
<string name="memory_label">Mit mond ez a memória</string>
|
||||
<string name="memory_hint">Valami, amit érdemes megjegyezni</string>
|
||||
<string name="memory_group">Adatcsoport</string>
|
||||
<string name="memory_forget">Elfelejtés</string>
|
||||
<string name="memory_by_model">Modell</string>
|
||||
<string name="chats_pinned">Kitűzött beszélgetések</string>
|
||||
<string name="chat_pin">Beszélgetés kitűzése</string>
|
||||
<string name="chat_unpin">Kitűzés megszüntetése</string>
|
||||
<string name="folder_move">Áthelyezés mappába</string>
|
||||
<string name="folder_none">Nincs mappa</string>
|
||||
<string name="folder_new">Új mappa</string>
|
||||
<string name="folder_name">Mappa neve</string>
|
||||
<string name="folder_rename">Mappa átnevezése</string>
|
||||
<string name="folder_delete">Mappa törlése</string>
|
||||
<string name="folder_delete_confirm">Törli a(z) „%1$s” mappát? A benne lévő csevegések megmaradnak.</string>
|
||||
<string name="delete">Törlés</string>
|
||||
<string name="edit">Szerkesztés</string>
|
||||
<string name="regenerate">Újragenerálás</string>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Küldés</string>
|
||||
<string name="stop">Leállítás</string>
|
||||
<string name="attach">Fájl csatolása</string>
|
||||
<string name="attach_take_photo">Fénykép készítése</string>
|
||||
<string name="attach_choose_photos">Fényképek kiválasztása</string>
|
||||
<string name="attach_choose_files">Fájlok kiválasztása</string>
|
||||
<string name="image_generate">Képek generálása</string>
|
||||
<string name="image_generated">A generált kép</string>
|
||||
<string name="copy_message">Üzenet másolása</string>
|
||||
<string name="copied">Másolva.</string>
|
||||
<string name="rename_chat">Csevegés átnevezése</string>
|
||||
<string name="save">Mentés</string>
|
||||
<string name="retry">Újrapróbálás</string>
|
||||
<string name="offline">A példány nem érhető el. Ellenőrizze a telefon kapcsolatát, és hogy eléri-e a példány címét.</string>
|
||||
<string name="dictate">Diktálás</string>
|
||||
<string name="remove">Eltávolítás</string>
|
||||
<string name="more">Továbbiak</string>
|
||||
<string name="back">Vissza</string>
|
||||
<string name="cancel">Mégse</string>
|
||||
<string name="close">Bezárás</string>
|
||||
<string name="effort_off">Erőfeszítés: kikapcsolva</string>
|
||||
<string name="mode_plan">Csomag</string>
|
||||
<string name="mode_plan">Terv</string>
|
||||
<string name="mode_edit">Szerkesztés</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Kézi</string>
|
||||
<string name="mode_auto">Automatikus</string>
|
||||
<string name="activity">Tevékenység</string>
|
||||
<string name="activity_open">A tevékenységpanel megnyitása</string>
|
||||
<string name="activity_context">Kontextus</string>
|
||||
<string name="activity_outputs">Kimenetek</string>
|
||||
<string name="activity_tasks">Háttérfeladatok</string>
|
||||
<string name="activity_used">%1$s%% foglalt</string>
|
||||
<string name="activity_window_unknown">az ablak ismeretlen</string>
|
||||
<string name="activity_not_measured">Nincs mérve.</string>
|
||||
<string name="activity_measured">A modell számolta az utolsó válasznál; a kategóriák becslések.</string>
|
||||
<string name="activity_estimated">Becslés: még egy válasz sem lett megszámolva.</string>
|
||||
<string name="activity_tools_offered">%1$s eszköz felkínálva.</string>
|
||||
<string name="ctx_messages">Üzenetek</string>
|
||||
<string name="ctx_system">Rendszerprompt</string>
|
||||
<string name="ctx_memory">Memória és személyes adatok</string>
|
||||
<string name="ctx_instructions">Utasításfájlok</string>
|
||||
<string name="ctx_tools">Eszközök</string>
|
||||
<string name="ctx_mcp_tools">MCP-eszközök</string>
|
||||
<string name="ctx_since">Az utolsó válasz óta</string>
|
||||
<string name="ctx_buffer">Tömörítési tartalék</string>
|
||||
<string name="ctx_free">Szabad hely</string>
|
||||
<string name="tasks_empty">A háttérben semmi sem fut. Az alügynökök, a parancsok és a csapat tagjai itt látszanak, amíg dolgoznak.</string>
|
||||
<string name="tasks_none_running">Semmi sem fut.</string>
|
||||
<string name="tasks_running">Fut</string>
|
||||
<string name="tasks_finished">Befejezve</string>
|
||||
<string name="tasks_n_running">%1$s fut</string>
|
||||
<string name="tasks_nested">Alatta: %1$s</string>
|
||||
<string name="task_subagent">Alügynök</string>
|
||||
<string name="task_command">Parancs</string>
|
||||
<string name="task_member">Csapattag</string>
|
||||
<string name="activity_until_compact">%1$s az automatikus tömörítésig</string>
|
||||
<string name="activity_compact_off">Az automatikus tömörítés ki van kapcsolva.</string>
|
||||
<string name="activity_compact">Tömörítés</string>
|
||||
<string name="agents_n_queued">%1$s sorban áll</string>
|
||||
<string name="agents_n_waiting">%1$s várakozik</string>
|
||||
<string name="agents_n_finished">%1$s befejezve</string>
|
||||
<string name="agent_state_queued">sorban áll</string>
|
||||
<string name="agent_state_working">dolgozik</string>
|
||||
<string name="agent_state_waiting">várakozik</string>
|
||||
<string name="agent_state_done">kész</string>
|
||||
<string name="agent_state_stopped">leállítva</string>
|
||||
<string name="agent_state_error">sikertelen</string>
|
||||
<string name="agent_steps">%1$s lépés, %2$s eszköz</string>
|
||||
<string name="agent_open_conversation">A beszélgetésének megnyitása</string>
|
||||
<string name="agent_stop">%1$s leállítása</string>
|
||||
<string name="agent_stop_member_confirm">Leállítja %1$s tagot és az alatta lévőket? Kilépnek a csapatból.</string>
|
||||
<string name="agent_stop_confirm">Leállítja: %1$s? Amit eddig elvégzett, megmarad.</string>
|
||||
<string name="agent_nothing_yet">Még nem mondott semmit.</string>
|
||||
<string name="agent_machine">A rendszertől</string>
|
||||
<string name="team_size">Csapat: %1$s / %2$s alügynök</string>
|
||||
<string name="team_room">Szoba</string>
|
||||
<string name="room_empty">A szobában még senki nem mondott semmit.</string>
|
||||
<string name="room_report">jelentés</string>
|
||||
<string name="team_agents">Alügynökök</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">A számok a csevegés saját ügynökét is beleszámítják: 1 az ügynök egyedül, alügynökök nélkül, a Max 4 pedig az ügynök és legfeljebb 3 alügynök, akiket vezet.</string>
|
||||
<string name="team_chip">Alügynökök: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Ez a modell egyszerre csak egy kérést szolgál ki: az alügynököknek másik modell kell, másik szerveren, a csevegésben megnevezve.</string>
|
||||
<string name="thinking_switch">Gondolkodjon válasz előtt</string>
|
||||
<string name="level_off">ki</string>
|
||||
<string name="level_default">alapértelmezett</string>
|
||||
<string name="chats_open">Csevegések megnyitása</string>
|
||||
<string name="chats_search">Keresés a csevegésekben</string>
|
||||
<string name="chats_today">Ma</string>
|
||||
<string name="chats_earlier">Korábban</string>
|
||||
<string name="chats_agents">Ügynök-csevegések</string>
|
||||
<string name="chats_found_in_messages">Az üzenetekben</string>
|
||||
<string name="chats_none_found">Egy csevegés címében sincs ilyen.</string>
|
||||
<string name="clear">Törlés</string>
|
||||
<string name="composer_hint_agent">Mondja meg az ügynöknek, mit tegyen</string>
|
||||
<string name="tune">Beállítások</string>
|
||||
<string name="effort">Ráfordítás</string>
|
||||
<string name="thinking_switch_hint">Lassabb, de jobb a nehéz kérdéseknél.</string>
|
||||
<string name="plan_first">Előbb terv</string>
|
||||
<string name="plan_first_hint">A modell tervet ír, amelyet jóváhagy, mielőtt cselekszik.</string>
|
||||
<string name="agent_mode">Mód</string>
|
||||
<string name="agent_greeting">Mit tegyen az ügynök?</string>
|
||||
<string name="agent_runs_on">Itt fut: %1$s, ebben: %2$s</string>
|
||||
<string name="agent_directory_default">az első mappája</string>
|
||||
<string name="kind_chat">Csevegés</string>
|
||||
<string name="kind_agent">Ügynök-csevegés</string>
|
||||
<string name="kind_chat_line">Beszélgessen egy modellel: kérdések, írás, a csatolt fájlok.</string>
|
||||
<string name="kind_agent_line">Egy összekapcsolt számítógépen dolgozik: olvas, ír és parancsokat futtat egy mappában.</string>
|
||||
<string name="agent_link_title">Előbb kapcsoljon össze egy számítógépet</string>
|
||||
<string name="agent_link_lede">Az ügynök-csevegések olyan gépen futnak, amelyen a LLeMbas CLI be van jelentkezve ebbe a példányba, és össze van kapcsolva. Most egy sincs összekapcsolva.</string>
|
||||
<string name="agent_link_install">Telepítse rá a LLeMbas CLI-t:</string>
|
||||
<string name="agent_link_login">Jelentkeztesse be ebbe a példányba, és hagyja jóvá a megjelenő kódot a megnyíló böngészőben:</string>
|
||||
<string name="agent_link_service">Ha innen szeretne ügynök-csevegéseket futtatni rajta, engedélyezze a konfigurációjában (~/.config/lembas/config.yaml), és indítsa el a szolgáltatást:</string>
|
||||
<string name="agent_link_dials_out">Ő hívja fel ezt a példányt; az Ön gépén semmi sem figyel. Ő dönti el, mely könyvtárakat és üzemmódokat használhatja a távoli munka, bármit is kérnek itt.</string>
|
||||
<string name="agent_link_check">Újraellenőrzés</string>
|
||||
<string name="model_choose">Modell kiválasztása</string>
|
||||
<string name="model_in_use">Használatban</string>
|
||||
<string name="model_sees_images">Látja a képeket</string>
|
||||
<string name="model_uses_tools">Eszközöket használ</string>
|
||||
<string name="model_context">%1$s kontextus</string>
|
||||
<string name="model_thinking_switchable">Gondolkodás be- vagy kikapcsolva</string>
|
||||
<string name="model_levels">Ráfordítás: %1$s</string>
|
||||
<string name="code">Kód</string>
|
||||
<string name="copy_code">Kód másolása</string>
|
||||
<string name="select_text">Szöveg kijelölése</string>
|
||||
<string name="tools_used">%1$s eszköz használva</string>
|
||||
<string name="suggest_explain">Magyarázd el,</string>
|
||||
<string name="suggest_explain_line">hogyan működik valami, egyszerűen</string>
|
||||
<string name="suggest_write">Írj</string>
|
||||
<string name="suggest_write_line">e-mailt, jegyzetet vagy bejegyzést</string>
|
||||
<string name="suggest_plan">Tervezz meg</string>
|
||||
<string name="suggest_plan_line">egy utat, egy hetet vagy egy projektet</string>
|
||||
<string name="suggest_check">Ellenőrizz</string>
|
||||
<string name="suggest_check_line">egy szöveget: hibák és hangnem</string>
|
||||
<string name="instance_in_use">Használatban</string>
|
||||
<string name="notification_settings">Értesítési beállítások</string>
|
||||
<string name="notification_settings_hint">Milyen értesítések jönnek és hogyan: válaszok, kérdések, ütemezett eredmények és hibák.</string>
|
||||
<string name="scheduled">Ütemezett</string>
|
||||
<string name="scheduled_empty">Nincs semmi ütemezve. Kérjen valamit minden reggelre, vagy egyszer a jövő hétre.</string>
|
||||
<string name="scheduled_unsupported">Ez a példány még nem kínál ütemezett feladatokat. Egy újabb LLeMbas-szal érkeznek a szerveren.</string>
|
||||
<string name="schedule_new">Új ütemezés</string>
|
||||
<string name="schedule_edit">Ütemezés szerkesztése</string>
|
||||
<string name="schedule_next">Következő: %1$s</string>
|
||||
<string name="schedule_paused">Szüneteltetve</string>
|
||||
<string name="schedule_pause">Szüneteltetés</string>
|
||||
<string name="schedule_resume">Folytatás</string>
|
||||
<string name="schedule_run_now">Futtatás most</string>
|
||||
<string name="schedule_started">Elindítva. Az eredmény az előzményekben jelenik meg.</string>
|
||||
<string name="schedule_next_runs">Következő futások</string>
|
||||
<string name="schedule_history">Előzmények</string>
|
||||
<string name="schedule_no_runs">Még nem futott.</string>
|
||||
<string name="schedule_model">Modell: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Törli ezt az ütemezést? A korábbi eredményei megmaradnak a csevegéseikben.</string>
|
||||
<string name="schedule_words_hint">Mondja el saját szavaival, mikor és mit. Mentés előtt látja, mit értett meg belőle.</string>
|
||||
<string name="schedule_words_example">Minden hétköznap 7:30-kor foglald össze a megújuló energiáról szóló híreket</string>
|
||||
<string name="schedule_preview">Előnézet</string>
|
||||
<string name="schedule_understood">Így értelmezve</string>
|
||||
<string name="notify_always">Mindig szól</string>
|
||||
<string name="notify_matters">Szól, ha számít</string>
|
||||
<string name="notify_never">Soha nem szól</string>
|
||||
<string name="run_ok">Kész</string>
|
||||
<string name="run_silent">Semmi új</string>
|
||||
<string name="run_unchanged">Változatlan</string>
|
||||
<string name="schedule_computer">Számítógép</string>
|
||||
<string name="schedule_computer_away">most nincs összekapcsolva</string>
|
||||
<string name="schedule_watching">Csak ha ez az oldal megváltozik</string>
|
||||
<string name="schedule_watching_command">Csak ha ennek a parancsnak a kimenete változik</string>
|
||||
<string name="run_failed">Sikertelen</string>
|
||||
<string name="run_missed">Kimaradt ×%1$s</string>
|
||||
<string name="run_skipped">Kihagyva</string>
|
||||
<string name="run_waiting">Modellre vár</string>
|
||||
<string name="run_waiting_computer">Várakozás a számítógépre</string>
|
||||
<string name="run_running">Fut</string>
|
||||
<string name="run_model_instead">%1$s, %2$s helyett</string>
|
||||
<string name="run_retry_at">Újrapróbálja: %1$s</string>
|
||||
<string name="run_result">Eredmény</string>
|
||||
<string name="run_no_text">Ez a futás nem hagyott szöveget.</string>
|
||||
<string name="run_open_chat">Csevegésének megnyitása</string>
|
||||
<string name="mode_fresh">Minden alkalommal új csevegés</string>
|
||||
<string name="mode_continue">Egy csevegés, amely bővül</string>
|
||||
<string name="schedule_models">Modellek az ütemezett feladatokhoz</string>
|
||||
<string name="schedule_models_hint">Az ütemezett feladatok ebben a sorrendben az első szabadot veszik. Vegye ki a pipát, hogy kihagyjon egyet.</string>
|
||||
<string name="model_free">Most szabad</string>
|
||||
<string name="model_busy">Foglalt: %1$s</string>
|
||||
<string name="channel_scheduled">Ütemezett eredmények</string>
|
||||
<string name="channel_scheduled_failures">Ütemezett hibák</string>
|
||||
<string name="scheduled_result_public">Egy ütemezett feladatnak eredménye van.</string>
|
||||
<string name="scheduled_failed_public">Egy ütemezett feladat sikertelen volt.</string>
|
||||
<string name="schedule_run_again">Futtatás újra</string>
|
||||
<string name="card_approval">Engedélyezzük ezt?</string>
|
||||
<string name="card_allow_once">Engedélyezés egyszer</string>
|
||||
<string name="card_allow_always">Ennek mindig engedélyezése</string>
|
||||
@@ -54,10 +254,66 @@
|
||||
<string name="card_answer">Az Ön válasza</string>
|
||||
<string name="card_something_else">Valami más</string>
|
||||
<string name="card_send">Küldés</string>
|
||||
<string name="progress_queued">Sorban áll</string>
|
||||
<string name="progress_queued_ahead">Sorban áll: %1$s van előtte</string>
|
||||
<string name="progress_waiting_for_model">Várakozás a(z) %1$s modellre: %2$s</string>
|
||||
<string name="progress_loading_model">%1$s betöltése</string>
|
||||
<string name="progress_reading_prompt">A prompt olvasása: %1$s / %2$s token (%3$s%%)</string>
|
||||
<string name="progress_reading_prompt_bare">A prompt olvasása</string>
|
||||
<string name="progress_thinking">Gondolkodás</string>
|
||||
<string name="progress_writing">Írás: %1$s token/s</string>
|
||||
<string name="progress_writing_bare">Írás</string>
|
||||
<string name="progress_running_tool">%1$s futtatása: %2$s</string>
|
||||
<string name="progress_running_tool_bare">%1$s futtatása</string>
|
||||
<string name="progress_waiting_for_person">Rád vár: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Az alügynökökre vár: %1$s dolgozik</string>
|
||||
<string name="progress_compacting">A beszélgetés tömörítése</string>
|
||||
<string name="progress_retrying">Újrapróbálás %1$s mp múlva: %2$s</string>
|
||||
<string name="progress_stopped">Leállítva</string>
|
||||
<string name="progress_stopped_reason">Leállítva: %1$s</string>
|
||||
<string name="progress_failed">Sikertelen: %1$s</string>
|
||||
<string name="progress_reason_busy">egyszerre egy kérést szolgál ki, és éppen egy másikat válaszol meg</string>
|
||||
<string name="progress_reason_slots">minden helye foglalt</string>
|
||||
<string name="progress_reason_group">a szervere most egy másik modellt tart betöltve</string>
|
||||
<string name="progress_what_approval">engedélyezed ezt: %1$s?</string>
|
||||
<string name="progress_what_approval_bare">egy jóváhagyás</string>
|
||||
<string name="progress_what_question">egy kérdés</string>
|
||||
<string name="progress_what_plan">a terv</string>
|
||||
<string name="progress_stopped_person">általad</string>
|
||||
<string name="progress_stopped_steps">lépéskorlát</string>
|
||||
<string name="progress_stopped_budget">keret</string>
|
||||
<string name="tree_state_working">dolgozik</string>
|
||||
<string name="tree_state_waiting">szabad helyre vár</string>
|
||||
<string name="tree_state_finished">kész</string>
|
||||
<string name="tree_state_idle">tétlen</string>
|
||||
<string name="tree_state_paused">szüneteltetve: tele a kontextus</string>
|
||||
<string name="tree_state_done">kész</string>
|
||||
<string name="tree_state_out_of_context">elfogyott a kontextus</string>
|
||||
<string name="tree_state_stopped">leállítva</string>
|
||||
<string name="tree_context">%1$s%% kontextus</string>
|
||||
<string name="tree_open_slots">Szabad helyek: %1$s</string>
|
||||
<string name="subagents_device_cannot">A számítógép, amelyen ez a beszélgetés fut, nem futtat alügynököket: frissítsd rajta a LLeMbas CLI-t.</string>
|
||||
<string name="card_asker">%1$s kérdezi:</string>
|
||||
<string name="card_subagent_asks">A(z) %1$s alügynök (%2$s), %3$s, kérdezi:</string>
|
||||
<string name="card_it_says">Ezt mondja: %1$s</string>
|
||||
<string name="card_change_before">Módosítás futtatás előtt</string>
|
||||
<string name="card_edit_runs">Az Engedélyezés azt futtatja, ami a mezőben van. Nem ellenőrizzük újra a csevegés szabályai szerint – ezt Ön írta be.</string>
|
||||
<string name="plan_approve">Terv jóváhagyása</string>
|
||||
<string name="plan_revise">Átdolgozás</string>
|
||||
<string name="plan_what_to_change">Mi változzon?</string>
|
||||
<string name="plan_carry_out">Terv végrehajtása</string>
|
||||
<string name="shown">Megjelenítve</string>
|
||||
<string name="viewer_open">Megnyitás</string>
|
||||
<string name="viewer_open_browser">Megnyitás a böngészőben</string>
|
||||
<string name="viewer_copy">Másolás</string>
|
||||
<string name="viewer_html_source">Ez az oldal forráskódja. Magát az oldalt a böngészőben megnyitva láthatja.</string>
|
||||
<string name="viewer_long_markdown">Hosszú fájl, ezért egyszerű szövegként jelenik meg.</string>
|
||||
<string name="viewer_unavailable">Ez a szerver még nem tudja átadni a fájlt az alkalmazásnak. Nyissa meg inkább a böngészőben.</string>
|
||||
<string name="viewer_too_large">Ez a fájl túl nagy a megjelenítéshez; legfeljebb 1 MB jeleníthető meg.</string>
|
||||
<string name="viewer_not_text">Ez nem szövegfájl, ezért itt nem jelenik meg.</string>
|
||||
<string name="files">Fájlok</string>
|
||||
<string name="files_all">Minden fájl</string>
|
||||
<string name="files_empty">Itt még nincs semmi. Még egy hobbitlyuk sem.</string>
|
||||
<string name="settings">Beállítások</string>
|
||||
<string name="settings_instances">Példányok</string>
|
||||
<string name="sign_out">Kijelentkezés</string>
|
||||
@@ -66,6 +322,13 @@
|
||||
<string name="theme_system">A rendszer szerint</string>
|
||||
<string name="theme_moria">Moria (sötét)</string>
|
||||
<string name="theme_shire">Shire (világos)</string>
|
||||
<string name="settings_language">Nyelv</string>
|
||||
<string name="language_hint">Csak a felület. A modellek azon a nyelven válaszolnak, amelyen ír nekik, függetlenül ettől a beállítástól.</string>
|
||||
<string name="language_account">Ugyanaz, mint a fiókomé</string>
|
||||
<string name="language_account_is">Ugyanaz, mint a fiókomé: %1$s</string>
|
||||
<string name="language_account_unknown">Még nincs beolvasva a példányáról</string>
|
||||
<string name="language_phone">A telefon nyelve</string>
|
||||
<string name="language_phone_is">A telefon nyelve: %1$s</string>
|
||||
<string name="settings_notifications">Értesítések</string>
|
||||
<string name="push_explained">Az értesítések a UnifiedPush-on keresztül érkeznek, Google-szolgáltatások nélkül: az Ön által választott elosztó alkalmazás szállítja őket, titkosítva, csak ehhez a telefonhoz.</string>
|
||||
<string name="push_no_distributor">Hogy értesítést kapjon, amikor egy válasz elkészül, telepítsen egy UnifiedPush-elosztót, például az ntfy-t, majd jöjjön vissza ide. Ha nincs ilyen, az alkalmazás csak akkor mutatja az új válaszokat, amikor meg van nyitva.</string>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Nem választottak elosztót, így az értesítések továbbra is ki vannak kapcsolva.</string>
|
||||
<string name="channel_replies">Válaszok</string>
|
||||
<string name="channel_asks">Kérdések és jóváhagyások</string>
|
||||
<string name="channel_reports">Jelentések</string>
|
||||
<string name="settings_assistant">Asszisztens</string>
|
||||
<string name="assistant_explained">Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.</string>
|
||||
<string name="assistant_open_settings">Asszisztens beállításainak megnyitása</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<string name="update_allow_installs">Engedélyezze, hogy az LLeMbas frissítéseket telepítsen, majd ellenőrizze újra.</string>
|
||||
<string name="update_bad_file">A letöltés nem egyezett a verzióval, és el lett dobva.</string>
|
||||
<string name="update_installing">%1$s telepítése…</string>
|
||||
<string name="update_checking">Ellenőrzés…</string>
|
||||
<string name="update_available">Elérhető a(z) %1$s. Koppintson a kiadás oldalának megnyitásához.</string>
|
||||
<string name="update_install">%1$s telepítése</string>
|
||||
<string name="update_auto">Új verziók keresése</string>
|
||||
<string name="update_auto_line">Naponta legfeljebb egyszer, induláskor az alkalmazás megkérdezi a példányát, melyik kiadás illik hozzá (régebbi példánynál a GitHubon lévő kiadások listáját olvassa be), és értesítésben jelzi, ha van újabb. Önről semmi nem megy máshová. Béta verzióban alapból bekapcsolva, egyébként kikapcsolva.</string>
|
||||
<string name="update_betas">Béták is</string>
|
||||
<string name="update_betas_line">Tesztverziók felajánlása is, nem csak kiadásoké. Alapból bekapcsolva, ha ez az alkalmazás maga is béta.</string>
|
||||
<string name="channel_updates">Alkalmazásfrissítések</string>
|
||||
<string name="update_notice_title">LLeMbas Androidra %1$s</string>
|
||||
<string name="update_notice_text">Újabb verzió érhető el. Koppintson a kiadás oldalának megnyitásához.</string>
|
||||
<string name="assist_hint">Kérdezzen bármit</string>
|
||||
<string name="assist_include_screen">Képernyő hozzáadása</string>
|
||||
<string name="assist_signed_out">Először jelentkezzen be egy LLeMbas példányba az alkalmazásban.</string>
|
||||
<string name="assist_open_app">Alkalmazás megnyitása</string>
|
||||
<string name="assist_open_in_app">Folytatás az alkalmazásban</string>
|
||||
<string name="assist_use_screen">Képernyő használata</string>
|
||||
<string name="assist_screen_both">A képernyő szövege és egy képernyőkép a következő kérdésével megy.</string>
|
||||
<string name="assist_screen_text">A képernyő szövege a következő kérdésével megy.</string>
|
||||
<string name="assist_screen_shot">Egy képernyőkép a következő kérdésével megy.</string>
|
||||
<string name="assist_quick_summarise">Összefoglalás</string>
|
||||
<string name="assist_quick_summarise_prompt">Foglald össze, mi van a képernyőmön.</string>
|
||||
<string name="assist_quick_translate">Fordítás</string>
|
||||
<string name="assist_quick_translate_prompt">Fordítsd le magyarra, ami a képernyőmön van.</string>
|
||||
<string name="assist_quick_explain">Magyarázat</string>
|
||||
<string name="assist_quick_explain_prompt">Magyarázd el, mi van a képernyőmön.</string>
|
||||
<string name="assist_continue">Az utolsó csevegés folytatása</string>
|
||||
<string name="assist_help">Tartsa lenyomva a bekapcsológombot, hogy bármely alkalmazás fölött megnyissa az asszisztenst, vagy használja a Gyorsbeállítások csempét.</string>
|
||||
<string name="assist_no_wake_word">Ébresztőszó nincs: a gyári Androidon az ébresztőszó figyelése a telefonba épített asszisztensé.</string>
|
||||
<string name="assist_connecting">Csatlakozás…</string>
|
||||
<string name="assist_offline">%1$s nem érhető el</string>
|
||||
<string name="assist_no_model">Nincs modell</string>
|
||||
<string name="assist_voice_reply_on">A hangos válasz be van kapcsolva</string>
|
||||
<string name="assist_voice_reply_off">A hangos válasz ki van kapcsolva</string>
|
||||
<string name="assist_read_aloud">Felolvasás</string>
|
||||
<string name="assist_stop_reading">Felolvasás leállítása</string>
|
||||
<string name="assist_answer_in_app">Ez a válasz az Ön döntésére vár: nyissa meg az alkalmazásban.</string>
|
||||
<string name="assist_send_now">Amit mondtam, küldés</string>
|
||||
<string name="assist_say_it">Mondja, aztán tartson szünetet</string>
|
||||
<string name="assist_type">Inkább gépelés</string>
|
||||
<string name="assist_writing_down">Lejegyzem, amit mondott…</string>
|
||||
<string name="assist_recogniser_failed">A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt.</string>
|
||||
<string name="assistant_listens">Hallgatás indítása az asszisztens megnyitásakor</string>
|
||||
<string name="voice_input">Hangbevitel</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">A példánya beszédfelismerése, a szerveren át. A felvétel a példányához megy, máshová nem.</string>
|
||||
<string name="voice_input_phone">Telefon (Google vagy a rendszeré)</string>
|
||||
<string name="voice_input_phone_line">A telefon saját beszédfelismerője. A szavak beszéd közben jelennek meg; a felvétel oda megy, ahová az a felismerő küldi.</string>
|
||||
<string name="voice_input_phone_none">Ennek a telefonnak nincs saját beszédfelismerője.</string>
|
||||
<string name="voice_input_hint">Az asszisztens és a csevegés mikrofonja használja. LLeMbasszal az asszisztens kis késéssel mutatja a szavakat, és egy szünet elküldi őket, a csevegés pedig akkor írja le őket, amikor abbahagyja; a telefon felismerőjével beszéd közben jelennek meg.</string>
|
||||
<string name="share_sending">Küldés az LLeMbas-nak…</string>
|
||||
<string name="share_default_prompt">Nézze meg ezt.</string>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Apri nel browser</string>
|
||||
<string name="signin_denied">L\'accesso è stato rifiutato.</string>
|
||||
<string name="signin_expired">Il codice è scaduto prima di essere approvato. Riprova.</string>
|
||||
<string name="signin_too_old">Questa istanza non ha ancora un\'API per l\'app. Richiede LLeMbas 1.7.0 o una versione più recente.</string>
|
||||
<string name="signin_too_old">Questa istanza usa una versione precedente di LLeMbas. Questa app richiede LLeMbas 2.0 o successivo.</string>
|
||||
<string name="signin_too_new">Questa istanza usa un\'API per l\'app più recente di questa app. Aggiorna l\'app.</string>
|
||||
<string name="new_chat">Nuova chat</string>
|
||||
<string name="tab_chats">Chat</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.</string>
|
||||
<string name="empty_agents">Nessuna chat agente. Avviane una dall\'interfaccia web su un dispositivo collegato.</string>
|
||||
<string name="new_agent_chat">Nuova chat agente</string>
|
||||
<string name="agent_device">Dispositivo</string>
|
||||
<string name="agent_no_device">Nessun dispositivo è collegato ora. Avvia `lembas service` su un computer connesso a questa istanza, poi torna qui.</string>
|
||||
<string name="agent_directory">Cartella sul dispositivo</string>
|
||||
<string name="agent_directory_hint">Vuoto: la prima cartella del dispositivo</string>
|
||||
<string name="empty_chat">Di cosa parliamo?</string>
|
||||
<string name="loading_line">I lembas stanno cuocendo…</string>
|
||||
<string name="archive">Archivia</string>
|
||||
<string name="archived">Archiviate</string>
|
||||
<string name="archived_restore">Ripristina chat</string>
|
||||
<string name="archived_none">Nessuna chat archiviata.</string>
|
||||
<string name="memory">Memoria</string>
|
||||
<string name="memory_intro">Cosa ricordano di te i modelli</string>
|
||||
<string name="memory_none">Ancora niente. Un modello con lo strumento memoria aggiunge qualcosa qui quando gli dici qualcosa che vale la pena ricordare.</string>
|
||||
<string name="memory_remember">Ricorda</string>
|
||||
<string name="memory_label">Cosa dice questa memoria</string>
|
||||
<string name="memory_hint">Qualcosa che vale la pena ricordare</string>
|
||||
<string name="memory_group">Gruppo di dati</string>
|
||||
<string name="memory_forget">Dimentica</string>
|
||||
<string name="memory_by_model">Modello</string>
|
||||
<string name="chats_pinned">Chat fissate</string>
|
||||
<string name="chat_pin">Fissa la chat</string>
|
||||
<string name="chat_unpin">Togli la chat dalle fissate</string>
|
||||
<string name="folder_move">Sposta nella cartella</string>
|
||||
<string name="folder_none">Nessuna cartella</string>
|
||||
<string name="folder_new">Nuova cartella</string>
|
||||
<string name="folder_name">Nome della cartella</string>
|
||||
<string name="folder_rename">Rinomina cartella</string>
|
||||
<string name="folder_delete">Elimina cartella</string>
|
||||
<string name="folder_delete_confirm">Eliminare la cartella “%1$s”? Le chat al suo interno vengono conservate.</string>
|
||||
<string name="delete">Elimina</string>
|
||||
<string name="edit">Modifica</string>
|
||||
<string name="regenerate">Rigenera</string>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Invia</string>
|
||||
<string name="stop">Ferma</string>
|
||||
<string name="attach">Allega un file</string>
|
||||
<string name="attach_take_photo">Scatta una foto</string>
|
||||
<string name="attach_choose_photos">Scegli foto</string>
|
||||
<string name="attach_choose_files">Scegli file</string>
|
||||
<string name="image_generate">Generare immagini</string>
|
||||
<string name="image_generated">L\'immagine generata</string>
|
||||
<string name="copy_message">Copia messaggio</string>
|
||||
<string name="copied">Copiato.</string>
|
||||
<string name="rename_chat">Rinomina chat</string>
|
||||
<string name="save">Salva</string>
|
||||
<string name="retry">Riprova</string>
|
||||
<string name="offline">L\'istanza non è raggiungibile. Controlla la connessione del telefono e che raggiunga l\'indirizzo dell\'istanza.</string>
|
||||
<string name="dictate">Detta</string>
|
||||
<string name="remove">Rimuovi</string>
|
||||
<string name="more">Altro</string>
|
||||
<string name="back">Indietro</string>
|
||||
<string name="cancel">Annulla</string>
|
||||
<string name="close">Chiudi</string>
|
||||
<string name="effort_off">Impegno: disattivato</string>
|
||||
<string name="mode_plan">Piano</string>
|
||||
<string name="mode_edit">Modifica</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Manuale</string>
|
||||
<string name="mode_auto">Automatico</string>
|
||||
<string name="activity">Attività</string>
|
||||
<string name="activity_open">Apri il pannello attività</string>
|
||||
<string name="activity_context">Contesto</string>
|
||||
<string name="activity_outputs">Risultati</string>
|
||||
<string name="activity_tasks">Attività in background</string>
|
||||
<string name="activity_used">%1$s%% usato</string>
|
||||
<string name="activity_window_unknown">finestra sconosciuta</string>
|
||||
<string name="activity_not_measured">Non misurato.</string>
|
||||
<string name="activity_measured">Contato dal modello all’ultima risposta; le categorie sono stime.</string>
|
||||
<string name="activity_estimated">Stima: nessuna risposta è stata ancora contata.</string>
|
||||
<string name="activity_tools_offered">%1$s strumenti offerti.</string>
|
||||
<string name="ctx_messages">Messaggi</string>
|
||||
<string name="ctx_system">Prompt di sistema</string>
|
||||
<string name="ctx_memory">Memoria e dati personali</string>
|
||||
<string name="ctx_instructions">File di istruzioni</string>
|
||||
<string name="ctx_tools">Strumenti</string>
|
||||
<string name="ctx_mcp_tools">Strumenti MCP</string>
|
||||
<string name="ctx_since">Dall’ultima risposta</string>
|
||||
<string name="ctx_buffer">Riserva per la compattazione</string>
|
||||
<string name="ctx_free">Spazio libero</string>
|
||||
<string name="tasks_empty">Niente in background. Sottoagenti, comandi e membri di un team compaiono qui mentre lavorano.</string>
|
||||
<string name="tasks_none_running">Nulla in esecuzione.</string>
|
||||
<string name="tasks_running">In esecuzione</string>
|
||||
<string name="tasks_finished">Terminate</string>
|
||||
<string name="tasks_n_running">%1$s in corso</string>
|
||||
<string name="tasks_nested">%1$s sotto</string>
|
||||
<string name="task_subagent">Sottoagente</string>
|
||||
<string name="task_command">Comando</string>
|
||||
<string name="task_member">Membro del team</string>
|
||||
<string name="activity_until_compact">%1$s alla compattazione automatica</string>
|
||||
<string name="activity_compact_off">La compattazione automatica è disattivata.</string>
|
||||
<string name="activity_compact">Compatta</string>
|
||||
<string name="agents_n_queued">%1$s in coda</string>
|
||||
<string name="agents_n_waiting">%1$s in attesa</string>
|
||||
<string name="agents_n_finished">%1$s terminati</string>
|
||||
<string name="agent_state_queued">in coda</string>
|
||||
<string name="agent_state_working">al lavoro</string>
|
||||
<string name="agent_state_waiting">in attesa</string>
|
||||
<string name="agent_state_done">finito</string>
|
||||
<string name="agent_state_stopped">interrotto</string>
|
||||
<string name="agent_state_error">fallito</string>
|
||||
<string name="agent_steps">%1$s passi, %2$s strumenti</string>
|
||||
<string name="agent_open_conversation">Apri la sua conversazione</string>
|
||||
<string name="agent_stop">Ferma %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Fermare %1$s e i membri sotto di lui? Lasciano la squadra.</string>
|
||||
<string name="agent_stop_confirm">Fermare %1$s? Ciò che ha fatto finora resta.</string>
|
||||
<string name="agent_nothing_yet">Non ha ancora detto nulla.</string>
|
||||
<string name="agent_machine">Dal sistema</string>
|
||||
<string name="team_size">Team: %1$s di %2$s sottoagenti</string>
|
||||
<string name="team_room">Stanza</string>
|
||||
<string name="room_empty">Nella stanza non è ancora stato detto nulla.</string>
|
||||
<string name="room_report">resoconto</string>
|
||||
<string name="team_agents">Sottoagenti</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">I numeri contano l\'agente di questa chat: 1 è l\'agente da solo, senza sottoagenti, e Max 4 è l\'agente più fino a 3 sottoagenti che guida.</string>
|
||||
<string name="team_chip">Sottoagenti: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Questo modello serve una sola richiesta alla volta: i sottoagenti hanno bisogno di un altro modello, su un altro server, nominato nella chat.</string>
|
||||
<string name="thinking_switch">Ragiona prima di rispondere</string>
|
||||
<string name="level_off">disattivato</string>
|
||||
<string name="level_default">predefinito</string>
|
||||
<string name="chats_open">Apri le chat</string>
|
||||
<string name="chats_search">Cerca nelle chat</string>
|
||||
<string name="chats_today">Oggi</string>
|
||||
<string name="chats_earlier">Prima</string>
|
||||
<string name="chats_agents">Chat con agente</string>
|
||||
<string name="chats_found_in_messages">Nei messaggi</string>
|
||||
<string name="chats_none_found">Nessuna chat lo ha nel titolo.</string>
|
||||
<string name="clear">Svuota</string>
|
||||
<string name="composer_hint_agent">Di’ all’agente cosa fare</string>
|
||||
<string name="tune">Opzioni</string>
|
||||
<string name="effort">Impegno</string>
|
||||
<string name="thinking_switch_hint">Più lento, e migliore con le domande difficili.</string>
|
||||
<string name="plan_first">Prima un piano</string>
|
||||
<string name="plan_first_hint">Il modello scrive un piano da approvare prima di agire.</string>
|
||||
<string name="agent_mode">Modalità</string>
|
||||
<string name="agent_greeting">Cosa deve fare l’agente?</string>
|
||||
<string name="agent_runs_on">Gira su %1$s, in %2$s</string>
|
||||
<string name="agent_directory_default">la sua prima cartella</string>
|
||||
<string name="kind_chat">Chat</string>
|
||||
<string name="kind_agent">Chat agente</string>
|
||||
<string name="kind_chat_line">Parli con un modello: domande, scrittura, i file che allega.</string>
|
||||
<string name="kind_agent_line">Lavora su un computer che ha collegato: legge, scrive ed esegue comandi in una cartella.</string>
|
||||
<string name="agent_link_title">Prima colleghi un computer</string>
|
||||
<string name="agent_link_lede">Le chat agente girano su una macchina con la LLeMbas CLI, connessa a questa istanza e collegata. Al momento non ce n\'è nessuna collegata.</string>
|
||||
<string name="agent_link_install">Installa la LLeMbas CLI sulla macchina:</string>
|
||||
<string name="agent_link_login">Lo colleghi a questa istanza e approvi il codice che mostra nel browser che si apre:</string>
|
||||
<string name="agent_link_service">Per eseguirci chat agente da qui, consentilo nella sua configurazione (~/.config/lembas/config.yaml) e avvia il servizio:</string>
|
||||
<string name="agent_link_dials_out">È lei a collegarsi a questa istanza; sulla tua macchina non resta in ascolto nulla. Decide lei quali cartelle e modalità può usare il lavoro remoto, qualunque cosa venga chiesta qui.</string>
|
||||
<string name="agent_link_check">Controlla di nuovo</string>
|
||||
<string name="model_choose">Scegli un modello</string>
|
||||
<string name="model_in_use">In uso</string>
|
||||
<string name="model_sees_images">Vede le immagini</string>
|
||||
<string name="model_uses_tools">Usa strumenti</string>
|
||||
<string name="model_context">contesto di %1$s</string>
|
||||
<string name="model_thinking_switchable">Ragionamento attivabile</string>
|
||||
<string name="model_levels">Impegno: %1$s</string>
|
||||
<string name="code">Codice</string>
|
||||
<string name="copy_code">Copia codice</string>
|
||||
<string name="select_text">Seleziona testo</string>
|
||||
<string name="tools_used">Usati %1$s strumenti</string>
|
||||
<string name="suggest_explain">Spiega</string>
|
||||
<string name="suggest_explain_line">come funziona qualcosa, in parole semplici</string>
|
||||
<string name="suggest_write">Scrivi</string>
|
||||
<string name="suggest_write_line">un’email, una nota o un post</string>
|
||||
<string name="suggest_plan">Pianifica</string>
|
||||
<string name="suggest_plan_line">un viaggio, una settimana o un progetto</string>
|
||||
<string name="suggest_check">Controlla</string>
|
||||
<string name="suggest_check_line">un testo: errori e tono</string>
|
||||
<string name="instance_in_use">In uso</string>
|
||||
<string name="notification_settings">Impostazioni delle notifiche</string>
|
||||
<string name="notification_settings_hint">Quali tipi arrivano e come: risposte, domande, risultati e errori pianificati.</string>
|
||||
<string name="scheduled">Pianificato</string>
|
||||
<string name="scheduled_empty">Non c’è niente in programma. Chiedi qualcosa ogni mattina, o una volta la settimana prossima.</string>
|
||||
<string name="scheduled_unsupported">Questa istanza non offre ancora attività pianificate. Arrivano con un LLeMbas più recente sul server.</string>
|
||||
<string name="schedule_new">Nuova pianificazione</string>
|
||||
<string name="schedule_edit">Modifica pianificazione</string>
|
||||
<string name="schedule_next">Prossima: %1$s</string>
|
||||
<string name="schedule_paused">In pausa</string>
|
||||
<string name="schedule_pause">Metti in pausa</string>
|
||||
<string name="schedule_resume">Riprendi</string>
|
||||
<string name="schedule_run_now">Esegui ora</string>
|
||||
<string name="schedule_started">Avviato. Il risultato appare nella cronologia.</string>
|
||||
<string name="schedule_next_runs">Prossime esecuzioni</string>
|
||||
<string name="schedule_history">Cronologia</string>
|
||||
<string name="schedule_no_runs">Non è ancora stata eseguita.</string>
|
||||
<string name="schedule_model">Modello: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Eliminare questa pianificazione? I risultati passati restano nelle loro chat.</string>
|
||||
<string name="schedule_words_hint">Di’ quando e cosa, con parole tue. Vedrai cosa è stato capito prima di salvare.</string>
|
||||
<string name="schedule_words_example">Ogni giorno feriale alle 7:30, riassumi le notizie sulle energie rinnovabili</string>
|
||||
<string name="schedule_preview">Anteprima</string>
|
||||
<string name="schedule_understood">Capito come</string>
|
||||
<string name="notify_always">Avvisa ogni volta</string>
|
||||
<string name="notify_matters">Avvisa quando conta</string>
|
||||
<string name="notify_never">Non avvisa mai</string>
|
||||
<string name="run_ok">Fatto</string>
|
||||
<string name="run_silent">Niente di nuovo</string>
|
||||
<string name="run_unchanged">Invariato</string>
|
||||
<string name="schedule_computer">Computer</string>
|
||||
<string name="schedule_computer_away">non collegato ora</string>
|
||||
<string name="schedule_watching">Solo quando questa pagina cambia</string>
|
||||
<string name="schedule_watching_command">Solo quando cambia l\'output di questo comando</string>
|
||||
<string name="run_failed">Non riusciti</string>
|
||||
<string name="run_missed">Saltata ×%1$s</string>
|
||||
<string name="run_skipped">Ignorata</string>
|
||||
<string name="run_waiting">In attesa di un modello</string>
|
||||
<string name="run_waiting_computer">In attesa del computer</string>
|
||||
<string name="run_running">In esecuzione</string>
|
||||
<string name="run_model_instead">%1$s, invece di %2$s</string>
|
||||
<string name="run_retry_at">Riprova alle %1$s</string>
|
||||
<string name="run_result">Risultato</string>
|
||||
<string name="run_no_text">Questa esecuzione non ha lasciato testo.</string>
|
||||
<string name="run_open_chat">Apri la sua chat</string>
|
||||
<string name="mode_fresh">Una nuova chat ogni volta</string>
|
||||
<string name="mode_continue">Una chat che cresce</string>
|
||||
<string name="schedule_models">Modelli per le attività pianificate</string>
|
||||
<string name="schedule_models_hint">Le attività pianificate usano il primo di questi che è libero, in quest’ordine. Togli la spunta per escluderne uno.</string>
|
||||
<string name="model_free">Libero ora</string>
|
||||
<string name="model_busy">Occupato: %1$s</string>
|
||||
<string name="channel_scheduled">Risultati pianificati</string>
|
||||
<string name="channel_scheduled_failures">Errori pianificati</string>
|
||||
<string name="scheduled_result_public">Un’attività pianificata ha un risultato.</string>
|
||||
<string name="scheduled_failed_public">Un’attività pianificata non è riuscita.</string>
|
||||
<string name="schedule_run_again">Esegui di nuovo</string>
|
||||
<string name="card_approval">Consentire questo?</string>
|
||||
<string name="card_allow_once">Consenti una volta</string>
|
||||
<string name="card_allow_always">Consenti sempre questo</string>
|
||||
@@ -54,10 +254,66 @@
|
||||
<string name="card_answer">La tua risposta</string>
|
||||
<string name="card_something_else">Altro</string>
|
||||
<string name="card_send">Invia</string>
|
||||
<string name="progress_queued">In coda</string>
|
||||
<string name="progress_queued_ahead">In coda: %1$s davanti</string>
|
||||
<string name="progress_waiting_for_model">In attesa di %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Caricamento di %1$s</string>
|
||||
<string name="progress_reading_prompt">Lettura del prompt: %1$s / %2$s token (%3$s%%)</string>
|
||||
<string name="progress_reading_prompt_bare">Lettura del prompt</string>
|
||||
<string name="progress_thinking">Ragionamento</string>
|
||||
<string name="progress_writing">Scrittura: %1$s tok/s</string>
|
||||
<string name="progress_writing_bare">Scrittura</string>
|
||||
<string name="progress_running_tool">Esecuzione di %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Esecuzione di %1$s</string>
|
||||
<string name="progress_waiting_for_person">In attesa di te: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">In attesa dei subagenti: %1$s al lavoro</string>
|
||||
<string name="progress_compacting">Compattazione della conversazione</string>
|
||||
<string name="progress_retrying">Nuovo tentativo tra %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Fermato</string>
|
||||
<string name="progress_stopped_reason">Fermato: %1$s</string>
|
||||
<string name="progress_failed">Non riuscito: %1$s</string>
|
||||
<string name="progress_reason_busy">serve una richiesta alla volta e ne sta servendo un’altra</string>
|
||||
<string name="progress_reason_slots">tutti i suoi posti sono occupati</string>
|
||||
<string name="progress_reason_group">il suo server ha ora un altro modello</string>
|
||||
<string name="progress_what_approval">consentire %1$s?</string>
|
||||
<string name="progress_what_approval_bare">un’approvazione</string>
|
||||
<string name="progress_what_question">una domanda</string>
|
||||
<string name="progress_what_plan">il piano</string>
|
||||
<string name="progress_stopped_person">da te</string>
|
||||
<string name="progress_stopped_steps">limite di passi</string>
|
||||
<string name="progress_stopped_budget">budget</string>
|
||||
<string name="tree_state_working">al lavoro</string>
|
||||
<string name="tree_state_waiting">in attesa di un posto</string>
|
||||
<string name="tree_state_finished">finito</string>
|
||||
<string name="tree_state_idle">inattivo</string>
|
||||
<string name="tree_state_paused">in pausa: contesto pieno</string>
|
||||
<string name="tree_state_done">finito</string>
|
||||
<string name="tree_state_out_of_context">senza contesto</string>
|
||||
<string name="tree_state_stopped">interrotto</string>
|
||||
<string name="tree_context">%1$s%% del contesto</string>
|
||||
<string name="tree_open_slots">Posti liberi: %1$s</string>
|
||||
<string name="subagents_device_cannot">Il computer su cui gira questa chat non esegue subagenti: aggiorna lì LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s chiede:</string>
|
||||
<string name="card_subagent_asks">Il subagente %1$s (%2$s), %3$s, chiede:</string>
|
||||
<string name="card_it_says">Dice: %1$s</string>
|
||||
<string name="card_change_before">Modificalo prima che venga eseguito</string>
|
||||
<string name="card_edit_runs">Consenti esegue ciò che c\'è nel campo. Non viene ricontrollato rispetto alle regole di questa chat — l\'hai scritto tu.</string>
|
||||
<string name="plan_approve">Approva il piano</string>
|
||||
<string name="plan_revise">Rivedi</string>
|
||||
<string name="plan_what_to_change">Cosa dovrebbe cambiare?</string>
|
||||
<string name="plan_carry_out">Esegui il piano</string>
|
||||
<string name="shown">Mostrato</string>
|
||||
<string name="viewer_open">Apri</string>
|
||||
<string name="viewer_open_browser">Apri nel browser</string>
|
||||
<string name="viewer_copy">Copia</string>
|
||||
<string name="viewer_html_source">Questo è il sorgente della pagina. Aprila nel browser per vedere la pagina.</string>
|
||||
<string name="viewer_long_markdown">Un file lungo, quindi è mostrato come testo semplice.</string>
|
||||
<string name="viewer_unavailable">Questo server non può ancora passare il file all\'app. Aprilo invece nel browser.</string>
|
||||
<string name="viewer_too_large">Questo file è troppo grande da mostrare; si può mostrare al massimo 1 MB.</string>
|
||||
<string name="viewer_not_text">Non è un file di testo, quindi non viene mostrato qui.</string>
|
||||
<string name="files">File</string>
|
||||
<string name="files_all">Tutti i file</string>
|
||||
<string name="files_empty">Ancora niente qui. Nemmeno una caverna hobbit.</string>
|
||||
<string name="settings">Impostazioni</string>
|
||||
<string name="settings_instances">Istanze</string>
|
||||
<string name="sign_out">Esci</string>
|
||||
@@ -66,6 +322,13 @@
|
||||
<string name="theme_system">Come il sistema</string>
|
||||
<string name="theme_moria">Moria (scuro)</string>
|
||||
<string name="theme_shire">Shire (chiaro)</string>
|
||||
<string name="settings_language">Lingua</string>
|
||||
<string name="language_hint">Solo l\'interfaccia. I modelli rispondono nella lingua in cui scrivi loro, qualunque cosa dica questa impostazione.</string>
|
||||
<string name="language_account">Come il mio account</string>
|
||||
<string name="language_account_is">Come il mio account: %1$s</string>
|
||||
<string name="language_account_unknown">Non ancora letta dalla sua istanza</string>
|
||||
<string name="language_phone">Lingua del telefono</string>
|
||||
<string name="language_phone_is">Lingua del telefono: %1$s</string>
|
||||
<string name="settings_notifications">Notifiche</string>
|
||||
<string name="push_explained">Le notifiche arrivano tramite UnifiedPush, senza servizi Google: l\'app di distribuzione che hai scelto le trasporta, cifrate solo per questo telefono.</string>
|
||||
<string name="push_no_distributor">Per essere avvisato quando una risposta è pronta, installa un distributore UnifiedPush come ntfy, poi torna qui. Senza uno, l\'app mostra le nuove risposte solo quando è aperta.</string>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Non è stato scelto nessun distributore, quindi le notifiche sono ancora disattivate.</string>
|
||||
<string name="channel_replies">Risposte</string>
|
||||
<string name="channel_asks">Domande e approvazioni</string>
|
||||
<string name="channel_reports">Report</string>
|
||||
<string name="settings_assistant">Assistente</string>
|
||||
<string name="assistant_explained">Rendi LLeMbas l\'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.</string>
|
||||
<string name="assistant_open_settings">Apri le impostazioni dell\'assistente</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<string name="update_allow_installs">Consenti a LLeMbas di installare gli aggiornamenti, poi controlla di nuovo.</string>
|
||||
<string name="update_bad_file">Il download non corrispondeva alla versione ed è stato scartato.</string>
|
||||
<string name="update_installing">Installazione di %1$s…</string>
|
||||
<string name="update_checking">Controllo in corso…</string>
|
||||
<string name="update_available">%1$s è disponibile. Tocca per aprire la pagina della release.</string>
|
||||
<string name="update_install">Installa %1$s</string>
|
||||
<string name="update_auto">Cerca nuove versioni</string>
|
||||
<string name="update_auto_line">Al massimo una volta al giorno, all’avvio, l’app chiede alla sua istanza quale release le corrisponde (con un’istanza più vecchia, legge l’elenco delle release su GitHub) e la avvisa con una notifica quando ce n’è una più recente. Nulla su di lei viene inviato altrove. Attivo per impostazione predefinita in una beta, altrimenti disattivato.</string>
|
||||
<string name="update_betas">Includi le beta</string>
|
||||
<string name="update_betas_line">Offri anche le versioni di prova, non solo le release. Attivo per impostazione predefinita quando questa app è essa stessa una beta.</string>
|
||||
<string name="channel_updates">Aggiornamenti dell’app</string>
|
||||
<string name="update_notice_title">LLeMbas per Android %1$s</string>
|
||||
<string name="update_notice_text">È disponibile una versione più recente. Tocca per aprire la pagina della release.</string>
|
||||
<string name="assist_hint">Chiedi qualsiasi cosa</string>
|
||||
<string name="assist_include_screen">Includi lo schermo</string>
|
||||
<string name="assist_signed_out">Accedi prima a un\'istanza LLeMbas nell\'app.</string>
|
||||
<string name="assist_open_app">Apri l\'app</string>
|
||||
<string name="assist_open_in_app">Continua nell\'app</string>
|
||||
<string name="assist_use_screen">Usa lo schermo</string>
|
||||
<string name="assist_screen_both">Il testo dello schermo e uno screenshot accompagnano la sua prossima domanda.</string>
|
||||
<string name="assist_screen_text">Il testo dello schermo accompagna la sua prossima domanda.</string>
|
||||
<string name="assist_screen_shot">Uno screenshot accompagna la sua prossima domanda.</string>
|
||||
<string name="assist_quick_summarise">Riassumi</string>
|
||||
<string name="assist_quick_summarise_prompt">Riassumi cosa c’è sul mio schermo.</string>
|
||||
<string name="assist_quick_translate">Traduci</string>
|
||||
<string name="assist_quick_translate_prompt">Traduci in italiano cosa c’è sul mio schermo.</string>
|
||||
<string name="assist_quick_explain">Spiega</string>
|
||||
<string name="assist_quick_explain_prompt">Spiega cosa c’è sul mio schermo.</string>
|
||||
<string name="assist_continue">Continua l’ultima chat</string>
|
||||
<string name="assist_help">Tenga premuto il tasto di accensione per aprire l’assistente sopra qualsiasi app, oppure usi il riquadro delle Impostazioni rapide.</string>
|
||||
<string name="assist_no_wake_word">Non c’è una parola di attivazione: su Android standard, l’ascolto di una tale parola è riservato all’assistente integrato nel telefono.</string>
|
||||
<string name="assist_connecting">Connessione…</string>
|
||||
<string name="assist_offline">%1$s non è raggiungibile</string>
|
||||
<string name="assist_no_model">Nessun modello</string>
|
||||
<string name="assist_voice_reply_on">Risposta vocale attiva</string>
|
||||
<string name="assist_voice_reply_off">Risposta vocale disattivata</string>
|
||||
<string name="assist_read_aloud">Leggi ad alta voce</string>
|
||||
<string name="assist_stop_reading">Interrompi la lettura</string>
|
||||
<string name="assist_answer_in_app">Questa risposta attende una sua decisione: la apra nell’app.</string>
|
||||
<string name="assist_send_now">Invia ciò che ho detto</string>
|
||||
<string name="assist_say_it">Lo dica, poi faccia una pausa</string>
|
||||
<string name="assist_type">Scrivi invece</string>
|
||||
<string name="assist_writing_down">Trascrivo ciò che ha detto…</string>
|
||||
<string name="assist_recogniser_failed">Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale.</string>
|
||||
<string name="assistant_listens">Inizia ad ascoltare all’apertura dell’assistente</string>
|
||||
<string name="voice_input">Input vocale</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">La trascrizione della sua istanza, tramite il server. La registrazione va alla sua istanza e da nessun’altra parte.</string>
|
||||
<string name="voice_input_phone">Telefono (Google o quello di sistema)</string>
|
||||
<string name="voice_input_phone_line">Il riconoscimento vocale del telefono. Le parole appaiono mentre parla; la registrazione va dove la manda quel riconoscimento.</string>
|
||||
<string name="voice_input_phone_none">Questo telefono non ha un riconoscimento vocale proprio.</string>
|
||||
<string name="voice_input_hint">La usano l’assistente e il microfono di una chat. Con LLeMbas l’assistente mostra le parole con un attimo di ritardo e una pausa le invia, e una chat le scrive quando si ferma; con il riconoscimento del telefono appaiono mentre parla.</string>
|
||||
<string name="share_sending">Invio a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Dai un\'occhiata a questo.</string>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Otwórz w przeglądarce</string>
|
||||
<string name="signin_denied">Logowanie zostało odrzucone.</string>
|
||||
<string name="signin_expired">Kod wygasł, zanim został zatwierdzony. Spróbuj ponownie.</string>
|
||||
<string name="signin_too_old">Ta instancja nie ma jeszcze API aplikacji. Wymaga LLeMbas 1.7.0 lub nowszego.</string>
|
||||
<string name="signin_too_old">Ta instancja działa na starszym LLeMbas. Ta aplikacja wymaga LLeMbas 2.0 lub nowszego.</string>
|
||||
<string name="signin_too_new">Ta instancja używa nowszego API aplikacji niż ta aplikacja. Zaktualizuj aplikację.</string>
|
||||
<string name="new_chat">Nowy czat</string>
|
||||
<string name="tab_chats">Czaty</string>
|
||||
<string name="tab_agents">Agenci</string>
|
||||
<string name="empty_chats">Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.</string>
|
||||
<string name="empty_agents">Brak czatów agenta. Zacznij jeden z interfejsu webowego na połączonym urządzeniu.</string>
|
||||
<string name="new_agent_chat">Nowy czat agenta</string>
|
||||
<string name="agent_device">Urządzenie</string>
|
||||
<string name="agent_no_device">Żadne urządzenie nie jest teraz połączone. Uruchom `lembas service` na komputerze zalogowanym do tej instancji i wróć.</string>
|
||||
<string name="agent_directory">Folder na urządzeniu</string>
|
||||
<string name="agent_directory_hint">Puste: pierwszy folder urządzenia</string>
|
||||
<string name="empty_chat">O czym porozmawiamy?</string>
|
||||
<string name="loading_line">Lembasy się pieczą…</string>
|
||||
<string name="archive">Archiwizuj</string>
|
||||
<string name="archived">Zarchiwizowane</string>
|
||||
<string name="archived_restore">Przywróć czat</string>
|
||||
<string name="archived_none">Brak zarchiwizowanych czatów.</string>
|
||||
<string name="memory">Pamięć</string>
|
||||
<string name="memory_intro">Co modele pamiętają o użytkowniku</string>
|
||||
<string name="memory_none">Jeszcze nic. Model z narzędziem pamięci dodaje tu wpis, gdy usłyszy coś, co warto zachować.</string>
|
||||
<string name="memory_remember">Zapamiętaj</string>
|
||||
<string name="memory_label">Treść tego wspomnienia</string>
|
||||
<string name="memory_hint">Coś, co warto zapamiętać</string>
|
||||
<string name="memory_group">Grupa danych</string>
|
||||
<string name="memory_forget">Zapomnij</string>
|
||||
<string name="memory_by_model">Model</string>
|
||||
<string name="chats_pinned">Przypięte czaty</string>
|
||||
<string name="chat_pin">Przypnij czat</string>
|
||||
<string name="chat_unpin">Odepnij czat</string>
|
||||
<string name="folder_move">Przenieś do folderu</string>
|
||||
<string name="folder_none">Bez folderu</string>
|
||||
<string name="folder_new">Nowy folder</string>
|
||||
<string name="folder_name">Nazwa folderu</string>
|
||||
<string name="folder_rename">Zmień nazwę folderu</string>
|
||||
<string name="folder_delete">Usuń folder</string>
|
||||
<string name="folder_delete_confirm">Usunąć folder „%1$s”? Czaty w nim zostaną zachowane.</string>
|
||||
<string name="delete">Usuń</string>
|
||||
<string name="edit">Edytuj</string>
|
||||
<string name="regenerate">Wygeneruj ponownie</string>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Wyślij</string>
|
||||
<string name="stop">Zatrzymać</string>
|
||||
<string name="attach">Załącz plik</string>
|
||||
<string name="attach_take_photo">Zrób zdjęcie</string>
|
||||
<string name="attach_choose_photos">Wybierz zdjęcia</string>
|
||||
<string name="attach_choose_files">Wybierz pliki</string>
|
||||
<string name="image_generate">Generuj obrazy</string>
|
||||
<string name="image_generated">Wygenerowany obraz</string>
|
||||
<string name="copy_message">Kopiuj wiadomość</string>
|
||||
<string name="copied">Skopiowano.</string>
|
||||
<string name="rename_chat">Zmień nazwę czatu</string>
|
||||
<string name="save">Zapisz</string>
|
||||
<string name="retry">Spróbuj ponownie</string>
|
||||
<string name="offline">Instancja jest nieosiągalna. Sprawdź połączenie telefonu i czy dociera on do adresu instancji.</string>
|
||||
<string name="dictate">Dyktuj</string>
|
||||
<string name="remove">Usuń</string>
|
||||
<string name="more">Więcej</string>
|
||||
<string name="back">Wstecz</string>
|
||||
<string name="cancel">Anuluj</string>
|
||||
<string name="close">Zamknij</string>
|
||||
<string name="effort_off">Wysiłek: wyłączony</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edytuj</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Ręcznie</string>
|
||||
<string name="mode_auto">Automatycznie</string>
|
||||
<string name="activity">Aktywność</string>
|
||||
<string name="activity_open">Otwórz panel aktywności</string>
|
||||
<string name="activity_context">Kontekst</string>
|
||||
<string name="activity_outputs">Wyniki</string>
|
||||
<string name="activity_tasks">Zadania w tle</string>
|
||||
<string name="activity_used">Użyto: %1$s%%</string>
|
||||
<string name="activity_window_unknown">okno nieznane</string>
|
||||
<string name="activity_not_measured">Nie zmierzono.</string>
|
||||
<string name="activity_measured">Policzone przez model przy ostatniej odpowiedzi; kategorie są szacunkowe.</string>
|
||||
<string name="activity_estimated">Szacunek: żadna odpowiedź nie została jeszcze policzona.</string>
|
||||
<string name="activity_tools_offered">Oferowane narzędzia: %1$s.</string>
|
||||
<string name="ctx_messages">Wiadomości</string>
|
||||
<string name="ctx_system">Prompt systemowy</string>
|
||||
<string name="ctx_memory">Pamięć i dane osobiste</string>
|
||||
<string name="ctx_instructions">Pliki z instrukcjami</string>
|
||||
<string name="ctx_tools">Narzędzia</string>
|
||||
<string name="ctx_mcp_tools">Narzędzia MCP</string>
|
||||
<string name="ctx_since">Od ostatniej odpowiedzi</string>
|
||||
<string name="ctx_buffer">Rezerwa na kompakcję</string>
|
||||
<string name="ctx_free">Wolne miejsce</string>
|
||||
<string name="tasks_empty">W tle nic nie działa. Podagenci, polecenia i członkowie zespołu pojawiają się tu, gdy pracują.</string>
|
||||
<string name="tasks_none_running">Nic nie działa.</string>
|
||||
<string name="tasks_running">Działa</string>
|
||||
<string name="tasks_finished">Zakończone</string>
|
||||
<string name="tasks_n_running">Działa: %1$s</string>
|
||||
<string name="tasks_nested">Pod nim: %1$s</string>
|
||||
<string name="task_subagent">Podagent</string>
|
||||
<string name="task_command">Polecenie</string>
|
||||
<string name="task_member">Członek zespołu</string>
|
||||
<string name="activity_until_compact">%1$s do automatycznego streszczenia</string>
|
||||
<string name="activity_compact_off">Automatyczne streszczanie jest wyłączone.</string>
|
||||
<string name="activity_compact">Streść</string>
|
||||
<string name="agents_n_queued">W kolejce: %1$s</string>
|
||||
<string name="agents_n_waiting">Czeka: %1$s</string>
|
||||
<string name="agents_n_finished">Zakończone: %1$s</string>
|
||||
<string name="agent_state_queued">w kolejce</string>
|
||||
<string name="agent_state_working">pracuje</string>
|
||||
<string name="agent_state_waiting">czeka</string>
|
||||
<string name="agent_state_done">gotowe</string>
|
||||
<string name="agent_state_stopped">zatrzymane</string>
|
||||
<string name="agent_state_error">nie powiodło się</string>
|
||||
<string name="agent_steps">Kroki: %1$s, narzędzia: %2$s</string>
|
||||
<string name="agent_open_conversation">Otwórz jego rozmowę</string>
|
||||
<string name="agent_stop">Zatrzymaj %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Zatrzymać %1$s i członków pod nim? Opuszczą zespół.</string>
|
||||
<string name="agent_stop_confirm">Zatrzymać %1$s? To, co już zrobił, zostaje.</string>
|
||||
<string name="agent_nothing_yet">Jeszcze nic nie powiedział.</string>
|
||||
<string name="agent_machine">Od systemu</string>
|
||||
<string name="team_size">Zespół: %1$s z %2$s podagentów</string>
|
||||
<string name="team_room">Pokój</string>
|
||||
<string name="room_empty">W pokoju nikt jeszcze nic nie powiedział.</string>
|
||||
<string name="room_report">raport</string>
|
||||
<string name="team_agents">Podagenci</string>
|
||||
<string name="team_min">Min</string>
|
||||
<string name="team_max">Maks</string>
|
||||
<string name="team_range">Min %1$s · Maks %2$s</string>
|
||||
<string name="team_hint">Liczby obejmują własnego agenta tego czatu: 1 to sam agent, bez podagentów, a Maks 4 to agent i do 3 podagentów, którymi kieruje.</string>
|
||||
<string name="team_chip">Podagenci: Min %1$s · Maks %2$s</string>
|
||||
<string name="subagents_named_only">Ten model obsługuje tylko jedno żądanie naraz: podagenci potrzebują innego modelu, na innym serwerze, nazwanego w czacie.</string>
|
||||
<string name="thinking_switch">Rozumuj przed odpowiedzią</string>
|
||||
<string name="level_off">wył.</string>
|
||||
<string name="level_default">domyślna</string>
|
||||
<string name="chats_open">Otwórz czaty</string>
|
||||
<string name="chats_search">Szukaj czatów</string>
|
||||
<string name="chats_today">Dzisiaj</string>
|
||||
<string name="chats_earlier">Wcześniej</string>
|
||||
<string name="chats_agents">Czaty z agentem</string>
|
||||
<string name="chats_found_in_messages">W wiadomościach</string>
|
||||
<string name="chats_none_found">Żaden czat nie ma tego w tytule.</string>
|
||||
<string name="clear">Wyczyść</string>
|
||||
<string name="composer_hint_agent">Powiedz agentowi, co ma zrobić</string>
|
||||
<string name="tune">Opcje</string>
|
||||
<string name="effort">Wysiłek</string>
|
||||
<string name="thinking_switch_hint">Wolniej, i lepiej przy trudnych pytaniach.</string>
|
||||
<string name="plan_first">Najpierw plan</string>
|
||||
<string name="plan_first_hint">Model pisze plan do zatwierdzenia, zanim zacznie działać.</string>
|
||||
<string name="agent_mode">Tryb</string>
|
||||
<string name="agent_greeting">Co ma zrobić agent?</string>
|
||||
<string name="agent_runs_on">Działa na %1$s, w %2$s</string>
|
||||
<string name="agent_directory_default">jego pierwszym folderze</string>
|
||||
<string name="kind_chat">Czat</string>
|
||||
<string name="kind_agent">Czat agenta</string>
|
||||
<string name="kind_chat_line">Rozmawiaj z modelem: pytania, pisanie, pliki, które dołączysz.</string>
|
||||
<string name="kind_agent_line">Pracuje na połączonym komputerze: czyta, zapisuje i uruchamia polecenia w folderze.</string>
|
||||
<string name="agent_link_title">Najpierw połącz komputer</string>
|
||||
<string name="agent_link_lede">Czaty agentów działają na maszynie z LLeMbas CLI, zalogowanym w tej instancji i połączonym. Teraz żaden nie jest połączony.</string>
|
||||
<string name="agent_link_install">Należy zainstalować na nim LLeMbas CLI:</string>
|
||||
<string name="agent_link_login">Zaloguj go do tej instancji i zatwierdź pokazany kod w przeglądarce, która się otworzy:</string>
|
||||
<string name="agent_link_service">Aby uruchamiać na nim czaty agenta stąd, należy na to zezwolić w jego konfiguracji (~/.config/lembas/config.yaml) i uruchomić usługę:</string>
|
||||
<string name="agent_link_dials_out">Sam łączy się z tą instancją; na komputerze nic nie nasłuchuje. To on decyduje, których katalogów i trybów może używać praca zdalna, bez względu na to, o co prosi się tutaj.</string>
|
||||
<string name="agent_link_check">Sprawdź ponownie</string>
|
||||
<string name="model_choose">Wybierz model</string>
|
||||
<string name="model_in_use">W użyciu</string>
|
||||
<string name="model_sees_images">Widzi obrazy</string>
|
||||
<string name="model_uses_tools">Używa narzędzi</string>
|
||||
<string name="model_context">kontekst %1$s</string>
|
||||
<string name="model_thinking_switchable">Myślenie włączane lub wyłączane</string>
|
||||
<string name="model_levels">Wysiłek: %1$s</string>
|
||||
<string name="code">Kod</string>
|
||||
<string name="copy_code">Kopiuj kod</string>
|
||||
<string name="select_text">Zaznacz tekst</string>
|
||||
<string name="tools_used">Użyte narzędzia: %1$s</string>
|
||||
<string name="suggest_explain">Wyjaśnij</string>
|
||||
<string name="suggest_explain_line">prostymi słowami, jak coś działa</string>
|
||||
<string name="suggest_write">Napisz</string>
|
||||
<string name="suggest_write_line">e-mail, notatkę lub wpis</string>
|
||||
<string name="suggest_plan">Zaplanuj</string>
|
||||
<string name="suggest_plan_line">podróż, tydzień lub projekt</string>
|
||||
<string name="suggest_check">Sprawdź</string>
|
||||
<string name="suggest_check_line">tekst pod kątem błędów i tonu</string>
|
||||
<string name="instance_in_use">W użyciu</string>
|
||||
<string name="notification_settings">Ustawienia powiadomień</string>
|
||||
<string name="notification_settings_hint">Jakie rodzaje przychodzą i jak: odpowiedzi, pytania, wyniki i błędy zaplanowanych zadań.</string>
|
||||
<string name="scheduled">Zaplanowane</string>
|
||||
<string name="scheduled_empty">Nic nie jest zaplanowane. Poproś o coś, co ma się dziać każdego ranka albo raz w przyszłym tygodniu.</string>
|
||||
<string name="scheduled_unsupported">Ta instancja nie oferuje jeszcze zaplanowanych zadań. Pojawią się z nowszym LLeMbas na serwerze.</string>
|
||||
<string name="schedule_new">Nowy harmonogram</string>
|
||||
<string name="schedule_edit">Edytuj harmonogram</string>
|
||||
<string name="schedule_next">Następnie: %1$s</string>
|
||||
<string name="schedule_paused">Wstrzymano</string>
|
||||
<string name="schedule_pause">Wstrzymaj</string>
|
||||
<string name="schedule_resume">Wznów</string>
|
||||
<string name="schedule_run_now">Uruchom teraz</string>
|
||||
<string name="schedule_started">Uruchomiono. Wynik pojawi się w historii.</string>
|
||||
<string name="schedule_next_runs">Następne uruchomienia</string>
|
||||
<string name="schedule_history">Historia</string>
|
||||
<string name="schedule_no_runs">Jeszcze się nie uruchomił.</string>
|
||||
<string name="schedule_model">Model: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Usunąć ten harmonogram? Jego wcześniejsze wyniki zostaną w swoich czatach.</string>
|
||||
<string name="schedule_words_hint">Powiedz własnymi słowami, kiedy i co. Zanim cokolwiek zostanie zapisane, zobaczysz, jak to zrozumiano.</string>
|
||||
<string name="schedule_words_example">W każdy dzień roboczy o 7:30 streść wiadomości o energii odnawialnej</string>
|
||||
<string name="schedule_preview">Podgląd</string>
|
||||
<string name="schedule_understood">Zrozumiano jako</string>
|
||||
<string name="notify_always">Powiadamia za każdym razem</string>
|
||||
<string name="notify_matters">Powiadamia, gdy to ważne</string>
|
||||
<string name="notify_never">Nigdy nie powiadamia</string>
|
||||
<string name="run_ok">Gotowe</string>
|
||||
<string name="run_silent">Nic nowego</string>
|
||||
<string name="run_unchanged">Bez zmian</string>
|
||||
<string name="schedule_computer">Komputer</string>
|
||||
<string name="schedule_computer_away">teraz niepołączony</string>
|
||||
<string name="schedule_watching">Tylko gdy ta strona się zmieni</string>
|
||||
<string name="schedule_watching_command">Tylko gdy zmieni się wynik tego polecenia</string>
|
||||
<string name="run_failed">Nieudane</string>
|
||||
<string name="run_missed">Pominięto ×%1$s</string>
|
||||
<string name="run_skipped">Pominięto</string>
|
||||
<string name="run_waiting">Czeka na model</string>
|
||||
<string name="run_waiting_computer">Czeka na komputer</string>
|
||||
<string name="run_running">Działa</string>
|
||||
<string name="run_model_instead">%1$s zamiast %2$s</string>
|
||||
<string name="run_retry_at">Ponowi próbę o %1$s</string>
|
||||
<string name="run_result">Wynik</string>
|
||||
<string name="run_no_text">To uruchomienie nie zostawiło tekstu.</string>
|
||||
<string name="run_open_chat">Otwórz jego czat</string>
|
||||
<string name="mode_fresh">Za każdym razem nowy czat</string>
|
||||
<string name="mode_continue">Jeden czat, który rośnie</string>
|
||||
<string name="schedule_models">Modele dla zaplanowanych zadań</string>
|
||||
<string name="schedule_models_hint">Zaplanowane zadania biorą pierwszy wolny z nich, w tej kolejności. Odznacz, aby któryś pominąć.</string>
|
||||
<string name="model_free">Teraz wolny</string>
|
||||
<string name="model_busy">Zajęty: %1$s</string>
|
||||
<string name="channel_scheduled">Wyniki zaplanowanych zadań</string>
|
||||
<string name="channel_scheduled_failures">Błędy zaplanowanych zadań</string>
|
||||
<string name="scheduled_result_public">Zaplanowane zadanie ma wynik.</string>
|
||||
<string name="scheduled_failed_public">Zaplanowane zadanie się nie powiodło.</string>
|
||||
<string name="schedule_run_again">Uruchom ponownie</string>
|
||||
<string name="card_approval">Zezwolić na to?</string>
|
||||
<string name="card_allow_once">Zezwól raz</string>
|
||||
<string name="card_allow_always">Zawsze na to zezwalaj</string>
|
||||
@@ -54,10 +254,66 @@
|
||||
<string name="card_answer">Twoja odpowiedź</string>
|
||||
<string name="card_something_else">Coś innego</string>
|
||||
<string name="card_send">Wyślij</string>
|
||||
<string name="progress_queued">W kolejce</string>
|
||||
<string name="progress_queued_ahead">W kolejce: przed nim %1$s</string>
|
||||
<string name="progress_waiting_for_model">Czekam na %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Wczytywanie %1$s</string>
|
||||
<string name="progress_reading_prompt">Czytanie promptu: %1$s / %2$s tokenów (%3$s%%)</string>
|
||||
<string name="progress_reading_prompt_bare">Czytanie promptu</string>
|
||||
<string name="progress_thinking">Rozumowanie</string>
|
||||
<string name="progress_writing">Pisanie: %1$s tok/s</string>
|
||||
<string name="progress_writing_bare">Pisanie</string>
|
||||
<string name="progress_running_tool">Uruchamianie %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Uruchamianie %1$s</string>
|
||||
<string name="progress_waiting_for_person">Czeka na ciebie: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Czeka na podagentów: pracuje %1$s</string>
|
||||
<string name="progress_compacting">Kompaktowanie rozmowy</string>
|
||||
<string name="progress_retrying">Ponowna próba za %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Zatrzymano</string>
|
||||
<string name="progress_stopped_reason">Zatrzymano: %1$s</string>
|
||||
<string name="progress_failed">Niepowodzenie: %1$s</string>
|
||||
<string name="progress_reason_busy">obsługuje jedno żądanie naraz i właśnie obsługuje inne</string>
|
||||
<string name="progress_reason_slots">wszystkie jego miejsca są zajęte</string>
|
||||
<string name="progress_reason_group">jego serwer ma teraz wczytany inny model</string>
|
||||
<string name="progress_what_approval">zezwolić na %1$s?</string>
|
||||
<string name="progress_what_approval_bare">zgoda</string>
|
||||
<string name="progress_what_question">pytanie</string>
|
||||
<string name="progress_what_plan">plan</string>
|
||||
<string name="progress_stopped_person">przez ciebie</string>
|
||||
<string name="progress_stopped_steps">limit kroków</string>
|
||||
<string name="progress_stopped_budget">budżet</string>
|
||||
<string name="tree_state_working">pracuje</string>
|
||||
<string name="tree_state_waiting">czeka na wolne miejsce</string>
|
||||
<string name="tree_state_finished">zakończony</string>
|
||||
<string name="tree_state_idle">bezczynny</string>
|
||||
<string name="tree_state_paused">wstrzymany: pełny kontekst</string>
|
||||
<string name="tree_state_done">gotowe</string>
|
||||
<string name="tree_state_out_of_context">bez kontekstu</string>
|
||||
<string name="tree_state_stopped">zatrzymane</string>
|
||||
<string name="tree_context">%1$s%% kontekstu</string>
|
||||
<string name="tree_open_slots">Wolne miejsca: %1$s</string>
|
||||
<string name="subagents_device_cannot">Komputer, na którym działa ta rozmowa, nie uruchamia podagentów: zaktualizuj na nim LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s pyta:</string>
|
||||
<string name="card_subagent_asks">Podagent %1$s (%2$s), %3$s, pyta:</string>
|
||||
<string name="card_it_says">Mówi: %1$s</string>
|
||||
<string name="card_change_before">Zmień to przed uruchomieniem</string>
|
||||
<string name="card_edit_runs">Zezwolenie uruchamia to, co jest w polu. Nie jest to ponownie sprawdzane z regułami tego czatu — zostało wpisane ręcznie.</string>
|
||||
<string name="plan_approve">Zatwierdź plan</string>
|
||||
<string name="plan_revise">Popraw</string>
|
||||
<string name="plan_what_to_change">Co powinno się zmienić?</string>
|
||||
<string name="plan_carry_out">Wykonaj plan</string>
|
||||
<string name="shown">Pokazano</string>
|
||||
<string name="viewer_open">Otwórz</string>
|
||||
<string name="viewer_open_browser">Otwórz w przeglądarce</string>
|
||||
<string name="viewer_copy">Kopiuj</string>
|
||||
<string name="viewer_html_source">To jest źródło strony. Otwórz ją w przeglądarce, aby zobaczyć samą stronę.</string>
|
||||
<string name="viewer_long_markdown">Długi plik, dlatego jest pokazany jako zwykły tekst.</string>
|
||||
<string name="viewer_unavailable">Ten serwer nie potrafi jeszcze przekazać pliku aplikacji. Otwórz go w przeglądarce.</string>
|
||||
<string name="viewer_too_large">Ten plik jest za duży, by go pokazać; można pokazać najwyżej 1 MB.</string>
|
||||
<string name="viewer_not_text">To nie jest plik tekstowy, więc nie jest tu pokazywany.</string>
|
||||
<string name="files">Pliki</string>
|
||||
<string name="files_all">Wszystkie pliki</string>
|
||||
<string name="files_empty">Jeszcze nic tu nie ma. Nawet hobbiciej norki.</string>
|
||||
<string name="settings">Ustawienia</string>
|
||||
<string name="settings_instances">Instancje</string>
|
||||
<string name="sign_out">Wyloguj się</string>
|
||||
@@ -66,6 +322,13 @@
|
||||
<string name="theme_system">Jak system</string>
|
||||
<string name="theme_moria">Moria (ciemny)</string>
|
||||
<string name="theme_shire">Shire (jasny)</string>
|
||||
<string name="settings_language">Język</string>
|
||||
<string name="language_hint">Tylko interfejs. Modele odpowiadają w języku, w którym się do nich pisze, bez względu na to ustawienie.</string>
|
||||
<string name="language_account">Tak jak moje konto</string>
|
||||
<string name="language_account_is">Tak jak moje konto: %1$s</string>
|
||||
<string name="language_account_unknown">Jeszcze nie odczytano z Twojej instancji</string>
|
||||
<string name="language_phone">Język telefonu</string>
|
||||
<string name="language_phone_is">Język telefonu: %1$s</string>
|
||||
<string name="settings_notifications">Powiadomienia</string>
|
||||
<string name="push_explained">Powiadomienia przychodzą przez UnifiedPush, bez usług Google: niesie je wybrana aplikacja dystrybucyjna, zaszyfrowane tylko dla tego telefonu.</string>
|
||||
<string name="push_no_distributor">Aby dostawać informacje, kiedy odpowiedź jest gotowa, zainstaluj dystrybutora UnifiedPush, na przykład ntfy, a potem wróć tutaj. Bez niego aplikacja pokazuje nowe odpowiedzi tylko wtedy, gdy jest otwarta.</string>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Nie wybrano dystrybutora, więc powiadomienia są wciąż wyłączone.</string>
|
||||
<string name="channel_replies">Odpowiedzi</string>
|
||||
<string name="channel_asks">Pytania i zatwierdzenia</string>
|
||||
<string name="channel_reports">Raporty</string>
|
||||
<string name="settings_assistant">Asystent</string>
|
||||
<string name="assistant_explained">Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.</string>
|
||||
<string name="assistant_open_settings">Otwórz ustawienia asystenta</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<string name="update_allow_installs">Zezwól LLeMbas na instalowanie aktualizacji, a potem sprawdź ponownie.</string>
|
||||
<string name="update_bad_file">Pobrany plik nie zgadzał się z wersją i został odrzucony.</string>
|
||||
<string name="update_installing">Instalowanie %1$s…</string>
|
||||
<string name="update_checking">Sprawdzanie…</string>
|
||||
<string name="update_available">Dostępna jest wersja %1$s. Dotknij, aby otworzyć jej stronę wydania.</string>
|
||||
<string name="update_install">Zainstaluj %1$s</string>
|
||||
<string name="update_auto">Szukaj nowych wersji</string>
|
||||
<string name="update_auto_line">Najwyżej raz dziennie, przy uruchomieniu, aplikacja pyta twoją instancję, które wydanie do niej pasuje (przy starszej instancji odczytuje listę wydań z GitHuba), i daje znać powiadomieniem, gdy jest nowsze. Nic o tobie nie jest wysyłane nigdzie indziej. W wersji beta domyślnie włączone, w przeciwnym razie wyłączone.</string>
|
||||
<string name="update_betas">Uwzględniaj bety</string>
|
||||
<string name="update_betas_line">Proponuj też wersje testowe, nie tylko wydania. Domyślnie włączone, gdy ta aplikacja sama jest betą.</string>
|
||||
<string name="channel_updates">Aktualizacje aplikacji</string>
|
||||
<string name="update_notice_title">LLeMbas na Androida %1$s</string>
|
||||
<string name="update_notice_text">Dostępna jest nowsza wersja. Dotknij, aby otworzyć jej stronę wydania.</string>
|
||||
<string name="assist_hint">Zapytaj o cokolwiek</string>
|
||||
<string name="assist_include_screen">Dołącz ekran</string>
|
||||
<string name="assist_signed_out">Najpierw zaloguj się do instancji LLeMbas w aplikacji.</string>
|
||||
<string name="assist_open_app">Otwórz aplikację</string>
|
||||
<string name="assist_open_in_app">Kontynuuj w aplikacji</string>
|
||||
<string name="assist_use_screen">Użyj ekranu</string>
|
||||
<string name="assist_screen_both">Tekst z ekranu i zrzut ekranu zostaną wysłane z następnym pytaniem.</string>
|
||||
<string name="assist_screen_text">Tekst z ekranu zostanie wysłany z następnym pytaniem.</string>
|
||||
<string name="assist_screen_shot">Zrzut ekranu zostanie wysłany z następnym pytaniem.</string>
|
||||
<string name="assist_quick_summarise">Podsumuj</string>
|
||||
<string name="assist_quick_summarise_prompt">Podsumuj, co jest na moim ekranie.</string>
|
||||
<string name="assist_quick_translate">Przetłumacz</string>
|
||||
<string name="assist_quick_translate_prompt">Przetłumacz na polski to, co jest na moim ekranie.</string>
|
||||
<string name="assist_quick_explain">Wyjaśnij</string>
|
||||
<string name="assist_quick_explain_prompt">Wyjaśnij, co jest na moim ekranie.</string>
|
||||
<string name="assist_continue">Kontynuuj ostatni czat</string>
|
||||
<string name="assist_help">Przytrzymaj przycisk zasilania, aby otworzyć asystenta nad dowolną aplikacją, albo użyj kafelka w Szybkich ustawieniach.</string>
|
||||
<string name="assist_no_wake_word">Nie ma słowa wybudzającego: w zwykłym Androidzie nasłuchiwanie go jest zarezerwowane dla asystenta wbudowanego w telefon.</string>
|
||||
<string name="assist_connecting">Łączenie…</string>
|
||||
<string name="assist_offline">%1$s jest nieosiągalna</string>
|
||||
<string name="assist_no_model">Brak modelu</string>
|
||||
<string name="assist_voice_reply_on">Odpowiedź głosowa włączona</string>
|
||||
<string name="assist_voice_reply_off">Odpowiedź głosowa wyłączona</string>
|
||||
<string name="assist_read_aloud">Przeczytaj na głos</string>
|
||||
<string name="assist_stop_reading">Przestań czytać</string>
|
||||
<string name="assist_answer_in_app">Ta odpowiedź czeka na Twoją decyzję: otwórz ją w aplikacji.</string>
|
||||
<string name="assist_send_now">Wyślij, co powiedziałem</string>
|
||||
<string name="assist_say_it">Powiedz to i zrób pauzę</string>
|
||||
<string name="assist_type">Zamiast tego pisz</string>
|
||||
<string name="assist_writing_down">Zapisuję, co powiedziałeś…</string>
|
||||
<string name="assist_recogniser_failed">Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe.</string>
|
||||
<string name="assistant_listens">Zacznij słuchać po otwarciu asystenta</string>
|
||||
<string name="voice_input">Wprowadzanie głosowe</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Zamiana mowy na tekst Twojej instancji, przez serwer. Nagranie trafia do Twojej instancji i nigdzie indziej.</string>
|
||||
<string name="voice_input_phone">Telefon (Google lub systemowy)</string>
|
||||
<string name="voice_input_phone_line">Własne rozpoznawanie mowy telefonu. Słowa pojawiają się w trakcie mówienia; nagranie trafia tam, dokąd wyśle je to rozpoznawanie.</string>
|
||||
<string name="voice_input_phone_none">Ten telefon nie ma własnego rozpoznawania mowy.</string>
|
||||
<string name="voice_input_hint">Używa go asystent i mikrofon w czacie. Z LLeMbas asystent pokazuje słowa z lekkim opóźnieniem, a pauza je wysyła, czat zapisuje je, gdy przestaniesz; z rozpoznawaniem telefonu pojawiają się w trakcie mówienia.</string>
|
||||
<string name="share_sending">Wysyłanie do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Zobacz to.</string>
|
||||
</resources>
|
||||
@@ -11,16 +11,40 @@
|
||||
<string name="signin_open_browser">Otvoriť v prehliadači</string>
|
||||
<string name="signin_denied">Prihlásenie bolo odmietnuté.</string>
|
||||
<string name="signin_expired">Kód vypršal skôr, než bol schválený. Skúste to znova.</string>
|
||||
<string name="signin_too_old">Táto inštancia ešte nemá API pre aplikácie. Potrebuje LLeMbas 1.7.0 alebo novší.</string>
|
||||
<string name="signin_too_old">Táto inštancia beží na staršom LLeMbas. Táto aplikácia potrebuje LLeMbas 2.0 alebo novší.</string>
|
||||
<string name="signin_too_new">Táto inštancia používa novšie API pre aplikácie než táto aplikácia. Aktualizujte aplikáciu.</string>
|
||||
<string name="new_chat">Nová konverzácia</string>
|
||||
<string name="tab_chats">Konverzácie</string>
|
||||
<string name="tab_agents">Agenti</string>
|
||||
<string name="empty_chats">Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.</string>
|
||||
<string name="empty_agents">Žiadne konverzácie s agentom. Spustite jednu z webového rozhrania na prepojenom zariadení.</string>
|
||||
<string name="new_agent_chat">Nová konverzácia s agentom</string>
|
||||
<string name="agent_device">Zariadenie</string>
|
||||
<string name="agent_no_device">Práve nie je prepojené žiadne zariadenie. Spustite `lembas service` na počítači prihlásenom do tejto inštancie a vráťte sa.</string>
|
||||
<string name="agent_directory">Zložka v zariadení</string>
|
||||
<string name="agent_directory_hint">Prázdne: prvá zložka zariadenia</string>
|
||||
<string name="empty_chat">O čom sa pozhovárame?</string>
|
||||
<string name="loading_line">Pečú sa lembasy…</string>
|
||||
<string name="archive">Archivovať</string>
|
||||
<string name="archived">Archivované</string>
|
||||
<string name="archived_restore">Obnoviť konverzáciu</string>
|
||||
<string name="archived_none">Žiadne archivované konverzácie.</string>
|
||||
<string name="memory">Pamäť</string>
|
||||
<string name="memory_intro">Čo si o vás modely pamätajú</string>
|
||||
<string name="memory_none">Zatiaľ nič. Model, ktorý má nástroj pamäti, tu pridá záznam, keď mu povieš niečo, čo sa vyplatí uchovať.</string>
|
||||
<string name="memory_remember">Zapamätať</string>
|
||||
<string name="memory_label">Čo si táto pamäť pamätá</string>
|
||||
<string name="memory_hint">Niečo, čo sa vyplatí zapamätať</string>
|
||||
<string name="memory_group">Dátová oblasť</string>
|
||||
<string name="memory_forget">Zabudnúť</string>
|
||||
<string name="memory_by_model">Model</string>
|
||||
<string name="chats_pinned">Pripnuté konverzácie</string>
|
||||
<string name="chat_pin">Pripnúť konverzáciu</string>
|
||||
<string name="chat_unpin">Odopnúť konverzáciu</string>
|
||||
<string name="folder_move">Presunúť do zložky</string>
|
||||
<string name="folder_none">Bez zložky</string>
|
||||
<string name="folder_new">Nová zložka</string>
|
||||
<string name="folder_name">Názov zložky</string>
|
||||
<string name="folder_rename">Premenovať zložku</string>
|
||||
<string name="folder_delete">Zmazať zložku</string>
|
||||
<string name="folder_delete_confirm">Zmazať zložku „%1$s“? Konverzácie v nej zostanú.</string>
|
||||
<string name="delete">Zmazať</string>
|
||||
<string name="edit">Upraviť</string>
|
||||
<string name="regenerate">Vygenerovať znova</string>
|
||||
@@ -35,16 +59,192 @@
|
||||
<string name="send">Poslať</string>
|
||||
<string name="stop">Zastaviť</string>
|
||||
<string name="attach">Priložiť súbor</string>
|
||||
<string name="attach_take_photo">Odfotiť</string>
|
||||
<string name="attach_choose_photos">Vybrať fotky</string>
|
||||
<string name="attach_choose_files">Vybrať súbory</string>
|
||||
<string name="image_generate">Generovať obrázky</string>
|
||||
<string name="image_generated">Vygenerovaný obrázok</string>
|
||||
<string name="copy_message">Skopírovať správu</string>
|
||||
<string name="copied">Skopírované.</string>
|
||||
<string name="rename_chat">Premenovať konverzáciu</string>
|
||||
<string name="save">Uložiť</string>
|
||||
<string name="retry">Skúsiť znova</string>
|
||||
<string name="offline">Inštancia nie je dostupná. Skontrolujte pripojenie telefónu a či sa dostane na adresu inštancie.</string>
|
||||
<string name="dictate">Diktovať</string>
|
||||
<string name="remove">Odstrániť</string>
|
||||
<string name="more">Viac</string>
|
||||
<string name="back">Späť</string>
|
||||
<string name="cancel">Zrušiť</string>
|
||||
<string name="close">Zavrieť</string>
|
||||
<string name="effort_off">Úsilie: vypnuté</string>
|
||||
<string name="mode_plan">Plán</string>
|
||||
<string name="mode_edit">Upraviť</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_manual">Ručne</string>
|
||||
<string name="mode_auto">Automaticky</string>
|
||||
<string name="activity">Aktivita</string>
|
||||
<string name="activity_open">Otvoriť panel aktivity</string>
|
||||
<string name="activity_context">Kontext</string>
|
||||
<string name="activity_outputs">Výstupy</string>
|
||||
<string name="activity_tasks">Úlohy na pozadí</string>
|
||||
<string name="activity_used">Využité: %1$s %%</string>
|
||||
<string name="activity_window_unknown">okno neznáme</string>
|
||||
<string name="activity_not_measured">Nezmerané.</string>
|
||||
<string name="activity_measured">Spočítal model pri poslednej odpovedi; kategórie sú odhadnuté.</string>
|
||||
<string name="activity_estimated">Odhad: žiadna odpoveď ešte nebola spočítaná.</string>
|
||||
<string name="activity_tools_offered">Ponúknuté nástroje: %1$s.</string>
|
||||
<string name="ctx_messages">Správy</string>
|
||||
<string name="ctx_system">Systémový pokyn</string>
|
||||
<string name="ctx_memory">Pamäť a osobné</string>
|
||||
<string name="ctx_instructions">Súbory s pokynmi</string>
|
||||
<string name="ctx_tools">Nástroje</string>
|
||||
<string name="ctx_mcp_tools">Nástroje MCP</string>
|
||||
<string name="ctx_since">Od poslednej odpovede</string>
|
||||
<string name="ctx_buffer">Rezerva na zhustenie</string>
|
||||
<string name="ctx_free">Voľné miesto</string>
|
||||
<string name="tasks_empty">Na pozadí nič nebeží. Podagenti, príkazy a členovia tímu sa tu ukážu, kým pracujú.</string>
|
||||
<string name="tasks_none_running">Nič nebeží.</string>
|
||||
<string name="tasks_running">Beží</string>
|
||||
<string name="tasks_finished">Dokončené</string>
|
||||
<string name="tasks_n_running">Beží: %1$s</string>
|
||||
<string name="tasks_nested">Pod ním: %1$s</string>
|
||||
<string name="task_subagent">Podagent</string>
|
||||
<string name="task_command">Príkaz</string>
|
||||
<string name="task_member">Člen tímu</string>
|
||||
<string name="activity_until_compact">%1$s do automatického zhrnutia</string>
|
||||
<string name="activity_compact_off">Automatické zhrnutie je vypnuté.</string>
|
||||
<string name="activity_compact">Zhrnúť</string>
|
||||
<string name="agents_n_queued">V rade: %1$s</string>
|
||||
<string name="agents_n_waiting">Čaká: %1$s</string>
|
||||
<string name="agents_n_finished">Dokončené: %1$s</string>
|
||||
<string name="agent_state_queued">v rade</string>
|
||||
<string name="agent_state_working">pracuje</string>
|
||||
<string name="agent_state_waiting">čaká</string>
|
||||
<string name="agent_state_done">hotovo</string>
|
||||
<string name="agent_state_stopped">zastavené</string>
|
||||
<string name="agent_state_error">zlyhalo</string>
|
||||
<string name="agent_steps">Kroky: %1$s, nástroje: %2$s</string>
|
||||
<string name="agent_open_conversation">Otvoriť jeho konverzáciu</string>
|
||||
<string name="agent_stop">Zastaviť %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Zastaviť %1$s a členov pod ním? Opustia tím.</string>
|
||||
<string name="agent_stop_confirm">Zastaviť %1$s? Čo doteraz urobil, zostane.</string>
|
||||
<string name="agent_nothing_yet">Zatiaľ nič nepovedal.</string>
|
||||
<string name="agent_machine">Od systému</string>
|
||||
<string name="team_size">Tím: %1$s z %2$s podagentov</string>
|
||||
<string name="team_room">Miestnosť</string>
|
||||
<string name="room_empty">V miestnosti zatiaľ nikto nič nepovedal.</string>
|
||||
<string name="room_report">hlásenie</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 rátajú aj vlastného agenta tohto chatu: 1 je agent sám, bez podagentov, a Max 4 je agent a až 3 podagenti, ktorých vedie.</string>
|
||||
<string name="team_chip">Podagenti: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">Tento model obslúži len jednu požiadavku naraz: podagenti potrebujú iný model, na inom serveri, pomenovaný v chate.</string>
|
||||
<string name="thinking_switch">Premýšľať pred odpoveďou</string>
|
||||
<string name="level_off">vypnuté</string>
|
||||
<string name="level_default">predvolené</string>
|
||||
<string name="chats_open">Otvoriť čety</string>
|
||||
<string name="chats_search">Hľadať v četoch</string>
|
||||
<string name="chats_today">Dnes</string>
|
||||
<string name="chats_earlier">Skôr</string>
|
||||
<string name="chats_agents">Čety s agentom</string>
|
||||
<string name="chats_found_in_messages">V správach</string>
|
||||
<string name="chats_none_found">Žiadny čet to nemá v názve.</string>
|
||||
<string name="clear">Vymazať</string>
|
||||
<string name="composer_hint_agent">Povedzte agentovi, čo má urobiť</string>
|
||||
<string name="tune">Možnosti</string>
|
||||
<string name="effort">Úsilie</string>
|
||||
<string name="thinking_switch_hint">Pomalšie a lepšie pri ťažkých otázkach.</string>
|
||||
<string name="plan_first">Najprv plán</string>
|
||||
<string name="plan_first_hint">Model napíše plán, ktorý schválite, skôr než začne konať.</string>
|
||||
<string name="agent_mode">Režim</string>
|
||||
<string name="agent_greeting">Čo má agent urobiť?</string>
|
||||
<string name="agent_runs_on">Beží na %1$s, v priečinku %2$s</string>
|
||||
<string name="agent_directory_default">jeho prvý priečinok</string>
|
||||
<string name="kind_chat">Konverzácia</string>
|
||||
<string name="kind_agent">Agentská konverzácia</string>
|
||||
<string name="kind_chat_line">Rozprávajte sa s modelom: otázky, písanie, súbory, ktoré priložíte.</string>
|
||||
<string name="kind_agent_line">Pracuje na počítači, ktorý ste prepojili: číta, zapisuje a spúšťa príkazy v priečinku.</string>
|
||||
<string name="agent_link_title">Najprv prepojte počítač</string>
|
||||
<string name="agent_link_lede">Agentské konverzácie bežia na počítači s LLeMbas CLI, ktoré je prihlásené do tejto instancie a pripojené. Teraz nie je pripojené žiadne.</string>
|
||||
<string name="agent_link_install">Nainštalujte naň LLeMbas CLI:</string>
|
||||
<string name="agent_link_login">Prihláste ho k tejto inštancii a kód, ktorý ukáže, schváľte v prehliadači, ktorý sa otvorí:</string>
|
||||
<string name="agent_link_service">Aby na ňom odtiaľto bežali agentové chaty, povoľte to v jeho konfigurácii (~/.config/lembas/config.yaml) a spustite službu:</string>
|
||||
<string name="agent_link_dials_out">Pripája sa sám k tejto inštancii; na vašom počítači nič nepočúva. O tom, ktoré adresáre a režimy môže práca na diaľku použiť, rozhoduje on, nech sa tu žiada čokoľvek.</string>
|
||||
<string name="agent_link_check">Skontrolovať znova</string>
|
||||
<string name="model_choose">Vyberte model</string>
|
||||
<string name="model_in_use">Používa sa</string>
|
||||
<string name="model_sees_images">Vidí obrázky</string>
|
||||
<string name="model_uses_tools">Používa nástroje</string>
|
||||
<string name="model_context">kontext %1$s</string>
|
||||
<string name="model_thinking_switchable">Premýšľanie zapnúť alebo vypnúť</string>
|
||||
<string name="model_levels">Úsilie: %1$s</string>
|
||||
<string name="code">Kód</string>
|
||||
<string name="copy_code">Skopírovať kód</string>
|
||||
<string name="select_text">Vybrať text</string>
|
||||
<string name="tools_used">Použité nástroje: %1$s</string>
|
||||
<string name="suggest_explain">Vysvetli</string>
|
||||
<string name="suggest_explain_line">jednoducho, ako niečo funguje</string>
|
||||
<string name="suggest_write">Napíš</string>
|
||||
<string name="suggest_write_line">e-mail, poznámku alebo príspevok</string>
|
||||
<string name="suggest_plan">Naplánuj</string>
|
||||
<string name="suggest_plan_line">výlet, týždeň alebo projekt</string>
|
||||
<string name="suggest_check">Skontroluj</string>
|
||||
<string name="suggest_check_line">text, chyby a tón</string>
|
||||
<string name="instance_in_use">Používa sa</string>
|
||||
<string name="notification_settings">Nastavenia upozornení</string>
|
||||
<string name="notification_settings_hint">Ktoré druhy prichádzajú a ako: odpovede, otázky, výsledky a zlyhania naplánovaných úloh.</string>
|
||||
<string name="scheduled">Naplánované</string>
|
||||
<string name="scheduled_empty">Nič nie je naplánované. Požiadajte o niečo, čo sa má stať každé ráno, alebo raz budúci týždeň.</string>
|
||||
<string name="scheduled_unsupported">Táto inštancia zatiaľ neponúka naplánované úlohy. Prídu s novším LLeMbas na serveri.</string>
|
||||
<string name="schedule_new">Nový plán</string>
|
||||
<string name="schedule_edit">Upraviť plán</string>
|
||||
<string name="schedule_next">Nabudúce: %1$s</string>
|
||||
<string name="schedule_paused">Pozastavené</string>
|
||||
<string name="schedule_pause">Pozastaviť</string>
|
||||
<string name="schedule_resume">Pokračovať</string>
|
||||
<string name="schedule_run_now">Spustiť teraz</string>
|
||||
<string name="schedule_started">Spustené. Výsledok sa objaví v histórii.</string>
|
||||
<string name="schedule_next_runs">Ďalšie spustenia</string>
|
||||
<string name="schedule_history">História</string>
|
||||
<string name="schedule_no_runs">Ešte nebežal.</string>
|
||||
<string name="schedule_model">Model: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Zmazať tento plán? Jeho doterajšie výsledky zostanú vo svojich četoch.</string>
|
||||
<string name="schedule_words_hint">Povedzte vlastnými slovami kedy a čo. Skôr než sa čokoľvek uloží, uvidíte, ako to bolo pochopené.</string>
|
||||
<string name="schedule_words_example">Každý pracovný deň o 7:30 zhrň správy o obnoviteľnej energii</string>
|
||||
<string name="schedule_preview">Náhľad</string>
|
||||
<string name="schedule_understood">Pochopené ako</string>
|
||||
<string name="notify_always">Dá vedieť zakaždým</string>
|
||||
<string name="notify_matters">Dá vedieť, keď na tom záleží</string>
|
||||
<string name="notify_never">Nedá vedieť nikdy</string>
|
||||
<string name="run_ok">Hotovo</string>
|
||||
<string name="run_silent">Nič nové</string>
|
||||
<string name="run_unchanged">Bez zmeny</string>
|
||||
<string name="schedule_computer">Počítač</string>
|
||||
<string name="schedule_computer_away">teraz nie je prepojený</string>
|
||||
<string name="schedule_watching">Len keď sa táto stránka zmení</string>
|
||||
<string name="schedule_watching_command">Len keď sa zmení výstup tohto príkazu</string>
|
||||
<string name="run_failed">Zlyhalo</string>
|
||||
<string name="run_missed">Zmeškané ×%1$s</string>
|
||||
<string name="run_skipped">Vynechané</string>
|
||||
<string name="run_waiting">Čaká na model</string>
|
||||
<string name="run_waiting_computer">Čaká na počítač</string>
|
||||
<string name="run_running">Beží</string>
|
||||
<string name="run_model_instead">%1$s, namiesto %2$s</string>
|
||||
<string name="run_retry_at">Skúsi to znova o %1$s</string>
|
||||
<string name="run_result">Výsledok</string>
|
||||
<string name="run_no_text">Tento beh nezanechal žiadny text.</string>
|
||||
<string name="run_open_chat">Otvoriť jeho konverzáciu</string>
|
||||
<string name="mode_fresh">Zakaždým nová konverzácia</string>
|
||||
<string name="mode_continue">Jedna konverzácia, ktorá rastie</string>
|
||||
<string name="schedule_models">Modely pre naplánované úlohy</string>
|
||||
<string name="schedule_models_hint">Naplánované úlohy vezmú prvý z nich, ktorý je voľný, v tomto poradí. Zrušte začiarknutie, ak niektorý chcete vynechať.</string>
|
||||
<string name="model_free">Teraz voľný</string>
|
||||
<string name="model_busy">Obsadený: %1$s</string>
|
||||
<string name="channel_scheduled">Výsledky naplánovaných úloh</string>
|
||||
<string name="channel_scheduled_failures">Zlyhania naplánovaných úloh</string>
|
||||
<string name="scheduled_result_public">Naplánovaná úloha má výsledok.</string>
|
||||
<string name="scheduled_failed_public">Naplánovaná úloha zlyhala.</string>
|
||||
<string name="schedule_run_again">Spustiť znova</string>
|
||||
<string name="card_approval">Povoliť to?</string>
|
||||
<string name="card_allow_once">Povoliť raz</string>
|
||||
<string name="card_allow_always">Toto vždy povoliť</string>
|
||||
@@ -54,10 +254,66 @@
|
||||
<string name="card_answer">Vaša odpoveď</string>
|
||||
<string name="card_something_else">Niečo iné</string>
|
||||
<string name="card_send">Poslať</string>
|
||||
<string name="progress_queued">Vo fronte</string>
|
||||
<string name="progress_queued_ahead">Vo fronte: pred ním %1$s</string>
|
||||
<string name="progress_waiting_for_model">Čaká sa na %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Načítava sa %1$s</string>
|
||||
<string name="progress_reading_prompt">Číta sa výzva: %1$s / %2$s tokenov (%3$s %%)</string>
|
||||
<string name="progress_reading_prompt_bare">Číta sa výzva</string>
|
||||
<string name="progress_thinking">Premýšľa</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">Spúšťa %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Spúšťa %1$s</string>
|
||||
<string name="progress_waiting_for_person">Čaká na vás: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Čaká na podagentov: pracujú %1$s</string>
|
||||
<string name="progress_compacting">Zhŕňa sa konverzácia</string>
|
||||
<string name="progress_retrying">Nový pokus o %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Zastavené</string>
|
||||
<string name="progress_stopped_reason">Zastavené: %1$s</string>
|
||||
<string name="progress_failed">Zlyhalo: %1$s</string>
|
||||
<string name="progress_reason_busy">vybavuje jednu požiadavku naraz a práve vybavuje inú</string>
|
||||
<string name="progress_reason_slots">všetky jeho sloty sú obsadené</string>
|
||||
<string name="progress_reason_group">jeho server má teraz načítaný iný model</string>
|
||||
<string name="progress_what_approval">povoliť %1$s?</string>
|
||||
<string name="progress_what_approval_bare">povolenie</string>
|
||||
<string name="progress_what_question">otázka</string>
|
||||
<string name="progress_what_plan">plán</string>
|
||||
<string name="progress_stopped_person">vami</string>
|
||||
<string name="progress_stopped_steps">limit krokov</string>
|
||||
<string name="progress_stopped_budget">rozpočet</string>
|
||||
<string name="tree_state_working">pracuje</string>
|
||||
<string name="tree_state_waiting">čaká na voľný 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">zastavené</string>
|
||||
<string name="tree_context">kontext %1$s %%</string>
|
||||
<string name="tree_open_slots">Voľné miesta: %1$s</string>
|
||||
<string name="subagents_device_cannot">Počítač, na ktorom táto konverzácia beží, nespúšťa podagentov: aktualizujte na ňom LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s sa pýta:</string>
|
||||
<string name="card_subagent_asks">Podagent %1$s (%2$s), %3$s, sa pýta:</string>
|
||||
<string name="card_it_says">Model uvádza: %1$s</string>
|
||||
<string name="card_change_before">Upraviť to pred spustením</string>
|
||||
<string name="card_edit_runs">Povolením sa spustí to, čo je v poli. Znova sa to neporovnáva s pravidlami tejto konverzácie — napísali ste to vy.</string>
|
||||
<string name="plan_approve">Schváliť plán</string>
|
||||
<string name="plan_revise">Prepracovať</string>
|
||||
<string name="plan_what_to_change">Čo by sa malo zmeniť?</string>
|
||||
<string name="plan_carry_out">Vykonať plán</string>
|
||||
<string name="shown">Zobrazené</string>
|
||||
<string name="viewer_open">Otvoriť</string>
|
||||
<string name="viewer_open_browser">Otvoriť v prehliadači</string>
|
||||
<string name="viewer_copy">Kopírovať</string>
|
||||
<string name="viewer_html_source">Toto je zdrojový kód stránky. Samotnú stránku uvidíte po otvorení v prehliadači.</string>
|
||||
<string name="viewer_long_markdown">Dlhý súbor, preto je zobrazený ako obyčajný text.</string>
|
||||
<string name="viewer_unavailable">Tento server zatiaľ nevie aplikácii súbor odovzdať. Otvorte ho v prehliadači.</string>
|
||||
<string name="viewer_too_large">Tento súbor je príliš veľký na zobrazenie; zobraziť možno najviac 1 MB.</string>
|
||||
<string name="viewer_not_text">Toto nie je textový súbor, preto sa tu nezobrazuje.</string>
|
||||
<string name="files">Súbory</string>
|
||||
<string name="files_all">Všetky súbory</string>
|
||||
<string name="files_empty">Zatiaľ tu nič nie je. Ani hobitia nora.</string>
|
||||
<string name="settings">Nastavenia</string>
|
||||
<string name="settings_instances">Inštancie</string>
|
||||
<string name="sign_out">Odhlásiť sa</string>
|
||||
@@ -66,6 +322,13 @@
|
||||
<string name="theme_system">Podľa systému</string>
|
||||
<string name="theme_moria">Moria (tmavá)</string>
|
||||
<string name="theme_shire">Shire (svetlá)</string>
|
||||
<string name="settings_language">Jazyk</string>
|
||||
<string name="language_hint">Len rozhranie. Modely odpovedajú v jazyku, v ktorom im píšete, bez ohľadu na toto nastavenie.</string>
|
||||
<string name="language_account">Rovnaký ako môj účet</string>
|
||||
<string name="language_account_is">Rovnaký ako môj účet: %1$s</string>
|
||||
<string name="language_account_unknown">Z vašej inštancie ešte nenačítaný</string>
|
||||
<string name="language_phone">Jazyk telefónu</string>
|
||||
<string name="language_phone_is">Jazyk telefónu: %1$s</string>
|
||||
<string name="settings_notifications">Upozornenia</string>
|
||||
<string name="push_explained">Upozornenia chodia cez UnifiedPush, bez služieb Google: doručuje ich distribučná aplikácia, ktorú ste zvolili, zašifrované len pre tento telefón.</string>
|
||||
<string name="push_no_distributor">Aby ste sa dozvedeli, že je odpoveď hotová, nainštalujte distributora UnifiedPush, napríklad ntfy, a potom sa vráťte sem. Bez neho aplikácia nové odpovede ukáže, len keď je otvorená.</string>
|
||||
@@ -74,7 +337,6 @@
|
||||
<string name="push_failed">Nebol zvolený žiadny distributor, takže upozornenia sú stále vypnuté.</string>
|
||||
<string name="channel_replies">Odpovede</string>
|
||||
<string name="channel_asks">Otázky a schválenia</string>
|
||||
<string name="channel_reports">Správy</string>
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.</string>
|
||||
<string name="assistant_open_settings">Otvoriť nastavenia asistenta</string>
|
||||
@@ -89,11 +351,54 @@
|
||||
<string name="update_allow_installs">Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.</string>
|
||||
<string name="update_bad_file">Stiahnutý súbor nezodpovedal verzii a bol zahodený.</string>
|
||||
<string name="update_installing">Inštaluje sa %1$s…</string>
|
||||
<string name="update_checking">Kontroluje sa…</string>
|
||||
<string name="update_available">Je dostupná %1$s. Ťuknutím otvoríte stránku vydania.</string>
|
||||
<string name="update_install">Nainštalovať %1$s</string>
|
||||
<string name="update_auto">Hľadať nové verzie</string>
|
||||
<string name="update_auto_line">Najviac raz denne, pri spustení, sa aplikácia opýta vašej inštancie, ktoré vydanie k nej patrí (pri staršej inštancii si prečíta zoznam vydaní na GitHube), a upozornením vám dá vedieť, keď je dostupné novšie. Nič o vás sa nikam inam neposiela. V beta verzii zapnuté, inak vypnuté.</string>
|
||||
<string name="update_betas">Vrátane beta verzií</string>
|
||||
<string name="update_betas_line">Ponúkať aj testovacie verzie, nielen vydania. Zapnuté, keď je táto aplikácia sama beta.</string>
|
||||
<string name="channel_updates">Aktualizácie aplikácie</string>
|
||||
<string name="update_notice_title">LLeMbas pre Android %1$s</string>
|
||||
<string name="update_notice_text">Je dostupná novšia verzia. Ťuknutím otvoríte stránku vydania.</string>
|
||||
<string name="assist_hint">Spýtajte sa na čokoľvek</string>
|
||||
<string name="assist_include_screen">Zahrnúť obrazovku</string>
|
||||
<string name="assist_signed_out">Najprv sa v aplikácii prihláste do inštancie LLeMbas.</string>
|
||||
<string name="assist_open_app">Otvoriť aplikáciu</string>
|
||||
<string name="assist_open_in_app">Pokračovať v aplikácii</string>
|
||||
<string name="assist_use_screen">Použiť obrazovku</string>
|
||||
<string name="assist_screen_both">S vašou ďalšou otázkou pôjde text obrazovky a snímka obrazovky.</string>
|
||||
<string name="assist_screen_text">S vašou ďalšou otázkou pôjde text obrazovky.</string>
|
||||
<string name="assist_screen_shot">S vašou ďalšou otázkou pôjde snímka obrazovky.</string>
|
||||
<string name="assist_quick_summarise">Zhrnúť</string>
|
||||
<string name="assist_quick_summarise_prompt">Zhrň, čo je na mojej obrazovke.</string>
|
||||
<string name="assist_quick_translate">Preložiť</string>
|
||||
<string name="assist_quick_translate_prompt">Prelož do slovenčiny, čo je na mojej obrazovke.</string>
|
||||
<string name="assist_quick_explain">Vysvetliť</string>
|
||||
<string name="assist_quick_explain_prompt">Vysvetli, čo je na mojej obrazovke.</string>
|
||||
<string name="assist_continue">Pokračovať v poslednej konverzácii</string>
|
||||
<string name="assist_help">Podržaním tlačidla napájania otvoríte asistenta nad ľubovoľnou aplikáciou; alebo použite dlaždicu v Rýchlych nastaveniach.</string>
|
||||
<string name="assist_no_wake_word">Budiace slovo nie je: na bežnom Androide je počúvanie budiaceho slova vyhradené asistentovi zabudovanému v telefóne.</string>
|
||||
<string name="assist_connecting">Pripája sa…</string>
|
||||
<string name="assist_offline">%1$s je nedostupná</string>
|
||||
<string name="assist_no_model">Žiadny model</string>
|
||||
<string name="assist_voice_reply_on">Hlasová odpoveď je zapnutá</string>
|
||||
<string name="assist_voice_reply_off">Hlasová odpoveď je vypnutá</string>
|
||||
<string name="assist_read_aloud">Prečítať nahlas</string>
|
||||
<string name="assist_stop_reading">Prestať čítať</string>
|
||||
<string name="assist_answer_in_app">Táto odpoveď čaká na vaše rozhodnutie: otvorte ju v aplikácii.</string>
|
||||
<string name="assist_send_now">Odoslať, čo som povedal</string>
|
||||
<string name="assist_say_it">Povedzte to a odmlčte sa</string>
|
||||
<string name="assist_type">Radšej písať</string>
|
||||
<string name="assist_writing_down">Zapisujem, čo ste povedali…</string>
|
||||
<string name="assist_recogniser_failed">Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup.</string>
|
||||
<string name="assistant_listens">Začať počúvať, keď sa asistent otvorí</string>
|
||||
<string name="voice_input">Hlasový vstup</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Prevod reči na text vašej inštancie, cez server. Nahrávka ide na vašu inštanciu a nikam inam.</string>
|
||||
<string name="voice_input_phone">Telefón (Google alebo systémový)</string>
|
||||
<string name="voice_input_phone_line">Vlastné rozpoznávanie reči v telefóne. Slová sa objavujú, ako hovoríte; nahrávka ide tam, kam ju to rozpoznávanie pošle.</string>
|
||||
<string name="voice_input_phone_none">Tento telefón nemá vlastné rozpoznávanie reči.</string>
|
||||
<string name="voice_input_hint">Používa ho asistent aj mikrofón v konverzácii. S LLeMbas asistent ukazuje slová s malým oneskorením a pauza ich odošle, konverzácia ich zapíše, keď prestanete; s rozpoznávaním v telefóne sa objavujú, ako hovoríte.</string>
|
||||
<string name="share_sending">Odosiela sa do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Pozrite sa na toto.</string>
|
||||
</resources>
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Moria's --bg, the colour the launcher tile sits on. -->
|
||||
<!-- Moria's background (the bg token), the colour the launcher tile sits on. -->
|
||||
<color name="launcher_background">#0B0D10</color>
|
||||
</resources>
|
||||
@@ -12,16 +12,40 @@
|
||||
<string name="signin_open_browser">Open in the browser</string>
|
||||
<string name="signin_denied">The sign-in was refused.</string>
|
||||
<string name="signin_expired">The code expired before it was approved. Try again.</string>
|
||||
<string name="signin_too_old">This instance has no app API yet. It needs LLeMbas 1.7.0 or newer.</string>
|
||||
<string name="signin_too_old">This instance runs an older LLeMbas. This app needs LLeMbas 2.0 or newer.</string>
|
||||
<string name="signin_too_new">This instance speaks a newer app API than this app. Update the app.</string>
|
||||
<string name="new_chat">New chat</string>
|
||||
<string name="tab_chats">Chats</string>
|
||||
<string name="tab_agents">Agents</string>
|
||||
<string name="empty_chats">No chats yet. Not all those who wander are lost — start one.</string>
|
||||
<string name="empty_agents">No agent chats. Start one from the web interface on a linked device.</string>
|
||||
<string name="new_agent_chat">New agent chat</string>
|
||||
<string name="agent_device">Device</string>
|
||||
<string name="agent_no_device">No device is linked right now. Start `lembas service` on a computer signed in to this instance, then come back.</string>
|
||||
<string name="agent_directory">Folder on the device</string>
|
||||
<string name="agent_directory_hint">Empty: the device\'s first folder</string>
|
||||
<string name="empty_chat">What shall we talk about?</string>
|
||||
<string name="loading_line">Baking lembas…</string>
|
||||
<string name="archive">Archive</string>
|
||||
<string name="archived">Archived</string>
|
||||
<string name="archived_restore">Restore chat</string>
|
||||
<string name="archived_none">No archived chats.</string>
|
||||
<string name="memory">Memory</string>
|
||||
<string name="memory_intro">What models remember about you</string>
|
||||
<string name="memory_none">Nothing yet. A model with the memory tool adds to this when you tell it something worth keeping.</string>
|
||||
<string name="memory_remember">Remember</string>
|
||||
<string name="memory_label">What this memory says</string>
|
||||
<string name="memory_hint">Something worth remembering</string>
|
||||
<string name="memory_group">Data group</string>
|
||||
<string name="memory_forget">Forget</string>
|
||||
<string name="memory_by_model">Model</string>
|
||||
<string name="chats_pinned">Pinned chats</string>
|
||||
<string name="chat_pin">Pin chat</string>
|
||||
<string name="chat_unpin">Unpin chat</string>
|
||||
<string name="folder_move">Move to folder</string>
|
||||
<string name="folder_none">No folder</string>
|
||||
<string name="folder_new">New folder</string>
|
||||
<string name="folder_name">Folder name</string>
|
||||
<string name="folder_rename">Rename folder</string>
|
||||
<string name="folder_delete">Delete folder</string>
|
||||
<string name="folder_delete_confirm">Delete the folder “%1$s”? Chats inside it are kept.</string>
|
||||
<string name="delete">Delete</string>
|
||||
<string name="edit">Edit</string>
|
||||
<string name="regenerate">Regenerate</string>
|
||||
@@ -36,16 +60,192 @@
|
||||
<string name="send">Send</string>
|
||||
<string name="stop">Stop</string>
|
||||
<string name="attach">Attach a file</string>
|
||||
<string name="attach_take_photo">Take a photo</string>
|
||||
<string name="attach_choose_photos">Choose photos</string>
|
||||
<string name="attach_choose_files">Choose files</string>
|
||||
<string name="image_generate">Generate images</string>
|
||||
<string name="image_generated">The generated image</string>
|
||||
<string name="copy_message">Copy message</string>
|
||||
<string name="copied">Copied.</string>
|
||||
<string name="rename_chat">Rename chat</string>
|
||||
<string name="save">Save</string>
|
||||
<string name="retry">Try again</string>
|
||||
<string name="offline">The instance cannot be reached. Check the phone\'s connection, and that it can reach the instance\'s address.</string>
|
||||
<string name="dictate">Dictate</string>
|
||||
<string name="remove">Remove</string>
|
||||
<string name="more">More</string>
|
||||
<string name="back">Back</string>
|
||||
<string name="cancel">Cancel</string>
|
||||
<string name="close">Close</string>
|
||||
<string name="effort_off">Effort: off</string>
|
||||
<string name="mode_plan">Plan</string>
|
||||
<string name="mode_edit">Edit</string>
|
||||
<string name="mode_manual">Manual</string>
|
||||
<string name="mode_auto">Auto</string>
|
||||
<string name="activity">Activity</string>
|
||||
<string name="activity_open">Open the activity panel</string>
|
||||
<string name="activity_context">Context</string>
|
||||
<string name="activity_outputs">Outputs</string>
|
||||
<string name="activity_tasks">Background tasks</string>
|
||||
<string name="activity_used">%1$s%% used</string>
|
||||
<string name="activity_window_unknown">window unknown</string>
|
||||
<string name="activity_not_measured">Not measured.</string>
|
||||
<string name="activity_measured">Counted by the model at the last reply; the categories are estimated.</string>
|
||||
<string name="activity_estimated">Estimated: no reply has been counted yet.</string>
|
||||
<string name="activity_tools_offered">%1$s tools offered.</string>
|
||||
<string name="ctx_messages">Messages</string>
|
||||
<string name="ctx_system">System prompt</string>
|
||||
<string name="ctx_memory">Memory and personal</string>
|
||||
<string name="ctx_instructions">Instruction files</string>
|
||||
<string name="ctx_tools">Tools</string>
|
||||
<string name="ctx_mcp_tools">MCP tools</string>
|
||||
<string name="ctx_since">Since the last reply</string>
|
||||
<string name="ctx_buffer">Compaction buffer</string>
|
||||
<string name="ctx_free">Free space</string>
|
||||
<string name="tasks_empty">Nothing runs in the background. Subagents, commands and a team\'s members show here while they work.</string>
|
||||
<string name="tasks_none_running">Nothing running.</string>
|
||||
<string name="tasks_running">Running</string>
|
||||
<string name="tasks_finished">Finished</string>
|
||||
<string name="tasks_n_running">%1$s running</string>
|
||||
<string name="tasks_nested">%1$s under it</string>
|
||||
<string name="task_subagent">Subagent</string>
|
||||
<string name="task_command">Command</string>
|
||||
<string name="task_member">Team member</string>
|
||||
<string name="activity_until_compact">%1$s until auto-compact</string>
|
||||
<string name="activity_compact_off">Auto-compact is off.</string>
|
||||
<string name="activity_compact">Compact</string>
|
||||
<string name="agents_n_queued">%1$s queued</string>
|
||||
<string name="agents_n_waiting">%1$s waiting</string>
|
||||
<string name="agents_n_finished">%1$s finished</string>
|
||||
<string name="agent_state_queued">queued</string>
|
||||
<string name="agent_state_working">working</string>
|
||||
<string name="agent_state_waiting">waiting</string>
|
||||
<string name="agent_state_done">done</string>
|
||||
<string name="agent_state_stopped">stopped</string>
|
||||
<string name="agent_state_error">failed</string>
|
||||
<string name="agent_steps">%1$s steps, %2$s tools</string>
|
||||
<string name="agent_open_conversation">Open its conversation</string>
|
||||
<string name="agent_stop">Stop %1$s</string>
|
||||
<string name="agent_stop_member_confirm">Stop %1$s and the members under it? They leave the team.</string>
|
||||
<string name="agent_stop_confirm">Stop %1$s? What it has done so far stays.</string>
|
||||
<string name="agent_nothing_yet">Nothing said yet.</string>
|
||||
<string name="agent_machine">From the system</string>
|
||||
<string name="team_size">Team: %1$s of %2$s subagents</string>
|
||||
<string name="team_room">Room</string>
|
||||
<string name="room_empty">Nothing has been said in the room yet.</string>
|
||||
<string name="room_report">report</string>
|
||||
<string name="team_agents">Subagents</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">The numbers count this chat\'s own agent: 1 is the agent alone, with no subagents, and Max 4 is the agent and up to 3 subagents it leads.</string>
|
||||
<string name="team_chip">Subagents: Min %1$s · Max %2$s</string>
|
||||
<string name="subagents_named_only">This model serves one request at a time: subagents need another model, on another server, named in the chat.</string>
|
||||
<string name="thinking_switch">Think before answering</string>
|
||||
<string name="level_off">off</string>
|
||||
<string name="level_default">default</string>
|
||||
<string name="chats_open">Open the chats</string>
|
||||
<string name="chats_search">Search chats</string>
|
||||
<string name="chats_today">Today</string>
|
||||
<string name="chats_earlier">Earlier</string>
|
||||
<string name="chats_agents">Agent chats</string>
|
||||
<string name="chats_found_in_messages">In the messages</string>
|
||||
<string name="chats_none_found">No chat has that in its title.</string>
|
||||
<string name="clear">Clear</string>
|
||||
<string name="composer_hint_agent">Tell the agent what to do</string>
|
||||
<string name="tune">Options</string>
|
||||
<string name="effort">Effort</string>
|
||||
<string name="thinking_switch_hint">Slower, and better at hard questions.</string>
|
||||
<string name="plan_first">Plan first</string>
|
||||
<string name="plan_first_hint">The model writes a plan for you to approve before it acts.</string>
|
||||
<string name="agent_mode">Mode</string>
|
||||
<string name="agent_greeting">What should the agent do?</string>
|
||||
<string name="agent_runs_on">Runs on %1$s, in %2$s</string>
|
||||
<string name="agent_directory_default">its first folder</string>
|
||||
<string name="kind_chat">Chat</string>
|
||||
<string name="kind_agent">Agent chat</string>
|
||||
<string name="kind_chat_line">Talk with a model: questions, writing, the files you attach.</string>
|
||||
<string name="kind_agent_line">Works on a computer you linked: reads, writes and runs commands in a folder.</string>
|
||||
<string name="agent_link_title">Link a computer first</string>
|
||||
<string name="agent_link_lede">Agent chats run on a machine with the LLeMbas CLI, signed in to this instance and linked. None is linked now.</string>
|
||||
<string name="agent_link_install">Install the LLeMbas CLI on it:</string>
|
||||
<string name="agent_link_login">Sign it in to this instance, and approve the code it shows in the browser that opens:</string>
|
||||
<string name="agent_link_service">To run agent chats on it from here, allow it in its config (~/.config/lembas/config.yaml) and start the service:</string>
|
||||
<string name="agent_link_dials_out">It dials out to this instance; nothing on your machine listens. It decides which directories and modes remote work may use, whatever is asked here.</string>
|
||||
<string name="agent_link_check">Check again</string>
|
||||
<string name="model_choose">Choose a model</string>
|
||||
<string name="model_in_use">In use</string>
|
||||
<string name="model_sees_images">Sees images</string>
|
||||
<string name="model_uses_tools">Uses tools</string>
|
||||
<string name="model_context">%1$s context</string>
|
||||
<string name="model_thinking_switchable">Thinking on or off</string>
|
||||
<string name="model_levels">Effort: %1$s</string>
|
||||
<string name="code">Code</string>
|
||||
<string name="copy_code">Copy code</string>
|
||||
<string name="select_text">Select text</string>
|
||||
<string name="tools_used">Used %1$s tools</string>
|
||||
<string name="suggest_explain">Explain</string>
|
||||
<string name="suggest_explain_line">how something works, in plain words</string>
|
||||
<string name="suggest_write">Write</string>
|
||||
<string name="suggest_write_line">an email, a note or a post</string>
|
||||
<string name="suggest_plan">Plan</string>
|
||||
<string name="suggest_plan_line">a trip, a week or a project</string>
|
||||
<string name="suggest_check">Check</string>
|
||||
<string name="suggest_check_line">a text for mistakes and tone</string>
|
||||
<string name="instance_in_use">In use</string>
|
||||
<string name="notification_settings">Notification settings</string>
|
||||
<string name="notification_settings_hint">Which kinds arrive, and how: replies, questions, scheduled results and failures.</string>
|
||||
<string name="scheduled">Scheduled</string>
|
||||
<string name="scheduled_empty">Nothing is scheduled. Ask for something to happen every morning, or once next week.</string>
|
||||
<string name="scheduled_unsupported">This instance does not offer scheduled tasks yet. They come with a newer LLeMbas on the server.</string>
|
||||
<string name="schedule_new">New schedule</string>
|
||||
<string name="schedule_edit">Edit schedule</string>
|
||||
<string name="schedule_next">Next: %1$s</string>
|
||||
<string name="schedule_paused">Paused</string>
|
||||
<string name="schedule_pause">Pause</string>
|
||||
<string name="schedule_resume">Resume</string>
|
||||
<string name="schedule_run_now">Run now</string>
|
||||
<string name="schedule_started">Started. The result appears in its history.</string>
|
||||
<string name="schedule_next_runs">Next runs</string>
|
||||
<string name="schedule_history">History</string>
|
||||
<string name="schedule_no_runs">It has not run yet.</string>
|
||||
<string name="schedule_model">Model: %1$s</string>
|
||||
<string name="schedule_delete_confirm">Delete this schedule? Its past results stay in their chats.</string>
|
||||
<string name="schedule_words_hint">Say when and what, in your own words. You will see what was understood before anything is saved.</string>
|
||||
<string name="schedule_words_example">Every weekday at 7:30, sum up the news about renewable energy</string>
|
||||
<string name="schedule_preview">Preview</string>
|
||||
<string name="schedule_understood">Understood as</string>
|
||||
<string name="notify_always">Tells you every time</string>
|
||||
<string name="notify_matters">Tells you when it matters</string>
|
||||
<string name="notify_never">Never tells you</string>
|
||||
<string name="run_ok">Done</string>
|
||||
<string name="run_silent">Nothing new</string>
|
||||
<string name="run_unchanged">Unchanged</string>
|
||||
<string name="schedule_computer">Computer</string>
|
||||
<string name="schedule_computer_away">not linked now</string>
|
||||
<string name="schedule_watching">Only when this page changes</string>
|
||||
<string name="schedule_watching_command">Only when this command\'s output changes</string>
|
||||
<string name="run_failed">Failed</string>
|
||||
<string name="run_missed">Missed ×%1$s</string>
|
||||
<string name="run_skipped">Skipped</string>
|
||||
<string name="run_waiting">Waiting for a model</string>
|
||||
<string name="run_waiting_computer">Waiting for the computer</string>
|
||||
<string name="run_running">Running</string>
|
||||
<string name="run_model_instead">%1$s, instead of %2$s</string>
|
||||
<string name="run_retry_at">Tries again at %1$s</string>
|
||||
<string name="run_result">Result</string>
|
||||
<string name="run_no_text">This run left no text.</string>
|
||||
<string name="run_open_chat">Open its chat</string>
|
||||
<string name="mode_fresh">A new chat each time</string>
|
||||
<string name="mode_continue">One chat that grows</string>
|
||||
<string name="schedule_models">Models for scheduled tasks</string>
|
||||
<string name="schedule_models_hint">Scheduled tasks take the first of these that is free, in this order. Untick one to leave it out.</string>
|
||||
<string name="model_free">Free now</string>
|
||||
<string name="model_busy">Busy: %1$s</string>
|
||||
<string name="channel_scheduled">Scheduled results</string>
|
||||
<string name="channel_scheduled_failures">Scheduled failures</string>
|
||||
<string name="scheduled_result_public">A scheduled task has a result.</string>
|
||||
<string name="scheduled_failed_public">A scheduled task failed.</string>
|
||||
<string name="schedule_run_again">Run again</string>
|
||||
<string name="card_approval">Allow this?</string>
|
||||
<string name="card_allow_once">Allow once</string>
|
||||
<string name="card_allow_always">Always allow this</string>
|
||||
@@ -55,10 +255,67 @@
|
||||
<string name="card_answer">Your answer</string>
|
||||
<string name="card_something_else">Something else</string>
|
||||
<string name="card_send">Send</string>
|
||||
<string name="progress_queued">Queued</string>
|
||||
<string name="progress_queued_ahead">Queued: %1$s ahead</string>
|
||||
<string name="progress_waiting_for_model">Waiting for %1$s: %2$s</string>
|
||||
<string name="progress_loading_model">Loading %1$s</string>
|
||||
<string name="progress_reading_prompt">Reading the prompt: %1$s / %2$s tokens (%3$s%%)</string>
|
||||
<string name="progress_reading_prompt_bare">Reading the prompt</string>
|
||||
<string name="progress_thinking">Thinking</string>
|
||||
<string name="progress_writing">Writing: %1$s tok/s</string>
|
||||
<string name="progress_writing_bare">Writing</string>
|
||||
<string name="progress_running_tool">Running %1$s: %2$s</string>
|
||||
<string name="progress_running_tool_bare">Running %1$s</string>
|
||||
<string name="progress_waiting_for_person">Waiting for you: %1$s</string>
|
||||
<string name="progress_waiting_for_subagents">Waiting for subagents: %1$s running</string>
|
||||
<string name="progress_compacting">Compacting the conversation</string>
|
||||
<string name="progress_retrying">Retrying in %1$s s: %2$s</string>
|
||||
<string name="progress_stopped">Stopped</string>
|
||||
<string name="progress_stopped_reason">Stopped: %1$s</string>
|
||||
<string name="progress_failed">Failed: %1$s</string>
|
||||
<string name="progress_reason_busy">it serves one request at a time and is answering another</string>
|
||||
<string name="progress_reason_slots">all its slots are in use</string>
|
||||
<string name="progress_reason_group">its server holds another model now</string>
|
||||
<string name="progress_what_approval">allow %1$s?</string>
|
||||
<string name="progress_what_approval_bare">an approval</string>
|
||||
<string name="progress_what_question">a question</string>
|
||||
<string name="progress_what_plan">the plan</string>
|
||||
<string name="progress_stopped_person">by you</string>
|
||||
<string name="progress_stopped_steps">step limit</string>
|
||||
<string name="progress_stopped_budget">budget</string>
|
||||
<string name="progress_line" translatable="false">%1$s · %2$s</string>
|
||||
<string name="tree_state_working">working</string>
|
||||
<string name="tree_state_waiting">waiting for a slot</string>
|
||||
<string name="tree_state_finished">finished</string>
|
||||
<string name="tree_state_idle">idle</string>
|
||||
<string name="tree_state_paused">paused: context full</string>
|
||||
<string name="tree_state_done">done</string>
|
||||
<string name="tree_state_out_of_context">out of context</string>
|
||||
<string name="tree_state_stopped">stopped</string>
|
||||
<string name="tree_context">%1$s%% context</string>
|
||||
<string name="tree_open_slots">Open slots: %1$s</string>
|
||||
<string name="subagents_device_cannot">The computer this chat runs on does not run subagents: update its LLeMbas CLI.</string>
|
||||
<string name="card_asker">%1$s asks:</string>
|
||||
<string name="card_subagent_asks">Subagent %1$s (%2$s), %3$s, asks:</string>
|
||||
<string name="card_it_says">It says: %1$s</string>
|
||||
<string name="card_change_before">Change this before it runs</string>
|
||||
<string name="card_edit_runs">Allow runs what is in the box. It is not checked against this chat\'s rules again — you typed it.</string>
|
||||
<string name="plan_approve">Approve the plan</string>
|
||||
<string name="plan_revise">Revise</string>
|
||||
<string name="plan_what_to_change">What should change?</string>
|
||||
<string name="plan_carry_out">Carry out the plan</string>
|
||||
<string name="shown">Shown</string>
|
||||
<string name="viewer_open">Open</string>
|
||||
<string name="viewer_open_browser">Open in the browser</string>
|
||||
<string name="viewer_copy">Copy</string>
|
||||
<string name="viewer_html_source">This is the page\'s source. Open it in the browser to see the page itself.</string>
|
||||
<string name="viewer_long_markdown">A long file, so it is shown as plain text.</string>
|
||||
<string name="viewer_unavailable">This server cannot hand the file to the app yet. Open it in the browser instead.</string>
|
||||
<string name="viewer_too_large">This file is too large to show here; at most 1 MB can be shown.</string>
|
||||
<string name="viewer_not_text">This is not a text file, so it is not shown here.</string>
|
||||
<string name="files">Files</string>
|
||||
<string name="files_all">All files</string>
|
||||
<string name="files_empty">Nothing here yet. Not even a hobbit hole.</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
@@ -67,6 +324,13 @@
|
||||
<string name="theme_system">As the system</string>
|
||||
<string name="theme_moria">Moria (dark)</string>
|
||||
<string name="theme_shire">Shire (light)</string>
|
||||
<string name="settings_language">Language</string>
|
||||
<string name="language_hint">The interface only. Models answer in the language you write to them in, whatever this says.</string>
|
||||
<string name="language_account">Same as my account</string>
|
||||
<string name="language_account_is">Same as my account: %1$s</string>
|
||||
<string name="language_account_unknown">Not read from your instance yet</string>
|
||||
<string name="language_phone">Phone language</string>
|
||||
<string name="language_phone_is">Phone language: %1$s</string>
|
||||
<string name="settings_notifications">Notifications</string>
|
||||
<string name="push_explained">Notifications come through UnifiedPush, with no Google services: the distributor app you chose carries them, encrypted for this phone only.</string>
|
||||
<string name="push_no_distributor">To be told when a reply is ready, install a UnifiedPush distributor such as ntfy, then come back here. Without one, the app shows new replies when it is open.</string>
|
||||
@@ -75,7 +339,6 @@
|
||||
<string name="push_failed">No distributor was chosen, so notifications are still off.</string>
|
||||
<string name="channel_replies">Replies</string>
|
||||
<string name="channel_asks">Questions and approvals</string>
|
||||
<string name="channel_reports">Reports</string>
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Make LLeMbas the phone\'s digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen\'s shortcut opens it over whatever is on screen.</string>
|
||||
<string name="assistant_open_settings">Open the assistant settings</string>
|
||||
@@ -90,11 +353,54 @@
|
||||
<string name="update_allow_installs">Allow LLeMbas to install updates, then check again.</string>
|
||||
<string name="update_bad_file">The download did not match the release and was discarded.</string>
|
||||
<string name="update_installing">Installing %1$s…</string>
|
||||
<string name="update_checking">Checking…</string>
|
||||
<string name="update_available">%1$s is available. Tap to open its release page.</string>
|
||||
<string name="update_install">Install %1$s</string>
|
||||
<string name="update_auto">Look for new versions</string>
|
||||
<string name="update_auto_line">At most once a day, when the app starts, it asks your instance which release goes with it (an older instance: the list of releases on GitHub) and tells you in a notification when there is a newer one. Nothing about you is sent anywhere else. On by default in a beta, off otherwise.</string>
|
||||
<string name="update_betas">Include betas</string>
|
||||
<string name="update_betas_line">Offer test versions as well as releases. On by default when this app is itself a beta.</string>
|
||||
<string name="channel_updates">App updates</string>
|
||||
<string name="update_notice_title">LLeMbas for Android %1$s</string>
|
||||
<string name="update_notice_text">A newer version is available. Tap to open its release page.</string>
|
||||
<string name="assist_hint">Ask anything</string>
|
||||
<string name="assist_include_screen">Include screen</string>
|
||||
<string name="assist_signed_out">Sign in to a LLeMbas instance in the app first.</string>
|
||||
<string name="assist_open_app">Open the app</string>
|
||||
<string name="assist_open_in_app">Continue in the app</string>
|
||||
<string name="assist_use_screen">Use screen</string>
|
||||
<string name="assist_screen_both">The screen\'s text and a screenshot go with your next question.</string>
|
||||
<string name="assist_screen_text">The screen\'s text goes with your next question.</string>
|
||||
<string name="assist_screen_shot">A screenshot goes with your next question.</string>
|
||||
<string name="assist_quick_summarise">Summarise this</string>
|
||||
<string name="assist_quick_summarise_prompt">Summarise what is on my screen.</string>
|
||||
<string name="assist_quick_translate">Translate this</string>
|
||||
<string name="assist_quick_translate_prompt">Translate what is on my screen into English.</string>
|
||||
<string name="assist_quick_explain">Explain this</string>
|
||||
<string name="assist_quick_explain_prompt">Explain what is on my screen.</string>
|
||||
<string name="assist_continue">Continue the last chat</string>
|
||||
<string name="assist_help">Hold the power button to open the assistant over any app, or use the Quick Settings tile.</string>
|
||||
<string name="assist_no_wake_word">There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone.</string>
|
||||
<string name="assist_connecting">Connecting…</string>
|
||||
<string name="assist_offline">%1$s cannot be reached</string>
|
||||
<string name="assist_no_model">No model</string>
|
||||
<string name="assist_voice_reply_on">Voice reply is on</string>
|
||||
<string name="assist_voice_reply_off">Voice reply is off</string>
|
||||
<string name="assist_read_aloud">Read aloud</string>
|
||||
<string name="assist_stop_reading">Stop reading</string>
|
||||
<string name="assist_answer_in_app">This reply is waiting for your answer: open it in the app.</string>
|
||||
<string name="assist_send_now">Send what I said</string>
|
||||
<string name="assist_say_it">Say it, then pause</string>
|
||||
<string name="assist_type">Type instead</string>
|
||||
<string name="assist_writing_down">Writing down what you said…</string>
|
||||
<string name="assist_recogniser_failed">The phone\'s speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input.</string>
|
||||
<string name="assistant_listens">Start listening when the assistant opens</string>
|
||||
<string name="voice_input">Voice input</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Your instance\'s speech-to-text, through the server. The recording goes to your instance and nowhere else.</string>
|
||||
<string name="voice_input_phone">Phone (Google or the system\'s)</string>
|
||||
<string name="voice_input_phone_line">The phone\'s own recogniser. The words appear as you speak; the recording goes wherever that recogniser sends it.</string>
|
||||
<string name="voice_input_phone_none">This phone has no speech recogniser of its own.</string>
|
||||
<string name="voice_input_hint">Used by the assistant and by the microphone in a chat. With LLeMbas the assistant shows the words a moment behind you and a pause sends them, and a chat writes them down when you stop; with the phone\'s recogniser they appear as you speak.</string>
|
||||
<string name="share_sending">Sending to LLeMbas…</string>
|
||||
<string name="share_default_prompt">Have a look at this.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- The one folder the app shares with another app: the cache folder a photo for the composer
|
||||
is taken into. The camera app may write the one file it was given, and nothing else. -->
|
||||
<paths>
|
||||
<cache-path name="camera" path="camera/" />
|
||||
</paths>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/gen-strings.py. Edit LANGS there. -->
|
||||
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<locale android:name="en" />
|
||||
<locale android:name="cs" />
|
||||
<locale android:name="de" />
|
||||
<locale android:name="es" />
|
||||
<locale android:name="fr" />
|
||||
<locale android:name="hu" />
|
||||
<locale android:name="it" />
|
||||
<locale android:name="pl" />
|
||||
<locale android:name="sk" />
|
||||
</locale-config>
|
||||
@@ -1,7 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- A self-hosted instance often sits behind its owner's own certificate authority. Trusting
|
||||
the CAs the person installed on this phone (Settings › Security › Install a certificate)
|
||||
is what lets the app reach it -- the same step the browser needs. No plain HTTP: a token
|
||||
is what lets the app reach it: the same step the browser needs. No plain HTTP: a token
|
||||
goes with every request. -->
|
||||
<network-security-config>
|
||||
<base-config cleartextTrafficPermitted="false">
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ActivityEnvelope
|
||||
import eu.llembas.android.api.ActivityFrame
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentDetail
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ContextUse
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.TeamEnvelope
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The beta.5 `/api/v2` (server dev, pinned in `contract/`): the models' levels and pictures, a
|
||||
* chat's team size, and the activity panel -- parsed with the app's models, then the panel's
|
||||
* arithmetic on what they said.
|
||||
*/
|
||||
class ActivityTest {
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T {
|
||||
val text = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
return LembasJson.decodeFromString(serializer, text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theModelsSayTheirLevelsAndControl() {
|
||||
val (qwen, gptOss, vision) = read("models", ModelList.serializer()).models
|
||||
assertEquals(listOf("off", "medium"), qwen.offered)
|
||||
assertEquals("switch", qwen.levelControl)
|
||||
assertTrue(qwen.thinkingSwitch)
|
||||
assertEquals("medium", qwen.onLevel)
|
||||
assertEquals(2, qwen.parallel)
|
||||
assertEquals("/api/v2/models/images/0a1b2c3d4e5f.png", qwen.image)
|
||||
assertTrue(qwen.mayHaveTeam)
|
||||
|
||||
assertEquals("slider", gptOss.levelControl)
|
||||
assertEquals("high", gptOss.level(null))
|
||||
assertEquals("low", gptOss.level("low"))
|
||||
// A level the model does not offer (an `off` from before) reads as its start level.
|
||||
assertEquals("high", gptOss.level("off"))
|
||||
// One request at a time: offered all the same, for a model the person names (server 3.3.0 rule).
|
||||
assertTrue(gptOss.mayHaveTeam)
|
||||
assertTrue(gptOss.subagents!!.namedOnly)
|
||||
assertNull(gptOss.image)
|
||||
|
||||
assertEquals("none", vision.levelControl)
|
||||
assertEquals("default", vision.level(null))
|
||||
// No stated limit, but no tools: no team.
|
||||
assertNull(vision.parallel)
|
||||
assertFalse(vision.mayHaveTeam)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOlderServersModelStillGetsAControl() {
|
||||
// Before beta.5: `efforts` only. The app offered "off" before them, as it did then.
|
||||
val old = ModelInfo(id = "m", efforts = listOf("low", "high"))
|
||||
assertEquals(listOf("off", "low", "high"), old.offered)
|
||||
assertEquals("slider", old.levelControl)
|
||||
assertEquals("none", ModelInfo(id = "n").levelControl)
|
||||
assertEquals("switch", ModelInfo(id = "s", efforts = listOf("medium")).levelControl)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPictureIsOnlyTheInstancesOwn() {
|
||||
val base = "https://example.org"
|
||||
assertEquals("https://example.org/api/v2/models/images/0a1b.png", ApiClient.modelImageUrl(base, "/api/v2/models/images/0a1b.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, null))
|
||||
assertNull(ApiClient.modelImageUrl(base, "https://elsewhere.example/x.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/../../me"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/a/b.png"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/api/v2/models/images/.hidden"))
|
||||
assertNull(ApiClient.modelImageUrl(base, "/uploads/models/x.png"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChatSaysItsTeamSizeAndDeviceSession() {
|
||||
val chat = read("chat", Chat.serializer())
|
||||
assertEquals(AgentsSetting(1, 4), chat.agents)
|
||||
assertNull(chat.deviceSessionId)
|
||||
assertEquals("ses_01waybread", read("chat_agent", Chat.serializer()).deviceSessionId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theActivityPanel() {
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
assertEquals("0123456789abcdef", activity.version)
|
||||
assertEquals(3, activity.summary.active)
|
||||
assertTrue(activity.teamOffered)
|
||||
|
||||
val (baker, job) = activity.agents
|
||||
assertEquals("member", baker.kind)
|
||||
assertEquals("read", baker.step?.tool)
|
||||
assertTrue(baker.step!!.running)
|
||||
assertEquals(listOf("wrapper", "baker:job1"), baker.children.map { it.id })
|
||||
assertEquals("command", job.type)
|
||||
assertFalse(job.transcript)
|
||||
|
||||
// The tree, flattened in order for drawing; the split is by the top level's state.
|
||||
assertEquals(listOf("baker", "wrapper", "baker:job1", "job1"), ActivityLogic.flatten(activity.agents).map { it.id })
|
||||
val (live, ended) = ActivityLogic.split(activity.agents)
|
||||
assertEquals(2, live.size)
|
||||
assertTrue(ended.isEmpty())
|
||||
|
||||
val team = activity.team!!
|
||||
assertEquals(3, team.size)
|
||||
assertEquals(2, team.cursor)
|
||||
assertTrue(team.room[1].report)
|
||||
assertEquals(listOf("baker"), team.room[1].to)
|
||||
|
||||
val context = activity.context!!
|
||||
assertEquals(128000, context.limit)
|
||||
assertEquals(listOf("messages", "system"), ActivityLogic.barParts(context).map { it.key })
|
||||
assertEquals("/home/frodo/recipe.md", activity.outputs.single().path)
|
||||
assertEquals(42, activity.outputs.single().added)
|
||||
assertNull(ActivityLogic.plan(activity.plan))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAgentsConversationAndTheTeamAndTheEvent() {
|
||||
val detail = read("agent", AgentDetail.serializer())
|
||||
assertEquals("baker", detail.agent.name)
|
||||
assertEquals(listOf("user", "assistant"), detail.transcript.map { it.role })
|
||||
assertEquals("recipe.md", detail.transcript[1].tools.single().title)
|
||||
assertTrue(detail.transcript[1].running)
|
||||
|
||||
val team = read("team", TeamEnvelope.serializer()).team
|
||||
assertTrue(team.offered)
|
||||
assertEquals(listOf(0, 1, 2), team.agents.map { it.depth })
|
||||
assertNull(team.agents[0].manager)
|
||||
|
||||
val frame = read("event_activity", ActivityFrame.serializer())
|
||||
assertEquals("0123456789abcdef", frame.version)
|
||||
assertEquals(2, frame.summary.working)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theStripCountsWhatIsGoing() {
|
||||
val summary = ActivitySummary(queued = 1, working = 3, waiting = 0, done = 4, finished = 4, active = 4, total = 8)
|
||||
assertEquals(listOf("working" to 3, "queued" to 1, "finished" to 4), ActivityLogic.stripCounts(summary))
|
||||
assertTrue(ActivityLogic.stripCounts(ActivitySummary(done = 2, finished = 2)).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoCompactIsCountedOnlyAgainstAKnownWindow() {
|
||||
// The app's own count, without the server's: 95 % of 128k is 121.6k; 41k used.
|
||||
val context = read("activity", ActivityEnvelope.serializer()).activity.context!!.copy(autoCompact = null, untilCompact = null)
|
||||
assertEquals(80_600, ActivityLogic.untilAutoCompact(context))
|
||||
assertEquals(0, ActivityLogic.untilAutoCompact(context.copy(used = 127_000)))
|
||||
assertNull(ActivityLogic.untilAutoCompact(context.copy(threshold = 0)))
|
||||
assertNull(ActivityLogic.untilAutoCompact(context.copy(limit = 0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTaskIsCalledByWhatItWasAskedToDo() {
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
val (baker, command) = activity.agents
|
||||
assertEquals("baker", ActivityLogic.title(baker))
|
||||
assertEquals("find mallorn leaves", ActivityLogic.title(baker.children[1]))
|
||||
assertEquals("pytest", ActivityLogic.title(command))
|
||||
assertEquals(2, ActivityLogic.descendants(baker))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun numbersAsTheServerWritesThem() {
|
||||
assertEquals("950", ActivityLogic.compactTokens(950))
|
||||
assertEquals("14.2k", ActivityLogic.compactTokens(14_200))
|
||||
assertEquals("41k", ActivityLogic.compactTokens(41_000))
|
||||
assertEquals("180k", ActivityLogic.compactTokens(180_400))
|
||||
assertEquals("1.54M", ActivityLogic.compactTokens(1_540_000))
|
||||
assertEquals("1M", ActivityLogic.compactTokens(1_000_000))
|
||||
assertEquals("5s", ActivityLogic.duration(5))
|
||||
assertEquals("1m 05s", ActivityLogic.duration(65))
|
||||
assertEquals("2h 03m", ActivityLogic.duration(7_380))
|
||||
assertEquals("32", ActivityLogic.percent(32.0))
|
||||
assertEquals("23.4", ActivityLogic.percent(23.4))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun elapsedTimeRunsOnOnlyForOneThatIsGoing() {
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
val (baker, _) = activity.agents
|
||||
val wrapper = baker.children[0]
|
||||
val subagent = baker.children[1]
|
||||
assertEquals(105L, ActivityLogic.elapsed(baker, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
assertEquals(0L, ActivityLogic.elapsed(wrapper, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
assertEquals(12L, ActivityLogic.elapsed(subagent, readAtMillis = 1_000, nowMillis = 11_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noWindowNoBar() {
|
||||
assertTrue(ActivityLogic.barParts(ContextUse(used = 10, limit = 0)).isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.Tail
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.AssistTurn
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.SheetStop
|
||||
import eu.llembas.android.assist.settle
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AssistTest {
|
||||
private val half = 1000f
|
||||
private val full = 1800f
|
||||
|
||||
@Test
|
||||
fun aSlowReleaseGoesToTheNearestStop() {
|
||||
assertEquals(SheetStop.Half, settle(1100f, half, full, 0f))
|
||||
assertEquals(SheetStop.Full, settle(1500f, half, full, 0f))
|
||||
assertEquals(SheetStop.Half, settle(800f, half, full, 0f))
|
||||
// Pulled well below the half: it goes.
|
||||
assertEquals(SheetStop.Gone, settle(500f, half, full, 0f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFlingDecidesByItsDirection() {
|
||||
assertEquals(SheetStop.Full, settle(1010f, half, full, -3000f))
|
||||
// Down from the full height: to the half, not away.
|
||||
assertEquals(SheetStop.Half, settle(1700f, half, full, 3000f))
|
||||
// Down from the half: away.
|
||||
assertEquals(SheetStop.Gone, settle(990f, half, full, 3000f))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTurnShowsWhatIsWrittenThenWhatWasWritten() {
|
||||
val asked = AssistTurn("Why?")
|
||||
assertFalse(asked.writing)
|
||||
val writing = asked.copy(reply = LiveReply("m1", tail = Tail(text = "Because")))
|
||||
assertTrue(writing.writing)
|
||||
assertEquals("Because", writing.steps.single().markdown)
|
||||
val earlier = AssistTurn("Why?", earlier = listOf(Step(kind = "text", markdown = "Because.")))
|
||||
assertFalse(earlier.writing)
|
||||
assertEquals("Because.", earlier.steps.single().markdown)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aVoiceReadsOnlyTheWords() {
|
||||
val steps = listOf(
|
||||
Step(kind = "thinking", text = "Hmm."),
|
||||
Step(kind = "text", markdown = "**Two** days."),
|
||||
Step(kind = "tools"),
|
||||
Step(kind = "text", markdown = "See [this](https://example.org)."),
|
||||
)
|
||||
assertEquals("Two days. See this.", AssistController.spokenWords(steps))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun silenceIsQuietAndAToneIsLoud() {
|
||||
assertEquals(0f, Recorder.rms(ByteArray(3200), 3200), 0f)
|
||||
// A full-scale square wave: every sample at +-32767.
|
||||
val loud = ByteArray(3200) { i ->
|
||||
if (i % 2 == 0) {
|
||||
0xFF.toByte()
|
||||
} else if ((i / 2) % 2 == 0) {
|
||||
0x7F
|
||||
} else {
|
||||
0x80.toByte()
|
||||
}
|
||||
}
|
||||
assertTrue(Recorder.rms(loud, loud.size) > 0.9f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun voiceInputChoosesTheSameRecogniserForTheAssistantAndTheChat() {
|
||||
// Chosen and present: the phone's.
|
||||
assertTrue(usePhoneRecognizer(Prefs.VOICE_PHONE, phoneHas = true, instanceStt = null))
|
||||
// Chosen but absent: the instance's, whatever it said.
|
||||
assertFalse(usePhoneRecognizer(Prefs.VOICE_PHONE, phoneHas = false, instanceStt = false))
|
||||
// LLeMbas chosen: the instance's, unless it said it has no speech-to-text.
|
||||
assertFalse(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = null))
|
||||
assertFalse(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = true))
|
||||
assertTrue(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.ui.home.folderTree
|
||||
import eu.llembas.android.ui.home.groupChats
|
||||
import eu.llembas.android.ui.home.markedSnippet
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
|
||||
class ChatGroupsTest {
|
||||
private val zone = ZoneId.of("Europe/Bratislava")
|
||||
private val today = LocalDate.of(2026, 3, 10)
|
||||
|
||||
private fun chat(id: String, title: String, updated: String?, kind: String = "chat") = Chat(id = id, title = title, kind = kind, updatedAt = updated)
|
||||
|
||||
@Test
|
||||
fun todayEarlierAndAgentsKeepTheirOrder() {
|
||||
val chats = listOf(
|
||||
chat("a", "Bread", "2026-03-10T08:00:00+00:00"),
|
||||
chat("b", "Repo", "2026-03-10T07:00:00+00:00", kind = "agent"),
|
||||
chat("c", "Honey", "2026-03-09T12:00:00+00:00"),
|
||||
chat("d", "Old", null),
|
||||
)
|
||||
val groups = groupChats(chats, "", today, zone)
|
||||
assertEquals(listOf("a"), groups.today.map { it.id })
|
||||
assertEquals(listOf("c", "d"), groups.earlier.map { it.id })
|
||||
assertEquals(listOf("b"), groups.agents.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theDayIsThePhones() {
|
||||
// 23:30 UTC on the 9th is already the 10th in Central Europe.
|
||||
val groups = groupChats(listOf(chat("a", "Late", "2026-03-09T23:30:00+00:00")), "", today, zone)
|
||||
assertEquals(listOf("a"), groups.today.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun searchMatchesTheTitleInAnyCase() {
|
||||
val chats = listOf(chat("a", "Lembas bread", null), chat("b", "Ropes", null))
|
||||
assertEquals(listOf("a"), groupChats(chats, " BREAD ", today, zone).earlier.map { it.id })
|
||||
assertTrue(groupChats(chats, "nothing", today, zone).isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinnedFirstWhereverFiledAndFoldersAsATree() {
|
||||
val folders = listOf(
|
||||
Folder("inner", "Recipes", parentId = "top", position = 0),
|
||||
Folder("top", "Waybread", position = 1),
|
||||
Folder("first", "Letters", position = 0),
|
||||
// Its parent is not in the list: shown at the top rather than lost.
|
||||
Folder("stray", "Stray", parentId = "gone", position = 2),
|
||||
)
|
||||
assertEquals(listOf("first" to 0, "top" to 0, "inner" to 1, "stray" to 0), folderTree(folders).map { it.first.id to it.second })
|
||||
|
||||
val chats = listOf(
|
||||
Chat(id = "p", title = "Pinned and filed", folderId = "inner", pinned = true),
|
||||
Chat(id = "r", title = "Rye", folderId = "inner"),
|
||||
Chat(id = "w", title = "Wrapping", folderId = "top"),
|
||||
Chat(id = "u", title = "Unfiled", updatedAt = "2026-03-10T08:00:00+00:00"),
|
||||
Chat(id = "x", title = "In a folder this list does not have", folderId = "elsewhere"),
|
||||
)
|
||||
val groups = groupChats(chats, "", today, zone, folders)
|
||||
assertEquals(listOf("p"), groups.pinned.map { it.id })
|
||||
assertEquals(
|
||||
listOf("first" to emptyList(), "top" to listOf("w"), "inner" to listOf("r"), "stray" to emptyList<String>()),
|
||||
groups.folders.map {
|
||||
it.folder.id to
|
||||
it.chats.map { c -> c.id }
|
||||
},
|
||||
)
|
||||
assertEquals(listOf("u"), groups.today.map { it.id })
|
||||
assertEquals(listOf("x"), groups.earlier.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aCollapsedFolderHidesItsChatsAndTheFoldersInside() {
|
||||
val folders = listOf(Folder("top", "Waybread", collapsed = true), Folder("inner", "Recipes", parentId = "top"), Folder("next", "Letters", position = 1))
|
||||
val chats = listOf(Chat(id = "r", title = "Rye", folderId = "inner"), Chat(id = "w", title = "Wrapping", folderId = "top"))
|
||||
val groups = groupChats(chats, "", today, zone, folders)
|
||||
assertEquals(listOf("top" to emptyList(), "next" to emptyList<String>()), groups.folders.map { it.folder.id to it.chats.map { c -> c.id } })
|
||||
assertFalse(groups.isEmpty)
|
||||
// Searching opens everything, and leaves out folders without a match.
|
||||
val found = groupChats(chats, "rye", today, zone, folders)
|
||||
assertEquals(listOf("inner" to listOf("r")), found.folders.map { it.folder.id to it.chats.map { c -> c.id } })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSnippetsMarksAndOnesThatDoNotFit() {
|
||||
val bold = SpanStyle(fontWeight = FontWeight.Bold)
|
||||
val marked = markedSnippet("how long does lembas keep", listOf(listOf(14, 20), listOf(22, 99), listOf(5), listOf(9, 3)), bold)
|
||||
assertEquals("how long does lembas keep", marked.text)
|
||||
assertEquals(listOf(14 to 20, 22 to 25), marked.spanStyles.map { it.start to it.end })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AgentSubagents
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.SubagentsOffer
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.chat.agents
|
||||
import eu.llembas.android.ui.chat.compactContext
|
||||
import eu.llembas.android.ui.chat.device
|
||||
import eu.llembas.android.ui.chat.level
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.chat.offersTeam
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** What the top bar, the composer and the tune sheet read from a chat's state. */
|
||||
class ChatStateTest {
|
||||
private val models = LembasJson.decodeFromString(
|
||||
ModelList.serializer(),
|
||||
requireNotNull(javaClass.classLoader!!.getResource("models.json")).readText(),
|
||||
).models
|
||||
|
||||
@Test
|
||||
fun theModelIsTheChatsThenTheDraftsThenTheDefault() {
|
||||
assertEquals("qwen", ChatState(models = models).modelId)
|
||||
assertEquals("gpt-oss", ChatState(models = models, draft = Draft(model = "gpt-oss")).modelId)
|
||||
assertEquals("vision-small", ChatState(models = models, chat = Chat(id = "c", model = "vision-small"), draft = Draft(model = "gpt-oss")).modelId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theLevelFollowsTheModelsControl() {
|
||||
// A switch model starts at its effort; one level is no choice at all.
|
||||
assertEquals("medium", ChatState(models = models).level)
|
||||
assertEquals("off", ChatState(models = models, draft = Draft(effort = "off")).level)
|
||||
assertNull(ChatState(models = models, draft = Draft(model = "vision-small")).level)
|
||||
// A level the model does not offer falls back to its own.
|
||||
assertEquals("high", ChatState(models = models, chat = Chat(id = "c", model = "gpt-oss", effort = "extreme")).level)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTeamIsOfferedByTheServerOrGuessedForANewChat() {
|
||||
assertTrue(ChatState(models = models).offersTeam(agent = false))
|
||||
assertFalse(ChatState(models = models).offersTeam(agent = true))
|
||||
// gpt-oss serves one at a time: offered, for a model named in the chat; vision-small not at all.
|
||||
assertTrue(ChatState(models = models, draft = Draft(model = "gpt-oss")).offersTeam(agent = false))
|
||||
assertFalse(ChatState(models = models, draft = Draft(model = "vision-small")).offersTeam(agent = false))
|
||||
assertTrue(ChatState(models = models, chat = Chat(id = "c", model = "gpt-oss"), teamOffered = true).offersTeam(agent = false))
|
||||
assertEquals(AgentsSetting(2, 6), ChatState(draft = Draft(agents = AgentsSetting(2, 6))).agents)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAgentChatHasTheSliderWhenTheServerOffersIt() {
|
||||
// Its subagents run on its device (spec 3.4.0 §14): the chat's own word decides, never a guess.
|
||||
val agentChat = Chat(id = "a", kind = "agent", model = "qwen")
|
||||
assertTrue(ChatState(models = models, chat = agentChat.copy(subagents = SubagentsOffer(offered = true, cap = 8))).offersTeam(agent = true))
|
||||
assertFalse(ChatState(models = models, chat = agentChat.copy(subagents = SubagentsOffer(offered = false, cap = 32))).offersTeam(agent = true))
|
||||
// A new agent chat: the server's fact for agent chats, never the model's guess.
|
||||
assertTrue(ChatState(models = models, agentSubagents = AgentSubagents(offered = true)).offersTeam(agent = true))
|
||||
assertFalse(ChatState(models = models, agentSubagents = AgentSubagents(offered = false)).offersTeam(agent = true))
|
||||
assertFalse(ChatState(models = models).offersTeam(agent = true))
|
||||
// A listed chat (`subagents: null`) asks the chat's activity.
|
||||
assertTrue(ChatState(models = models, chat = agentChat, teamOffered = true).offersTeam(agent = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewAgentChatRunsOnTheChosenDeviceOrTheFirst() {
|
||||
val devices = listOf(LinkedDevice("d1"), LinkedDevice("d2"))
|
||||
assertEquals("d1", ChatState(devices = devices).device?.id)
|
||||
assertEquals("d2", ChatState(devices = devices, draft = Draft(device = "d2")).device?.id)
|
||||
assertNull(ChatState().device)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun contextWindowsAreSaidShort() {
|
||||
assertEquals("128K", compactContext(131072))
|
||||
assertEquals("8K", compactContext(8192))
|
||||
assertEquals("1M", compactContext(1_000_000))
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,24 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AgentTarget
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.ui.unreachable
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.net.ConnectException
|
||||
import java.net.UnknownHostException
|
||||
|
||||
class ClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
@@ -33,6 +39,35 @@ class ClientTest {
|
||||
assertEquals("http://10.1.2.3:8080", normaliseBase("http://10.1.2.3:8080"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAgentChatNamesItsDeviceAndFolder() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody("""{"chat":{"id":"c1","kind":"agent"}}"""))
|
||||
val made = client().createChat("Look around", mode = "edit", agent = AgentTarget("tok1", " ~/src/shire "))
|
||||
assertEquals("agent", made.chat.kind)
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertTrue(body, body.contains("\"kind\":\"agent\""))
|
||||
assertTrue(body, body.contains("\"device\":\"tok1\""))
|
||||
assertTrue(body, body.contains("\"directory\":\"~/src/shire\""))
|
||||
assertTrue(body, body.contains("\"mode\":\"edit\""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPlainChatSaysNothingOfDevices() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody("""{"chat":{"id":"c2"}}"""))
|
||||
client().createChat("Hello", effort = "low")
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertFalse(body, body.contains("device"))
|
||||
assertFalse(body, body.contains("kind"))
|
||||
assertTrue(body, body.contains("\"effort\":\"low\""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun unreachableIsNotARefusal() {
|
||||
assertTrue(unreachable(UnknownHostException("llm.example.org")))
|
||||
assertTrue(unreachable(ConnectException("refused")))
|
||||
assertFalse(unreachable(ApiException(403, "No.")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyCallCarriesTheToken() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"api":1,"account":{"name":"Frodo","email":"f@shire.test"}}"""))
|
||||
@@ -61,4 +96,39 @@ class ClientTest {
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertTrue(body, body.contains(""""choices":{"q0":["Tea"]}"""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShownFileIsTheShowRouteAsPlainText() = runTest {
|
||||
server.enqueue(MockResponse().setHeader("Content-Type", "text/plain; charset=utf-8").setBody("# Lembas\n"))
|
||||
server.enqueue(MockResponse().setBody("x"))
|
||||
val api = client()
|
||||
val tree = ShowCard(path = "/home/frodo/recipe.md", nodeId = "node1", versionId = "ver1")
|
||||
assertEquals("# Lembas\n", api.shownText("chat1", tree))
|
||||
assertEquals("/api/v2/chats/chat1/show?node=node1&version=ver1", server.takeRequest().path)
|
||||
api.shownText("chat1", ShowCard(path = "src/oven.py", source = "device", shownId = "shown1"))
|
||||
assertEquals("/api/v2/chats/chat1/show?shown=shown1", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShownFileTheServerWillNotGiveIsItsStatus() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(415).setBody("""{"detail":"This is not a text file, so it is not shown here."}"""))
|
||||
try {
|
||||
client().shownText("chat1", ShowCard(nodeId = "n", versionId = "v"))
|
||||
fail("a 415 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(415, e.status)
|
||||
assertEquals("This is not a text file, so it is not shown here.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theFilesRoutesTakeThePathAsAQuery() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"path":"/home/frodo","parent":"/home","entries":[]}"""))
|
||||
server.enqueue(MockResponse().setBody("""{"path":"/home/frodo/a b.md","name":"a b.md","text":"hi"}"""))
|
||||
val api = client()
|
||||
assertEquals("/home", api.files("/home/frodo").parent)
|
||||
assertEquals("/api/v2/files?path=%2Fhome%2Ffrodo", server.takeRequest().path)
|
||||
assertEquals("hi", api.fileContent("/home/frodo/a b.md").text)
|
||||
assertEquals("/api/v2/files/content?path=%2Fhome%2Ffrodo%2Fa%20b.md", server.takeRequest().path)
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,43 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.APP_API
|
||||
import eu.llembas.android.api.AgentSubagents
|
||||
import eu.llembas.android.api.AskFrame
|
||||
import eu.llembas.android.api.CardSubagent
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.DoneFrame
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.FolderEnvelope
|
||||
import eu.llembas.android.api.FolderList
|
||||
import eu.llembas.android.api.JobsFrame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Me
|
||||
import eu.llembas.android.api.MemoryEnvelope
|
||||
import eu.llembas.android.api.MemoryList
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Metrics
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.SearchResults
|
||||
import eu.llembas.android.api.StatusFrame
|
||||
import eu.llembas.android.api.SteeredFrame
|
||||
import eu.llembas.android.api.StepsFrame
|
||||
import eu.llembas.android.api.SubagentTranscript
|
||||
import eu.llembas.android.api.Tail
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.TreeFrame
|
||||
import eu.llembas.android.api.TreeView
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.approvalTexts
|
||||
import eu.llembas.android.ui.chat.offersTeam
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
@@ -29,10 +52,110 @@ class ContractTest {
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(serializer, text(name))
|
||||
|
||||
@Test
|
||||
fun theFoldersAndOne() {
|
||||
val folders = read("folders", FolderList.serializer()).folders
|
||||
assertEquals(listOf("fold1", "fold2"), folders.map { it.id })
|
||||
assertEquals("fold1", folders[1].parentId)
|
||||
assertTrue(folders[1].collapsed)
|
||||
assertEquals("Waybread", read("folder", FolderEnvelope.serializer()).folder.name)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMemoriesAndOne() {
|
||||
val list = read("memories", MemoryList.serializer())
|
||||
val one = list.memories.single()
|
||||
assertEquals("Prefers lembas warm.", one.content)
|
||||
assertFalse(one.byModel)
|
||||
assertEquals("default", one.dataGroup.id)
|
||||
assertEquals(listOf("Default"), list.groups.map { it.name })
|
||||
assertEquals("mem1", read("memory", MemoryEnvelope.serializer()).memory.id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSearchFindsAChatAFileAndAMemory() {
|
||||
val found = read("search", SearchResults.serializer())
|
||||
assertEquals(listOf("chats", "files", "memories"), found.offered)
|
||||
val chat = found.hits("chats").single()
|
||||
assertEquals("chat1", chat.id)
|
||||
assertEquals("lembas", chat.snippet.substring(chat.marks[0][0], chat.marks[0][1]))
|
||||
assertEquals("/home/frodo/bread.md", found.hits("files").single().path)
|
||||
assertEquals("mem1", found.hits("memories").single().id)
|
||||
assertTrue(found.results.first().more)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScheduleThatRunsOnAComputer() {
|
||||
val schedule = LembasJson.parseToJsonElement(text("schedule_on_device")).jsonObject
|
||||
// Parsed by the app's model without a field for it yet: the rest must still read.
|
||||
assertEquals("sched3", read("schedule_on_device", eu.llembas.android.api.ScheduleEnvelope.serializer()).schedule.id)
|
||||
assertTrue("runs_on" in schedule.getValue("schedule").jsonObject)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theVersionIsOneThisAppReads() {
|
||||
val version = LembasJson.parseToJsonElement(text("version")).toString()
|
||||
assertEquals("""{"app_api":1}""", version)
|
||||
assertEquals("""{"app_api":$APP_API}""", version)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShowCardFromTheTreeAndOneFromADevice() {
|
||||
// The server's own `show` cards (`tool_show.json`): what the app reads them by, and the
|
||||
// query that fetches the text from `GET /api/v2/chats/{chat}/show`.
|
||||
val calls = LembasJson.parseToJsonElement(text("tool_show")).jsonObject.getValue("calls")
|
||||
val (tree, device) = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
|
||||
val show = tree.show!!
|
||||
assertEquals("show", tree.name)
|
||||
assertEquals("recipe.md", show.name)
|
||||
assertEquals("/home/frodo/recipe.md", show.path)
|
||||
assertEquals("markdown", show.viewKind)
|
||||
assertEquals(3, show.line)
|
||||
assertEquals(120L, show.size)
|
||||
assertEquals(listOf("node" to "node1", "version" to "ver1"), show.query)
|
||||
|
||||
val kept = device.show!!
|
||||
assertEquals("device", kept.source)
|
||||
assertEquals("code", kept.viewKind)
|
||||
assertEquals("python", kept.language)
|
||||
// `line: null` reads as no line, and the tree's two ids are empty on a device's card.
|
||||
assertEquals(0, kept.line)
|
||||
assertEquals(listOf("shown" to "shown1"), kept.query)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDirectoryOfThePersonsFiles() {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
assertEquals("/home/frodo", listing.path)
|
||||
assertEquals("/home", listing.parent)
|
||||
assertEquals(listOf("recipes", "lembas.md"), listing.entries.map { it.name })
|
||||
assertTrue(listing.entries[0].isFolder)
|
||||
val file = listing.entries[1]
|
||||
assertFalse(file.isFolder)
|
||||
assertEquals(27L, file.size)
|
||||
assertEquals("text/markdown", file.mime)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFileAndAWithheldOne() {
|
||||
val file = read("file_content", FileContent.serializer())
|
||||
assertNull(file.withheld)
|
||||
assertEquals("markdown", file.viewKind)
|
||||
assertTrue(file.text.startsWith("# Lembas"))
|
||||
|
||||
val image = read("file_content_withheld", FileContent.serializer())
|
||||
assertEquals("", image.text)
|
||||
assertEquals("not_text", image.withheld!!.reason)
|
||||
assertTrue(image.withheld!!.message.isNotBlank())
|
||||
// An image is no kind the viewer draws, so if its text ever came it would be plain text.
|
||||
assertEquals("text", image.viewKind)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTwoPointOhContractHasNoCanvas() {
|
||||
// LLeMbas 2.0 removed the canvas: no `canvas` frame, so no fixture for one. A stream
|
||||
// that still sends it (a 1.x server) is ignored frame by frame, as any unknown event is.
|
||||
assertNull(javaClass.classLoader!!.getResource("event_canvas.json"))
|
||||
assertEquals(LiveReply("m"), LiveReply("m").apply("canvas", """{"tabs": [], "active": ""}"""))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -52,6 +175,13 @@ class ContractTest {
|
||||
val user = read("message_user", Message.serializer())
|
||||
assertTrue(user.isUser)
|
||||
assertEquals("How is lembas made?", user.text)
|
||||
assertNull(user.progress)
|
||||
|
||||
// A prompt waiting behind a running reply says so, and how many are ahead of it.
|
||||
val queued = read("message_queued", Message.serializer())
|
||||
assertTrue(queued.queued)
|
||||
assertEquals("queued", queued.progress!!.phase)
|
||||
assertEquals(2, queued.progress!!.ahead)
|
||||
|
||||
val reply = read("message_assistant", Message.serializer())
|
||||
assertEquals(listOf("thinking", "text", "tools", "steer", "text"), reply.steps.map { it.kind })
|
||||
@@ -64,6 +194,109 @@ class ContractTest {
|
||||
assertEquals(40, reply.metrics!!.completionTokens)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeviceApprovalCorrectsItsDetail() {
|
||||
// A device's approval: the heading in `title`, the command in `detail` -- the text an
|
||||
// `editable` item corrects -- no "Something else", and the subagent asking in `job`.
|
||||
val approval = read("event_ask", AskFrame.serializer()).cards.first { it.kind == "approval" }
|
||||
val item = approval.items.single()
|
||||
assertEquals("Run a command", item.title)
|
||||
assertEquals("rm -rf build", item.detail)
|
||||
assertTrue(item.editable)
|
||||
assertFalse(item.freeText)
|
||||
assertEquals("explore (job1)", item.job)
|
||||
assertTrue(item.reason.isNotBlank())
|
||||
// Untouched, the same, blank: nothing sent. Corrected: the item's key with the new command.
|
||||
assertEquals(emptyMap<String, String>(), approvalTexts(approval.items, emptyMap()))
|
||||
assertEquals(emptyMap<String, String>(), approvalTexts(approval.items, mapOf(item.key to " rm -rf build ")))
|
||||
assertEquals(emptyMap<String, String>(), approvalTexts(approval.items, mapOf(item.key to " ")))
|
||||
assertEquals(mapOf(item.key to "rm -rf build/tmp"), approvalTexts(approval.items, mapOf(item.key to "rm -rf build/tmp\n")))
|
||||
// An item that is not editable never sends a correction.
|
||||
assertEquals(emptyMap<String, String>(), approvalTexts(listOf(item.copy(editable = false)), mapOf(item.key to "ls")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aListedChatLeavesTheSubagentFactsToTheChat() {
|
||||
// The list does not work the facts out: null means "read the chat", never "not offered".
|
||||
val page = read("chats_listed", ChatPage.serializer())
|
||||
val chat = page.chats.single()
|
||||
assertEquals("Waybread", chat.title)
|
||||
assertNull(chat.subagents)
|
||||
assertEquals(4, chat.agents?.max)
|
||||
assertFalse(page.more)
|
||||
// The agent chat's own facts (3.4.0): offered -- the setting goes to its device -- the cap said.
|
||||
val agent = read("chat_agent", Chat.serializer())
|
||||
assertEquals(true, agent.subagents?.offered)
|
||||
assertEquals(32, agent.subagents?.cap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTreeSubagentAsksThePerson() {
|
||||
// A device's subagent asks for what nobody in its tree may allow: the card names it.
|
||||
val cards = read("event_ask", AskFrame.serializer()).cards
|
||||
val item = cards.single { c -> c.items.any { it.subagent != null } }.items.single()
|
||||
assertEquals(CardSubagent(id = "s1", name = "parser", position = "reviews the parser"), item.subagent)
|
||||
assertEquals("git push", item.detail)
|
||||
assertEquals("", item.job)
|
||||
assertNull(cards.first().items.single().subagent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTreeFrame() {
|
||||
val tree = read("event_tree", TreeFrame.serializer()).tree!!
|
||||
assertEquals(1, tree.openSlots)
|
||||
assertEquals(listOf("lead", "parser"), tree.agents.map { it.name })
|
||||
assertEquals("Review src/parse.ts.", tree.agents[1].task)
|
||||
assertEquals(6, tree.agents[1].contextPercent)
|
||||
assertEquals("done", tree.ended.single().state)
|
||||
assertNull(tree.ended.single().progress)
|
||||
// The stream carries it; the reply keeps it.
|
||||
assertEquals(tree, LiveReply("m").apply("tree", text("event_tree")).tree)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTreeReadAndASubagentsConversation() {
|
||||
val view = read("tree", TreeView.serializer())
|
||||
assertTrue(view.live)
|
||||
assertNotNull(view.tree)
|
||||
assertEquals(listOf("message", "report"), view.room.map { if (it.report) "report" else "message" })
|
||||
val read = read("subagent_transcript", SubagentTranscript.serializer())
|
||||
assertEquals("s2", read.id)
|
||||
assertEquals("working", read.state)
|
||||
assertTrue(read.turns.first().machine)
|
||||
assertEquals("src/api.py", read.turns[1].tools.single().title)
|
||||
assertTrue(read.turns[1].running)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun meSaysTheLanguageAndTheServices() {
|
||||
// `/api/v2/me` (me.json): the account's language the app follows by default, and the
|
||||
// instance's speech services the assistant uses.
|
||||
val me = read("me", Me.serializer())
|
||||
assertEquals("sk", me.accountLanguage)
|
||||
assertEquals("qwen", me.defaultModel)
|
||||
assertTrue(me.hasSpeechToText)
|
||||
assertEquals(true, me.speechToText)
|
||||
assertFalse(me.hasTextToSpeech)
|
||||
assertEquals("Frodo", me.account.name)
|
||||
// Not said: no language (a kept answer stands), and speech-to-text unknown, not "no".
|
||||
val silent = me.copy(language = "", services = emptyMap())
|
||||
assertNull(silent.accountLanguage)
|
||||
assertNull(silent.speechToText)
|
||||
assertFalse(silent.hasSpeechToText)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewAgentChatsSubagentsFact() {
|
||||
// `/models?kind=agent&device=` (models_agent.json): offered, and the device runs them.
|
||||
val list = read("models_agent", ModelList.serializer())
|
||||
assertEquals(AgentSubagents(offered = true, deviceRuns = true), list.agentSubagents)
|
||||
assertTrue(list.models.all { it.subagents?.offered == true })
|
||||
assertTrue(ChatState(models = list.models, agentSubagents = list.agentSubagents).offersTeam(agent = true))
|
||||
// Without kind=agent the field is not there.
|
||||
assertNull(read("models", ModelList.serializer()).agentSubagents)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyFrameParses() {
|
||||
assertTrue(read("event_steps", StepsFrame.serializer()).steps.isNotEmpty())
|
||||
@@ -72,7 +305,7 @@ class ContractTest {
|
||||
assertEquals("Bake lembas", read("event_plan", Plan.serializer()).title)
|
||||
assertTrue(read("event_status", StatusFrame.serializer()).text.isNotEmpty())
|
||||
val cards = read("event_ask", AskFrame.serializer()).cards
|
||||
assertEquals(listOf("question", "approval", "plan"), cards.map { it.kind })
|
||||
assertEquals(listOf("question", "approval", "plan", "approval"), cards.map { it.kind })
|
||||
assertEquals(listOf("Honey", "Plain"), cards[0].items[0].options.map { it.label })
|
||||
assertTrue(cards[1].items[0].editable)
|
||||
assertNotNull(cards[2].items[0].plan)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
|
||||
class LanguageTest {
|
||||
@Test
|
||||
fun theAccountsLanguageIsTheDefault() {
|
||||
assertEquals("en", AppLanguage.effective(AppLanguage.ACCOUNT, "en"))
|
||||
assertEquals("sk", AppLanguage.effective(AppLanguage.ACCOUNT, "sk"))
|
||||
// A server language written with a region still names one the app has.
|
||||
assertEquals("cs", AppLanguage.effective(AppLanguage.ACCOUNT, "cs_CZ"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnknownOrUnreadAccountLanguageFollowsThePhone() {
|
||||
assertNull(AppLanguage.effective(AppLanguage.ACCOUNT, ""))
|
||||
assertNull(AppLanguage.effective(AppLanguage.ACCOUNT, "ja"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aChoiceBeatsTheAccount() {
|
||||
assertNull(AppLanguage.effective(AppLanguage.PHONE, "en"))
|
||||
assertEquals("de", AppLanguage.effective("de", "en"))
|
||||
// A code the app no longer has (a newer build's choice, say) follows the phone.
|
||||
assertNull(AppLanguage.effective("ja", "en"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyLanguageIsNamedInItself() {
|
||||
assertEquals("Slovenčina", AppLanguage.name("sk"))
|
||||
assertEquals("English", AppLanguage.name("en-GB"))
|
||||
assertNull(AppLanguage.name("ja"))
|
||||
}
|
||||
|
||||
/** The list Settings offers, the strings gen-strings.py writes, and the locale config agree. */
|
||||
@Test
|
||||
fun theLanguagesAreTheOnesTheAppHasStringsFor() {
|
||||
val res = File("src/main/res")
|
||||
val folders = res.listFiles().orEmpty()
|
||||
.map { it.name }
|
||||
.filter { it.startsWith("values-") && File(res, "$it/strings.xml").exists() }
|
||||
.map { it.removePrefix("values-") }
|
||||
.toSet()
|
||||
val offered = AppLanguage.LANGUAGES.map { it.first }.toSet()
|
||||
assertEquals(offered - "en", folders)
|
||||
val config = File(res, "xml/locales_config.xml").readText()
|
||||
val listed = Regex("""android:name="([a-z]+)"""").findAll(config).map { it.groupValues[1] }.toSet()
|
||||
assertEquals(offered, listed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.ui.Segment
|
||||
import eu.llembas.android.ui.splitFences
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class MarkdownSplitTest {
|
||||
@Test
|
||||
fun proseOnlyIsOnePiece() {
|
||||
assertEquals(listOf(Segment.Prose("Hello *there*.")), splitFences("Hello *there*.\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFenceBetweenProse() {
|
||||
val split = splitFences("Here is how:\n\n```sh\nbake --slow\n```\n\nDone.")
|
||||
assertEquals(
|
||||
listOf(Segment.Prose("Here is how:"), Segment.Code("sh", "bake --slow"), Segment.Prose("Done.")),
|
||||
split,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anUnclosedFenceRunsToTheEndWhileWritten() {
|
||||
val split = splitFences("Code:\n```kotlin\nval a = 1\nval b")
|
||||
assertEquals(listOf(Segment.Prose("Code:"), Segment.Code("kotlin", "val a = 1\nval b", closed = false)), split)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLongerFenceHoldsAShorterOne() {
|
||||
val split = splitFences("````md\n```\ninner\n```\n````")
|
||||
assertEquals(listOf(Segment.Code("md", "```\ninner\n```")), split)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tildesAndNoLanguage() {
|
||||
assertEquals(listOf(Segment.Code("", "x")), splitFences("~~~\nx\n~~~"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFenceInsideAListStaysProse() {
|
||||
val text = "1. Run it:\n\n ```sh\n make\n ```"
|
||||
assertEquals(listOf(Segment.Prose(text)), splitFences(text))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun inlineBackticksAreNotAFence() {
|
||||
assertEquals(listOf(Segment.Prose("Use ``` to fence code.")), splitFences("Use ``` to fence code."))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Progress
|
||||
import eu.llembas.android.api.ProgressWords
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.StatusFrame
|
||||
import eu.llembas.android.api.elapsed
|
||||
import eu.llembas.android.api.progressLine
|
||||
import eu.llembas.android.api.progressText
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.long
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* The progress line (harness spec 3.4.0, `progress.md`): the spec's own conformance cases
|
||||
* (`conformance/progress.json`, the file every client and the server test against, pinned as
|
||||
* `contract/harness_progress.json` from the server's copy of the spec), drawn with
|
||||
* the app's English strings as `res/values/strings.xml` has them -- so a string that drifted
|
||||
* from `loop.json`'s `progress.texts` fails here too.
|
||||
*/
|
||||
class ProgressTest {
|
||||
/** The app's English, read from the generated resources, formatted as Android formats it. */
|
||||
private val english: ProgressWords by lazy {
|
||||
val xml = File("src/main/res/values/strings.xml").readText()
|
||||
val strings = Regex("""<string name="progress_([a-z_]+)"[^>]*>(.*?)</string>""").findAll(xml)
|
||||
.associate { it.groupValues[1] to it.groupValues[2].replace("\\'", "'").replace("&", "&") }
|
||||
val keys = mapOf("stopped_reason_person" to "stopped_person", "stopped_reason_steps" to "stopped_steps", "stopped_reason_budget" to "stopped_budget")
|
||||
ProgressWords { key, args -> strings[keys[key] ?: key]?.let { String.format(Locale.ROOT, it, *args) } }
|
||||
}
|
||||
|
||||
private val cases: List<JsonObject> by lazy {
|
||||
// The server's vendored copy of the spec's file, pinned with the contract.
|
||||
val text = requireNotNull(javaClass.classLoader!!.getResource("harness_progress.json")) { "contract/harness_progress.json is missing" }.readText()
|
||||
LembasJson.parseToJsonElement(text).jsonObject.getValue("cases").jsonArray.map { it.jsonObject }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyConformanceCase() {
|
||||
assertEquals(25, cases.size)
|
||||
for (case in cases) {
|
||||
val progress = LembasJson.decodeFromJsonElement(Progress.serializer(), case.getValue("progress"))
|
||||
val now = case.getValue("now").jsonPrimitive.long
|
||||
val expect = case.getValue("expect").jsonObject
|
||||
val about = case["about"]?.jsonPrimitive?.content
|
||||
assertEquals(about, expect.getValue("text").jsonPrimitive.content, progressText(progress, english, now, Locale.ROOT))
|
||||
assertEquals(about, expect.getValue("line").jsonPrimitive.content, progressLine(progress, english, now, Locale.ROOT))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aClockWritesDurations() {
|
||||
assertEquals("0s", elapsed(-1500))
|
||||
assertEquals("59s", elapsed(59_999))
|
||||
assertEquals("1m 00s", elapsed(60_000))
|
||||
assertEquals("59m 59s", elapsed(3_599_000))
|
||||
assertEquals("1h 00m", elapsed(3_600_000))
|
||||
assertEquals("26h 03m", elapsed(93_780_000))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRateInThePersonsNumberFormat() {
|
||||
val writing = Progress(phase = "writing", since = 0, rate = 12.46)
|
||||
assertEquals("Writing: 12,5 tok/s", progressText(writing, english, 0, Locale.forLanguageTag("sk")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPhaseThisAppDoesNotKnowFallsBackToStatus() {
|
||||
assertNull(progressLine(Progress(phase = "dreaming", since = 0), english, 0))
|
||||
// A required field missing: no half sentence, the status text instead.
|
||||
assertNull(progressLine(Progress(phase = "running_tool", since = 0), english, 0))
|
||||
assertNull(progressLine(Progress(phase = "waiting_for_model", since = 0, model = "coder"), english, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theStatusFrameCarriesProgress() {
|
||||
val frame = """{"text": "Running bake --slow", "progress": {"phase": "running_tool", "since": 1762790400000, "tool": "bash", "what": "bake --slow"}}"""
|
||||
val live = LiveReply("m").apply("status", frame)
|
||||
assertEquals("Running bake --slow", live.status)
|
||||
assertEquals("bake --slow", live.progress?.what)
|
||||
// An older server's frame: the text alone, no progress.
|
||||
val old = live.apply("status", """{"text": "Thinking"}""")
|
||||
assertEquals("Thinking", old.status)
|
||||
assertNull(old.progress)
|
||||
// Idle: progress null.
|
||||
assertNull(live.apply("status", """{"text": "", "progress": null}""").progress)
|
||||
// The reply ends: neither is kept.
|
||||
val done = LembasJson.parseToJsonElement(File("../contract/event_done.json").readText()).toString()
|
||||
assertNull(live.apply("done", done).progress)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theContractsStatusFrames() {
|
||||
fun frame(name: String) = LembasJson.decodeFromString(
|
||||
StatusFrame.serializer(),
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")).readText(),
|
||||
)
|
||||
val running = frame("event_status")
|
||||
assertEquals("Running bake --slow", running.text)
|
||||
val since = running.progress!!.since
|
||||
assertEquals("Running bash: bake --slow · 5s", progressLine(running.progress!!, english, since + 5_000, Locale.ROOT))
|
||||
assertEquals("Waiting for you: a question · 0s", progressLine(frame("event_status_person").progress!!, english, since, Locale.ROOT))
|
||||
// Stopped is its text alone, though the free text is empty: the progress is what is drawn.
|
||||
val stopped = frame("event_status_stopped")
|
||||
assertEquals("", stopped.text)
|
||||
assertEquals("Stopped: by you", progressLine(stopped.progress!!, english, since + 60_000, Locale.ROOT))
|
||||
assertNull(frame("event_status_idle").progress)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScheduledRunSaysItsProgress() {
|
||||
val text = requireNotNull(javaClass.classLoader!!.getResource("schedule_run.json")).readText()
|
||||
// The contract's run has finished: `progress` is there, and null.
|
||||
assertTrue(text.contains("\"progress\": null"))
|
||||
assertNull(LembasJson.decodeFromString(RunResult.serializer(), text).run.progress)
|
||||
val waiting =
|
||||
"""{"run": {"id": "r", "status": "waiting", "progress": {"phase": "waiting_for_model", "since": 0, "model": "coder", "reason": "slots"}}}"""
|
||||
val run = LembasJson.decodeFromString(RunResult.serializer(), waiting).run
|
||||
assertEquals("Waiting for coder: all its slots are in use", progressText(run.progress!!, english, 0, Locale.ROOT))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.PushPayload
|
||||
import eu.llembas.android.api.RulePreview
|
||||
import eu.llembas.android.api.RunEnvelope
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.ScheduleCompiled
|
||||
import eu.llembas.android.api.ScheduleEnvelope
|
||||
import eu.llembas.android.api.ScheduleList
|
||||
import eu.llembas.android.api.ScheduleRuns
|
||||
import eu.llembas.android.api.SchedulesFrame
|
||||
import eu.llembas.android.api.SchedulingModels
|
||||
import eu.llembas.android.api.computerAway
|
||||
import eu.llembas.android.push.ScheduledNotice
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.scheduled.SchedulingLogic
|
||||
import eu.llembas.android.ui.scheduled.Tone
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonArray
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The server's scheduling contract (`contract/schedule*.json`, `event_schedules.json`, written
|
||||
* by its serialisers): every shape parses into this app's models and says what it said. And the
|
||||
* push a scheduled run sends (services/schedule/notify.py `payload`), read into a notification.
|
||||
*/
|
||||
class ScheduleContractTest {
|
||||
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(serializer, text(name))
|
||||
|
||||
/** The schedule every fixture carries: sched1, "Waybread check", with run1 as its last run. */
|
||||
private fun assertWaybread(s: Schedule) {
|
||||
assertEquals("sched1", s.id)
|
||||
assertEquals("Waybread check", s.title)
|
||||
assertEquals("Check the waybread is wrapped.", s.instruction)
|
||||
assertEquals("every second Monday at 7:30", s.request)
|
||||
assertEquals("On the second Monday of each month at 07:30", s.description)
|
||||
assertEquals("UTC", s.timezone)
|
||||
assertTrue(s.enabled)
|
||||
assertFalse(s.paused)
|
||||
assertEquals("2026-01-12T07:30:00+00:00", s.nextRun)
|
||||
assertEquals(5, s.nextRuns.size)
|
||||
assertEquals("fresh", s.mode)
|
||||
assertEquals("matters", s.notify)
|
||||
assertEquals("one", s.catchUp)
|
||||
assertNull(s.graceMinutes)
|
||||
assertEquals("qwen", s.model)
|
||||
assertEquals("high", s.effort)
|
||||
assertNull(s.agents)
|
||||
assertTrue("plan" in s.tools)
|
||||
assertEquals("chat1", s.chatId)
|
||||
assertEquals(3, s.firedCount)
|
||||
assertEquals(0, s.failureStreak)
|
||||
assertFalse(s.running)
|
||||
// The rule is the server's own form, kept whole to be handed back.
|
||||
val nth = s.rule.getValue("at").jsonObject.getValue("nth").jsonArray.single().jsonObject
|
||||
assertEquals(2, nth.getValue("n").jsonPrimitive.int)
|
||||
|
||||
val run = s.lastRun!!
|
||||
assertEquals("run1", run.id)
|
||||
assertEquals("sched1", run.scheduleId)
|
||||
assertEquals("ok", run.status)
|
||||
assertEquals("late", run.timing)
|
||||
assertEquals("GPT-OSS", run.model.label)
|
||||
assertEquals("switched", run.model.reason)
|
||||
assertEquals("Qwen", run.model.switchedFrom)
|
||||
assertEquals(1200L, run.tokens.prompt)
|
||||
assertNull(run.cost)
|
||||
assertNull(run.error)
|
||||
assertEquals("msg2", run.messageId)
|
||||
assertEquals("All the waybread is wrapped.", run.preview)
|
||||
assertTrue(run.notified)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theListOneScheduleAndTheEventFrame() {
|
||||
assertWaybread(read("schedules", ScheduleList.serializer()).schedules.single())
|
||||
assertWaybread(read("schedule", ScheduleEnvelope.serializer()).schedule)
|
||||
val frame = read("event_schedules", SchedulesFrame.serializer())
|
||||
assertEquals("8bee85746004dc19", frame.version)
|
||||
assertWaybread(frame.schedules.single())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aWatchingScheduleAndItsUnchangedRun() {
|
||||
// Monitor mode (`schedule_watching.json`): the address it looks at, and a run that found
|
||||
// nothing changed -- no model, no notification.
|
||||
val watching = read("schedule_watching", ScheduleEnvelope.serializer()).schedule
|
||||
assertEquals("url", watching.watch!!.kind)
|
||||
assertEquals("https://shop.example/mallorn", watching.watch!!.target)
|
||||
val run = watching.lastRun!!
|
||||
assertEquals("unchanged", run.status)
|
||||
assertFalse(run.watch!!.changed)
|
||||
assertNull(run.notification)
|
||||
assertEquals(Tone.Quiet, ScheduleLogic.tone(run.status))
|
||||
// A schedule that watches nothing says null.
|
||||
assertNull(read("schedule", ScheduleEnvelope.serializer()).schedule.watch)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScheduleOnAComputerAndARunThatFoundItAway() {
|
||||
val on = read("schedule_on_device", ScheduleEnvelope.serializer()).schedule
|
||||
val where = on.runsOn!!
|
||||
assertEquals("bag-end", where.deviceName)
|
||||
assertEquals("/home/frodo/waybread", where.cwd)
|
||||
assertEquals("edit", where.mode)
|
||||
assertEquals(30, where.approvalWaitMinutes)
|
||||
val run = on.lastRun!!
|
||||
assertEquals("device", run.waitingFor)
|
||||
assertTrue(run.computerAway)
|
||||
assertNull(read("schedule", ScheduleEnvelope.serializer()).schedule.runsOn)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theRunsAWaitingOneAndOneInFull() {
|
||||
val page = read("schedule_runs", ScheduleRuns.serializer())
|
||||
assertFalse(page.more)
|
||||
val (waiting, done) = page.runs
|
||||
assertEquals("waiting", waiting.status)
|
||||
assertEquals("model", waiting.waitingFor)
|
||||
assertEquals("2026-01-02T03:09:05+00:00", waiting.retryAt)
|
||||
assertEquals(2, waiting.missed)
|
||||
assertEquals(2, waiting.attempts)
|
||||
assertNull(waiting.model.label)
|
||||
assertNull(waiting.chatId)
|
||||
assertEquals("no_model", waiting.error?.kind)
|
||||
assertEquals("Waiting for a free model: Qwen: it is answering someone.", waiting.error?.text)
|
||||
assertEquals("run1", done.id)
|
||||
|
||||
val one = read("schedule_run", RunResult.serializer())
|
||||
assertEquals("run1", one.run.id)
|
||||
assertEquals("chat1", one.run.chatId)
|
||||
assertEquals("All the waybread is *wrapped*.", one.text)
|
||||
|
||||
// `POST /schedules/{id}/run` answers 202 with the run alone.
|
||||
val started = LembasJson.decodeFromString(RunEnvelope.serializer(), """{"run":{"id":"run3","status":"running","timing":"manual"}}""")
|
||||
assertEquals("manual", started.run.timing)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theCompileAndThePreview() {
|
||||
val compiled = read("schedule_compile", ScheduleCompiled.serializer())
|
||||
assertTrue(compiled.ok)
|
||||
assertNull(compiled.reason)
|
||||
assertEquals("Waybread check", compiled.title)
|
||||
assertEquals("chat", compiled.target)
|
||||
assertEquals("On the second Monday of each month at 07:30", compiled.description)
|
||||
assertEquals(5, compiled.nextRuns.size)
|
||||
assertTrue(compiled.savable)
|
||||
|
||||
// A rule that cannot run comes back empty, in no words, with no runs: not savable.
|
||||
val preview = read("schedule_preview", RulePreview.serializer())
|
||||
assertTrue(preview.rule.isEmpty())
|
||||
assertNull(preview.description)
|
||||
assertTrue(preview.nextRuns.isEmpty())
|
||||
assertFalse(ScheduleCompiled(ok = false, reason = "Say what you want to happen.", instruction = "x").savable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSchedulingModelsAndANarrowing() {
|
||||
val models = read("schedule_models", SchedulingModels.serializer())
|
||||
val (gpt, qwen) = models.models
|
||||
assertEquals("gpt-oss", gpt.id)
|
||||
assertFalse(gpt.free)
|
||||
assertEquals("it is answering someone", gpt.busy)
|
||||
assertTrue(gpt.chosen)
|
||||
assertTrue(qwen.free)
|
||||
assertNull(qwen.busy)
|
||||
assertFalse(qwen.chosen)
|
||||
assertEquals("/api/v2/models/images/0a1b2c3d4e5f.png", qwen.image)
|
||||
assertEquals(listOf("gpt-oss", "qwen"), models.instance)
|
||||
assertEquals(listOf("gpt-oss"), models.mine)
|
||||
|
||||
// Ticking Qwen ticks every one: no narrowing at all. Unticking the last one: refused.
|
||||
assertEquals(emptyList<String>(), SchedulingLogic.toggled(models.models, "qwen"))
|
||||
assertNull(SchedulingLogic.toggled(models.models, "gpt-oss"))
|
||||
val all = models.models.map { it.copy(chosen = true) }
|
||||
assertEquals(listOf("gpt-oss"), SchedulingLogic.toggled(all, "qwen"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aResultsPushOpensTheRun() {
|
||||
// What notify.payload and push.announce send for a run that finished: ids, a fixed
|
||||
// sentence, never the result.
|
||||
val payload = LembasJson.decodeFromString(
|
||||
PushPayload.serializer(),
|
||||
"""{"schedule_id":"sched1","run_id":"run1","chat_id":"chat1","status":"ok","visibility":"private",
|
||||
"actions":["open"],"ask":"","pause_label":"Pause","title":"LLeMbas",
|
||||
"body":"A scheduled task has finished.","url":"/scheduled/sched1?run=run1","kind":"schedule"}""",
|
||||
)
|
||||
val notice = ScheduledNotice.from(payload)!!
|
||||
assertEquals("sched1", notice.scheduleId)
|
||||
assertEquals("run1", notice.runId)
|
||||
assertFalse(notice.failed)
|
||||
assertTrue(notice.open)
|
||||
assertFalse(notice.pause)
|
||||
assertEquals("private", payload.visibility)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFailurePushOffersPauseAndAsksAfterThree() {
|
||||
val failed = LembasJson.decodeFromString(
|
||||
PushPayload.serializer(),
|
||||
"""{"schedule_id":"sched1","run_id":"run2","status":"failed","visibility":"private","actions":["open","pause"],
|
||||
"ask":"pause","body":"A scheduled task failed 3 times in a row. Pause it?","url":"/scheduled/sched1?run=run2",
|
||||
"kind":"schedule_failed"}""",
|
||||
)
|
||||
val notice = ScheduledNotice.from(failed)!!
|
||||
assertTrue(notice.failed)
|
||||
assertTrue(notice.askPause)
|
||||
assertTrue(notice.pause)
|
||||
// A push about the same run replaces its notification; another run gets its own.
|
||||
assertEquals(notice.id, notice.copy(failed = false).id)
|
||||
assertTrue(notice.id != notice.copy(runId = "run3").id)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theServersNotificationWordsAndRunAgain() {
|
||||
// `push_schedule.json`: the task's name and first lines unlocked, Finished on the lock
|
||||
// screen, Open and Run again with the owner's labels.
|
||||
val done = ScheduledNotice.from(read("push_schedule", PushPayload.serializer()))!!
|
||||
assertEquals("Waybread check", done.title)
|
||||
assertEquals("All the waybread is wrapped.", done.body)
|
||||
assertEquals("Waybread check", done.publicTitle)
|
||||
assertEquals("Finished", done.publicBody)
|
||||
assertTrue(done.open)
|
||||
assertTrue(done.runAgain)
|
||||
assertFalse(done.pause)
|
||||
assertEquals("Run again", done.label("run_again", "x"))
|
||||
assertEquals("x", done.label("pause", "x"))
|
||||
|
||||
// `push_schedule_failed.json`: three failures ask about Pause, beside Open and Run again.
|
||||
val failed = ScheduledNotice.from(read("push_schedule_failed", PushPayload.serializer()))!!
|
||||
assertTrue(failed.failed)
|
||||
assertTrue(failed.askPause)
|
||||
assertTrue(failed.pause)
|
||||
assertTrue(failed.runAgain)
|
||||
assertEquals("Failed", failed.publicBody)
|
||||
assertEquals("run3", failed.runId)
|
||||
|
||||
// The run's own copy (the schedules frame) says the same.
|
||||
val run = read("schedule_run", RunResult.serializer()).run
|
||||
assertEquals(listOf("open", "run_again"), run.notification!!.actions)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPushWithOnlyItsUrlAndOneThatIsNotScheduled() {
|
||||
val bare = PushPayload(kind = "schedule", url = "/scheduled/sched1?run=run1")
|
||||
val notice = ScheduledNotice.from(bare)!!
|
||||
assertEquals("sched1", notice.scheduleId)
|
||||
assertEquals("run1", notice.runId)
|
||||
assertTrue(notice.open)
|
||||
assertNull(ScheduledNotice.from(PushPayload(kind = "reply", chatId = "chat1")))
|
||||
assertNull(ScheduledNotice.from(PushPayload(kind = "schedule", url = "/chat/chat1")))
|
||||
assertEquals(null to null, ScheduledNotice.fromUrl("/elsewhere"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ScheduleList
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.scheduled.Tone
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.time.ZoneId
|
||||
import java.util.Locale
|
||||
|
||||
class ScheduleLogicTest {
|
||||
private val zone = ZoneId.of("Europe/Bratislava")
|
||||
|
||||
@Test
|
||||
fun statusesHaveTones() {
|
||||
assertEquals(Tone.Good, ScheduleLogic.tone("ok"))
|
||||
assertEquals(Tone.Quiet, ScheduleLogic.tone("silent"))
|
||||
assertEquals(Tone.Bad, ScheduleLogic.tone("failed"))
|
||||
assertEquals(Tone.Bad, ScheduleLogic.tone("missed"))
|
||||
assertEquals(Tone.Waiting, ScheduleLogic.tone("waiting"))
|
||||
assertEquals(Tone.Neutral, ScheduleLogic.tone("something new"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMomentIsShownWhereThePhoneIs() {
|
||||
assertEquals("Tue 10 Mar, 08:00", ScheduleLogic.moment("2026-03-10T07:00:00+00:00", zone, Locale.ENGLISH))
|
||||
assertNull(ScheduleLogic.moment("tomorrow", zone, Locale.ENGLISH))
|
||||
assertNull(ScheduleLogic.moment(null, zone, Locale.ENGLISH))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun upcomingKeepsFiveReadableRuns() {
|
||||
val runs = (1..7).map { "2026-03-1${it}T07:00:00+00:00" } + "nonsense"
|
||||
assertEquals(5, ScheduleLogic.upcoming(runs, zone = zone, locale = Locale.ENGLISH).size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScheduleListThatSaysLittleStillParses() {
|
||||
val list = LembasJson.decodeFromString(ScheduleList.serializer(), """{"schedules":[{"id":"s1","enabled":false,"model":null,"later":1}]}""")
|
||||
val one = list.schedules.single()
|
||||
assertEquals("s1", one.id)
|
||||
assertTrue(one.paused)
|
||||
assertNull(one.nextRun)
|
||||
assertNull(one.model)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Discovery
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ServerFit
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.fit
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* What the server's contract fixtures cannot say: how the app reads a `show` card the server
|
||||
* never wrote (an unknown kind), and which servers it works with at all. The server's own `show`
|
||||
* cards are in `contract/tool_show.json` and read by `ContractTest`.
|
||||
*/
|
||||
class ShowAndServerTest {
|
||||
@Test
|
||||
fun aGeneratedPictureIsAnAttachmentIdAndASize() {
|
||||
// services/images/tool.py: `image: {id, width, height}` on the tool event; no URL at all.
|
||||
val call = LembasJson.decodeFromString(
|
||||
ToolCall.serializer(),
|
||||
"""{"id":"t1","name":"image_generate","status":"ok","attachment_id":"att1",
|
||||
"image":{"id":"att1","width":1216,"height":832},"block":{"kind":"image","title":"a leaf"}}""",
|
||||
)
|
||||
assertEquals("att1", call.image!!.id)
|
||||
assertEquals(1216, call.image!!.width)
|
||||
assertEquals(832, call.image!!.height)
|
||||
assertNull(LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"read"}""").image)
|
||||
assertEquals("image_generate", eu.llembas.android.ui.chat.IMAGE_TOOL)
|
||||
}
|
||||
|
||||
private fun call(json: String) = LembasJson.decodeFromString(ToolCall.serializer(), json)
|
||||
|
||||
@Test
|
||||
fun anUnknownKindIsPlainText() {
|
||||
val c = call("""{"name": "show", "show": {"path": "x.svg", "kind": "svg"}}""")
|
||||
assertEquals("text", c.show!!.viewKind)
|
||||
assertNull(call("""{"name": "bash"}""").show)
|
||||
}
|
||||
|
||||
private fun discovery(json: String) = LembasJson.decodeFromString(Discovery.serializer(), json)
|
||||
|
||||
@Test
|
||||
fun onlyAServerOnTheTwoPointOhProtocolAndAppApiTwoFits() {
|
||||
val two = """{"service": "lembas", "version": "2.0.0-beta.1", "protocol": 3, "protocols": [3],
|
||||
"app_api": 2, "scopes": ["app", "models"]}"""
|
||||
assertEquals(ServerFit.FITS, fit(discovery(two)))
|
||||
// A 2.0 `dev` server from before the show route and the files: protocol 3, app API 1.
|
||||
assertEquals(ServerFit.TOO_OLD, fit(discovery(two.replace("\"app_api\": 2", "\"app_api\": 1"))))
|
||||
// 1.7: protocol 2, the app API already there -- and still refused.
|
||||
val old = """{"service": "lembas", "version": "1.7.3", "protocol": 2, "protocols": [1, 2],
|
||||
"app_api": 1, "scopes": ["app", "models"]}"""
|
||||
assertEquals(ServerFit.TOO_OLD, fit(discovery(old)))
|
||||
// A server with no protocol at all is older still.
|
||||
assertEquals(ServerFit.TOO_OLD, fit(discovery("""{"service": "lembas", "app_api": 2, "scopes": ["app"]}""")))
|
||||
assertEquals(ServerFit.TOO_NEW, fit(discovery(two.replace("\"app_api\": 2", "\"app_api\": 3"))))
|
||||
assertEquals(ServerFit.NOT_LEMBAS, fit(discovery("""{"service": "other", "protocol": 3}""")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Activity
|
||||
import eu.llembas.android.api.ActivityEnvelope
|
||||
import eu.llembas.android.api.ActivityLogic
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ContextUse
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.SubagentsOffer
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.chat.offersTeam
|
||||
import eu.llembas.android.ui.chat.subagentsCap
|
||||
import eu.llembas.android.ui.chat.subagentsNamedOnly
|
||||
import kotlinx.serialization.KSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* The Subagents setting by the server's word (harness spec 3.3.0, `subagents.md` §4): shown
|
||||
* when it says subagents are offered, with its note when only a named model could serve, up to
|
||||
* the instance's cap -- and, from a server that says none of it, the app's old guess.
|
||||
*/
|
||||
class SubagentsTest {
|
||||
private val serving = ModelInfo(id = "qwen", tools = true, parallel = 4)
|
||||
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T =
|
||||
LembasJson.decodeFromString(serializer, requireNotNull(javaClass.classLoader!!.getResource("$name.json")).readText())
|
||||
|
||||
@Test
|
||||
fun theContractSaysItAll() {
|
||||
val list = read("models", ModelList.serializer())
|
||||
assertEquals(32, list.subagentsCap)
|
||||
assertEquals(listOf(true, true, false), list.models.map { it.subagents?.offered })
|
||||
assertEquals(listOf(false, true, false), list.models.map { it.subagents?.namedOnly })
|
||||
|
||||
val chat = read("chat", Chat.serializer())
|
||||
assertEquals(SubagentsOffer(offered = true, namedOnly = false, cap = 32), chat.subagents)
|
||||
val agentChat = read("chat_agent", Chat.serializer())
|
||||
// An agent chat is offered subagents (3.4.0): its device runs them, the setting goes down.
|
||||
assertEquals(SubagentsOffer(offered = true, cap = 32), agentChat.subagents)
|
||||
|
||||
val activity = read("activity", ActivityEnvelope.serializer()).activity
|
||||
assertEquals(true, activity.subagentsOffered)
|
||||
val context = activity.context!!
|
||||
assertEquals(true, context.autoCompact)
|
||||
assertEquals(true, context.compactable)
|
||||
// The server's count and the app's own agree on the same facts.
|
||||
assertEquals(context.untilCompact, ActivityLogic.untilAutoCompact(context.copy(untilCompact = null, autoCompact = null)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theServersWordWinsOverTheGuess() {
|
||||
// The guess would offer them (tools, four at once); the server says no.
|
||||
val refused = serving.copy(subagents = SubagentsOffer(offered = false))
|
||||
assertFalse(refused.mayHaveTeam)
|
||||
// The guess would not (one at a time); the server offers them for a named model.
|
||||
val oneAtATime = serving.copy(parallel = 1, subagents = SubagentsOffer(offered = true, namedOnly = true))
|
||||
assertTrue(oneAtATime.mayHaveTeam)
|
||||
// An older server: the guess.
|
||||
assertTrue(serving.mayHaveTeam)
|
||||
assertFalse(serving.copy(parallel = 1).mayHaveTeam)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewChatAsksItsModel() {
|
||||
val state = ChatState(models = listOf(serving.copy(parallel = 1, subagents = SubagentsOffer(offered = true, namedOnly = true))), modelsCap = 8)
|
||||
assertTrue(state.offersTeam(agent = false))
|
||||
assertFalse(state.offersTeam(agent = true))
|
||||
assertTrue(state.subagentsNamedOnly)
|
||||
assertEquals(8, state.subagentsCap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOpenChatAsksItself() {
|
||||
val chat = Chat(id = "c1", model = "qwen", subagents = SubagentsOffer(offered = false, cap = 6))
|
||||
// The activity's older word says yes; the chat's own says no, and wins.
|
||||
val state = ChatState(chat = chat, models = listOf(serving), teamOffered = true, modelsCap = 8)
|
||||
assertFalse(state.offersTeam(agent = false))
|
||||
assertEquals(6, state.subagentsCap)
|
||||
assertFalse(state.subagentsNamedOnly)
|
||||
// A chat from an older server: the activity's word, and the spec's cap.
|
||||
val older = ChatState(chat = chat.copy(subagents = null), teamOffered = true, draft = Draft())
|
||||
assertTrue(older.offersTeam(agent = false))
|
||||
assertEquals(AgentsSetting.CAP, older.subagentsCap)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theNewFieldsParseAndTheOldOnesStillDo() {
|
||||
val list = LembasJson.decodeFromString(
|
||||
ModelList.serializer(),
|
||||
"""{"models": [{"id": "qwen", "subagents": {"offered": true, "named_only": false}}], "subagents_cap": 12}""",
|
||||
)
|
||||
assertEquals(12, list.subagentsCap)
|
||||
assertEquals(SubagentsOffer(offered = true), list.models.single().subagents)
|
||||
val bare = LembasJson.decodeFromString(ModelList.serializer(), """{"models": [{"id": "qwen"}]}""")
|
||||
assertNull(bare.subagentsCap)
|
||||
assertNull(bare.models.single().subagents)
|
||||
|
||||
val activity = LembasJson.decodeFromString(
|
||||
Activity.serializer(),
|
||||
"""{"team_offered": true, "subagents_offered": false,
|
||||
"context": {"used": 1000, "limit": 10000, "threshold": 95, "auto_compact": true, "until_compact": 8000, "compactable": false}}""",
|
||||
)
|
||||
assertEquals(false, activity.subagentsOffered)
|
||||
assertEquals(8000, ActivityLogic.untilAutoCompact(activity.context!!))
|
||||
assertEquals(false, activity.context!!.compactable)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun autoCompactOffIsOffWhateverTheThreshold() {
|
||||
val context = ContextUse(used = 1000, limit = 10000, threshold = 95, autoCompact = false, untilCompact = 8500)
|
||||
assertNull(ActivityLogic.untilAutoCompact(context))
|
||||
// Without the server's facts: worked out from the threshold.
|
||||
assertEquals(8500, ActivityLogic.untilAutoCompact(ContextUse(used = 1000, limit = 10000, threshold = 95)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.TreeLogic
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** The subagent tree (harness spec 3.4.0, `subagents.md` §12) and the reduced list's rows. */
|
||||
class TreeTest {
|
||||
/** §12's own example, with a sub-manager and one under it added. */
|
||||
private val tree = LembasJson.decodeFromString(
|
||||
SubagentTree.serializer(),
|
||||
"""
|
||||
{ "min": 1, "max": 4, "size": 3, "open_slots": 1,
|
||||
"agents": [
|
||||
{ "id": "lead", "name": "lead", "position": "the main agent", "parent": null, "state": "working",
|
||||
"model": "qwen-27b", "mode": "edit", "request": [], "manager": true,
|
||||
"context": { "used": 41200, "window": 131072 }, "progress": { "phase": "thinking", "since": 1762790400000 } },
|
||||
{ "id": "s1", "name": "parser", "position": "reviews the parser", "parent": "lead", "state": "working",
|
||||
"model": "qwen-27b", "mode": "manual", "request": ["write"], "manager": true, "task": "…",
|
||||
"context": { "used": 9100, "window": 131072 },
|
||||
"progress": { "phase": "running_tool", "since": 1762790401000, "tool": "read", "what": "src/parse.ts" },
|
||||
"findings": 2, "messages": 3 },
|
||||
{ "id": "s3", "name": "lexer", "position": "the lexer's tests", "parent": "parser", "state": "paused",
|
||||
"model": "qwen-27b", "mode": "manual", "request": [], "manager": false, "task": "…", "findings": 0, "messages": 0 }
|
||||
],
|
||||
"ended": [ { "id": "s0", "name": "scout", "position": "…", "parent": "lead", "state": "done", "ended": 1762790300000, "findings": 1 } ] }
|
||||
""",
|
||||
)
|
||||
|
||||
@Test
|
||||
fun theTreeReads() {
|
||||
assertEquals(1, tree.openSlots)
|
||||
val parser = tree.agents[1]
|
||||
assertEquals("s1", parser.id)
|
||||
assertEquals("running_tool", parser.progress?.phase)
|
||||
assertEquals(listOf("write"), parser.request)
|
||||
assertTrue(tree.agents[0].isMain)
|
||||
assertFalse(parser.isMain)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun contextIsFlooredAndNeedsAWindow() {
|
||||
assertEquals(31, tree.agents[0].contextPercent) // 41200 × 100 / 131072 = 31.43
|
||||
assertEquals(6, tree.agents[1].contextPercent)
|
||||
assertNull(tree.agents[2].contextPercent)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun rowsInTreeOrderThenTheEnded() {
|
||||
val rows = TreeLogic.rows(tree)
|
||||
assertEquals(listOf("lead", "parser", "lexer", "scout"), rows.map { it.agent.name })
|
||||
assertEquals(listOf(0, 1, 2, 1), rows.map { it.depth })
|
||||
assertEquals(listOf(false, false, false, true), rows.map { it.ended })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aParentTheTreeDoesNotHoldIsTheMainAgents() {
|
||||
val moved = tree.copy(agents = tree.agents.map { if (it.name == "lexer") it.copy(parent = "gone") else it })
|
||||
assertEquals(1, TreeLogic.rows(moved).single { it.agent.name == "lexer" }.depth)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMainAgentAloneIsNoList() {
|
||||
assertFalse(TreeLogic.hasSubagents(null))
|
||||
assertFalse(TreeLogic.hasSubagents(tree.copy(agents = tree.agents.take(1), ended = emptyList(), openSlots = 0)))
|
||||
assertTrue(TreeLogic.hasSubagents(tree.copy(agents = tree.agents.take(1), ended = emptyList(), openSlots = 2)))
|
||||
assertTrue(TreeLogic.hasSubagents(tree))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.AppsInfo
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.PublicRelease
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.update.checksUpdates
|
||||
import eu.llembas.android.update.offersBetas
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class UpdateCheckTest {
|
||||
private fun v(text: String) = AppVersion.parse(text)!!
|
||||
|
||||
@Test
|
||||
fun versionsSortAsTheirCodesDo() {
|
||||
assertTrue(v("1.0.0-beta.2") > v("1.0.0-beta.1"))
|
||||
assertTrue(v("1.0.0-beta.10") > v("1.0.0-beta.9"))
|
||||
assertTrue(v("1.0.0") > v("1.0.0-beta.99"))
|
||||
assertTrue(v("1.0.1-beta.1") > v("1.0.0"))
|
||||
assertEquals(v("v1.2.3"), v("1.2.3"))
|
||||
// A test build's suffix is not part of the version.
|
||||
assertEquals(v("1.0.0-beta.5"), v("1.0.0-beta.5-debug.44"))
|
||||
assertNull(AppVersion.parse("1.0.0-rc.1"))
|
||||
assertNull(AppVersion.parse("latest"))
|
||||
}
|
||||
|
||||
// GitHub's answer, cut to what the check reads plus a field it does not.
|
||||
private val releases = LembasJson.decodeFromString(
|
||||
ListSerializer(PublicRelease.serializer()),
|
||||
"""
|
||||
[
|
||||
{"tag_name": "v1.1.0-beta.1", "prerelease": true, "draft": false, "html_url": "https://example.org/b1", "assets": []},
|
||||
{"tag_name": "v1.0.1", "prerelease": false, "draft": false, "html_url": "https://example.org/101"},
|
||||
{"tag_name": "v1.2.0", "prerelease": false, "draft": true, "html_url": "https://example.org/draft"},
|
||||
{"tag_name": "v1.0.0", "prerelease": false, "html_url": "https://example.org/100"},
|
||||
{"tag_name": "nightly", "prerelease": true}
|
||||
]
|
||||
""",
|
||||
)
|
||||
|
||||
@Test
|
||||
fun aReleaseIsOfferedTheNewestItMayHave() {
|
||||
// A release without betas: the newest release, never the draft.
|
||||
val stable = ReleaseCheck.newest(releases, v("1.0.0"), betas = false)!!
|
||||
assertEquals(v("1.0.1"), stable.version)
|
||||
assertEquals("https://example.org/101", stable.page)
|
||||
// With betas: the beta above it.
|
||||
assertEquals(v("1.1.0-beta.1"), ReleaseCheck.newest(releases, v("1.0.0"), betas = true)!!.version)
|
||||
// Nothing newer: nothing offered.
|
||||
assertNull(ReleaseCheck.newest(releases, v("1.1.0-beta.1"), betas = true))
|
||||
assertNull(ReleaseCheck.newest(releases, v("1.0.1"), betas = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSettingsFollowTheInstalledChannelUntilChosen() {
|
||||
val unset = Prefs()
|
||||
assertTrue(unset.checksUpdates(installedIsBeta = true))
|
||||
assertFalse(unset.checksUpdates(installedIsBeta = false))
|
||||
assertTrue(unset.offersBetas(installedIsBeta = true))
|
||||
assertFalse(unset.offersBetas(installedIsBeta = false))
|
||||
assertFalse(Prefs(updateCheck = false).checksUpdates(installedIsBeta = true))
|
||||
assertTrue(Prefs(updateBetas = true).offersBetas(installedIsBeta = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onceADayAtMost() {
|
||||
val day = 24L * 60 * 60 * 1000
|
||||
assertTrue(ReleaseCheck.due(0, 5))
|
||||
assertFalse(ReleaseCheck.due(1_000, 1_000 + day - 1))
|
||||
assertTrue(ReleaseCheck.due(1_000, 1_000 + day))
|
||||
// A clock set back is not a reason to wait a year.
|
||||
assertTrue(ReleaseCheck.due(10 * day, day))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theServersRecommendationComesFirst() {
|
||||
fun read(name: String) = LembasJson.decodeFromString(
|
||||
AppsInfo.serializer(),
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")).readText(),
|
||||
)
|
||||
val beta = read("apps")
|
||||
assertEquals("1.1.0-beta.2", beta.android!!.version)
|
||||
val offer = ReleaseCheck.recommended(beta, v("1.0.0-beta.5"), betas = true)!!
|
||||
assertEquals("1.1.0-beta.2", offer.version.toString())
|
||||
assertEquals("https://github.com/LLeMbas/LLeMbas-Android/releases/tag/v1.1.0-beta.2", offer.page)
|
||||
// A beta is not offered to someone who did not want betas, nor anything not newer.
|
||||
assertNull(ReleaseCheck.recommended(beta, v("1.0.0-beta.5"), betas = false))
|
||||
assertNull(ReleaseCheck.recommended(beta, v("1.1.0-beta.2"), betas = true))
|
||||
// A stable server with no Android pin recommends nothing, so nothing is offered.
|
||||
val stable = read("apps_stable")
|
||||
assertNull(stable.android)
|
||||
assertNull(ReleaseCheck.recommended(stable, v("1.0.0-beta.5"), betas = true))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,577 @@
|
||||
package eu.llembas.android.shots
|
||||
|
||||
import eu.llembas.android.api.ActivityAgent
|
||||
import eu.llembas.android.api.ActivityEnvelope
|
||||
import eu.llembas.android.api.ActivitySummary
|
||||
import eu.llembas.android.api.AgentStep
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ContextPart
|
||||
import eu.llembas.android.api.DataGroup
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.Memory
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Metrics
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Progress
|
||||
import eu.llembas.android.api.RunError
|
||||
import eu.llembas.android.api.RunModel
|
||||
import eu.llembas.android.api.RunResult
|
||||
import eu.llembas.android.api.RunTokens
|
||||
import eu.llembas.android.api.Schedule
|
||||
import eu.llembas.android.api.ScheduleCompiled
|
||||
import eu.llembas.android.api.ScheduleEnvelope
|
||||
import eu.llembas.android.api.ScheduleRun
|
||||
import eu.llembas.android.api.SchedulingModel
|
||||
import eu.llembas.android.api.SchedulingModels
|
||||
import eu.llembas.android.api.SearchHit
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.SubagentTree
|
||||
import eu.llembas.android.api.SubagentsOffer
|
||||
import eu.llembas.android.api.Tail
|
||||
import eu.llembas.android.api.ToolBlock
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.TreeAgent
|
||||
import eu.llembas.android.api.TreeContext
|
||||
import eu.llembas.android.assist.AssistTurn
|
||||
import eu.llembas.android.assist.AssistUiState
|
||||
import eu.llembas.android.assist.Connection
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
import eu.llembas.android.ui.memory.MemoryState
|
||||
import eu.llembas.android.ui.scheduled.EditState
|
||||
import eu.llembas.android.ui.scheduled.ModelsState
|
||||
import eu.llembas.android.ui.scheduled.RunState
|
||||
import eu.llembas.android.ui.scheduled.ScheduleState
|
||||
import eu.llembas.android.ui.scheduled.ScheduledState
|
||||
import eu.llembas.android.ui.settings.SettingsState
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import java.time.LocalDate
|
||||
|
||||
/** Made-up data for the screenshots: the server's own contract files where they fit. */
|
||||
object Fakes {
|
||||
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")).readText()
|
||||
|
||||
/** The day the drawer is drawn on: chats updated on it are "Today". */
|
||||
val today: LocalDate = LocalDate.of(2026, 3, 10)
|
||||
|
||||
val models = LembasJson.decodeFromString(ModelList.serializer(), text("models")).models
|
||||
val question = LembasJson.decodeFromString(Message.serializer(), text("message_user"))
|
||||
val answer = LembasJson.decodeFromString(Message.serializer(), text("message_assistant"))
|
||||
|
||||
private val packing = Message(
|
||||
id = "m3",
|
||||
role = "user",
|
||||
text = "Plan a three-day walk to the hills. What should I pack?",
|
||||
attachments = listOf(Attachment(id = "a1", name = "map.jpg", image = true), Attachment(id = "a2", name = "route.gpx", mime = "application/gpx+xml")),
|
||||
)
|
||||
|
||||
private val packingSteps = listOf(
|
||||
Step(
|
||||
index = 0,
|
||||
kind = "thinking",
|
||||
text = "Three days, hills, early spring: warm layers, water, food that keeps.",
|
||||
label = "for 4 seconds · 120 tokens",
|
||||
),
|
||||
Step(
|
||||
index = 0,
|
||||
kind = "tools",
|
||||
calls = listOf(
|
||||
ToolCall(id = "c1", name = "web_search", status = "ok", block = ToolBlock(kind = "web", title = "weather in the hills next week")),
|
||||
ToolCall(
|
||||
id = "c2",
|
||||
name = "read",
|
||||
status = "ok",
|
||||
text = "Day 1: 18 km\nDay 2: 22 km\nDay 3: 15 km",
|
||||
block = ToolBlock(kind = "read", title = "notes/route.md"),
|
||||
),
|
||||
),
|
||||
),
|
||||
Step(
|
||||
index = 1,
|
||||
kind = "text",
|
||||
markdown = "Here is a list for **three days**, light enough to carry:\n\n" +
|
||||
"- Lembas, wrapped in leaves (one bite fills a grown man)\n" +
|
||||
"- A warm cloak and a spare pair of socks\n" +
|
||||
"- Two litres of water, and a way to refill it\n\n" +
|
||||
"```python\ndef pack(days):\n return [\"lembas\"] * days + [\"cloak\", \"rope\"]\n```\n\n" +
|
||||
"The second day is the longest: start early.",
|
||||
),
|
||||
)
|
||||
|
||||
private val packingAnswer = Message(
|
||||
id = "m4",
|
||||
role = "assistant",
|
||||
model = "qwen",
|
||||
steps = packingSteps,
|
||||
metrics = Metrics(completionTokens = 412, elapsedMs = 9000, tokPerSecond = 45.8),
|
||||
)
|
||||
|
||||
val chat = Chat(id = "c1", title = "Packing for the road", model = "qwen", updatedAt = "2026-03-10T09:00:00+00:00")
|
||||
|
||||
// A picture the instance made, and the composer asking for the next one.
|
||||
val picture = ChatState(
|
||||
chat = chat,
|
||||
models = models,
|
||||
imagesOffered = true,
|
||||
draft = Draft(image = true),
|
||||
messages = listOf(
|
||||
Message(id = "p1", role = "user", text = "Draw lembas wrapped in a mallorn leaf, on a wooden table."),
|
||||
Message(
|
||||
id = "p2",
|
||||
role = "assistant",
|
||||
model = "qwen",
|
||||
steps = listOf(
|
||||
Step(
|
||||
index = 0,
|
||||
kind = "tools",
|
||||
calls = listOf(
|
||||
ToolCall(
|
||||
id = "g1",
|
||||
name = "image_generate",
|
||||
status = "ok",
|
||||
image = GeneratedImage(id = "att-picture", width = 1216, height = 832),
|
||||
block = ToolBlock(kind = "image", title = "lembas in a mallorn leaf"),
|
||||
),
|
||||
),
|
||||
),
|
||||
Step(index = 1, kind = "text", markdown = "Here it is: the leaf folded twice, as the elves wrap it."),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val newChat = ChatState(models = models)
|
||||
|
||||
val newAgentChat = ChatState(
|
||||
models = models,
|
||||
devices = listOf(LinkedDevice(id = "d1", name = "Workstation", host = "workstation"), LinkedDevice(id = "d2", name = "Laptop", host = "laptop")),
|
||||
draft = Draft(directory = "~/src/garden"),
|
||||
)
|
||||
|
||||
/** A new agent chat with no computer linked: the steps to link one. */
|
||||
val newAgentChatUnlinked = ChatState(models = models, instanceBase = "https://llm.example.org")
|
||||
|
||||
val transcript = ChatState(
|
||||
chat = chat,
|
||||
messages = listOf(question, answer, packing, packingAnswer),
|
||||
models = models,
|
||||
teamOffered = true,
|
||||
summary = ActivitySummary(working = 2, queued = 1, done = 4, finished = 4, active = 3, total = 7),
|
||||
)
|
||||
|
||||
private val fixture = LembasJson.decodeFromString(ActivityEnvelope.serializer(), text("activity")).activity
|
||||
|
||||
private fun job(id: String, type: String, role: String, brief: String, state: String, seconds: Int, stoppable: Boolean = true) = ActivityAgent(
|
||||
kind = "job",
|
||||
id = id,
|
||||
type = type,
|
||||
name = id,
|
||||
role = role,
|
||||
brief = brief,
|
||||
state = state,
|
||||
seconds = seconds,
|
||||
model = if (type == "command") "" else "qwen",
|
||||
agent = if (type == "command") "" else "explore",
|
||||
manager = "lead",
|
||||
stoppable = stoppable,
|
||||
transcript = type != "command",
|
||||
)
|
||||
|
||||
/**
|
||||
* The activity sheet with everything in it, as the reference has it: a context two thirds
|
||||
* free with auto-compact ahead, a team with a member under the lead, subagents and commands
|
||||
* running, four finished, the room and no plan.
|
||||
*/
|
||||
val activity = fixture.copy(
|
||||
summary = ActivitySummary(queued = 1, working = 4, done = 4, finished = 4, active = 5, total = 9),
|
||||
agents = listOf(
|
||||
fixture.agents[0].copy(seconds = 1_135, step = AgentStep(tool = "edit", label = "Edit", title = "recipe.md", running = true)),
|
||||
job("job2", "subagent", "Find where the waybread recipe is used", "Search the notes for every use of the recipe", "working", 97),
|
||||
job("job3", "command", "Run related test files", "pytest -q tests/test_bake.py", "working", 40),
|
||||
fixture.agents[1].copy(role = "Relax status, rerun targeted tests", seconds = 39),
|
||||
) + listOf(
|
||||
job("job4", "subagent", "Read the old packing list", "", "done", 64, stoppable = false),
|
||||
job("job5", "command", "Lint the notes", "ruff check", "done", 12, stoppable = false),
|
||||
job("job6", "subagent", "Check the weather on the pass", "", "error", 8, stoppable = false),
|
||||
job("job7", "command", "Count the provisions", "wc -l list.md", "stopped", 3, stoppable = false),
|
||||
),
|
||||
context = fixture.context!!.copy(
|
||||
used = 41_200,
|
||||
limit = 128_000,
|
||||
percent = 32.2,
|
||||
categories = listOf(
|
||||
ContextPart("messages", 26_300, 20.5),
|
||||
ContextPart("memory", 2_400, 1.9),
|
||||
ContextPart("mcp_tools", 2_300, 1.8),
|
||||
ContextPart("tools", 2_000, 1.6),
|
||||
ContextPart("instructions", 1_300, 1.0),
|
||||
ContextPart("system", 500, 0.4),
|
||||
ContextPart("since", 200, 0.1),
|
||||
ContextPart("buffer", 6_400, 5.0),
|
||||
ContextPart("free", 80_400, 62.8),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/** The last reply while it is being written: its tools done, its words coming in. */
|
||||
val writing = transcript.copy(
|
||||
messages = listOf(question, answer, packing, packingAnswer.copy(steps = emptyList(), complete = false)),
|
||||
live = LiveReply(
|
||||
messageId = "m4",
|
||||
steps = packingSteps.take(2),
|
||||
tail = Tail(text = "Here is a list for **three days**, light enough"),
|
||||
status = "Writing",
|
||||
progress = Progress(phase = "writing", since = 1762790400000, rate = 12.46),
|
||||
),
|
||||
summary = null,
|
||||
)
|
||||
|
||||
/** Waiting for a model, the long reason: the progress line at its widest. */
|
||||
val waitingForModel = writing.copy(
|
||||
live = writing.live!!.copy(progress = Progress(phase = "waiting_for_model", since = 1762790400000, model = "Qwen 27B", reason = "busy")),
|
||||
)
|
||||
|
||||
/**
|
||||
* The subagent tree beside the activity sheet (spec 3.4.0's tree): the main agent, a
|
||||
* sub-manager with one under it paused, one waiting for a slot, an open slot and one ended.
|
||||
*/
|
||||
val tree = SubagentTree(
|
||||
min = 2,
|
||||
max = 5,
|
||||
size = 4,
|
||||
openSlots = 1,
|
||||
agents = listOf(
|
||||
TreeAgent(
|
||||
id = "lead", name = "lead", position = "the main agent", state = "working", model = "qwen", mode = "edit", manager = true,
|
||||
context = TreeContext(41_200, 131_072), progress = Progress(phase = "waiting_for_subagents", since = 1762790400000, running = 2),
|
||||
),
|
||||
TreeAgent(
|
||||
id = "s1", name = "parser", position = "reviews the parser and everything that reads its output", parent = "lead",
|
||||
state = "working", model = "qwen", mode = "edit", manager = true, context = TreeContext(9_100, 131_072),
|
||||
progress = Progress(phase = "running_tool", since = 1762790401000, tool = "read", what = "src/parse.ts"),
|
||||
),
|
||||
TreeAgent(
|
||||
id = "s3", name = "lexer", position = "the lexer's tests", parent = "parser", state = "paused",
|
||||
model = "qwen", mode = "manual", context = TreeContext(112_000, 131_072), progress = Progress(phase = "thinking", since = 1762790402000),
|
||||
),
|
||||
TreeAgent(id = "s4", name = "docs", position = "writes the changelog", parent = "lead", state = "waiting", model = "qwen", mode = "edit"),
|
||||
),
|
||||
ended = listOf(
|
||||
TreeAgent(
|
||||
id = "s2",
|
||||
name = "scout",
|
||||
position = "finds the old parser",
|
||||
parent = "lead",
|
||||
state = "out_of_context",
|
||||
ended = 1762790300000,
|
||||
findings = 2,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/** A chat on a model with effort levels, a team and a plan: the tune sheet with everything. */
|
||||
val tuned = transcript.copy(
|
||||
chat = chat.copy(model = "gpt-oss", effort = "high", mode = "plan", agents = AgentsSetting(1, 4)),
|
||||
)
|
||||
|
||||
/** A chat whose model serves one request at a time, on an instance that caps subagents at 6. */
|
||||
val tunedOneAtATime = tuned.copy(
|
||||
chat = tuned.chat!!.copy(agents = AgentsSetting(2, 3), subagents = SubagentsOffer(offered = true, namedOnly = true, cap = 6)),
|
||||
)
|
||||
|
||||
/** The agent alone: Min 1 · Max 1, no subagents, on an instance that caps a chat at 8. */
|
||||
val tunedAlone = tuned.copy(
|
||||
chat = tuned.chat!!.copy(agents = AgentsSetting(1, 1), subagents = SubagentsOffer(offered = true, cap = 8)),
|
||||
)
|
||||
|
||||
val chats = ChatsState(
|
||||
chats = listOf(
|
||||
chat,
|
||||
Chat(id = "c2", title = "Repairing the garden gate", kind = "agent", updatedAt = "2026-03-10T08:00:00+00:00", running = true),
|
||||
Chat(id = "c3", title = "A letter to the mayor about the bridge", updatedAt = "2026-03-10T07:00:00+00:00", unread = true),
|
||||
Chat(id = "c4", title = "Sourdough timings", updatedAt = "2026-03-09T18:00:00+00:00"),
|
||||
Chat(id = "c5", title = "Translate the recipe into Slovak", updatedAt = "2026-03-08T10:00:00+00:00"),
|
||||
Chat(id = "c6", title = "Why do leaves keep bread fresh, and does it work with any leaf or only some?", updatedAt = "2026-03-01T10:00:00+00:00"),
|
||||
Chat(id = "c7", title = "Clean up the build scripts", kind = "agent", updatedAt = "2026-03-02T10:00:00+00:00"),
|
||||
Chat(id = "c8", title = "The cram recipe, for the long road", folderId = "f2", pinned = true, updatedAt = "2026-02-20T10:00:00+00:00"),
|
||||
Chat(id = "c9", title = "Honey cakes for the party", folderId = "f2", updatedAt = "2026-02-21T10:00:00+00:00"),
|
||||
Chat(id = "c10", title = "Which leaves to wrap it in", folderId = "f1", updatedAt = "2026-02-22T10:00:00+00:00"),
|
||||
),
|
||||
folders = listOf(
|
||||
Folder(id = "f1", name = "Baking", position = 0),
|
||||
Folder(id = "f2", name = "Recipes from the Shire, the long list", parentId = "f1", position = 0),
|
||||
Folder(id = "f3", name = "Letters", position = 1, collapsed = true),
|
||||
),
|
||||
)
|
||||
|
||||
// Memory: one the person wrote, two a model did, in two data groups.
|
||||
val memory = MemoryState(
|
||||
memories = listOf(
|
||||
Memory("m1", "Prefers lembas warm, with a little honey.", author = "user", dataGroup = DataGroup("default", "Default")),
|
||||
Memory(
|
||||
"m2",
|
||||
"Is walking to the mountain with three friends and asks for recipes that keep for weeks without spoiling on the road.",
|
||||
author = "model",
|
||||
dataGroup = DataGroup("default", "Default"),
|
||||
),
|
||||
Memory("m3", "Writes the garden's diary in Slovak.", author = "model", dataGroup = DataGroup("garden", "The garden")),
|
||||
),
|
||||
groups = listOf(DataGroup("default", "Default"), DataGroup("garden", "The garden")),
|
||||
)
|
||||
|
||||
val chatsFound = chats.copy(
|
||||
foundFor = "bread",
|
||||
found = listOf(
|
||||
SearchHit(
|
||||
kind = "chat",
|
||||
id = "c4",
|
||||
title = "Sourdough timings",
|
||||
snippet = "…leave the bread to rise overnight, then bake it at dawn…",
|
||||
marks = listOf(listOf(11, 16)),
|
||||
),
|
||||
SearchHit(
|
||||
kind = "chat",
|
||||
id = "c6",
|
||||
title = "Why do leaves keep bread fresh, and does it work with any leaf or only some?",
|
||||
snippet = "Mallorn leaves keep waybread fresh for weeks; other leaves dry the bread out within days.",
|
||||
marks = listOf(listOf(20, 28), listOf(67, 72)),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
private val home = Instance(id = "i1", base = "https://llm.example.org", name = "Home", email = "frodo@example.org", sealedToken = "")
|
||||
private val work = Instance(id = "i2", base = "https://ai.example.com", name = "Work", email = "f.baggins@example.com", sealedToken = "")
|
||||
|
||||
val settings = SettingsState(
|
||||
instances = listOf(home, work),
|
||||
active = home,
|
||||
prefs = Prefs(theme = "", assistantTemporary = true, accountLanguage = "en"),
|
||||
hasDistributor = true,
|
||||
version = "1.0.0-beta.3",
|
||||
selfUpdate = true,
|
||||
phoneRecognizer = true,
|
||||
)
|
||||
|
||||
// The assistant's sheet, as it opens and as it answers.
|
||||
private val assistBase = AssistUiState(
|
||||
instanceName = "Home",
|
||||
connection = Connection.Online,
|
||||
models = models,
|
||||
modelId = models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id,
|
||||
canSpeak = true,
|
||||
)
|
||||
|
||||
/** Just opened over an app that handed over its screen: listening, the words coming in. */
|
||||
val assistListening = assistBase.copy(
|
||||
listening = true,
|
||||
heard = "How long does waybread keep if it is wrapped in",
|
||||
level = 0.4f,
|
||||
screenText = true,
|
||||
last = LastAssist("c1", "Packing for the road", 0),
|
||||
)
|
||||
|
||||
/** Opened from the tile, nothing asked yet: the last chat, the help, the microphone. */
|
||||
val assistOpened = assistBase.copy(last = LastAssist("c1", "Packing for the road", 0), screenText = true, includeScreen = true)
|
||||
|
||||
/** A spoken question answered, the answer read aloud. */
|
||||
val assistAnswered = assistBase.copy(
|
||||
chatId = "c9",
|
||||
turns = listOf(AssistTurn(question.text.orEmpty(), earlier = answer.steps)),
|
||||
speaking = true,
|
||||
)
|
||||
|
||||
/** An answer being written. */
|
||||
val assistWriting = assistBase.copy(
|
||||
chatId = "c9",
|
||||
busy = true,
|
||||
turns = listOf(
|
||||
AssistTurn(
|
||||
"What is on my screen?",
|
||||
reply = LiveReply("m9", tail = Tail(text = "It is a recipe for waybread: flour, honey and a leaf to wrap it in. The"), status = "Writing…"),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/** The instance cannot be reached. */
|
||||
val assistOffline = assistBase.copy(
|
||||
connection = Connection.Offline,
|
||||
models = emptyList(),
|
||||
modelId = null,
|
||||
canSpeak = false,
|
||||
error = "Home cannot be reached.",
|
||||
)
|
||||
|
||||
// Scheduled: shaped as the server's contract fixtures are (contract/schedule*.json).
|
||||
private fun rule(text: String) = LembasJson.parseToJsonElement(text).jsonObject
|
||||
|
||||
private val ok = ScheduleRun(
|
||||
id = "r1",
|
||||
scheduleId = "s1",
|
||||
status = "ok",
|
||||
timing = "on_time",
|
||||
dueAt = "2026-03-10T07:30:00+00:00",
|
||||
startedAt = "2026-03-10T07:30:02+00:00",
|
||||
finishedAt = "2026-03-10T07:31:40+00:00",
|
||||
attempts = 1,
|
||||
model = RunModel(id = "qwen", name = "Qwen", reason = "pinned"),
|
||||
tokens = RunTokens(prompt = 1200, completion = 340),
|
||||
chatId = "c9",
|
||||
messageId = "m9",
|
||||
preview = "1. Two new offshore wind farms approved in the North Sea. 2. Solar output hit a March record in Spain.",
|
||||
notified = true,
|
||||
)
|
||||
private val nextRuns = listOf(11, 12, 13, 16, 17).map { "2026-03-${it}T07:30:00+00:00" }
|
||||
|
||||
val schedules = listOf(
|
||||
Schedule(
|
||||
id = "s1",
|
||||
title = "Morning news on renewables",
|
||||
instruction = "Sum up the news about renewable energy from the last day, in five points.",
|
||||
request = "Every weekday at 7:30, sum up the news about renewable energy in five points",
|
||||
rule = rule("""{"at":{"weekdays":[0,1,2,3,4],"times":["07:30"]}}"""),
|
||||
description = "Every weekday at 07:30",
|
||||
timezone = "Europe/Bratislava",
|
||||
nextRun = nextRuns.first(),
|
||||
nextRuns = nextRuns,
|
||||
mode = "fresh",
|
||||
notify = "matters",
|
||||
model = "qwen",
|
||||
chatId = "c9",
|
||||
firedCount = 41,
|
||||
lastRun = ok,
|
||||
),
|
||||
Schedule(
|
||||
id = "s2",
|
||||
title = "Check the garden sensors",
|
||||
instruction = "Read the sensors and tell me if the soil is too dry.",
|
||||
rule = rule("""{"every":{"hours":3}}"""),
|
||||
description = "Every 3 hours",
|
||||
nextRun = "2026-03-10T12:00:00+00:00",
|
||||
nextRuns = listOf("2026-03-10T12:00:00+00:00"),
|
||||
mode = "continue",
|
||||
notify = "matters",
|
||||
running = true,
|
||||
lastRun = ScheduleRun(id = "r2", scheduleId = "s2", status = "silent", timing = "on_time"),
|
||||
),
|
||||
Schedule(
|
||||
id = "s3",
|
||||
title = "Weekly backup report",
|
||||
instruction = "Summarise last week's backups and anything that failed.",
|
||||
description = "Every Monday at 09:00",
|
||||
enabled = false,
|
||||
failureStreak = 3,
|
||||
lastRun = ScheduleRun(
|
||||
id = "r3",
|
||||
scheduleId = "s3",
|
||||
status = "failed",
|
||||
error = RunError(kind = "unreachable", text = "The model could not be reached."),
|
||||
),
|
||||
),
|
||||
Schedule(
|
||||
id = "s4",
|
||||
title = "Dentist",
|
||||
instruction = "Remind me to call the dentist.",
|
||||
description = "Once, on Thursday 12 March at 10:00",
|
||||
nextRun = "2026-03-12T09:00:00+00:00",
|
||||
nextRuns = listOf("2026-03-12T09:00:00+00:00"),
|
||||
notify = "always",
|
||||
lastRun = ScheduleRun(
|
||||
id = "r4",
|
||||
scheduleId = "s4",
|
||||
status = "waiting",
|
||||
waitingFor = "model",
|
||||
retryAt = "2026-03-10T07:35:00+00:00",
|
||||
attempts = 2,
|
||||
error = RunError(kind = "no_model", text = "Waiting for a free model: Qwen: it is answering someone."),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val scheduled = ScheduledState(schedules = schedules)
|
||||
|
||||
private val switched = ScheduleRun(
|
||||
id = "r0",
|
||||
scheduleId = "s1",
|
||||
status = "ok",
|
||||
timing = "late",
|
||||
dueAt = "2026-03-09T07:30:00+00:00",
|
||||
startedAt = "2026-03-09T07:41:00+00:00",
|
||||
model = RunModel(id = "gpt-oss", name = "GPT-OSS", reason = "switched", switchedFrom = "Qwen"),
|
||||
chatId = "c8",
|
||||
preview = "Little happened over the weekend: one grid-storage tender in Austria.",
|
||||
)
|
||||
|
||||
private val onComputer = LembasJson.decodeFromString(ScheduleEnvelope.serializer(), text("schedule_on_device")).schedule
|
||||
|
||||
val scheduleOnComputer = ScheduleState(schedule = onComputer, runs = listOfNotNull(onComputer.lastRun))
|
||||
|
||||
val schedule = ScheduleState(
|
||||
schedule = schedules[0],
|
||||
runs = listOf(
|
||||
ok,
|
||||
switched,
|
||||
ScheduleRun(id = "r-1", scheduleId = "s1", dueAt = "2026-03-06T07:30:00+00:00", status = "silent", model = RunModel(id = "qwen", name = "Qwen")),
|
||||
ScheduleRun(id = "r-2", scheduleId = "s1", dueAt = "2026-03-05T07:30:00+00:00", status = "missed", missed = 2),
|
||||
ScheduleRun(
|
||||
id = "r-3",
|
||||
scheduleId = "s1",
|
||||
startedAt = "2026-03-04T07:30:00+00:00",
|
||||
status = "failed",
|
||||
model = RunModel(id = "qwen", name = "Qwen"),
|
||||
error = RunError(kind = "timeout", text = "The model stopped answering after 10 minutes."),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val run = RunState(
|
||||
title = "Morning news on renewables",
|
||||
result = RunResult(
|
||||
run = switched,
|
||||
text = """
|
||||
|Little happened over the weekend. **One thing** worth knowing:
|
||||
|
|
||||
|1. Austria opened a tender for **200 MW** of grid storage, bids due in May.
|
||||
|2. A [report](https://example.org/report) puts Europe's March solar output 18 % above last year.
|
||||
|
|
||||
|```text
|
||||
|storage tender: 200 MW, deadline 2026-05-15
|
||||
|```
|
||||
""".trimMargin(),
|
||||
),
|
||||
)
|
||||
|
||||
val schedulingModels = ModelsState(
|
||||
models = SchedulingModels(
|
||||
models = listOf(
|
||||
SchedulingModel(id = "gpt-oss", name = "GPT-OSS", free = false, busy = "it is answering someone", chosen = true),
|
||||
SchedulingModel(id = "qwen", name = "Qwen", free = true, chosen = true),
|
||||
SchedulingModel(id = "gemma", name = "Gemma 3 27B", free = true, chosen = false),
|
||||
),
|
||||
instance = listOf("gpt-oss", "qwen", "gemma"),
|
||||
mine = listOf("gpt-oss", "qwen"),
|
||||
),
|
||||
)
|
||||
|
||||
val editing = EditState(
|
||||
words = "Every weekday at 7:30, sum up the news about renewable energy in five points",
|
||||
compiled = ScheduleCompiled(
|
||||
ok = true,
|
||||
title = "Morning news on renewables",
|
||||
instruction = "Sum up the news about renewable energy from the last day, in five points.",
|
||||
rule = rule("""{"at":{"weekdays":[0,1,2,3,4],"times":["07:30"]}}"""),
|
||||
description = "Every weekday at 07:30",
|
||||
nextRuns = nextRuns,
|
||||
timezone = "Europe/Bratislava",
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package eu.llembas.android.shots
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
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.shape.RoundedCornerShape
|
||||
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.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.assist.AssistActions
|
||||
import eu.llembas.android.assist.AssistSheetContent
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.AssistUiState
|
||||
import eu.llembas.android.ui.chat.ActivityActions
|
||||
import eu.llembas.android.ui.chat.ActivityContent
|
||||
import eu.llembas.android.ui.chat.CardSheet
|
||||
import eu.llembas.android.ui.chat.ChatActions
|
||||
import eu.llembas.android.ui.chat.ChatContent
|
||||
import eu.llembas.android.ui.chat.ModelPickerContent
|
||||
import eu.llembas.android.ui.chat.TuneContent
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.home.ArchivedActions
|
||||
import eu.llembas.android.ui.home.ArchivedContent
|
||||
import eu.llembas.android.ui.home.ChatsState
|
||||
import eu.llembas.android.ui.home.DrawerActions
|
||||
import eu.llembas.android.ui.home.DrawerContent
|
||||
import eu.llembas.android.ui.memory.MemoryActions
|
||||
import eu.llembas.android.ui.memory.MemoryContent
|
||||
import eu.llembas.android.ui.memory.MemoryState
|
||||
import eu.llembas.android.ui.scheduled.RunContent
|
||||
import eu.llembas.android.ui.scheduled.ScheduleContent
|
||||
import eu.llembas.android.ui.scheduled.ScheduleEditContent
|
||||
import eu.llembas.android.ui.scheduled.ScheduledContent
|
||||
import eu.llembas.android.ui.scheduled.SchedulingModelsContent
|
||||
import eu.llembas.android.ui.settings.LanguageChoices
|
||||
import eu.llembas.android.ui.settings.SettingsActions
|
||||
import eu.llembas.android.ui.settings.SettingsContent
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.time.ZoneOffset
|
||||
|
||||
private object NoChatActions : ChatActions
|
||||
|
||||
private object NoDrawerActions : DrawerActions
|
||||
|
||||
private object NoArchivedActions : ArchivedActions
|
||||
|
||||
private object NoMemoryActions : MemoryActions
|
||||
|
||||
private object NoActivityActions : ActivityActions
|
||||
|
||||
private object NoSettingsActions : SettingsActions
|
||||
|
||||
private object NoAssistActions : AssistActions
|
||||
|
||||
/**
|
||||
* The app's screens with made-up data ([Fakes]), as a phone shows them: each in Shire and
|
||||
* Moria, at a large phone's size and, where things crowd, a small one's and with large type.
|
||||
* See [shoot]. These are looked at after every design change; they assert nothing.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(sdk = [35], qualifiers = "xhdpi")
|
||||
class ScreenShots {
|
||||
@Test
|
||||
fun newChat() {
|
||||
shoot("01-new-chat") { ChatContent(Fakes.newChat, NoChatActions, agent = false, onKind = {}) }
|
||||
shoot("01-new-chat", Phone.Small) { ChatContent(Fakes.newChat, NoChatActions, agent = false, onKind = {}) }
|
||||
shoot("01-new-chat", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.newChat, NoChatActions, agent = false, onKind = {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun newAgentChat() {
|
||||
shoot("02-new-agent-chat") { ChatContent(Fakes.newAgentChat, NoChatActions, agent = true, onKind = {}) }
|
||||
// No computer linked: Agent stays, and says how to link one.
|
||||
shoot("02-new-agent-chat-unlinked") { ChatContent(Fakes.newAgentChatUnlinked, NoChatActions, agent = true, onKind = {}) }
|
||||
shoot("02-new-agent-chat-unlinked", Phone.Small) { ChatContent(Fakes.newAgentChatUnlinked, NoChatActions, agent = true, onKind = {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun transcript() {
|
||||
shoot("03-transcript") { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
shoot("03-transcript", Phone.Small) { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
shoot("03-transcript", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun writing() {
|
||||
// The 3.4.0 progress line under the reply: `{{text}} · {{elapsed}}`, the clock still.
|
||||
shoot("04-writing") { ChatContent(Fakes.writing, NoChatActions, agent = false) }
|
||||
shoot("04-waiting-for-model", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.waitingForModel, NoChatActions, agent = false) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun drawer() {
|
||||
val drawn: @Composable () -> Unit = {
|
||||
ModalNavigationDrawer(
|
||||
drawerState = rememberDrawerState(DrawerValue.Open),
|
||||
drawerContent = {
|
||||
DrawerContent(
|
||||
Fakes.chats,
|
||||
current = "c1",
|
||||
account = "Home · frodo@example.org",
|
||||
actions = NoDrawerActions,
|
||||
today = Fakes.today,
|
||||
zone = ZoneOffset.UTC,
|
||||
)
|
||||
},
|
||||
) { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
}
|
||||
shoot("05-drawer", content = drawn)
|
||||
shoot("05-drawer", Phone.Small, content = drawn)
|
||||
// Searching: the titles that match, then what the instance found inside the messages.
|
||||
shoot("05-drawer-search") {
|
||||
ModalNavigationDrawer(
|
||||
drawerState = rememberDrawerState(DrawerValue.Open),
|
||||
drawerContent = {
|
||||
DrawerContent(
|
||||
Fakes.chatsFound,
|
||||
current = null,
|
||||
account = "Home · frodo@example.org",
|
||||
actions = NoDrawerActions,
|
||||
today = Fakes.today,
|
||||
zone = ZoneOffset.UTC,
|
||||
initialQuery = "bread",
|
||||
)
|
||||
},
|
||||
) { ChatContent(Fakes.transcript, NoChatActions, agent = false) }
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun modelPicker() = shoot("06-model-picker") {
|
||||
SheetOver { ModelPickerContent(Fakes.models, Fakes.transcript.modelId, onPick = {}) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tune() {
|
||||
shoot("07-tune") { SheetOver { TuneContent(Fakes.tuned, NoChatActions, agent = false) } }
|
||||
shoot("07-tune-one-at-a-time") { SheetOver { TuneContent(Fakes.tunedOneAtATime, NoChatActions, agent = false) } }
|
||||
// The Subagents range whole, at a cap of 32 and of 6, and the agent alone (Min 1 · Max 1)
|
||||
// at the narrow phone and large type.
|
||||
shoot("07-tune", Phone.Scroll) { SheetOver { TuneContent(Fakes.tuned, NoChatActions, agent = false) } }
|
||||
shoot("07-tune-one-at-a-time", Phone.Scroll, fontScale = 1.5f) { SheetOver { TuneContent(Fakes.tunedOneAtATime, NoChatActions, agent = false) } }
|
||||
// A new agent chat whose computer's CLI cannot run subagents yet: the setting says so.
|
||||
val agentTune = Fakes.newAgentChat.copy(agentSubagents = eu.llembas.android.api.AgentSubagents(offered = true, deviceRuns = false))
|
||||
shoot("07-tune-new-agent", Phone.Scroll) { SheetOver { TuneContent(agentTune, NoChatActions, agent = true) } }
|
||||
shoot("07-tune-alone", Phone.SmallScroll, fontScale = 1.5f) { SheetOver { TuneContent(Fakes.tunedAlone, NoChatActions, agent = false) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun settings() {
|
||||
shoot("08-settings") { SettingsContent(Fakes.settings, NoSettingsActions) }
|
||||
shoot("08-settings", Phone.Small) { SettingsContent(Fakes.settings, NoSettingsActions) }
|
||||
// The whole page: Language, the assistant's switches and Voice input.
|
||||
shoot("08-settings", Phone.Scroll) { SettingsContent(Fakes.settings, NoSettingsActions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun language() {
|
||||
shoot("17-language", Phone.Scroll) { SheetOver { LanguageChoices(Fakes.settings.prefs, onPick = {}) } }
|
||||
shoot("17-language", Phone.Small, fontScale = 1.5f) { SheetOver { LanguageChoices(Fakes.settings.prefs, onPick = {}) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun scheduled() {
|
||||
shoot("09-scheduled") { ScheduledContent(Fakes.scheduled) }
|
||||
shoot("09-scheduled", Phone.Small) { ScheduledContent(Fakes.scheduled) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun schedule() = shoot("10-schedule") { ScheduleContent(Fakes.schedule) }
|
||||
|
||||
@Test
|
||||
fun scheduleOnAComputer() {
|
||||
// The server's own fixture: on bag-end, in a folder, Edit, and the computer away.
|
||||
shoot("10-schedule-on-computer") { ScheduleContent(Fakes.scheduleOnComputer) }
|
||||
shoot("10-schedule-on-computer", Phone.Small, fontScale = 1.5f) { ScheduleContent(Fakes.scheduleOnComputer) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun scheduleEdit() = shoot("11-schedule-edit") { ScheduleEditContent(Fakes.editing, editing = false) }
|
||||
|
||||
@Test
|
||||
fun scheduleRun() {
|
||||
shoot("12-schedule-run") { RunContent(Fakes.run) }
|
||||
shoot("12-schedule-run", Phone.Small) { RunContent(Fakes.run) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activity() {
|
||||
val sheet: @Composable () -> Unit = { SheetOver { ActivityContent(Fakes.activity, readAt = 0, now = 0, actions = NoActivityActions) } }
|
||||
val open: @Composable () -> Unit = {
|
||||
SheetOver { ActivityContent(Fakes.activity, readAt = 0, now = 0, actions = NoActivityActions, unfolded = true) }
|
||||
}
|
||||
shoot("14-activity", content = sheet)
|
||||
shoot("14-activity", Phone.Small, content = sheet)
|
||||
shoot("14-activity", Phone.Small, fontScale = 1.5f, content = sheet)
|
||||
shoot("14-activity", Phone.Scroll, content = sheet)
|
||||
shoot("15-activity-open", Phone.Scroll, content = open)
|
||||
// Spec 3.4.0's subagents: the reduced list above the background tasks.
|
||||
val tree: @Composable () -> Unit = {
|
||||
SheetOver { ActivityContent(Fakes.activity, readAt = 0, now = 0, actions = NoActivityActions, tree = Fakes.tree) }
|
||||
}
|
||||
shoot("26-subagents", Phone.Scroll, content = tree)
|
||||
shoot("26-subagents", Phone.Small, fontScale = 1.5f, content = tree)
|
||||
shoot("16-activity-new-chat") {
|
||||
SheetOver { ActivityContent(eu.llembas.android.api.Activity(), readAt = 0, now = 0, actions = NoActivityActions, canCompact = false) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet over an app (a chat stands in for whatever was on screen): at half
|
||||
* height as it opens, at a small phone's size and with large type too.
|
||||
*/
|
||||
@Test
|
||||
fun assistant() {
|
||||
val over: (AssistUiState, Boolean) -> @Composable () -> Unit = { state, locked ->
|
||||
{
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
ChatContent(Fakes.transcript, NoChatActions, agent = false)
|
||||
AssistSheetFrame(onDismiss = {}) { handle, _ -> AssistSheetContent(state, NoAssistActions, locked, handle) }
|
||||
}
|
||||
}
|
||||
}
|
||||
shoot("18-assistant-listening", content = over(Fakes.assistListening, false))
|
||||
shoot("18-assistant-listening", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistListening, false))
|
||||
shoot("19-assistant-opened", content = over(Fakes.assistOpened, false))
|
||||
shoot("19-assistant-opened", Phone.Small, content = over(Fakes.assistOpened, false))
|
||||
shoot("20-assistant-answered", content = over(Fakes.assistAnswered, false))
|
||||
shoot("21-assistant-writing", content = over(Fakes.assistWriting, false))
|
||||
shoot("22-assistant-locked", content = over(Fakes.assistOpened, true))
|
||||
shoot("23-assistant-offline", Phone.Small, content = over(Fakes.assistOffline, false))
|
||||
}
|
||||
|
||||
/**
|
||||
* The cards a reply waits on, as the server's contract (`event_ask.json`) has them: a device's
|
||||
* approval (the subagent asking, the heading, the command in its box, the server's reason),
|
||||
* and a question.
|
||||
*/
|
||||
@Test
|
||||
fun cards() {
|
||||
val frame = requireNotNull(javaClass.classLoader!!.getResource("event_ask.json")).readText()
|
||||
val cards = eu.llembas.android.api.LembasJson.decodeFromString(eu.llembas.android.api.AskFrame.serializer(), frame).cards
|
||||
val approval = cards.first { it.kind == "approval" }
|
||||
val fromSubagent = cards.first { it.kind == "approval" && it.items.any { item -> item.subagent != null } }
|
||||
val question = cards.first { it.kind == "question" }
|
||||
shoot("24-approval") { SheetOver { CardSheet(approval, onAnswer = {}) } }
|
||||
shoot("24-approval-subagent") { SheetOver { CardSheet(fromSubagent, onAnswer = {}) } }
|
||||
shoot("24-approval", Phone.Small, fontScale = 1.5f) { SheetOver { CardSheet(approval, onAnswer = {}) } }
|
||||
shoot("25-question") { SheetOver { CardSheet(question, onAnswer = {}) } }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun schedulingModels() = shoot("13-scheduling-models") { SchedulingModelsContent(Fakes.schedulingModels) }
|
||||
|
||||
@Test
|
||||
fun archived() {
|
||||
shoot("27-archived") { ArchivedContent(Fakes.chats, NoArchivedActions) }
|
||||
shoot("27-archived", Phone.Small, fontScale = 1.5f) { ArchivedContent(Fakes.chats, NoArchivedActions) }
|
||||
shoot("27-archived-none") { ArchivedContent(ChatsState(), NoArchivedActions) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun picture() {
|
||||
// The picture's place is its size before it loads (screenshots fetch nothing).
|
||||
shoot("29-generated-image") { ChatContent(Fakes.picture, NoChatActions, agent = false) }
|
||||
shoot("29-generated-image", Phone.Small, fontScale = 1.5f) { ChatContent(Fakes.picture, NoChatActions, agent = false) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun memory() {
|
||||
shoot("28-memory") { MemoryContent(Fakes.memory, NoMemoryActions) }
|
||||
shoot("28-memory", Phone.Small, fontScale = 1.5f) { MemoryContent(Fakes.memory, NoMemoryActions) }
|
||||
shoot("28-memory-none") { MemoryContent(MemoryState(), NoMemoryActions) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A bottom sheet's content as the sheet shows it, over a dimmed page: the sheet itself is a
|
||||
* window of its own, which a screenshot of the page does not hold.
|
||||
*/
|
||||
@Composable
|
||||
private fun SheetOver(content: @Composable () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Box(Modifier.fillMaxSize().background(palette.bg)) {
|
||||
Box(Modifier.fillMaxSize().background(palette.inkInverse.copy(alpha = 0.5f)))
|
||||
Surface(
|
||||
color = palette.surface,
|
||||
shape = RoundedCornerShape(topStart = 28.dp, topEnd = 28.dp),
|
||||
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth(),
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(Modifier.padding(vertical = 16.dp).size(width = 32.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp)))
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
@file:OptIn(ExperimentalRoborazziApi::class)
|
||||
|
||||
package eu.llembas.android.shots
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.github.takahirom.roborazzi.ExperimentalRoborazziApi
|
||||
import com.github.takahirom.roborazzi.RoborazziComposeOptions
|
||||
import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.github.takahirom.roborazzi.fontScale
|
||||
import com.github.takahirom.roborazzi.inspectionMode
|
||||
import com.github.takahirom.roborazzi.size
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
|
||||
/**
|
||||
* The phones the screens are looked at on: a large one, and a small one where things crowd.
|
||||
* [Scroll] is the large one's width, tall enough to see a sheet's whole scroll at once;
|
||||
* [SmallScroll] the same for the small one.
|
||||
*/
|
||||
enum class Phone(val tag: String, val widthDp: Int, val heightDp: Int) {
|
||||
Large("411x891", 411, 891),
|
||||
Small("360x640", 360, 640),
|
||||
Scroll("411x2000", 411, 2000),
|
||||
SmallScroll("360x2000", 360, 2000),
|
||||
}
|
||||
|
||||
/**
|
||||
* Render [content] in the app's theme, light (Shire) and dark (Moria), at [phone]'s size and
|
||||
* write each to `app/build/screenshots/<phone>-<name>-<theme>.png`, which CI uploads. These are
|
||||
* for looking at -- by a person, or by an agent reading the PNGs -- not compared against
|
||||
* anything: a design change is meant to change them.
|
||||
*/
|
||||
fun shoot(name: String, phone: Phone = Phone.Large, fontScale: Float = 1f, content: @Composable () -> Unit) {
|
||||
for ((theme, choice) in listOf("light" to "shire", "dark" to "moria")) {
|
||||
val font = if (fontScale != 1f) "-font$fontScale" else ""
|
||||
captureRoboImage(
|
||||
filePath = "build/screenshots/${phone.tag}-$name-$theme$font.png",
|
||||
roborazziComposeOptions = RoborazziComposeOptions {
|
||||
size(phone.widthDp, phone.heightDp)
|
||||
// As a preview: no endless animation, no pictures fetched from an instance.
|
||||
inspectionMode(true)
|
||||
if (fontScale != 1f) fontScale(fontScale)
|
||||
},
|
||||
) {
|
||||
LembasTheme(choice) {
|
||||
Surface(Modifier.fillMaxSize()) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,189 @@
|
||||
{
|
||||
"activity": {
|
||||
"version": "0123456789abcdef",
|
||||
"summary": {
|
||||
"queued": 1,
|
||||
"working": 2,
|
||||
"waiting": 0,
|
||||
"done": 1,
|
||||
"stopped": 0,
|
||||
"error": 0,
|
||||
"active": 3,
|
||||
"finished": 1,
|
||||
"total": 4
|
||||
},
|
||||
"agents": [
|
||||
{
|
||||
"kind": "member",
|
||||
"id": "baker",
|
||||
"type": "member",
|
||||
"name": "baker",
|
||||
"role": "owns the oven",
|
||||
"brief": "Bake the waybread.",
|
||||
"state": "working",
|
||||
"seconds": 95,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "general",
|
||||
"manager": "lead",
|
||||
"depth": 0,
|
||||
"lead": true,
|
||||
"step": {
|
||||
"tool": "read",
|
||||
"label": "Read",
|
||||
"title": "recipe.md",
|
||||
"error": false,
|
||||
"running": true
|
||||
},
|
||||
"text": "The dough needs…",
|
||||
"steps": 4,
|
||||
"tools": 3,
|
||||
"stoppable": true,
|
||||
"transcript": true,
|
||||
"children": [
|
||||
{
|
||||
"kind": "member",
|
||||
"id": "wrapper",
|
||||
"type": "member",
|
||||
"name": "wrapper",
|
||||
"role": "owns the leaves",
|
||||
"brief": "Wrap each cake.",
|
||||
"state": "queued",
|
||||
"seconds": 0,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "general",
|
||||
"manager": "baker",
|
||||
"depth": 1,
|
||||
"lead": false,
|
||||
"step": null,
|
||||
"text": "",
|
||||
"steps": 0,
|
||||
"tools": 0,
|
||||
"stoppable": true,
|
||||
"transcript": true,
|
||||
"children": []
|
||||
},
|
||||
{
|
||||
"kind": "job",
|
||||
"id": "baker:job1",
|
||||
"type": "subagent",
|
||||
"name": "baker:job1",
|
||||
"role": "find mallorn leaves",
|
||||
"brief": "Where do mallorn grow?",
|
||||
"state": "done",
|
||||
"seconds": 12,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "explore",
|
||||
"manager": "baker",
|
||||
"depth": 1,
|
||||
"lead": false,
|
||||
"step": null,
|
||||
"text": "In Lothlórien.",
|
||||
"steps": 2,
|
||||
"tools": 1,
|
||||
"stoppable": false,
|
||||
"transcript": true,
|
||||
"children": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "job",
|
||||
"id": "job1",
|
||||
"type": "command",
|
||||
"name": "job1",
|
||||
"role": "pytest",
|
||||
"brief": "pytest -q",
|
||||
"state": "working",
|
||||
"seconds": 30,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "",
|
||||
"agent": "",
|
||||
"manager": "lead",
|
||||
"depth": 0,
|
||||
"lead": false,
|
||||
"step": null,
|
||||
"text": "",
|
||||
"steps": 0,
|
||||
"tools": 0,
|
||||
"stoppable": true,
|
||||
"transcript": false,
|
||||
"children": []
|
||||
}
|
||||
],
|
||||
"team": {
|
||||
"min": 1,
|
||||
"max": 4,
|
||||
"size": 3,
|
||||
"goal": "Bake for the journey",
|
||||
"room": [
|
||||
{
|
||||
"n": 1,
|
||||
"from": "baker",
|
||||
"to": [
|
||||
"wrapper"
|
||||
],
|
||||
"text": "Leaves by noon?",
|
||||
"report": false,
|
||||
"created": "2026-01-02T03:04:05+00:00"
|
||||
},
|
||||
{
|
||||
"n": 2,
|
||||
"from": "wrapper",
|
||||
"to": [
|
||||
"baker"
|
||||
],
|
||||
"text": "Done: *mallorn* leaves.",
|
||||
"report": true,
|
||||
"created": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
],
|
||||
"cursor": 2
|
||||
},
|
||||
"team_offered": true,
|
||||
"subagents_offered": true,
|
||||
"context": {
|
||||
"used": 41000,
|
||||
"limit": 128000,
|
||||
"percent": 32.0,
|
||||
"measured": true,
|
||||
"threshold": 95,
|
||||
"auto_compact": true,
|
||||
"until_compact": 80600,
|
||||
"compactable": true,
|
||||
"tools_count": 24,
|
||||
"mcp_count": 2,
|
||||
"categories": [
|
||||
{
|
||||
"key": "messages",
|
||||
"tokens": 30000,
|
||||
"percent": 23.4
|
||||
},
|
||||
{
|
||||
"key": "system",
|
||||
"tokens": 4000,
|
||||
"percent": 3.1
|
||||
},
|
||||
{
|
||||
"key": "free",
|
||||
"tokens": 80600,
|
||||
"percent": 63.0
|
||||
}
|
||||
]
|
||||
},
|
||||
"outputs": [
|
||||
{
|
||||
"path": "/home/frodo/recipe.md",
|
||||
"name": "recipe.md",
|
||||
"writes": 2,
|
||||
"created": false,
|
||||
"added": 42,
|
||||
"removed": 6,
|
||||
"at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
],
|
||||
"plan": null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"agent": {
|
||||
"kind": "member",
|
||||
"id": "baker",
|
||||
"type": "member",
|
||||
"name": "baker",
|
||||
"role": "owns the oven",
|
||||
"brief": "Bake the waybread.",
|
||||
"state": "working",
|
||||
"seconds": 95,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "general",
|
||||
"manager": "lead",
|
||||
"depth": 0,
|
||||
"lead": true,
|
||||
"step": {
|
||||
"tool": "read",
|
||||
"label": "Read",
|
||||
"title": "recipe.md",
|
||||
"error": false,
|
||||
"running": true
|
||||
},
|
||||
"text": "The dough needs…",
|
||||
"steps": 4,
|
||||
"tools": 3,
|
||||
"stoppable": true,
|
||||
"transcript": true,
|
||||
"children": [
|
||||
{
|
||||
"kind": "member",
|
||||
"id": "wrapper",
|
||||
"type": "member",
|
||||
"name": "wrapper",
|
||||
"role": "owns the leaves",
|
||||
"brief": "Wrap each cake.",
|
||||
"state": "queued",
|
||||
"seconds": 0,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "general",
|
||||
"manager": "baker",
|
||||
"depth": 1,
|
||||
"lead": false,
|
||||
"step": null,
|
||||
"text": "",
|
||||
"steps": 0,
|
||||
"tools": 0,
|
||||
"stoppable": true,
|
||||
"transcript": true,
|
||||
"children": []
|
||||
},
|
||||
{
|
||||
"kind": "job",
|
||||
"id": "baker:job1",
|
||||
"type": "subagent",
|
||||
"name": "baker:job1",
|
||||
"role": "find mallorn leaves",
|
||||
"brief": "Where do mallorn grow?",
|
||||
"state": "done",
|
||||
"seconds": 12,
|
||||
"started": "2026-01-02T03:04:05+00:00",
|
||||
"model": "local/qwen",
|
||||
"agent": "explore",
|
||||
"manager": "baker",
|
||||
"depth": 1,
|
||||
"lead": false,
|
||||
"step": null,
|
||||
"text": "In Lothlórien.",
|
||||
"steps": 2,
|
||||
"tools": 1,
|
||||
"stoppable": false,
|
||||
"transcript": true,
|
||||
"children": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"transcript": [
|
||||
{
|
||||
"role": "user",
|
||||
"text": "Bake the waybread.",
|
||||
"machine": false
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"text": "Baking.",
|
||||
"tools": [
|
||||
{
|
||||
"name": "read",
|
||||
"title": "recipe.md",
|
||||
"isError": false
|
||||
}
|
||||
],
|
||||
"error": "",
|
||||
"running": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"server": {
|
||||
"version": "2.1.0-beta.3",
|
||||
"channel": "beta"
|
||||
},
|
||||
"apps": {
|
||||
"android": {
|
||||
"version": "1.1.0-beta.2",
|
||||
"tag": "v1.1.0-beta.2",
|
||||
"channel": "beta",
|
||||
"page": "https://github.com/LLeMbas/LLeMbas-Android/releases/tag/v1.1.0-beta.2"
|
||||
},
|
||||
"desktop": {
|
||||
"version": "1.0.1",
|
||||
"tag": "v1.0.1",
|
||||
"channel": "stable",
|
||||
"page": "https://github.com/LLeMbas/LLeMbas-Desktop/releases/tag/v1.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"server": {
|
||||
"version": "2.0.0",
|
||||
"channel": "stable"
|
||||
},
|
||||
"apps": {
|
||||
"android": null,
|
||||
"desktop": {
|
||||
"version": "1.0.1",
|
||||
"tag": "v1.0.1",
|
||||
"channel": "stable",
|
||||
"page": "https://github.com/LLeMbas/LLeMbas-Desktop/releases/tag/v1.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,17 @@
|
||||
"mode": "",
|
||||
"effort": "low",
|
||||
"device": null,
|
||||
"device_session_id": null,
|
||||
"parent_chat_id": null,
|
||||
"agents": {
|
||||
"min": 1,
|
||||
"max": 4
|
||||
},
|
||||
"subagents": {
|
||||
"offered": true,
|
||||
"named_only": false,
|
||||
"cap": 32
|
||||
},
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
@@ -15,7 +15,17 @@
|
||||
"token_id": "token1",
|
||||
"directory": "/home/dev/project"
|
||||
},
|
||||
"device_session_id": "ses_01waybread",
|
||||
"parent_chat_id": null,
|
||||
"agents": {
|
||||
"min": 1,
|
||||
"max": 4
|
||||
},
|
||||
"subagents": {
|
||||
"offered": true,
|
||||
"named_only": false,
|
||||
"cap": 32
|
||||
},
|
||||
"created_at": "2026-01-02T03:04:05+00:00",
|
||||
"updated_at": "2026-01-02T03:04:05+00:00"
|
||||
}
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user