Compare commits
63
Commits
v1.0.0-beta.9
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e5829856f
|
||
|
|
1e9862fc0b
|
||
|
|
85bd4b0489
|
||
|
|
f84551c65e
|
||
|
|
81f255bd94
|
||
|
|
1e32868d36
|
||
|
|
da2c5891ed
|
||
|
|
f8d122d409
|
||
|
|
827f57839f
|
||
|
|
71b2e847cf
|
||
|
|
cf092ef1a1
|
||
|
|
549ce17645
|
||
|
|
4e1a16a351
|
||
|
|
864bdc6b6e
|
||
|
|
79cd9f3804
|
||
|
|
08a720465e
|
||
|
|
bac89b5e68
|
||
|
|
5e5e63353a
|
||
|
|
660ff90b3a
|
||
|
|
9610a8a9d8
|
||
|
|
1f596af56d
|
||
|
|
635982a4f8
|
||
|
|
5d9e367992
|
||
|
|
72657ba157
|
||
|
|
37574292cd
|
||
|
|
a9bdfcc18a
|
||
|
|
5256959a11
|
||
|
|
c4813831f5
|
||
|
|
6e08795a5c
|
||
|
|
385f2f7f5d
|
||
|
|
eeba64b1c7
|
||
|
|
a249b516fd
|
||
|
|
7a75633ea1
|
||
|
|
7fcdecf1c8
|
||
|
|
7971676344
|
||
|
|
97ba7f6a29
|
||
|
|
e485530e46
|
||
|
|
1659a79848
|
||
|
|
dec2225a9c
|
||
|
|
5d1e36868c
|
||
|
|
6e24f6f370
|
||
|
|
536f71a627
|
||
|
|
ceaf8ea91f
|
||
|
|
c38582f600
|
||
|
|
7d49b8d94b
|
||
|
|
2375affca8
|
||
|
|
df20788d7f
|
||
|
|
8e84f0d53d
|
||
|
|
4b4fe46725
|
||
|
|
8a486b7228
|
||
|
|
f04a670227
|
||
|
|
efba3aacf4
|
||
|
|
1d3154cefa
|
||
|
|
979a504600
|
||
|
|
c0dd0b5a50
|
||
|
|
5689994037
|
||
|
|
4344b35a27
|
||
|
|
6540d160df
|
||
|
|
a4a5c5dba1
|
||
|
|
cdb6a35371
|
||
|
|
5e45293462
|
||
|
|
7ca44ef5e2
|
||
|
|
2f43b94e56
|
No files matched your search
+456
-2
@@ -1,7 +1,461 @@
|
||||
# Changelog
|
||||
|
||||
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
|
||||
is in alpha and releases come off `main`.
|
||||
What changed in each release of LLeMbas for Android. Versions follow SemVer: the `1.0.0-beta.N`
|
||||
releases are the betas of 1.0.0 and come off `dev`; a release without a suffix comes off `main`.
|
||||
|
||||
## Unreleased
|
||||
|
||||
## [1.0.0-beta.18] — 2026-12-03
|
||||
|
||||
A round of checking: the code, the words, what an outside app can make the app do. Fixes only.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A beta is offered the release.** The app's own installer compared versions by a rule of its
|
||||
own, by which 1.0.0 was not newer than 1.0.0-beta.N: *Install* would have answered "This is the
|
||||
newest version". It now compares as the rest of the app does.
|
||||
- **A list read a page at a time no longer ends the app.** The chats in the drawer, the archived
|
||||
chats and a schedule's runs ask for their next page when the list's end comes into view; while
|
||||
that page was on its way a second request for it could start, and the same rows arriving twice
|
||||
closed the app. One page is read at a time, and no row is added twice.
|
||||
- **After a switch of instance the drawer is the new instance's.** It showed the other
|
||||
instance's chats and its Reports badge until its own list had been read -- for good, if that
|
||||
read failed -- and an instance refused as too old left the next one refused as well.
|
||||
- **A photo taken with the phone turned is attached.** When the screen was made again on the way
|
||||
back from the camera, the photo was dropped without a word.
|
||||
- **Pause in a scheduled task's notification asks for the unlock**, as Allow once, Deny, Run
|
||||
again and Mark read do: it acts on the account, and a lock screen that shows notifications in
|
||||
full offered it to whoever held the phone.
|
||||
- **A file picked for a message is opened as a shared one is.** What a picker answers is another
|
||||
app's word; one that named a file of this app's own (a copy it holds for another app, a path
|
||||
into its data) was read with the app's own rights and would have been attached. Only the photo
|
||||
the camera took for the message is the app's own.
|
||||
- **A photo whose upload failed does not stay on the phone.** It goes with the other copies at
|
||||
sign-out and on a switch of instance, and by its age when the app starts.
|
||||
- **The sign-in page scrolls**: a long sentence about a certificate, large type and the keyboard
|
||||
could push *Continue* out of reach.
|
||||
- A failure of the app's own installer is said in the app's words, not a library's.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Words.** The wake word is under *Settings › Wake word*, and the assistant's hint now says so
|
||||
(it named a place under *Assistant*). *Voice input › LLeMbas* no longer says the recording goes
|
||||
"nowhere else": the phone sends it to your instance only, and the instance writes it down with
|
||||
the speech model set up there. *Look for new versions* says when GitHub's list is read:
|
||||
whenever the instance cannot say which release goes with it. Signing in no longer compares
|
||||
itself to the CLI, and "speaks a newer app API" is "is newer than this app can work with". A
|
||||
linked machine is a "computer" in a new agent chat as it is everywhere else.
|
||||
- **Translations.** *Set as default* and *Switch instance* were English in every language.
|
||||
Slovak, Czech and French used two or three words for a chat, and Slovak and Czech two for a
|
||||
notification: one each now, the instance's own. German, Spanish and Hungarian addressed you
|
||||
formally in some sentences and informally in others, Italian likewise; each now keeps to the
|
||||
form the instance's own sentences use. Translations are the engineers' own and not proofread.
|
||||
|
||||
## [1.0.0-beta.17] — 2026-12-01
|
||||
|
||||
How the app connects to an instance, brought in line with the other LLeMbas clients. Fixes only.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **An instance that signed the phone out is noticed.** When an instance refuses the app's token
|
||||
(it was revoked there, or it expired), that instance -- not whichever happens to be in use --
|
||||
is marked signed out, nothing more is asked with the dead token, and a page offers *Sign in
|
||||
again* in one step. Chats being written, the settings kept for the instance and every other
|
||||
instance stay as they were. Before, each screen showed the server's refusal and the app went on
|
||||
as if signed in. A "not allowed" (403) is still just the server's sentence, and a refusal
|
||||
passed on from a provider behind the instance signs nobody out.
|
||||
- **One rule for the address.** `HTTPS://Example.org/`, `example.org/chat?x=1` and
|
||||
`example.org:8443/` are read as the other LLeMbas clients read them: the scheme in any case,
|
||||
the host in lower case, the path dropped. An `http://` address is answered where it is typed
|
||||
-- this app needs https -- instead of failing later with a library's error.
|
||||
- **The address you typed is the one kept.** A new sign-in stores the address as it was typed
|
||||
(read by the rule above), not the one the instance says of itself, and the sign-in itself goes
|
||||
only to that address: an instance whose proxy makes it name another host says so in words.
|
||||
Instances already on the phone are untouched -- same entry, same token, same settings, same
|
||||
notifications -- and signing in again to one of them, by either address, refreshes that entry
|
||||
rather than adding a second one.
|
||||
- **An instance can say the app is too old.** Where an instance names the oldest version of
|
||||
the app it works with (`min_clients` in its discovery document) and this one is older, the app
|
||||
says so with both versions and does not go on.
|
||||
- **Each failure says what it is.** Cannot be reached, did not answer in time, a certificate the
|
||||
phone does not trust (with where to install the CA), no LLeMbas instance at the address, "the
|
||||
server answered 502", an instance too old, an app too old: one sentence each. A server in
|
||||
trouble is no longer "not a LLeMbas instance", and another service is no longer "an older
|
||||
LLeMbas".
|
||||
- **A sign-in ends by its real reason.** Only an expired code is "the code expired"; a server
|
||||
that restarts or a network that drops while you approve in the browser no longer ends the
|
||||
sign-in; too many sign-ins is said in the server's words. Cancelling a sign-in no longer
|
||||
leaves an error line under the address.
|
||||
- **A dead connection is noticed.** A stream that says nothing for 45 seconds (the instance
|
||||
sends a keepalive every 15) is opened again, instead of being followed for ever after the
|
||||
phone changed network.
|
||||
- **One reconnect schedule.** Streams are opened again after 1 second doubling to 60, each
|
||||
jittered by a fifth, and quickly again only after a connection held for half a minute. "Too
|
||||
many requests" (429) waits as long as the instance asks.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The app names itself.** Every request carries `User-Agent: llembas-android/<version>`, and
|
||||
the sign-in sends the same string, so an instance's list of devices shows which app and
|
||||
version signed in.
|
||||
|
||||
## [1.0.0-beta.16] — 2026-11-26
|
||||
|
||||
### Added
|
||||
|
||||
- **Default instance and quick drawer switcher.** Choose a **Default** account
|
||||
or instance in Settings → Instances (marked with a badge and opened on cold
|
||||
starts, as well as used by Assistant, Widget, and Share actions). Switch
|
||||
between saved accounts and instances directly from the navigation drawer or
|
||||
add another account with quick-pick chips for existing servers.
|
||||
- **Per-account actions in Settings.** Every saved account row now offers
|
||||
*Set as default* and *Sign out* from its overflow menu (not only the active
|
||||
account).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Per-instance preferences isolation.** Assistant model, last assistant chat,
|
||||
and account language are now stored per instance rather than leaking across
|
||||
accounts when switching.
|
||||
|
||||
## [1.0.0-beta.15] — 2026-11-24
|
||||
|
||||
What is said here of shown files and of an edit's diff needs an instance newer than LLeMbas
|
||||
2.0.0-beta.18. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **A file an agent shows is in the chat, whatever it is.** When an agent puts a file in front
|
||||
of you that is not text -- a screenshot it took, a recording, a report -- the reply holds it
|
||||
where generated media is: a picture is drawn, with its name under it; sound and video have
|
||||
Play and the app's own player; a PDF has Open, which lays its pages out over the chat. A 3D
|
||||
model, an archive, a text file that came this way and any other file are a row with the
|
||||
file's name, what it is in words and its size. A kind the app has not heard of is a "File",
|
||||
never an empty place. Every one of them has Open in Files, Download, Share and Open with.
|
||||
Whether a file is shown does not depend on what the model itself can read.
|
||||
- **An edit's approval card shows what would change.** Where a linked computer asks before an
|
||||
edit, the card lists each file with the lines that go and the lines that come, marked by a
|
||||
sign and by colour, with a little unchanged text around them; a new file and a deleted one
|
||||
say so. Long lines scroll sideways inside their own box; a long change is folded to its first
|
||||
lines with "Show all". Both texts are drawn as plain text. Allow and Deny are as they were.
|
||||
A character that cannot be seen or that changes the direction of a line, in a line or in a
|
||||
path, is written as its code point (`<U+202E>`), so what the card shows is what is written. A
|
||||
file whose line endings change says so once instead of showing every line twice. A very long
|
||||
change is compared only at its beginning and says so, and is worked out beside the screen,
|
||||
not in it. The call's arguments stay in view when there is no change to show.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A picture in a chat is fetched only while the app is in front of an unlocked phone**, like
|
||||
every other file of the account; one that comes into view behind the lock waits. The
|
||||
assistant's sheet counts as the app in front, so a picture in it is fetched as before.
|
||||
- **"Open with" offers a file as what it is.** The type handed to the other app is read from the
|
||||
file's own first bytes, or from its name's extension where the bytes carry no mark, and no
|
||||
longer taken from what the instance said of it.
|
||||
- Pinned to the server's `dev` at `809b87b`. A linked computer's files and the editor's two
|
||||
models are read from the instance and not shown anywhere yet: this app has no browser for a
|
||||
computer's files and no screen for the editor's settings.
|
||||
|
||||
- **The launcher icon is the app's own**: the LLeMbas leaf with a small phone beside it, so the app
|
||||
is told apart from the other LLeMbas products. The notification icon stays the leaf.
|
||||
|
||||
## [1.0.0-beta.14] — 2026-11-24
|
||||
|
||||
What is said here of replies that start by themselves needs an instance newer than LLeMbas
|
||||
2.0.0-beta.17. On an older one the app behaves as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **An open chat shows a reply it did not ask for, as it is written.** When a subagent finishes
|
||||
and the main agent answers, when a scheduled task's result or a finished generation wakes the
|
||||
chat, or when the linked computer starts a turn itself, the reply appears and is written in
|
||||
front of you, with its tools and cards, instead of only after the chat was opened again.
|
||||
Coming back to the app reads the chat once, for what happened meanwhile. Such a reply is
|
||||
followed only while the app is in front of an unlocked phone: locked or in the background the
|
||||
app lets it go and asks the instance nothing, and on your return it picks up where the chat
|
||||
is then. A reply you asked for yourself goes on being received, as before.
|
||||
- **The list of chats moves by itself.** While the drawer is open, a chat a reply starts in
|
||||
goes to the top and shows its dot, and the dot of a reply being written goes when the reply
|
||||
ends, without the drawer being closed and opened.
|
||||
|
||||
- **A message that waits can be sent now or discarded.** Under a message that has not been
|
||||
given to a model yet -- queued behind a reply, or waiting on a linked computer -- there are
|
||||
"Send now" and "Discard", as on the web page. Send now starts its reply, which is written in
|
||||
front of you like any you asked for; Discard asks once and takes the message away. Where the
|
||||
instance refuses (a reply is still being written; the message is no longer waiting), it says
|
||||
so in its own words and the chat is read again. A waiting message is not offered Edit: the
|
||||
instance refuses that. Needs an instance that has these two actions.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A waiting message says how it waits**, in the instance's words. One of which it is not
|
||||
known whether it reached the linked computer says so, instead of looking queued: the
|
||||
instance does not send it by itself. One the computer holds says that the computer has it
|
||||
and takes it in with its next turn.
|
||||
- **A turn the linked computer started is a quiet note**, as a schedule's line is: it never
|
||||
looks like something you typed.
|
||||
- In an agent chat, a finished reply that holds nothing, after such a turn, says "The reply to
|
||||
this was not recorded." in one line. Older instances left a few of these as blank rows.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The chat keeps its place.** At the end of the chat you stay at the end; anywhere else, what
|
||||
you are reading does not move.
|
||||
- Reading the chat again (after an edit, a queued message, a reply that woke the chat) no
|
||||
longer takes away the earlier messages you had loaded, and with them the row you were
|
||||
reading.
|
||||
- The app's own scroll to the end can no longer be taken for you scrolling away, which
|
||||
stopped the chat from following a reply although you had not touched it. The assistant's
|
||||
sheet has the same fix.
|
||||
- Scrolling up with a mouse wheel, a keyboard or a screen reader while a reply arrives no
|
||||
longer throws you back to the end: only a finger used to count as you scrolling.
|
||||
- A reply's foot is as tall while it is written as when it has finished, so the end of a
|
||||
reply no longer changes the height of the page.
|
||||
|
||||
## [1.0.0-beta.13] — 2026-11-19
|
||||
|
||||
For Files, generated media and MCP servers as described here the instance must be newer than
|
||||
LLeMbas 2.0.0-beta.16. On an older one Files lists and shows text as before, and says so where
|
||||
it cannot do more.
|
||||
|
||||
### Added
|
||||
|
||||
- **Files is a file manager.** Upload from the phone (several at once, with progress; a file
|
||||
over the instance's limit is refused in the instance's own words and the others still go),
|
||||
make a folder or a text file, rename, move and copy by walking to the folder rather than
|
||||
typing a path, and delete to the trash. A long press chooses; with several chosen, a bar moves,
|
||||
copies, downloads, shares or deletes them all, and says which the instance refused.
|
||||
- **The trash and a file's versions.** What was deleted can be restored or removed for good,
|
||||
one thing or everything. A file's earlier versions are listed, and any of them can be made
|
||||
the file again without losing the others, or saved to the phone as it was.
|
||||
- **Download, Open with and Share.** A file is saved where you choose in the phone's own
|
||||
"Save to" page; several files or a folder come as one zip. Open with and Share hand another
|
||||
app a copy from the app's private storage, which is deleted an hour later, and at once when
|
||||
you sign out or switch instance. The app asks for no storage permission.
|
||||
- **Text files can be edited.** Markdown, code, plain text, a page's source and a table's text,
|
||||
up to the instance's 1 MB. If the file changed on the instance while you were writing, nothing
|
||||
is written over: you choose Reload or Save anyway. Leaving with unsaved text asks first.
|
||||
- **A viewer for each kind of file.** Pictures, with zoom and pan; PDFs, page by page; sound and
|
||||
video, streamed, with seeking; CSV and TSV as a grid; notebooks as their cells' text; an
|
||||
archive as the list of what is inside it, with nothing unpacked. For 3D models and anything
|
||||
else: what it is, with Download, Open with and Share. A PDF is shown up to 100 MB and 2000
|
||||
pages. An HTML page and an SVG are shown as their source -- the app draws nothing a file
|
||||
could script.
|
||||
- **"Save to Files" in the share sheet.** Something shared from another app can be kept in a
|
||||
folder of your files instead of being sent into a chat; shared text is kept as a note. If a
|
||||
file is refused, Save again goes on from that file and does not send the earlier ones twice.
|
||||
- **The share sheet says what came in.** Each shared file is listed with its name and size
|
||||
before anything is sent, and the instance is asked nothing until you choose what to do.
|
||||
- **What a model makes is shown in the chat.** A picture, a video, a piece of music or a 3D
|
||||
model the instance made has a card in the reply: the picture drawn, video and music with
|
||||
Play, a 3D model as what it is. Each card leads to the file in Files -- where it is now, also
|
||||
after it was renamed or moved -- saves it where you choose, shares it, or opens it with
|
||||
another app.
|
||||
- **A long generation shows how it stands.** A video or a track takes minutes. Its card says
|
||||
what is being made, whether it is waiting or running and for how long, and has Cancel. When
|
||||
it is ready the card becomes the player and the chat says so; when it was not made, the card
|
||||
says why in the instance's own words. Nothing of this is shown over the lock screen, and the
|
||||
app posts no notification about a file.
|
||||
- **Sound and video you attached can be played** from the message they are attached to.
|
||||
- **Settings › MCP servers.** The MCP servers your chats may be offered, how many tools each
|
||||
has and how each is signed in to. One that waits for your sign-in has a button that opens the
|
||||
instance's own sign-in page in the browser; the list is read again when you come back.
|
||||
- **A new folder from inside the folder picker**, when moving, copying or saving a share.
|
||||
- **A table can be shown as its text**, and as a table again.
|
||||
|
||||
### Changed
|
||||
|
||||
- **A new file is never written over another.** The instance now makes a new file only where
|
||||
nothing has that name, and says what is there otherwise.
|
||||
- **Only models you can chat with are offered** in the model lists and for the assistant.
|
||||
- **Nothing new is sent while the phone is locked.** Uploads, downloads and the copies for
|
||||
Share and Open with go one request at a time: when the phone locks or the app is left, the
|
||||
one under way finishes and the rest wait, and go on by themselves when the app is open on an
|
||||
unlocked phone again. The progress dialog says when it is waiting.
|
||||
- **The share sheet takes files only from other apps.** A share that names something of
|
||||
LLeMbas's own storage is left out, and the sheet says so.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A chat on a model two connections serve shows the right connection.** When an instance has
|
||||
the same model on two connections, a chat, a reply and a scheduled task on the second one were
|
||||
shown as being on the first: the title, the tick in the model list, the picture, the thinking
|
||||
control. The instance now says which connection each is on, and the app shows that one. The
|
||||
line under a reply and a scheduled task's model name the connection where two share a name.
|
||||
An instance that does not say it yet is shown as before. A chat or a scheduled task whose
|
||||
connection is no longer offered shows no model rather than another connection's.
|
||||
|
||||
## [1.0.0-beta.12] — 2026-11-18
|
||||
|
||||
For what is new here the instance must be newer than LLeMbas 2.0.0-beta.14; an older one ignores
|
||||
what the app adds and answers as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Dictation and Read aloud follow the chat's model.** An instance may now give a connection
|
||||
speech models of its own, used for the chats whose model is on that connection. The app says
|
||||
which chat a recording or a reading is for: the chat it is in, or -- before the chat exists --
|
||||
the model chosen for it (in the assistant, the assistant's model). Dictation into another app
|
||||
belongs to no chat and stays on the instance's default. When the chat's own speech model did
|
||||
not answer and the default did, the chat says so once, quietly, naming what answered; the
|
||||
assistant's sheet does not say it, because it may be open over the lock screen. Nothing new
|
||||
is sent while the phone is locked.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A dictation that fails says so.** When the instance refused a recording or could not be
|
||||
reached, the chat's field simply stayed as it was. Now the chat says why.
|
||||
- **A refusal about speech is said in the instance's own words.** A dictation or a reading the
|
||||
instance refused showed "The server answered 502." in the chat and in the assistant; the
|
||||
instance's sentence is shown instead.
|
||||
|
||||
## [1.0.0-beta.11] — 2026-11-18
|
||||
|
||||
Needs LLeMbas 2.0.0-beta.14 for what is new here; with an older instance the app works as before.
|
||||
|
||||
### Added
|
||||
|
||||
- **Choose a folder on your computer instead of typing its path.** A new agent chat's *Folder
|
||||
on the device* opens a picker: the computer's places, then down through its folders and back
|
||||
up -- the back gesture goes up a level and closes at the top. A folder the computer will not
|
||||
open a session in says why and cannot be chosen; a folder you worked in before names the
|
||||
model you last used there. The path can still be typed, and that is what remains when the
|
||||
computer is not linked, does not answer, or runs a LLeMbas CLI too old to list its folders --
|
||||
the picker says which.
|
||||
- **A new agent chat starts on the model you last used in that folder.** Once the computer and
|
||||
the folder are chosen, the model shown is the folder's usual one (the computer remembers it;
|
||||
the app keeps nothing), and it changes when you choose another computer or folder. A model
|
||||
you pick yourself stays picked.
|
||||
- **Scheduled tasks have two types: Chat and Agentic.** The form asks the type first. *Chat*
|
||||
runs on your instance, as tasks always have. *Agentic* runs on one of your computers, in one
|
||||
folder there, as an agent: you choose the computer, the folder (with the picker, or typed),
|
||||
the mode (only those the computer allows), how long an approval waits, a command to watch
|
||||
(the task then runs only when its output changed), and the model -- *The folder's usual
|
||||
model* unless you choose one of your scheduling models. Editing a task says to the instance
|
||||
only what you changed, so a task's words can be put right while its computer is not linked. Agentic can be chosen only while one of your computers
|
||||
accepts scheduled work, and says so otherwise. A task's page shows its type, computer, folder
|
||||
and model; each run says where it ran and when its model was the folder's usual one, your
|
||||
default or the conversation's own.
|
||||
- **Two models with the same name on different connections are told apart.** Where an instance
|
||||
serves one model through two connections, the pickers say *Name · Connection*, and the one
|
||||
you pick is the one used -- in a chat, as the assistant's model, in a scheduled task. A
|
||||
model chosen before this still finds its row.
|
||||
- **`@` in the composer.** Type `@` and a few letters at the end of a message: in a chat the
|
||||
list offers your files, what was attached earlier in the chat and a web address, and a tap
|
||||
attaches it; in an agent chat it offers the files in the chat's folder on the computer, and
|
||||
a tap completes the path for the agent to read.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The badge on Reports is live.** The count of unread reports in the drawer follows the
|
||||
instance while the app is in front -- a report that arrives, or one read on another device,
|
||||
moves it at once. Before, it was read only when the drawer opened.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Two quick taps on *Older* no longer end the app.** The same page of older messages was
|
||||
fetched twice and put above the chat twice. One page is read at a time now, and a message is
|
||||
never added a second time.
|
||||
- **A reply whose stream ends without its last frame no longer disappears.** What had been
|
||||
written vanished until the chat was opened again. The chat is now read again at that point;
|
||||
where it cannot be read, what was written stays as it stood, with its *Stopped* or *Failed*
|
||||
line where the instance had said one.
|
||||
- **Other apps' dictation sends nothing to your instance while the phone is locked.** While
|
||||
LLeMbas is the digital assistant, an app that asks Android's speech recogniser is answered by
|
||||
your instance -- until now also over the lock screen. A locked phone now uses its own
|
||||
on-device recogniser where it has one, and otherwise tells the app that no recogniser is
|
||||
available; a phone that locks while it is listening sends nothing either.
|
||||
- **A thinking block you opened stays open.** It closed by itself when the thinking ended and
|
||||
the words began, and again when the reply finished.
|
||||
- **Edit, Regenerate, Continue and Carry out the plan tell the instance they come from the
|
||||
phone**, as a new message always did, so a reply started that way is also written for an app
|
||||
that draws no pages.
|
||||
- **The chat no longer pulls you away from what you are reading while a reply is written.** The
|
||||
view follows the reply only while you are at the end. Once you scroll up it stays exactly
|
||||
where you are -- a finger on the list ends the following at once -- and scrolling back to the
|
||||
end takes it up again. Before, the next queued turn starting, a transcript read again and a
|
||||
rotation could each throw the view to the end.
|
||||
- **Older messages no longer throw the chat to its end.** Tapping *Older* keeps the message you
|
||||
were at in place, with the older ones above it.
|
||||
- **The keyboard no longer covers the last lines**: opening it at the end of a chat keeps the
|
||||
end in view.
|
||||
- **The assistant's sheet follows the same rule.** It pulled the answer back to its end at every
|
||||
word, also for somebody reading further up.
|
||||
- **A message written on another device no longer throws the chat to its end** while you read
|
||||
further up: only a message sent from this phone does.
|
||||
|
||||
## [1.0.0-beta.10] — 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Assistant model** in Settings › Assistant: the model the assistant's new chats start on --
|
||||
*Instance default* (your account's default, as before) or any model of the instance. A large
|
||||
default model is slow to answer a spoken question; a quick one can be chosen for the assistant
|
||||
alone. It holds for every way in: the sheet, the wake word, Share. Picking a model in the
|
||||
sheet still changes it too.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The wake word and the hands-free parts of the voice assistant are marked Experimental** in
|
||||
Settings: the wake word as a whole, and with the assistant *Start listening when the
|
||||
assistant opens* and *Keep a spoken conversation going*. They are new and have been tried on
|
||||
few phones: the wake word may miss the phrase, start by mistake, or hear you and still not
|
||||
open the assistant; listening may stop too early or too late. Typing a question and the
|
||||
microphone button are the parts to rely on.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The wake word with the screen off: the sheet showed for a moment and was gone.** A phone
|
||||
whose screen is off is locked, and a sheet opened over the lock screen asked Android to unlock
|
||||
first and closed itself when that was turned down -- which is what happens when nobody is
|
||||
there to unlock. Opened to listen (the wake word, a headset's button), the sheet now stays up
|
||||
over the lock screen and listens, and Android is asked to unlock once it has heard you: a face
|
||||
or a fingerprint sends the question. Leave it, and it stays until the screen goes off.
|
||||
- **Nothing goes to your instance while the phone is locked.** Not the question, not the
|
||||
recording, not even "which models are there". With Voice input › LLeMbas the question waits on
|
||||
the phone as a recording -- the sheet says *Question heard*, with no words, and **Unlock to
|
||||
send** -- and is written down and asked once you unlock. With Voice input › Phone the phone's
|
||||
own recogniser writes it down (the recording goes wherever that recogniser sends it, as
|
||||
always) and the words are shown while they wait. No answer is shown or spoken over the lock
|
||||
screen, and an answer over the lock screen is not offered.
|
||||
- **A phone that locks while the assistant is open stops there.** The screen going off stops the
|
||||
microphone and the voice at once; a question still being listened to is dropped; an answer is
|
||||
no longer read aloud on a locked phone, a spoken conversation does not go on, and the
|
||||
conversation that was on the sheet is not readable over the lock screen -- nor a failure's
|
||||
words, which may name the instance. The screen stays on while an answer is read aloud.
|
||||
- **Another app can no longer put a question into the assistant.** The
|
||||
sheet's screen has to be startable by Android (the assist action, a headset's button), so any
|
||||
app can start it. A question handed from the assistant's own sheet no longer travels in the
|
||||
intent, where any app could have written one to be asked on your account (or to wait for your
|
||||
next unlock): it stays in the app's memory and the intent carries a one-time ticket. Opening
|
||||
listening, the last chat and turning the screen on are honoured only on intents the app made
|
||||
itself. Android's own headset actions still open it listening, as they must.
|
||||
- The sheet no longer asks its question a second time, or loses the one that waits, when the
|
||||
phone is turned, folded or switches theme while it is up.
|
||||
- Closing the sheet lets go of the microphone at once, also when it was closed in the middle of
|
||||
listening.
|
||||
- Listening no longer runs to the limit after speech into a headset that gates its noise to
|
||||
exact silence, and no longer gives up as "nothing said" on someone who goes straight on after
|
||||
the wake word in a steady voice. The phone's recogniser is not given up on while it reports
|
||||
speech but shows no words yet.
|
||||
- **A new assistant chat could start on the wrong model.** After *Continue the last chat*, *New
|
||||
chat* kept that chat's model instead of going back to the assistant's own; and a question
|
||||
sent the moment the sheet opened, before the instance had said which models it has, went to
|
||||
the instance's default whatever was chosen.
|
||||
|
||||
- **Listening went on and on in a quiet room.** With the instance's speech-to-text the sheet
|
||||
decided "somebody is speaking" and "it is quiet again" by two fixed loudness levels. A phone
|
||||
whose room noise sat above the quiet level never heard a pause, so it listened until the
|
||||
two-minute limit; and words the speech-to-text invented from silence counted as speech. Now
|
||||
the room's own level is measured from the first moment and followed all the time, and speech
|
||||
and quiet are judged against it: nothing said ends after five seconds, a question ends a
|
||||
second and a half after you stop, a click or a knock is not speech, and the limit is one
|
||||
minute. Silence is no longer sent to be written down while you have said nothing.
|
||||
- The phone's own recogniser (Voice input › Phone) is asked for the same pause, and is watched:
|
||||
one that never answers no longer leaves the sheet listening for good.
|
||||
- An app that uses the system's recogniser while LLeMbas is the assistant no longer waits the
|
||||
full fifteen seconds every time: it ends at the pause after speech, or says that nothing was
|
||||
said.
|
||||
|
||||
## [1.0.0-beta.9] — 2026-11-13
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ digital assistant -- hold the power button and ask.
|
||||
- **Your instance, nobody else's.** Nothing is predefined: the app talks to the address you give
|
||||
it, and to nothing else.
|
||||
|
||||
> **Alpha.** 0.x versions may change how things work between releases.
|
||||
> **Beta.** These are the betas of 1.0.0: how things work may still change from one to the next.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -40,12 +40,19 @@ certificate). The app trusts CAs you installed, as the browser does.
|
||||
digital assistant app. On Samsung phones also set Settings › Advanced features › Side button ›
|
||||
Press and hold › Digital assistant.
|
||||
|
||||
A wake word is there if you want one, off by default: Settings › Assistant › Wake word, a
|
||||
A wake word is there if you want one, off by default: Settings › Wake word, a
|
||||
greeting and a name in English ("Hey Assistant"). Android reserves its low-power, always-on
|
||||
hotword detection for the system's own preinstalled assistant, so LLeMbas listens with an
|
||||
on-device engine in a microphone service, with a notification up the whole time; nothing leaves
|
||||
the phone before the word. Not in the F-Droid build.
|
||||
|
||||
The wake word and the hands-free parts of the voice assistant (listening by itself, the spoken
|
||||
conversation) are **experimental**: new, and tried on few phones. Settings marks them so.
|
||||
|
||||
Over the lock screen the assistant can listen (the wake word, a headset's button), but nothing
|
||||
goes to the instance and no answer is shown or spoken until the phone is unlocked: with the
|
||||
instance's speech-to-text the question waits on the phone as a recording.
|
||||
|
||||
## Build
|
||||
|
||||
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is
|
||||
|
||||
@@ -31,7 +31,7 @@ android {
|
||||
// The one source of the version. versionCode is derived from it, so the two cannot
|
||||
// drift, and a beta sorts below its release: 1.0.0-beta.1 -> 1000001,
|
||||
// 1.0.0-beta.2 -> 1000002, 1.0.0 -> 1000099, 1.2.3 -> 1020399.
|
||||
versionName = "1.0.0-beta.9"
|
||||
versionName = "1.0.0-beta.18"
|
||||
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
|
||||
|
||||
@@ -63,10 +63,14 @@
|
||||
|
||||
<!-- The assistant's sheet as an activity: the tile, the widget, the shortcuts,
|
||||
ACTION_ASSIST, a headset's voice button, and the lock-screen path (it asks to
|
||||
unlock before sending anything). -->
|
||||
unlock before sending anything). Exported for Android's own actions; what only the
|
||||
app's own parts may ask of it is told apart in OwnIntents.kt. It handles
|
||||
configuration changes itself (Compose redraws): turned, folded or switched to the
|
||||
dark theme, it is not made again, and neither is the question it holds. -->
|
||||
<activity
|
||||
android:name=".assist.AssistActivity"
|
||||
android:exported="true"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboard|keyboardHidden|navigation|uiMode|density|fontScale"
|
||||
android:excludeFromRecents="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity=""
|
||||
@@ -207,7 +211,9 @@
|
||||
android:name=".push.ScheduleActionReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<!-- A photo for the composer: the camera app writes into one file in the cache. -->
|
||||
<!-- One file of the private cache at a time, to one other app: the photo the camera app
|
||||
takes for the composer, and the copy of a file that Open with or Share hands over
|
||||
(res/xml/file_paths.xml names the two folders). Not exported. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.files"
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Whether a new request that carries the account's files may start: only while the app is in
|
||||
* front and the phone is unlocked. Work that goes on by itself -- a queue of uploads, the copies
|
||||
* for a share, a player's copy -- asks [pass] before each request. A request already on its way
|
||||
* is not touched, so what the person started finishes; the next one waits here, and goes on by
|
||||
* itself when the app is in front of an unlocked phone again.
|
||||
*
|
||||
* The process has one ([LembasApp.gate]). It hears of the app's activities starting and stopping,
|
||||
* of the assistant's sheet showing and hiding (a session's window, which is no activity), and of
|
||||
* the screen going off and the phone being unlocked; [locked] is asked each time.
|
||||
*/
|
||||
class InstanceGate(private val locked: () -> Boolean) {
|
||||
private val started = AtomicInteger(0)
|
||||
private val sheet = AtomicBoolean(false)
|
||||
private val state = MutableStateFlow(false)
|
||||
|
||||
/** Whether a request may start now, as it was last looked at. */
|
||||
val open: StateFlow<Boolean> = state.asStateFlow()
|
||||
|
||||
fun activityStarted() {
|
||||
started.incrementAndGet()
|
||||
look()
|
||||
}
|
||||
|
||||
fun activityStopped() {
|
||||
started.updateAndGet { (it - 1).coerceAtLeast(0) }
|
||||
look()
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet is up. It is a window of the system's session and no activity, so it
|
||||
* says so itself: the app is in front while it shows, as while an activity is started. Told
|
||||
* once however often the system shows a sheet that is already up. The lock still shuts the
|
||||
* gate: a sheet over the lock screen asks the instance for nothing.
|
||||
*/
|
||||
fun sessionShown() {
|
||||
sheet.set(true)
|
||||
look()
|
||||
}
|
||||
|
||||
fun sessionHidden() {
|
||||
sheet.set(false)
|
||||
look()
|
||||
}
|
||||
|
||||
/** Looks again (the screen went off, the phone was unlocked) and says whether a request may start. */
|
||||
fun look(): Boolean {
|
||||
val now = (started.get() > 0 || sheet.get()) && !locked()
|
||||
state.value = now
|
||||
return now
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns when a request may start. [waiting] hears `true` when that is not now, and `false`
|
||||
* when the wait is over (also when it is given up), so a screen can say what it is waiting
|
||||
* for. While waiting the lock is looked at again every [AGAIN_MS]: an unlock nobody
|
||||
* announced must not leave a queue standing.
|
||||
*/
|
||||
suspend fun pass(waiting: (Boolean) -> Unit = {}) {
|
||||
if (look()) return
|
||||
waiting(true)
|
||||
try {
|
||||
while (!look()) withTimeoutOrNull(AGAIN_MS) { state.first { it } }
|
||||
} finally {
|
||||
waiting(false)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [pass], for a wait that may last as long as the phone lies locked or the app is away: it
|
||||
* sleeps until the gate is told of a change (an activity starting, the unlock) instead of
|
||||
* looking at the lock every second, and only then takes its turn as [pass] does.
|
||||
*/
|
||||
suspend fun passLater() {
|
||||
if (!look()) state.first { it }
|
||||
pass()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val AGAIN_MS = 1_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [work], for as long as a request may start: something nobody asked for (a reply that began by
|
||||
* itself) is followed only while the app is in front of an unlocked phone. When the gate closes
|
||||
* the work is let go -- cancelled, with its connection -- and the answer is null; so it is when
|
||||
* the gate is closed already, and then nothing is started. [stays] says the work is the
|
||||
* person's own after all (they asked for it while it ran): that goes on behind the gate, as a
|
||||
* request under way does. The caller's own cancellation is not taken for a letting go.
|
||||
*/
|
||||
suspend fun <T : Any> InstanceGate.whileOpen(stays: () -> Boolean = { false }, work: suspend () -> T): T? {
|
||||
if (!look() && !stays()) return null
|
||||
return coroutineScope {
|
||||
val doing = async { work() }
|
||||
val watch = launch {
|
||||
open.first { !it && !stays() }
|
||||
doing.cancel()
|
||||
}
|
||||
try {
|
||||
doing.await()
|
||||
} catch (e: CancellationException) {
|
||||
// The caller's own end is the caller's; only the gate's is "let go".
|
||||
currentCoroutineContext().ensureActive()
|
||||
null
|
||||
} finally {
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [send] for each of [items] from the one at [from], each after its [turn] at the gate, and
|
||||
* [done] hears how many are through after each. A failure leaves the count where it was, so
|
||||
* the same call with that count takes the queue up at the one that failed, not at the first.
|
||||
*/
|
||||
suspend fun <T> sendFrom(items: List<T>, from: Int, turn: suspend () -> Unit, done: (Int) -> Unit, send: suspend (T) -> Unit) {
|
||||
for (i in from.coerceAtLeast(0) until items.size) {
|
||||
turn()
|
||||
send(items[i])
|
||||
done(i + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant's sheet as the gate hears of it: every way the session's window can go says so.
|
||||
* Android may show a sheet that is up again, hide it once, or tear the session down without
|
||||
* hiding it at all -- [gone] is for each of those ends, so the sheet can never be left counted
|
||||
* as the app in front when nothing of the app is.
|
||||
*/
|
||||
class SheetAtGate(private val gate: InstanceGate) {
|
||||
fun shown() = gate.sessionShown()
|
||||
|
||||
/** Hidden, destroyed, or its service gone: whichever comes, and however many of them. */
|
||||
fun gone() = gate.sessionHidden()
|
||||
}
|
||||
@@ -2,31 +2,100 @@ package eu.llembas.android
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.api.EventsHub
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.RefusedTokens
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.auth.InstanceStore
|
||||
import eu.llembas.android.wake.AppVisibility
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** The process: one store of instances, and the notification channels, made once. */
|
||||
class LembasApp : Application() {
|
||||
lateinit var instances: InstanceStore
|
||||
private set
|
||||
|
||||
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
/** The one connection to the person's events route, shared by all that watch it. */
|
||||
val events = EventsHub(background)
|
||||
|
||||
/**
|
||||
* The events route of the instance in use, as its frames; null when not signed in. Whoever
|
||||
* collects them does so only while its screen is in front (`repeatOnLifecycle`), never from
|
||||
* a scope that outlives the screen: the connection is open for as long as anybody listens.
|
||||
*/
|
||||
suspend fun eventFrames(): Flow<Frame>? {
|
||||
// An instance that signed this phone out is asked nothing more: its route is not opened.
|
||||
val instance = instances.current()?.takeUnless { it.signedOut } ?: return null
|
||||
val api = instances.clientFor(instance)
|
||||
// Every opening of the route waits at the gate: it is not opened, or opened again, behind a lock.
|
||||
// The line is the token's, not only the instance's: after a sign-in again the route is
|
||||
// opened with the new token, never taken up with the one the instance refused.
|
||||
return events.frames(eventsKey(instance.id, instance.sealedToken)) { StreamClient(api).watch(turn = { gate.pass() }) { api.events() } }
|
||||
}
|
||||
|
||||
/** Whether a new request with the account's files may start: the app in front, the phone unlocked. */
|
||||
val gate = InstanceGate { getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true }
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instances = InstanceStore(this)
|
||||
// A token the instance refuses (a 401 of its own, on any request: a call, a stream, a
|
||||
// download) signs out the instance that token belongs to -- that one only, and nothing
|
||||
// else is forgotten. Its screens then offer the sign-in (MainActivity).
|
||||
RefusedTokens.heard = { token -> background.launch { runCatching { instances.refused(token) } } }
|
||||
// Copies of the account's files left by a process that was killed. A viewer's own are
|
||||
// nobody's now; one another app was handed may still be read there (a mail being
|
||||
// written), so those go by their age only.
|
||||
eu.llembas.android.ui.files.FileCache.atStart(this)
|
||||
// The gate hears the lock from the screen going off and the unlock; the activities below say the rest.
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
gate.look()
|
||||
}
|
||||
},
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_SCREEN_ON)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// Whether the app is on screen: the wake word may open the assistant's sheet as an
|
||||
// activity only then (Android blocks one started from the background, silently).
|
||||
registerActivityLifecycleCallbacks(
|
||||
object : ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) = AppVisibility.activityStarted()
|
||||
override fun onActivityStarted(activity: Activity) {
|
||||
AppVisibility.activityStarted()
|
||||
gate.activityStarted()
|
||||
}
|
||||
|
||||
override fun onActivityStopped(activity: Activity) = AppVisibility.activityStopped()
|
||||
override fun onActivityStopped(activity: Activity) {
|
||||
AppVisibility.activityStopped()
|
||||
gate.activityStopped()
|
||||
}
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
|
||||
|
||||
override fun onActivityResumed(activity: Activity) = Unit
|
||||
override fun onActivityResumed(activity: Activity) {
|
||||
gate.look()
|
||||
}
|
||||
|
||||
override fun onActivityPaused(activity: Activity) = Unit
|
||||
|
||||
@@ -53,6 +122,7 @@ class LembasApp : Application() {
|
||||
manager.deleteNotificationChannel("reports")
|
||||
// The launcher's long-press shortcuts, in the app's language as it is now.
|
||||
eu.llembas.android.widget.Shortcuts.publish(this)
|
||||
eu.llembas.android.widget.AskWidget.refresh(this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -67,3 +137,6 @@ class LembasApp : Application() {
|
||||
}
|
||||
|
||||
val android.content.Context.lembas: LembasApp get() = applicationContext as LembasApp
|
||||
|
||||
/** What names one connection to an instance's events route: the instance and the token it is followed with. */
|
||||
fun eventsKey(instanceId: String, sealedToken: String): String = instanceId + "#" + sealedToken.hashCode()
|
||||
@@ -4,6 +4,7 @@ import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
@@ -17,6 +18,7 @@ import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.rememberDrawerState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
@@ -24,10 +26,15 @@ import androidx.compose.runtime.mutableStateMapOf
|
||||
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.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.lifecycle.repeatOnLifecycle
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
@@ -41,6 +48,7 @@ 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.files.FileCache
|
||||
import eu.llembas.android.ui.files.FilesScreen
|
||||
import eu.llembas.android.ui.home.ArchivedScreen
|
||||
import eu.llembas.android.ui.home.ChatsViewModel
|
||||
@@ -54,8 +62,10 @@ 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.McpScreen
|
||||
import eu.llembas.android.ui.settings.SettingsScreen
|
||||
import eu.llembas.android.ui.signin.SignInScreen
|
||||
import eu.llembas.android.ui.signin.SignedOutScreen
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
import eu.llembas.android.wake.WakeBootReceiver
|
||||
@@ -80,6 +90,9 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
if (savedInstanceState == null && intent?.getStringExtra(Notifications.EXTRA_INSTANCE).isNullOrBlank()) {
|
||||
lifecycleScope.launch { lembas.instances.resetToDefault() }
|
||||
}
|
||||
take(intent)
|
||||
followLanguage()
|
||||
// At most once a day, and only while Settings › About says so (update/ReleaseCheck.kt).
|
||||
@@ -167,7 +180,45 @@ class MainActivity : ComponentActivity() {
|
||||
when {
|
||||
loaded == null -> Box(Modifier.fillMaxSize())
|
||||
instance == null -> SignInScreen()
|
||||
else -> key(instance.id) { Home(instance, open, opened) }
|
||||
else -> key(instance.id) { Signed(instance, open, opened) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance in use: its pages, and over them the way back in when the instance signed
|
||||
* this phone out (it refused the token). The pages stay underneath as they were -- a message
|
||||
* half written is there again after the sign-in -- and ask the instance nothing meanwhile
|
||||
* (no client is handed out for a signed-out instance). An instance that was signed out
|
||||
* before its pages were ever up has none to keep: they are made after the sign-in.
|
||||
*/
|
||||
@Composable
|
||||
private fun Signed(instance: Instance, open: Opening?, opened: () -> Unit) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var up by rememberSaveable { mutableStateOf(false) }
|
||||
if (!instance.signedOut && !up) SideEffect { up = true }
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
if (up || !instance.signedOut) Home(instance, open, opened)
|
||||
if (instance.signedOut) {
|
||||
val all by lembas.instances.instances.collectAsState(initial = emptyList())
|
||||
SignedOutScreen(
|
||||
instance = instance,
|
||||
others = all.filter { it.id != instance.id },
|
||||
onUse = { other ->
|
||||
scope.launch {
|
||||
lembas.instances.use(other.id)
|
||||
FileCache.clear(this@MainActivity)
|
||||
}
|
||||
},
|
||||
onRemove = {
|
||||
scope.launch {
|
||||
Push.disable(this@MainActivity, instance)
|
||||
lembas.instances.remove(instance.id)
|
||||
// The copies of the account's files this phone held go with it.
|
||||
FileCache.clear(this@MainActivity)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,8 +233,12 @@ class MainActivity : ComponentActivity() {
|
||||
val nav = rememberNavController()
|
||||
val drawer = rememberDrawerState(DrawerValue.Closed)
|
||||
val scope = rememberCoroutineScope()
|
||||
val chats: ChatsViewModel = viewModel()
|
||||
// One list per instance: what was read of one instance (its chats, its badge, whether it
|
||||
// was refused as too old) is never shown, or held against, another after a switch.
|
||||
val chats: ChatsViewModel = viewModel(key = "chats:" + instance.id)
|
||||
val list by chats.state.collectAsStateWithLifecycle()
|
||||
val instances by lembas.instances.instances.collectAsState(initial = emptyList())
|
||||
val defaultInstance by lembas.instances.defaultInstance.collectAsState(initial = null)
|
||||
val entry by nav.currentBackStackEntryAsState()
|
||||
val route = entry?.destination?.route
|
||||
val current = entry?.arguments?.getString("id")?.takeIf { route == "chat/{id}" }
|
||||
@@ -201,13 +256,33 @@ class MainActivity : ComponentActivity() {
|
||||
// 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) {
|
||||
val cached = lembas.instances.prefs.first().forInstance(instance.id).accountLanguage
|
||||
if (cached.isNotBlank()) {
|
||||
lembas.instances.savePrefs { it.copy(accountLanguage = cached) }
|
||||
}
|
||||
runCatching { lembas.instances.clientFor(instance).me() }.onSuccess { me ->
|
||||
me.accountLanguage?.let { language -> lembas.instances.savePrefs { it.copy(accountLanguage = language) } }
|
||||
me.accountLanguage?.let { language ->
|
||||
lembas.instances.savePrefs { p ->
|
||||
p.withInstance(instance.id) { it.copy(accountLanguage = language) }.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() }
|
||||
// While it is open the list follows the replies; closed, nothing reads it.
|
||||
val lifecycle = LocalLifecycleOwner.current.lifecycle
|
||||
LaunchedEffect(drawer.isOpen) {
|
||||
chats.shown(drawer.isOpen)
|
||||
if (drawer.isOpen) {
|
||||
chats.load()
|
||||
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchRunning() }
|
||||
}
|
||||
}
|
||||
// The chat on screen: the end of its reply is not something new in the list.
|
||||
LaunchedEffect(current) { chats.open = current }
|
||||
// The badge on Reports follows the instance while the app is in front.
|
||||
LaunchedEffect(instance.id) { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { chats.watchReports() } }
|
||||
LaunchedEffect(open) {
|
||||
open?.let {
|
||||
// Meant for another instance: left for that one's pages, once it is in use.
|
||||
@@ -259,6 +334,16 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun settings() = over("settings")
|
||||
|
||||
override fun useInstance(instance: Instance) {
|
||||
scope.launch {
|
||||
drawer.close()
|
||||
lembas.instances.use(instance.id)
|
||||
FileCache.clear(this@MainActivity)
|
||||
}
|
||||
}
|
||||
|
||||
override fun addInstance() = over("add")
|
||||
|
||||
override fun more() = chats.more()
|
||||
|
||||
override fun retry() = chats.load()
|
||||
@@ -269,12 +354,21 @@ class MainActivity : ComponentActivity() {
|
||||
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
|
||||
val reportTitles = remember { mutableStateMapOf<String, String>() }
|
||||
val menu: () -> Unit = { scope.launch { drawer.open() } }
|
||||
val filesAt: (String) -> Unit = { folder -> over("files-at/" + Uri.encode(folder)) }
|
||||
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)
|
||||
DrawerContent(
|
||||
list,
|
||||
current,
|
||||
listOf(instance.name, instance.email).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
actions,
|
||||
instances = instances,
|
||||
activeInstance = instance,
|
||||
defaultInstanceId = defaultInstance?.id,
|
||||
)
|
||||
},
|
||||
) {
|
||||
NavHost(nav, startDestination = "new") {
|
||||
@@ -286,6 +380,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onOpened = { id -> top("chat/$id") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("new-agent") {
|
||||
@@ -305,9 +400,13 @@ class MainActivity : ComponentActivity() {
|
||||
onMenu = menu,
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { top("new") },
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("files") { FilesScreen(onBack = { nav.popBackStack() }) }
|
||||
// Files at a folder: where a generated file's "Open in Files" leads.
|
||||
composable("files-at/{at}") { e -> FilesScreen(onBack = { nav.popBackStack() }, start = e.arguments?.getString("at")) }
|
||||
composable("mcp") { McpScreen(onBack = { nav.popBackStack() }) }
|
||||
composable("archived") {
|
||||
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
|
||||
}
|
||||
@@ -334,6 +433,7 @@ class MainActivity : ComponentActivity() {
|
||||
onNewChat = { top("new") },
|
||||
onLeave = { nav.popBackStack() },
|
||||
report = reportTitles[id].orEmpty(),
|
||||
onFiles = filesAt,
|
||||
)
|
||||
}
|
||||
composable("scheduled") {
|
||||
@@ -375,11 +475,11 @@ class MainActivity : ComponentActivity() {
|
||||
ScheduleEditScreen(e.arguments?.getString("id"), onBack = { nav.popBackStack() }, onSaved = { nav.popBackStack() })
|
||||
}
|
||||
composable("settings") {
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") })
|
||||
SettingsScreen(onBack = { nav.popBackStack() }, onAddInstance = { over("add") }, onMcp = { over("mcp") })
|
||||
}
|
||||
// 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() }) }
|
||||
composable("add") { SignInScreen(onDone = { nav.popBackStack() }, onCancel = { nav.popBackStack() }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
|
||||
/**
|
||||
* What a typed address is, by the one rule every LLeMbas client reads an address with: trimmed;
|
||||
* `https://` when no scheme was typed (a scheme is read whatever its case); http and https only;
|
||||
* the scheme, the host in lower case and a port that is not the scheme's own are kept; a path, a
|
||||
* query, a fragment and a trailing slash are dropped.
|
||||
*
|
||||
* This app talks https only (Android's network policy of the app forbids cleartext), so an
|
||||
* `http://` address is its own answer: said in words where the address is typed, not as a
|
||||
* library's error three steps later.
|
||||
*/
|
||||
sealed interface Address {
|
||||
/** An instance's base URL: `https://host` or `https://host:port`, nothing after it. */
|
||||
data class Base(val url: String) : Address
|
||||
|
||||
/** Nothing was typed. */
|
||||
data object Empty : Address
|
||||
|
||||
/** `http://…`: an address the rule accepts and this app cannot use. */
|
||||
data object NeedsHttps : Address
|
||||
|
||||
/** Another scheme (`ftp://…`): no LLeMbas client reads it. */
|
||||
data object NotHttp : Address
|
||||
|
||||
/** Not an address at all (no host, a port that is no number). */
|
||||
data object Unreadable : Address
|
||||
}
|
||||
|
||||
private val SCHEME = Regex("^([A-Za-z][A-Za-z0-9+.-]*)://")
|
||||
|
||||
/** [typed] as an [Address]. Pure: nothing is looked up, nothing is asked. */
|
||||
fun address(typed: String): Address {
|
||||
val text = typed.trim()
|
||||
if (text.isEmpty()) return Address.Empty
|
||||
val scheme = SCHEME.find(text)?.groupValues?.get(1)?.lowercase()
|
||||
val rest = if (scheme == null) text else text.substring(text.indexOf("://") + 3)
|
||||
return when (scheme) {
|
||||
null, "https" -> {
|
||||
val url = "https://$rest".toHttpUrlOrNull() ?: return Address.Unreadable
|
||||
val base = url.newBuilder().username("").password("").encodedPath("/").query(null).fragment(null).build()
|
||||
Address.Base(base.toString().trimEnd('/'))
|
||||
}
|
||||
|
||||
"http" -> Address.NeedsHttps
|
||||
|
||||
else -> Address.NotHttp
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two stored or said bases name one instance: compared as [address] reads them, so that
|
||||
* a capital, a trailing slash or the scheme's own port makes no difference. One that the rule
|
||||
* does not read (an `http://` base a server once said of itself) is compared as it stands.
|
||||
*/
|
||||
fun sameBase(one: String, other: String): Boolean = canonical(one) == canonical(other)
|
||||
|
||||
private fun canonical(base: String): String = (address(base) as? Address.Base)?.url ?: base.trim().trimEnd('/').lowercase()
|
||||
|
||||
/**
|
||||
* Whether [url] is on the origin of [base]: the same scheme, host and port. An endpoint a
|
||||
* discovery document names is used only then -- the token and the sign-in go to the address the
|
||||
* person typed and to no other host, whatever the document says.
|
||||
*/
|
||||
fun onOrigin(base: String, url: String): Boolean {
|
||||
val home = base.toHttpUrlOrNull() ?: return false
|
||||
val there = url.toHttpUrlOrNull() ?: return false
|
||||
return home.scheme == there.scheme && home.host == there.host && home.port == there.port
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import kotlinx.serialization.json.put
|
||||
import kotlinx.serialization.serializer
|
||||
import okhttp3.Call
|
||||
@@ -22,14 +26,21 @@ import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
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)
|
||||
/**
|
||||
* A refusal from the server, in its own words (`{"detail": "…"}`). [retryAfter] is the seconds a
|
||||
* 429 asked the caller to wait (`Retry-After`), where it said so.
|
||||
*/
|
||||
class ApiException(val status: Int, message: String, val retryAfter: Long? = null) : IOException(message)
|
||||
|
||||
/** An address that answered, and is no LLeMbas instance: no discovery document, or another service's. */
|
||||
class NotLembas : IOException("Not a LLeMbas instance.")
|
||||
|
||||
private val JSON = "application/json; charset=utf-8".toMediaType()
|
||||
|
||||
@@ -39,6 +50,8 @@ val SharedHttp: OkHttpClient by lazy {
|
||||
.connectTimeout(15, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.writeTimeout(120, TimeUnit.SECONDS)
|
||||
// Every request says which app asks, and a token the instance refuses is heard once, here.
|
||||
.addInterceptor(Identity())
|
||||
.build()
|
||||
}
|
||||
|
||||
@@ -55,27 +68,26 @@ suspend fun Call.await(): Response = suspendCancellableCoroutine { cont ->
|
||||
cont.invokeOnCancellation { runCatching { cancel() } }
|
||||
}
|
||||
|
||||
/** The address a person typed, as the instance's base URL: https assumed, no trailing slash. */
|
||||
fun normaliseBase(typed: String): String {
|
||||
var text = typed.trim().trimEnd('/')
|
||||
if (!text.startsWith("http://") && !text.startsWith("https://")) text = "https://$text"
|
||||
return text.toHttpUrl().toString().trimEnd('/')
|
||||
}
|
||||
|
||||
/** The calls that need no token: finding the instance and signing in. */
|
||||
class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
||||
suspend fun discover(base: String): Discovery {
|
||||
val response = http.newCall(Request.Builder().url("$base/.well-known/lembas.json").build()).await()
|
||||
return response.use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, "Not a LLeMbas instance (${it.code}).")
|
||||
LembasJson.decodeFromString(Discovery.serializer(), it.body!!.string())
|
||||
// No such document: something else lives at the address. Any other refusal -- a proxy
|
||||
// whose server is down (502), a server that is starting -- is the server's answer,
|
||||
// said with its number: it may well be a LLeMbas instance.
|
||||
if (it.code == 404) throw NotLembas()
|
||||
if (!it.isSuccessful) throw ApiException(it.code, "")
|
||||
val text = it.body?.string().orEmpty()
|
||||
// A page, or another program's JSON, is not the document either.
|
||||
runCatching { LembasJson.decodeFromString(Discovery.serializer(), text) }.getOrNull() ?: throw NotLembas()
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deviceCode(url: String, deviceName: String, model: String): DeviceCode {
|
||||
val body = buildJsonObject {
|
||||
put("scope", "app models")
|
||||
put("client_id", "lembas-android")
|
||||
put("client_id", USER_AGENT)
|
||||
put("device_name", deviceName)
|
||||
put("device_host", model)
|
||||
put("device_platform", "android")
|
||||
@@ -87,14 +99,23 @@ class Doorstep(private val http: OkHttpClient = SharedHttp) {
|
||||
}
|
||||
}
|
||||
|
||||
/** One poll. A pending login is a 400 with `authorization_pending` -- not a failure. */
|
||||
/**
|
||||
* One poll. A pending login is a 400 with `authorization_pending` -- not a failure. An answer
|
||||
* that is no such document (a proxy's 502 page, a 429) is the server's refusal with its
|
||||
* number, never "the code expired".
|
||||
*/
|
||||
suspend fun deviceToken(url: String, deviceCode: String): DeviceToken {
|
||||
val body = buildJsonObject {
|
||||
put("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
|
||||
put("device_code", deviceCode)
|
||||
}
|
||||
val response = http.newCall(post(url, body)).await()
|
||||
return response.use { LembasJson.decodeFromString(DeviceToken.serializer(), it.body!!.string()) }
|
||||
return response.use {
|
||||
val text = it.body?.string().orEmpty()
|
||||
val said = runCatching { LembasJson.decodeFromString(DeviceToken.serializer(), text) }.getOrNull()
|
||||
if (said != null && (said.accessToken != null || said.error != null)) return@use said
|
||||
throw ApiException(it.code, refusal(text).orEmpty(), retryAfterSeconds(it.header("Retry-After")))
|
||||
}
|
||||
}
|
||||
|
||||
private fun post(url: String, body: JsonObject) = Request.Builder().url(url).post(body.toString().toRequestBody(JSON)).build()
|
||||
@@ -107,12 +128,20 @@ private fun agentsJson(agents: AgentsSetting) = buildJsonObject {
|
||||
|
||||
internal fun detail(response: Response): String {
|
||||
val text = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
val said = runCatching {
|
||||
LembasJson.parseToJsonElement(text).let { it as JsonObject }["detail"]?.jsonPrimitive?.content
|
||||
}.getOrNull()
|
||||
return said ?: "The server answered ${response.code}."
|
||||
return refusal(text) ?: "The server answered ${response.code}."
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's own sentence in a refusal's body: `detail` on `/api/v2`, OpenAI's shape
|
||||
* (`error.message`) on `/v1`, where speech lives, and the sign-in's (`error_description`, RFC
|
||||
* 8628). Null when the body says none of them.
|
||||
*/
|
||||
internal fun refusal(body: String): String? = runCatching {
|
||||
val said = LembasJson.parseToJsonElement(body) as JsonObject
|
||||
fun words(of: Any?): String? = (of as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content?.ifBlank { null }
|
||||
words(said["detail"]) ?: words((said["error"] as? JsonObject)?.get("message")) ?: words(said["error_description"])
|
||||
}.getOrNull()
|
||||
|
||||
/**
|
||||
* Everything the app asks one instance, with its token. Every call is the server's
|
||||
* `/api/v2` (or `/v1` for speech), and every refusal comes back as an [ApiException]
|
||||
@@ -146,12 +175,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
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 with the instance's subagent cap; with [chatId], whether each is offered subagents
|
||||
* on that chat. Only models a chat can be on (`capability` `chat`): this list is what every
|
||||
* picker and the assistant's model setting are filled from.
|
||||
*/
|
||||
suspend fun modelList(chatId: String? = null): ModelList = get<ModelList>(if (chatId != null) "/models?chat=$chatId" else "/models").forChat()
|
||||
|
||||
/** 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 agentModelList(deviceId: String?, directory: String? = null): ModelList = get<ModelList>(
|
||||
"/models?kind=agent" + deviceId?.let { "&device=" + segment(it) }.orEmpty() +
|
||||
// With a directory (spec 3.9.0) the answer carries `start`: the model a chat there starts on.
|
||||
directory?.takeIf { deviceId != null && it.isNotBlank() }?.let { "&directory=" + segment(it.trim()) }.orEmpty(),
|
||||
).forChat()
|
||||
|
||||
suspend fun folders(): List<Folder> = get<FolderList>("/folders").folders
|
||||
|
||||
@@ -174,6 +210,16 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
/** The app releases this server recommends; 404 from a server older than the route. */
|
||||
suspend fun apps(): AppsInfo = get("/apps")
|
||||
|
||||
/**
|
||||
* What `@` offers in an agent chat: the device's files matching [q], from the chat's
|
||||
* directory ([chatId]) or, before the chat exists, from the folder chosen for it ([cwd]).
|
||||
*/
|
||||
suspend fun deviceFiles(deviceId: String, q: String, chatId: String? = null, cwd: String? = null): DeviceFiles = get(
|
||||
"/devices/${segment(deviceId)}/files?q=${segment(q)}" +
|
||||
chatId?.let { "&chat=${segment(it)}" }.orEmpty() +
|
||||
cwd?.takeIf { chatId == null && it.isNotBlank() }?.let { "&cwd=${segment(it.trim())}" }.orEmpty(),
|
||||
)
|
||||
|
||||
/** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */
|
||||
suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: ""))
|
||||
|
||||
@@ -219,6 +265,14 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
suspend fun devices(): List<LinkedDevice> = get<DeviceList>("/devices").devices
|
||||
|
||||
/**
|
||||
* A directory on a linked device, for choosing where an agent chat or an Agentic schedule
|
||||
* works; without a [path], the device's places. No listing is still an answer: its `code`
|
||||
* and `error` say why.
|
||||
*/
|
||||
suspend fun deviceDirectories(deviceId: String, path: String? = null): DeviceDirectory =
|
||||
get("/devices/${segment(deviceId)}/directories" + path?.takeIf { it.isNotEmpty() }?.let { "?path=" + segment(it) }.orEmpty())
|
||||
|
||||
/** The token revokes itself (`lembas logout`'s route). */
|
||||
suspend fun signOut() = empty(authed("$base/api/v1/token").delete().build())
|
||||
|
||||
@@ -294,14 +348,33 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
suspend fun stop(chatId: String, messageId: String) =
|
||||
empty(authed("$v2/chats/$chatId/messages/$messageId/stop").post(ByteArray(0).toRequestBody(null)).build())
|
||||
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn =
|
||||
send("POST", "/chats/$chatId/messages/$messageId/edit", buildJsonObject { put("text", text) })
|
||||
// Every request that can start a reply says what this app can do, as a message does: the
|
||||
// server then knows who the reply is written for however it was asked for.
|
||||
suspend fun edit(chatId: String, messageId: String, text: String): Turn = send(
|
||||
"POST",
|
||||
"/chats/$chatId/messages/$messageId/edit",
|
||||
buildJsonObject {
|
||||
put("text", text)
|
||||
put("client", CAPABILITIES)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", null)
|
||||
/**
|
||||
* Send a message that waits (`queued`) now: the message as it is after, and the reply started
|
||||
* for it, as a message sent answers. 409 in the instance's words while a reply is being
|
||||
* written in the chat, and when the message no longer waits.
|
||||
*/
|
||||
suspend fun sendWaiting(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/${segment(messageId)}/send", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", null)
|
||||
/** Withdraw a message that waits: its row is gone. 409 in words when it no longer waits, 404 when it is not there. */
|
||||
suspend fun discardWaiting(chatId: String, messageId: String): Discarded =
|
||||
call(authed("$v2/chats/$chatId/messages/${segment(messageId)}/discard").post(emptyBody()).build(), Discarded.serializer())
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", null)
|
||||
suspend fun regenerate(chatId: String, messageId: String): Turn = send("POST", "/chats/$chatId/messages/$messageId/regenerate", DECLARED)
|
||||
|
||||
suspend fun continueChat(chatId: String): Turn = send("POST", "/chats/$chatId/continue", DECLARED)
|
||||
|
||||
suspend fun executePlan(chatId: String): Turn = send("POST", "/chats/$chatId/plan/execute", DECLARED)
|
||||
|
||||
suspend fun answer(chatId: String, cardId: String, answer: CardAnswer) {
|
||||
val body = LembasJson.encodeToString(CardAnswer.serializer(), answer).toRequestBody(JSON)
|
||||
@@ -338,8 +411,6 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
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. */
|
||||
@@ -364,15 +435,58 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
},
|
||||
)
|
||||
|
||||
/** A rule read back: cleaned, in words, and its next runs. An empty rule cannot run. */
|
||||
suspend fun previewRule(rule: JsonObject): RulePreview = send("POST", "/schedules/preview", buildJsonObject { put("rule", rule) })
|
||||
|
||||
/**
|
||||
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
|
||||
* edited. The words go along as the schedule's `request`, so editing starts from them.
|
||||
*/
|
||||
suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null, notify: String? = null, notifyWhen: String = ""): Schedule {
|
||||
suspend fun saveSchedule(
|
||||
compiled: ScheduleCompiled,
|
||||
words: String,
|
||||
id: String? = null,
|
||||
notify: String? = null,
|
||||
notifyWhen: String = "",
|
||||
where: WhereToRun = WhereToRun.Leave,
|
||||
model: String? = null,
|
||||
watch: WatchCommand? = null,
|
||||
): Schedule {
|
||||
val body = buildJsonObject {
|
||||
// The type (spec 3.9.0): Agentic is a schedule with a computer, Chat one without. Left
|
||||
// out where the form did not say, so a schedule is never moved by a form that did not read it.
|
||||
when (where) {
|
||||
WhereToRun.Leave -> Unit
|
||||
|
||||
WhereToRun.Server -> put("runs_on", JsonNull)
|
||||
|
||||
is WhereToRun.Computer -> {
|
||||
put(
|
||||
"runs_on",
|
||||
buildJsonObject {
|
||||
put("device", where.device)
|
||||
put("cwd", where.cwd)
|
||||
put("mode", where.mode)
|
||||
where.approvalWaitMinutes?.let { put("approval_wait_minutes", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
// The model, where the form says one: empty is the folder's usual model for an
|
||||
// Agentic schedule, asked of the computer as each run starts.
|
||||
model?.let { put("model", it) }
|
||||
// The watched command, where the form says one: none at all is "watch nothing".
|
||||
watch?.let { said ->
|
||||
if (said.command.isBlank()) {
|
||||
put("watch", JsonNull)
|
||||
} else {
|
||||
put(
|
||||
"watch",
|
||||
buildJsonObject {
|
||||
put("kind", "command")
|
||||
put("command", said.command)
|
||||
said.timeoutS?.let { put("timeout_s", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
put("title", compiled.title)
|
||||
put("instruction", compiled.instruction)
|
||||
put("rule", compiled.rule)
|
||||
@@ -518,6 +632,230 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
return call(authed(url.toString()).get().build(), FileContent.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the file with node id [id] is now, after any rename or move: `GET /api/v2/files/node`.
|
||||
* A file the person may not read and an id that names nothing are the same 404; an instance
|
||||
* from before this route answers a 404 or a 405 of its own ([eu.llembas.android.ui.files.noSuchRoute]).
|
||||
*/
|
||||
suspend fun fileNode(id: String): FileNode = call(authed(filesUrl("/node", "id" to id)).get().build(), FileNode.serializer())
|
||||
|
||||
// --- The file manager's writes, the trash, versions and bytes ---------------------------------
|
||||
// Each write answers the listing of the directory it changed; a refusal is the tree's own
|
||||
// sentence (400), a path that cannot be read a 404, and both come back as an ApiException.
|
||||
|
||||
private fun filesUrl(path: String, vararg query: Pair<String, String?>): String = "$v2/files$path".toHttpUrl().newBuilder()
|
||||
.apply { query.forEach { (name, value) -> if (value != null) addQueryParameter(name, value) } }
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
suspend fun makeFolder(dir: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/mkdir",
|
||||
buildJsonObject {
|
||||
put("path", dir)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
suspend fun renameFile(path: String, name: String): FileListing = send(
|
||||
"POST",
|
||||
"/files/rename",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("name", name)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Move or copy [paths] into the directory [to], or delete them (to the trash): `op` is
|
||||
* `move`, `copy` or `delete`. Each path is done by itself, so the answer is read for what
|
||||
* failed even though the request succeeded.
|
||||
*/
|
||||
suspend fun batchFiles(op: String, paths: List<String>, to: String? = null): BatchAnswer = send(
|
||||
"POST",
|
||||
"/files/batch",
|
||||
buildJsonObject {
|
||||
put("op", op)
|
||||
put("paths", JsonArray(paths.map { JsonPrimitive(it) }))
|
||||
to?.let { put("to", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Save a text file. [base] is the `sha` the file had when it was opened: when it holds
|
||||
* something else by now the server writes nothing and this throws [SaveConflict] with its
|
||||
* sentence, unless [force]. Without a [base] nothing is compared, and a path with no file
|
||||
* makes one. With [create] the file must be new: where something is already at the path the
|
||||
* server writes nothing (409, `exists`) and this throws [FileExists] with its sentence -- an
|
||||
* older server knows no `create` and writes as before.
|
||||
*/
|
||||
suspend fun saveFile(path: String, text: String, base: String? = null, force: Boolean = false, create: Boolean = false): FileContent {
|
||||
val body = buildJsonObject {
|
||||
put("path", path)
|
||||
put("text", text)
|
||||
base?.takeIf { it.isNotBlank() }?.let { put("base", it) }
|
||||
if (force) put("force", true)
|
||||
if (create) put("create", true)
|
||||
}
|
||||
val request = authed("$v2/files/content").put(body.toString().toRequestBody(JSON)).build()
|
||||
return withContext(Dispatchers.IO) { http.newCall(request).await().use { response -> saved(response) } }
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file called [name] in the directory [dir]; its path. Never over what
|
||||
* is there: `create` has the instance refuse a taken name ([FileExists], its sentence), and
|
||||
* because an instance from before `create` ignores the word and would empty the file, the
|
||||
* directory is read first and a name it holds is refused here, with nothing sent.
|
||||
*/
|
||||
suspend fun newFile(dir: String, name: String): String {
|
||||
val path = FileKinds.child(dir, name)
|
||||
if (files(dir).entries.any { it.name == name.trim() || it.path == path }) throw FileExists("")
|
||||
saveFile(path, "", create = true)
|
||||
return path
|
||||
}
|
||||
|
||||
/** A save's answer: the file as it is now, or what refused it. */
|
||||
private fun saved(response: Response): FileContent {
|
||||
val said = runCatching { response.body?.string().orEmpty() }.getOrDefault("")
|
||||
if (response.code == 409) {
|
||||
val conflict = runCatching { LembasJson.parseToJsonElement(said) as? JsonObject }.getOrNull() ?: JsonObject(emptyMap())
|
||||
if ((conflict["conflict"] as? JsonPrimitive)?.content == "true") {
|
||||
throw SaveConflict(refusal(said).orEmpty(), (conflict["sha"] as? JsonPrimitive)?.takeUnless { it is JsonNull }?.content.orEmpty())
|
||||
}
|
||||
// A new file whose name is taken: nothing was written, and the sentence says what is there.
|
||||
if ((conflict["exists"] as? JsonPrimitive)?.content == "true") throw FileExists(refusal(said).orEmpty())
|
||||
}
|
||||
if (!response.isSuccessful) throw ApiException(response.code, refusal(said) ?: "The server answered ${response.code}.")
|
||||
return LembasJson.decodeFromString(FileContent.serializer(), said)
|
||||
}
|
||||
|
||||
suspend fun trash(): TrashList = get("/files/trash")
|
||||
|
||||
suspend fun restoreTrashed(id: String): TrashList = send("POST", "/files/restore", buildJsonObject { put("id", id) })
|
||||
|
||||
/** Remove for good: the one thing named, or with no [id] everything in the trash. */
|
||||
suspend fun removeTrashed(id: String? = null): TrashList = call(authed(filesUrl("/trash", "id" to id)).delete().build(), TrashList.serializer())
|
||||
|
||||
suspend fun fileVersions(path: String): FileVersions = call(authed(filesUrl("/versions", "path" to path)).get().build(), FileVersions.serializer())
|
||||
|
||||
/** Make an older version the file again, as a new version: nothing is lost. */
|
||||
suspend fun restoreVersion(path: String, version: String): FileVersions = send(
|
||||
"POST",
|
||||
"/files/versions/restore",
|
||||
buildJsonObject {
|
||||
put("path", path)
|
||||
put("version", version)
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Upload one file into the directory [dir], streamed: [body] writes the file's bytes as they
|
||||
* are read, so a large file is never held in memory. A file over the instance's limit is a
|
||||
* 413 whose sentence names it.
|
||||
*/
|
||||
suspend fun uploadFile(dir: String, name: String, body: RequestBody): FileListing {
|
||||
val form = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", name, body).build()
|
||||
return call(authed(filesUrl("/upload", "path" to dir)).post(form).build(), FileListing.serializer())
|
||||
}
|
||||
|
||||
/**
|
||||
* The request for a file's bytes (`/files/raw`), or for [range] of them. The token goes in
|
||||
* the Authorization header, as on every call: the address names the path and nothing else.
|
||||
*/
|
||||
fun rawFile(path: String, range: LongRange? = null, inline: Boolean = false): Request = raw(Raw.Path(path), range, inline)
|
||||
|
||||
/**
|
||||
* The request for [what]'s bytes, or for [range] of them: a file of the tree by its path (one
|
||||
* [Raw.Path.version] of it, where named), a file by its node id wherever it is now, or a chat's
|
||||
* attachment. Always with the token in the header and never in the address.
|
||||
*/
|
||||
fun raw(what: Raw, range: LongRange? = null, inline: Boolean = false): Request = authed(
|
||||
when (what) {
|
||||
is Raw.Path -> filesUrl("/raw", "path" to what.path, "version" to what.version?.ifBlank { null }, "inline" to if (inline) "1" else null)
|
||||
is Raw.Node -> filesUrl("/raw", "node" to what.id, "inline" to if (inline) "1" else null)
|
||||
is Raw.Attached -> "$v2/attachments/${segment(what.id)}"
|
||||
},
|
||||
)
|
||||
.header("Accept", "*/*")
|
||||
.apply { range?.let { header("Range", "bytes=${it.first}-${it.last}") } }
|
||||
.get()
|
||||
.build()
|
||||
|
||||
/** The request for [paths] (files and folders) as one zip. */
|
||||
fun zipFiles(paths: List<String>): Request = authed("$v2/files/zip")
|
||||
.header("Accept", "*/*")
|
||||
.post(buildJsonObject { put("paths", JsonArray(paths.map { JsonPrimitive(it) })) }.toString().toRequestBody(JSON))
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Run [request] and copy what it answers into [out] as it comes, saying how far it is
|
||||
* ([progress]: bytes so far, and the total when the server said one, else -1). At most
|
||||
* [most] bytes are taken: more than that is refused as a 413, with nothing more read.
|
||||
*/
|
||||
suspend fun download(request: Request, out: OutputStream, most: Long = Long.MAX_VALUE, progress: (done: Long, total: Long) -> Unit = { _, _ -> }): Long =
|
||||
withContext(Dispatchers.IO) {
|
||||
val call = http.newCall(request)
|
||||
val finished = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
// A read that waits for the server does not hear that the transfer was given up:
|
||||
// the call is cancelled from beside it, which ends the read at once.
|
||||
val watch = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
if (!finished.get()) call.cancel()
|
||||
}
|
||||
}
|
||||
try {
|
||||
call.await().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
val body = response.body ?: throw ApiException(response.code, "")
|
||||
val total = body.contentLength()
|
||||
if (total > most) throw ApiException(413, "")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var done = 0L
|
||||
body.byteStream().use { stream ->
|
||||
while (true) {
|
||||
ensureActive()
|
||||
val n = stream.read(buffer)
|
||||
if (n < 0) break
|
||||
done += n
|
||||
if (done > most) throw ApiException(413, "")
|
||||
out.write(buffer, 0, n)
|
||||
progress(done, total)
|
||||
}
|
||||
}
|
||||
out.flush()
|
||||
done
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
// The read a cancelled call ends with is the cancelling, not a failure of the network.
|
||||
ensureActive()
|
||||
throw e
|
||||
} finally {
|
||||
// Ended by itself: the watcher is let go, and leaves the finished call alone.
|
||||
finished.set(true)
|
||||
watch.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes `[from, to]` of a file, for a player or a table's first rows: a `Range` request,
|
||||
* blocking, on whatever thread asks (never the main one). A server that answers the whole
|
||||
* file to a range that does not start at 0 is refused rather than read from the wrong place.
|
||||
*/
|
||||
fun rawBytes(path: String, from: Long, to: Long): ByteArray = rawBytes(Raw.Path(path), from, to)
|
||||
|
||||
/** The same for any [Raw]: a file by its node id is read a piece at a time as one by its path is. */
|
||||
fun rawBytes(what: Raw, from: Long, to: Long): ByteArray = http.newCall(raw(what, from..to)).execute().use { response ->
|
||||
if (!response.isSuccessful) throw ApiException(response.code, detail(response))
|
||||
if (response.code != 206 && from > 0) throw ApiException(416, "")
|
||||
val want = to - from + 1
|
||||
response.body!!.source().use { source ->
|
||||
source.request(want)
|
||||
source.buffer.readByteArray(minOf(source.buffer.size, want))
|
||||
}
|
||||
}
|
||||
|
||||
/** 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()
|
||||
|
||||
@@ -528,6 +866,21 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
.build()
|
||||
.toString()
|
||||
|
||||
// --- Generated media's jobs, and the MCP servers ----------------------------------------------
|
||||
|
||||
/** A chat's long generations, newest first (at most 50); with [active] only those under way. */
|
||||
suspend fun mediaJobs(chatId: String, active: Boolean = false): List<MediaJob> =
|
||||
get<MediaJobList>("/media/jobs?chat_id=${segment(chatId)}" + if (active) "&active=true" else "").jobs
|
||||
|
||||
/** One job as it stands; somebody else's, or one that is gone, is a 404 in the server's words. */
|
||||
suspend fun mediaJob(id: String): MediaJob = get("/media/jobs/${segment(id)}")
|
||||
|
||||
/** Stop a job: the job as it is after. One that has ended stays what it was, so this is safe to repeat. */
|
||||
suspend fun cancelMediaJob(id: String): MediaJob = call(authed("$v2/media/jobs/${segment(id)}").delete().build(), MediaJob.serializer())
|
||||
|
||||
/** The MCP servers whose tools this person's chats may be offered, and how each is signed in to. */
|
||||
suspend fun mcpServers(): List<McpServer> = get<McpServerList>("/mcp").servers
|
||||
|
||||
// --- Push --------------------------------------------------------------------------------
|
||||
suspend fun pushKey(): PushKey = get("/push")
|
||||
|
||||
@@ -543,22 +896,28 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
suspend fun forgetPush() = empty(authed("$v2/push").delete().build())
|
||||
|
||||
// --- Voice (/v1, the `models` scope) -----------------------------------------------------
|
||||
suspend fun transcribe(wav: ByteArray, language: String? = null): String {
|
||||
|
||||
/**
|
||||
* Write a recording down. [media] says which chat it is for, so that the chat's model's
|
||||
* connection may serve it with its own speech model (server 2.0.0-beta.15); a server before
|
||||
* that reads only the fields it knows and answers from its one endpoint.
|
||||
*/
|
||||
suspend fun transcribe(wav: ByteArray, language: String? = null, media: MediaFor = MediaFor.DEFAULT): Heard = withContext(Dispatchers.IO) {
|
||||
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
|
||||
.addFormDataPart("file", "speech.wav", wav.toRequestBody("audio/wav".toMediaType()))
|
||||
.apply { language?.let { addFormDataPart("language", it) } }
|
||||
.apply { transcriptionFields(language, media).forEach { (name, value) -> addFormDataPart(name, value) } }
|
||||
.build()
|
||||
return call(authed("$base/v1/audio/transcriptions").post(body).build(), Transcript.serializer()).text
|
||||
http.newCall(authed("$base/v1/audio/transcriptions").post(body).build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
Heard(LembasJson.decodeFromString(Transcript.serializer(), it.body!!.string()).text, fallbackSource(it))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun speech(text: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
val body = buildJsonObject {
|
||||
put("input", text.take(20_000))
|
||||
put("response_format", "mp3")
|
||||
}
|
||||
http.newCall(authed("$base/v1/audio/speech").post(body.toString().toRequestBody(JSON)).build()).await().use {
|
||||
/** [text] as speech, for the chat [media] names (see [transcribe]). */
|
||||
suspend fun speech(text: String, media: MediaFor = MediaFor.DEFAULT): Spoken = withContext(Dispatchers.IO) {
|
||||
http.newCall(authed("$base/v1/audio/speech").post(speechBody(text, media).toString().toRequestBody(JSON)).build()).await().use {
|
||||
if (!it.isSuccessful) throw ApiException(it.code, detail(it))
|
||||
it.body!!.bytes()
|
||||
Spoken(it.body!!.bytes(), fallbackSource(it))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,14 +926,45 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* What this app can do, sent with every message (spec 3.6.0): the phone carries out
|
||||
* `phone_action` calls the person confirms here, so the chat is offered the tool.
|
||||
* What this app can do, sent with every request that can start a reply (spec 3.6.0):
|
||||
* the phone carries out `phone_action` calls the person confirms here, so the chat is
|
||||
* offered the tool -- and a reply for the phone is one without pages to draw.
|
||||
*/
|
||||
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
|
||||
|
||||
/** The body of a request that says nothing else: the declaration alone. */
|
||||
private val DECLARED = JsonObject(mapOf("client" to CAPABILITIES))
|
||||
|
||||
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
|
||||
const val SHOWN_MAX_BYTES = 1_100_000L
|
||||
|
||||
/** The transcription's form fields beside the file: the language, and which chat. */
|
||||
fun transcriptionFields(language: String?, media: MediaFor): List<Pair<String, String>> = buildList {
|
||||
language?.let { add("language" to it) }
|
||||
media.chatId?.let { add("chat_id" to it) }
|
||||
media.chatModel?.let { add("chat_model" to it) }
|
||||
}
|
||||
|
||||
/** The body of a speech request: the words, the format, and which chat. */
|
||||
fun speechBody(text: String, media: MediaFor): JsonObject = buildJsonObject {
|
||||
put("input", text.take(20_000))
|
||||
put("response_format", "mp3")
|
||||
media.chatId?.let { put("chat_id", it) }
|
||||
media.chatModel?.let { put("chat_model", it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The source that answered in place of the chat's own (`X-Lembas-Fallback`), by its name
|
||||
* (`X-Lembas-Source`, percent-encoded: a header is Latin-1); null when the one expected
|
||||
* answered, and from a server that says neither.
|
||||
*/
|
||||
fun fallbackSource(fallback: String?, source: String?): String? {
|
||||
if (fallback.isNullOrBlank() || fallback == "0" || source.isNullOrBlank()) return null
|
||||
return runCatching { java.net.URLDecoder.decode(source.replace("+", "%2B"), "UTF-8") }.getOrDefault(source).ifBlank { null }
|
||||
}
|
||||
|
||||
private fun fallbackSource(response: Response): String? = fallbackSource(response.header("X-Lembas-Fallback"), response.header("X-Lembas-Source"))
|
||||
|
||||
fun emptyBody(): RequestBody = ByteArray(0).toRequestBody(null)
|
||||
|
||||
/** A model's picture is small; anything larger is not one. */
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -29,3 +32,38 @@ fun fit(found: Discovery): ServerFit {
|
||||
else -> ServerFit.FITS
|
||||
}
|
||||
}
|
||||
|
||||
/** This app's name among the products a discovery document's `min_clients` lists. */
|
||||
const val PRODUCT = "android"
|
||||
|
||||
/** The oldest version of [product] the instance says it works with, or null: nothing said, or not in words this app reads. */
|
||||
fun Discovery.minClient(product: String = PRODUCT): String? {
|
||||
val said = (minClients as? JsonObject)?.get(product) as? JsonPrimitive ?: return null
|
||||
return said.takeIf { it.isString }?.content?.trim()?.ifEmpty { null }
|
||||
}
|
||||
|
||||
private val VERSION = Regex("""^v?(\d+)\.(\d+)\.(\d+)(?:-beta\.(\d+))?""")
|
||||
|
||||
/**
|
||||
* A version as numbers that compare: `1.2.3` or `1.2.3-beta.4`, a release above every beta of
|
||||
* itself. Whatever follows is a build's own mark (`-debug.12`, a flavour) and is left off. Null
|
||||
* for what is no such version.
|
||||
*/
|
||||
fun versionNumbers(text: String): List<Int>? {
|
||||
val match = VERSION.find(text.trim()) ?: return null
|
||||
val (major, minor, patch, beta) = match.destructured
|
||||
val parts = listOf(major.toIntOrNull(), minor.toIntOrNull(), patch.toIntOrNull(), if (beta.isEmpty()) Int.MAX_VALUE else beta.toIntOrNull())
|
||||
return if (parts.any { it == null }) null else parts.filterNotNull()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the version [mine] is older than [needed]. By numbers, never as text: `1.0.0-beta.10`
|
||||
* is newer than `1.0.0-beta.9`, and `1.0.0` newer than both. False when either cannot be read:
|
||||
* a document that says nonsense locks nobody out.
|
||||
*/
|
||||
fun olderThan(mine: String, needed: String): Boolean {
|
||||
val own = versionNumbers(mine) ?: return false
|
||||
val least = versionNumbers(needed) ?: return false
|
||||
for (i in own.indices) if (own[i] != least[i]) return own[i] < least[i]
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
// An edit's diff on its approval card, worked out on the phone from the two texts the card
|
||||
// carries (`contract/event_ask_edit.json`). Lines only: what is drawn is text with a sign, and
|
||||
// every step is bounded before it is taken, because both texts are a model's and a file's words
|
||||
// of any size.
|
||||
|
||||
/** What a line of a diff is: in both texts, only in the new one, only in the old one, or the mark of lines left out between two changes. */
|
||||
enum class DiffSign { Same, Added, Removed, Gap }
|
||||
|
||||
data class DiffLine(val sign: DiffSign, val text: String)
|
||||
|
||||
/**
|
||||
* One file's change as the card draws it: the changed lines with a little around them, and how
|
||||
* many were added and removed. [endings] says a change of line endings (`"LF" to "CRLF"`), which
|
||||
* is said once instead of as every line going and coming. [cut]: the texts were longer than what
|
||||
* a phone compares, and only their beginning was.
|
||||
*/
|
||||
data class DiffView(val lines: List<DiffLine>, val added: Int, val removed: Int, val endings: Pair<String, String>? = null, val cut: Boolean = false) {
|
||||
/** The lines drawn: the first [DIFF_FOLD] until the person opens it, and never more than [DIFF_MOST]. */
|
||||
fun shown(open: Boolean): List<DiffLine> = lines.take(if (open) DIFF_MOST else DIFF_FOLD)
|
||||
|
||||
/** Whether there is more than the folded card shows. */
|
||||
val folds: Boolean get() = lines.size > DIFF_FOLD
|
||||
|
||||
/** The lines not drawn even when open. */
|
||||
val beyond: Int get() = (lines.size - DIFF_MOST).coerceAtLeast(0)
|
||||
|
||||
/** Whether the block says anything of the change at all; a card whose diffs say nothing keeps its arguments in view. */
|
||||
val says: Boolean get() = lines.isNotEmpty() || endings != null || cut
|
||||
}
|
||||
|
||||
/** How many lines of a file's diff the card shows before it is opened. */
|
||||
const val DIFF_FOLD = 12
|
||||
|
||||
/** The most lines of one file's diff the card lays out: a card is for deciding, not for reading a megabyte. */
|
||||
const val DIFF_MOST = 400
|
||||
|
||||
/** The lines kept around a change. */
|
||||
const val DIFF_CONTEXT = 3
|
||||
|
||||
/** Past this many pairs of lines the two middles are not compared: the old one is shown going and the new one coming. */
|
||||
private const val DIFF_CELLS = 1_000_000L
|
||||
|
||||
/** The most lines of one text that are compared, and the most characters: what is past either is left out before any work is done. */
|
||||
const val DIFF_TEXT_LINES = 2_000
|
||||
const val DIFF_TEXT_CHARS = 200_000
|
||||
|
||||
/** A text's lines as they are compared, and whether the text went on past what is. */
|
||||
data class TextLines(val lines: List<String>, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* The lines of [text], at most [mostLines] of them from at most its first [mostChars]
|
||||
* characters: nothing past either bound is read, split or kept. The newline that ends the last
|
||||
* line starts no empty one, and a line is compared without the `\r` before its newline, so a
|
||||
* file whose line endings change is not a file whose every line changes.
|
||||
*/
|
||||
fun textLines(text: String, mostLines: Int = DIFF_TEXT_LINES, mostChars: Int = DIFF_TEXT_CHARS): TextLines {
|
||||
val end = minOf(text.length, mostChars)
|
||||
val lines = ArrayList<String>()
|
||||
var from = 0
|
||||
while (from < end && lines.size < mostLines) {
|
||||
val newline = text.indexOf('\n', from).let { if (it < 0 || it >= end) -1 else it }
|
||||
val to = if (newline < 0) end else newline
|
||||
lines += text.substring(from, if (to > from && text[to - 1] == '\r') to - 1 else to)
|
||||
from = if (newline < 0) end else newline + 1
|
||||
}
|
||||
return TextLines(lines, cut = from < text.length)
|
||||
}
|
||||
|
||||
/** How [text]'s lines end, where it has any: `CRLF` when its first newline follows a `\r`, else `LF`; null for a text of one line. */
|
||||
internal fun lineEnding(text: String): String? {
|
||||
val newline = text.indexOf('\n')
|
||||
return when {
|
||||
newline < 0 -> null
|
||||
newline > 0 && text[newline - 1] == '\r' -> "CRLF"
|
||||
else -> "LF"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [old] turned into [new], line by line: what both begin and end with is the same without being
|
||||
* compared, and the middle is the longest run of lines the two share -- or, where the middles
|
||||
* are too long to compare on a phone, the old middle removed and the new one added.
|
||||
*/
|
||||
fun diffLines(old: List<String>, new: List<String>): List<DiffLine> {
|
||||
var head = 0
|
||||
while (head < old.size && head < new.size && old[head] == new[head]) head++
|
||||
var tail = 0
|
||||
while (tail < old.size - head && tail < new.size - head && old[old.size - 1 - tail] == new[new.size - 1 - tail]) tail++
|
||||
val a = old.subList(head, old.size - tail)
|
||||
val b = new.subList(head, new.size - tail)
|
||||
val out = ArrayList<DiffLine>(old.size + b.size)
|
||||
for (i in 0 until head) out += DiffLine(DiffSign.Same, old[i])
|
||||
if (a.isEmpty() || b.isEmpty() || a.size.toLong() * b.size > DIFF_CELLS) {
|
||||
a.forEach { out += DiffLine(DiffSign.Removed, it) }
|
||||
b.forEach { out += DiffLine(DiffSign.Added, it) }
|
||||
} else {
|
||||
// shared[i][j]: how many lines the rest of a from i and the rest of b from j have in common, in order.
|
||||
val shared = Array(a.size + 1) { IntArray(b.size + 1) }
|
||||
for (i in a.size - 1 downTo 0) {
|
||||
for (j in b.size - 1 downTo 0) {
|
||||
shared[i][j] = if (a[i] == b[j]) shared[i + 1][j + 1] + 1 else maxOf(shared[i + 1][j], shared[i][j + 1])
|
||||
}
|
||||
}
|
||||
var i = 0
|
||||
var j = 0
|
||||
while (i < a.size && j < b.size) {
|
||||
when {
|
||||
a[i] == b[j] -> {
|
||||
out += DiffLine(DiffSign.Same, a[i])
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
shared[i + 1][j] >= shared[i][j + 1] -> out += DiffLine(DiffSign.Removed, a[i++])
|
||||
|
||||
else -> out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
}
|
||||
while (i < a.size) out += DiffLine(DiffSign.Removed, a[i++])
|
||||
while (j < b.size) out += DiffLine(DiffSign.Added, b[j++])
|
||||
}
|
||||
for (i in old.size - tail until old.size) out += DiffLine(DiffSign.Same, old[i])
|
||||
return out
|
||||
}
|
||||
|
||||
/** The changed lines of [lines] with [context] unchanged ones around each, and one [DiffSign.Gap] where lines between two changes are left out. */
|
||||
fun hunks(lines: List<DiffLine>, context: Int = DIFF_CONTEXT): List<DiffLine> {
|
||||
val keep = BooleanArray(lines.size)
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (line.sign != DiffSign.Same) for (k in maxOf(0, at - context)..minOf(lines.size - 1, at + context)) keep[k] = true
|
||||
}
|
||||
val out = ArrayList<DiffLine>()
|
||||
var left = false
|
||||
lines.forEachIndexed { at, line ->
|
||||
if (keep[at]) {
|
||||
if (left && out.isNotEmpty()) out += DiffLine(DiffSign.Gap, "")
|
||||
left = false
|
||||
out += line
|
||||
} else {
|
||||
left = true
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* This file's change for the card: a file that is made is all added, one that goes is all
|
||||
* removed. Bounded before it starts ([textLines]) and while it runs ([diffLines]); it is still
|
||||
* work for a background thread, never for a frame.
|
||||
*/
|
||||
fun FileDiff.view(): DiffView {
|
||||
val before = oldText.orEmpty()
|
||||
val after = if (deleted) "" else newText
|
||||
val old = textLines(before)
|
||||
val new = textLines(after)
|
||||
val all = diffLines(old.lines, new.lines)
|
||||
val from = lineEnding(before)
|
||||
val to = lineEnding(after)
|
||||
return DiffView(
|
||||
hunks(all),
|
||||
added = all.count { it.sign == DiffSign.Added },
|
||||
removed = all.count { it.sign == DiffSign.Removed },
|
||||
endings = if (from != null && to != null && from != to) from to to else null,
|
||||
cut = old.cut || new.cut,
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether an approval's item shows its `detail` (the call's arguments): always without diffs, and with them when none of them says anything. [views] is null while they are worked out. */
|
||||
fun showsDetail(item: CardItem, views: List<DiffView>?): Boolean = item.diffs.isEmpty() || (views != null && views.none { it.says })
|
||||
|
||||
// Characters a person cannot see, or that would move or break a line: on a card where somebody
|
||||
// decides, each is written as its code point.
|
||||
private fun unseen(c: Char): Boolean = when (c.code) {
|
||||
in 0x00..0x1F, in 0x7F..0x9F -> true
|
||||
0x00AD, 0x061C, 0x180E, 0xFEFF -> true
|
||||
in 0x200B..0x200F, in 0x2028..0x202E, in 0x2060..0x206F -> true
|
||||
in 0xFFF9..0xFFFB -> true
|
||||
else -> false
|
||||
}
|
||||
|
||||
/**
|
||||
* [text] with every invisible, direction-changing or line-breaking character written as
|
||||
* `<U+202E>`: a bidi override, a zero-width space, a line separator, a control. A tab is four
|
||||
* spaces. What is drawn reads as what is written.
|
||||
*/
|
||||
fun visibly(text: String): String {
|
||||
if (text.none { it == '\t' || unseen(it) }) return text
|
||||
return buildString(text.length + 16) {
|
||||
for (c in text) {
|
||||
when {
|
||||
c == '\t' -> append(" ")
|
||||
unseen(c) -> append("<U+").append(c.code.toString(16).uppercase().padStart(4, '0')).append('>')
|
||||
else -> append(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// --- A linked device's directories (`GET /api/v2/devices/{id}/directories`) -------------------
|
||||
//
|
||||
// The JSON twin of the page's directory dialog (harness spec 3.9.0), as the contract pins it
|
||||
// (`contract/device_directories*.json`). Every field has a default, so a server that says less
|
||||
// still parses.
|
||||
|
||||
/** The model last used in a directory on the device, as one the person still has. */
|
||||
@Serializable
|
||||
data class DirectoryModel(val id: String = "", val name: String = "", val ref: String = "") {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String get() = name.ifBlank { id }
|
||||
}
|
||||
|
||||
/** A subdirectory: whether a session may be opened in it ([reason]: the device's words when not), and its [model]. */
|
||||
@Serializable
|
||||
data class DirectoryEntry(
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One directory on a device, or -- with an empty [path] -- the device's places. Where there is
|
||||
* no listing, [code] says why (`device_not_linked`, `cli_too_old`, `no_answer`, `refused`) and
|
||||
* [error] is the sentence for the person; a typed path still works then.
|
||||
*/
|
||||
@Serializable
|
||||
data class DeviceDirectory(
|
||||
val device: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val accepted: Boolean = true,
|
||||
val reason: String = "",
|
||||
val model: DirectoryModel? = null,
|
||||
val parent: String = "",
|
||||
val roots: List<String> = emptyList(),
|
||||
val entries: List<DirectoryEntry> = emptyList(),
|
||||
/** Whether the device says a directory's model at all. */
|
||||
val remembers: Boolean = false,
|
||||
val code: String = "",
|
||||
val error: String = "",
|
||||
) {
|
||||
/** The device's places, not a directory. */
|
||||
val places: Boolean get() = path.isEmpty()
|
||||
|
||||
/** Whether this answer is a listing; one with a [code] is the reason there is none. */
|
||||
val listed: Boolean get() = code.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a new agent chat on a device and directory starts on when the app names none
|
||||
* (`GET /models?kind=agent&device=&directory=`): [from] `directory` (the model last used
|
||||
* there) or `default`. The device remembers it; nothing here is kept by the app.
|
||||
*/
|
||||
@Serializable
|
||||
data class StartModel(val model: String = "", val from: String = "", val ref: String = "") {
|
||||
/** The model's unambiguous name where the server says one, else its id. */
|
||||
val key: String get() = ref.ifBlank { model }
|
||||
}
|
||||
@@ -136,11 +136,96 @@ enum class Drawn {
|
||||
* instruction, the line that opens a report's conversation) is not something the person said,
|
||||
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
|
||||
* [first] such line, which only tells the model what the conversation continues, is left out,
|
||||
* since the report itself is one tap back.
|
||||
* since the report itself is one tap back. A turn the linked computer's harness started
|
||||
* (`origin` `harness`: a job's end, a team member's report) is such a line whatever else the
|
||||
* row says: nobody typed it, here or in a terminal.
|
||||
*/
|
||||
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
|
||||
!message.isUser -> Drawn.Reply
|
||||
!message.machine -> Drawn.Person
|
||||
!message.byMachine -> Drawn.Person
|
||||
reportChat && first -> Drawn.Hidden
|
||||
else -> Drawn.Note
|
||||
}
|
||||
|
||||
/** The `origin` of a turn the linked computer's harness started by itself. */
|
||||
const val ORIGIN_HARNESS = "harness"
|
||||
|
||||
/** The `origin` of a message handed to the linked computer whose arrival there was never heard. */
|
||||
const val ORIGIN_UNSURE = "unsure"
|
||||
|
||||
/**
|
||||
* Whether this is the person's message of which nobody knows whether it reached the linked
|
||||
* computer (`origin` `unsure`, waiting): the instance never sends it by itself, so it is not
|
||||
* "queued, two ahead" -- it says what it is, in the instance's sentence. Any other origin this
|
||||
* app does not know is drawn as none.
|
||||
*/
|
||||
val Message.fateUnknown: Boolean get() = isUser && queued && origin == ORIGIN_UNSURE
|
||||
|
||||
/** The `origin` of a message the linked computer has said it holds for its next turn. */
|
||||
const val ORIGIN_CARRIED = "carried"
|
||||
|
||||
/** Why a message of the person's has not been given to a model yet. */
|
||||
enum class Waiting {
|
||||
/** A reply was being written when it was sent: it goes when its turn comes. */
|
||||
Queued,
|
||||
|
||||
/** Handed to the linked computer, its arrival never heard: the instance never sends it by itself. */
|
||||
Unsure,
|
||||
|
||||
/** The linked computer holds it and takes it in with its next turn. */
|
||||
Carried,
|
||||
}
|
||||
|
||||
/**
|
||||
* How this message waits, or null for one that does not: a message of the person's with
|
||||
* `queued` true. Such a message is not a turn yet, so it is sent now or discarded, never
|
||||
* edited. An origin this app does not know waits as a plain queued one does.
|
||||
*/
|
||||
val Message.waiting: Waiting?
|
||||
get() = when {
|
||||
!isUser || !queued -> null
|
||||
origin == ORIGIN_UNSURE -> Waiting.Unsure
|
||||
origin == ORIGIN_CARRIED -> Waiting.Carried
|
||||
else -> Waiting.Queued
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Edit is offered on this message of the person's: not while a reply is being
|
||||
* [writing], and never on one that still waits -- the instance refuses that, since it has not
|
||||
* been a turn yet and a linked computer may still hold its old words.
|
||||
*/
|
||||
fun Message.editable(writing: Boolean): Boolean = isUser && !writing && !queued
|
||||
|
||||
/** Whether nobody typed this row: the server wrote it (`machine`), or a device's harness did. */
|
||||
val Message.byMachine: Boolean get() = machine || origin == ORIGIN_HARNESS
|
||||
|
||||
/**
|
||||
* Whether [reply] is a finished reply that holds nothing at all and answers a turn nobody typed
|
||||
* ([asked], the row before it): what was said to that turn was never written into the chat
|
||||
* (instances from before the reply to a harness turn followed the device hold a few). One quiet
|
||||
* line says so in its place -- the server's rule for its own page, never a blank row with
|
||||
* buttons. A reply still being written, one that was stopped or failed, one that holds a plan
|
||||
* and nothing else, and an empty reply to something a person asked are not this.
|
||||
*
|
||||
* [live] is the reply this screen knows is being written, by its id: that one is never this,
|
||||
* whatever its row says. A row says `complete` only when the server does, and a row that says
|
||||
* nothing reads as complete ([Message.complete]); the rule does not rest on that alone.
|
||||
*/
|
||||
fun replyUnrecorded(reply: Message, asked: Message?, live: String? = null): Boolean = !reply.isUser &&
|
||||
reply.id != live &&
|
||||
reply.complete &&
|
||||
!reply.stopped &&
|
||||
reply.error.isNullOrBlank() &&
|
||||
reply.end == null &&
|
||||
reply.text.isNullOrBlank() &&
|
||||
reply.steps.isEmpty() &&
|
||||
reply.plan == null &&
|
||||
reply.attachments.isEmpty() &&
|
||||
asked != null &&
|
||||
asked.isUser &&
|
||||
asked.byMachine
|
||||
|
||||
/** The replies of [messages] that are [replyUnrecorded], by id; [live] is the one being written, if any. */
|
||||
fun unrecordedReplies(messages: List<Message>, live: String? = null): Set<String> = messages.indices
|
||||
.filter { replyUnrecorded(messages[it], messages.getOrNull(it - 1), live) }
|
||||
.mapTo(HashSet()) { messages[it].id }
|
||||
@@ -0,0 +1,55 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import kotlinx.coroutines.flow.onSubscription
|
||||
import kotlinx.coroutines.flow.shareIn
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* One connection to a person's events route (`GET /events`) for everything that watches it --
|
||||
* the drawer's Reports badge, the Scheduled list -- instead of one each. It is open while
|
||||
* somebody watches and closed when nobody does.
|
||||
*
|
||||
* A frame of the route is a whole state (`schedules`, `reports`), which the server sends at
|
||||
* once to a new connection. A watcher that joins a connection already open missed that, so it
|
||||
* is first told the last frame of each such kind this connection carried.
|
||||
*
|
||||
* `reply` is the exception ([MOMENTS]): something that happened, not how things are. It is
|
||||
* passed on to whoever is watching and never said again -- a watcher that joins later would
|
||||
* take a reply long finished for one that has just started.
|
||||
*
|
||||
* A route that refuses (an older server) ends quietly: its watchers hear nothing, as they did
|
||||
* when each asked for itself.
|
||||
*/
|
||||
class EventsHub(private val scope: CoroutineScope) {
|
||||
private class Line(val key: String, val frames: SharedFlow<Frame>, val latest: MutableMap<String, Frame>)
|
||||
|
||||
private var line: Line? = null
|
||||
|
||||
/** The frames of the route [key] names (an instance's id), opened by [open] when nobody watches it yet. */
|
||||
@Synchronized
|
||||
fun frames(key: String, open: () -> Flow<Frame>): Flow<Frame> {
|
||||
val now = line?.takeIf { it.key == key } ?: run {
|
||||
val latest = ConcurrentHashMap<String, Frame>()
|
||||
val shared = open()
|
||||
// A connection opened anew is told everything again: what the last one said is stale.
|
||||
.onStart { latest.clear() }
|
||||
.onEach { if (it.event !in MOMENTS) latest[it.event] = it }
|
||||
.catch { }
|
||||
.shareIn(scope, SharingStarted.WhileSubscribed(), replay = 0)
|
||||
Line(key, shared, latest).also { line = it }
|
||||
}
|
||||
return now.frames.onSubscription { now.latest.values.toList().forEach { emit(it) } }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** The frames that say something happened, rather than how things are: never told again to a late watcher. */
|
||||
val MOMENTS = setOf("reply")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.io.IOException
|
||||
|
||||
// The person's files as a file manager needs them: the shapes of the trash, the versions and a
|
||||
// batch (`contract/files_*.json`, `file_versions.json`, `file_save_conflict.json`), and what the
|
||||
// app decides from a file's kind without a phone: which viewer, a table's rows, a notebook's cells.
|
||||
|
||||
/** One thing in the trash: restored or removed for good by its [id]. */
|
||||
@Serializable
|
||||
data class TrashItem(
|
||||
val id: String = "",
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
val size: Long = 0,
|
||||
@SerialName("trashed_at") val trashedAt: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /files/trash`, and what is left after a restore ([restored]: where it went back to) or a removal. */
|
||||
@Serializable
|
||||
data class TrashList(val items: List<TrashItem> = emptyList(), val restored: String? = null, val removed: Int = 0)
|
||||
|
||||
/** One version of a file, newest first in [FileVersions]; [current] is what the file holds now. */
|
||||
@Serializable
|
||||
data class FileVersion(
|
||||
val id: String = "",
|
||||
val sha: String = "",
|
||||
val size: Long = 0,
|
||||
val at: String? = null,
|
||||
val by: String? = null,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
val current: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FileVersions(val path: String = "", val sha: String = "", val versions: List<FileVersion> = emptyList())
|
||||
|
||||
/** One path of a batch: done ([ok], and where it is now) or refused, in the server's sentence. */
|
||||
@Serializable
|
||||
data class BatchResult(val path: String = "", val ok: Boolean = false, val to: String? = null, val error: String? = null)
|
||||
|
||||
/** `POST /files/batch`: never all-or-nothing, so [failed] is read even from a 200. */
|
||||
@Serializable
|
||||
data class BatchAnswer(val op: String = "", val to: String? = null, val results: List<BatchResult> = emptyList(), val done: Int = 0, val failed: Int = 0) {
|
||||
/** The server's sentences for what was refused, each once, at most [most]. */
|
||||
fun refusals(most: Int = 3): List<String> = results.filter { !it.ok }.mapNotNull { it.error?.ifBlank { null } }.distinct().take(most)
|
||||
}
|
||||
|
||||
/**
|
||||
* A save the server refused because the file changed since it was opened (409, `conflict: true`):
|
||||
* its sentence, and the [sha] the file holds now. Nothing was written.
|
||||
*/
|
||||
class SaveConflict(message: String, val sha: String) : IOException(message)
|
||||
|
||||
/** The viewer a file gets, by the server's word for what it is. */
|
||||
enum class FileView {
|
||||
/** Markdown, code, text, and the source of an HTML page or an SVG: drawn as text, editable. */
|
||||
Text,
|
||||
Image,
|
||||
Pdf,
|
||||
Audio,
|
||||
Video,
|
||||
Table,
|
||||
Notebook,
|
||||
|
||||
/** Nothing to draw here: what the file is, and Download, Open with, Share. */
|
||||
Details,
|
||||
}
|
||||
|
||||
object FileKinds {
|
||||
/** The kinds whose text the server hands over and the app may save back. */
|
||||
val TEXT = setOf("markdown", "code", "text", "html", "svg")
|
||||
|
||||
/**
|
||||
* The viewer for a file of [kind]. A server that does not say the kind (null) is read as
|
||||
* before: as text, and the content answer says when it is not. An SVG is its source -- the
|
||||
* app has no WebView and draws nothing a file could script.
|
||||
*/
|
||||
fun viewer(kind: String?): FileView = when (kind) {
|
||||
null, "", in TEXT -> FileView.Text
|
||||
"image" -> FileView.Image
|
||||
"pdf" -> FileView.Pdf
|
||||
"audio" -> FileView.Audio
|
||||
"video" -> FileView.Video
|
||||
"table" -> FileView.Table
|
||||
"notebook" -> FileView.Notebook
|
||||
else -> FileView.Details
|
||||
}
|
||||
|
||||
/** Whether the app offers to edit it: a text kind (a table too, as its text) the person may change. */
|
||||
fun editable(kind: String?, writable: Boolean?, withheld: Boolean): Boolean = writable == true && !withheld && (kind in TEXT || kind == "table")
|
||||
|
||||
/** Why [name] cannot be a file's or a folder's name, as the server would refuse it; false for a good one. */
|
||||
fun badName(name: String): Boolean = name.isBlank() || "/" in name || name.trim() in setOf(".", "..")
|
||||
|
||||
/** [name] inside the directory [dir]. */
|
||||
fun child(dir: String, name: String): String = dir.trimEnd('/') + "/" + name.trim()
|
||||
|
||||
/** The directory a path is in; `/` for a path at the top. */
|
||||
fun parent(path: String): String = path.trimEnd('/').substringBeforeLast('/', "").ifEmpty { "/" }
|
||||
|
||||
/** The last name of a path. */
|
||||
fun name(path: String): String = path.trimEnd('/').substringAfterLast('/').ifBlank { path }
|
||||
|
||||
/**
|
||||
* A name another app or a file system may be given: no separators, no control characters,
|
||||
* never empty, and at most [most] bytes as UTF-8 -- a file system counts a name in bytes
|
||||
* (255 of them), and a name in another script is three bytes a letter. A longer name loses
|
||||
* the end of its stem and keeps its extension, which is what says how to open it.
|
||||
*/
|
||||
fun safeName(name: String, most: Int = NAME_MAX_BYTES): String {
|
||||
val kept = name.map { if (it == '/' || it == '\\' || it.isISOControl()) '_' else it }.joinToString("").trim().trim('.').ifBlank { "file" }
|
||||
if (utf8(kept) <= most) return kept
|
||||
val dot = kept.lastIndexOf('.')
|
||||
// An extension is short; a last dot far from the end is a sentence's, and the name is cut as a whole.
|
||||
val ext = if (dot > 0 && utf8(kept.substring(dot)) <= minOf(EXTENSION_MAX_BYTES, most / 2)) kept.substring(dot) else ""
|
||||
val stem = kept.substring(0, kept.length - ext.length)
|
||||
val room = most - utf8(ext)
|
||||
val cut = StringBuilder()
|
||||
var used = 0
|
||||
var i = 0
|
||||
while (i < stem.length) {
|
||||
// By code point: half of a pair is not a character.
|
||||
val point = stem.codePointAt(i)
|
||||
val bytes = utf8(String(Character.toChars(point)))
|
||||
if (used + bytes > room) break
|
||||
cut.appendCodePoint(point)
|
||||
used += bytes
|
||||
i += Character.charCount(point)
|
||||
}
|
||||
return cut.toString().trimEnd().trimEnd('.').ifBlank { "file" } + ext
|
||||
}
|
||||
|
||||
private fun utf8(text: String): Int = text.toByteArray(Charsets.UTF_8).size
|
||||
|
||||
/** The longest name [safeName] gives, in bytes. */
|
||||
const val NAME_MAX_BYTES = 200
|
||||
private const val EXTENSION_MAX_BYTES = 24
|
||||
}
|
||||
|
||||
/** One thing an archive holds: its [name] is the archive's own text (a path inside it), [size] null for a folder and where the archive does not say. */
|
||||
@Serializable
|
||||
data class ArchiveEntry(val name: String = "", val size: Long? = null, val dir: Boolean = false)
|
||||
|
||||
/**
|
||||
* What is inside an archive, listed by the instance and never unpacked: at most 2000 [entries];
|
||||
* [total] how many it holds where it says; [truncated] when there are more than are listed.
|
||||
* [problem] is null, or why there is no listing (`unreadable`, `unsupported`, `busy`), with the
|
||||
* instance's sentence for it in [message].
|
||||
*/
|
||||
@Serializable
|
||||
data class ArchiveListing(
|
||||
val entries: List<ArchiveEntry> = emptyList(),
|
||||
val total: Int? = null,
|
||||
val truncated: Boolean = false,
|
||||
val problem: String? = null,
|
||||
val message: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Where a file known by its id is now (`GET /files/node?id=`): [parent] is the directory to
|
||||
* list, [path] the file. [trashed]: it is in the trash, and [path] is where it lay.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileNode(
|
||||
val id: String = "",
|
||||
val path: String = "",
|
||||
val name: String = "",
|
||||
val parent: String = "",
|
||||
val kind: String = "",
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val trashed: Boolean = false,
|
||||
)
|
||||
|
||||
/** Where "Open in Files" leads for a file a chat names by its id. */
|
||||
sealed interface Whereabouts {
|
||||
/** The directory to open: where the file is now. */
|
||||
data class Folder(val path: String) : Whereabouts
|
||||
|
||||
/** It is in the trash: no directory holds it. */
|
||||
data object Trashed : Whereabouts
|
||||
}
|
||||
|
||||
/**
|
||||
* Where to go for a file last known at [written], from what the instance says of its node
|
||||
* ([node]; null from an instance that cannot say): the directory it is in now -- it may have
|
||||
* been renamed or moved -- else the one it was written to.
|
||||
*/
|
||||
fun whereabouts(node: FileNode?, written: String): Whereabouts = when {
|
||||
node == null -> Whereabouts.Folder(FileKinds.parent(written))
|
||||
node.trashed -> Whereabouts.Trashed
|
||||
else -> Whereabouts.Folder(node.parent.ifBlank { FileKinds.parent(node.path.ifBlank { written }) })
|
||||
}
|
||||
|
||||
/** A table's first rows and columns; [cut] when the file has more than is laid out. */
|
||||
data class Table(val rows: List<List<String>>, val columns: Int, val cut: Boolean)
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as rows of cells: quoted cells, doubled quotes and line breaks inside quotes
|
||||
* as RFC 4180 has them. At most [maxRows] rows of at most [maxColumns] cells are kept, each cell
|
||||
* at most [maxCell] characters -- a table is for looking at, the text has all of it. [partial]:
|
||||
* the text is only the file's beginning, so its last line may be half a row and is left out.
|
||||
*/
|
||||
fun parseTable(text: String, delimiter: Char, maxRows: Int = 500, maxColumns: Int = 40, maxCell: Int = 200, partial: Boolean = false): Table {
|
||||
val rows = mutableListOf<List<String>>()
|
||||
var row = mutableListOf<String>()
|
||||
val cell = StringBuilder()
|
||||
var quoted = false
|
||||
var cut = partial
|
||||
var widest = 0
|
||||
var i = 0
|
||||
|
||||
fun endCell() {
|
||||
if (row.size < maxColumns) row += cell.toString().take(maxCell) else cut = true
|
||||
cell.setLength(0)
|
||||
}
|
||||
|
||||
fun endRow(): Boolean {
|
||||
endCell()
|
||||
if (row.size > 1 || row[0].isNotEmpty()) {
|
||||
rows += row
|
||||
widest = maxOf(widest, row.size)
|
||||
}
|
||||
row = mutableListOf()
|
||||
return rows.size < maxRows
|
||||
}
|
||||
|
||||
var open = true
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
quoted && c == '"' && i + 1 < text.length && text[i + 1] == '"' -> {
|
||||
cell.append('"')
|
||||
i++
|
||||
}
|
||||
|
||||
c == '"' && (quoted || cell.isEmpty()) -> quoted = !quoted
|
||||
|
||||
!quoted && c == delimiter -> endCell()
|
||||
|
||||
!quoted && (c == '\n' || c == '\r') -> {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') i++
|
||||
if (!endRow()) {
|
||||
cut = cut || i + 1 < text.length
|
||||
open = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
else -> if (cell.length <= maxCell) cell.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
// What is left after the last line break: a whole last row, unless the text was cut short.
|
||||
if (open && !partial && (cell.isNotEmpty() || row.isNotEmpty())) endRow()
|
||||
return Table(rows, widest, cut)
|
||||
}
|
||||
|
||||
/** The delimiter a table file is cut by: a tab for `.tsv` (or a first line with tabs and no commas), else a comma. */
|
||||
fun tableDelimiter(name: String, text: String): Char {
|
||||
if (name.endsWith(".tsv", ignoreCase = true) || name.endsWith(".tab", ignoreCase = true)) return '\t'
|
||||
val first = text.lineSequence().firstOrNull().orEmpty()
|
||||
return if ('\t' in first && ',' !in first) {
|
||||
'\t'
|
||||
} else if (';' in first && ',' !in first) {
|
||||
';'
|
||||
} else {
|
||||
','
|
||||
}
|
||||
}
|
||||
|
||||
/** One cell of a notebook, as text: its [source], and what it printed ([output], plain text only). */
|
||||
data class NotebookCell(val kind: String, val source: String, val output: String = "", val count: Int? = null, val cut: Boolean = false)
|
||||
|
||||
/** A notebook's first cells; [more]: how many are not shown. Null from [parseNotebook]: not a notebook. */
|
||||
data class Notebook(val cells: List<NotebookCell>, val more: Int = 0, val language: String = "")
|
||||
|
||||
/**
|
||||
* A Jupyter notebook, read-only, as text and nothing else: a cell's source, and of its outputs
|
||||
* only the plain text (a stream, `text/plain`, an error's name and value). HTML, pictures and
|
||||
* scripts in an output are not drawn and not kept. Null for a file that is not a notebook.
|
||||
*/
|
||||
fun parseNotebook(text: String, maxCells: Int = 200, maxChars: Int = 20_000): Notebook? {
|
||||
val root = runCatching { LembasJson.parseToJsonElement(text) as? JsonObject }.getOrNull() ?: return null
|
||||
val cells = root["cells"] as? JsonArray ?: return null
|
||||
|
||||
fun words(of: JsonElement?): String = when (of) {
|
||||
is JsonPrimitive -> if (of.isString) of.content else ""
|
||||
is JsonArray -> of.joinToString("") { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content.orEmpty() }
|
||||
else -> ""
|
||||
}
|
||||
|
||||
fun printed(cell: JsonObject): String = (cell["outputs"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.joinToString("") { out ->
|
||||
when ((out["output_type"] as? JsonPrimitive)?.content) {
|
||||
"stream" -> words(out["text"])
|
||||
"error" -> listOf(words(out["ename"]), words(out["evalue"])).filter { it.isNotBlank() }.joinToString(": ") + "\n"
|
||||
else -> words((out["data"] as? JsonObject)?.get("text/plain")).let { if (it.isEmpty() || it.endsWith("\n")) it else it + "\n" }
|
||||
}
|
||||
}.trimEnd('\n')
|
||||
|
||||
val language = (((root["metadata"] as? JsonObject)?.get("kernelspec") as? JsonObject)?.get("language") as? JsonPrimitive)?.content
|
||||
?: ((((root["metadata"] as? JsonObject)?.get("language_info") as? JsonObject)?.get("name")) as? JsonPrimitive)?.content
|
||||
val read = cells.mapNotNull { it as? JsonObject }.take(maxCells).map { cell ->
|
||||
val source = words(cell["source"])
|
||||
val output = printed(cell)
|
||||
NotebookCell(
|
||||
kind = (cell["cell_type"] as? JsonPrimitive)?.content ?: "code",
|
||||
source = source.take(maxChars),
|
||||
output = output.take(maxChars),
|
||||
count = (cell["execution_count"] as? JsonPrimitive)?.content?.toIntOrNull(),
|
||||
cut = source.length > maxChars || output.length > maxChars,
|
||||
)
|
||||
}
|
||||
return Notebook(read, more = (cells.size - read.size).coerceAtLeast(0), language = language.orEmpty())
|
||||
}
|
||||
|
||||
/**
|
||||
* How much smaller a picture of [width] × [height] is decoded (a power of two, `inSampleSize`):
|
||||
* so its longer edge is at most about [edge] and it holds at most [pixels] pixels, whatever the
|
||||
* file claims. A picture of 30 000 × 30 000 is then a few megabytes in memory, not gigabytes.
|
||||
*/
|
||||
fun sampleFor(width: Int, height: Int, edge: Int = 2560, pixels: Long = 8_000_000): Int {
|
||||
if (width <= 0 || height <= 0) return 1
|
||||
var sample = 1
|
||||
while (maxOf(width, height) / sample > edge || (width.toLong() / sample) * (height.toLong() / sample) > pixels) sample *= 2
|
||||
return sample
|
||||
}
|
||||
|
||||
/**
|
||||
* A file read a piece at a time, for a player that seeks: [fetch] gets the bytes `[from, to]`
|
||||
* (a `Range` request with the token in its header), a few blocks are kept, and a read is
|
||||
* answered from the block its position is in. [length] is the file's size as the server said it.
|
||||
*/
|
||||
class RangeReader(private val length: Long, private val block: Int = BLOCK, private val keep: Int = 6, private val fetch: (from: Long, to: Long) -> ByteArray) {
|
||||
private val blocks = object : LinkedHashMap<Long, ByteArray>(keep, 0.75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?): Boolean = size > keep
|
||||
}
|
||||
|
||||
/** Up to [size] bytes from [position] into [buffer] at [offset]; -1 at or past the end. */
|
||||
@Synchronized
|
||||
fun read(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
|
||||
if (position < 0 || position >= length) return -1
|
||||
if (size <= 0) return 0
|
||||
val index = position / block
|
||||
val start = index * block
|
||||
val bytes = blocks[index] ?: fetch(start, minOf(start + block, length) - 1).also { blocks[index] = it }
|
||||
val within = (position - start).toInt()
|
||||
if (within >= bytes.size) return -1
|
||||
val n = minOf(size, bytes.size - within)
|
||||
System.arraycopy(bytes, within, buffer, offset, n)
|
||||
return n
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun close() = blocks.clear()
|
||||
|
||||
companion object {
|
||||
const val BLOCK = 512 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a file's beginning says what it is. */
|
||||
const val SNIFF_BYTES = 16
|
||||
|
||||
private fun ByteArray.begins(at: Int, vararg bytes: Int): Boolean =
|
||||
size >= at + bytes.size && bytes.indices.all { (this[at + it].toInt() and 0xFF) == bytes[it] }
|
||||
|
||||
private fun ByteArray.says(at: Int, word: String): Boolean = size >= at + word.length && word.indices.all { this[at + it].toInt() == word[it].code }
|
||||
|
||||
/**
|
||||
* What a file is by its first bytes ([head], [SNIFF_BYTES] of them are enough), for the kinds a
|
||||
* chat hands out: pictures, sound, video, a PDF, a 3D model, the archives. Null for anything
|
||||
* else -- text has no mark, and a guess is worse than none.
|
||||
*/
|
||||
fun sniffType(head: ByteArray): String? = when {
|
||||
head.begins(0, 0x89, 0x50, 0x4E, 0x47) -> "image/png"
|
||||
head.begins(0, 0xFF, 0xD8, 0xFF) -> "image/jpeg"
|
||||
head.says(0, "GIF8") -> "image/gif"
|
||||
head.says(0, "RIFF") && head.says(8, "WEBP") -> "image/webp"
|
||||
head.says(0, "RIFF") && head.says(8, "WAVE") -> "audio/wav"
|
||||
head.says(0, "BM") -> "image/bmp"
|
||||
head.says(0, "%PDF-") -> "application/pdf"
|
||||
head.says(0, "OggS") -> "audio/ogg"
|
||||
head.says(0, "fLaC") -> "audio/flac"
|
||||
head.says(0, "ID3") || head.begins(0, 0xFF, 0xFB) || head.begins(0, 0xFF, 0xF3) -> "audio/mpeg"
|
||||
head.says(4, "ftyp") -> "video/mp4"
|
||||
head.begins(0, 0x1A, 0x45, 0xDF, 0xA3) -> "video/webm"
|
||||
head.says(0, "glTF") -> "model/gltf-binary"
|
||||
head.says(0, "PK\u0003\u0004") -> "application/zip"
|
||||
head.begins(0, 0x1F, 0x8B) -> "application/gzip"
|
||||
head.says(0, "7z") && head.begins(2, 0xBC, 0xAF) -> "application/x-7z-compressed"
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The type a copy is offered to another app as ("Open with"): what its bytes say, else what its
|
||||
* name's extension says ([named], the platform's table), else anything. A zip is the one mark
|
||||
* that many kinds of document carry inside, so there a known extension is the better word. The
|
||||
* type the instance said is not asked: it is not the phone's own reading.
|
||||
*/
|
||||
fun openType(head: ByteArray, named: String?): String {
|
||||
val sniffed = sniffType(head)
|
||||
val byName = named?.ifBlank { null }
|
||||
return when {
|
||||
sniffed == null -> byName ?: "*/*"
|
||||
sniffed == "application/zip" && byName != null -> byName
|
||||
else -> sniffed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import eu.llembas.android.BuildConfig
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
|
||||
/** This app's name to a server, with [version]: `llembas-android/1.2.3`. */
|
||||
fun userAgent(version: String): String = "llembas-android/$version"
|
||||
|
||||
/**
|
||||
* Who is asking: the `User-Agent` of every request this app makes (calls, streams, uploads and
|
||||
* downloads) and the device code's `client_id` -- one string, so a server's list of devices and
|
||||
* its logs name the same program.
|
||||
*/
|
||||
val USER_AGENT: String = userAgent(BuildConfig.VERSION_NAME)
|
||||
|
||||
/**
|
||||
* The token a response says the instance no longer accepts, or null. Only the instance's own
|
||||
* refusal counts: a 401 with its `WWW-Authenticate: Bearer realm="lembas"`, to a request that
|
||||
* carried a token. A 401 passed on from somewhere else -- a speech provider behind `/v1`
|
||||
* refusing the instance's key -- has no such header and signs nobody out; nor does a 403, which
|
||||
* is the server's sentence about one thing that is not allowed.
|
||||
*/
|
||||
fun refusedToken(status: Int, challenge: String?, authorization: String?): String? {
|
||||
if (status != 401 || challenge == null || authorization == null) return null
|
||||
val asked = challenge.trim()
|
||||
if (!asked.startsWith("Bearer", ignoreCase = true) || !asked.contains("realm=\"lembas\"", ignoreCase = true)) return null
|
||||
if (!authorization.startsWith("Bearer ")) return null
|
||||
return authorization.removePrefix("Bearer ").trim().ifEmpty { null }
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a refused token is said: once for the process, heard by whoever keeps the instances
|
||||
* (`LembasApp`). It is told the token, not "the instance in use" -- a request of another
|
||||
* instance, or one that was under way while the person switched, signs out the instance whose
|
||||
* token it carried and no other. Called on the thread the answer arrived on: the listener only
|
||||
* hands it on.
|
||||
*/
|
||||
object RefusedTokens {
|
||||
@Volatile
|
||||
var heard: ((String) -> Unit)? = null
|
||||
}
|
||||
|
||||
/** Names the app on every request, and listens for the instance refusing a token. */
|
||||
internal class Identity : Interceptor {
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
val request = chain.request().newBuilder().header("User-Agent", USER_AGENT).build()
|
||||
val response = chain.proceed(request)
|
||||
refusedToken(response.code, response.header("WWW-Authenticate"), request.header("Authorization"))?.let { token ->
|
||||
RefusedTokens.heard?.invoke(token)
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
/** A `Retry-After` in seconds (the server sends a number), or null: absent, a date, or nonsense. */
|
||||
fun retryAfterSeconds(header: String?): Long? = header?.trim()?.toLongOrNull()?.takeIf { it >= 0 }
|
||||
|
||||
/**
|
||||
* The one reconnect schedule of every LLeMbas client: a pause of 1 second that doubles to 60,
|
||||
* each within ±20 % so that the clients of a server that restarted do not all return at the same
|
||||
* moment, and back to 1 second only after a connection that stayed healthy for 30 seconds -- a
|
||||
* stream that opens, says one frame and breaks again is not a reason to ask every second.
|
||||
*
|
||||
* [jitter] gives a number in 0..1 (0.5 is no jitter).
|
||||
*/
|
||||
class Reconnect(private val jitter: () -> Double = { Math.random() }) {
|
||||
private var step = FIRST_MS
|
||||
|
||||
/**
|
||||
* The pause before the next opening. [healthyMs] is how long the connection that just ended
|
||||
* had been carrying frames (0 for one that never did); [retryAfterMs] is what the server asked
|
||||
* for on a 429, honoured when it is the longer of the two (up to [MOST_ASKED_MS]).
|
||||
*/
|
||||
fun pause(healthyMs: Long, retryAfterMs: Long = 0): Long {
|
||||
if (healthyMs >= HEALTHY_MS) step = FIRST_MS
|
||||
val now = step
|
||||
step = (step * 2).coerceAtMost(LAST_MS)
|
||||
val jittered = (now * (0.8 + 0.4 * jitter().coerceIn(0.0, 1.0))).toLong()
|
||||
return maxOf(jittered, retryAfterMs.coerceIn(0L, MOST_ASKED_MS))
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val FIRST_MS = 1_000L
|
||||
const val LAST_MS = 60_000L
|
||||
const val HEALTHY_MS = 30_000L
|
||||
|
||||
/** A server may ask for a long wait; a stream somebody watches is looked at again within five minutes. */
|
||||
const val MOST_ASKED_MS = 300_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package eu.llembas.android.api
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// What a model made, as the app is told of it (`contract/tool_media.json`, `media_job*.json`,
|
||||
// `mcp_servers.json`): a tool call's typed result, a long generation's job, and -- because they
|
||||
// arrived with the same server -- the instance's MCP servers and how each is signed in to.
|
||||
|
||||
/**
|
||||
* A file a tool call made: [kind] is what was asked for (`image`, `image_edit`, `video`, `music`,
|
||||
* `model3d`), and the file is in the person's Files at [path] -- a moment's truth, since they may
|
||||
* move it; [nodeId] names it wherever it is. Its bytes are `GET /files/raw?node=`. [width],
|
||||
* [height] and [seconds] are 0 where the server did not know them.
|
||||
*
|
||||
* With [shown] it is a file an agent put in front of the person (`contract/tool_media_shown.json`)
|
||||
* and [kind] is what the file is, read from its bytes: `image`, `audio`, `video`, `pdf`,
|
||||
* `model3d`, `archive`, `binary`, `text`, or a word this app does not know yet. Whatever it is,
|
||||
* its card names it and leads to the file; what the phone can draw is drawn as well.
|
||||
*/
|
||||
@Serializable
|
||||
data class GeneratedMedia(
|
||||
val kind: String = "",
|
||||
val path: String = "",
|
||||
@SerialName("node_id") val nodeId: String = "",
|
||||
@SerialName("version_id") val versionId: String = "",
|
||||
val name: String = "",
|
||||
val mime: String = "",
|
||||
val size: Long = 0,
|
||||
val width: Int = 0,
|
||||
val height: Int = 0,
|
||||
val seconds: Double = 0.0,
|
||||
/** An agent showed this file (the `show` tool on a file that is not text); it did not make it. */
|
||||
val shown: Boolean = false,
|
||||
) {
|
||||
/** How the card shows it, by its kind: an unknown kind is its details, never a player. */
|
||||
val view: MediaView
|
||||
get() = when (kind) {
|
||||
"image", "image_edit" -> MediaView.Picture
|
||||
"video" -> MediaView.Video
|
||||
"music", "audio" -> MediaView.Sound
|
||||
"pdf" -> MediaView.Document
|
||||
else -> MediaView.Details
|
||||
}
|
||||
|
||||
/** The kinds this app has a word for; anything else is said as "File" when shown, never as nothing. */
|
||||
val knownKind: Boolean get() = kind in KINDS
|
||||
|
||||
/** What to call it: its name, else the last name of its path. */
|
||||
val title: String get() = name.ifBlank { FileKinds.name(path) }
|
||||
|
||||
/** Where its bytes are asked for: by its id, which outlives a rename or a move; by its path from a result without one. */
|
||||
val raw: Raw get() = if (nodeId.isNotBlank()) Raw.Node(nodeId) else Raw.Path(path)
|
||||
|
||||
/** The folder of the person's Files it was written to. */
|
||||
val folder: String get() = FileKinds.parent(path)
|
||||
|
||||
companion object {
|
||||
val KINDS = setOf("image", "image_edit", "video", "music", "audio", "model3d", "pdf", "archive", "binary", "text")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a file's card is: a picture drawn, a player, a document with pages the phone can lay out
|
||||
* (a PDF), or -- a 3D model, an archive, anything unknown -- the file's details. Every one of
|
||||
* them names the file and has the ways to it.
|
||||
*/
|
||||
enum class MediaView { Picture, Video, Sound, Document, Details }
|
||||
|
||||
/** The job a tool call started (`media_job`): [state] as it was when the call returned. */
|
||||
@Serializable
|
||||
data class MediaJobRef(val id: String = "", val kind: String = "", val state: String = "")
|
||||
|
||||
/** What a finished job was counted as; an empty [currency] is the instance's own. */
|
||||
@Serializable
|
||||
data class MediaCost(val amount: Double = 0.0, val currency: String = "")
|
||||
|
||||
/**
|
||||
* A long generation (`GET /media/jobs/{id}`): `queued` and `running` are under way, `done` has
|
||||
* its [result], `failed`, `cancelled` and `expired` say why in [error] -- the server's sentence,
|
||||
* for the person. [seconds] is how long it has taken so far, or took. [told]: the chat was woken
|
||||
* with a reply about it.
|
||||
*/
|
||||
@Serializable
|
||||
data class MediaJob(
|
||||
val id: String = "",
|
||||
val kind: String = "",
|
||||
val state: String = "",
|
||||
val active: Boolean = false,
|
||||
@SerialName("chat_id") val chatId: String? = null,
|
||||
@SerialName("message_id") val messageId: String? = null,
|
||||
val source: String = "",
|
||||
val prompt: String = "",
|
||||
val started: String? = null,
|
||||
val ended: String? = null,
|
||||
val deadline: String? = null,
|
||||
val seconds: Double = 0.0,
|
||||
val error: String = "",
|
||||
val result: GeneratedMedia? = null,
|
||||
val cost: MediaCost? = null,
|
||||
val told: Boolean = false,
|
||||
) {
|
||||
/** Still to end: by the server's word, or by a state that is one of the two that are under way. */
|
||||
val underWay: Boolean get() = active || state in ACTIVE
|
||||
|
||||
/** Ended some way other than with a file. */
|
||||
val unsuccessful: Boolean get() = !underWay && state != DONE
|
||||
|
||||
companion object {
|
||||
val ACTIVE = setOf("queued", "running")
|
||||
const val DONE = "done"
|
||||
const val CANCELLED = "cancelled"
|
||||
|
||||
/** A job known only by the call that started it. */
|
||||
fun of(ref: MediaJobRef): MediaJob = MediaJob(id = ref.id, kind = ref.kind, state = ref.state, active = ref.state in ACTIVE)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class MediaJobList(val jobs: List<MediaJob> = emptyList())
|
||||
|
||||
/**
|
||||
* A new file that was not made because something is already called that (409, `exists: true`):
|
||||
* the server's sentence. Nothing was written.
|
||||
*/
|
||||
class FileExists(message: String) : java.io.IOException(message)
|
||||
|
||||
/**
|
||||
* How an MCP server is signed in to: [kind] `none`, `secret` or `oauth`; [state] `ready`,
|
||||
* `signed_in`, `signed_out` or `needs_signin`. [account] is who the provider says signed in -- a
|
||||
* stranger's text, drawn as plain text. [signinUrl] is a page of the instance to open in a
|
||||
* browser, where the person signs in to the instance itself with its cookie: the app's token is
|
||||
* never part of it.
|
||||
*/
|
||||
@Serializable
|
||||
data class McpAuth(
|
||||
val kind: String = "none",
|
||||
val state: String = "ready",
|
||||
val shared: Boolean = false,
|
||||
val account: String = "",
|
||||
@SerialName("expires_at") val expiresAt: String? = null,
|
||||
val renews: Boolean = false,
|
||||
@SerialName("signin_url") val signinUrl: String? = null,
|
||||
) {
|
||||
/** The server's tools are not offered until somebody signs in. */
|
||||
val needsSignIn: Boolean get() = state == "signed_out" || state == "needs_signin"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServer(val id: String = "", val slug: String = "", val name: String = "", val tools: Int = 0, val auth: McpAuth = McpAuth()) {
|
||||
val label: String get() = name.ifBlank { slug.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class McpServerList(val servers: List<McpServer> = emptyList())
|
||||
|
||||
/**
|
||||
* The address the browser is sent to for a sign-in: always a page of the instance the app is
|
||||
* signed in to ([base]). An address on that origin is taken as it is; a path alone, or an
|
||||
* address the instance wrote with another name for itself, is that path on [base] -- so nothing
|
||||
* the list says can send the person to another host. Null for no address, or one that is no
|
||||
* http(s) page.
|
||||
*/
|
||||
fun signInAddress(base: String, url: String?): String? {
|
||||
val said = url?.trim().orEmpty()
|
||||
if (said.isEmpty()) return null
|
||||
val want = runCatching { java.net.URI(said) }.getOrNull() ?: return null
|
||||
val home = runCatching { java.net.URI(base) }.getOrNull() ?: return null
|
||||
if (want.scheme != null && want.scheme.lowercase() !in setOf("http", "https")) return null
|
||||
val path = want.rawPath.orEmpty()
|
||||
if (!path.startsWith("/") || path.startsWith("//")) return null
|
||||
|
||||
fun port(u: java.net.URI) = when {
|
||||
u.port >= 0 -> u.port
|
||||
u.scheme.equals("https", true) -> 443
|
||||
else -> 80
|
||||
}
|
||||
val same = want.scheme != null && want.scheme.equals(home.scheme, true) && want.host != null && want.host.equals(home.host, true) &&
|
||||
port(want) == port(home) && want.userInfo == null
|
||||
return if (same) said else base.trimEnd('/') + path + want.rawQuery?.let { "?$it" }.orEmpty()
|
||||
}
|
||||
|
||||
/** Which bytes of the instance are asked for: a file of the tree (or one version of it), a file by its id, or a chat's attachment. */
|
||||
sealed interface Raw {
|
||||
data class Path(val path: String, val version: String? = null) : Raw
|
||||
|
||||
/** A file by its node id, wherever it is now: what a generated file's result carries. */
|
||||
data class Node(val id: String) : Raw
|
||||
|
||||
/** A chat's attachment. Answered whole: a player gets a copy, not a stream. */
|
||||
data class Attached(val id: String) : Raw
|
||||
}
|
||||
@@ -33,6 +33,12 @@ data class Discovery(
|
||||
@SerialName("app_api") val appApi: Int = 0,
|
||||
val login: Login = Login(),
|
||||
val scopes: List<String> = emptyList(),
|
||||
/**
|
||||
* The oldest version of each client the instance works with, by product (`{"android": "1.0.0"}`).
|
||||
* Kept as whatever the document says -- read through [minClient], so that a shape this app
|
||||
* does not expect is "says nothing", never "not a LLeMbas instance".
|
||||
*/
|
||||
@SerialName("min_clients") val minClients: JsonElement? = null,
|
||||
) {
|
||||
@Serializable
|
||||
data class Login(val device: DeviceLogin = DeviceLogin())
|
||||
@@ -117,7 +123,29 @@ data class ModelInfo(
|
||||
val default: Boolean = false,
|
||||
/** Whether a new chat on this model is offered subagents (server 2.0.0-beta.7); null from an older one. */
|
||||
val subagents: SubagentsOffer? = null,
|
||||
/** On a connection whose terms allow interactive use only: never a schedule's model. */
|
||||
@SerialName("interactive_only") val interactiveOnly: Boolean = false,
|
||||
/**
|
||||
* The model's one unambiguous name, `provider/id` (server 2.0.0-beta.14): two connections may
|
||||
* serve one [id], which alone names only the first of them. Empty from an older server.
|
||||
*/
|
||||
val ref: String = "",
|
||||
val provider: String = "",
|
||||
/** The connection's name, for telling two models with one [id] apart. */
|
||||
val connection: String = "",
|
||||
/**
|
||||
* What the model is for (server 2.0.0-beta.17): `chat`, or a word for something a chat cannot
|
||||
* start on (`embedding`, and later `image`, `video`, …). A server that does not say it offers
|
||||
* only models to chat with.
|
||||
*/
|
||||
val capability: String = CHAT,
|
||||
) {
|
||||
/** Whether a chat can be on it: the one capability this app's pickers offer. An unknown word is not one. */
|
||||
val forChat: Boolean get() = capability == CHAT
|
||||
|
||||
/** What this model is chosen, kept and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
|
||||
/**
|
||||
* The levels, for a server that says them; an older one said only `efforts`, offered after
|
||||
* an `off` that meant "the model's default" -- as the app showed it before.
|
||||
@@ -149,9 +177,60 @@ data class ModelInfo(
|
||||
|
||||
companion object {
|
||||
val CONTROLS = setOf("none", "switch", "slider")
|
||||
const val CHAT = "chat"
|
||||
}
|
||||
}
|
||||
|
||||
/** The models a chat can be on, of a list: what every model picker and the assistant's model setting offer. */
|
||||
fun List<ModelInfo>.forChat(): List<ModelInfo> = filter { it.forChat }
|
||||
|
||||
/**
|
||||
* The model a name means, in a list: by its `ref`, else the first with that `id` -- which is
|
||||
* what a bare id names on the server too. So a name kept from before refs (a setting, a chat's
|
||||
* `model`, a schedule's) still finds its model.
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?): ModelInfo? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a kept name means when it is known how the name was said. A name the server said as
|
||||
* a `model_ref` ([isRef]) is looked up as a ref and nothing else: an id may itself hold a slash
|
||||
* (a model of an aggregator, `openai/gpt`), so a ref whose model has left the list could
|
||||
* otherwise "find" another connection's model that happens to be called that. A name of
|
||||
* unknown kind -- a setting, a pick -- goes through [named].
|
||||
*/
|
||||
fun List<ModelInfo>.named(name: String?, isRef: Boolean): ModelInfo? = if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* The model a chat, a reply or a schedule is on, in a list. The server says the id (`model`) and,
|
||||
* where it knows it, which connection serves it (`model_ref`). With a [ref] the model is the one
|
||||
* with that ref and no other: one that is not in the list is no model here, never "the first
|
||||
* with that id" -- that would name the wrong connection. Without one (an older server, or a
|
||||
* connection that is gone) the bare [id] is all there is.
|
||||
*/
|
||||
fun List<ModelInfo>.serving(ref: String?, id: String?): ModelInfo? = if (ref.isNullOrBlank()) named(id) else firstOrNull { it.ref == ref }
|
||||
|
||||
/** What such a thing's model is kept and sent by: its [ref] where the server says one, else its [id]; null for neither. */
|
||||
fun modelKey(ref: String?, id: String?): String? = ref?.ifBlank { null } ?: id?.ifBlank { null }
|
||||
|
||||
/**
|
||||
* The quiet line under a reply: the model's [id] as before, and its connection only where the
|
||||
* reply says which one ([ref]) and another model here shares the id. Null when there is no id.
|
||||
*/
|
||||
fun List<ModelInfo>.replyModel(ref: String?, id: String?): String? {
|
||||
val said = id?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return said
|
||||
return twinTitle(said, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A model's name in a list of [all]: with its connection where another model there shares its id. */
|
||||
fun ModelInfo.titleAmong(all: List<ModelInfo>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** "Name · Connection" for a model one of two that share an id ([twin]), where the connection has a name; else the name. */
|
||||
fun twinTitle(name: String, connection: String, twin: Boolean): String = if (twin && connection.isNotBlank()) "$name · $connection" else name
|
||||
|
||||
@Serializable
|
||||
data class ModelList(
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
@@ -159,7 +238,12 @@ data class ModelList(
|
||||
@SerialName("subagents_cap") val subagentsCap: Int? = null,
|
||||
/** With `kind=agent` (spec 3.4.0 §14): whether a new agent chat may have subagents. */
|
||||
@SerialName("agent_subagents") val agentSubagents: AgentSubagents? = null,
|
||||
)
|
||||
/** With `kind=agent`, a device and a directory (spec 3.9.0): the model a new agent chat there starts on. */
|
||||
val start: StartModel? = null,
|
||||
) {
|
||||
/** The same answer with only the models a chat can be on. */
|
||||
fun forChat(): ModelList = if (models.all { it.forChat }) this else copy(models = models.forChat())
|
||||
}
|
||||
|
||||
/**
|
||||
* A new agent chat's Subagents fact (`/models?kind=agent&device=`): [offered] where the instance
|
||||
@@ -243,6 +327,14 @@ data class Mention(val kind: String = "", val id: String = "", val path: String
|
||||
@Serializable
|
||||
data class Mentions(val items: List<Mention> = emptyList())
|
||||
|
||||
/** A file or directory on a linked device, by its [path] from the chat's directory ([kind] `file` or `dir`). */
|
||||
@Serializable
|
||||
data class DeviceFile(val path: String = "", val kind: String = "", val name: String = "")
|
||||
|
||||
/** What `@` offers in an agent chat (`GET /devices/{id}/files`): the device's files; one that cannot answer offers none and may say why. */
|
||||
@Serializable
|
||||
data class DeviceFiles(val files: List<DeviceFile> = emptyList(), val error: String = "", val device: String = "")
|
||||
|
||||
@Serializable
|
||||
data class ServerChannel(val version: String = "", val channel: String = "")
|
||||
|
||||
@@ -288,7 +380,27 @@ data class FolderList(val folders: List<Folder> = emptyList())
|
||||
data class Device(@SerialName("token_id") val tokenId: String? = null, val directory: String = "")
|
||||
|
||||
@Serializable
|
||||
data class LinkedDevice(val id: String, val name: String = "", val host: String = "", val platform: String = "")
|
||||
data class LinkedDevice(
|
||||
val id: String,
|
||||
val name: String = "",
|
||||
val host: String = "",
|
||||
val platform: String = "",
|
||||
/** Whether the device accepts scheduled work: only then may an Agentic schedule belong to it. */
|
||||
val scheduled: Boolean = false,
|
||||
/** The widest mode the device lets a scheduled run have; empty where it accepts none. */
|
||||
@SerialName("max_mode") val maxMode: String = "",
|
||||
/** Whether the device remembers the model last used in a directory (spec 3.9.0). */
|
||||
@SerialName("directory_model") val directoryModel: Boolean = false,
|
||||
/** Whether the device hands its files over the link at all (spec 3.11.0, `fs`). Parsed; no screen reads it yet. */
|
||||
val files: Boolean = false,
|
||||
/** False where its highest mode is plan: its files can be read and not changed. */
|
||||
@SerialName("files_writable") val filesWritable: Boolean = false,
|
||||
/** Whether the device lets files that run code (git's own, an agent's configuration) be changed from here. */
|
||||
@SerialName("files_that_run_code") val filesThatRunCode: Boolean = false,
|
||||
) {
|
||||
/** What to call it: its name, else its host. */
|
||||
val label: String get() = name.ifBlank { host.ifBlank { id } }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class DeviceList(val devices: List<LinkedDevice> = emptyList())
|
||||
@@ -299,6 +411,8 @@ data class Chat(
|
||||
val kind: String = "chat",
|
||||
val title: String = "",
|
||||
val model: String = "",
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or when that connection is gone. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
@SerialName("folder_id") val folderId: String? = null,
|
||||
val pinned: Boolean = false,
|
||||
val archived: Boolean = false,
|
||||
@@ -326,6 +440,9 @@ data class Chat(
|
||||
) {
|
||||
val isAgent: Boolean get() = kind == "agent"
|
||||
|
||||
/** The chat's model as it is looked up and sent: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
|
||||
fun allows(control: String): Boolean = controls?.contains(control) ?: true
|
||||
}
|
||||
|
||||
@@ -348,6 +465,16 @@ data class ChatPage(val chats: List<Chat> = emptyList(), val more: Boolean = fal
|
||||
@Serializable
|
||||
data class ChatDetail(val chat: Chat, val messages: List<Message> = emptyList(), val more: Boolean = false, val live: String? = null)
|
||||
|
||||
/**
|
||||
* `GET /events`, frame `reply`: a reply started in the chat [chatId] -- whoever started it, this
|
||||
* app's own too -- and, with [live] false, that it is over (`event_reply_end.json`): once per
|
||||
* reply, however it ended; a reply shorter than the news of its start is said by that one frame
|
||||
* alone. [messageId] is the reply's row. An event, not a state: a start is said once (and, on a
|
||||
* connection just opened, for every reply being written then), an end once and never again.
|
||||
*/
|
||||
@Serializable
|
||||
data class ReplyFrame(@SerialName("chat_id") val chatId: String = "", @SerialName("message_id") val messageId: String = "", val live: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class MessagePage(val messages: List<Message> = emptyList(), val more: Boolean = false)
|
||||
|
||||
@@ -430,6 +557,10 @@ data class ToolCall(
|
||||
val show: ShowCard? = null,
|
||||
/** `image_generate`'s picture: the server's own attachment, by id, and its size. */
|
||||
val image: GeneratedImage? = null,
|
||||
/** The file the call made (a picture, video, music, a 3D model), which is in the person's Files. */
|
||||
val media: GeneratedMedia? = null,
|
||||
/** A generation that takes minutes: the job the call started, as it was when the call returned. */
|
||||
@SerialName("media_job") val mediaJob: MediaJobRef? = null,
|
||||
val block: ToolBlock = ToolBlock(),
|
||||
)
|
||||
|
||||
@@ -483,6 +614,12 @@ data class FileEntry(
|
||||
val name: String = "",
|
||||
val path: String = "",
|
||||
val kind: String = "file",
|
||||
/**
|
||||
* What the file is, read by the server from its name and its own bytes: `markdown`, `code`,
|
||||
* `text`, `html`, `image`, `svg`, `pdf`, `audio`, `video`, `table`, `notebook`, `model3d`,
|
||||
* `archive` or `binary`. Null for a folder, and from a server that does not say it.
|
||||
*/
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
@SerialName("updated_at") val updatedAt: String? = null,
|
||||
@@ -493,7 +630,13 @@ data class FileEntry(
|
||||
|
||||
/** 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())
|
||||
data class FileListing(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
/** After a copy: the new entry, under the name the server gave it (a taken name is numbered). */
|
||||
val copied: FileEntry? = null,
|
||||
)
|
||||
|
||||
/** Why a file's text did not come: `reason` is `not_text` or `too_large`; `message` says it. */
|
||||
@Serializable
|
||||
@@ -510,10 +653,17 @@ data class FileContent(
|
||||
val size: Long = 0,
|
||||
val mime: String = "",
|
||||
val kind: String = "text",
|
||||
/** What the file is ([FileEntry.fileKind]); null from a server that does not say it. */
|
||||
@SerialName("file_kind") val fileKind: String? = null,
|
||||
/** Whether the person may change it; null from a server that does not say (then: no editing). */
|
||||
val writable: Boolean? = null,
|
||||
val language: String = "",
|
||||
/** What the file holds now: sent back as a save's `base`, so a save over somebody else's change is refused. */
|
||||
val sha: String = "",
|
||||
val text: String = "",
|
||||
val withheld: Withheld? = null,
|
||||
/** What is inside an archive, as far as the instance lists it; null for every other kind and from a server that does not say. */
|
||||
val archive: ArchiveListing? = 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"
|
||||
@@ -571,6 +721,8 @@ data class Message(
|
||||
val machine: Boolean = false,
|
||||
val origin: String = "",
|
||||
val model: String? = null,
|
||||
/** Which connection wrote this reply (see [Chat.modelRef]). */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val attachments: List<Attachment> = emptyList(),
|
||||
val text: String? = null,
|
||||
val steps: List<Step> = emptyList(),
|
||||
@@ -585,6 +737,10 @@ data class Message(
|
||||
@Serializable
|
||||
data class Turn(val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
/** The answer to discarding a waiting message: the row that is gone, by its id. */
|
||||
@Serializable
|
||||
data class Discarded(val id: String = "", val discarded: Boolean = false)
|
||||
|
||||
@Serializable
|
||||
data class NewChat(val chat: Chat, val message: Message? = null, val reply: Message? = null)
|
||||
|
||||
@@ -621,8 +777,40 @@ data class CardItem(
|
||||
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
|
||||
*/
|
||||
val phone: JsonObject? = null,
|
||||
/** An edit's changes, one per file (`contract/event_ask_edit.json`); empty on a card without them. */
|
||||
val diffs: List<FileDiff> = emptyList(),
|
||||
)
|
||||
|
||||
/**
|
||||
* What an edit would do to one file, on its approval card: [oldText] is null for a file that is
|
||||
* made, [deleted] marks one that goes. Both texts are a model's and a file's words: drawn as
|
||||
* text by the app's own diff view (`api/Diff.kt`), never rendered.
|
||||
*/
|
||||
@Serializable
|
||||
data class FileDiff(
|
||||
val path: String = "",
|
||||
@SerialName("old_text") val oldText: String? = null,
|
||||
@SerialName("new_text") val newText: String = "",
|
||||
val deleted: Boolean = false,
|
||||
) {
|
||||
/** A file that does not exist yet. */
|
||||
val made: Boolean get() = oldText == null && !deleted
|
||||
}
|
||||
|
||||
/**
|
||||
* A person's two models for an editor (`GET /editor`, `contract/editor.json`): parsed so the
|
||||
* shape is pinned; this app has no screen for them.
|
||||
*/
|
||||
@Serializable
|
||||
data class EditorModels(val autocomplete: Autocomplete = Autocomplete(), val main: Main = Main()) {
|
||||
/** [source]: `person`, `instance` or null with no model. [allowed]: the refs an administrator allows, null for any. */
|
||||
@Serializable
|
||||
data class Autocomplete(val model: String? = null, val source: String? = null, val allowed: List<String>? = null)
|
||||
|
||||
@Serializable
|
||||
data class Main(val model: String? = null)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
data class CardSubagent(val id: String = "", val name: String = "", val position: String = "")
|
||||
|
||||
@@ -677,6 +865,31 @@ data class PushKey(val key: String = "", val registered: Boolean = false)
|
||||
@Serializable
|
||||
data class Transcript(val text: String = "")
|
||||
|
||||
/**
|
||||
* Which chat a recording or a reading is for: the chat's own id, or -- for a chat that does not
|
||||
* exist yet -- the model it will be on. The instance serves it from that model's connection
|
||||
* where the connection has speech models of its own; with neither ([DEFAULT]) from its default.
|
||||
* Never both: a chat that exists says its model itself.
|
||||
*/
|
||||
data class MediaFor(val chatId: String? = null, val chatModel: String? = null) {
|
||||
companion object {
|
||||
/** No chat: another app's dictation. */
|
||||
val DEFAULT = MediaFor()
|
||||
|
||||
fun of(chatId: String?, model: String?): MediaFor = when {
|
||||
!chatId.isNullOrBlank() -> MediaFor(chatId = chatId)
|
||||
!model.isNullOrBlank() -> MediaFor(chatModel = model)
|
||||
else -> DEFAULT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A recording written down; [fallback] names the source that answered when the chat's own did not. */
|
||||
data class Heard(val text: String, val fallback: String? = null)
|
||||
|
||||
/** Words as sound (mp3); [fallback] as [Heard]'s. */
|
||||
class Spoken(val audio: ByteArray, val fallback: String? = null)
|
||||
|
||||
// --- The stream's frames -----------------------------------------------------------------
|
||||
@Serializable
|
||||
data class Tail(val thinking: String = "", val text: String = "", val label: String = "")
|
||||
|
||||
@@ -11,13 +11,20 @@ import kotlinx.serialization.json.JsonObject
|
||||
// `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. */
|
||||
/**
|
||||
* The model a run used, and how it came to it ([reason]): `pinned` (the schedule's own),
|
||||
* `switched` (it stood in for [switchedFrom], which was busy), `directory` (the folder's usual
|
||||
* model, asked of the computer), `default` (the person's default, where the folder had none) or
|
||||
* `session` (a continued conversation kept its own).
|
||||
*/
|
||||
@Serializable
|
||||
data class RunModel(
|
||||
val id: String? = null,
|
||||
val name: String? = null,
|
||||
val reason: String? = null,
|
||||
@SerialName("switched_from") val switchedFrom: String? = null,
|
||||
/** Which connection served the run (`provider/model`); null from an older server. */
|
||||
val ref: String? = null,
|
||||
) {
|
||||
/** What to call it: its name, else its id. */
|
||||
val label: String? get() = name ?: id
|
||||
@@ -29,9 +36,13 @@ 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. */
|
||||
/**
|
||||
* Why a run failed or waits: [kind] a class the app may read, [text] the sentence to show (the
|
||||
* server's, or the device's own), and [reason] a narrower word where there is one -- `terminal`:
|
||||
* the schedule's session was open in a terminal on the computer.
|
||||
*/
|
||||
@Serializable
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "")
|
||||
data class RunError(@SerialName("class") val kind: String = "", val text: String = "", val reason: String? = null)
|
||||
|
||||
/**
|
||||
* One run of a schedule: when it was due and how it went. [status] is `running`, `waiting` (no
|
||||
@@ -72,6 +83,8 @@ data class ScheduleRun(
|
||||
val note: String = "",
|
||||
/** The report this run filed, when it filed one: its id (or an object carrying it). */
|
||||
val report: JsonElement? = null,
|
||||
/** Where an Agentic schedule's run ran (spec 3.9.0); null for a Chat schedule's, or from an older server. */
|
||||
@SerialName("ran_on") val ranOn: RanOn? = null,
|
||||
) {
|
||||
val reportId: String? get() = idOf(report)
|
||||
}
|
||||
@@ -104,6 +117,8 @@ data class Schedule(
|
||||
@SerialName("catch_up") val catchUp: String = "",
|
||||
@SerialName("grace_minutes") val graceMinutes: Int? = null,
|
||||
val model: String? = null,
|
||||
/** Which connection serves [model] (`provider/model`); null from an older server, or with no model of its own. */
|
||||
@SerialName("model_ref") val modelRef: String? = null,
|
||||
val effort: String? = null,
|
||||
val agents: Int? = null,
|
||||
val tools: List<String> = emptyList(),
|
||||
@@ -121,6 +136,9 @@ data class Schedule(
|
||||
@SerialName("created_at") val createdAt: String? = null,
|
||||
) {
|
||||
val paused: Boolean get() = !enabled
|
||||
|
||||
/** The schedule's model as a form holds and sends it: its ref, else its id. */
|
||||
val modelKey: String? get() = modelKey(modelRef, model)
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@@ -185,15 +203,55 @@ data class SchedulingModel(
|
||||
val free: Boolean = false,
|
||||
val busy: String? = null,
|
||||
val chosen: Boolean = true,
|
||||
)
|
||||
/** The model's unambiguous name (`provider/id`) and its connection's, as on every model object. */
|
||||
val ref: String = "",
|
||||
val connection: String = "",
|
||||
) {
|
||||
/** What a schedule's model is chosen and sent by: its [ref], or its [id] from a server without refs. */
|
||||
val key: String get() = ref.ifBlank { id }
|
||||
}
|
||||
|
||||
/** The scheduling model a name means: by its `ref`, else the first with that `id`. */
|
||||
fun List<SchedulingModel>.named(name: String?): SchedulingModel? {
|
||||
if (name.isNullOrBlank()) return null
|
||||
return firstOrNull { it.ref == name } ?: firstOrNull { it.id == name }
|
||||
}
|
||||
|
||||
/** The same when it is known that the server said the name as a `model_ref` ([isRef]): then by ref alone, never by an id that looks like it. */
|
||||
fun List<SchedulingModel>.named(name: String?, isRef: Boolean): SchedulingModel? =
|
||||
if (isRef) firstOrNull { !name.isNullOrBlank() && it.ref == name } else named(name)
|
||||
|
||||
/**
|
||||
* What a schedule's or a run's model is called among [this] list: [said] (the id or the name
|
||||
* the server gave), and its connection where the server says which one ([ref]) and another
|
||||
* model in the list shares the id. A ref the list does not have leaves [said] as it is.
|
||||
*/
|
||||
fun List<SchedulingModel>.saidWithConnection(ref: String?, said: String?): String? {
|
||||
val word = said?.ifBlank { null } ?: return null
|
||||
val model = firstOrNull { !ref.isNullOrBlank() && it.ref == ref } ?: return word
|
||||
return twinTitle(word, model.connection, count { it.id == model.id } > 1)
|
||||
}
|
||||
|
||||
/** A scheduling model's name in a list of [all]: with its connection where another there shares its id. */
|
||||
fun SchedulingModel.titleAmong(all: List<SchedulingModel>): String = twinTitle(name.ifBlank { id }, connection, all.count { it.id == id } > 1)
|
||||
|
||||
/** `GET`/`PUT /schedules/models`: the models, the instance's order, and the person's narrowing. */
|
||||
@Serializable
|
||||
data class SchedulingModels(val models: List<SchedulingModel> = emptyList(), val instance: List<String> = emptyList(), val mine: List<String> = emptyList())
|
||||
|
||||
/** What a watching schedule looks at before each run: [kind] `url` and the address. */
|
||||
/**
|
||||
* What a watching schedule looks at before each run: [kind] `url` and the address, or -- on a
|
||||
* linked computer -- `command`, the [command] run in the schedule's folder and how many seconds
|
||||
* it may take ([timeoutS]). [target] is either, as one string.
|
||||
*/
|
||||
@Serializable
|
||||
data class ScheduleWatch(val kind: String = "", val target: String = "", @SerialName("changed_at") val changedAt: String? = null)
|
||||
data class ScheduleWatch(
|
||||
val kind: String = "",
|
||||
val target: String = "",
|
||||
val command: String = "",
|
||||
@SerialName("timeout_s") val timeoutS: Int? = null,
|
||||
@SerialName("changed_at") val changedAt: String? = null,
|
||||
)
|
||||
|
||||
/** One run's look: whether the address [changed] since the last one, or why the look failed. */
|
||||
@Serializable
|
||||
@@ -235,5 +293,31 @@ data class RunsOn(
|
||||
@SerialName("approval_wait_minutes") val approvalWaitMinutes: Int? = null,
|
||||
)
|
||||
|
||||
/** Where one run ran: the computer ([deviceName]), the folder there and the mode it had. */
|
||||
@Serializable
|
||||
data class RanOn(val device: String = "", @SerialName("device_name") val deviceName: String = "", val cwd: String = "", val mode: String = "")
|
||||
|
||||
/** The two types of schedule (spec 3.9.0). There is no field for it: Agentic is one with a computer. */
|
||||
val Schedule.agentic: Boolean get() = runsOn != null
|
||||
|
||||
/** A run that waits because its computer is not linked (`error.class` `device_away`). */
|
||||
val ScheduleRun.computerAway: Boolean get() = error?.kind == "device_away"
|
||||
|
||||
/**
|
||||
* What a save says about where a schedule runs, which is its type: nothing ([Leave]), on the
|
||||
* server ([Server]: Chat), or on a computer ([Computer]: Agentic) -- in a folder there, in a
|
||||
* mode, with an approval's wait in minutes (null: the server's default).
|
||||
*/
|
||||
sealed interface WhereToRun {
|
||||
data object Leave : WhereToRun
|
||||
|
||||
data object Server : WhereToRun
|
||||
|
||||
data class Computer(val device: String, val cwd: String, val mode: String, val approvalWaitMinutes: Int?) : WhereToRun
|
||||
}
|
||||
|
||||
/**
|
||||
* The command an Agentic schedule watches before each run, as a save says it: the [command]
|
||||
* (empty: watch nothing) and how many seconds it may take (null: the server's own).
|
||||
*/
|
||||
data class WatchCommand(val command: String, val timeoutS: Int?)
|
||||
@@ -17,77 +17,70 @@ data class Frame(val event: String, val data: String)
|
||||
|
||||
/**
|
||||
* Follow a reply: the stream's frames, and when the connection drops before `close`, the same
|
||||
* stream opened again after a pause -- 1, 2, 4, 8 … up to 30 seconds. Nothing is replayed or
|
||||
* stream opened again after a pause -- the one schedule of [Reconnect]. Nothing is replayed or
|
||||
* deduplicated: the server's first pass after a reconnect is the whole state, which is exactly
|
||||
* what [LiveReply.apply] wants.
|
||||
*
|
||||
* A refusal (a 4xx: the chat was deleted, the token signed out) ends the flow with the error;
|
||||
* only a broken connection is retried.
|
||||
* only a broken connection is retried, and a 429, which is "later" rather than "no" -- and each
|
||||
* opening after the first is a new request, so it waits for its `turn` (the gate: nothing new is
|
||||
* asked behind a lock).
|
||||
*
|
||||
* Silence is a broken connection too. Every stream this app follows (a reply's, the person's
|
||||
* events, a chat's activity) is sent a keepalive by the server at least every 15 seconds, so a
|
||||
* connection that says nothing for [SILENCE_SECONDS] is dead without having said so -- a phone
|
||||
* that changed network, a proxy that dropped it -- and is opened again like any other.
|
||||
*/
|
||||
class StreamClient(private val api: ApiClient) {
|
||||
private val http = api.http.newBuilder().readTimeout(0, TimeUnit.SECONDS).build()
|
||||
private val http = api.http.newBuilder().readTimeout(SILENCE_SECONDS, TimeUnit.SECONDS).build()
|
||||
|
||||
fun follow(chatId: String, messageId: String): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
once(api.streamRequest(chatId, messageId)).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
}
|
||||
}
|
||||
fun follow(chatId: String, messageId: String, turn: suspend () -> Unit = {}): Flow<Frame> = reopened(turn) { once(api.streamRequest(chatId, messageId)) }
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* activity panel's does): opened again at once after a `close`, and after a pause
|
||||
* ([Reconnect]) when the connection drops or closes without a frame. It runs until
|
||||
* its collector stops; a refusal (4xx) ends it with the error. Each opening, the first
|
||||
* too, waits for its [turn].
|
||||
*/
|
||||
fun watch(request: () -> Request): Flow<Frame> = flow {
|
||||
var wait = 1_000L
|
||||
fun watch(turn: suspend () -> Unit = {}, request: () -> Request): Flow<Frame> = flow {
|
||||
val schedule = Reconnect()
|
||||
while (true) {
|
||||
var closed = false
|
||||
var said = false
|
||||
var refused: ApiException? = null
|
||||
var since: Long? = null
|
||||
var slowed = 0L
|
||||
// Every opening is a request of its own: it waits for its turn (the gate).
|
||||
turn()
|
||||
once(request()).collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
wait = 1_000L
|
||||
if (result.frame.event == "close") closed = true else emit(result.frame)
|
||||
if (result.frame.event == "close") {
|
||||
closed = true
|
||||
} else {
|
||||
said = true
|
||||
if (since == null) since = monotonicMs()
|
||||
emit(result.frame)
|
||||
}
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Slowed -> slowed = result.seconds
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) continue
|
||||
delay(wait)
|
||||
wait = (wait * 2).coerceAtMost(30_000L)
|
||||
// A route that closes after it has said something is opened again at once. One
|
||||
// that closes having said nothing waits as a dropped one does: a server that only
|
||||
// ever answers `close` must not be asked in a tight loop.
|
||||
if (reopenAtOnce(closed, said)) continue
|
||||
delay(schedule.pause(healthyMs = since?.let { monotonicMs() - it } ?: 0L, retryAfterMs = slowed * 1000L))
|
||||
}
|
||||
}
|
||||
|
||||
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(request: Request): Flow<Outcome> = callbackFlow {
|
||||
val source = EventSources.createFactory(http).newEventSource(
|
||||
request,
|
||||
@@ -103,7 +96,10 @@ class StreamClient(private val api: ApiClient) {
|
||||
|
||||
override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
|
||||
val code = response?.code ?: 0
|
||||
if (code in 400..499) {
|
||||
if (code == 429) {
|
||||
// "Later", not "no": opened again, after what the server asked for.
|
||||
trySend(Outcome.Slowed(retryAfterSeconds(response?.header("Retry-After")) ?: 0L))
|
||||
} else if (code in 400..499) {
|
||||
trySend(Outcome.Refused(ApiException(code, response?.let { detail(it) } ?: "Refused ($code).")))
|
||||
} else {
|
||||
trySend(Outcome.Dropped)
|
||||
@@ -114,4 +110,65 @@ class StreamClient(private val api: ApiClient) {
|
||||
)
|
||||
awaitClose { source.cancel() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* How long a stream may say nothing before it counts as broken. The server's keepalive
|
||||
* comes every 15 seconds on each of the three routes followed here; three of them missed
|
||||
* is not a slow server.
|
||||
*/
|
||||
const val SILENCE_SECONDS = 45L
|
||||
}
|
||||
}
|
||||
|
||||
/** A clock that only goes forward, in milliseconds: for how long a connection lasted. */
|
||||
fun monotonicMs(): Long = System.nanoTime() / 1_000_000L
|
||||
|
||||
/**
|
||||
* What one opening of a stream gave: a frame, a refusal (4xx), a "too many requests" (429, with
|
||||
* the seconds its `Retry-After` asked for, 0 when it named none), or a connection that broke.
|
||||
*/
|
||||
sealed interface Outcome {
|
||||
data class Event(val frame: Frame) : Outcome
|
||||
data class Refused(val error: ApiException) : Outcome
|
||||
data class Slowed(val seconds: Long) : Outcome
|
||||
data object Dropped : Outcome
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply's stream, [open]ed again whenever it ends before `close`: after a pause by [schedule]
|
||||
* (1 second doubling to 60, jittered, and short again only after a connection that held for half
|
||||
* a minute by [clock]), and after its [turn] -- every opening but the first is a request nobody
|
||||
* is waiting for at that moment, so it asks first whether it may start. A refusal ends the flow
|
||||
* with the error.
|
||||
*/
|
||||
fun reopened(turn: suspend () -> Unit, schedule: Reconnect = Reconnect(), clock: () -> Long = ::monotonicMs, open: () -> Flow<Outcome>): Flow<Frame> = flow {
|
||||
while (true) {
|
||||
var closed = false
|
||||
var refused: ApiException? = null
|
||||
var since: Long? = null
|
||||
var slowed = 0L
|
||||
open().collect { result ->
|
||||
when (result) {
|
||||
is Outcome.Event -> {
|
||||
if (since == null) since = clock()
|
||||
emit(result.frame)
|
||||
if (result.frame.event == "close") closed = true
|
||||
}
|
||||
|
||||
is Outcome.Refused -> refused = result.error
|
||||
|
||||
is Outcome.Slowed -> slowed = result.seconds
|
||||
|
||||
is Outcome.Dropped -> Unit
|
||||
}
|
||||
}
|
||||
refused?.let { throw it }
|
||||
if (closed) return@flow
|
||||
delay(schedule.pause(healthyMs = since?.let { clock() - it } ?: 0L, retryAfterMs = slowed * 1000L))
|
||||
turn()
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an events route that ended is opened again without a pause: only one that [closed] itself after it [said] something. */
|
||||
fun reopenAtOnce(closed: Boolean, said: Boolean): Boolean = closed && said
|
||||
@@ -3,10 +3,13 @@ package eu.llembas.android.assist
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
@@ -14,6 +17,7 @@ import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.auth.Prefs
|
||||
@@ -22,6 +26,9 @@ import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.WakeWordService
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.launch
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/** What a way into the sheet asks for. */
|
||||
@@ -34,30 +41,64 @@ enum class Opening {
|
||||
companion object {
|
||||
/**
|
||||
* A headset's voice button sends `VOICE_COMMAND` (or, locked, `VOICE_SEARCH_HANDS_FREE`):
|
||||
* the person means to speak, so the sheet opens listening whatever Settings says.
|
||||
* the person means to speak, so the sheet opens listening whatever Settings says. Those
|
||||
* two are Android's, and anybody's to send. The app's own ways in -- listening for the
|
||||
* widget's microphone and the wake word, the last chat -- count only on an intent the
|
||||
* app made itself ([own], [OwnIntents]); from anyone else they are just the sheet.
|
||||
*/
|
||||
fun of(intent: Intent): Opening = when {
|
||||
intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false) -> Listen
|
||||
intent.action == AssistActivity.ACTION_CONTINUE -> Continue
|
||||
intent.action in LISTENING -> Listen
|
||||
fun of(action: String?, listenExtra: Boolean, own: Boolean): Opening = when {
|
||||
own && listenExtra -> Listen
|
||||
own && action == AssistActivity.ACTION_CONTINUE -> Continue
|
||||
own && action == AssistActivity.ACTION_LISTEN -> Listen
|
||||
action in PUBLIC_LISTENING -> Listen
|
||||
else -> Sheet
|
||||
}
|
||||
|
||||
private val LISTENING = setOf(
|
||||
AssistActivity.ACTION_LISTEN,
|
||||
Intent.ACTION_VOICE_COMMAND,
|
||||
"android.speech.action.VOICE_SEARCH_HANDS_FREE",
|
||||
)
|
||||
fun of(intent: Intent, own: Boolean): Opening = of(intent.action, own && intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false), own)
|
||||
|
||||
private val PUBLIC_LISTENING = setOf(Intent.ACTION_VOICE_COMMAND, "android.speech.action.VOICE_SEARCH_HANDS_FREE")
|
||||
}
|
||||
}
|
||||
|
||||
/** How the sheet starts, given whether the phone is locked. */
|
||||
enum class LockedStart {
|
||||
/** Not locked: do what the way in asked for. */
|
||||
Go,
|
||||
|
||||
/** Locked, and the way in means to speak: stay over the lock screen and listen; what is heard waits for the unlock. */
|
||||
Listen,
|
||||
|
||||
/** Locked, with a question handed over: it is shown and waits for the unlock. */
|
||||
Hold,
|
||||
|
||||
/** Locked, anything else: ask Android to unlock first; the sheet goes if that is turned down. */
|
||||
Unlock,
|
||||
}
|
||||
|
||||
/**
|
||||
* What a sheet opened while the phone is [locked] does. The wake word with the screen off, and a
|
||||
* headset's button, open it listening ([Opening.Listen]) and nobody is there to unlock: asking
|
||||
* Android to unlock first -- and closing when that is cancelled, which is what happens when
|
||||
* nobody answers the lock screen -- showed the sheet for a moment and took it away again. So it
|
||||
* stays and listens, and only *sending* waits for the unlock. Without the microphone's
|
||||
* permission there is nothing to listen with, and its prompt needs the phone unlocked anyway.
|
||||
*/
|
||||
fun lockedStart(locked: Boolean, opening: Opening, question: Boolean, micAllowed: Boolean): LockedStart = when {
|
||||
!locked -> LockedStart.Go
|
||||
question -> LockedStart.Hold
|
||||
opening == Opening.Listen && micAllowed -> LockedStart.Listen
|
||||
else -> LockedStart.Unlock
|
||||
}
|
||||
|
||||
/**
|
||||
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
|
||||
* `ACTION_ASSIST` open, and where the voice-interaction session hands 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.
|
||||
* anything -- and shows nothing from the account until then. Opened there to listen (the wake
|
||||
* word, a headset's button) it stays up and listens; the question it heard is shown and waits
|
||||
* for the unlock ([lockedStart]).
|
||||
*/
|
||||
class AssistActivity : ComponentActivity() {
|
||||
private lateinit var controller: AssistController
|
||||
@@ -65,12 +106,38 @@ class AssistActivity : ComponentActivity() {
|
||||
private var started = false
|
||||
private var byWake = false
|
||||
|
||||
/** The screen went off since the sheet was last seen: on the way back, the lock is looked at again. */
|
||||
private var wentOff = false
|
||||
|
||||
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
|
||||
private val locked = mutableStateOf(false)
|
||||
private val mic = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||
if (granted) controller.listen()
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone was unlocked by the person themselves (a fingerprint while the sheet is up): the
|
||||
* question that waited is sent. And the screen went off: the microphone and the voice stop
|
||||
* at once, whatever the lock says yet, and nothing of the conversation is left in the
|
||||
* picture the phone keeps of the sheet; a sheet that was over the lock screen goes, so that
|
||||
* it is not what the phone shows when it is next picked up.
|
||||
*/
|
||||
private val screen = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
Intent.ACTION_USER_PRESENT -> unlockedNow()
|
||||
|
||||
Intent.ACTION_SCREEN_OFF -> {
|
||||
val overLock = locked.value
|
||||
wentOff = true
|
||||
if (keyguard.isKeyguardLocked) controller.lockedNow() else controller.screenOff()
|
||||
locked.value = true
|
||||
if (overLock) finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
@@ -80,10 +147,39 @@ class AssistActivity : ComponentActivity() {
|
||||
controller = AssistController(this, lifecycleScope)
|
||||
keyguard = getSystemService(KeyguardManager::class.java)
|
||||
locked.value = keyguard.isKeyguardLocked
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
screen,
|
||||
IntentFilter().apply {
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
},
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
// A question waits for the unlock: Android is asked for it at once (a face or a
|
||||
// fingerprint is then enough), and the sheet stays if nobody answers.
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.held }.distinctUntilChanged().collect { held ->
|
||||
if (held && locked.value) askToUnlock()
|
||||
}
|
||||
}
|
||||
// The lock screen turns the display off after a few seconds: not in the middle of a
|
||||
// question, and not in the middle of an answer read aloud (the screen going off stops it).
|
||||
lifecycleScope.launch {
|
||||
controller.state.map { it.listening || it.busy || it.speaking }.distinctUntilChanged().collect { on ->
|
||||
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
}
|
||||
}
|
||||
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
|
||||
// so nothing else has woken the phone).
|
||||
woken(intent)
|
||||
take(intent)
|
||||
// Once: made again by Android (after the app was put away and brought back), the sheet
|
||||
// must not ask the same question a second time. What waited for the unlock is kept.
|
||||
if (savedInstanceState == null) {
|
||||
take(intent)
|
||||
} else {
|
||||
savedInstanceState.getString(STATE_WAITING)?.let { controller.hold(Held(it, null, savedInstanceState.getBoolean(STATE_SPOKEN))) }
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
LembasTheme(prefs.theme) {
|
||||
@@ -91,15 +187,13 @@ class AssistActivity : ComponentActivity() {
|
||||
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)
|
||||
}
|
||||
},
|
||||
)
|
||||
// Typed over the lock screen: held (in the place of a question that
|
||||
// waited already), so that whichever way the unlock is heard of first,
|
||||
// one question is asked, once.
|
||||
val waited = controller.state.value.held
|
||||
if (text.isNotBlank()) controller.ask(text)
|
||||
// A first held question asks Android to unlock by itself (onCreate).
|
||||
if (waited || text.isBlank()) askToUnlock { if (text.isBlank()) controller.opened() }
|
||||
},
|
||||
onOpenApp = {
|
||||
startActivity(controller.appIntent())
|
||||
@@ -107,6 +201,7 @@ class AssistActivity : ComponentActivity() {
|
||||
},
|
||||
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
|
||||
onDismiss = { finish() },
|
||||
onUnlock = { askToUnlock() },
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -128,7 +223,7 @@ class AssistActivity : ComponentActivity() {
|
||||
* the assistant's own sheet can take its place if that one comes after all.
|
||||
*/
|
||||
private fun woken(intent: Intent?) {
|
||||
byWake = intent?.getBooleanExtra(EXTRA_WAKE, false) == true
|
||||
byWake = OwnIntents.isOwn(this, intent) && intent?.getBooleanExtra(EXTRA_WAKE, false) == true
|
||||
if (byWake) setTurnScreenOn(true)
|
||||
}
|
||||
|
||||
@@ -140,6 +235,16 @@ class AssistActivity : ComponentActivity() {
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
started = true
|
||||
// The phone may have locked, or been unlocked, while the sheet was out of sight.
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
// Found locked: the controller is told, unless the sheet was opened over the lock
|
||||
// screen in the first place (and is listening there).
|
||||
if (!locked.value || wentOff) controller.lockedNow()
|
||||
locked.value = true
|
||||
} else {
|
||||
unlockedNow()
|
||||
}
|
||||
wentOff = false
|
||||
open = WeakReference(this)
|
||||
AssistPresence.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
@@ -155,29 +260,41 @@ class AssistActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
/**
|
||||
* What the way in asked for: a question handed over by the session, listening (the headset's
|
||||
* voice button, the widget's microphone, the Speak shortcut), the last assistant chat (the
|
||||
* widget, the shortcut), or just the sheet. Over the lock screen each waits for Android to
|
||||
* unlock first.
|
||||
* What the way in asked for: a question handed over by the session ([AssistHandOff]),
|
||||
* listening (the headset's voice button, the widget's microphone, the Speak shortcut, the
|
||||
* wake word), the last assistant chat (the widget, the shortcut), or just the sheet. Over
|
||||
* the lock screen: [lockedStart]. Only an intent the app made itself ([OwnIntents]) can
|
||||
* hand over a question or ask for more than Android's own actions do.
|
||||
*/
|
||||
private fun take(intent: Intent) {
|
||||
val opening = Opening.of(intent)
|
||||
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
|
||||
val own = OwnIntents.isOwn(this, intent)
|
||||
val opening = Opening.of(intent, own)
|
||||
val handed = if (own) AssistHandOff.take(intent.getStringExtra(EXTRA_HANDOFF)) else null
|
||||
val go = {
|
||||
when {
|
||||
waiting.isNotBlank() -> controller.ask(waiting)
|
||||
handed != null -> controller.hold(handed)
|
||||
opening == Opening.Continue -> controller.continueWhenReady()
|
||||
opening == Opening.Listen && !controller.micAllowed() -> mic.launch(Manifest.permission.RECORD_AUDIO)
|
||||
opening == Opening.Listen -> controller.opened(locked = false, listen = true)
|
||||
else -> controller.opened(locked = false)
|
||||
opening == Opening.Listen -> controller.opened(listen = true)
|
||||
else -> controller.opened()
|
||||
}
|
||||
}
|
||||
if (keyguard.isKeyguardLocked) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
val isLocked = keyguard.isKeyguardLocked
|
||||
if (isLocked) locked.value = true
|
||||
when (lockedStart(isLocked, opening, handed != null, controller.micAllowed())) {
|
||||
// Not locked, a handed-over question is asked at once ([AssistController.hold]).
|
||||
LockedStart.Go -> go()
|
||||
|
||||
LockedStart.Listen -> controller.opened(listen = true)
|
||||
|
||||
// Shown, and Android asked to unlock (the collector in onCreate): it stays if nobody does.
|
||||
LockedStart.Hold -> handed?.let { controller.hold(it) }
|
||||
|
||||
LockedStart.Unlock -> keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
locked.value = false
|
||||
unlockedNow()
|
||||
go()
|
||||
}
|
||||
|
||||
@@ -186,18 +303,58 @@ class AssistActivity : ComponentActivity() {
|
||||
override fun onDismissError() = finish()
|
||||
},
|
||||
)
|
||||
} else {
|
||||
go()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask Android to unlock. When it does, the question that waited is sent and [then] runs.
|
||||
* When it does not -- nobody there, or Back on the lock screen -- nothing happens: the sheet
|
||||
* stays as it is, with the way to try again.
|
||||
*/
|
||||
private fun askToUnlock(then: () -> Unit = {}) {
|
||||
keyguard.requestDismissKeyguard(
|
||||
this,
|
||||
object : KeyguardManager.KeyguardDismissCallback() {
|
||||
override fun onDismissSucceeded() {
|
||||
unlockedNow()
|
||||
then()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked now, however that was heard of -- Android's answer to the asking,
|
||||
* the person's own unlock, the sheet coming back: once, and only if the lock itself says so.
|
||||
*/
|
||||
private fun unlockedNow() {
|
||||
if (!locked.value || keyguard.isKeyguardLocked) return
|
||||
locked.value = false
|
||||
controller.unlocked()
|
||||
}
|
||||
|
||||
/** A question that waits for the unlock outlives the sheet being made again; a recording does not. */
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
val waiting = controller.state.value.waiting
|
||||
if (waiting.isNotBlank()) {
|
||||
outState.putString(STATE_WAITING, waiting)
|
||||
outState.putBoolean(STATE_SPOKEN, controller.heldSpoken)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
runCatching { unregisterReceiver(screen) }
|
||||
controller.close()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_QUESTION = "eu.llembas.android.QUESTION"
|
||||
/** The ticket of a question handed over by the session ([AssistHandOff]); never the question. */
|
||||
const val EXTRA_HANDOFF = "eu.llembas.android.HANDOFF"
|
||||
|
||||
private const val STATE_WAITING = "waiting"
|
||||
private const val STATE_SPOKEN = "spoken"
|
||||
|
||||
/** Handed over by the session: ask for the microphone, then listen. */
|
||||
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
|
||||
@@ -209,7 +366,7 @@ class AssistActivity : ComponentActivity() {
|
||||
const val ACTION_CONTINUE = "eu.llembas.android.action.CONTINUE"
|
||||
|
||||
/** The sheet, listening. */
|
||||
fun listening(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN)
|
||||
fun listening(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_LISTEN))
|
||||
|
||||
/** The sheet that is on screen now, if this activity is it. */
|
||||
@Volatile
|
||||
@@ -227,6 +384,12 @@ class AssistActivity : ComponentActivity() {
|
||||
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
/** The sheet, at the last assistant chat. */
|
||||
fun continuing(context: Context): Intent = Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE)
|
||||
fun continuing(context: Context): Intent = OwnIntents.own(context, Intent(context, AssistActivity::class.java).setAction(ACTION_CONTINUE))
|
||||
|
||||
/** The sheet, taking the question left under [ticket] -- or asking for the microphone and listening. */
|
||||
fun handedOver(context: Context, ticket: String?, listen: Boolean): Intent = OwnIntents.own(
|
||||
context,
|
||||
Intent(context, AssistActivity::class.java).putExtra(EXTRA_HANDOFF, ticket).putExtra(EXTRA_LISTEN, listen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.MainActivity
|
||||
@@ -14,21 +16,27 @@ import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Card
|
||||
import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.notify.NotificationReader
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.transformWhile
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.isActive
|
||||
@@ -45,6 +53,12 @@ data class AssistTurn(val question: String, val reply: LiveReply? = null, val ea
|
||||
val writing: Boolean get() = reply != null && reply.finished == null && !reply.closed
|
||||
}
|
||||
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: its [text], or -- heard where the instance
|
||||
* writes speech down -- its recording ([wav]), which stays on the phone until then.
|
||||
*/
|
||||
class Held(val text: String, val wav: ByteArray?, val spoken: Boolean)
|
||||
|
||||
/** Whether the instance answers: being asked, yes, or no (and why). */
|
||||
enum class Connection { Checking, Online, Offline }
|
||||
|
||||
@@ -57,6 +71,8 @@ data class AssistUiState(
|
||||
val connection: Connection = Connection.Checking,
|
||||
val models: List<ModelInfo> = emptyList(),
|
||||
val modelId: String? = null,
|
||||
/** [modelId] is a continued chat's own `model_ref`: looked up as a ref alone, never as an id. */
|
||||
val modelIsRef: Boolean = false,
|
||||
val listening: Boolean = false,
|
||||
/** The words heard so far, while listening and while the last of them is written down. */
|
||||
val heard: String = "",
|
||||
@@ -85,9 +101,23 @@ data class AssistUiState(
|
||||
val conversation: Boolean = false,
|
||||
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
|
||||
val canReadNotifications: Boolean = false,
|
||||
/**
|
||||
* A question that waits for the phone to be unlocked: typed over the lock screen, or heard
|
||||
* there by the phone's own recogniser -- the person's own words and nothing from the
|
||||
* account. Asked once the phone is unlocked.
|
||||
*/
|
||||
val waiting: String = "",
|
||||
/**
|
||||
* A question heard over the lock screen that waits as a recording, on the phone: the
|
||||
* instance writes speech down, and nothing goes to the instance while the phone is locked.
|
||||
*/
|
||||
val waitingRecording: Boolean = false,
|
||||
) {
|
||||
/** Whether a question waits for the unlock, as words or as a recording. */
|
||||
val held: Boolean get() = waiting.isNotBlank() || waitingRecording
|
||||
|
||||
val screenAvailable: Boolean get() = screenText || screenshot != null
|
||||
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
|
||||
val modelInfo: ModelInfo? get() = models.named(modelId, modelIsRef)
|
||||
val empty: Boolean get() = turns.isEmpty()
|
||||
}
|
||||
|
||||
@@ -127,7 +157,15 @@ interface AssistActions {
|
||||
* 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 {
|
||||
class AssistController(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
/**
|
||||
* Whether the phone is locked, asked each time it matters. While it is, nothing goes to the
|
||||
* instance from here: no question, no recording to write down, not even "which models".
|
||||
*/
|
||||
private val locked: () -> Boolean = { context.getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true },
|
||||
) : AssistActions {
|
||||
private val _state = MutableStateFlow(AssistUiState())
|
||||
val state = _state.asStateFlow()
|
||||
private val recorder = Recorder(scope)
|
||||
@@ -136,40 +174,105 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
private val route = HeadsetRoute(context)
|
||||
private var following: Job? = null
|
||||
private var hearing: Job? = null
|
||||
|
||||
/** The ear for the end of speech, while the instance's speech-to-text listens. */
|
||||
private var ear: EndOfSpeech? = null
|
||||
private var usingPhone = false
|
||||
private var screenText: String? = null
|
||||
private var stt: Boolean? = null
|
||||
private val ready: Job
|
||||
|
||||
/** The instance this assistant sheet speaks to (the default instance). */
|
||||
private var targetId: String? = null
|
||||
|
||||
/** The account's own default model, as the instance said it: what "Instance default" means. */
|
||||
private var accountDefault: String? = null
|
||||
|
||||
/**
|
||||
* The model a new chat starts on (Settings › Assistant › Assistant model). The sheet's
|
||||
* [AssistUiState.modelId] is the model of the chat it is in, which for a continued chat is
|
||||
* that chat's own; a new chat goes back to this one.
|
||||
*/
|
||||
private var newChatModel: String? = null
|
||||
|
||||
/** The question that waits for the unlock ([hold]). */
|
||||
private var held: Held? = null
|
||||
|
||||
/** Whether the question that waits was spoken. */
|
||||
val heldSpoken: Boolean get() = held?.spoken == true
|
||||
|
||||
/** When the phone's recogniser last gave a sign of somebody speaking (elapsed ms). */
|
||||
private var phoneActiveAt = 0L
|
||||
|
||||
/** What the phone itself knows: Settings, the instance's name. */
|
||||
private val local: Job
|
||||
|
||||
/** What the instance says -- its models, what it offers: asked only once the phone is unlocked. */
|
||||
private var remote: Job? = null
|
||||
|
||||
init {
|
||||
ready = scope.launch { load() }
|
||||
local = scope.launch {
|
||||
loadLocal()
|
||||
if (!locked()) askInstance()
|
||||
}
|
||||
scope.launch { speaker.playing.collect { on -> _state.update { it.copy(speaking = on) } } }
|
||||
// Settings changed the assistant's model while this sheet lives: the next new chat has it.
|
||||
scope.launch {
|
||||
context.lembas.instances.prefs.map { it.forInstance(targetId).assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
|
||||
ready()
|
||||
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
|
||||
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel, modelIsRef = false) else it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The instance, its models and what it offers this account; the choices kept in Settings. */
|
||||
private suspend fun load() {
|
||||
/** Everything known: Settings, and -- unless the phone is locked -- what the instance says. */
|
||||
private suspend fun ready() {
|
||||
local.join()
|
||||
if (!locked()) askInstance().join()
|
||||
}
|
||||
|
||||
/** Ask the instance what it has, once. */
|
||||
private fun askInstance(): Job = remote ?: scope.launch { loadRemote() }.also { remote = it }
|
||||
|
||||
/** The choices kept in Settings, and which instance: nothing here leaves the phone. */
|
||||
private suspend fun loadLocal() {
|
||||
val store = context.lembas.instances
|
||||
val instance = store.current()
|
||||
val instance = store.default()
|
||||
targetId = instance?.id
|
||||
val prefs = store.prefs.first()
|
||||
val own = prefs.forInstance(instance?.id)
|
||||
_state.update {
|
||||
it.copy(
|
||||
signedIn = instance != null,
|
||||
// An instance that signed this phone out is "not signed in" here: the sheet says
|
||||
// to sign in in the app, and asks that instance nothing.
|
||||
signedIn = instance != null && !instance.signedOut,
|
||||
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
|
||||
voiceReply = prefs.readAloudSpoken,
|
||||
canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context),
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
val api = instance?.let { store.clientFor(it) } ?: return
|
||||
// Until the instance has said what it has, the choice in Settings stands as it is: a
|
||||
// question asked while the list could not be read still goes to the chosen model.
|
||||
newChatModel = own.assistantModel.ifBlank { null }
|
||||
}
|
||||
|
||||
/** The instance's models and what it offers this account. */
|
||||
private suspend fun loadRemote() {
|
||||
val store = context.lembas.instances
|
||||
val prefs = store.prefs.first()
|
||||
val instance = store.default()?.takeUnless { it.signedOut } ?: return
|
||||
targetId = instance.id
|
||||
val api = store.clientFor(instance)
|
||||
val own = prefs.forInstance(instance.id)
|
||||
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
|
||||
accountDefault = me.defaultModel
|
||||
val chosen = assistantModelFor(own.assistantModel, me.defaultModel, models)
|
||||
newChatModel = chosen
|
||||
_state.update {
|
||||
it.copy(
|
||||
connection = Connection.Online,
|
||||
@@ -186,26 +289,101 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
/**
|
||||
* 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). [listen]
|
||||
* is a way in that means to speak -- a headset's voice button -- and listens regardless.
|
||||
* opens -- unless Settings says not to or the microphone is not allowed yet (that needs an
|
||||
* activity to ask). [listen] is a way in that means to speak -- the wake word, a headset's
|
||||
* voice button -- and listens regardless.
|
||||
*
|
||||
* Over the lock screen only such a way in listens, and what it hears is held for the unlock
|
||||
* ([hold]), never asked from there; the microphone opens without waiting for the instance.
|
||||
*/
|
||||
fun opened(locked: Boolean, listen: Boolean = false) {
|
||||
fun opened(listen: Boolean = false) {
|
||||
scope.launch {
|
||||
ready.join()
|
||||
if (locked()) {
|
||||
local.join()
|
||||
val s = _state.value
|
||||
if (listen && s.signedIn && !s.listening && !s.held && micAllowed()) listen()
|
||||
return@launch
|
||||
}
|
||||
ready()
|
||||
val prefs = context.lembas.instances.prefs.first()
|
||||
val s = _state.value
|
||||
if (s.signedIn && !locked && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
|
||||
if (s.signedIn && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
|
||||
if (listen || s.empty) listen()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep [question] until the phone is unlocked ([unlocked]); it takes the place of one that
|
||||
* waited already. With the phone not locked there is nothing to wait for.
|
||||
*/
|
||||
fun hold(question: Held) {
|
||||
if (question.text.isBlank() && question.wav == null) return
|
||||
held = question
|
||||
_state.update { it.copy(waiting = question.text, waitingRecording = question.wav != null, conversation = false) }
|
||||
if (!locked()) unlocked()
|
||||
}
|
||||
|
||||
/** The question that waits, taken away from here: to be handed to another sheet. */
|
||||
fun takeHeld(): Held? {
|
||||
val waited = held
|
||||
held = null
|
||||
_state.update { it.copy(waiting = "", waitingRecording = false) }
|
||||
return waited
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone is unlocked: the instance is asked what it has, and the question that waited is
|
||||
* asked now -- a recording is written down first. Does nothing while the phone is still locked.
|
||||
*/
|
||||
fun unlocked() {
|
||||
if (locked()) return
|
||||
askInstance()
|
||||
val waited = takeHeld() ?: return
|
||||
val wav = waited.wav
|
||||
if (wav == null) {
|
||||
ask(waited.text, spoken = waited.spoken)
|
||||
return
|
||||
}
|
||||
scope.launch {
|
||||
try {
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
|
||||
_state.update { it.copy(busy = false) }
|
||||
if (text.isNotBlank()) ask(text, spoken = true)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(busy = false, error = context.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The screen went off: the microphone and the voice stop, whatever the lock says -- nobody
|
||||
* is looking, and a phone that is about to lock must not go on listening or talking.
|
||||
*/
|
||||
fun screenOff() {
|
||||
speaker.stop()
|
||||
if (_state.value.listening) type()
|
||||
_state.update { it.copy(conversation = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone locked while the sheet was up: as [screenOff], and the answer being written is
|
||||
* no longer followed. Whatever is asked from now on waits for the unlock ([ask]).
|
||||
*/
|
||||
fun lockedNow() {
|
||||
screenOff()
|
||||
following?.cancel()
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
|
||||
/** Open at the last assistant chat, once it is known which that is. */
|
||||
fun continueWhenReady() {
|
||||
scope.launch {
|
||||
ready.join()
|
||||
if (_state.value.last != null) continueLast() else opened(locked = false)
|
||||
ready()
|
||||
if (_state.value.last != null) continueLast() else opened()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,7 +416,11 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
val headset = route.microphone()
|
||||
if (usingPhone) {
|
||||
phone.start(
|
||||
onPartial = { words -> _state.update { it.copy(heard = words) } },
|
||||
onPartial = { words ->
|
||||
phoneActiveAt = SystemClock.elapsedRealtime()
|
||||
_state.update { it.copy(heard = words) }
|
||||
},
|
||||
onActive = { phoneActiveAt = SystemClock.elapsedRealtime() },
|
||||
onLevel = { l -> _state.update { it.copy(level = l) } },
|
||||
onResult = { words ->
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
@@ -256,8 +438,10 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
}
|
||||
},
|
||||
)
|
||||
watchPhone()
|
||||
} else {
|
||||
recorder.preferred = headset
|
||||
ear = EndOfSpeech(TICK_MS)
|
||||
recorder.start()
|
||||
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
|
||||
launch { writeDownAsSaid() }
|
||||
@@ -271,52 +455,85 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
/**
|
||||
* 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.
|
||||
* a second more has been said, not past the first minute -- and not before the microphone
|
||||
* has heard anything above the room: silence written down is an invented sentence. Never
|
||||
* while the phone is locked: the recording stays on the phone until it is unlocked.
|
||||
*/
|
||||
private suspend fun writeDownAsSaid() {
|
||||
val api = context.lembas.instances.client() ?: return
|
||||
val api = context.lembas.instances.defaultClient() ?: return
|
||||
var sent = 0f
|
||||
while (scope.isActive) {
|
||||
delay(PARTIAL_EVERY_MS)
|
||||
val seconds = recorder.seconds
|
||||
if (seconds - sent < 0.5f || seconds > 60f) continue
|
||||
if (seconds - sent < 0.5f || seconds > 60f || ear?.heardSomething != true || locked()) continue
|
||||
sent = seconds
|
||||
val words = runCatching { api.transcribe(recorder.snapshot()) }.getOrNull()
|
||||
val words = runCatching { api.transcribe(recorder.snapshot(), media = mediaFor()).text }.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). */
|
||||
/**
|
||||
* Wait for a pause after speech (true) -- or for nothing said at all, which gives up (false).
|
||||
* [EndOfSpeech] decides, from the microphone's level against the room's own and the words
|
||||
* written down so far.
|
||||
*/
|
||||
private suspend fun untilQuiet(): Boolean {
|
||||
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
|
||||
val ear = ear ?: return false
|
||||
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
|
||||
// Over the lock screen no words are written down: the level alone decides.
|
||||
when (ear.tick(recorder.level.value, _state.value.heard)) {
|
||||
EndOfSpeech.Verdict.Said -> return true
|
||||
EndOfSpeech.Verdict.Nothing -> return false
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's recogniser finds the end of speech itself -- and is watched all the same
|
||||
* ([phoneWatch]): one that never calls back would leave the sheet listening for good.
|
||||
*/
|
||||
private suspend fun watchPhone() {
|
||||
var waited = 0L
|
||||
var words = ""
|
||||
var sameFor = 0L
|
||||
var asked = false
|
||||
val began = SystemClock.elapsedRealtime()
|
||||
phoneActiveAt = 0L
|
||||
while (_state.value.listening) {
|
||||
delay(TICK_MS)
|
||||
waited += TICK_MS
|
||||
val heard = _state.value.heard
|
||||
if (heard.isNotBlank()) spoke = true
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += TICK_MS
|
||||
sameFor = 0
|
||||
} else {
|
||||
sameFor += TICK_MS
|
||||
}
|
||||
// Since it last gave a sign of somebody speaking; never, and it is as long as it has listened.
|
||||
val silentFor = if (phoneActiveAt >= began) SystemClock.elapsedRealtime() - phoneActiveAt else waited
|
||||
when (phoneWatch(waited, heard.isNotBlank(), sameFor, silentFor)) {
|
||||
PhoneWatch.Wait -> Unit
|
||||
|
||||
PhoneWatch.Finish -> if (!asked) {
|
||||
asked = true
|
||||
phone.finish()
|
||||
}
|
||||
|
||||
PhoneWatch.Take -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "") }
|
||||
askOrStop(heard)
|
||||
return
|
||||
}
|
||||
|
||||
PhoneWatch.GiveUp -> {
|
||||
phone.stop()
|
||||
_state.update { it.copy(listening = false, level = 0f, heard = "", conversation = false) }
|
||||
return
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,9 +553,16 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(heard = "") }
|
||||
return@launch
|
||||
}
|
||||
// Over the lock screen nothing goes to the instance, a recording to write down
|
||||
// included: it waits on the phone, and is written down and asked on the unlock.
|
||||
if (locked()) {
|
||||
_state.update { it.copy(heard = "") }
|
||||
hold(Held("", wav, spoken = true))
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
_state.update { it.copy(busy = true) }
|
||||
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
val text = context.lembas.instances.defaultClient()?.transcribe(wav, media = mediaFor())?.text.orEmpty()
|
||||
_state.update { it.copy(busy = false, heard = "") }
|
||||
if (text.isNotBlank()) askOrStop(text) else endConversation()
|
||||
} catch (e: Exception) {
|
||||
@@ -361,6 +585,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
|
||||
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
|
||||
private fun askOrStop(words: String) {
|
||||
if (locked()) return hold(Held(words, null, spoken = true))
|
||||
val phrases = context.getString(R.string.assist_stop_words).split("|")
|
||||
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
|
||||
}
|
||||
@@ -381,8 +606,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
/** The sheet's "Summarise my notifications": the notifications up now go with the question. */
|
||||
override fun summariseNotifications() = ask(context.getString(R.string.assist_notifications_prompt), spoken = false, notifications = true)
|
||||
|
||||
/**
|
||||
* Ask [question]. With the phone locked it is not asked but held for the unlock, whoever
|
||||
* called: this is the one door to the instance, and it is shut while the phone is locked.
|
||||
*/
|
||||
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
|
||||
if (question.isBlank()) return
|
||||
if (locked()) return hold(Held(question, null, spoken))
|
||||
if (_state.value.listening) type()
|
||||
following?.cancel()
|
||||
following = scope.launch {
|
||||
@@ -394,8 +624,12 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
_state.update { it.copy(conversation = talking) }
|
||||
try {
|
||||
val store = context.lembas.instances
|
||||
val api = store.client() ?: throw ApiException(401, "Not signed in.")
|
||||
val instance = store.default()?.takeUnless { it.signedOut } ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
targetId = instance.id
|
||||
val api = store.clientFor(instance)
|
||||
val prefs = store.prefs.first()
|
||||
// A question typed the moment the sheet opened: the model is known first.
|
||||
ready()
|
||||
val now = _state.value
|
||||
val withScreen = now.includeScreen
|
||||
val attachments = buildList {
|
||||
@@ -424,13 +658,15 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
inChat = chatId
|
||||
replyId = sent.reply?.id ?: return@launch
|
||||
} else {
|
||||
val made = api.createChat(text, attachments, model = now.modelId, temporary = prefs.assistantTemporary)
|
||||
val made = api.createChat(text, attachments, model = now.modelId ?: newChatModel, temporary = prefs.assistantTemporary)
|
||||
inChat = made.chat.id
|
||||
replyId = made.reply?.id ?: return@launch
|
||||
_state.update { it.copy(chatId = inChat) }
|
||||
if (!prefs.assistantTemporary) {
|
||||
store.savePrefs {
|
||||
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
|
||||
store.savePrefs { p ->
|
||||
p.withInstance(targetId) {
|
||||
it.copy(lastAssistChat = inChat, lastAssistTitle = question.take(120), lastAssistAt = System.currentTimeMillis())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -455,7 +691,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
}
|
||||
// The answer was heard to the end: listen for the next thing said. Stopped, a
|
||||
// card waiting, or nothing to read: the conversation ends there.
|
||||
if (_state.value.conversation && heardAll && micAllowed()) listen() else endConversation()
|
||||
if (_state.value.conversation && heardAll && micAllowed() && !locked()) listen() else endConversation()
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e), conversation = false) }
|
||||
} finally {
|
||||
@@ -475,7 +711,13 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
delay(TITLE_ASK_MS)
|
||||
val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty()
|
||||
if (title.isNotBlank() && title != provisional) {
|
||||
context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it }
|
||||
context.lembas.instances.savePrefs { p ->
|
||||
if (p.forInstance(targetId).lastAssistChat == chatId) {
|
||||
p.withInstance(targetId) { it.copy(lastAssistTitle = title.take(120)) }
|
||||
} else {
|
||||
p
|
||||
}
|
||||
}
|
||||
_state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) }
|
||||
break
|
||||
}
|
||||
@@ -490,16 +732,27 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
scope.launch {
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return@launch
|
||||
val api = context.lembas.instances.defaultClient() ?: 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) }
|
||||
val own = detail.chat.modelKey
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = last.chatId,
|
||||
turns = turns,
|
||||
modelId = own ?: it.modelId,
|
||||
modelIsRef = if (own != null) !detail.chat.modelRef.isNullOrBlank() else it.modelIsRef,
|
||||
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) }
|
||||
context.lembas.instances.savePrefs { p ->
|
||||
p.withInstance(targetId) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
}
|
||||
_state.update { it.copy(last = null) }
|
||||
} else {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
@@ -515,7 +768,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
val chat = _state.value.chatId ?: return
|
||||
scope.launch {
|
||||
try {
|
||||
context.lembas.instances.client()?.answer(chat, card.id, answer)
|
||||
context.lembas.instances.defaultClient()?.answer(chat, card.id, answer)
|
||||
} catch (e: ApiException) {
|
||||
// First answer wins: a 409 is somebody answering elsewhere already.
|
||||
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
|
||||
@@ -528,16 +781,29 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
override fun newChat() {
|
||||
following?.cancel()
|
||||
speaker.stop()
|
||||
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false) }
|
||||
// And on the assistant's own model again, not the one of the chat that was continued.
|
||||
_state.update {
|
||||
it.copy(
|
||||
chatId = null,
|
||||
turns = emptyList(),
|
||||
error = null,
|
||||
busy = false,
|
||||
conversation = false,
|
||||
modelId = newChatModel ?: it.modelId,
|
||||
modelIsRef =
|
||||
newChatModel == null && it.modelIsRef,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
newChatModel = id
|
||||
_state.update { it.copy(modelId = id, modelIsRef = false) }
|
||||
scope.launch {
|
||||
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
|
||||
context.lembas.instances.savePrefs { p -> p.withInstance(targetId) { it.copy(assistantModel = id) } }
|
||||
val chat = _state.value.chatId ?: return@launch
|
||||
runCatching { context.lembas.instances.client()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
|
||||
runCatching { context.lembas.instances.defaultClient()?.updateChat(chat, JsonObject(mapOf("model" to JsonPrimitive(id)))) }
|
||||
.onFailure { e -> _state.update { it.copy(error = context.explain(e)) } }
|
||||
}
|
||||
}
|
||||
@@ -558,12 +824,19 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
|
||||
override fun stopReading() = speaker.stop()
|
||||
|
||||
/**
|
||||
* Which chat the sheet's speech is for: the chat it is in, else the model its next chat
|
||||
* starts on. That a fallback answered is not said here: the sheet may be over the lock.
|
||||
*/
|
||||
private fun mediaFor(): MediaFor = _state.value.let { MediaFor.of(it.chatId, it.modelId ?: newChatModel) }
|
||||
|
||||
/** Read [words] aloud; true when they were heard to the end. */
|
||||
private suspend fun speak(words: String): Boolean {
|
||||
if (words.isBlank()) return false
|
||||
// Never aloud over the lock screen: an answer is the account's.
|
||||
if (words.isBlank() || locked()) return false
|
||||
return try {
|
||||
val api = context.lembas.instances.client() ?: return false
|
||||
speaker.playToEnd(api.speech(words))
|
||||
val api = context.lembas.instances.defaultClient() ?: return false
|
||||
speaker.playToEnd(api.speech(words, mediaFor()).audio)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = context.explain(e)) }
|
||||
false
|
||||
@@ -574,7 +847,10 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
* start activities differently. */
|
||||
fun appIntent(): Intent = Intent(context, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.apply { _state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) } }
|
||||
.apply {
|
||||
_state.value.chatId?.let { putExtra(Notifications.EXTRA_CHAT, it) }
|
||||
targetId?.let { putExtra(Notifications.EXTRA_INSTANCE, it) }
|
||||
}
|
||||
|
||||
fun close() {
|
||||
following?.cancel()
|
||||
@@ -582,7 +858,9 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
speaker.stop()
|
||||
phone.stop()
|
||||
route.release()
|
||||
scope.launch { recorder.stop() }
|
||||
// Not in a coroutine: the scope may be cancelled already, and the microphone must be let go.
|
||||
recorder.stopNow()
|
||||
held = null
|
||||
}
|
||||
|
||||
private suspend fun png(bitmap: Bitmap): ByteArray = withContext(Dispatchers.Default) {
|
||||
@@ -600,18 +878,22 @@ class AssistController(private val context: Context, private val scope: Coroutin
|
||||
private const val TITLE_WAIT_MS = 20_000L
|
||||
private const val TITLE_ASK_MS = 4_000L
|
||||
|
||||
// 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
|
||||
// Listening: how often the end of speech is looked for (EndOfSpeech has the rules and
|
||||
// their numbers), and how often the recording so far is written down.
|
||||
private const val TICK_MS = EndOfSpeech.TICK_MS
|
||||
private const val PARTIAL_EVERY_MS = 1_200L
|
||||
|
||||
/**
|
||||
* The model a new assistant chat starts on: the one [chosen] in Settings while the
|
||||
* instance still has it; else ("Instance default", or a model that is gone) the
|
||||
* account's default, the instance's, or its first.
|
||||
*/
|
||||
fun assistantModelFor(chosen: String, accountDefault: String?, models: List<ModelInfo>): String? {
|
||||
// By ref, or -- a choice saved before refs, the account's default -- by id: either
|
||||
// way what comes back is the row's own unambiguous name.
|
||||
return (models.named(chosen) ?: models.named(accountDefault) ?: models.firstOrNull { it.default } ?: models.firstOrNull())?.key
|
||||
}
|
||||
|
||||
/** A reply's words, for a voice: its text steps, without the markup. */
|
||||
fun spokenWords(steps: List<Step>): String = plain(steps.filter { it.kind == "text" }.joinToString("\n\n") { it.markdown.orEmpty() })
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ fun AssistPanel(
|
||||
onOpenApp: () -> Unit,
|
||||
onNeedMic: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
onUnlock: () -> Unit = {},
|
||||
) {
|
||||
val state by controller.state.collectAsState()
|
||||
AssistSheetFrame(onDismiss = onDismiss) { handle, _ ->
|
||||
@@ -27,6 +28,7 @@ fun AssistPanel(
|
||||
locked = locked,
|
||||
handle = handle,
|
||||
onOpenApp = onOpenApp,
|
||||
onUnlock = onUnlock,
|
||||
onSend = { text -> if (locked) onUnlockAndAsk(text) else controller.ask(text) },
|
||||
onMic = {
|
||||
when {
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.app.assist.AssistStructure
|
||||
import android.app.role.RoleManager
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.ColorDrawable
|
||||
import android.os.Bundle
|
||||
@@ -29,6 +28,7 @@ import androidx.savedstate.SavedStateRegistryController
|
||||
import androidx.savedstate.SavedStateRegistryOwner
|
||||
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.SheetAtGate
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import eu.llembas.android.wake.AssistLink
|
||||
@@ -36,6 +36,7 @@ import eu.llembas.android.wake.AssistPresence
|
||||
import eu.llembas.android.wake.wakeLogConnected
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -79,6 +80,8 @@ class LembasAssistService : VoiceInteractionService() {
|
||||
|
||||
override fun onDestroy() {
|
||||
AssistLink.destroyed(System.currentTimeMillis())
|
||||
// With the service gone no sheet of it is up, whatever its session managed to say.
|
||||
lembas.gate.sessionHidden()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@@ -143,6 +146,10 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
|
||||
private var up = false
|
||||
private val atGate = SheetAtGate(context.lembas.gate)
|
||||
|
||||
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
|
||||
private var handing: Job? = null
|
||||
|
||||
override val lifecycle: Lifecycle get() = registry
|
||||
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
|
||||
@@ -176,12 +183,12 @@ class LembasAssistSession(context: Context) :
|
||||
AssistPanel(
|
||||
controller = current.value,
|
||||
locked = locked(),
|
||||
onUnlockAndAsk = { text -> handOff(text) },
|
||||
onUnlockAndAsk = { text -> handOff(Held(text, null, spoken = false).takeIf { text.isNotBlank() }) },
|
||||
onOpenApp = {
|
||||
startAssistantActivity(current.value.appIntent())
|
||||
hide()
|
||||
},
|
||||
onNeedMic = { handOff("", listen = true) },
|
||||
onNeedMic = { handOff(null, listen = true) },
|
||||
onDismiss = { hide() },
|
||||
)
|
||||
}
|
||||
@@ -198,12 +205,25 @@ class LembasAssistSession(context: Context) :
|
||||
up = true
|
||||
AssistPresence.shown()
|
||||
}
|
||||
// The sheet is the app in front: what it draws of the account (a reply's picture) may be
|
||||
// asked for, unless the phone is locked. Said each time; the gate keeps it as one.
|
||||
atGate.shown()
|
||||
AssistLink.sheetShown(SystemClock.elapsedRealtime())
|
||||
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
|
||||
// this one was slow to come, goes now that this one is here.
|
||||
AssistActivity.closeWoken()
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening.
|
||||
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
// The wake word asks for the sheet listening, whatever Settings says about opening --
|
||||
// over the lock screen too, where what it hears is held and not asked.
|
||||
val showing = controller
|
||||
showing.opened(listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
|
||||
// A question that waits for the unlock (heard, or typed, over the lock screen) goes to
|
||||
// the sheet's activity, which can ask Android to unlock. Once: Android may call onShow
|
||||
// again while the sheet is up.
|
||||
handing?.cancel()
|
||||
handing = scope.launch {
|
||||
showing.state.first { it.held && locked() }
|
||||
showing.takeHeld()?.let { handOff(it) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -217,6 +237,7 @@ class LembasAssistSession(context: Context) :
|
||||
up = false
|
||||
AssistPresence.hidden()
|
||||
}
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -227,6 +248,8 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
// A session torn down without being hidden must not leave the gate open behind it.
|
||||
atGate.gone()
|
||||
controller.close()
|
||||
scope.cancel()
|
||||
registry.currentState = Lifecycle.State.DESTROYED
|
||||
@@ -258,16 +281,12 @@ class LembasAssistSession(context: Context) :
|
||||
|
||||
/**
|
||||
* Over the lock screen nothing is sent from here: the question goes to [AssistActivity],
|
||||
* which asks Android to unlock first and only then sends it. The microphone's permission
|
||||
* which asks Android to unlock first and only then sends it. It is left in the app's own
|
||||
* memory ([AssistHandOff]) and the intent carries its ticket. The microphone's permission
|
||||
* prompt needs an activity too.
|
||||
*/
|
||||
private fun handOff(text: String, 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),
|
||||
)
|
||||
private fun handOff(question: Held?, listen: Boolean = false) {
|
||||
startAssistantActivity(AssistActivity.handedOver(context, question?.let { AssistHandOff.leave(it) }, listen))
|
||||
hide()
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import androidx.compose.foundation.gestures.Orientation
|
||||
import androidx.compose.foundation.gestures.draggable
|
||||
import androidx.compose.foundation.gestures.rememberDraggableState
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -46,6 +47,7 @@ import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Keyboard
|
||||
import androidx.compose.material.icons.filled.Lightbulb
|
||||
import androidx.compose.material.icons.filled.LockOpen
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.ScreenshotMonitor
|
||||
@@ -74,6 +76,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
@@ -89,10 +92,13 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.chat.PhoneCard
|
||||
import eu.llembas.android.ui.chat.Steps
|
||||
import eu.llembas.android.ui.chat.restFollows
|
||||
import eu.llembas.android.ui.chat.yielding
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -197,7 +203,10 @@ fun AssistSheetFrame(onDismiss: () -> Unit, content: @Composable ColumnScope.(ha
|
||||
* - **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.
|
||||
* Nothing from the account is on it while the phone is [locked]: no model list, no last chat,
|
||||
* no question asked earlier, no answer, no failure's words. A question heard over the lock
|
||||
* screen waits -- shown as the person's own words where the phone wrote them down, as "Question
|
||||
* heard" where it waits as a recording -- with the way to unlock, which sends it ([onUnlock]).
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.AssistSheetContent(
|
||||
@@ -206,14 +215,52 @@ fun ColumnScope.AssistSheetContent(
|
||||
locked: Boolean,
|
||||
handle: Modifier = Modifier,
|
||||
onOpenApp: () -> Unit = {},
|
||||
onUnlock: () -> Unit = {},
|
||||
onSend: (String) -> Unit = actions::ask,
|
||||
onMic: () -> Unit = actions::listen,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var text by remember { mutableStateOf("") }
|
||||
val scroll = rememberScrollState()
|
||||
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 turns keep to their end while an answer is written only for a person who is there
|
||||
// (`ui/chat/Follow.kt`, the chat's rule): a finger on them ends the following, where they
|
||||
// come to rest says whether it is taken up again, and a question asked always shows.
|
||||
var following by remember { mutableStateOf(true) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
LaunchedEffect(scroll) {
|
||||
scroll.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(scroll) {
|
||||
var moving = false
|
||||
var from = scroll.value
|
||||
snapshotFlow { scroll.isScrollInProgress }.collect { now ->
|
||||
if (now && !moving) from = scroll.value
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`), not one of ours
|
||||
// that an arriving line left short of the end.
|
||||
following = restFollows(following, touched[0] || scroll.value < from, scroll.maxValue - scroll.value, slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
LaunchedEffect(state.turns.size) { following = true }
|
||||
// The end moves when the answer grows and when the keyboard opens; before the first layout
|
||||
// it is not known yet.
|
||||
LaunchedEffect(scroll) {
|
||||
// Never against a finger: nothing is moved while a scroll is under way, and one of
|
||||
// ours that a finger interrupts does not end this follower (`yielding`). Whether a
|
||||
// scroll is under way is asked here and not watched: our own scroll is one too, and
|
||||
// watching it would have each scroll to the end start the next.
|
||||
snapshotFlow { if (following) scroll.maxValue else -1 }
|
||||
.collect { end -> if (end in 0 until Int.MAX_VALUE && !scroll.isScrollInProgress) yielding { scroll.scrollTo(end) } }
|
||||
}
|
||||
|
||||
// The top: the handle and the bar. Both drag the sheet.
|
||||
Column(handle.fillMaxWidth()) {
|
||||
@@ -267,14 +314,20 @@ fun ColumnScope.AssistSheetContent(
|
||||
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 ->
|
||||
when {
|
||||
locked && state.held -> Waiting(state.waiting, onUnlock)
|
||||
|
||||
// A conversation that was on the sheet when the phone locked: not for the lock screen.
|
||||
locked && !state.empty -> Text(stringResource(R.string.assist_locked_line), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
state.empty -> Starting(state, actions, locked)
|
||||
|
||||
else -> state.turns.forEachIndexed { i, turn ->
|
||||
Turn(turn, last = i == state.turns.lastIndex, state, actions, onOpenApp)
|
||||
}
|
||||
}
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
// Not over the lock screen: a failure's words may name the instance.
|
||||
if (!locked) state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
// The foot.
|
||||
@@ -388,15 +441,15 @@ private fun ModelChip(state: AssistUiState, actions: AssistActions) {
|
||||
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) {
|
||||
text = { Text(model.titleAmong(state.models), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
trailingIcon = if (model.key == state.modelInfo?.key) {
|
||||
{ Box(Modifier.size(8.dp).clip(CircleShape).background(palette.accent)) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = {
|
||||
open = false
|
||||
actions.pickModel(model.id)
|
||||
actions.pickModel(model.key)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -468,6 +521,41 @@ private fun QuickAction(icon: androidx.compose.ui.graphics.vector.ImageVector, l
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Over the lock screen: the question that was heard, as its bubble, and the one thing to do about
|
||||
* it. Unlocking sends it; nothing is sent and no answer shown before.
|
||||
*/
|
||||
@Composable
|
||||
private fun Waiting(question: String, onUnlock: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// The words, where the phone itself wrote them down or they were typed; a question the
|
||||
// instance will write down waits as a recording, and there are no words to show yet.
|
||||
Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.CenterEnd) {
|
||||
Surface(color = palette.bubbleUser, contentColor = palette.ink, shape = RoundedCornerShape(20.dp), modifier = Modifier.widthIn(max = 300.dp)) {
|
||||
Text(
|
||||
question.ifBlank { stringResource(R.string.assist_question_heard) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(if (question.isBlank()) R.string.assist_recording_waits_line else R.string.assist_locked_line),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
)
|
||||
AssistChip(
|
||||
onClick = onUnlock,
|
||||
label = { Text(stringResource(R.string.assist_unlock_to_send)) },
|
||||
leadingIcon = { Icon(Icons.Filled.LockOpen, contentDescription = null, modifier = Modifier.size(18.dp)) },
|
||||
colors = AssistChipDefaults.assistChipColors(containerColor = palette.surfaceRaised, leadingIconContentColor = palette.accent),
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** One question, as a bubble on the right, and its answer at full width -- as in the app's chats. */
|
||||
@Composable
|
||||
private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions: AssistActions, onOpenApp: () -> Unit) {
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
/**
|
||||
* When to stop listening, for the instance's speech-to-text (which takes a whole recording and
|
||||
* finds no end of speech itself). Fed the microphone's level once a tick ([tick]); apart from
|
||||
* Android, so it is tested with sequences of levels.
|
||||
*
|
||||
* Nothing here is an absolute loudness: a room's own noise differs from phone to phone by more
|
||||
* than a voice differs from a room. The **noise floor** is measured from the first sound on and
|
||||
* followed all the time -- the quietest level of the last two seconds, taken at once when it
|
||||
* falls and slowly, in calm moments, when it rises: the dips between words keep it down while
|
||||
* somebody speaks, and a steady noise (a fan, a car) becomes the floor within a moment. Speech and quiet are
|
||||
* levels relative to it:
|
||||
*
|
||||
* - **speech** begins when the level is well above the floor in [ONSET_TICKS] of the last
|
||||
* [ONSET_WINDOW] ticks -- a voice rises and falls, and one click or knock is not speech;
|
||||
* - listening may begin in the middle of a sentence (the wake word's shape: the person goes
|
||||
* straight on), and a voice that never dips far must not become "the room": the floor rises
|
||||
* only while the sound is calm, and sound that stays above the floor without being steady is
|
||||
* speech;
|
||||
* - once somebody spoke, a **pause** of [PAUSE_MS] back near the floor ends it ([Verdict.Said]);
|
||||
* - when **nothing is said**, it gives up after [NOTHING_SAID_MS] ([Verdict.Nothing]);
|
||||
* - the words written down so far are a second ear: the same words for [SAME_WORDS_MS] end it,
|
||||
* and words count as speech for a quiet voice -- but only when the microphone heard at least
|
||||
* something above the floor, because a speech-to-text model asked to write down silence
|
||||
* invents a sentence;
|
||||
* - and never longer than [LONGEST_MS].
|
||||
*/
|
||||
class EndOfSpeech(private val tickMs: Long = TICK_MS) {
|
||||
enum class Verdict { Listening, Said, Nothing }
|
||||
|
||||
/** The room's own level, as followed so far; 0 until the microphone gave any sound. */
|
||||
var floor = 0f
|
||||
private set
|
||||
|
||||
/** Whether somebody spoke. */
|
||||
var spoke = false
|
||||
private set
|
||||
|
||||
/**
|
||||
* Whether the microphone heard anything above the room at all: only then is the recording
|
||||
* worth writing down while it runs.
|
||||
*/
|
||||
val heardSomething: Boolean get() = spoke || stirred >= STIRRED_TICKS
|
||||
|
||||
private val recent = ArrayDeque<Float>()
|
||||
private var waited = 0L
|
||||
private val loud = ArrayDeque<Boolean>()
|
||||
private var stirred = 0
|
||||
private var aboveRun = 0
|
||||
|
||||
/** The floor is a guess: listening began in the middle of sound louder than any room is taken to be. */
|
||||
private var guessed = false
|
||||
private var overGuess = 0
|
||||
private var quietFor = 0L
|
||||
private var words = ""
|
||||
private var sameWordsFor = 0L
|
||||
|
||||
/** The level from which a sound is speech beginning, and the level under which it is a pause. */
|
||||
private fun speechFrom(): Float = maxOf(floor * SPEECH_RATIO, floor + SPEECH_MARGIN)
|
||||
|
||||
private fun pauseUnder(): Float = maxOf(floor * PAUSE_RATIO, floor + PAUSE_MARGIN)
|
||||
|
||||
/** One tick: the microphone's [level] (0..1, RMS) and the [heard] words written down so far. */
|
||||
fun tick(level: Float, heard: String = ""): Verdict {
|
||||
waited += tickMs
|
||||
// Exact zero before any sound is a microphone that has not given anything yet (or gives
|
||||
// nothing at all): it says nothing about the room. After sound it is silence -- a
|
||||
// headset that gates its noise gives exactly that between sentences -- and so a pause.
|
||||
if (level > 0f) {
|
||||
follow(level)
|
||||
} else if (floor > 0f) {
|
||||
judge(loud = false, above = false)
|
||||
}
|
||||
if (heard != words) {
|
||||
words = heard
|
||||
sameWordsFor = 0
|
||||
} else if (heard.isNotBlank()) {
|
||||
sameWordsFor += tickMs
|
||||
}
|
||||
if (heard.isNotBlank() && stirred >= STIRRED_TICKS) spoke = true
|
||||
return when {
|
||||
spoke && quietFor >= PAUSE_MS -> Verdict.Said
|
||||
spoke && sameWordsFor >= SAME_WORDS_MS -> Verdict.Said
|
||||
!spoke && waited >= NOTHING_SAID_MS -> Verdict.Nothing
|
||||
waited >= LONGEST_MS -> if (spoke) Verdict.Said else Verdict.Nothing
|
||||
else -> Verdict.Listening
|
||||
}
|
||||
}
|
||||
|
||||
private fun follow(level: Float) {
|
||||
recent.addLast(level)
|
||||
if (recent.size > WINDOW_TICKS) recent.removeFirst()
|
||||
val lowest = recent.min()
|
||||
// Steady over the whole window: a noise. Calm in the last half second: no voice now.
|
||||
val steady = recent.size >= CALM_TICKS && recent.max() <= lowest * STEADY_RATIO
|
||||
val last = recent.takeLast(CALM_TICKS)
|
||||
val calm = last.size >= CALM_TICKS && last.max() <= last.min() * STEADY_RATIO
|
||||
// The first sound is the room, unless somebody is already speaking -- then a guess,
|
||||
// until a dip or a calm moment shows the room. After it: down at once; up slowly, and
|
||||
// only while the sound is calm, so a voice does not lift the floor under itself.
|
||||
when {
|
||||
floor == 0f -> {
|
||||
floor = minOf(level, START_MAX)
|
||||
guessed = level > START_MAX
|
||||
}
|
||||
|
||||
lowest < floor -> {
|
||||
floor = lowest
|
||||
guessed = false
|
||||
}
|
||||
|
||||
calm -> {
|
||||
floor += (lowest - floor) * RISE
|
||||
guessed = false
|
||||
}
|
||||
}
|
||||
floor = floor.coerceAtLeast(MIN_FLOOR)
|
||||
judge(loud = level >= speechFrom(), above = level >= pauseUnder())
|
||||
// Sound that stays above the floor and is not steady is a voice: one that never dips
|
||||
// far, or -- while the floor is only a guess -- one that began before the listening did.
|
||||
overGuess = if (guessed && level > floor) overGuess + 1 else 0
|
||||
if ((aboveRun >= SUSTAINED_TICKS || overGuess >= SUSTAINED_TICKS) && !steady) spoke = true
|
||||
}
|
||||
|
||||
/** One tick's sound, judged: [loud] enough to be speech beginning, or at least [above] a pause. */
|
||||
private fun judge(loud: Boolean, above: Boolean) {
|
||||
this.loud.addLast(loud)
|
||||
if (this.loud.size > ONSET_WINDOW) this.loud.removeFirst()
|
||||
if (this.loud.count { it } >= ONSET_TICKS) spoke = true
|
||||
if (above) {
|
||||
stirred++
|
||||
aboveRun++
|
||||
quietFor = 0
|
||||
} else {
|
||||
aboveRun = 0
|
||||
quietFor += tickMs
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TICK_MS = 100L
|
||||
|
||||
/** How long the room's quietest level is looked for: two seconds. */
|
||||
private const val WINDOW_TICKS = 20
|
||||
|
||||
/** How fast the floor follows a room that got louder: a twentieth of the way each tick. */
|
||||
private const val RISE = 0.05f
|
||||
|
||||
/** No microphone is quieter than this; and the most the first sound may claim as "the room". */
|
||||
private const val MIN_FLOOR = 0.0008f
|
||||
private const val START_MAX = 0.02f
|
||||
|
||||
// Speech begins at a little over twice the floor (and at least a small step above it, for
|
||||
// a silent room); a pause is back within 1.6 times of it. Between the two nothing changes.
|
||||
private const val SPEECH_RATIO = 2.2f
|
||||
private const val SPEECH_MARGIN = 0.004f
|
||||
private const val PAUSE_RATIO = 1.6f
|
||||
private const val PAUSE_MARGIN = 0.002f
|
||||
private const val ONSET_TICKS = 3
|
||||
private const val ONSET_WINDOW = 8
|
||||
private const val STIRRED_TICKS = 4
|
||||
|
||||
// Steady, calm: the loudest within half again of the quietest -- over the window, over
|
||||
// the last half second. Sustained: above the floor for a second without a break.
|
||||
private const val CALM_TICKS = 5
|
||||
private const val STEADY_RATIO = 1.5f
|
||||
private const val SUSTAINED_TICKS = 10
|
||||
|
||||
const val PAUSE_MS = 1_500L
|
||||
const val SAME_WORDS_MS = 4_500L
|
||||
const val NOTHING_SAID_MS = 5_000L
|
||||
const val LONGEST_MS = 60_000L
|
||||
}
|
||||
}
|
||||
|
||||
/** What to do about the phone's own recogniser, which finds the end of speech itself -- usually. */
|
||||
enum class PhoneWatch {
|
||||
Wait,
|
||||
|
||||
/** Ask it to stop and give what it has. */
|
||||
Finish,
|
||||
|
||||
/** It did not answer the asking either: take the words it showed. */
|
||||
Take,
|
||||
|
||||
/** Nothing was said, and it has not said so itself. */
|
||||
GiveUp,
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch kept over the phone's recogniser, from how long it has listened ([waitedMs]), whether
|
||||
* it has shown any words ([anyWords]), for how long they have stayed the same ([sameForMs]), and
|
||||
* how long ago it last gave a sign of somebody speaking ([silentForMs]: its "speech began", a
|
||||
* loud level, new words -- not every recogniser shows words while one speaks).
|
||||
* A recogniser normally ends by itself; some never call back, and the sheet would listen for good.
|
||||
* No words and nothing heard for a while gives up; when somebody did speak before that quiet, it
|
||||
* is first asked for what it has.
|
||||
*/
|
||||
fun phoneWatch(waitedMs: Long, anyWords: Boolean, sameForMs: Long, silentForMs: Long = waitedMs): PhoneWatch = when {
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS + PHONE_GRACE_MS -> if (anyWords) PhoneWatch.Take else PhoneWatch.GiveUp
|
||||
waitedMs >= EndOfSpeech.LONGEST_MS -> PhoneWatch.Finish
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS + PHONE_GRACE_MS -> PhoneWatch.GiveUp
|
||||
!anyWords && silentForMs >= PHONE_NOTHING_SAID_MS -> if (silentForMs < waitedMs) PhoneWatch.Finish else PhoneWatch.GiveUp
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS + PHONE_GRACE_MS -> PhoneWatch.Take
|
||||
anyWords && sameForMs >= EndOfSpeech.SAME_WORDS_MS && silentForMs >= EndOfSpeech.PAUSE_MS -> PhoneWatch.Finish
|
||||
else -> PhoneWatch.Wait
|
||||
}
|
||||
|
||||
/** Longer than the recogniser's own "no speech" (about five seconds on most): it gets to say so first. */
|
||||
const val PHONE_NOTHING_SAID_MS = 8_000L
|
||||
|
||||
/** How long a recogniser that was asked to stop has to answer. */
|
||||
const val PHONE_GRACE_MS = 2_500L
|
||||
@@ -1,11 +1,17 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.Manifest
|
||||
import android.app.KeyguardManager
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.speech.RecognitionListener
|
||||
import android.speech.RecognitionService
|
||||
import android.speech.RecognizerIntent
|
||||
import android.speech.SpeechRecognizer
|
||||
import androidx.annotation.RequiresApi
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.lembas
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -15,11 +21,39 @@ import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Who writes down what an app asked the system's recogniser to hear. */
|
||||
enum class Recognise {
|
||||
/** The instance's speech-to-text: the recording is sent to it. */
|
||||
Instance,
|
||||
|
||||
/** The phone's on-device recogniser: nothing leaves the phone through LLeMbas. */
|
||||
OnDevice,
|
||||
|
||||
/** Nobody: the calling app is told there is no recogniser for it now. */
|
||||
Refuse,
|
||||
}
|
||||
|
||||
/**
|
||||
* The lock-screen rule for the system recogniser: nothing goes to the instance while the phone
|
||||
* is [locked], whoever asks. Locked, the on-device recogniser hears it where the phone has one
|
||||
* ([onDevice]); a phone without one answers the app that it cannot.
|
||||
*/
|
||||
fun recogniseWith(locked: Boolean, onDevice: Boolean): Recognise = when {
|
||||
!locked -> Recognise.Instance
|
||||
onDevice -> Recognise.OnDevice
|
||||
else -> Recognise.Refuse
|
||||
}
|
||||
|
||||
/**
|
||||
* Speech recognition through the instance (`/v1/audio/transcriptions`). Android requires a
|
||||
* digital assistant to name a recognition service; this is it, and any app that asks the
|
||||
* system's recognizer while LLeMbas is the assistant is answered by the instance's
|
||||
* speech-to-text. Listening ends when the caller says stop, or after [LIMIT_MS].
|
||||
* speech-to-text. Listening ends when the caller says stop, at a pause after speech or when
|
||||
* nothing is said ([EndOfSpeech], as in the assistant's sheet), or after [LIMIT_MS].
|
||||
*
|
||||
* Not while the phone is locked ([recogniseWith]): an app over the lock screen gets the phone's
|
||||
* on-device recogniser, or [UNAVAILABLE]. A phone that locks while a recording is being made
|
||||
* sends nothing either.
|
||||
*/
|
||||
class LembasRecognitionService : RecognitionService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
@@ -27,31 +61,133 @@ class LembasRecognitionService : RecognitionService() {
|
||||
private var callback: RecognitionService.Callback? = null
|
||||
private var limit: Job? = null
|
||||
|
||||
/** The on-device recogniser hearing a locked phone's request, while it does. */
|
||||
private var phone: SpeechRecognizer? = null
|
||||
|
||||
private fun locked(): Boolean = getSystemService(KeyguardManager::class.java)?.isKeyguardLocked == true
|
||||
|
||||
private fun onDevice(): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(this)
|
||||
|
||||
override fun onStartListening(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
listener.error(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS)
|
||||
return
|
||||
}
|
||||
dropPhone()
|
||||
when (recogniseWith(locked(), onDevice())) {
|
||||
Recognise.Instance -> Unit
|
||||
|
||||
Recognise.OnDevice -> {
|
||||
if (Build.VERSION.SDK_INT >= 31) listenOnDevice(intent, listener)
|
||||
return
|
||||
}
|
||||
|
||||
Recognise.Refuse -> {
|
||||
listener.error(UNAVAILABLE)
|
||||
return
|
||||
}
|
||||
}
|
||||
callback = listener
|
||||
recorder.start()
|
||||
listener.readyForSpeech(Bundle())
|
||||
listener.beginningOfSpeech()
|
||||
limit = scope.launch {
|
||||
delay(LIMIT_MS)
|
||||
val ear = EndOfSpeech()
|
||||
var waited = 0L
|
||||
while (waited < LIMIT_MS) {
|
||||
delay(EndOfSpeech.TICK_MS)
|
||||
waited += EndOfSpeech.TICK_MS
|
||||
when (ear.tick(recorder.level.value)) {
|
||||
EndOfSpeech.Verdict.Said -> break
|
||||
|
||||
// Nothing said is nothing sent: silence written down is an invented sentence.
|
||||
EndOfSpeech.Verdict.Nothing -> {
|
||||
silent()
|
||||
return@launch
|
||||
}
|
||||
|
||||
EndOfSpeech.Verdict.Listening -> Unit
|
||||
}
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's on-device recogniser in LLeMbas's place: what it hears and says goes to the
|
||||
* calling app as it is. Never the system's default recogniser, which is this service.
|
||||
*/
|
||||
@RequiresApi(31)
|
||||
private fun listenOnDevice(intent: Intent?, listener: RecognitionService.Callback) {
|
||||
val made = SpeechRecognizer.createOnDeviceSpeechRecognizer(this)
|
||||
phone = made
|
||||
// The calling app may be gone by the time a word comes: nobody is left to tell.
|
||||
fun tell(say: () -> Unit) {
|
||||
runCatching(say)
|
||||
}
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) = tell { listener.readyForSpeech(params ?: Bundle()) }
|
||||
|
||||
override fun onBeginningOfSpeech() = tell { listener.beginningOfSpeech() }
|
||||
|
||||
override fun onRmsChanged(rmsdB: Float) = tell { listener.rmsChanged(rmsdB) }
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = tell { listener.endOfSpeech() }
|
||||
|
||||
override fun onError(error: Int) {
|
||||
dropPhone()
|
||||
tell { listener.error(error) }
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
dropPhone()
|
||||
tell { listener.results(results ?: Bundle()) }
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) = tell { listener.partialResults(partialResults ?: Bundle()) }
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
},
|
||||
)
|
||||
made.startListening(intent?.let { Intent(it) } ?: Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH))
|
||||
}
|
||||
|
||||
private fun dropPhone() {
|
||||
phone?.runCatching {
|
||||
cancel()
|
||||
destroy()
|
||||
}
|
||||
phone = null
|
||||
}
|
||||
|
||||
override fun onStopListening(listener: RecognitionService.Callback) {
|
||||
phone?.let {
|
||||
it.stopListening()
|
||||
return
|
||||
}
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCancel(listener: RecognitionService.Callback) {
|
||||
dropPhone()
|
||||
limit?.cancel()
|
||||
callback = null
|
||||
scope.launch { recorder.stop() }
|
||||
}
|
||||
|
||||
/** Nobody spoke: the caller is told so, and nothing is written down. */
|
||||
private fun silent() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
scope.launch {
|
||||
recorder.stop()
|
||||
listener.error(SpeechRecognizer.ERROR_SPEECH_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
private fun finish() {
|
||||
val listener = callback ?: return
|
||||
callback = null
|
||||
@@ -59,8 +195,14 @@ class LembasRecognitionService : RecognitionService() {
|
||||
scope.launch {
|
||||
val wav = recorder.stop()
|
||||
listener.endOfSpeech()
|
||||
// The phone locked while it listened: the recording goes nowhere.
|
||||
if (locked()) {
|
||||
listener.error(UNAVAILABLE)
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val text = lembas.instances.client()?.transcribe(wav).orEmpty()
|
||||
// Another app's dictation belongs to no chat: the instance's default writes it down.
|
||||
val text = lembas.instances.client()?.transcribe(wav, media = MediaFor.DEFAULT)?.text.orEmpty()
|
||||
if (text.isBlank()) {
|
||||
listener.error(SpeechRecognizer.ERROR_NO_MATCH)
|
||||
} else {
|
||||
@@ -73,11 +215,19 @@ class LembasRecognitionService : RecognitionService() {
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
dropPhone()
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val LIMIT_MS = 15_000L
|
||||
|
||||
/**
|
||||
* What a calling app is told when nothing may hear it now: the recogniser is busy, which
|
||||
* is the error an app takes as "not now, try again" rather than as its own mistake or a
|
||||
* missing permission.
|
||||
*/
|
||||
const val UNAVAILABLE = SpeechRecognizer.ERROR_RECOGNIZER_BUSY
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package eu.llembas.android.assist
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Telling the app's own intents from anybody's. [AssistActivity] is exported -- Android's
|
||||
* `ACTION_ASSIST` and a headset's voice button must reach it -- so any app can start it with any
|
||||
* action and any extras. What only the app's own parts may ask for (open listening, continue the
|
||||
* last chat, turn the screen on, take a handed-over question) is therefore honoured only on an
|
||||
* intent that carries the app's own mark: a random value made once on this phone and kept in the
|
||||
* app's private storage. The widget's and the shortcuts' intents carry it inside a
|
||||
* `PendingIntent` or a shortcut, which no other app can read.
|
||||
*/
|
||||
object OwnIntents {
|
||||
private const val STORE = "own_intents"
|
||||
private const val KEY = "mark"
|
||||
private const val EXTRA_MARK = "eu.llembas.android.OWN"
|
||||
|
||||
@Volatile
|
||||
private var cached: String? = null
|
||||
|
||||
private fun mark(context: Context): String = cached ?: synchronized(this) {
|
||||
cached ?: run {
|
||||
val store = context.applicationContext.getSharedPreferences(STORE, Context.MODE_PRIVATE)
|
||||
val kept = store.getString(KEY, null) ?: newMark().also { store.edit().putString(KEY, it).apply() }
|
||||
cached = kept
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
private fun newMark(): String = ByteArray(24).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
|
||||
/** [intent], marked as the app's own. */
|
||||
fun own(context: Context, intent: Intent): Intent = intent.putExtra(EXTRA_MARK, mark(context))
|
||||
|
||||
/** Whether [intent] was made by the app itself. */
|
||||
fun isOwn(context: Context, intent: Intent?): Boolean = sameMark(runCatching { intent?.getStringExtra(EXTRA_MARK) }.getOrNull(), mark(context))
|
||||
|
||||
/** Compared in full, whatever differs: how long it takes says nothing about where. */
|
||||
internal fun sameMark(given: String?, kept: String): Boolean {
|
||||
if (given == null || given.length != kept.length) return false
|
||||
var differs = 0
|
||||
for (i in kept.indices) differs = differs or (given[i].code xor kept[i].code)
|
||||
return differs == 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A question on its way from one sheet to the other -- the assistant's own sheet hands what was
|
||||
* typed or heard over the lock screen to [AssistActivity], which can ask Android to unlock. It
|
||||
* never travels in the intent: an intent's extras are whatever its sender says, and a question
|
||||
* found there would be asked on the account for any app that put it there. The question waits
|
||||
* here, in the app's own memory; the intent carries only the ticket, good once.
|
||||
*/
|
||||
object AssistHandOff {
|
||||
private var ticket: String? = null
|
||||
private var waiting: Held? = null
|
||||
|
||||
/** Leave [question] here; the ticket to put on the intent. */
|
||||
@Synchronized
|
||||
fun leave(question: Held): String {
|
||||
val made = ByteArray(16).also { SecureRandom().nextBytes(it) }.joinToString("") { "%02x".format(it) }
|
||||
ticket = made
|
||||
waiting = question
|
||||
return made
|
||||
}
|
||||
|
||||
/** The question left under [given], once; nothing for any other ticket, or none. */
|
||||
@Synchronized
|
||||
fun take(given: String?): Held? {
|
||||
val kept = ticket ?: return null
|
||||
if (given == null || !OwnIntents.sameMark(given, kept)) return null
|
||||
val question = waiting
|
||||
ticket = null
|
||||
waiting = null
|
||||
return question
|
||||
}
|
||||
}
|
||||
@@ -107,6 +107,22 @@ class Recorder(private val scope: CoroutineScope) {
|
||||
return if (body.isEmpty()) body else wav(body)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and keep nothing, at once and without a coroutine: for when the scope that would
|
||||
* run [stop] is already cancelled (the sheet is going), and the microphone must still be
|
||||
* let go.
|
||||
*/
|
||||
fun stopNow() {
|
||||
val audio = record ?: return
|
||||
record = null
|
||||
job?.cancel()
|
||||
// Stop returns the blocked `read`; the loop then sees it is cancelled, or reads an error.
|
||||
runCatching { audio.stop() }
|
||||
runCatching { audio.release() }
|
||||
_level.value = 0f
|
||||
pcm.reset()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RATE = 16_000
|
||||
private const val MAX_BYTES = RATE * 2 * 120 // two minutes
|
||||
@@ -255,53 +271,66 @@ private fun words(text: String): List<String> = text.lowercase()
|
||||
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) {
|
||||
/** [onActive]: a sign that somebody is speaking -- "speech began", or a loud level -- for a recogniser that shows no words meanwhile. */
|
||||
fun start(onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit, onActive: () -> Unit = {}) {
|
||||
stop()
|
||||
startWith(onDevice(context), onPartial, onLevel, onResult, onFail)
|
||||
startWith(onDevice(context), Heard(onPartial, onLevel, onResult, onFail, onActive))
|
||||
}
|
||||
|
||||
private class Heard(
|
||||
val onPartial: (String) -> Unit,
|
||||
val onLevel: (Float) -> Unit,
|
||||
val onResult: (String) -> Unit,
|
||||
val onFail: (Int) -> Unit,
|
||||
val onActive: () -> Unit,
|
||||
)
|
||||
|
||||
// `onFail`, not `onError`: inside the listener below that name is the listener's own method.
|
||||
private fun startWith(onDevice: Boolean, onPartial: (String) -> Unit, onLevel: (Float) -> Unit, onResult: (String) -> Unit, onFail: (Int) -> Unit) {
|
||||
private fun startWith(onDevice: Boolean, to: Heard) {
|
||||
val other = component(context)
|
||||
val made = when {
|
||||
onDevice && Build.VERSION.SDK_INT >= 31 -> SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
|
||||
other != null -> SpeechRecognizer.createSpeechRecognizer(context, other)
|
||||
else -> return onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
else -> return to.onFail(SpeechRecognizer.ERROR_CLIENT)
|
||||
}
|
||||
recognizer = made
|
||||
made.setRecognitionListener(
|
||||
object : RecognitionListener {
|
||||
override fun onReadyForSpeech(params: Bundle?) {}
|
||||
|
||||
override fun onBeginningOfSpeech() {}
|
||||
override fun onBeginningOfSpeech() = to.onActive()
|
||||
|
||||
// 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 onRmsChanged(rmsdB: Float) {
|
||||
val level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f)
|
||||
to.onLevel(level)
|
||||
if (level >= LOUD) to.onActive()
|
||||
}
|
||||
|
||||
override fun onBufferReceived(buffer: ByteArray?) {}
|
||||
|
||||
override fun onEndOfSpeech() = onLevel(0f)
|
||||
override fun onEndOfSpeech() = to.onLevel(0f)
|
||||
|
||||
override fun onError(error: Int) {
|
||||
// The on-device recogniser lacks this language: another app's may have it.
|
||||
if (onDevice && other != null && (error == LANGUAGE_NOT_SUPPORTED || error == LANGUAGE_UNAVAILABLE)) {
|
||||
stop()
|
||||
startWith(false, onPartial, onLevel, onResult, onFail)
|
||||
startWith(false, to)
|
||||
return
|
||||
}
|
||||
stop()
|
||||
onFail(error)
|
||||
to.onFail(error)
|
||||
}
|
||||
|
||||
override fun onResults(results: Bundle?) {
|
||||
val text = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
|
||||
stop()
|
||||
onResult(text)
|
||||
to.onResult(text)
|
||||
}
|
||||
|
||||
override fun onPartialResults(partialResults: Bundle?) {
|
||||
partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()
|
||||
?.takeIf { it.isNotBlank() }?.let(onPartial)
|
||||
?.takeIf { it.isNotBlank() }?.let(to.onPartial)
|
||||
}
|
||||
|
||||
override fun onEvent(eventType: Int, params: Bundle?) {}
|
||||
@@ -311,6 +340,10 @@ class PhoneRecognizer(private val context: Context) {
|
||||
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
|
||||
.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
|
||||
.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
|
||||
// How long a silence ends it: a hint, which not every recogniser takes -- the
|
||||
// sheet keeps its own watch as well (phoneWatch).
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS, EndOfSpeech.PAUSE_MS)
|
||||
.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.packageName),
|
||||
)
|
||||
}
|
||||
@@ -333,6 +366,9 @@ class PhoneRecognizer(private val context: Context) {
|
||||
private const val LANGUAGE_NOT_SUPPORTED = 12
|
||||
private const val LANGUAGE_UNAVAILABLE = 13
|
||||
|
||||
/** Half of the meter: a level that is a voice, not a room. */
|
||||
private const val LOUD = 0.5f
|
||||
|
||||
private fun onDevice(context: Context): Boolean = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
|
||||
|
||||
/** Another app's recogniser -- never LLeMbas's own, which would send it back to the instance. */
|
||||
|
||||
@@ -9,6 +9,7 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.sameBase
|
||||
import eu.llembas.android.wake.WakeAttempt
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -21,9 +22,18 @@ import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/** One instance this phone is signed in to. The token is stored encrypted, never in the clear. */
|
||||
/**
|
||||
* One instance this phone is signed in to. The token is stored encrypted, never in the clear.
|
||||
* [base] is the address the person typed, as the address rule reads it; what the instance says
|
||||
* of its own address is not kept. [id] is a key and nothing more: whatever it was made from, it
|
||||
* is never taken apart or made again -- the choices kept for the instance, its notifications and
|
||||
* its push registration all hang on it.
|
||||
* [signedOut]: the instance refused that token (it was revoked there, or it expired). The entry
|
||||
* stays -- with its place in the list and every choice kept for it -- until the person signs in
|
||||
* again, which replaces the token, or removes it; meanwhile nothing more is asked with it.
|
||||
*/
|
||||
@Serializable
|
||||
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String)
|
||||
data class Instance(val id: String, val base: String, val name: String, val email: String, val sealedToken: String, val signedOut: Boolean = false)
|
||||
|
||||
/**
|
||||
* The token's lock: an AES key that lives in the Android Keystore and never leaves it. A copy
|
||||
@@ -65,8 +75,76 @@ object TokenCipher {
|
||||
private val Context.store by preferencesDataStore(name = "instances")
|
||||
private val INSTANCES = stringPreferencesKey("instances")
|
||||
private val ACTIVE = stringPreferencesKey("active")
|
||||
private val DEFAULT = stringPreferencesKey("default")
|
||||
private val PREFS = stringPreferencesKey("prefs")
|
||||
|
||||
/** Choices kept per instance (assistant model, last assistant chat, account language). */
|
||||
@Serializable
|
||||
data class PerInstancePrefs(
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
val lastAssistAt: Long = 0,
|
||||
val accountLanguage: String = "",
|
||||
)
|
||||
|
||||
/**
|
||||
* Pure selection and mutation rules for [InstanceStore]: kept free of Android types so unit
|
||||
* tests exercise default fallback, multi-account ids and removal directly.
|
||||
*/
|
||||
object InstanceLogic {
|
||||
fun pickDefault(instances: List<Instance>, defaultId: String?): Instance? = instances.firstOrNull { it.id == defaultId } ?: instances.firstOrNull()
|
||||
|
||||
fun pickActive(instances: List<Instance>, activeId: String?, defaultId: String?): Instance? =
|
||||
instances.firstOrNull { it.id == activeId } ?: pickDefault(instances, defaultId)
|
||||
|
||||
/**
|
||||
* The entry a finished sign-in is kept as. An instance already here for the same account --
|
||||
* its stored base is the address just typed, or the one the instance says of itself
|
||||
* ([said], which older versions of the app stored) -- is that same instance: it keeps its
|
||||
* id, and so everything kept under it, and gets the new token and the typed address. Only an
|
||||
* instance that is not here yet is a new entry, its id made from the typed address.
|
||||
*/
|
||||
fun signedIn(instances: List<Instance>, typed: String, said: String, name: String, email: String, sealedToken: String): Instance {
|
||||
val twin = instances.firstOrNull {
|
||||
it.email.equals(email, ignoreCase = true) && (sameBase(it.base, typed) || (said.isNotBlank() && sameBase(it.base, said)))
|
||||
}
|
||||
return twin?.copy(base = typed, name = name, sealedToken = sealedToken, signedOut = false)
|
||||
?: Instance(id = "$email@$typed", base = typed, name = name, email = email, sealedToken = sealedToken)
|
||||
}
|
||||
|
||||
/** Adding [added] replaces any existing entry with the same id, makes it active, and sets it
|
||||
* as default only when no surviving default exists yet. */
|
||||
fun afterAdd(instances: List<Instance>, added: Instance, currentDefault: String?): Triple<List<Instance>, String, String> {
|
||||
val next = instances.filter { it.id != added.id } + added
|
||||
val keptDefault = next.firstOrNull { it.id == currentDefault }?.id ?: added.id
|
||||
return Triple(next, added.id, keptDefault)
|
||||
}
|
||||
|
||||
/**
|
||||
* The list after the instance refused a token: every entry whose token [refused] says it was is
|
||||
* marked signed out, and nothing else changes -- not which instance is in use, not the default,
|
||||
* not another instance. Null when no entry changes (the token is nobody's any more, or its
|
||||
* entry is marked already), so that nothing is written.
|
||||
*/
|
||||
fun afterRefusal(instances: List<Instance>, refused: (Instance) -> Boolean): List<Instance>? {
|
||||
if (instances.none { !it.signedOut && refused(it) }) return null
|
||||
return instances.map { if (!it.signedOut && refused(it)) it.copy(signedOut = true) else it }
|
||||
}
|
||||
|
||||
/** Removing [removedId] promotes the surviving default (or first) for active, and the
|
||||
* surviving active (or first) for default, or null when no instance remains. */
|
||||
fun afterRemove(instances: List<Instance>, removedId: String, currentActive: String?, currentDefault: String?): Triple<List<Instance>, String?, String?> {
|
||||
val remaining = instances.filter { it.id != removedId }
|
||||
val nextDefault = remaining.firstOrNull { it.id == currentDefault }?.id
|
||||
?: remaining.firstOrNull { it.id == currentActive }?.id
|
||||
?: remaining.firstOrNull()?.id
|
||||
val nextActive = remaining.firstOrNull { it.id == currentActive }?.id
|
||||
?: nextDefault
|
||||
return Triple(remaining, nextActive, nextDefault)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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].
|
||||
@@ -115,7 +193,34 @@ data class Prefs(
|
||||
val updateCheckedAt: Long = 0,
|
||||
/** The last version a notification announced, so it is announced once. */
|
||||
val updateNotified: String = "",
|
||||
/** Per-instance choices, keyed by [Instance.id]. */
|
||||
val perInstance: Map<String, PerInstancePrefs> = emptyMap(),
|
||||
) {
|
||||
fun forInstance(id: String?): PerInstancePrefs = id?.let { perInstance[it] } ?: PerInstancePrefs(
|
||||
assistantModel = assistantModel,
|
||||
lastAssistChat = lastAssistChat,
|
||||
lastAssistTitle = lastAssistTitle,
|
||||
lastAssistAt = lastAssistAt,
|
||||
accountLanguage = accountLanguage,
|
||||
)
|
||||
|
||||
fun withInstance(id: String?, change: (PerInstancePrefs) -> PerInstancePrefs): Prefs {
|
||||
val updated = change(forInstance(id))
|
||||
return if (id == null) {
|
||||
copy(
|
||||
assistantModel = updated.assistantModel,
|
||||
lastAssistChat = updated.lastAssistChat,
|
||||
lastAssistTitle = updated.lastAssistTitle,
|
||||
lastAssistAt = updated.lastAssistAt,
|
||||
accountLanguage = updated.accountLanguage,
|
||||
)
|
||||
} else {
|
||||
copy(perInstance = perInstance + (id to updated))
|
||||
}
|
||||
}
|
||||
|
||||
fun withoutInstance(id: String): Prefs = if (id in perInstance) copy(perInstance = perInstance - id) else this
|
||||
|
||||
companion object {
|
||||
const val VOICE_LEMBAS = "lembas"
|
||||
const val VOICE_PHONE = "phone"
|
||||
@@ -129,9 +234,14 @@ class InstanceStore(private val context: Context) {
|
||||
prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
}
|
||||
|
||||
val defaultInstance: Flow<Instance?> = context.store.data.map { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
InstanceLogic.pickDefault(all, prefs[DEFAULT])
|
||||
}
|
||||
|
||||
val active: Flow<Instance?> = context.store.data.map { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
all.firstOrNull { it.id == prefs[ACTIVE] } ?: all.firstOrNull()
|
||||
InstanceLogic.pickActive(all, prefs[ACTIVE], prefs[DEFAULT])
|
||||
}
|
||||
|
||||
val prefs: Flow<Prefs> = context.store.data.map { p ->
|
||||
@@ -140,35 +250,77 @@ class InstanceStore(private val context: Context) {
|
||||
|
||||
suspend fun current(): Instance? = active.first()
|
||||
|
||||
suspend fun client(): ApiClient? = current()?.let { clientFor(it) }
|
||||
suspend fun default(): Instance? = defaultInstance.first()
|
||||
|
||||
/** A client for the instance in use; none when there is no instance, or it signed this phone out. */
|
||||
suspend fun client(): ApiClient? = current()?.takeUnless { it.signedOut }?.let { clientFor(it) }
|
||||
|
||||
suspend fun defaultClient(): ApiClient? = default()?.takeUnless { it.signedOut }?.let { clientFor(it) }
|
||||
|
||||
fun clientFor(instance: Instance): ApiClient = ApiClient(instance.base, TokenCipher.open(instance.sealedToken))
|
||||
|
||||
suspend fun add(base: String, name: String, email: String, token: String): Instance {
|
||||
val instance = Instance(
|
||||
id = "$email@$base",
|
||||
base = base,
|
||||
name = name,
|
||||
email = email,
|
||||
sealedToken = TokenCipher.seal(token),
|
||||
)
|
||||
/**
|
||||
* A sign-in finished: at [base], the address the person typed as the address rule reads it,
|
||||
* which is the one kept. [said] is the instance's own word for its address -- never stored,
|
||||
* and looked at only to know an instance signed in to before ([InstanceLogic.signedIn]).
|
||||
*/
|
||||
suspend fun add(base: String, said: String, name: String, email: String, token: String) {
|
||||
val locked = TokenCipher.seal(token)
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != instance.id } + instance)
|
||||
prefs[ACTIVE] = instance.id
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
val instance = InstanceLogic.signedIn(all, base, said, name, email, locked)
|
||||
val (next, activeId, defaultId) = InstanceLogic.afterAdd(all, instance, prefs[DEFAULT])
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next)
|
||||
prefs[ACTIVE] = activeId
|
||||
prefs[DEFAULT] = defaultId
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance refused [token] (a 401 of its own): the entry that holds it is marked signed
|
||||
* out. Asked by the token, never by "the one in use": the answer may be to a request of
|
||||
* another instance, or to one sent before the person switched or signed in again -- a token
|
||||
* that is no entry's any more marks nothing.
|
||||
*/
|
||||
suspend fun refused(token: String) {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
val next = InstanceLogic.afterRefusal(all) { runCatching { TokenCipher.open(it.sealedToken) }.getOrNull() == token }
|
||||
if (next != null) prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, next)
|
||||
}
|
||||
return instance
|
||||
}
|
||||
|
||||
suspend fun use(id: String) {
|
||||
context.store.edit { it[ACTIVE] = id }
|
||||
}
|
||||
|
||||
suspend fun setDefault(id: String) {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
if (all.any { it.id == id }) prefs[DEFAULT] = id
|
||||
}
|
||||
}
|
||||
|
||||
/** On a cold start with no notification target, switch active back to the default instance. */
|
||||
suspend fun resetToDefault() {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
InstanceLogic.pickDefault(all, prefs[DEFAULT])?.let { prefs[ACTIVE] = it.id }
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun remove(id: String) {
|
||||
context.store.edit { prefs ->
|
||||
val all = prefs[INSTANCES]?.let { LembasJson.decodeFromString(listSerializer, it) } ?: emptyList()
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, all.filter { it.id != id })
|
||||
if (prefs[ACTIVE] == id) prefs.remove(ACTIVE)
|
||||
val all = prefs[INSTANCES]?.let { runCatching { LembasJson.decodeFromString(listSerializer, it) }.getOrNull() } ?: emptyList()
|
||||
val (remaining, nextActive, nextDefault) = InstanceLogic.afterRemove(all, id, prefs[ACTIVE], prefs[DEFAULT])
|
||||
prefs[INSTANCES] = LembasJson.encodeToString(listSerializer, remaining)
|
||||
if (nextActive != null) prefs[ACTIVE] = nextActive else prefs.remove(ACTIVE)
|
||||
if (nextDefault != null) prefs[DEFAULT] = nextDefault else prefs.remove(DEFAULT)
|
||||
prefs[PREFS]?.let { raw ->
|
||||
runCatching { LembasJson.decodeFromString(Prefs.serializer(), raw) }.getOrNull()?.let { current ->
|
||||
prefs[PREFS] = LembasJson.encodeToString(Prefs.serializer(), current.withoutInstance(id))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,7 +146,8 @@ object Notifications {
|
||||
* 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.
|
||||
* Run again starts it again and Pause (there when offered) pauses the task, each only once
|
||||
* the phone is unlocked.
|
||||
*/
|
||||
private fun scheduled(context: Context, instance: String, payload: PushPayload) {
|
||||
val notice = ScheduledNotice.from(payload) ?: return
|
||||
@@ -179,7 +180,8 @@ object Notifications {
|
||||
}
|
||||
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)
|
||||
// It acts on the account, as Run again does: only once the phone is unlocked.
|
||||
builder.addAction(unlocked(notice.label("pause", context.getString(R.string.schedule_pause)), pause))
|
||||
}
|
||||
NotificationManagerCompat.from(context).notify(notice.id, builder.build())
|
||||
}
|
||||
|
||||
@@ -4,25 +4,35 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.provider.OpenableColumns
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.core.content.IntentCompat
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.MainActivity
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.assist.AssistSheetFrame
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.push.Notifications
|
||||
import eu.llembas.android.sendFrom
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.FolderPicker
|
||||
import eu.llembas.android.ui.files.LocalFile
|
||||
import eu.llembas.android.ui.files.describe
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.uploadFrom
|
||||
import eu.llembas.android.ui.theme.LembasTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
@@ -36,102 +46,221 @@ import kotlinx.coroutines.withContext
|
||||
* or to the last chat the assistant made; files are uploaded first and bound to that message, as
|
||||
* the composer's are. The chat then opens in the app. A new chat made here becomes the
|
||||
* assistant's last chat, so the next share can follow it.
|
||||
*
|
||||
* The instance is asked nothing until the person has chosen what to do, and no request starts
|
||||
* while the phone is locked or the sheet is not in front ([eu.llembas.android.InstanceGate]).
|
||||
*/
|
||||
class ShareActivity :
|
||||
ComponentActivity(),
|
||||
ShareActions {
|
||||
private val state = MutableStateFlow(ShareState())
|
||||
private var uris: List<Uri> = emptyList()
|
||||
|
||||
/** The files that came in and may be sent on ([SharedSource]), as the provider describes each. */
|
||||
private var files: List<LocalFile> = emptyList()
|
||||
private val choosing = MutableStateFlow(false)
|
||||
|
||||
/** How far "Save to Files" got into which folder: a second try takes it up at the one that failed. */
|
||||
private var kept = Kept()
|
||||
|
||||
/** The attachments already uploaded for which chat (null: a new one), so a second try does not upload them again. */
|
||||
private var attached: Pair<String?, List<String>> = null to emptyList()
|
||||
private var homeAsked = false
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
uris = when (intent.action) {
|
||||
val given = when (intent.action) {
|
||||
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
|
||||
Intent.ACTION_SEND_MULTIPLE -> IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
|
||||
else -> emptyList()
|
||||
}
|
||||
// The addresses are the other app's word: one that names something of this app's own is never opened.
|
||||
val taken = given.filter { SharedSource.acceptable(this, it) }
|
||||
val text = listOfNotNull(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString())
|
||||
.filter { it.isNotBlank() }
|
||||
.distinct()
|
||||
.joinToString("\n\n")
|
||||
.trim()
|
||||
state.update { it.copy(text = text, files = uris.map { uri -> SharedFile(nameOf(uri), (contentResolver.getType(uri) ?: "").startsWith("image/")) }) }
|
||||
state.update { it.copy(text = text, refused = taken.size < given.size, reading = taken.isNotEmpty()) }
|
||||
lifecycleScope.launch {
|
||||
// What each is called and how large, from its provider, before anything can be sent. The instance is asked nothing yet.
|
||||
files = withContext(Dispatchers.IO) { taken.map { contentResolver.describe(it) } }
|
||||
state.update { it.copy(files = files.map { f -> SharedFile(f.name, f.mime.startsWith("image/"), f.size) }, reading = false) }
|
||||
}
|
||||
lifecycleScope.launch {
|
||||
val store = lembas.instances
|
||||
val instance = store.default()
|
||||
val prefs = store.prefs.first()
|
||||
val own = prefs.forInstance(instance?.id)
|
||||
state.update {
|
||||
it.copy(
|
||||
signedIn = store.current() != null,
|
||||
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
|
||||
signedIn = instance != null,
|
||||
last = own.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
|
||||
?.let { id -> LastAssist(id, own.lastAssistTitle, own.lastAssistAt) },
|
||||
)
|
||||
}
|
||||
}
|
||||
setContent {
|
||||
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
|
||||
val shown by state.collectAsState()
|
||||
val picking by choosing.collectAsState()
|
||||
LembasTheme(prefs.theme) {
|
||||
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
|
||||
if (picking) {
|
||||
FolderPicker(
|
||||
stringResource(R.string.files_choose_folder),
|
||||
stringResource(R.string.files_save_here),
|
||||
shown.folder ?: "/",
|
||||
onPick = { folder ->
|
||||
choosing.value = false
|
||||
state.update { it.copy(folder = folder) }
|
||||
},
|
||||
onDismiss = { choosing.value = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun cancel() = finish()
|
||||
|
||||
override fun chooseFolder() {
|
||||
choosing.value = true
|
||||
}
|
||||
|
||||
/** The gate, before a request: nothing is sent while the phone is locked or the sheet is not in front. */
|
||||
private suspend fun turn() = lembas.gate.pass { waiting -> state.update { it.copy(waiting = waiting) } }
|
||||
|
||||
/**
|
||||
* "Save to Files" was chosen: only now is the instance asked where the person's files
|
||||
* open, once. Until it answers there is no folder and nothing can be saved; the folder
|
||||
* picker works either way.
|
||||
*/
|
||||
override fun toFiles() {
|
||||
if (homeAsked || state.value.folder != null) return
|
||||
homeAsked = true
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
turn()
|
||||
val home = lembas.instances.defaultClient()?.files("/")?.path ?: return@launch
|
||||
state.update { it.copy(folder = it.folder ?: home) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
homeAsked = false
|
||||
state.update { it.copy(error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep what was shared in the person's files: each file streamed into the folder as it is,
|
||||
* the text (when there is any) as a note beside them. No chat is made and no model is asked.
|
||||
* What the instance refuses -- a file over its limit, a folder that may not be written --
|
||||
* is said in its own sentence, and the sheet stays; Save again goes on from the file that
|
||||
* failed, into the same folder, and does not send the ones before it twice.
|
||||
*/
|
||||
override fun saveToFiles() {
|
||||
val now = state.value
|
||||
val folder = now.folder ?: return
|
||||
if (now.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val api = lembas.instances.defaultClient() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
// The files, then the text as a note (null): one queue, so a second try knows where it was.
|
||||
val items: List<LocalFile?> = if (now.text.isNotBlank()) files + listOf<LocalFile?>(null) else files
|
||||
kept = kept.into(folder)
|
||||
sendFrom(items, kept.done, { turn() }, { kept = kept.copy(done = it) }) { file ->
|
||||
if (file != null) {
|
||||
api.uploadFrom(this@ShareActivity, file, folder)
|
||||
} else {
|
||||
// The note is new each time: never over one that is there.
|
||||
api.saveFile(FileKinds.child(folder, sharedNoteName(java.time.LocalDateTime.now())), now.text + "\n", create = true)
|
||||
}
|
||||
}
|
||||
Toast.makeText(this@ShareActivity, R.string.files_uploaded, Toast.LENGTH_SHORT).show()
|
||||
finish()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.update { it.copy(sending = false, error = filesSay(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun send(ask: String, toLast: Boolean) {
|
||||
if (state.value.sending) return
|
||||
state.update { it.copy(sending = true, error = null) }
|
||||
lifecycleScope.launch {
|
||||
try {
|
||||
val store = lembas.instances
|
||||
val api = store.client() ?: run {
|
||||
val instance = store.default() ?: run {
|
||||
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
|
||||
finish()
|
||||
return@launch
|
||||
}
|
||||
val api = store.clientFor(instance)
|
||||
val now = state.value
|
||||
val into = if (toLast) now.last?.chatId else null
|
||||
val files = uris.map { uri ->
|
||||
val bytes = withContext(Dispatchers.IO) { contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) }
|
||||
api.upload(nameOf(uri), contentResolver.getType(uri) ?: "application/octet-stream", bytes, into).id
|
||||
// What a first try already uploaded for this chat is not uploaded again.
|
||||
if (attached.first != into) attached = into to emptyList()
|
||||
val ids = attached.second.toMutableList()
|
||||
sendFrom(files, ids.size, { turn() }, { attached = into to ids.toList() }) { file ->
|
||||
val bytes = withContext(Dispatchers.IO) { SharedSource.open(this@ShareActivity, file.uri).use { it.readBytes() } }
|
||||
ids += api.upload(file.name, file.mime, bytes, into).id
|
||||
}
|
||||
val sent = ids.toList()
|
||||
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
|
||||
turn()
|
||||
val chatId = if (into != null) {
|
||||
api.sendMessage(into, message, files)
|
||||
api.sendMessage(into, message, sent)
|
||||
into
|
||||
} else {
|
||||
val prefs = store.prefs.first()
|
||||
val made = api.createChat(message, files, model = prefs.assistantModel.ifBlank { null })
|
||||
store.savePrefs {
|
||||
it.copy(
|
||||
lastAssistChat = made.chat.id,
|
||||
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
|
||||
lastAssistAt = System.currentTimeMillis(),
|
||||
)
|
||||
// The assistant's model while the instance still has it; a model that is
|
||||
// gone is not asked for (the instance's default answers instead).
|
||||
val chosen = prefs.forInstance(instance.id).assistantModel
|
||||
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.let { it.named(chosen) == null } == true
|
||||
turn()
|
||||
val made = api.createChat(message, sent, model = chosen.takeIf { it.isNotBlank() && !gone })
|
||||
store.savePrefs { p ->
|
||||
p.withInstance(instance.id) {
|
||||
it.copy(
|
||||
lastAssistChat = made.chat.id,
|
||||
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
|
||||
lastAssistAt = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
}
|
||||
made.chat.id
|
||||
}
|
||||
startActivity(
|
||||
Intent(this@ShareActivity, MainActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
||||
.putExtra(Notifications.EXTRA_CHAT, chatId),
|
||||
.putExtra(Notifications.EXTRA_CHAT, chatId)
|
||||
.putExtra(Notifications.EXTRA_INSTANCE, instance.id),
|
||||
)
|
||||
finish()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The last chat deleted since: it is not offered again.
|
||||
if (e is ApiException && e.status == 404 && toLast) {
|
||||
lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
val id = lembas.instances.default()?.id
|
||||
lembas.instances.savePrefs { p ->
|
||||
p.withInstance(id) { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
|
||||
}
|
||||
state.update { it.copy(last = null) }
|
||||
}
|
||||
state.update { it.copy(sending = false, error = explain(e)) }
|
||||
state.update { it.copy(sending = false, error = if (e is SharedRefused) filesSay(e) else explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun nameOf(uri: Uri): String = runCatching {
|
||||
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
|
||||
}.getOrNull() ?: uri.lastPathSegment ?: "shared"
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -21,6 +22,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material3.Button
|
||||
@@ -43,6 +45,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
@@ -52,8 +55,16 @@ import eu.llembas.android.R
|
||||
import eu.llembas.android.assist.LastAssist
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** One shared file, as the sheet names it. */
|
||||
data class SharedFile(val name: String, val image: Boolean)
|
||||
/** One shared file, as the sheet names it: what its provider calls it and how large it says it is ([size] -1: it does not say). */
|
||||
data class SharedFile(val name: String, val image: Boolean, val size: Long = -1)
|
||||
|
||||
/** How far a "Save to Files" got: [done] of its queue are in [folder]. Another folder starts at the first again. */
|
||||
data class Kept(val folder: String = "", val done: Int = 0) {
|
||||
fun into(folder: String): Kept = if (folder == this.folder) this else Kept(folder, 0)
|
||||
}
|
||||
|
||||
/** A shared address that is not taken: not `content:`, this app's own provider, or one that opens onto this app's own files. */
|
||||
class SharedRefused : java.io.IOException("")
|
||||
|
||||
/** What was shared, where it may go, and how sending it went. */
|
||||
data class ShareState(
|
||||
@@ -64,6 +75,14 @@ data class ShareState(
|
||||
val last: LastAssist? = null,
|
||||
val sending: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** Where "Save to Files" would put it: the person's own folder until they choose another; null while it is not known. */
|
||||
val folder: String? = null,
|
||||
/** Something that came in was left out: its address named what another app may not have sent on ([SharedSource]). */
|
||||
val refused: Boolean = false,
|
||||
/** The files are still being asked what they are called. */
|
||||
val reading: Boolean = false,
|
||||
/** The next request waits for the phone to be unlocked and the sheet to be in front. */
|
||||
val waiting: Boolean = false,
|
||||
)
|
||||
|
||||
/** What the share sheet can do; nothing by default, for the screenshot tests. */
|
||||
@@ -71,20 +90,31 @@ interface ShareActions {
|
||||
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
|
||||
fun send(ask: String, toLast: Boolean) {}
|
||||
|
||||
/** Keep what was shared as files in [ShareState.folder], asking no model anything. */
|
||||
fun saveToFiles() {}
|
||||
|
||||
/** "Save to Files" was chosen as where it goes: the instance may now be asked where the person's files open. */
|
||||
fun toFiles() {}
|
||||
|
||||
/** Choose another folder to save into. */
|
||||
fun chooseFolder() {}
|
||||
|
||||
fun cancel() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, or the
|
||||
* last chat the assistant made -- and Send. Rows of unknown height stack; the two choices are
|
||||
* whole-row tap targets of at least 56 dp.
|
||||
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, the
|
||||
* last chat the assistant made, or the person's Files, where nothing is asked of a model -- and
|
||||
* Send or Save. Rows of unknown height stack; the choices are whole-row tap targets of at least
|
||||
* 56 dp.
|
||||
*/
|
||||
@Composable
|
||||
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var ask by remember { mutableStateOf("") }
|
||||
var toLast by remember { mutableStateOf(false) }
|
||||
var toFiles by remember { mutableStateOf(false) }
|
||||
val last = state.last
|
||||
|
||||
Column(handle.fillMaxWidth()) {
|
||||
@@ -141,8 +171,19 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(file.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (file.size >= 0) {
|
||||
// The name gives; the size is short and stays whole.
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
Formatter.formatShortFileSize(LocalContext.current, file.size),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.refused) Text(stringResource(R.string.share_refused), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
|
||||
// What to do with it.
|
||||
TextField(
|
||||
@@ -157,27 +198,47 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
unfocusedIndicatorColor = Color.Transparent,
|
||||
),
|
||||
maxLines = 4,
|
||||
enabled = !state.sending,
|
||||
// Files keep what was shared as it is: there is nobody to tell what to do with it.
|
||||
enabled = !state.sending && !toFiles,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
)
|
||||
|
||||
// Where it goes.
|
||||
if (last != null) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast, enabled = !state.sending) { toLast = false }
|
||||
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
|
||||
toLast =
|
||||
true
|
||||
Surface(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = palette.surfaceRaised,
|
||||
border = BorderStroke(1.dp, palette.border),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column {
|
||||
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast && !toFiles, enabled = !state.sending) {
|
||||
toLast = false
|
||||
toFiles = false
|
||||
}
|
||||
if (last != null) {
|
||||
Destination(
|
||||
Icons.Filled.History,
|
||||
stringResource(R.string.assist_continue),
|
||||
last.title,
|
||||
selected = toLast && !toFiles,
|
||||
enabled = !state.sending,
|
||||
) {
|
||||
toLast = true
|
||||
toFiles = false
|
||||
}
|
||||
}
|
||||
Destination(Icons.Filled.Folder, stringResource(R.string.share_to_files), state.folder, selected = toFiles, enabled = !state.sending) {
|
||||
toFiles = true
|
||||
actions.toFiles()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (toFiles) {
|
||||
TextButton(onClick = actions::chooseFolder, enabled = !state.sending, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_choose_folder))
|
||||
}
|
||||
}
|
||||
if (state.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
|
||||
}
|
||||
|
||||
@@ -189,11 +250,21 @@ fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, hand
|
||||
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Button(
|
||||
onClick = { actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
|
||||
onClick = { if (toFiles) actions.saveToFiles() else actions.send(ask, toLast && last != null) },
|
||||
enabled = !state.sending && !state.reading && (state.text.isNotBlank() || state.files.isNotEmpty()) && (!toFiles || state.folder != null),
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.heightIn(min = 48.dp),
|
||||
) { Text(stringResource(if (state.sending) R.string.share_sending else R.string.send)) }
|
||||
) {
|
||||
Text(
|
||||
stringResource(
|
||||
when {
|
||||
toFiles -> R.string.save
|
||||
state.sending -> R.string.share_sending
|
||||
else -> R.string.send
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,3 +299,7 @@ fun shareMessage(ask: String, shared: String, fallback: String): String {
|
||||
val request = ask.trim().ifBlank { fallback }
|
||||
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
|
||||
}
|
||||
|
||||
/** What shared text is called when it is kept as a file: `shared-20260102-030405.txt`, from the moment it was saved. */
|
||||
fun sharedNoteName(at: java.time.LocalDateTime): String =
|
||||
"shared-" + at.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss", java.util.Locale.ROOT)) + ".txt"
|
||||
@@ -0,0 +1,77 @@
|
||||
package eu.llembas.android.share
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.system.Os
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
|
||||
/**
|
||||
* What another app may hand this one to send on. A share names its files by address, and the
|
||||
* address is the other app's word: it could as well name something of this app's own -- a file
|
||||
* in its private data, a copy in its cache through its own provider -- and have the person send
|
||||
* it to a chat without knowing. So only a `content:` address of another app's provider is taken,
|
||||
* and what it opens must not be a file of this app's.
|
||||
*/
|
||||
object SharedSource {
|
||||
/**
|
||||
* Whether an address is refused by its looks: anything that is not `content:` (a `file:`
|
||||
* path is read with this app's own rights), and a provider that is this app's ([own]: its
|
||||
* authorities). An authority may carry a user before an `@`; the provider is what follows.
|
||||
*/
|
||||
fun refused(scheme: String?, authority: String?, own: Set<String>): Boolean {
|
||||
if (!scheme.equals("content", ignoreCase = true)) return true
|
||||
val provider = authority?.substringAfterLast('@')?.lowercase().orEmpty()
|
||||
return provider.isBlank() || provider in own.map { it.lowercase() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [resolved] -- where an opened descriptor really leads -- is inside one of [roots],
|
||||
* this app's private places. Compared by whole path segments: `/data/user/0/app` does not
|
||||
* hold `/data/user/0/app.other`.
|
||||
*/
|
||||
fun inside(resolved: String, roots: List<String>): Boolean = roots.any { root ->
|
||||
val base = root.trimEnd('/')
|
||||
base.isNotEmpty() && (resolved == base || resolved.startsWith("$base/"))
|
||||
}
|
||||
|
||||
/** This app's providers, by authority: its own FileProvider and whatever its libraries declare. */
|
||||
fun ownAuthorities(context: Context): Set<String> {
|
||||
val declared = runCatching {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_PROVIDERS).providers
|
||||
}.getOrNull().orEmpty()
|
||||
return declared.flatMap { it.authority.orEmpty().split(';') }.filter { it.isNotBlank() }.toSet() + (context.packageName + ".files")
|
||||
}
|
||||
|
||||
/** This app's private places, as the paths a descriptor can lead to (the data directory under each of its names). */
|
||||
fun privateRoots(context: Context): List<String> {
|
||||
val dirs = listOfNotNull(context.dataDir, context.filesDir?.parentFile, context.cacheDir, context.codeCacheDir, context.noBackupFilesDir) +
|
||||
context.externalCacheDirs.orEmpty().filterNotNull().mapNotNull { it.parentFile } +
|
||||
context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { it.parentFile }
|
||||
return dirs.flatMap { listOf(it.absolutePath, runCatching { it.canonicalPath }.getOrDefault(it.absolutePath)) }.distinct()
|
||||
}
|
||||
|
||||
fun acceptable(context: Context, uri: Uri): Boolean = !refused(uri.scheme, uri.authority, ownAuthorities(context))
|
||||
|
||||
/**
|
||||
* Opens what [uri] names for reading, or throws: an address refused by its looks is never
|
||||
* opened, and one that opens onto a file of this app's is closed again unread. The stream
|
||||
* is of the very descriptor that was looked at, so nothing can be swapped in between.
|
||||
*/
|
||||
fun open(context: Context, uri: Uri): InputStream {
|
||||
if (!acceptable(context, uri)) throw SharedRefused()
|
||||
val opened = context.contentResolver.openAssetFileDescriptor(uri, "r") ?: throw IOException("The file could not be opened.")
|
||||
try {
|
||||
val leads = runCatching { Os.readlink("/proc/self/fd/" + opened.parcelFileDescriptor.fd) }.getOrDefault("")
|
||||
val resolved = if (leads.startsWith("/")) runCatching { File(leads).canonicalPath }.getOrDefault(leads) else leads
|
||||
if (inside(resolved, privateRoots(context)) || inside(leads, privateRoots(context))) throw SharedRefused()
|
||||
return opened.createInputStream()
|
||||
} catch (e: Throwable) {
|
||||
runCatching { opened.close() }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.DirectoryEntry
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Choosing a folder on a linked computer: the last listing the device gave ([listing]; null
|
||||
* before the first, or where there never was one), the path in the field ([typed]: where the
|
||||
* walk is, or what the person wrote -- the way in that always works), and the sentence for a
|
||||
* listing that could not be had, or that came with one ([error]). [edited]: the person wrote in
|
||||
* the field since the device was last asked, so its answer does not write over them.
|
||||
* [failed]: the last question got no listing.
|
||||
*/
|
||||
data class PickerState(
|
||||
val listing: DeviceDirectory? = null,
|
||||
val loading: Boolean = false,
|
||||
val typed: String = "",
|
||||
val error: String? = null,
|
||||
val edited: Boolean = false,
|
||||
val failed: Boolean = false,
|
||||
)
|
||||
|
||||
/** The most subdirectories shown; a device that names more is cut there. */
|
||||
const val PICKER_ENTRIES = 500
|
||||
|
||||
/** The longest a device's own words are kept: a name, a reason, a sentence. */
|
||||
const val PICKER_WORDS = 300
|
||||
|
||||
private fun String.kept(): String = if (length > PICKER_WORDS) take(PICKER_WORDS) + "…" else this
|
||||
|
||||
/**
|
||||
* A listing as the picker holds it: each path once (the rows are keyed by it), at most
|
||||
* [PICKER_ENTRIES] of them, and the device's words -- names, reasons, a model's name -- cut to
|
||||
* a length that cannot push the controls away.
|
||||
*/
|
||||
fun DeviceDirectory.bounded(): DeviceDirectory = copy(
|
||||
reason = reason.kept(),
|
||||
error = error.kept(),
|
||||
model = model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) },
|
||||
entries = entries.filter { it.path.isNotEmpty() }.distinctBy { it.path }.take(PICKER_ENTRIES).map { entry ->
|
||||
entry.copy(name = entry.name.kept(), reason = entry.reason.kept(), model = entry.model?.let { it.copy(name = it.name.kept(), id = it.id.kept()) })
|
||||
},
|
||||
)
|
||||
|
||||
/** The device is being asked: what is typed from now on is the person's, newer than the answer. */
|
||||
fun PickerState.asking(): PickerState = copy(loading = true, error = null, edited = false)
|
||||
|
||||
/**
|
||||
* The device's answer. A listing is shown ([bounded]) and the field follows it -- unless the
|
||||
* person wrote in the field while the device was answering, or the listing is the places,
|
||||
* which have no path: then the field keeps what it has. A listing may come with a sentence
|
||||
* (part of it could not be read): it is shown with it. No listing -- the device is away, too
|
||||
* old, silent or said no -- leaves the last listing and the typed path where they were, with
|
||||
* the server's sentence ([fallback] where it sent none).
|
||||
*/
|
||||
fun PickerState.took(answer: DeviceDirectory, fallback: String = ""): PickerState = when {
|
||||
answer.listed -> copy(
|
||||
listing = answer.bounded(),
|
||||
loading = false,
|
||||
failed = false,
|
||||
error = answer.error.kept().ifBlank { null },
|
||||
typed = if (edited) typed else answer.path.ifEmpty { typed },
|
||||
)
|
||||
|
||||
else -> copy(loading = false, failed = true, error = answer.error.kept().ifBlank { fallback })
|
||||
}
|
||||
|
||||
/** The device could not be asked at all ([said]: why): as an answer without a listing. */
|
||||
fun PickerState.unanswered(said: String): PickerState = copy(loading = false, failed = true, error = said.kept())
|
||||
|
||||
/**
|
||||
* Where "up" leads from the listing shown: the parent, the places (`""`) from a directory that
|
||||
* has none, or null at the places themselves and where nothing is listed -- there the picker
|
||||
* closes instead.
|
||||
*/
|
||||
val PickerState.up: String?
|
||||
get() = listing?.takeIf { !it.places }?.parent
|
||||
|
||||
/**
|
||||
* Where Back leads: up a level, or null to close -- at the top, and after a question that got
|
||||
* no listing (the device went away mid-walk), where "up" would only ask it again for ever.
|
||||
*/
|
||||
val PickerState.back: String?
|
||||
get() = if (failed) null else up
|
||||
|
||||
/**
|
||||
* Whether the path in the field may be chosen: something is written, and it is not the listed
|
||||
* directory the device said it would open no session in. A path the device was never asked
|
||||
* about may be chosen: the instance checks it when it is used.
|
||||
*/
|
||||
val PickerState.canChoose: Boolean
|
||||
get() = typed.isNotBlank() && !refusedHere
|
||||
|
||||
/** The field holds the listed directory, and the device will not open a session there. */
|
||||
val PickerState.refusedHere: Boolean
|
||||
get() = listing?.let { !it.places && !it.accepted && it.path == typed.trim() } == true
|
||||
|
||||
interface PickerActions {
|
||||
fun open(path: String) {}
|
||||
fun typed(text: String) {}
|
||||
fun choose() {}
|
||||
fun back() {}
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* The directory picker over whatever asked for it: [load] asks the device for a path (`""`:
|
||||
* its places), [onPick] is given the chosen path. It opens at [initial], or at the places.
|
||||
* Back goes up a level, and closes at the top.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPicker(title: String, initial: String, load: suspend (String) -> DeviceDirectory, onPick: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(PickerState(typed = initial.trim(), loading = true)) }
|
||||
var reading by remember { mutableStateOf<Job?>(null) }
|
||||
val fallback = stringResource(R.string.directory_no_listing)
|
||||
val read: (String) -> Unit = { path ->
|
||||
reading?.cancel()
|
||||
state = state.asking()
|
||||
reading = scope.launch {
|
||||
try {
|
||||
val answer = load(path)
|
||||
// Applied to the state as it is now: `took` leaves what was typed meanwhile.
|
||||
state = state.took(answer, fallback)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.unanswered(context.explain(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { read(initial.trim()) }
|
||||
val actions = object : PickerActions {
|
||||
override fun open(path: String) = read(path)
|
||||
|
||||
override fun typed(text: String) {
|
||||
state = state.copy(typed = text, edited = true)
|
||||
}
|
||||
|
||||
override fun choose() {
|
||||
if (state.canChoose) onPick(state.typed.trim())
|
||||
}
|
||||
|
||||
override fun back() {
|
||||
val up = state.back
|
||||
if (up == null) onDismiss() else read(up)
|
||||
}
|
||||
|
||||
override fun close() = onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = actions::back, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
DirectoryPickerContent(title, state, actions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The picker, drawn from its state: where the walk is, the model last used there, the
|
||||
* subdirectories (a row is 56 dp; its name gives, the model beside it keeps to a third), and at
|
||||
* the foot the path as text with Choose -- which is all there is when the device lists nothing.
|
||||
*/
|
||||
@Composable
|
||||
fun DirectoryPickerContent(title: String, state: PickerState, actions: PickerActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val listing = state.listing
|
||||
Surface(color = palette.bg, contentColor = palette.ink, modifier = modifier.fillMaxSize()) {
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
IconButton(onClick = actions::back) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
Text(title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.padding(horizontal = 12.dp).size(20.dp))
|
||||
IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) }
|
||||
}
|
||||
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
Text(
|
||||
listing?.path?.ifEmpty { null } ?: stringResource(R.string.directory_places),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontFamily = if (listing?.places == false) FontFamily.Monospace else null,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
listing?.model?.let {
|
||||
Text(
|
||||
stringResource(R.string.directory_last_used, it.label),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (listing != null && !listing.places && !listing.accepted) {
|
||||
Text(
|
||||
listing.reason.ifBlank { stringResource(R.string.directory_refused) },
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
maxLines = 3,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
state.error?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger, maxLines = 4, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxWidth().weight(1f).padding(top = 8.dp)) {
|
||||
// The way out of a directory, and -- where nothing is listed -- the way to the places.
|
||||
if (listing?.places != true) {
|
||||
item(key = "up") {
|
||||
val places = listing == null || listing.parent.isEmpty()
|
||||
EntryRow(
|
||||
name = stringResource(if (places) R.string.directory_all_places else R.string.directory_up),
|
||||
icon = { Icon(Icons.Filled.ArrowUpward, contentDescription = null, tint = palette.inkMuted) },
|
||||
onClick = { actions.open(listing?.parent.orEmpty()) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (listing != null && listing.entries.isEmpty() && !state.loading) {
|
||||
item(key = "empty") {
|
||||
Text(
|
||||
stringResource(if (listing.places) R.string.directory_no_places else R.string.directory_empty),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(listing?.entries.orEmpty(), key = { "d:" + it.path }) { entry -> Entry(entry, onOpen = { actions.open(entry.path) }) }
|
||||
}
|
||||
HorizontalDivider(color = palette.border)
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
value = state.typed,
|
||||
onValueChange = actions::typed,
|
||||
singleLine = true,
|
||||
label = { Text(stringResource(R.string.directory_path)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(
|
||||
Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.End),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = actions::close, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
|
||||
Button(onClick = actions::choose, enabled = state.canChoose, modifier = Modifier.heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.directory_choose))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A subdirectory: its name, why no session opens in it where none does, and the model last used in it. */
|
||||
@Composable
|
||||
private fun Entry(entry: DirectoryEntry, onOpen: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
EntryRow(
|
||||
name = entry.name.ifBlank { entry.path },
|
||||
note = if (entry.accepted) null else entry.reason.ifBlank { stringResource(R.string.directory_not_trusted) },
|
||||
model = entry.model?.label,
|
||||
icon = {
|
||||
Icon(
|
||||
if (entry.accepted) Icons.Filled.Folder else Icons.Filled.FolderOff,
|
||||
contentDescription = null,
|
||||
tint = if (entry.accepted) palette.accent else palette.inkFaint,
|
||||
)
|
||||
},
|
||||
onClick = onOpen,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(name: String, icon: @Composable () -> Unit, onClick: () -> Unit, note: String? = null, model: String? = null) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(onClick = onClick).heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) { icon() }
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
note?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis) }
|
||||
}
|
||||
model?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.widthIn(max = 120.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,94 @@ package eu.llembas.android.ui
|
||||
import android.content.Context
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.NotLembas
|
||||
import java.io.InterruptedIOException
|
||||
import java.net.ConnectException
|
||||
import java.net.NoRouteToHostException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
import java.net.UnknownServiceException
|
||||
import java.security.cert.CertPathValidatorException
|
||||
import java.security.cert.CertificateException
|
||||
import javax.net.ssl.SSLPeerUnverifiedException
|
||||
|
||||
/** What went wrong between the phone and an instance, as the kinds a person can tell apart. */
|
||||
enum class Trouble {
|
||||
/** The instance said no, or answered with an error: its own sentence, or its number. */
|
||||
ANSWERED,
|
||||
|
||||
/** No way to it: no network, a name that does not resolve, a refused connection. */
|
||||
UNREACHABLE,
|
||||
|
||||
/** It was reached and did not answer in time. */
|
||||
TIMEOUT,
|
||||
|
||||
/** Its certificate is not one this phone trusts. */
|
||||
NOT_TRUSTED,
|
||||
|
||||
/** The address is plain http, which this app does not speak. */
|
||||
NEEDS_HTTPS,
|
||||
|
||||
/** Something answers there, and it is no LLeMbas instance. */
|
||||
NOT_LEMBAS,
|
||||
|
||||
/** None of these: the failure's own message is all there is. */
|
||||
OTHER,
|
||||
}
|
||||
|
||||
/** Which [Trouble] a failure is. Pure, so the cases are a table in a test. */
|
||||
fun trouble(e: Throwable): Trouble = when {
|
||||
e is ApiException -> Trouble.ANSWERED
|
||||
|
||||
e is NotLembas -> Trouble.NOT_LEMBAS
|
||||
|
||||
untrusted(e) -> Trouble.NOT_TRUSTED
|
||||
|
||||
e is UnknownHostException || e is ConnectException || e is NoRouteToHostException -> Trouble.UNREACHABLE
|
||||
|
||||
// OkHttp's own timeouts are an InterruptedIOException saying "timeout".
|
||||
e is SocketTimeoutException || (e is InterruptedIOException && e.message == "timeout") -> Trouble.TIMEOUT
|
||||
|
||||
// Android's network policy refusing cleartext: "CLEARTEXT communication to … not permitted".
|
||||
e is UnknownServiceException && e.message.orEmpty().contains("CLEARTEXT", ignoreCase = true) -> Trouble.NEEDS_HTTPS
|
||||
|
||||
else -> Trouble.OTHER
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* A failure in words a person can act on, one sentence for each kind of [Trouble]. The server's
|
||||
* refusal is its own sentence (a 403 says what is not allowed, and signs nobody out); an answer
|
||||
* without one is said with its number -- "the server answered 502" is never "cannot be reached"
|
||||
* and never "not a LLeMbas instance". A phone that cannot reach the instance at all, one that
|
||||
* waited in vain, and a certificate the phone does not trust each say so, the last with what to
|
||||
* do about it.
|
||||
*/
|
||||
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
|
||||
fun Context.explain(e: Throwable): String = when (trouble(e)) {
|
||||
Trouble.ANSWERED -> e.message?.ifBlank { null } ?: getString(R.string.server_answered, ((e as? ApiException)?.status ?: 0).toString())
|
||||
Trouble.UNREACHABLE -> getString(R.string.offline)
|
||||
Trouble.TIMEOUT -> getString(R.string.timed_out)
|
||||
Trouble.NOT_TRUSTED -> getString(R.string.not_trusted)
|
||||
Trouble.NEEDS_HTTPS -> getString(R.string.address_needs_https)
|
||||
Trouble.NOT_LEMBAS -> getString(R.string.signin_not_lembas)
|
||||
Trouble.OTHER -> 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
|
||||
|
||||
/**
|
||||
* Whether a failure is a certificate this phone does not trust: no authority the phone knows
|
||||
* signed it, it is out of date, or the name on it is another host's. Looked for down the
|
||||
* causes, where the platform puts it under the handshake's failure -- a handshake that failed
|
||||
* for another reason (no protocol in common) is not this.
|
||||
*/
|
||||
fun untrusted(e: Throwable): Boolean {
|
||||
var at: Throwable? = e
|
||||
var depth = 0
|
||||
while (at != null && depth < 8) {
|
||||
if (at is SSLPeerUnverifiedException || at is CertificateException || at is CertPathValidatorException) return true
|
||||
at = at.cause
|
||||
depth++
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package eu.llembas.android.ui
|
||||
|
||||
/**
|
||||
* A list with its next [page] put after it, no row twice. A list that is read a page at a time
|
||||
* asks for the next one whenever its end comes into view, and the end can come into view again
|
||||
* while that page is still on its way (the list was read again meanwhile, a row was added at its
|
||||
* head): the same page then arrives twice. The rows are keyed by [id], and a key drawn twice
|
||||
* ends the app -- so a row [held] already, or named twice by the page itself, is not added.
|
||||
*/
|
||||
fun <T> appended(held: List<T>, page: List<T>, id: (T) -> String): List<T> {
|
||||
val have = held.mapTo(HashSet()) { id(it) }
|
||||
return held + page.filter { have.add(id(it)) }
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import eu.llembas.android.api.CardAnswer
|
||||
import eu.llembas.android.api.CardItem
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.Plan
|
||||
import eu.llembas.android.api.showsDetail
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
/** The sentinel the web card's "Something else" row submits (`interaction.OTHER`). */
|
||||
@@ -73,6 +74,7 @@ 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 ->
|
||||
val views = diffViews(item.diffs)
|
||||
// A subagent asks, not the chat's own turn: said first, as the page says it.
|
||||
val subagent = item.subagent
|
||||
if (subagent != null) {
|
||||
@@ -100,9 +102,12 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
|
||||
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()) {
|
||||
} else if (item.detail.isNotBlank() && showsDetail(item, views)) {
|
||||
Text(item.detail, fontFamily = FontFamily.Monospace)
|
||||
}
|
||||
// An edit says what it would change: the diff stands where the call's arguments would,
|
||||
// as text. Diffs that say nothing (the same text twice) leave the arguments in view.
|
||||
if (item.diffs.isNotEmpty()) CardDiffs(item.diffs, views)
|
||||
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, and only when it was corrected.
|
||||
|
||||
@@ -8,6 +8,7 @@ import android.os.Build
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.gestures.scrollBy
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.interaction.DragInteraction
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
@@ -78,9 +79,11 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
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.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -91,14 +94,29 @@ 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.Attachment
|
||||
import eu.llembas.android.api.Drawn
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.drawn
|
||||
import eu.llembas.android.api.editable
|
||||
import eu.llembas.android.api.unrecordedReplies
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.ProgressStatus
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.DocumentDialog
|
||||
import eu.llembas.android.ui.viewer.FileViewer
|
||||
import eu.llembas.android.ui.viewer.PlayerDialog
|
||||
import eu.llembas.android.ui.viewer.Playing
|
||||
import eu.llembas.android.ui.viewer.Reading
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
@@ -117,6 +135,8 @@ fun ChatScreen(
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
/** Entered from a report (its Reply): the bar says "Report: title" and has Back, to the report, where the menu is. */
|
||||
report: String? = null,
|
||||
/** Open the person's Files at a folder: where a generated file's "Open in Files" leads. */
|
||||
onFiles: (String) -> Unit = {},
|
||||
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
@@ -134,6 +154,17 @@ fun ChatScreen(
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchActivity() }
|
||||
}
|
||||
// The chat's long generations (a video, a track), read again every few seconds while the
|
||||
// screen is in front and not otherwise. An agent chat runs on a computer and makes none.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null && !isAgent) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchMedia() }
|
||||
}
|
||||
// Replies nobody asked for from this screen (a subagent that woke the main agent, a schedule,
|
||||
// a turn the linked computer started): heard on the person's events route while the screen is
|
||||
// in front, and caught up with once on every return to it.
|
||||
LaunchedEffect(state.chat?.id) {
|
||||
if (state.chat?.id != null) lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { model.watchReplies() }
|
||||
}
|
||||
LaunchedEffect(state.error, state.notice) {
|
||||
(state.error ?: state.notice)?.let {
|
||||
snackbar.showSnackbar(it)
|
||||
@@ -141,10 +172,51 @@ fun ChatScreen(
|
||||
}
|
||||
}
|
||||
|
||||
// What a generated file's card does: the player over the chat, the folder in Files, and the
|
||||
// ways a file leaves the app. Its own transfers, as each screen that hands files out has.
|
||||
val transfers: TransferViewModel = viewModel(key = "chat-transfers")
|
||||
val saveTo = rememberSaver(transfers)
|
||||
var playing by remember { mutableStateOf<Playing?>(null) }
|
||||
var reading by remember { mutableStateOf<Reading?>(null) }
|
||||
val media = remember(model, transfers) {
|
||||
object : MediaActions {
|
||||
override fun play(media: GeneratedMedia) {
|
||||
playing = Playing(media.raw, media.title, media.size, video = media.view == MediaView.Video)
|
||||
}
|
||||
|
||||
override fun play(attachment: Attachment) {
|
||||
playing = Playing(Raw.Attached(attachment.id), attachment.name, attachment.size, video = attachment.kind == "video")
|
||||
}
|
||||
|
||||
override fun view(media: GeneratedMedia) {
|
||||
reading = Reading(media.raw, media.title, media.size)
|
||||
}
|
||||
|
||||
// Where the file is now, by its id: it may have been renamed or moved since it was made.
|
||||
override fun openInFiles(media: GeneratedMedia) = model.whereIs(media, onFiles)
|
||||
|
||||
override fun download(media: GeneratedMedia) = saveTo(media.raw, media.title, media.mime)
|
||||
|
||||
override fun share(media: GeneratedMedia) = transfers.share(media.raw, media.title, media.mime)
|
||||
|
||||
override fun openWith(media: GeneratedMedia) = transfers.openWith(media.raw, media.title)
|
||||
|
||||
override fun cancel(job: MediaJob) = model.cancelJob(job)
|
||||
}
|
||||
}
|
||||
|
||||
// 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) } } }
|
||||
val readAloud = remember {
|
||||
ReadAloud(
|
||||
context,
|
||||
scope,
|
||||
media = { model.state.value.mediaFor },
|
||||
onFallback = { source -> model.mediaFellBack(MEDIA_SPEECH, context.getString(R.string.read_by_fallback, source)) },
|
||||
onError = { said -> scope.launch { snackbar.showSnackbar(said) } },
|
||||
)
|
||||
}
|
||||
LaunchedEffect(Unit) { readAloud.load() }
|
||||
DisposableEffect(Unit) { onDispose { readAloud.stop() } }
|
||||
|
||||
@@ -161,6 +233,7 @@ fun ChatScreen(
|
||||
onShow = { showing = it },
|
||||
onKind = onKind,
|
||||
report = report,
|
||||
media = media,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -171,6 +244,9 @@ fun ChatScreen(
|
||||
showing?.let { file ->
|
||||
state.chat?.id?.let { id -> FileViewer(id, file, onClose = { showing = null }) }
|
||||
}
|
||||
playing?.let { PlayerDialog(it, onClose = { playing = null }, gone = stringResource(R.string.media_gone)) }
|
||||
reading?.let { DocumentDialog(it, onClose = { reading = null }, gone = stringResource(R.string.media_gone)) }
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
/** What the bar says of a chat entered from a report: "Report: title", or "Report" when the title is not known. */
|
||||
@@ -194,10 +270,13 @@ fun ChatContent(
|
||||
onShow: (ShowCard) -> Unit = {},
|
||||
onKind: ((agent: Boolean) -> Unit)? = null,
|
||||
report: String? = null,
|
||||
/** What the cards of generated media do; null draws none of them (a picture stays a picture). */
|
||||
media: MediaActions? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val chatMedia = remember(state.mediaJobs, media) { media?.let { ChatMedia(state.mediaJobs, it) } }
|
||||
// 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) }
|
||||
@@ -205,6 +284,7 @@ fun ChatContent(
|
||||
var tuning by remember { mutableStateOf(false) }
|
||||
var renaming by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf<Message?>(null) }
|
||||
var discarding by remember { mutableStateOf<Message?>(null) }
|
||||
var suggestion by remember { mutableStateOf("") }
|
||||
var suggested by remember { mutableIntStateOf(0) }
|
||||
val copy: (String) -> Unit = { text ->
|
||||
@@ -216,18 +296,81 @@ fun ChatContent(
|
||||
val live = state.live
|
||||
val rows = state.messages
|
||||
val info = state.modelInfo
|
||||
// Only in an agent chat: there a turn's reply is the linked computer's, and may never have been written here.
|
||||
val unrecorded = remember(rows, chat?.isAgent, live?.messageId) { if (chat?.isAgent == true) unrecordedReplies(rows, live?.messageId) else emptySet() }
|
||||
|
||||
// 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
|
||||
// The view keeps to the end while a reply is written only for a person who is there
|
||||
// (`Follow.kt` has the rule): a finger on the list ends the following at once, and where the
|
||||
// list comes to rest says whether it is taken up again. Kept over a rotation, with the place.
|
||||
var following by rememberSaveable { mutableStateOf(true) }
|
||||
var drawnBefore by rememberSaveable { mutableStateOf(false) }
|
||||
val slack = with(LocalDensity.current) { 48.dp.roundToPx() }
|
||||
// Whether a finger has been on the list since it last came to rest.
|
||||
val touched = remember { booleanArrayOf(false) }
|
||||
// How many of this app's own scrolls are under way (`ownScroll`): any other scroll is the person's.
|
||||
val own = remember { intArrayOf(0) }
|
||||
// The model drops the far end of a long transcript only under a person who is at its end.
|
||||
LaunchedEffect(following) { actions.reading(atEnd = following) }
|
||||
LaunchedEffect(list) {
|
||||
list.interactionSource.interactions.collect {
|
||||
if (it is DragInteraction.Start) {
|
||||
touched[0] = true
|
||||
following = false
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(list) {
|
||||
var moving = false
|
||||
var fromIndex = list.firstVisibleItemIndex
|
||||
var fromOffset = list.firstVisibleItemScrollOffset
|
||||
var startedByApp = false
|
||||
snapshotFlow { list.isScrollInProgress }.collect { now ->
|
||||
if (now && !moving) {
|
||||
fromIndex = list.firstVisibleItemIndex
|
||||
fromOffset = list.firstVisibleItemScrollOffset
|
||||
startedByApp = own[0] > 0
|
||||
}
|
||||
if (moving && !now) {
|
||||
// Only the person's own scroll ends the following (`restFollows`): this app's
|
||||
// scroll to the end, overtaken by a line that arrived meanwhile, does not.
|
||||
val byPerson = scrollWasPersons(
|
||||
touched = touched[0],
|
||||
wentBack = wentBack(fromIndex, fromOffset, list.firstVisibleItemIndex, list.firstVisibleItemScrollOffset),
|
||||
startedByApp = startedByApp,
|
||||
)
|
||||
following = restFollows(following, byPerson, list.distanceToEnd(), slack)
|
||||
touched[0] = false
|
||||
}
|
||||
moving = now
|
||||
}
|
||||
}
|
||||
// The rows as they were at the last draw, to tell a message sent from an older page loaded.
|
||||
val known = remember { arrayOfNulls<List<Message>>(1) }
|
||||
LaunchedEffect(rows) {
|
||||
val before = known[0]
|
||||
known[0] = rows
|
||||
val change = transcriptChange(before, rows, restored = drawnBefore, sent = state.lastSent)
|
||||
if (rows.isNotEmpty()) drawnBefore = true
|
||||
if (change == TranscriptChange.Older) {
|
||||
// An older page above the very top: the row that was first stays first, so reading
|
||||
// goes on upwards from it. Anywhere else the list keeps its place by the rows' keys.
|
||||
val kept = keptRow(before.orEmpty(), rows)
|
||||
if (kept != null && list.firstVisibleItemIndex == 0) ownScroll(own) { list.scrollToItem(kept + if (state.more) 1 else 0) }
|
||||
} else if (movesToEnd(change, following, personScrolls(list.isScrollInProgress, own[0]))) {
|
||||
// A list the person is moving is left to them: where it rests says whether it follows.
|
||||
following = true
|
||||
ownScroll(own) { list.toEnd() }
|
||||
}
|
||||
}
|
||||
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() }
|
||||
LaunchedEffect(growth) { if (growth > 0 && following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
// The keyboard opening takes the list's foot away: a person at the end stays at the end.
|
||||
LaunchedEffect(list) {
|
||||
// A finger on the list ends a scroll of ours by cancelling it: this follower goes on.
|
||||
snapshotFlow { list.layoutInfo.viewportSize.height }.drop(1).collect { if (following && !list.isScrollInProgress) ownScroll(own) { list.toEnd() } }
|
||||
}
|
||||
|
||||
CompositionLocalProvider(LocalCopy provides copy) {
|
||||
CompositionLocalProvider(LocalCopy provides copy, LocalChatMedia provides chatMedia) {
|
||||
Scaffold(
|
||||
containerColor = palette.bg,
|
||||
snackbarHost = { SnackbarHost(snackbar) },
|
||||
@@ -245,7 +388,7 @@ fun ChatContent(
|
||||
title = {
|
||||
ModelTitle(
|
||||
model = info,
|
||||
fallback = state.modelId ?: stringResource(R.string.app_name),
|
||||
fallback = state.modelWord ?: stringResource(R.string.app_name),
|
||||
// A report's conversation says which report: by what it was entered with, else by
|
||||
// what the chat itself says (after the app was closed in between).
|
||||
subtitle = if (report != null || chat?.report != null) {
|
||||
@@ -359,6 +502,8 @@ fun ChatContent(
|
||||
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
|
||||
}
|
||||
items(rows, key = { it.id }) { message ->
|
||||
// One key for a reply while it is written and once it is stored: the row
|
||||
// is the same row at `done`, so the list has nothing to put elsewhere.
|
||||
// The first row is the chat's first message only once nothing older is left to load.
|
||||
val first = !state.more && message.id == rows.firstOrNull()?.id
|
||||
when (drawn(message, first, reportChat = report != null || chat?.report != null)) {
|
||||
@@ -367,19 +512,32 @@ fun ChatContent(
|
||||
|
||||
Drawn.Note -> MachineNote(message.text.orEmpty())
|
||||
|
||||
Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = message })
|
||||
// A message that waits is sent now or discarded, never edited.
|
||||
Drawn.Person -> UserMessage(
|
||||
message,
|
||||
canEdit = message.editable(writing = live != null),
|
||||
onEdit = { editing = message },
|
||||
busy = state.acting != null,
|
||||
onSendNow = { actions.sendNow(message) },
|
||||
onDiscard = { discarding = message },
|
||||
)
|
||||
|
||||
Drawn.Reply -> when {
|
||||
live != null && live.messageId == message.id && live.finished == null ->
|
||||
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
|
||||
|
||||
else -> AssistantMessage(
|
||||
// One call for a reply being written and the same reply finished:
|
||||
// what the person opened in it (a thinking chip) stays open at `done`.
|
||||
// A finished reply with nothing in it, after a turn nobody typed: one
|
||||
// quiet line in its place, not a blank row with buttons.
|
||||
Drawn.Reply -> if (message.id in unrecorded) {
|
||||
MachineNote(stringResource(R.string.reply_unrecorded))
|
||||
} else {
|
||||
val writing = live?.takeIf { it.messageId == message.id && it.finished == null }
|
||||
AssistantMessage(
|
||||
message,
|
||||
message.steps,
|
||||
writing = false,
|
||||
writing?.shown ?: message.steps,
|
||||
writing = writing != null,
|
||||
canRegenerate = live == null && message == rows.lastOrNull(),
|
||||
onRegenerate = { actions.regenerate(message) },
|
||||
onShow = onShow,
|
||||
models = state.models,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -391,7 +549,7 @@ fun ChatContent(
|
||||
|
||||
if (picking) {
|
||||
ModalBottomSheet(onDismissRequest = { picking = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
ModelPickerContent(state.models, state.modelId, onPick = { id ->
|
||||
ModelPickerContent(state.models, state.modelInfo?.key, onPick = { id ->
|
||||
picking = false
|
||||
if (chat == null) actions.updateDraft { it.copy(model = id) } else actions.change("model", id)
|
||||
})
|
||||
@@ -431,6 +589,21 @@ fun ChatContent(
|
||||
)
|
||||
}
|
||||
|
||||
// Discarding cannot be taken back, so it is asked once -- in the page's own words.
|
||||
discarding?.let { message ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { discarding = null },
|
||||
text = { Text(stringResource(R.string.discard_message_confirm)) },
|
||||
confirmButton = {
|
||||
TextButton(onClick = {
|
||||
actions.discard(message)
|
||||
discarding = null
|
||||
}) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { discarding = null }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
editing?.let { message ->
|
||||
var text by remember(message.id) { mutableStateOf(message.text.orEmpty()) }
|
||||
AlertDialog(
|
||||
@@ -461,6 +634,14 @@ private suspend fun LazyListState.toEnd() {
|
||||
scrollBy(1_000_000f)
|
||||
}
|
||||
|
||||
/** How far the list stands from its very end, in pixels; a last row not on screen is "far". */
|
||||
private fun LazyListState.distanceToEnd(): Int {
|
||||
val info = layoutInfo
|
||||
val last = info.visibleItemsInfo.lastOrNull() ?: return 0
|
||||
if (last.index < info.totalItemsCount - 1) return Int.MAX_VALUE
|
||||
return last.offset + last.size + info.afterContentPadding - info.viewportEndOffset
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -514,7 +695,7 @@ private fun Greeting(
|
||||
}
|
||||
TextButton(onClick = onTune) { Text(where, textAlign = TextAlign.Center, color = palette.inkMuted) }
|
||||
} else {
|
||||
ModelAvatar(state.modelInfo, state.modelId ?: "?", size = 64.dp)
|
||||
ModelAvatar(state.modelInfo, state.modelWord ?: "?", size = 64.dp)
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Text(stringResource(R.string.empty_chat), style = MaterialTheme.typography.headlineSmall, textAlign = TextAlign.Center)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -28,12 +28,16 @@ import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.Brush
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.PhotoCamera
|
||||
import androidx.compose.material.icons.filled.PhotoLibrary
|
||||
@@ -51,7 +55,6 @@ 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
|
||||
@@ -83,12 +86,15 @@ import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.AgentsSetting
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.Mention
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -157,7 +163,9 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
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) }
|
||||
// Kept across the screen being made again: the camera is held sideways as often as not, and
|
||||
// the photo that comes back then must still know where it was taken to.
|
||||
var photo by rememberSaveable { 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.
|
||||
@@ -209,6 +217,9 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
// A suggestion from the empty chat lands here (a new value each tap).
|
||||
LaunchedEffect(initial) { if (initial.isNotBlank()) text = initial }
|
||||
// Asked again when the words change -- and when the computer or the folder does: an
|
||||
// agent chat's `@` is that folder's files.
|
||||
LaunchedEffect(text, state.chat?.id, state.device?.id, state.draft.directory) { actions.suggest(mentionQuery(text)) }
|
||||
val newAgent = agent && state.chat == null
|
||||
val canSend = (text.isNotBlank() || state.pending.isNotEmpty()) && !state.uploading && (!newAgent || state.device != null)
|
||||
val summary = tuneSummary(state, agent)
|
||||
@@ -262,6 +273,19 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
}
|
||||
}
|
||||
// What `@` offers for the word being typed, above the words: a tap attaches it (the
|
||||
// server's files, earlier attachments, pages) or completes it (a device's file).
|
||||
if (state.mentions.isNotEmpty() && mentionQuery(text) != null) {
|
||||
MentionList(state.mentions) { item ->
|
||||
if (item.kind == MENTION_DEVICE) {
|
||||
text = withMention(text, item.path)
|
||||
} else {
|
||||
text = withoutMention(text)
|
||||
actions.mention(item)
|
||||
}
|
||||
actions.suggest(null)
|
||||
}
|
||||
}
|
||||
TextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
@@ -374,8 +398,18 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
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() }
|
||||
// A transcription that was refused or never arrived is said: a field
|
||||
// that stays as it was, without a word, reads as "nothing was heard".
|
||||
try {
|
||||
val heard = context.lembas.instances.client()?.transcribe(wav, media = state.mediaFor)
|
||||
val said = heard?.text
|
||||
if (!said.isNullOrBlank()) text = (text + " " + said).trim()
|
||||
heard?.fallback?.let { actions.mediaFellBack(MEDIA_DICTATION, context.getString(R.string.transcribed_by_fallback, it)) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
actions.failed(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
|
||||
@@ -419,6 +453,48 @@ fun Composer(state: ChatState, actions: ChatActions, agent: Boolean, onTune: ()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The `@` list: at most a few rows in view, the rest scrolled to. A row is 48 dp; its name
|
||||
* gives, and where it is (a path, a kind) is one quiet line under it.
|
||||
*/
|
||||
@Composable
|
||||
private fun MentionList(items: List<Mention>, onPick: (Mention) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
Column(Modifier.fillMaxWidth().heightIn(max = 216.dp).verticalScroll(rememberScrollState()).padding(top = 8.dp)) {
|
||||
items.take(MENTION_LIMIT).forEach { item ->
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { onPick(item) }.heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
when (item.kind) {
|
||||
"url" -> Icons.Filled.Link
|
||||
"attachment" -> Icons.Filled.AttachFile
|
||||
else -> if (item.detail.endsWith("/")) Icons.Filled.Folder else Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
item.name.ifBlank {
|
||||
item.path.ifBlank { item.url }
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (item.detail.isNotBlank() && item.detail != item.name) {
|
||||
Text(item.detail, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- The tune sheet --------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -549,26 +625,15 @@ fun TuneContent(state: ChatState, actions: ChatActions, agent: Boolean, modifier
|
||||
}
|
||||
|
||||
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(),
|
||||
)
|
||||
DirectoryPicker(
|
||||
title = stringResource(R.string.agent_directory),
|
||||
initial = state.draft.directory,
|
||||
load = actions::directories,
|
||||
onPick = { path ->
|
||||
actions.updateDraft { it.copy(directory = path) }
|
||||
askDirectory = false
|
||||
},
|
||||
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)) } },
|
||||
onDismiss = { askDirectory = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
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.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.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.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
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.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.DiffLine
|
||||
import eu.llembas.android.api.DiffSign
|
||||
import eu.llembas.android.api.DiffView
|
||||
import eu.llembas.android.api.FileDiff
|
||||
import eu.llembas.android.api.view
|
||||
import eu.llembas.android.api.visibly
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.theme.Palette
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
// An edit's diff on its approval card: per file its path, how many lines come and go, and the
|
||||
// changed lines as text -- a sign before each and the theme's colour behind it, in one width of
|
||||
// letter. The lines scroll sideways in a box of their own, so the card never does. Both texts
|
||||
// are a model's and a file's words: one plain Text draws them, and nothing in them is rendered.
|
||||
|
||||
/** The most of one line that is drawn: a line of a megabyte is still one line of the card. */
|
||||
internal const val DIFF_LINE_MOST = 400
|
||||
|
||||
private val DiffShape = RoundedCornerShape(12.dp)
|
||||
|
||||
/**
|
||||
* A line as the card writes it: its sign, then its text cut at [DIFF_LINE_MOST], with whatever
|
||||
* a person could not see in it -- a direction override, a zero-width space, a line separator --
|
||||
* written as its code point ([visibly]).
|
||||
*/
|
||||
internal fun diffRow(line: DiffLine): String {
|
||||
val sign = when (line.sign) {
|
||||
DiffSign.Added -> "+ "
|
||||
DiffSign.Removed -> "- "
|
||||
DiffSign.Same -> " "
|
||||
DiffSign.Gap -> return "⋯"
|
||||
}
|
||||
val long = line.text.length > DIFF_LINE_MOST
|
||||
return sign + visibly(if (long) line.text.take(DIFF_LINE_MOST) else line.text) + if (long) "…" else ""
|
||||
}
|
||||
|
||||
private fun diffText(lines: List<DiffLine>, palette: Palette): AnnotatedString = buildAnnotatedString {
|
||||
lines.forEachIndexed { at, line ->
|
||||
val style = when (line.sign) {
|
||||
DiffSign.Added -> SpanStyle(color = palette.success, background = palette.successSoft)
|
||||
DiffSign.Removed -> SpanStyle(color = palette.danger, background = palette.dangerSoft)
|
||||
DiffSign.Same -> SpanStyle(color = palette.ink)
|
||||
DiffSign.Gap -> SpanStyle(color = palette.inkFaint)
|
||||
}
|
||||
withStyle(style) { append(diffRow(line)) }
|
||||
if (at < lines.lastIndex) append('\n')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The diffs of an item, worked out: null until they are. Off the main thread -- two texts of a
|
||||
* megabyte are not compared inside a frame -- and one file after another, so fifty files hold
|
||||
* one comparison's memory at a time. A screenshot has no later frame: there it is done at once.
|
||||
*/
|
||||
@Composable
|
||||
fun diffViews(diffs: List<FileDiff>): List<DiffView>? {
|
||||
if (diffs.isEmpty()) return emptyList()
|
||||
if (LocalInspectionMode.current) return remember(diffs) { diffs.map { it.view() } }
|
||||
val views by produceState<List<DiffView>?>(null, diffs) {
|
||||
value = withContext(Dispatchers.Default) {
|
||||
diffs.map {
|
||||
ensureActive()
|
||||
it.view()
|
||||
}
|
||||
}
|
||||
}
|
||||
return views
|
||||
}
|
||||
|
||||
/** The diffs of one item of an approval card, a block per file; [views] as [diffViews] gave them. */
|
||||
@Composable
|
||||
fun CardDiffs(diffs: List<FileDiff>, views: List<DiffView>?, modifier: Modifier = Modifier) {
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
diffs.forEachIndexed { at, diff -> key(at, diff.path) { FileDiffBlock(diff, views?.getOrNull(at)) } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One file's change. The path gives (it wraps) and the two counts keep their width. The lines
|
||||
* are folded to the first few; "Show all" opens them, up to what a card lays out. Until [view]
|
||||
* is worked out the block is its path alone.
|
||||
*/
|
||||
@Composable
|
||||
private fun FileDiffBlock(diff: FileDiff, view: DiffView?) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(diff.path) { mutableStateOf(false) }
|
||||
val path = remember(diff.path) { visibly(diff.path) }
|
||||
Column(Modifier.fillMaxWidth().clip(DiffShape).background(palette.codeBg).border(1.dp, palette.codeBorder, DiffShape)) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(path, style = MaterialTheme.typography.bodySmall, fontFamily = FontFamily.Monospace, color = palette.ink)
|
||||
val state = when {
|
||||
diff.deleted -> stringResource(R.string.diff_deleted)
|
||||
diff.made -> stringResource(R.string.files_new_file)
|
||||
else -> null
|
||||
}
|
||||
if (state != null) Text(state, style = MaterialTheme.typography.labelSmall, color = palette.inkMuted)
|
||||
}
|
||||
if (view != null) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
val counts = stringResource(R.string.diff_counts, view.added.toString(), view.removed.toString())
|
||||
Row(Modifier.clearAndSetSemantics { contentDescription = counts }, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text("+${view.added}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.success)
|
||||
Text("−${view.removed}", style = MaterialTheme.typography.labelMedium, fontFamily = FontFamily.Monospace, color = palette.danger)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (view != null) {
|
||||
// Said once, where every line would otherwise go and come with the same words.
|
||||
view.endings?.let { (from, to) -> DiffNote(stringResource(R.string.diff_endings, from, to)) }
|
||||
val lines = view.shown(open)
|
||||
if (lines.isNotEmpty()) {
|
||||
val text = remember(lines, palette) { diffText(lines, palette) }
|
||||
Box(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
softWrap = false,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (open && view.beyond > 0) DiffNote(stringResource(R.string.diff_more, view.beyond.toString()))
|
||||
if (view.cut) DiffNote(stringResource(R.string.diff_cut))
|
||||
if (view.folds) {
|
||||
TextButton(onClick = { open = !open }, modifier = Modifier.heightIn(min = 48.dp).padding(horizontal = 4.dp)) {
|
||||
Text(if (open) stringResource(R.string.diff_show_less) else stringResource(R.string.diff_show_all, view.lines.size.toString()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A sentence of the block's own, under its lines. */
|
||||
@Composable
|
||||
private fun DiffNote(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = LocalPalette.current.inkMuted,
|
||||
modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.Message
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
|
||||
/*
|
||||
* Whether a list keeps to its end while something is written into it. The rule, the same for the
|
||||
* chat's transcript and the assistant's sheet: the view follows only while the person is at the
|
||||
* end; once they have scrolled away it stays exactly where they are, and coming back to the end
|
||||
* takes the following up again. Nothing here knows Compose, so the tests read it as it is.
|
||||
*/
|
||||
|
||||
/** What happened to the transcript's rows between two draws. */
|
||||
enum class TranscriptChange {
|
||||
/** Nothing to follow: no rows, or the same rows. */
|
||||
None,
|
||||
|
||||
/** A chat shown for the first time, or another chat in the same place. */
|
||||
Opened,
|
||||
|
||||
/** A message this app just sent is new at the end: sending always shows what was sent. */
|
||||
Sent,
|
||||
|
||||
/** New rows at the end that the person did not write: a reply, the queue's next turn. */
|
||||
Appended,
|
||||
|
||||
/** An older page was put in front; the end has not moved. */
|
||||
Older,
|
||||
|
||||
/** Rows changed in place: a finished reply for the one being written, a transcript read again. */
|
||||
Changed,
|
||||
}
|
||||
|
||||
/**
|
||||
* What changed from [before] to [after]. [before] is null when this draw is the first one this
|
||||
* list makes; [restored] then says the list had rows before (a rotation, a return to the
|
||||
* screen), so its place is the one it kept, not a chat being opened. [sent] is the id of the
|
||||
* message this app sent last: only that one is "sent". The person's row arriving from
|
||||
* elsewhere -- written on the page or another device while this chat is open here -- is a row
|
||||
* like a reply's, and does not pull a reader down.
|
||||
*/
|
||||
fun transcriptChange(before: List<Message>?, after: List<Message>, restored: Boolean = false, sent: String? = null): TranscriptChange {
|
||||
if (after.isEmpty()) return TranscriptChange.None
|
||||
if (before == null) return if (restored) TranscriptChange.Changed else TranscriptChange.Opened
|
||||
val known = before.mapTo(HashSet()) { it.id }
|
||||
val firstKept = after.indexOfFirst { it.id in known }
|
||||
if (firstKept < 0) return TranscriptChange.Opened
|
||||
val added = after.subList(after.indexOfLast { it.id in known } + 1, after.size)
|
||||
return when {
|
||||
sent != null && added.any { it.id == sent } -> TranscriptChange.Sent
|
||||
added.isNotEmpty() -> TranscriptChange.Appended
|
||||
firstKept > 0 -> TranscriptChange.Older
|
||||
before == after -> TranscriptChange.None
|
||||
else -> TranscriptChange.Changed
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the view goes to the end after [change], given whether it was [following]. Opening a
|
||||
* chat and sending a message always do; an older page never does; everything else -- and a reply
|
||||
* growing, a keyboard opening -- only for a person who is at the end already, and never while
|
||||
* the list is being scrolled by the person ([personScrolling]): a wheel, a key or a screen
|
||||
* reader moving it upwards has not come to rest yet, so the following has not ended yet, and
|
||||
* going to the end now would cancel that scroll and throw the reader back down.
|
||||
*/
|
||||
fun movesToEnd(change: TranscriptChange, following: Boolean, personScrolling: Boolean = false): Boolean = when (change) {
|
||||
TranscriptChange.Opened, TranscriptChange.Sent -> true
|
||||
TranscriptChange.None, TranscriptChange.Older -> false
|
||||
TranscriptChange.Appended, TranscriptChange.Changed -> following && !personScrolling
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a scroll is the person's. One that is [inProgress] and that this app did not start
|
||||
* ([ownScrolls]: how many of the app's own scrolls are under way) is theirs, whatever moved
|
||||
* the list -- a finger, a wheel, a keyboard, a screen reader. The app marks its own; everything
|
||||
* else is somebody.
|
||||
*/
|
||||
fun personScrolls(inProgress: Boolean, ownScrolls: Int): Boolean = inProgress && ownScrolls <= 0
|
||||
|
||||
/**
|
||||
* Whether a scroll that has come to rest was the person's: a finger was on the list
|
||||
* ([touched]), the list went back towards its start ([wentBack]), or the scroll began with
|
||||
* none of this app's own under way ([startedByApp] false).
|
||||
*/
|
||||
fun scrollWasPersons(touched: Boolean, wentBack: Boolean, startedByApp: Boolean): Boolean = touched || wentBack || !startedByApp
|
||||
|
||||
/**
|
||||
* Whether the view follows, once a scroll has come to rest [distance] pixels short of the end.
|
||||
* Within [slack] counts as the end: a line that arrived while the list was settling must not
|
||||
* read as "scrolled away".
|
||||
*/
|
||||
fun followsAt(distance: Int, slack: Int): Boolean = distance <= slack
|
||||
|
||||
/**
|
||||
* Whether the view follows once a scroll has come to rest. Only a scroll the person made
|
||||
* ([byPerson]: a finger on the list, or the list gone back towards its start, which this
|
||||
* app's own scroll to the end never does) can end the following, by where it rests. Any other scroll is this
|
||||
* app's own keeping to the end; a line, a card or a picture that arrived before it settled
|
||||
* leaves it short of the end without anybody having left, and reading that as "scrolled away"
|
||||
* is what switches the following off under a person who never moved. Such a scroll can only
|
||||
* take the following up (it rested at the end), never end it.
|
||||
*/
|
||||
fun restFollows(following: Boolean, byPerson: Boolean, distance: Int, slack: Int): Boolean = if (byPerson) {
|
||||
followsAt(distance, slack)
|
||||
} else {
|
||||
following ||
|
||||
followsAt(distance, slack)
|
||||
}
|
||||
|
||||
/** Whether a list that stood at row [fromIndex], [fromOffset] pixels into it, has gone back towards its start. */
|
||||
fun wentBack(fromIndex: Int, fromOffset: Int, toIndex: Int, toOffset: Int): Boolean = toIndex < fromIndex || (toIndex == fromIndex && toOffset < fromOffset)
|
||||
|
||||
/**
|
||||
* The row that keeps its place when an older page arrives while the list stands at its very
|
||||
* top: the first row there was before, by its place in [after]. Null when it is gone.
|
||||
*/
|
||||
fun keptRow(before: List<Message>, after: List<Message>): Int? {
|
||||
val first = before.firstOrNull() ?: return null
|
||||
return after.indexOfFirst { it.id == first.id }.takeIf { it >= 0 }
|
||||
}
|
||||
|
||||
/**
|
||||
* A scroll this app makes for the person ([scroll]: to the end, as the reply grows). A finger
|
||||
* on the list takes it over, and Compose ends the scroll by cancelling it -- which, left
|
||||
* alone, would also end whatever follower called it, for good. So that cancellation is taken
|
||||
* here, and only that one: when the follower itself is cancelled, it still ends.
|
||||
*/
|
||||
suspend fun yielding(scroll: suspend () -> Unit) {
|
||||
try {
|
||||
scroll()
|
||||
} catch (e: CancellationException) {
|
||||
currentCoroutineContext().ensureActive()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [yielding], counted in [own] while it runs: how the list's watchers tell this app's scroll
|
||||
* from the person's ([personScrolls]). A count and not a flag: one of the app's scrolls may
|
||||
* overtake another, and the first one's end must not unmark the second.
|
||||
*/
|
||||
suspend fun ownScroll(own: IntArray, scroll: suspend () -> Unit) {
|
||||
own[0]++
|
||||
try {
|
||||
yielding(scroll)
|
||||
} finally {
|
||||
own[0]--
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,15 @@ 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.padding
|
||||
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.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -36,34 +39,54 @@ 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.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The pictures the instance made, fetched the two ways the app fetches a chat's files: by
|
||||
* attachment id, or -- for a generated file with no attachment -- by its node id in the
|
||||
* person's Files; always 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
|
||||
const val MAX_BYTES = 24L * 1024 * 1024
|
||||
private val cache = LruCache<String, ImageBitmap>(8)
|
||||
private val failed = mutableSetOf<String>()
|
||||
private val gone = mutableSetOf<String>()
|
||||
|
||||
fun cached(id: String): ImageBitmap? = cache.get(id)
|
||||
fun cached(key: String): ImageBitmap? = cache.get(key)
|
||||
|
||||
suspend fun load(context: Context, id: String): ImageBitmap? {
|
||||
cache.get(id)?.let { return it }
|
||||
if (id.isBlank() || id in failed) return null
|
||||
/** Whether the instance said there is no such file (any more). */
|
||||
fun isGone(key: String): Boolean = key in gone
|
||||
|
||||
suspend fun load(context: Context, key: String, fetch: suspend (ApiClient) -> ByteArray): ImageBitmap? {
|
||||
cache.get(key)?.let { return it }
|
||||
if (key in failed) return null
|
||||
val api = context.lembas.instances.client() ?: return null
|
||||
val bytes = runCatching { api.attachmentBytes(id) }.getOrNull()?.takeIf { it.size <= MAX_BYTES }
|
||||
// A picture that comes into view behind the lock, or with the app not in front, waits there.
|
||||
context.lembas.gate.passLater()
|
||||
val bytes = try {
|
||||
fetch(api).takeIf { it.size <= MAX_BYTES }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is ApiException && e.status == 404) gone += key
|
||||
null
|
||||
}
|
||||
val image = bytes?.let { decode(it) }
|
||||
if (image == null) failed += id else cache.put(id, image)
|
||||
if (image == null) failed += key else cache.put(key, image)
|
||||
return image
|
||||
}
|
||||
|
||||
@@ -84,20 +107,57 @@ private object Pictures {
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
if (image.id.isBlank()) return
|
||||
Picture("attachment:" + image.id, image.width, image.height, modifier) { api -> api.attachmentBytes(image.id) }
|
||||
}
|
||||
|
||||
/**
|
||||
* A generated picture that is a file of the person's Files and no attachment: fetched by its
|
||||
* node id from `/files/raw`, drawn the same way. One the person has since put in the trash
|
||||
* says that it is no longer there.
|
||||
*/
|
||||
@Composable
|
||||
fun GeneratedPicture(media: GeneratedMedia, modifier: Modifier = Modifier) {
|
||||
if (media.nodeId.isBlank()) return
|
||||
Picture("node:" + media.nodeId, media.width, media.height, modifier) { api ->
|
||||
// What the server says it weighs decides before a byte is asked for.
|
||||
if (media.size > Pictures.MAX_BYTES) throw ApiException(413, "")
|
||||
val held = ByteArrayOutputStream()
|
||||
api.download(api.raw(Raw.Node(media.nodeId), inline = true), held, most = Pictures.MAX_BYTES)
|
||||
held.toByteArray()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape a picture's place is given before its bytes are there: width over height, from the
|
||||
* size the server said, kept between a quarter and four. A size the server did not say is a
|
||||
* square. The place is that shape from its first draw to its last, so the picture arriving (or
|
||||
* not arriving) moves nothing in the transcript.
|
||||
*/
|
||||
internal fun pictureRatio(width: Int, height: Int): Float = if (width > 0 && height > 0) (width.toFloat() / height).coerceIn(0.25f, 4f) else 1f
|
||||
|
||||
@Composable
|
||||
private fun Picture(key: String, width: Int, height: Int, modifier: Modifier, fetch: suspend (ApiClient) -> ByteArray) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
val still = LocalInspectionMode.current
|
||||
var bitmap by remember(image.id) { mutableStateOf(Pictures.cached(image.id)) }
|
||||
var bitmap by remember(key) { mutableStateOf(Pictures.cached(key)) }
|
||||
var gone by remember(key) { mutableStateOf(Pictures.isGone(key)) }
|
||||
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
|
||||
LaunchedEffect(key) {
|
||||
if (bitmap == null && !still) {
|
||||
bitmap = Pictures.load(context, key, fetch)
|
||||
gone = Pictures.isGone(key)
|
||||
}
|
||||
}
|
||||
val ratio = pictureRatio(width, height)
|
||||
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))
|
||||
.aspectRatio(ratio)
|
||||
.clip(shape)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, shape)
|
||||
@@ -107,6 +167,8 @@ fun GeneratedPicture(image: GeneratedImage, modifier: Modifier = Modifier) {
|
||||
val shown = bitmap
|
||||
if (shown != null) {
|
||||
Image(shown, contentDescription = described, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
|
||||
} else if (gone) {
|
||||
Text(stringResource(R.string.media_gone), color = palette.inkMuted, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp))
|
||||
} else {
|
||||
Icon(Icons.Filled.Image, contentDescription = described, tint = palette.inkFaint, modifier = Modifier.size(32.dp))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import android.os.SystemClock
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.border
|
||||
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.fillMaxWidth
|
||||
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.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.FolderOpen
|
||||
import androidx.compose.material.icons.filled.FolderZip
|
||||
import androidx.compose.material.icons.filled.HourglassEmpty
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.ViewInAr
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
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.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.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Attachment
|
||||
import eu.llembas.android.api.GeneratedImage
|
||||
import eu.llembas.android.api.GeneratedMedia
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
// What a model made or an agent showed, in the reply: a card for a file (a picture drawn, a video
|
||||
// or a track with Play, a PDF with Open, a 3D model or anything else as what it is) and a card for
|
||||
// a generation still under way.
|
||||
// The file is one of the person's Files, so each card leads there, and out of the app the ways
|
||||
// a file leaves it: saved where the person chooses, shared, or opened with another app. The
|
||||
// cards are drawn only where a chat provides [LocalChatMedia] -- the chat's own screen, which
|
||||
// is never over the lock screen; the assistant's sheet provides none and draws none.
|
||||
|
||||
/** What the media cards of a chat can do; nothing by default, for the screenshot tests. */
|
||||
interface MediaActions {
|
||||
/** Play a generated video or track, over the chat. */
|
||||
fun play(media: GeneratedMedia) {}
|
||||
|
||||
/** Play sound or video the person attached. */
|
||||
fun play(attachment: Attachment) {}
|
||||
|
||||
/** Lay a document's pages out over the chat (a PDF). */
|
||||
fun view(media: GeneratedMedia) {}
|
||||
|
||||
/** The folder of the person's Files the file is in. */
|
||||
fun openInFiles(media: GeneratedMedia) {}
|
||||
|
||||
/** Save it where the person chooses (the system's "Save to" page). */
|
||||
fun download(media: GeneratedMedia) {}
|
||||
|
||||
fun share(media: GeneratedMedia) {}
|
||||
|
||||
fun openWith(media: GeneratedMedia) {}
|
||||
|
||||
/** Stop a generation that is under way. */
|
||||
fun cancel(job: MediaJob) {}
|
||||
}
|
||||
|
||||
/** A chat's generated media as its cards need it: what is known of its jobs, and what a card can do. */
|
||||
class ChatMedia(val jobs: Map<String, JobSeen>, val actions: MediaActions)
|
||||
|
||||
/** Provided by the chat's screen; null anywhere else, and then no media card is drawn. */
|
||||
val LocalChatMedia = compositionLocalOf<ChatMedia?> { null }
|
||||
|
||||
private val CardShape = RoundedCornerShape(16.dp)
|
||||
|
||||
/** The string for a kind this app has a word for; null for any other. */
|
||||
internal fun mediaKindWord(kind: String): Int? = when (kind) {
|
||||
"image", "image_edit" -> R.string.media_image
|
||||
"video" -> R.string.media_video
|
||||
"music" -> R.string.media_music
|
||||
"audio" -> R.string.media_audio
|
||||
"model3d" -> R.string.media_model
|
||||
"pdf" -> R.string.media_pdf
|
||||
"archive" -> R.string.media_archive
|
||||
"text" -> R.string.media_text
|
||||
"binary" -> R.string.media_binary
|
||||
else -> null
|
||||
}
|
||||
|
||||
/**
|
||||
* The word for what a file is: a picture, a video, music, audio, a 3D model, a PDF, an archive,
|
||||
* a text file, a file. A kind this app does not know is the server's own word for a generated
|
||||
* file and "File" for one an agent showed ([shown]): a shown file always says what it is.
|
||||
*/
|
||||
@Composable
|
||||
internal fun mediaKind(kind: String, shown: Boolean = false): String =
|
||||
mediaKindWord(kind)?.let { stringResource(it) } ?: if (shown) stringResource(R.string.media_binary) else kind
|
||||
|
||||
/** The mark of a kind; `binary` and a kind this app does not know are a file. */
|
||||
internal fun mediaIcon(kind: String): ImageVector = when (kind) {
|
||||
"image", "image_edit" -> Icons.Filled.Image
|
||||
"video" -> Icons.Filled.Movie
|
||||
"music", "audio" -> Icons.Filled.MusicNote
|
||||
"model3d" -> Icons.Filled.ViewInAr
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"archive" -> Icons.Filled.FolderZip
|
||||
"text" -> Icons.Filled.Description
|
||||
else -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
}
|
||||
|
||||
/** What is known of a file, in one line: what it is, how long, how large, its size in pixels. */
|
||||
@Composable
|
||||
internal fun mediaFacts(media: GeneratedMedia): String {
|
||||
val context = LocalContext.current
|
||||
return listOfNotNull(
|
||||
mediaKind(media.kind, media.shown).ifBlank { null },
|
||||
media.seconds.takeIf { it > 0 }?.let { playTime((it * 1000).toInt()) },
|
||||
media.size.takeIf { it > 0 }?.let { Formatter.formatShortFileSize(context, it) },
|
||||
if (media.width > 0 && media.height > 0) "${media.width} × ${media.height}" else null,
|
||||
).joinToString(" · ")
|
||||
}
|
||||
|
||||
/**
|
||||
* A file a tool call made, or one an agent showed. A picture is drawn -- from its attachment
|
||||
* where the call has one ([image]), else from the file itself; a video or a track is its name
|
||||
* with Play (48 dp), which opens the player over the chat; a PDF is its name with Open, which
|
||||
* lays its pages out over the chat; a 3D model, an archive and anything this app does not know
|
||||
* is its name and what it is. Under each, four buttons of one size: Open in Files, Download,
|
||||
* Share, Open with.
|
||||
*
|
||||
* A file that was shown is always named: its picture has its name and facts under it, so one
|
||||
* that cannot be drawn on this phone (too large, a format the phone does not read) is still a
|
||||
* name, a kind in words and the ways to the file.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaCard(media: GeneratedMedia, image: GeneratedImage?, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
Column(modifier.widthIn(max = 480.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
when (media.view) {
|
||||
MediaView.Picture -> {
|
||||
// A result that names no node has no picture to ask for: its row stands in, so the card is never empty.
|
||||
val drawable = (image != null && image.id.isNotBlank()) || media.nodeId.isNotBlank()
|
||||
if (image != null && image.id.isNotBlank()) GeneratedPicture(image) else GeneratedPicture(media)
|
||||
if (media.shown && drawable) {
|
||||
Column(Modifier.fillMaxWidth().padding(horizontal = 4.dp)) { MediaWords(media) }
|
||||
} else if (!drawable) {
|
||||
MediaRow(media, actions)
|
||||
}
|
||||
}
|
||||
|
||||
MediaView.Video, MediaView.Sound, MediaView.Document, MediaView.Details -> MediaRow(media, actions)
|
||||
}
|
||||
// Four buttons of 48 dp: nothing here depends on how long a word is in any language.
|
||||
Row {
|
||||
CardButton(Icons.Filled.FolderOpen, R.string.media_open_in_files) { actions.openInFiles(media) }
|
||||
CardButton(Icons.Filled.Download, R.string.download) { actions.download(media) }
|
||||
CardButton(Icons.Filled.Share, R.string.report_share) { actions.share(media) }
|
||||
CardButton(Icons.AutoMirrored.Filled.OpenInNew, R.string.files_open_with) { actions.openWith(media) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's name on one line (its middle gives) and what is known of it on the next. */
|
||||
@Composable
|
||||
private fun MediaWords(media: GeneratedMedia) {
|
||||
val palette = LocalPalette.current
|
||||
Text(media.title, style = MaterialTheme.typography.bodyLarge, color = palette.ink, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
|
||||
Text(mediaFacts(media), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
|
||||
/**
|
||||
* A file as a row: a mark of 48 dp -- Play for sound and video, Open for a PDF, else the kind's
|
||||
* icon -- and the file's words, which give.
|
||||
*/
|
||||
@Composable
|
||||
private fun MediaRow(media: GeneratedMedia, actions: MediaActions) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, CardShape).padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
val filled = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk)
|
||||
when (media.view) {
|
||||
MediaView.Video, MediaView.Sound -> FilledIconButton(onClick = { actions.play(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(R.string.play))
|
||||
}
|
||||
|
||||
MediaView.Document -> FilledIconButton(onClick = { actions.view(media) }, colors = filled, modifier = Modifier.size(48.dp)) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = stringResource(R.string.viewer_open))
|
||||
}
|
||||
|
||||
MediaView.Picture, MediaView.Details -> Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
Icon(mediaIcon(media.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) { MediaWords(media) }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CardButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label), tint = LocalPalette.current.inkMuted) }
|
||||
}
|
||||
|
||||
/** The word for where a job stands; a state this app does not know is said as the server says it. */
|
||||
@Composable
|
||||
internal fun jobState(state: String): String = when (state) {
|
||||
"queued" -> stringResource(R.string.job_queued)
|
||||
"running" -> stringResource(R.string.job_running)
|
||||
"done" -> stringResource(R.string.job_done)
|
||||
"failed" -> stringResource(R.string.job_failed)
|
||||
"cancelled" -> stringResource(R.string.job_cancelled)
|
||||
"expired" -> stringResource(R.string.job_expired)
|
||||
else -> state
|
||||
}
|
||||
|
||||
/**
|
||||
* A generation that takes minutes, on the card of the call that started it: what is being made,
|
||||
* where it stands and for how long, and Cancel while it is under way. One that ended without a
|
||||
* file says why in the server's own sentence. The mark keeps its 48 dp and Cancel its own width;
|
||||
* the words between them give.
|
||||
*/
|
||||
@Composable
|
||||
fun JobCard(seen: JobSeen, actions: MediaActions, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
val still = LocalInspectionMode.current
|
||||
val job = seen.job
|
||||
var now by remember { mutableLongStateOf(if (still) seen.at else SystemClock.elapsedRealtime()) }
|
||||
// The clock on the card runs on the phone between two reads of the job.
|
||||
LaunchedEffect(job.id, job.underWay) {
|
||||
while (job.underWay && !still) {
|
||||
now = SystemClock.elapsedRealtime()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier.widthIn(max = 480.dp).fillMaxWidth().border(1.dp, palette.border, CardShape).padding(start = 12.dp, end = 4.dp, top = 10.dp, bottom = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(Modifier.size(48.dp), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
// A wheel that never ends never lets a screenshot be taken: a still mark there.
|
||||
job.underWay && !still -> CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
|
||||
|
||||
job.underWay -> Icon(Icons.Filled.HourglassEmpty, contentDescription = null, tint = palette.inkMuted)
|
||||
|
||||
job.unsuccessful -> Icon(
|
||||
Icons.Filled.ErrorOutline,
|
||||
contentDescription = null,
|
||||
tint = if (job.state ==
|
||||
"failed"
|
||||
) {
|
||||
palette.danger
|
||||
} else {
|
||||
palette.inkMuted
|
||||
},
|
||||
)
|
||||
|
||||
else -> Icon(mediaIcon(job.kind), contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
listOf(mediaKind(job.kind), jobState(job.state)).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
)
|
||||
val elapsed = seen.elapsed(now)
|
||||
val facts = listOfNotNull(
|
||||
if (elapsed >
|
||||
0
|
||||
) {
|
||||
playTime((elapsed * 1000).coerceAtMost(Int.MAX_VALUE.toLong()).toInt())
|
||||
} else {
|
||||
null
|
||||
},
|
||||
job.source.ifBlank { null },
|
||||
)
|
||||
if (facts.isNotEmpty()) {
|
||||
Text(
|
||||
facts.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
// Why it was not made, in the instance's words: a sentence for the person, shown whole.
|
||||
if (job.unsuccessful && job.error.isNotBlank()) {
|
||||
Text(
|
||||
job.error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (job.state == "failed") palette.danger else palette.inkMuted,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (job.underWay) {
|
||||
TextButton(onClick = { actions.cancel(job) }) { Text(stringResource(R.string.cancel)) }
|
||||
} else {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a call that made media leaves in the reply, always in view: its file's card; or its
|
||||
* job's card, which becomes the file's once the job is done.
|
||||
*/
|
||||
@Composable
|
||||
fun CallMedia(media: GeneratedMedia?, image: GeneratedImage?, job: JobSeen?, chat: ChatMedia) {
|
||||
if (media != null) MediaCard(media, image, chat.actions)
|
||||
if (job != null) {
|
||||
val result = job.job.result
|
||||
if (result != null && job.job.state == MediaJob.DONE) MediaCard(result, null, chat.actions) else JobCard(job, chat.actions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobRef
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
|
||||
// A chat's long generations as the chat keeps them. There is no stream frame for a job -- a chat
|
||||
// has no stream while no reply is being written -- so the jobs under way are read again every few
|
||||
// seconds while the chat is in front, and the chat is read again when one of them has woken it.
|
||||
|
||||
/** A job as it was last read, and when ([at], the phone's uptime clock; 0: known only from the call). */
|
||||
data class JobSeen(val job: MediaJob, val at: Long = 0) {
|
||||
/** How long it has taken, in seconds, at [now]: counted on from the read while it is under way. */
|
||||
fun elapsed(now: Long): Long {
|
||||
val said = job.seconds.toLong().coerceAtLeast(0)
|
||||
return if (job.underWay && at > 0 && now > at) said + (now - at) / 1000 else said
|
||||
}
|
||||
}
|
||||
|
||||
/** How often jobs under way are read again. */
|
||||
const val JOB_POLL_MS = 3000L
|
||||
|
||||
/** How many more reads a job that has ended is given to say that the chat was told. */
|
||||
const val TELL_ROUNDS = 20
|
||||
|
||||
private fun calls(steps: List<Step>): Sequence<ToolCall> {
|
||||
fun all(call: ToolCall): Sequence<ToolCall> = sequenceOf(call) + call.children.orEmpty().asSequence().flatMap { all(it) }
|
||||
return steps.asSequence().flatMap { it.calls.asSequence() }.flatMap { all(it) }
|
||||
}
|
||||
|
||||
/** Every job the calls of these messages (and of the steps being written, [live]) started, each once, in the order the calls come. */
|
||||
fun jobRefsOf(messages: List<Message>, live: List<Step> = emptyList()): List<MediaJobRef> {
|
||||
val all = messages.asSequence().flatMap { calls(it.steps) } + calls(live)
|
||||
return all.mapNotNull { it.mediaJob?.takeIf { ref -> ref.id.isNotBlank() } }.distinctBy { it.id }.toList()
|
||||
}
|
||||
|
||||
/** The jobs this chat's calls started (the reply being written included). */
|
||||
val ChatState.jobRefs: List<MediaJobRef> get() = jobRefsOf(messages, live?.shown.orEmpty())
|
||||
|
||||
/**
|
||||
* A job that has ended and has not said yet that the chat was told: the reply about it is still
|
||||
* to come, so it is read a few more times. A cancelled job wakes nobody.
|
||||
*/
|
||||
fun awaitsTelling(job: MediaJob): Boolean = !job.underWay && !job.told && job.state != MediaJob.CANCELLED
|
||||
|
||||
/**
|
||||
* The jobs to read again: the ones a call names that were never read (the call's own word is
|
||||
* from the moment it returned), and the ones under way. A job that has ended is left alone.
|
||||
*/
|
||||
fun ChatState.jobsToRead(): List<String> {
|
||||
val named = jobRefs.map { it.id }.filter { mediaJobs[it]?.let { seen -> seen.at == 0L || seen.job.underWay } ?: true }
|
||||
val known = mediaJobs.values.filter { it.job.underWay }.map { it.job.id }
|
||||
return (named + known).distinct()
|
||||
}
|
||||
|
||||
/** [jobs], read at [at], among what the chat knows of its jobs. */
|
||||
fun ChatState.withJobs(jobs: List<MediaJob>, at: Long): ChatState =
|
||||
if (jobs.isEmpty()) this else copy(mediaJobs = mediaJobs + jobs.filter { it.id.isNotBlank() }.associate { it.id to JobSeen(it, at) })
|
||||
|
||||
/**
|
||||
* Whether a read says the chat was woken since the last one: the job was known and had not told
|
||||
* the chat, and now has. Then there is a reply this app did not start, and the transcript is
|
||||
* read again. A job first heard of already told is part of the transcript that was just read.
|
||||
*/
|
||||
fun woke(before: MediaJob?, after: MediaJob): Boolean = before != null && !before.told && after.told
|
||||
|
||||
/** What a call's job is drawn from: what was read of it, else the call's own word. */
|
||||
fun ChatMedia.job(ref: MediaJobRef): JobSeen = jobs[ref.id] ?: JobSeen(MediaJob.of(ref))
|
||||
@@ -0,0 +1,46 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.DeviceFile
|
||||
import eu.llembas.android.api.Mention
|
||||
|
||||
// The composer's `@`: what is being asked for is the `@word` the text ends with. The field's
|
||||
// cursor is not followed -- a mention is offered for what is typed last, which is where typing
|
||||
// on a phone is.
|
||||
|
||||
/** A file on a linked device, as the `@` list holds it beside the server's kinds: put into the text as `@path`, never attached. */
|
||||
const val MENTION_DEVICE = "device"
|
||||
|
||||
/**
|
||||
* The `@` word [text] ends with, without the `@` (empty right after it), or null when it ends
|
||||
* with none: the `@` must open a word (so an e-mail address is not one), and the word holds no
|
||||
* space yet.
|
||||
*/
|
||||
fun mentionQuery(text: String): String? {
|
||||
val at = text.lastIndexOf('@')
|
||||
if (at < 0 || (at > 0 && !text[at - 1].isWhitespace())) return null
|
||||
return text.substring(at + 1).takeIf { word -> word.none { it.isWhitespace() } }
|
||||
}
|
||||
|
||||
/** [text] without the `@word` it ends with: what stays when the mention became an attachment. */
|
||||
fun withoutMention(text: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@'))
|
||||
|
||||
/** [text] with the `@word` it ends with made `@path` and a space: a device's file, which the device reads. */
|
||||
fun withMention(text: String, path: String): String = if (mentionQuery(text) == null) text else text.substring(0, text.lastIndexOf('@')) + "@" + path + " "
|
||||
|
||||
/** The most entries the `@` list shows. */
|
||||
const val MENTION_LIMIT = 50
|
||||
|
||||
/** The longest path a device's file may have to be offered. */
|
||||
const val MENTION_PATH = 512
|
||||
|
||||
/**
|
||||
* A device's file as an entry of the `@` list: its name, and its path as the detail. Null for
|
||||
* one that is not offered: its path goes into the message as it is, so a path with a line
|
||||
* break or another control character in it -- which the one-line row would not show -- or one
|
||||
* too long to be a path is left out.
|
||||
*/
|
||||
fun DeviceFile.asMention(): Mention? {
|
||||
if (path.isBlank() || path.length > MENTION_PATH || path.any { it.isISOControl() }) return null
|
||||
val shown = name.filterNot { it.isISOControl() }.take(MENTION_PATH).ifBlank { path }
|
||||
return Mention(kind = MENTION_DEVICE, path = path, name = shown, detail = if (kind == "dir") "$path/" else path)
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.ui.ModelAvatar
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
|
||||
@@ -99,12 +100,15 @@ fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (Strin
|
||||
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
|
||||
// [current] is the key of the row in use, looked up by the caller, who knows how the name
|
||||
// was said: a chat's `model_ref` that is not in the list ticks no row, never one with that id.
|
||||
val inUse = current
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m ->
|
||||
val chosen = m.key == inUse
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(m.id) }
|
||||
.clickable { onPick(m.key) }
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
@@ -112,7 +116,7 @@ fun ModelPickerContent(models: List<ModelInfo>, current: String?, onPick: (Strin
|
||||
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)
|
||||
Text(m.titleAmong(models), style = MaterialTheme.typography.titleMedium)
|
||||
modelNotes(m).takeIf { it.isNotEmpty() }?.let {
|
||||
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.Speaker
|
||||
import eu.llembas.android.lembas
|
||||
@@ -23,7 +24,15 @@ import kotlinx.coroutines.launch
|
||||
* shows a button that can only fail.
|
||||
*/
|
||||
@Stable
|
||||
class ReadAloud(private val context: Context, private val scope: CoroutineScope, private val onError: (String) -> Unit) {
|
||||
class ReadAloud(
|
||||
private val context: Context,
|
||||
private val scope: CoroutineScope,
|
||||
/** Which chat is read from, asked at each reading: its connection may have a voice of its own. */
|
||||
private val media: () -> MediaFor = { MediaFor.DEFAULT },
|
||||
/** Another source read it than the chat's own: its name. */
|
||||
private val onFallback: (String) -> Unit = {},
|
||||
private val onError: (String) -> Unit,
|
||||
) {
|
||||
private val speaker = Speaker(context)
|
||||
private var job: Job? = null
|
||||
|
||||
@@ -45,7 +54,9 @@ class ReadAloud(private val context: Context, private val scope: CoroutineScope,
|
||||
job = scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: return@launch
|
||||
speaker.play(api.speech(AssistController.plain(markdown)))
|
||||
val spoken = api.speech(AssistController.plain(markdown), media())
|
||||
spoken.fallback?.let(onFallback)
|
||||
speaker.play(spoken.audio)
|
||||
speaker.playing.first { !it }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* The reads of one thing (a chat's transcript) that several pieces of news ask for, one at a
|
||||
* time and none twice for the same news. Whoever learns something that needs a read takes a
|
||||
* [mark] at that moment -- before waiting for anything -- and asks [since] it; a read that began
|
||||
* after the mark and came back has seen what the mark's news was about, so the asker's own is
|
||||
* not made. A burst of frames, or a return to the front that several watchers notice, is then
|
||||
* one read; news that arrives while a read is under way is newer than that read, and gets its own.
|
||||
*/
|
||||
class Reads {
|
||||
private val one = Mutex()
|
||||
|
||||
/** How many reads have begun. */
|
||||
private var begun = 0L
|
||||
|
||||
/** The last read that came back with an answer, by its number. */
|
||||
private var answered = 0L
|
||||
|
||||
/** The moment some news was learned: every read that begins from now on covers it. */
|
||||
fun mark(): Long = begun
|
||||
|
||||
/**
|
||||
* [read], unless a read that began after [mark] has already answered, or [wanted] says -- once
|
||||
* it is this asker's turn -- that nothing is asked for any more. [read] says whether it got
|
||||
* an answer; one that did not covers nobody. True when [read] ran.
|
||||
*/
|
||||
suspend fun since(mark: Long, wanted: () -> Boolean = { true }, read: suspend () -> Boolean): Boolean = one.withLock {
|
||||
if (answered > mark || !wanted()) return@withLock false
|
||||
val mine = ++begun
|
||||
if (read()) answered = mine
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,14 @@ import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
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.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
@@ -41,6 +44,8 @@ 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.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
@@ -61,6 +66,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.compositionLocalOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -83,11 +89,15 @@ 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.ModelInfo
|
||||
import eu.llembas.android.api.ShowCard
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.Waiting
|
||||
import eu.llembas.android.api.ending
|
||||
import eu.llembas.android.api.replyModel
|
||||
import eu.llembas.android.api.shownMarkdown
|
||||
import eu.llembas.android.api.waiting
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.MarkdownText
|
||||
import eu.llembas.android.ui.Segment
|
||||
@@ -106,13 +116,32 @@ private val Bubble = RoundedCornerShape(topStart = 20.dp, topEnd = 6.dp, bottomS
|
||||
private val Block = RoundedCornerShape(12.dp)
|
||||
private val Pill = RoundedCornerShape(50)
|
||||
|
||||
/** A reply's foot: the gap above it, and the height of its row of buttons (an icon button's 48 dp). */
|
||||
private val FootTop = 2.dp
|
||||
private val FootHeight = 48.dp
|
||||
|
||||
/** A waiting message's two buttons: a tap target's height. */
|
||||
private val WaitingButton = 48.dp
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* A message that waits says how it waits in words under the bubble, and -- where [onSendNow]
|
||||
* and [onDiscard] are given, which only the chat's own screen does -- offers the two things a
|
||||
* person does with it. They rest while [busy]: one of them is being asked of the instance.
|
||||
*/
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun UserMessage(
|
||||
message: Message,
|
||||
canEdit: Boolean,
|
||||
onEdit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
busy: Boolean = false,
|
||||
onSendNow: (() -> Unit)? = null,
|
||||
onDiscard: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
@@ -159,14 +188,32 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier
|
||||
}
|
||||
}
|
||||
}
|
||||
if (message.queued) {
|
||||
// The server's queued progress ("Queued, 2 ahead · 12s") where it sends one.
|
||||
message.waiting?.let { waiting ->
|
||||
// How it waits, in words. Queued behind a reply: the server's progress ("Queued: 2
|
||||
// ahead · 12s") where it sends one. Not for one a linked computer was handed: that
|
||||
// one waits for the person or for the computer, not for its turn here.
|
||||
Text(
|
||||
progressLineOf(message.progress) ?: stringResource(R.string.queued),
|
||||
when (waiting) {
|
||||
Waiting.Unsure -> stringResource(R.string.fate_unknown)
|
||||
Waiting.Carried -> stringResource(R.string.fate_carried)
|
||||
Waiting.Queued -> progressLineOf(message.progress) ?: stringResource(R.string.queued)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
color = if (waiting == Waiting.Unsure) palette.warning else palette.inkFaint,
|
||||
modifier = Modifier.padding(top = 4.dp, end = 4.dp),
|
||||
)
|
||||
if (onSendNow != null && onDiscard != null) {
|
||||
// Two buttons of unknown width (eight languages, any type size): they share a
|
||||
// row that wraps, each a full tap target, from the bubble's edge.
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End)) {
|
||||
TextButton(onClick = onDiscard, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.discard))
|
||||
}
|
||||
TextButton(onClick = onSendNow, enabled = !busy, modifier = Modifier.heightIn(min = WaitingButton)) {
|
||||
Text(stringResource(R.string.send_now))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,6 +252,8 @@ fun AssistantMessage(
|
||||
onRegenerate: () -> Unit,
|
||||
onShow: ((ShowCard) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
/** The models offered here: a reply by one of two that share an id says its connection. */
|
||||
models: List<ModelInfo> = emptyList(),
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val copy = LocalCopy.current
|
||||
@@ -245,7 +294,10 @@ fun AssistantMessage(
|
||||
}
|
||||
}
|
||||
if (writing) {
|
||||
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
|
||||
// Once there is something written, the pulse stands in the finished reply's foot --
|
||||
// the same top and the same height as its row of buttons -- so the reply ending
|
||||
// does not change the row's height under a person at the end of it.
|
||||
if (steps.isEmpty()) Writing(withLine = true) else Writing(Modifier.padding(top = FootTop), minHeight = FootHeight)
|
||||
} else {
|
||||
// How a reply that did not finish ended (display.md §4): the progress text alone --
|
||||
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
|
||||
@@ -259,7 +311,7 @@ fun AssistantMessage(
|
||||
)
|
||||
}
|
||||
// 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)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = FootTop)) {
|
||||
if (words.isNotBlank()) {
|
||||
IconButton(onClick = { copy(words) }) {
|
||||
Icon(
|
||||
@@ -291,7 +343,7 @@ fun AssistantMessage(
|
||||
)
|
||||
}
|
||||
}
|
||||
footLine(message)?.let { line ->
|
||||
footLine(message, models)?.let { line ->
|
||||
Text(
|
||||
line,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -333,11 +385,12 @@ fun replyText(message: Message): String = pageProjection(
|
||||
private const val PAGE_UNTITLED = "Page"
|
||||
|
||||
/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */
|
||||
private fun footLine(message: Message): String? {
|
||||
val m = message.metrics ?: return message.model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return message.model
|
||||
internal fun footLine(message: Message, models: List<ModelInfo> = emptyList()): String? {
|
||||
val model = models.replyModel(message.modelRef, message.model)
|
||||
val m = message.metrics ?: return model
|
||||
if (m.completionTokens == 0 && m.elapsedMs == 0L) return model
|
||||
return buildList {
|
||||
message.model?.let { add(it) }
|
||||
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 }
|
||||
@@ -345,13 +398,13 @@ private fun footLine(message: Message): String? {
|
||||
|
||||
/** Three dots that breathe, and (before the first word) the loading line beside them. */
|
||||
@Composable
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false) {
|
||||
fun Writing(modifier: Modifier = Modifier, withLine: Boolean = false, minHeight: Dp = 32.dp) {
|
||||
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) {
|
||||
Row(modifier.heightIn(min = minHeight), verticalAlignment = Alignment.CenterVertically) {
|
||||
repeat(3) { i ->
|
||||
val alpha = if (still) {
|
||||
listOf(1f, 0.6f, 0.3f)[i]
|
||||
@@ -386,7 +439,9 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
|
||||
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
steps.forEach { step ->
|
||||
when (step.kind) {
|
||||
"thinking" -> ThinkingChip(step)
|
||||
// By its place in the reply, not by its turn in this loop: a chip the person
|
||||
// opened is the same chip when its step closes and others come after it.
|
||||
"thinking" -> key(step.index, step.kind) { ThinkingChip(step) }
|
||||
|
||||
// A closed step's pages are the server's to name (its `text`); in the step still
|
||||
// being written a page's fence is a page already, not source scrolling by.
|
||||
@@ -525,7 +580,9 @@ private fun FoldChip(
|
||||
@Composable
|
||||
private fun ThinkingChip(step: Step) {
|
||||
val palette = LocalPalette.current
|
||||
var open by rememberSaveable(step.index, step.open) { mutableStateOf(false) }
|
||||
// Open only because the person opened it, and then it stays open: the step closing (the
|
||||
// thinking is over, the words begin) is not a reason to fold away what somebody is reading.
|
||||
var open by rememberSaveable(step.index) { mutableStateOf(false) }
|
||||
val label = if (step.open) stringResource(R.string.thinking) + "…" else stringResource(R.string.thought) + (step.label?.let { " $it" } ?: "")
|
||||
FoldChip(
|
||||
open = open,
|
||||
@@ -583,9 +640,20 @@ private fun ToolsChip(step: Step, onShow: ((ShowCard) -> Unit)?) {
|
||||
}
|
||||
}
|
||||
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) }
|
||||
// What the instance made stays in view, like a `show` card: it is the answer. A picture as
|
||||
// before; in a chat's own screen also the file's card (a player, the ways to the file) and
|
||||
// the card of a generation still under way. Elsewhere -- the assistant's sheet, which may be
|
||||
// over the lock screen -- only the picture, as before.
|
||||
val media = LocalChatMedia.current
|
||||
step.calls.filter { it.status != "error" && it.error.isNullOrEmpty() }.forEach { call ->
|
||||
val image = call.image?.takeIf { it.id.isNotBlank() }
|
||||
if (media == null) {
|
||||
image?.let { GeneratedPicture(it) }
|
||||
} else {
|
||||
if (call.media == null) image?.let { GeneratedPicture(it) }
|
||||
CallMedia(call.media, image, call.mediaJob?.takeIf { it.id.isNotBlank() }?.let { media.job(it) }, media)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
@@ -636,7 +704,17 @@ private object Thumbnails {
|
||||
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) {
|
||||
// Sound and video the person attached are played, where a chat's screen has a player.
|
||||
val play = LocalChatMedia.current?.actions?.takeIf { attachment.kind == "audio" || attachment.kind == "video" }
|
||||
Box(
|
||||
modifier
|
||||
.size(side)
|
||||
.clip(Block)
|
||||
.background(palette.surfaceRaised)
|
||||
.border(1.dp, palette.border, Block)
|
||||
.then(if (play != null) Modifier.clickable(onClickLabel = stringResource(R.string.play)) { play.play(attachment) } else Modifier),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
if (attachment.image) {
|
||||
var image by remember(attachment.id) { mutableStateOf(Thumbnails.cached(attachment.id)) }
|
||||
val still = LocalInspectionMode.current
|
||||
@@ -649,7 +727,15 @@ fun AttachmentTile(attachment: Attachment, side: Dp, modifier: Modifier = Modifi
|
||||
}
|
||||
} else {
|
||||
Column(Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(Icons.Filled.Description, contentDescription = null, tint = palette.inkMuted)
|
||||
Icon(
|
||||
when (attachment.kind) {
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
else -> Icons.Filled.Description
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = if (play != null) palette.accent else palette.inkMuted,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
attachment.name,
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package eu.llembas.android.ui.chat
|
||||
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.ChatDetail
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.api.Turn
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
/**
|
||||
* A waiting message was sent now ([turn], the instance's answer): its row is the message as it
|
||||
* is after -- no longer waiting -- where it stood, and the reply started for it is the last row.
|
||||
* No row is there twice: the list's rows are keyed by id.
|
||||
*/
|
||||
fun ChatState.sentNow(turn: Turn): ChatState {
|
||||
val sent = turn.message
|
||||
val reply = turn.reply
|
||||
val rows = messages.filterNot { it.id == reply?.id }.map { if (it.id == sent?.id) sent else it }
|
||||
return copy(messages = rows + listOfNotNull(reply), lastSent = sent?.id ?: lastSent)
|
||||
}
|
||||
|
||||
/** A waiting message was discarded: its row is gone, and nothing else moved. */
|
||||
fun ChatState.discarded(id: String): ChatState = copy(messages = messages.filterNot { it.id == id })
|
||||
|
||||
/**
|
||||
* Whether a refusal says the screen showed a message as waiting that is not so any more, or
|
||||
* could not be acted on as shown: 409 (a reply is being written; the message no longer waits)
|
||||
* and 404 (it is not there). The chat is then read again. Anything else -- no network, a server
|
||||
* error -- says nothing about the message, and the row stays as it is.
|
||||
*/
|
||||
fun staleWaiting(e: Throwable): Boolean = e is ApiException && (e.status == 409 || e.status == 404)
|
||||
|
||||
/** A reply to follow, and whether the person asked for it from this screen. */
|
||||
data class Followed(val reply: String, val own: Boolean)
|
||||
|
||||
/**
|
||||
* Which reply is followed once a waiting message was sent now: the one the send started
|
||||
* ([reply]), as a reply the person asked for from this screen -- unless the chat, [read] after
|
||||
* the send, no longer holds it as being written. That happens by design: a linked computer
|
||||
* that still knew the message does not run it a second time, and the reply started for it is
|
||||
* removed. Then whatever else the read says is being written is followed, as nobody's.
|
||||
*/
|
||||
fun followedAfterSend(reply: String?, read: ChatDetail?): Followed? {
|
||||
if (reply != null && (read == null || read.live == reply || read.messages.any { it.id == reply && !it.complete })) {
|
||||
return Followed(reply, own = true)
|
||||
}
|
||||
return read?.live?.let { Followed(it, own = false) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The two things a person does with a message that waits, as the chat's screen does them. The
|
||||
* instance is asked through each action's own request; what the screen shows is [state].
|
||||
*
|
||||
* Sent: the row stops waiting at once, the chat is read ([read]; a chat on a linked computer
|
||||
* sorts the message to where it was sent), and the reply started for it is followed ([follow])
|
||||
* exactly as one the person asked for by typing. Discarded: the row is gone. Refused with a
|
||||
* 409 or a 404: the instance's sentence is said ([say]) and the chat is read again
|
||||
* ([catchUp]), because what the screen showed as waiting is not so any more. While one of the
|
||||
* two is under way for a message, [ChatState.acting] names it and its buttons rest.
|
||||
*/
|
||||
class WaitingActions(
|
||||
private val state: MutableStateFlow<ChatState>,
|
||||
private val read: suspend () -> ChatDetail?,
|
||||
private val follow: (Followed) -> Unit,
|
||||
private val say: (Throwable) -> Unit,
|
||||
private val catchUp: suspend () -> Unit,
|
||||
) {
|
||||
suspend fun sendNow(message: Message, send: suspend () -> Turn) = act(message) {
|
||||
val turn = send()
|
||||
state.update { it.sentNow(turn) }
|
||||
followedAfterSend(turn.reply?.id, read())?.let(follow)
|
||||
}
|
||||
|
||||
suspend fun discard(message: Message, withdraw: suspend () -> Unit) = act(message) {
|
||||
withdraw()
|
||||
state.update { it.discarded(message.id) }
|
||||
}
|
||||
|
||||
/** One action at a time: a second tap while the first is asked is not a second request. */
|
||||
private suspend fun act(message: Message, action: suspend () -> Unit) {
|
||||
if (state.value.acting != null) return
|
||||
state.update { it.copy(acting = message.id) }
|
||||
var stale = false
|
||||
try {
|
||||
action()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
say(e)
|
||||
stale = staleWaiting(e)
|
||||
} finally {
|
||||
state.update { if (it.acting == message.id) it.copy(acting = null) else it }
|
||||
}
|
||||
// After the buttons are free again: the read may wait for a reply being written here.
|
||||
if (stale) catchUp()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.text.format.Formatter
|
||||
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.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.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.DeleteForever
|
||||
import androidx.compose.material.icons.filled.DeleteSweep
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
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.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileVersion
|
||||
import eu.llembas.android.api.TrashItem
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// The file manager's smaller pages: a name, a yes or no, the folder to move or copy into, the
|
||||
// trash, and a file's versions. Each is drawn from its state alone.
|
||||
|
||||
/** Ask for a name: a new folder's, a new file's, or a new one for something that has one. */
|
||||
@Composable
|
||||
fun NameDialog(title: String, ask: String?, initial: String, confirm: String, onName: (String) -> Unit, onDismiss: () -> Unit) {
|
||||
var name by remember { mutableStateOf(initial) }
|
||||
val bad = FileKinds.badName(name)
|
||||
val problem: (@Composable () -> Unit)? = if (name.isNotEmpty() && bad) {
|
||||
{ Text(stringResource(R.string.files_bad_name)) }
|
||||
} else {
|
||||
null
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(title) },
|
||||
text = {
|
||||
Column {
|
||||
ask?.let { Text(it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(bottom = 12.dp)) }
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
singleLine = true,
|
||||
isError = name.isNotEmpty() && bad,
|
||||
supportingText = problem,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { onName(name.trim()) }, enabled = !bad && name.trim() != initial) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A question with one thing to do and a way not to. */
|
||||
@Composable
|
||||
fun ConfirmDialog(text: String, confirm: String, onConfirm: () -> Unit, onDismiss: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onConfirm) { Text(confirm) } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** Where the folder picker is: the folders of [path], on their way or refused. */
|
||||
data class FolderPickState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val folders: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = true,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* Choosing a folder of the tree by walking to it: where something is moved or copied, or where
|
||||
* a share is saved. No path is typed. [hidden]: the things being moved, which cannot be their
|
||||
* own destination.
|
||||
*/
|
||||
@Composable
|
||||
fun FolderPicker(title: String, confirm: String, start: String, onPick: (String) -> Unit, onDismiss: () -> Unit, hidden: Set<String> = emptySet()) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(FolderPickState(path = start)) }
|
||||
var asked by remember { mutableStateOf(start) }
|
||||
var again by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
LaunchedEffect(asked, again) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val listing = api.files(asked)
|
||||
FolderPickState(listing.path, listing.parent, listing.entries.filter { it.isFolder && it.path !in hidden }, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
val up: () -> Unit = {
|
||||
val parent = state.parent
|
||||
if (parent != null) asked = parent else onDismiss()
|
||||
}
|
||||
Dialog(onDismissRequest = up, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
FolderPickContent(
|
||||
title,
|
||||
confirm,
|
||||
state,
|
||||
onOpen = { asked = it },
|
||||
onUp = up,
|
||||
onPick = { onPick(state.path) },
|
||||
onDismiss = onDismiss,
|
||||
onNewFolder = { naming = true },
|
||||
)
|
||||
}
|
||||
if (naming) {
|
||||
NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
naming = false
|
||||
val dir = state.path
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.makeFolder(dir, name)
|
||||
// Made, and walked into: it is most likely where the thing is meant to go.
|
||||
if (asked == FileKinds.child(dir, name)) again++ else asked = FileKinds.child(dir, name)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { naming = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/** The folder picker's page: where it is, that folder's folders, and the one button that chooses the folder shown. */
|
||||
@Composable
|
||||
fun FolderPickContent(
|
||||
title: String,
|
||||
confirm: String,
|
||||
state: FolderPickState,
|
||||
onOpen: (String) -> Unit = {},
|
||||
onUp: () -> Unit = {},
|
||||
onPick: () -> Unit = {},
|
||||
onDismiss: () -> Unit = {},
|
||||
/** Make a folder in the one shown; null where the page cannot. */
|
||||
onNewFolder: (() -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
actions = {
|
||||
if (onNewFolder != null) {
|
||||
IconButton(onClick = onNewFolder, enabled = !state.loading && state.error == null) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.folder_new))
|
||||
}
|
||||
}
|
||||
},
|
||||
navigationIcon = {
|
||||
IconButton(onClick = if (state.parent != null) onUp else onDismiss) {
|
||||
Icon(
|
||||
if (state.parent != null) Icons.AutoMirrored.Filled.ArrowBack else Icons.Filled.Close,
|
||||
contentDescription = stringResource(if (state.parent != null) R.string.back else R.string.close),
|
||||
)
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(title, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
state.path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
bottomBar = {
|
||||
Button(
|
||||
onClick = onPick,
|
||||
enabled = !state.loading && state.error == null,
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(16.dp).heightIn(min = 48.dp),
|
||||
) { Text(confirm) }
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.folders.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.folders.isEmpty() -> Text(
|
||||
stringResource(R.string.files_no_folders),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.folders, key = { it.path }) { folder ->
|
||||
ListItem(
|
||||
modifier = Modifier.fillMaxWidth().clickable { onOpen(folder.path) },
|
||||
leadingContent = {
|
||||
Icon(
|
||||
if (folder.kind == "mount") Icons.Filled.FolderShared else Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
headlineContent = { Text(folder.name.ifBlank { folder.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The trash as the page draws it. */
|
||||
data class TrashState(val items: List<TrashItem> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** What the trash page can do; nothing by default, for the screenshot tests. */
|
||||
interface TrashActions {
|
||||
fun restore(item: TrashItem) {}
|
||||
|
||||
fun remove(item: TrashItem) {}
|
||||
|
||||
fun empty() {}
|
||||
|
||||
fun close() {}
|
||||
}
|
||||
|
||||
/** The trash: what was deleted, each to be restored or removed for good, and all of it emptied. [onChanged]: something went back to the tree. */
|
||||
@Composable
|
||||
fun TrashDialog(onClose: () -> Unit, onChanged: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember { mutableStateOf(TrashState()) }
|
||||
var asking by remember { mutableStateOf<TrashItem?>(null) }
|
||||
var emptying by remember { mutableStateOf(false) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun act(block: suspend (ApiClient) -> List<TrashItem>) {
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
state = TrashState(block(api), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val words = context.filesSay(e)
|
||||
if (state.loading) state = state.copy(loading = false, error = words) else said = words
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(Unit) { act { it.trash().items } }
|
||||
val actions = remember {
|
||||
object : TrashActions {
|
||||
override fun restore(item: TrashItem) = act { api ->
|
||||
api.restoreTrashed(item.id).items.also { onChanged() }
|
||||
}
|
||||
|
||||
override fun remove(item: TrashItem) {
|
||||
asking = item
|
||||
}
|
||||
|
||||
override fun empty() {
|
||||
emptying = true
|
||||
}
|
||||
|
||||
override fun close() = onClose()
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
TrashContent(state, actions)
|
||||
}
|
||||
asking?.let { item ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_remove_confirm, item.name),
|
||||
stringResource(R.string.trash_remove),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
act { it.removeTrashed(item.id).items }
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
if (emptying) {
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.trash_empty_confirm),
|
||||
stringResource(R.string.trash_empty),
|
||||
onConfirm = {
|
||||
emptying = false
|
||||
act { it.removeTrashed().items }
|
||||
},
|
||||
onDismiss = { emptying = false },
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The trash's page. A row is the thing's name over where it was, and two buttons of 48 dp at
|
||||
* its end: the name gives, the buttons keep their size.
|
||||
*/
|
||||
@Composable
|
||||
fun TrashContent(state: TrashState, actions: TrashActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = actions::close) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(stringResource(R.string.trash), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::empty, enabled = state.items.isNotEmpty()) {
|
||||
Icon(Icons.Filled.DeleteSweep, contentDescription = stringResource(R.string.trash_empty))
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.items.isEmpty() -> Text(
|
||||
stringResource(R.string.trash_is_empty),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.items, key = { it.id }) { item ->
|
||||
ListItem(
|
||||
leadingContent = { EntryIcon(if (item.kind == "file") null else item.kind, null, selected = false) },
|
||||
headlineContent = { Text(item.name.ifBlank { item.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val size = if (item.kind == "file") Formatter.formatShortFileSize(context, item.size) else null
|
||||
Text(listOfNotNull(FileKinds.parent(item.path), size).joinToString(" · "), maxLines = 1, overflow = TextOverflow.StartEllipsis)
|
||||
},
|
||||
trailingContent = {
|
||||
Row {
|
||||
IconButton(onClick = { actions.restore(item) }) {
|
||||
Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.restore))
|
||||
}
|
||||
IconButton(onClick = { actions.remove(item) }) {
|
||||
Icon(Icons.Filled.DeleteForever, contentDescription = stringResource(R.string.trash_remove), tint = palette.danger)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A file's versions as the page draws them. */
|
||||
data class VersionsState(val versions: List<FileVersion> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/** A file's versions, newest first; an older one can be made the file again, which adds a version and loses none. */
|
||||
@Composable
|
||||
fun VersionsDialog(path: String, onClose: () -> Unit, onRestored: () -> Unit, onDownload: ((FileVersion) -> Unit)? = null) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var state by remember(path) { mutableStateOf(VersionsState()) }
|
||||
var asking by remember { mutableStateOf<FileVersion?>(null) }
|
||||
LaunchedEffect(path) {
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
VersionsState(api.fileVersions(path).versions, loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
VersionsState(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
VersionsContent(FileKinds.name(path), state, onRestore = { asking = it }, onClose = onClose, onDownload = onDownload)
|
||||
}
|
||||
asking?.let { version ->
|
||||
ConfirmDialog(
|
||||
stringResource(R.string.version_restore_confirm),
|
||||
stringResource(R.string.version_restore),
|
||||
onConfirm = {
|
||||
asking = null
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
api.restoreVersion(path, version.id)
|
||||
onRestored()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state = state.copy(error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
},
|
||||
onDismiss = { asking = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The versions' page: when, by whom and how large; the one the file holds now says so, the others
|
||||
* can be restored, and any of them saved to the phone as it was ([onDownload]; a 48 dp button
|
||||
* before the row's last part, so the buttons stand in one column whatever that part says).
|
||||
*/
|
||||
@Composable
|
||||
fun VersionsContent(
|
||||
name: String,
|
||||
state: VersionsState,
|
||||
onRestore: (FileVersion) -> Unit = {},
|
||||
onClose: () -> Unit = {},
|
||||
onDownload: ((FileVersion) -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(stringResource(R.string.versions), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(name, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
if (state.loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||
return@Column
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize()) {
|
||||
items(state.versions, key = { it.id }) { version ->
|
||||
val download: (@Composable () -> Unit)? = if (onDownload != null) {
|
||||
{
|
||||
IconButton(onClick = { onDownload(version) }) {
|
||||
Icon(Icons.Filled.Download, contentDescription = stringResource(R.string.download))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
ListItem(
|
||||
headlineContent = { Text(ScheduleLogic.moment(version.at) ?: version.id, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = {
|
||||
val facts = listOfNotNull(version.by?.ifBlank { null }, Formatter.formatShortFileSize(context, version.size))
|
||||
Text(facts.joinToString(" · "), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
leadingContent = download,
|
||||
trailingContent = {
|
||||
if (version.current) {
|
||||
Text(stringResource(R.string.version_current), style = MaterialTheme.typography.labelLarge, color = palette.inkMuted)
|
||||
} else {
|
||||
TextButton(onClick = { onRestore(version) }) { Text(stringResource(R.string.restore)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,59 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
|
||||
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
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.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
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.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Description
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
import androidx.compose.material.icons.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.FolderShared
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.RestoreFromTrash
|
||||
import androidx.compose.material.icons.filled.SelectAll
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material.icons.filled.TableChart
|
||||
import androidx.compose.material3.BottomAppBar
|
||||
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.LinearProgressIndicator
|
||||
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
|
||||
@@ -31,10 +63,12 @@ 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.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
@@ -45,34 +79,136 @@ 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.BatchAnswer
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.Raw
|
||||
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.CancellationException
|
||||
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. */
|
||||
/**
|
||||
* One directory of the person's tree: what is in it, what is chosen in it, and what is under
|
||||
* way. [error] is a listing that could not be read (said above the list, which stays); [said] a
|
||||
* refusal of something the person did (a sentence to read, in a dialog); [notice] a word that
|
||||
* it was done.
|
||||
*/
|
||||
data class FilesState(
|
||||
val path: String = "/",
|
||||
val parent: String? = null,
|
||||
val entries: List<FileEntry> = emptyList(),
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
)
|
||||
val selected: Set<String> = emptySet(),
|
||||
/** An upload under way: which file of how many, and how far it is. */
|
||||
val upload: Transfer? = null,
|
||||
/** A write under way (a move, a rename…): the list waits for it. */
|
||||
val working: Boolean = false,
|
||||
val said: String? = null,
|
||||
val notice: String? = null,
|
||||
) {
|
||||
val selecting: Boolean get() = selected.isNotEmpty()
|
||||
|
||||
/** The chosen entries, in the list's order. */
|
||||
val chosen: List<FileEntry> get() = entries.filter { it.path in selected }
|
||||
|
||||
fun toggled(path: String): FilesState = copy(selected = if (path in selected) selected - path else selected + path)
|
||||
|
||||
fun allSelected(): FilesState = copy(selected = entries.map { it.path }.toSet())
|
||||
|
||||
/** A listing read: the directory it is of, and of what was chosen only what is still there. */
|
||||
fun listed(listing: FileListing): FilesState {
|
||||
val same = listing.path == path
|
||||
val there = listing.entries.map { it.path }.toSet()
|
||||
return copy(
|
||||
path = listing.path,
|
||||
parent = listing.parent,
|
||||
entries = listing.entries,
|
||||
loading = false,
|
||||
error = null,
|
||||
selected = if (same) selected intersect there else emptySet(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a batch ended in: the server's sentences for what it refused, and the word for what it did. */
|
||||
data class BatchOutcome(val said: String?, val done: Int)
|
||||
|
||||
fun outcome(answer: BatchAnswer): BatchOutcome {
|
||||
if (answer.failed == 0) return BatchOutcome(null, answer.done)
|
||||
// Where the server gave no sentence, at least which ones: their names.
|
||||
val names = answer.results.filter { !it.ok }.take(3).joinToString(", ") { FileKinds.name(it.path) }
|
||||
return BatchOutcome(answer.refusals().joinToString("\n").ifBlank { names }, answer.done)
|
||||
}
|
||||
|
||||
/** Something the Files page asks the person before it is done, or a page it opens over itself. */
|
||||
sealed interface Ask {
|
||||
data object NewFolder : Ask
|
||||
|
||||
data object NewFile : Ask
|
||||
|
||||
data object Trash : Ask
|
||||
|
||||
data class Rename(val entry: FileEntry) : Ask
|
||||
|
||||
data class Delete(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Move(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Copy(val entries: List<FileEntry>) : Ask
|
||||
|
||||
data class Versions(val entry: FileEntry) : Ask
|
||||
}
|
||||
|
||||
/** What the Files page can do; nothing by default, for the screenshot tests. */
|
||||
interface FilesActions {
|
||||
fun back() {}
|
||||
|
||||
fun open(entry: FileEntry) {}
|
||||
|
||||
fun reload() {}
|
||||
|
||||
fun toggle(entry: FileEntry) {}
|
||||
|
||||
fun selectAll() {}
|
||||
|
||||
fun clearSelection() {}
|
||||
|
||||
fun pickUpload() {}
|
||||
|
||||
fun ask(what: Ask) {}
|
||||
|
||||
fun download(entries: List<FileEntry>) {}
|
||||
|
||||
fun share(entries: List<FileEntry>) {}
|
||||
|
||||
fun openWith(entry: FileEntry) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* The person's files as a file manager: `GET /api/v2/files` and the explorer's writes. The tree
|
||||
* is read and changed as the person, with no chat -- their own access, the same the web UI's
|
||||
* explorer draws by -- and every refusal is the server's own sentence.
|
||||
*/
|
||||
class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(FilesState(loading = true))
|
||||
val state = _state.asStateFlow()
|
||||
private var loading: Job? = null
|
||||
private var uploading: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
private suspend fun api(): ApiClient = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
|
||||
/**
|
||||
* Opens a directory. A refusal (a path no longer readable, the server unreachable) keeps the
|
||||
@@ -83,16 +219,14 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
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)
|
||||
// Also read again after an upload that ended behind the lock: not before the app is in front.
|
||||
app.lembas.gate.pass()
|
||||
val listing = api().files(path)
|
||||
_state.update { it.listed(listing) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
if (e is kotlinx.coroutines.CancellationException) throw e
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
_state.update { it.copy(loading = false, error = app.explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,85 +238,464 @@ class FilesViewModel(app: Application) : AndroidViewModel(app) {
|
||||
open(parent)
|
||||
return true
|
||||
}
|
||||
|
||||
fun toggle(entry: FileEntry) = _state.update { it.toggled(entry.path) }
|
||||
|
||||
fun selectAll() = _state.update { it.allSelected() }
|
||||
|
||||
fun clearSelection() = _state.update { it.copy(selected = emptySet()) }
|
||||
|
||||
fun clearSaid() = _state.update { it.copy(said = null, notice = null) }
|
||||
|
||||
/** One write, then the directory read again: what is there is what the server says is there. */
|
||||
private fun write(block: suspend (ApiClient) -> String?) {
|
||||
if (_state.value.working) return
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(working = true, said = null, notice = null) }
|
||||
try {
|
||||
val notice = block(api())
|
||||
_state.update { it.copy(notice = notice) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(said = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(working = false) }
|
||||
}
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
fun newFolder(name: String) = write { api ->
|
||||
api.makeFolder(_state.value.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, empty text file, and [then] its path, to open it for writing. The instance makes it
|
||||
* only where nothing is called that (`create`): otherwise nothing is written and its own
|
||||
* sentence says what is there. An instance from before `create` would write over what is
|
||||
* there, so the directory is read first and a name it holds is refused here
|
||||
* ([ApiClient.newFile]).
|
||||
*/
|
||||
fun newFile(name: String, then: (String) -> Unit) = write { api ->
|
||||
try {
|
||||
then(api.newFile(_state.value.path, name))
|
||||
} catch (e: FileExists) {
|
||||
_state.update { it.copy(said = e.message?.ifBlank { null } ?: app.getString(R.string.files_taken, name)) }
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
fun rename(entry: FileEntry, name: String) = write { api ->
|
||||
api.renameFile(entry.path, name)
|
||||
null
|
||||
}
|
||||
|
||||
/** Move or copy the entries into the directory [to], or with `delete` put them in the trash; each is answered for by itself. */
|
||||
fun batch(op: String, entries: List<FileEntry>, to: String? = null) = write { api ->
|
||||
val done = outcome(api.batchFiles(op, entries.map { it.path }, to))
|
||||
_state.update { it.copy(selected = emptySet(), said = done.said) }
|
||||
when {
|
||||
done.done == 0 -> null
|
||||
op == "delete" -> app.getString(R.string.files_trashed)
|
||||
op == "copy" -> app.getString(R.string.copied)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload files of the phone into the directory shown, one request each: a file the instance
|
||||
* refuses (too large: its 413 names the file) does not take the others with it. Each is
|
||||
* streamed from where it is; none is read into memory.
|
||||
*/
|
||||
fun upload(uris: List<Uri>) {
|
||||
if (uris.isEmpty() || uploading?.isActive == true) return
|
||||
val dir = _state.value.path
|
||||
uploading = viewModelScope.launch {
|
||||
val refused = mutableListOf<String>()
|
||||
var sent = 0
|
||||
try {
|
||||
val api = api()
|
||||
val files = uris.map { app.contentResolver.describe(it) }
|
||||
files.forEachIndexed { i, file ->
|
||||
val words = app.getString(R.string.files_uploading, (i + 1).toString(), files.size.toString())
|
||||
_state.update { it.copy(upload = Transfer(words, 0, file.size)) }
|
||||
var last = 0L
|
||||
try {
|
||||
// The file under way when the phone locks goes through; the next waits for the app in front, unlocked.
|
||||
app.lembas.gate.pass { waiting -> _state.update { it.copy(upload = it.upload?.copy(waiting = waiting)) } }
|
||||
api.uploadFrom(app, file, dir) { bytes ->
|
||||
if (bytes - last >= 256 * 1024) {
|
||||
last = bytes
|
||||
_state.update { it.copy(upload = it.upload?.copy(done = bytes)) }
|
||||
}
|
||||
}
|
||||
sent++
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
refused += app.filesSay(e)
|
||||
} finally {
|
||||
val words = refused.distinct().take(3).joinToString("\n").ifBlank { null }
|
||||
_state.update { it.copy(upload = null, said = words, notice = if (sent > 0) app.getString(R.string.files_uploaded) else null) }
|
||||
reload()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelUpload() {
|
||||
uploading?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun FilesScreen(onBack: () -> Unit, model: FilesViewModel = viewModel()) {
|
||||
fun FilesScreen(onBack: () -> Unit, start: String? = null, model: FilesViewModel = viewModel(), transfers: TransferViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
var viewing by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(state.path) }
|
||||
var writing by rememberSaveable { mutableStateOf(false) }
|
||||
var asked by remember { mutableStateOf<Ask?>(null) }
|
||||
var saving by remember { mutableStateOf<List<FileEntry>>(emptyList()) }
|
||||
// Opened at a folder ([start]: where a generated file is) the first time; after that, where the person walked to.
|
||||
LaunchedEffect(Unit) { if (state.entries.isEmpty() && state.error == null) model.open(start?.ifBlank { null } ?: state.path) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clearSaid()
|
||||
}
|
||||
}
|
||||
|
||||
// Back goes up one directory first, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.parent != null) { model.up() }
|
||||
// Back lets go of what is chosen first, then goes up one directory, as a file manager's does; at the top it leaves.
|
||||
BackHandler(enabled = state.selecting || state.parent != null) { if (state.selecting) model.clearSelection() else model.up() }
|
||||
|
||||
val pick = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { model.upload(it) }
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = saving
|
||||
saving = emptyList()
|
||||
if (to != null && what.isNotEmpty()) {
|
||||
transfers.download(what.map { it.path }, zip = asZip(what), to = to)
|
||||
model.clearSelection()
|
||||
}
|
||||
}
|
||||
val actions = remember(model, transfers) {
|
||||
object : FilesActions {
|
||||
override fun back() {
|
||||
if (!model.up()) onBack()
|
||||
}
|
||||
|
||||
override fun open(entry: FileEntry) {
|
||||
if (entry.isFolder) {
|
||||
model.open(entry.path)
|
||||
} else {
|
||||
writing = false
|
||||
viewing = entry.path
|
||||
}
|
||||
}
|
||||
|
||||
override fun reload() = model.reload()
|
||||
|
||||
override fun toggle(entry: FileEntry) = model.toggle(entry)
|
||||
|
||||
override fun selectAll() = model.selectAll()
|
||||
|
||||
override fun clearSelection() = model.clearSelection()
|
||||
|
||||
override fun pickUpload() = pick.launch(arrayOf("*/*"))
|
||||
|
||||
override fun ask(what: Ask) {
|
||||
asked = what
|
||||
}
|
||||
|
||||
override fun download(entries: List<FileEntry>) {
|
||||
if (entries.isEmpty()) return
|
||||
saving = entries
|
||||
val zip = asZip(entries)
|
||||
saveTo.launch(
|
||||
CreateFile.Ask(
|
||||
if (zip) {
|
||||
TransferViewModel.zipName(
|
||||
entries.map {
|
||||
it.path
|
||||
},
|
||||
)
|
||||
} else {
|
||||
entries[0].name
|
||||
},
|
||||
if (zip) "application/zip" else entries[0].mime,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
override fun share(entries: List<FileEntry>) {
|
||||
transfers.share(entries)
|
||||
model.clearSelection()
|
||||
}
|
||||
|
||||
override fun openWith(entry: FileEntry) = transfers.openWith(entry.path, entry.name)
|
||||
}
|
||||
}
|
||||
|
||||
FilesContent(state, actions)
|
||||
|
||||
when (val now = asked) {
|
||||
null -> Unit
|
||||
|
||||
Ask.NewFolder -> NameDialog(
|
||||
stringResource(R.string.folder_new),
|
||||
stringResource(R.string.files_new_folder_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = {
|
||||
asked = null
|
||||
model.newFolder(it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
Ask.NewFile -> NameDialog(
|
||||
stringResource(R.string.files_new_file),
|
||||
stringResource(R.string.files_new_file_ask),
|
||||
"",
|
||||
stringResource(R.string.save),
|
||||
onName = { name ->
|
||||
asked = null
|
||||
model.newFile(name) { path ->
|
||||
writing = true
|
||||
viewing = path
|
||||
}
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Rename -> NameDialog(
|
||||
stringResource(R.string.rename),
|
||||
stringResource(R.string.files_new_name),
|
||||
now.entry.name,
|
||||
stringResource(R.string.rename),
|
||||
onName = {
|
||||
asked = null
|
||||
model.rename(now.entry, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Delete -> ConfirmDialog(
|
||||
if (now.entries.size == 1) {
|
||||
stringResource(R.string.files_trash_one, now.entries[0].name)
|
||||
} else {
|
||||
stringResource(R.string.files_trash_many, now.entries.size.toString())
|
||||
},
|
||||
stringResource(R.string.files_to_trash),
|
||||
onConfirm = {
|
||||
asked = null
|
||||
model.batch("delete", now.entries)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Move -> FolderPicker(
|
||||
stringResource(R.string.files_move_which),
|
||||
stringResource(R.string.files_move_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("move", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
hidden = now.entries.map { it.path }.toSet(),
|
||||
)
|
||||
|
||||
is Ask.Copy -> FolderPicker(
|
||||
stringResource(R.string.files_copy_which),
|
||||
stringResource(R.string.files_copy_here),
|
||||
state.path,
|
||||
onPick = {
|
||||
asked = null
|
||||
model.batch("copy", now.entries, it)
|
||||
},
|
||||
onDismiss = { asked = null },
|
||||
)
|
||||
|
||||
is Ask.Versions -> VersionsDialog(
|
||||
now.entry.path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(now.entry.path, version.id), now.entry.name, now.entry.mime) },
|
||||
onClose = { asked = null },
|
||||
onRestored = {
|
||||
asked = null
|
||||
model.reload()
|
||||
},
|
||||
)
|
||||
|
||||
Ask.Trash -> TrashDialog(onClose = { asked = null }, onChanged = model::reload)
|
||||
}
|
||||
|
||||
state.upload?.let { TransferDialog(it, onCancel = model::cancelUpload) }
|
||||
state.said?.let { SaidDialog(it, onClose = model::clearSaid) }
|
||||
TransferHost(transfers)
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }, startEditing = writing, onChanged = model::reload) }
|
||||
}
|
||||
|
||||
/** Several things, or a folder, leave as one zip; a single file as itself. */
|
||||
fun asZip(entries: List<FileEntry>): Boolean = entries.size > 1 || entries.any { it.isFolder }
|
||||
|
||||
/**
|
||||
* The Files page, from [state] alone. A tap opens; a long press chooses, and while anything is
|
||||
* chosen a tap chooses too and the bar at the bottom acts on all of it. Each row's own menu
|
||||
* (the three dots, 48 dp) has what can be done to that one thing.
|
||||
*/
|
||||
@Composable
|
||||
fun FilesContent(state: FilesState, actions: FilesActions) {
|
||||
val palette = LocalPalette.current
|
||||
var adding by remember { mutableStateOf(false) }
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = { if (!model.up()) onBack() }) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
|
||||
if (state.selecting) {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::clearSelection) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.cancel)) }
|
||||
},
|
||||
title = { Text(stringResource(R.string.files_selected, state.selected.size.toString()), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
actions = {
|
||||
IconButton(onClick = actions::selectAll) {
|
||||
Icon(Icons.Filled.SelectAll, contentDescription = stringResource(R.string.files_select_all))
|
||||
}
|
||||
},
|
||||
)
|
||||
} else {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = actions::back) { 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,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
Box {
|
||||
IconButton(onClick = { adding = true }) { Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.files_upload)) }
|
||||
DropdownMenu(expanded = adding, onDismissRequest = { adding = false }) {
|
||||
MenuItem(R.string.files_upload) {
|
||||
adding = false
|
||||
actions.pickUpload()
|
||||
}
|
||||
MenuItem(R.string.folder_new) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFolder)
|
||||
}
|
||||
MenuItem(R.string.files_new_file) {
|
||||
adding = false
|
||||
actions.ask(Ask.NewFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = {
|
||||
actions.ask(Ask.Trash)
|
||||
}) { Icon(Icons.Filled.RestoreFromTrash, contentDescription = stringResource(R.string.trash)) }
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
bottomBar = {
|
||||
if (state.selecting) {
|
||||
val chosen = state.chosen
|
||||
// Five actions of one size, spread evenly: none of them is a word, so none can crowd another.
|
||||
BottomAppBar {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically) {
|
||||
BarButton(Icons.Filled.DriveFileMove, R.string.files_move) { actions.ask(Ask.Move(chosen)) }
|
||||
BarButton(Icons.Filled.ContentCopy, R.string.files_copy_to) { actions.ask(Ask.Copy(chosen)) }
|
||||
BarButton(Icons.Filled.Download, if (asZip(chosen)) R.string.files_download_zip else R.string.download) { actions.download(chosen) }
|
||||
BarButton(Icons.Filled.Share, R.string.report_share) { actions.share(chosen) }
|
||||
BarButton(Icons.Filled.Delete, R.string.files_to_trash) { actions.ask(Ask.Delete(chosen)) }
|
||||
}
|
||||
},
|
||||
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.working) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
state.error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }
|
||||
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::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),
|
||||
)
|
||||
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 }
|
||||
EntryRow(entry, selected = entry.path in state.selected, selecting = state.selecting, actions = actions)
|
||||
HorizontalDivider()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
viewing?.let { path -> TreeFileViewer(path, onClose = { viewing = null }) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
private fun MenuItem(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
@Composable
|
||||
private fun BarButton(icon: ImageVector, label: Int, onClick: () -> Unit) {
|
||||
IconButton(onClick = onClick) { Icon(icon, contentDescription = stringResource(label)) }
|
||||
}
|
||||
|
||||
/** What an entry is, as a picture: a folder, a shared folder, or the file's kind; a tick when it is chosen. */
|
||||
@Composable
|
||||
internal fun EntryIcon(folder: String?, fileKind: String?, selected: Boolean) {
|
||||
val palette = LocalPalette.current
|
||||
val icon = when {
|
||||
selected -> Icons.Filled.CheckCircle
|
||||
|
||||
folder == "mount" -> Icons.Filled.FolderShared
|
||||
|
||||
folder != null -> Icons.Filled.Folder
|
||||
|
||||
else -> when (fileKind) {
|
||||
"image", "svg" -> Icons.Filled.Image
|
||||
"pdf" -> Icons.Filled.PictureAsPdf
|
||||
"audio" -> Icons.Filled.MusicNote
|
||||
"video" -> Icons.Filled.Movie
|
||||
"table" -> Icons.Filled.TableChart
|
||||
"code", "html", "notebook" -> Icons.Filled.Code
|
||||
"archive" -> Icons.Filled.Archive
|
||||
"model3d", "binary" -> Icons.AutoMirrored.Filled.InsertDriveFile
|
||||
else -> Icons.Filled.Description
|
||||
}
|
||||
}
|
||||
Icon(icon, contentDescription = null, tint = if (selected) palette.accent else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EntryRow(entry: FileEntry, selected: Boolean, selecting: Boolean, actions: FilesActions) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
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,
|
||||
)
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
onClick = { if (selecting) actions.toggle(entry) else actions.open(entry) },
|
||||
onLongClick = { actions.toggle(entry) },
|
||||
),
|
||||
colors = ListItemDefaults.colors(containerColor = if (selected) palette.accentSoft else palette.bg),
|
||||
leadingContent = { EntryIcon(if (entry.isFolder) entry.kind else null, entry.fileKind, selected) },
|
||||
headlineContent = { Text(entry.name.ifBlank { entry.path }, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
supportingContent = if (entry.isFolder) {
|
||||
null
|
||||
@@ -192,5 +705,33 @@ private fun EntryRow(entry: FileEntry, onOpen: () -> Unit) {
|
||||
Text(line, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
},
|
||||
trailingContent = if (selecting) {
|
||||
null
|
||||
} else {
|
||||
{
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val one = listOf(entry)
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
MenuItem(R.string.rename, then { actions.ask(Ask.Rename(entry)) })
|
||||
MenuItem(R.string.files_move, then { actions.ask(Ask.Move(one)) })
|
||||
MenuItem(R.string.files_copy_to, then { actions.ask(Ask.Copy(one)) })
|
||||
MenuItem(if (entry.isFolder) R.string.files_download_zip else R.string.download, then { actions.download(one) })
|
||||
MenuItem(R.string.report_share, then { actions.share(one) })
|
||||
if (!entry.isFolder) {
|
||||
MenuItem(R.string.files_open_with, then { actions.openWith(entry) })
|
||||
MenuItem(R.string.versions, then { actions.ask(Ask.Versions(entry)) })
|
||||
}
|
||||
MenuItem(R.string.files_to_trash, then { actions.ask(Ask.Delete(one)) })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Application
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.text.format.Formatter
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
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.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.share.SharedRefused
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
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
|
||||
|
||||
/**
|
||||
* Something on its way to or from the instance: what it is, and how far ([total] -1: not known).
|
||||
* [waiting]: its next request has not started, because the app is not in front or the phone is
|
||||
* locked ([eu.llembas.android.InstanceGate]); it goes on by itself.
|
||||
*/
|
||||
data class Transfer(val text: String, val done: Long = 0, val total: Long = -1, val waiting: Boolean = false)
|
||||
|
||||
/** A transfer under way, what it ended in, and the other app to open once a copy is ready. */
|
||||
data class TransferState(val running: Transfer? = null, val error: String? = null, val notice: String? = null, val launch: Intent? = null)
|
||||
|
||||
/** A failure of the file manager in words: an instance without these routes says so, the rest as everywhere. */
|
||||
fun Context.filesSay(e: Throwable): String = when {
|
||||
noSuchRoute(e) -> getString(R.string.viewer_unavailable)
|
||||
e is SharedRefused -> getString(R.string.share_refused)
|
||||
e is ApiException && e.message.isNullOrBlank() -> getString(R.string.files_not_shown)
|
||||
else -> explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* Files leaving the instance for the phone: a download into a document the person chose, and a
|
||||
* copy in the private cache for another app (Open with, Share). One at a time, with its
|
||||
* progress, and it can be given up. It outlives a turn of the phone. Each request asks the gate
|
||||
* first ([turn]): none starts while the phone is locked or the app is not in front, and the one
|
||||
* under way then is let finish.
|
||||
*/
|
||||
class TransferViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(TransferState())
|
||||
val state = _state.asStateFlow()
|
||||
private var job: Job? = null
|
||||
private val app: Application get() = getApplication()
|
||||
|
||||
/** One file's bytes, or with [zip] several files and folders as one zip, into the document [to]. */
|
||||
fun download(paths: List<String>, zip: Boolean, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, if (zip) api.zipFiles(paths) else api.rawFile(paths.first()), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
/** One thing's bytes -- a version of a file, a generated file by its id, an attachment -- into the document [to]. */
|
||||
fun download(what: Raw, to: Uri) = start { api, progress ->
|
||||
turn()
|
||||
api.downloadTo(app, api.raw(what), to, progress)
|
||||
_state.update { it.copy(notice = app.getString(R.string.files_downloaded)) }
|
||||
}
|
||||
|
||||
fun openWith(path: String, name: String) = openWith(Raw.Path(path), name)
|
||||
|
||||
/** A copy for another app to open; its type is read from the copy ([Handover.view]), not taken from the instance. */
|
||||
fun openWith(what: Raw, name: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
turn()
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.view(app, copy)) }
|
||||
}
|
||||
|
||||
/** One thing that is not named by a path (a generated file by its id), shared as itself. */
|
||||
fun share(what: Raw, name: String, mime: String) = start { api, progress ->
|
||||
FileCache.sweepShared(app)
|
||||
turn()
|
||||
val copy = api.copyInto(api.raw(what), FileCache.shared(app, name), progress = progress)
|
||||
_state.update { it.copy(launch = Handover.share(app, listOf(copy), mime.ifBlank { "*/*" })) }
|
||||
}
|
||||
|
||||
/** A few files go as themselves; many, or any folder, as one zip the instance makes. */
|
||||
fun share(entries: List<FileEntry>) = start { api, progress ->
|
||||
if (entries.isEmpty()) return@start
|
||||
FileCache.sweepShared(app)
|
||||
val plain = entries.none { it.isFolder } && entries.size <= SHARE_MOST
|
||||
val copies = if (plain) {
|
||||
entries.map {
|
||||
turn()
|
||||
api.copyInto(api.rawFile(it.path), FileCache.shared(app, it.name), progress = progress)
|
||||
}
|
||||
} else {
|
||||
turn()
|
||||
listOf(api.copyInto(api.zipFiles(entries.map { it.path }), FileCache.shared(app, zipName(entries.map { it.path })), progress = progress))
|
||||
}
|
||||
val mime = if (plain) entries.map { it.mime }.distinct().singleOrNull()?.ifBlank { null } ?: "*/*" else "application/zip"
|
||||
_state.update { it.copy(launch = Handover.share(app, copies, mime)) }
|
||||
}
|
||||
|
||||
fun launched() = _state.update { it.copy(launch = null) }
|
||||
|
||||
fun say(error: String) = _state.update { it.copy(error = error) }
|
||||
|
||||
fun clear() = _state.update { it.copy(error = null, notice = null) }
|
||||
|
||||
fun cancel() {
|
||||
job?.cancel()
|
||||
}
|
||||
|
||||
/** The gate, before a request: while it is shut the dialog says the transfer is waiting. */
|
||||
private suspend fun turn() = app.lembas.gate.pass { waiting -> _state.update { it.copy(running = it.running?.copy(waiting = waiting)) } }
|
||||
|
||||
private fun start(block: suspend (ApiClient, (Long, Long) -> Unit) -> Unit) {
|
||||
if (job?.isActive == true) return
|
||||
job = viewModelScope.launch {
|
||||
_state.update { it.copy(running = Transfer(app.getString(R.string.files_downloading)), error = null, notice = null) }
|
||||
try {
|
||||
val api = app.lembas.instances.client() ?: throw ApiException(401, app.getString(R.string.assist_signed_out))
|
||||
block(api, stepped { done, total -> _state.update { it.copy(running = it.running?.copy(done = done, total = total)) } })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = app.filesSay(e)) }
|
||||
} finally {
|
||||
_state.update { it.copy(running = null) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The copies another app was handed stay while it may be reading them: only the old ones go. */
|
||||
override fun onCleared() {
|
||||
FileCache.sweepShared(app)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** More files than this are shared as one zip. */
|
||||
const val SHARE_MOST = 10
|
||||
|
||||
/** What a zip of [paths] is called: the one thing's name, else the folder they are in. */
|
||||
fun zipName(paths: List<String>): String {
|
||||
val one = paths.singleOrNull()?.let { FileKinds.name(it) }
|
||||
val folder = paths.firstOrNull()?.let { FileKinds.name(FileKinds.parent(it)) }?.takeIf { it != "/" }
|
||||
return (one ?: folder ?: "files").removeSuffix(".zip") + ".zip"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* "Save to" for one thing: the system's page for where it goes, and then the download into the
|
||||
* document chosen there. What is to be saved is kept while that page is open.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberSaver(transfers: TransferViewModel): (what: Raw, name: String, mime: String) -> Unit {
|
||||
var pending by remember { mutableStateOf<Raw?>(null) }
|
||||
val page = rememberLauncherForActivityResult(CreateFile()) { to ->
|
||||
val what = pending
|
||||
pending = null
|
||||
if (to != null && what != null) transfers.download(what, to)
|
||||
}
|
||||
return { what, name, mime ->
|
||||
pending = what
|
||||
page.launch(CreateFile.Ask(FileKinds.safeName(name), mime))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a screen shows of its transfers: the one under way with Cancel, the other app once a
|
||||
* copy is ready, a failure in a dialog (it is a sentence to read), and a short word when one
|
||||
* is done -- which names no file.
|
||||
*/
|
||||
@Composable
|
||||
fun TransferHost(model: TransferViewModel) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
val context = LocalContext.current
|
||||
LaunchedEffect(state.launch) {
|
||||
val intent = state.launch ?: return@LaunchedEffect
|
||||
try {
|
||||
context.startActivity(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
model.say(context.getString(R.string.files_no_app))
|
||||
}
|
||||
model.launched()
|
||||
}
|
||||
LaunchedEffect(state.notice) {
|
||||
state.notice?.let {
|
||||
Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
|
||||
model.clear()
|
||||
}
|
||||
}
|
||||
state.running?.let { TransferDialog(it, onCancel = model::cancel) }
|
||||
state.error?.let { SaidDialog(it, onClose = model::clear) }
|
||||
}
|
||||
|
||||
/** A transfer under way: what, how far, and Cancel. Drawn from [transfer] alone. */
|
||||
@Composable
|
||||
fun TransferDialog(transfer: Transfer, onCancel: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text(transfer.text, style = MaterialTheme.typography.bodyLarge)
|
||||
if (transfer.waiting) Text(stringResource(R.string.files_waiting), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
if (transfer.total > 0) {
|
||||
LinearProgressIndicator(progress = { (transfer.done.toFloat() / transfer.total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
}
|
||||
if (transfer.done > 0) {
|
||||
val done = Formatter.formatShortFileSize(context, transfer.done)
|
||||
val line = if (transfer.total > 0) done + " / " + Formatter.formatShortFileSize(context, transfer.total) else done
|
||||
Text(line, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** A sentence the person has to read (a refusal, a failure), with one way on. */
|
||||
@Composable
|
||||
fun SaidDialog(text: String, onClose: () -> Unit) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onClose,
|
||||
text = { Text(text, style = MaterialTheme.typography.bodyLarge) },
|
||||
confirmButton = { TextButton(onClick = onClose) { Text(stringResource(R.string.close)) } },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package eu.llembas.android.ui.files
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ClipData
|
||||
import android.content.ContentResolver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import android.provider.OpenableColumns
|
||||
import android.webkit.MimeTypeMap
|
||||
import androidx.activity.result.contract.ActivityResultContract
|
||||
import androidx.core.content.FileProvider
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.SNIFF_BYTES
|
||||
import eu.llembas.android.api.openType
|
||||
import eu.llembas.android.share.SharedSource
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
import okio.BufferedSink
|
||||
import okio.source
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
/**
|
||||
* The copies of the account's files this phone holds for a moment, all in the app's private
|
||||
* cache and nowhere else: [viewing] for what a viewer needs as a file (a PDF's pages, a
|
||||
* picture's pixels), deleted when the viewer closes; [shared] for what another app is handed
|
||||
* through the FileProvider (Open with, Share). A shared copy cannot be deleted the moment it is
|
||||
* handed over, nor when the screen that made it closes or the app starts again: the other app
|
||||
* may still be reading it (a mail being written). So it goes by its age alone, [SHARED_KEPT_MS]
|
||||
* after it was written -- looked at when the app starts, when a screen with transfers closes and
|
||||
* before a new copy is made -- and all of them go at sign-out and on a switch of instance, with
|
||||
* the photos taken for the composer ([CAMERA]). No
|
||||
* storage permission is involved: what the person keeps, they save through the system's own
|
||||
* "Save to" page.
|
||||
*/
|
||||
object FileCache {
|
||||
private const val VIEWING = "viewing"
|
||||
private const val SHARED = "shared"
|
||||
|
||||
/**
|
||||
* The folder a photo for the composer is taken into (`res/xml/file_paths.xml`). A photo is
|
||||
* deleted once it is uploaded; one whose upload failed, or that was never attached, would
|
||||
* otherwise stay for good -- so these go with the rest at sign-out and on a switch of
|
||||
* instance, and by their age when the app starts.
|
||||
*/
|
||||
const val CAMERA = "camera"
|
||||
|
||||
/** How long a copy another app was handed is kept: an hour. */
|
||||
const val SHARED_KEPT_MS = 60 * 60 * 1000L
|
||||
|
||||
private fun dir(context: Context, name: String): File = File(context.cacheDir, name).apply { mkdirs() }
|
||||
|
||||
/** A new, empty place for one viewer's copy. */
|
||||
fun viewing(context: Context, name: String): File = File(dir(context, VIEWING), UUID.randomUUID().toString() + "-" + FileKinds.safeName(name, 80))
|
||||
|
||||
/** A new place for a copy another app will read, under its own name in a folder of its own. */
|
||||
fun shared(context: Context, name: String): File =
|
||||
File(File(dir(context, SHARED), UUID.randomUUID().toString()).apply { mkdirs() }, FileKinds.safeName(name))
|
||||
|
||||
/** Every copy, gone: at sign-out and on a switch of instance. */
|
||||
fun clear(context: Context) {
|
||||
for (name in listOf(VIEWING, SHARED, CAMERA)) runCatching { File(context.cacheDir, name).deleteRecursively() }
|
||||
}
|
||||
|
||||
/** When the process starts: no viewer is open, so their copies go; the shared ones by their age. */
|
||||
fun atStart(context: Context) {
|
||||
runCatching { File(context.cacheDir, VIEWING).deleteRecursively() }
|
||||
sweepShared(context)
|
||||
// A photo being taken right now is younger than this; one left from a failed upload is not.
|
||||
sweep(File(context.cacheDir, CAMERA), System.currentTimeMillis(), SHARED_KEPT_MS)
|
||||
}
|
||||
|
||||
/** The shared copies older than [olderThanMs], and no other. */
|
||||
fun sweepShared(context: Context, olderThanMs: Long = SHARED_KEPT_MS) = sweep(File(context.cacheDir, SHARED), System.currentTimeMillis(), olderThanMs)
|
||||
|
||||
/**
|
||||
* Deletes what is directly in [dir] and was last written more than [olderThanMs] before
|
||||
* [now]. A copy's folder is as old as the newest thing in it: a long download's folder was
|
||||
* made when it began.
|
||||
*/
|
||||
fun sweep(dir: File, now: Long, olderThanMs: Long) {
|
||||
dir.listFiles()?.forEach { entry ->
|
||||
val written = maxOf(entry.lastModified(), entry.listFiles()?.maxOfOrNull { it.lastModified() } ?: 0L)
|
||||
if (now - written > olderThanMs) runCatching { entry.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
/** The address another app is given for a [shared] copy: the app's FileProvider, read-only, for that one grant. */
|
||||
fun uri(context: Context, file: File): Uri = FileProvider.getUriForFile(context, context.packageName + ".files", file)
|
||||
}
|
||||
|
||||
/** "Save to": the system's page for where a file goes (the Storage Access Framework), by a suggested name and type. */
|
||||
class CreateFile : ActivityResultContract<CreateFile.Ask, Uri?>() {
|
||||
data class Ask(val name: String, val mime: String)
|
||||
|
||||
override fun createIntent(context: Context, input: Ask): Intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
|
||||
.addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType(input.mime.ifBlank { "application/octet-stream" })
|
||||
.putExtra(Intent.EXTRA_TITLE, input.name)
|
||||
|
||||
override fun parseResult(resultCode: Int, intent: Intent?): Uri? = intent?.data?.takeIf { resultCode == Activity.RESULT_OK }
|
||||
}
|
||||
|
||||
/** A file on the phone, as the picker or another app's share named it. */
|
||||
data class LocalFile(val uri: Uri, val name: String, val size: Long, val mime: String)
|
||||
|
||||
fun ContentResolver.describe(uri: Uri): LocalFile {
|
||||
var name: String? = null
|
||||
var size = -1L
|
||||
runCatching {
|
||||
query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let { name = c.getString(it) }
|
||||
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
val said = name?.substringAfterLast('/')?.ifBlank { null } ?: uri.lastPathSegment?.substringAfterLast('/')?.ifBlank { null } ?: "upload"
|
||||
return LocalFile(uri, said, size, getType(uri) ?: "application/octet-stream")
|
||||
}
|
||||
|
||||
/**
|
||||
* A request body that reads [open]'s stream as it is sent: the file is never in memory whole.
|
||||
* [length] is its size when known (-1: sent chunked). [progress] hears how many bytes went.
|
||||
*/
|
||||
class StreamBody(
|
||||
private val type: MediaType?,
|
||||
private val length: Long,
|
||||
private val progress: (Long) -> Unit = {},
|
||||
private val open: () -> java.io.InputStream?,
|
||||
) : RequestBody() {
|
||||
override fun contentType(): MediaType? = type
|
||||
|
||||
override fun contentLength(): Long = length
|
||||
|
||||
/** The stream is read once: a failed upload is said, not silently sent again from a stream that may not open twice. */
|
||||
override fun isOneShot(): Boolean = true
|
||||
|
||||
override fun writeTo(sink: BufferedSink) {
|
||||
val stream = open() ?: throw IOException("The file could not be opened.")
|
||||
stream.source().use { source ->
|
||||
var sent = 0L
|
||||
while (true) {
|
||||
val n = source.read(sink.buffer, 64 * 1024L)
|
||||
if (n < 0) break
|
||||
sent += n
|
||||
sink.emitCompleteSegments()
|
||||
progress(sent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload one file of the phone into [dir], streamed from its content address -- opened through
|
||||
* [SharedSource], so an address that leads to this app's own files is refused whoever named it.
|
||||
*/
|
||||
suspend fun ApiClient.uploadFrom(context: Context, file: LocalFile, dir: String, progress: (Long) -> Unit = {}): FileListing =
|
||||
uploadFile(dir, file.name, StreamBody(file.mime.toMediaTypeOrNull(), file.size, progress) { SharedSource.open(context, file.uri) })
|
||||
|
||||
/**
|
||||
* Download what [request] answers into the document [to] the person chose. A download that
|
||||
* fails or is given up leaves no half file behind where the provider lets it be removed.
|
||||
*/
|
||||
suspend fun ApiClient.downloadTo(context: Context, request: okhttp3.Request, to: Uri, progress: (Long, Long) -> Unit = { _, _ -> }) {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
val out = context.contentResolver.openOutputStream(to, "w") ?: throw IOException("The file could not be written.")
|
||||
out.use { download(request, it, progress = progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { DocumentsContract.deleteDocument(context.contentResolver, to) } }
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** A copy of what [request] answers in [file] (the private cache), at most [most] bytes. */
|
||||
suspend fun ApiClient.copyInto(request: okhttp3.Request, file: File, most: Long = Long.MAX_VALUE, progress: (Long, Long) -> Unit = { _, _ -> }): File {
|
||||
try {
|
||||
withContext(Dispatchers.IO) {
|
||||
file.parentFile?.mkdirs()
|
||||
file.outputStream().use { download(request, it, most, progress) }
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
withContext(kotlinx.coroutines.NonCancellable + Dispatchers.IO) { runCatching { file.delete() } }
|
||||
throw e
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
/** Hand [files] (cache copies) to another app: "Open with" for one, Share for one or several. Read-only, for this one grant. */
|
||||
object Handover {
|
||||
/**
|
||||
* "Open with" for the copy [file]. What it is offered as is read from the copy itself
|
||||
* ([openType]: its first bytes, else its name's extension) -- never the type the instance
|
||||
* said, which for a file an agent showed is one more thing a model had a hand in.
|
||||
*/
|
||||
fun view(context: Context, file: File): Intent {
|
||||
val uri = FileCache.uri(context, file)
|
||||
// A copy that cannot be read again is offered by its name alone.
|
||||
val head = try {
|
||||
file.inputStream().use { stream ->
|
||||
val bytes = ByteArray(SNIFF_BYTES)
|
||||
bytes.copyOf(stream.read(bytes).coerceAtLeast(0))
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
ByteArray(0)
|
||||
}
|
||||
val named = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension.lowercase())
|
||||
val intent = Intent(Intent.ACTION_VIEW).setDataAndType(uri, openType(head, named)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
|
||||
fun share(context: Context, files: List<File>, mime: String): Intent {
|
||||
val uris = files.map { FileCache.uri(context, it) }
|
||||
val intent = if (uris.size == 1) {
|
||||
Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris[0])
|
||||
} else {
|
||||
Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uris))
|
||||
}
|
||||
intent.setType(mime.ifBlank { "*/*" }).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
// The chooser's own preview reads the address too: it is told through the clip.
|
||||
intent.clipData = ClipData.newRawUri(null, uris[0]).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
|
||||
return Intent.createChooser(intent, null)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a failure says the server has no such route at all (an older instance), rather than refusing. */
|
||||
fun noSuchRoute(e: Throwable): Boolean = e is ApiException && (e.status == 405 || (e.status == 404 && e.message == "Not Found"))
|
||||
|
||||
/** [report], heard only every quarter megabyte and at the end: a transfer does not redraw the screen for every packet. */
|
||||
fun stepped(report: (Long, Long) -> Unit): (Long, Long) -> Unit {
|
||||
var last = 0L
|
||||
return { done, total ->
|
||||
if (done - last >= 256 * 1024 || done == total) {
|
||||
last = done
|
||||
report(done, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,10 @@ 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.appended
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
@@ -67,13 +69,17 @@ class ArchivedViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
private var moreRead: Job? = null
|
||||
|
||||
/** The page after the last row: one read at a time, and no chat twice ([appended]). */
|
||||
fun more() {
|
||||
if (moreRead?.isActive == true) return
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
moreRead = 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) }
|
||||
_state.update { it.copy(chats = appended(it.chats, page.chats) { chat -> chat.id }, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import android.app.Application
|
||||
@@ -7,6 +9,7 @@ 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.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
@@ -22,7 +25,9 @@ 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.Add
|
||||
import androidx.compose.material.icons.filled.Archive
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
@@ -39,6 +44,7 @@ import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Summarize
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.UnfoldMore
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
@@ -46,6 +52,7 @@ 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.ModalDrawerSheet
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
@@ -53,6 +60,7 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TextField
|
||||
import androidx.compose.material3.TextFieldDefaults
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -75,24 +83,35 @@ import androidx.lifecycle.viewModelScope
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.ChatPage
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Folder
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import eu.llembas.android.api.ReportsFrame
|
||||
import eu.llembas.android.api.SearchHit
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.appended
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
import eu.llembas.android.ui.signin.unfit
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.buildJsonObject
|
||||
import kotlinx.serialization.json.put
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
data class ChatsState(
|
||||
@@ -111,13 +130,77 @@ data class ChatsState(
|
||||
val reports: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* The events route's `reports` frame, as the drawer takes it: the badge is the server's count
|
||||
* of the unread, and an instance that sends the frame has Reports. Anything else it carries
|
||||
* (the newest report) is not the drawer's. A frame that cannot be read changes nothing.
|
||||
*/
|
||||
fun ChatsState.reported(data: String): ChatsState {
|
||||
val frame = runCatching { LembasJson.decodeFromString(ReportsFrame.serializer(), data) }.getOrNull() ?: return this
|
||||
return copy(unreadReports = frame.unread.coerceAtLeast(0), reports = true)
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's newest page read again ([page]), merged by id: the page's chats first, as the server
|
||||
* orders and marks them now (the one a reply just started in first, running or unread), then
|
||||
* every chat this list held that the page does not name, in the order it had. A chat that came
|
||||
* up from a later page a person had loaded is in the page, so it moves; the ones around its old
|
||||
* place stay. No chat is listed twice.
|
||||
*
|
||||
* The list is ordered by when a chat last changed, so the page holds every chat that changed
|
||||
* since its own last one did: a chat held here from after that moment which the page does not
|
||||
* name is no longer in the list (deleted, archived or filed away elsewhere), and goes. A page
|
||||
* with nothing after it is the whole list.
|
||||
*/
|
||||
fun ChatsState.withNewest(page: ChatPage): ChatsState {
|
||||
if (!page.more) return copy(chats = page.chats, more = false)
|
||||
val newest = page.chats.mapTo(HashSet()) { it.id }
|
||||
val floor = page.chats.lastOrNull()?.updatedAt?.let(::moment)
|
||||
val older = chats.filter { it.id !in newest && !gone(it, floor) }
|
||||
// Nothing below the page: whether there is more is the page's word.
|
||||
return copy(chats = page.chats + older, more = if (older.isEmpty()) page.more else more)
|
||||
}
|
||||
|
||||
/** Whether [chat], which the newest page does not name, changed after the page's last chat did ([floor]): it would be in the page were it still listed. */
|
||||
private fun gone(chat: Chat, floor: Instant?): Boolean {
|
||||
val changed = chat.updatedAt?.let(::moment) ?: return false
|
||||
return floor != null && changed.isAfter(floor)
|
||||
}
|
||||
|
||||
/** A time as the server writes it (ISO 8601 with an offset); null for anything else. */
|
||||
private fun moment(stamp: String): Instant? = runCatching { OffsetDateTime.parse(stamp).toInstant() }.getOrNull()
|
||||
|
||||
/**
|
||||
* Whether the events route's `reply` frame [said] asks for the list to be read again. Only
|
||||
* while something shows the list ([shown]; the drawer reads it whenever it opens), and only for
|
||||
* what the list does not show already: a reply that started in a chat whose row says it is
|
||||
* running is no news (every reconnection of the route says all of those again), and the end
|
||||
* of a reply in a chat that is listed is marked on its row without a read ([ended]). A list
|
||||
* not read yet is left to its first read.
|
||||
*/
|
||||
fun ChatsState.readsFor(said: ReplyFrame, shown: Boolean): Boolean {
|
||||
if (!shown || chats.isEmpty() || said.chatId.isBlank()) return false
|
||||
val row = chats.firstOrNull { it.id == said.chatId }
|
||||
return if (said.live) row?.running != true else row == null
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply ended in the chat [said] names (`live` false): its row is no longer running, and shows
|
||||
* that it has something new -- unless it is the chat [open] on screen, where the person watched
|
||||
* it end. Nothing is read for it.
|
||||
*/
|
||||
fun ChatsState.ended(said: ReplyFrame, open: String?): ChatsState {
|
||||
if (said.live || chats.none { it.id == said.chatId }) return this
|
||||
return copy(chats = chats.map { if (it.id == said.chatId) it.copy(running = false, unread = it.unread || it.id != open) else it })
|
||||
}
|
||||
|
||||
/** 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 refused: String? = null
|
||||
private var checked = false
|
||||
|
||||
/** Read the list; the rows already shown stay while it is read again. */
|
||||
@@ -131,13 +214,14 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
if (!checked) {
|
||||
runCatching { Doorstep().discover(api.base) }.onSuccess {
|
||||
checked = true
|
||||
refused = refusal(fit(it))
|
||||
refused = getApplication<Application>().unfit(it)
|
||||
}
|
||||
}
|
||||
refused?.let { said ->
|
||||
_state.value = ChatsState(error = getApplication<Application>().getString(said))
|
||||
_state.value = ChatsState(error = said)
|
||||
return@launch
|
||||
}
|
||||
val told = reportsTold
|
||||
val page = api.chats()
|
||||
// Folders are a side dish: the chats show without them if they cannot be read.
|
||||
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
|
||||
@@ -152,12 +236,15 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
} else {
|
||||
_state.value.reports
|
||||
}
|
||||
// The events route may have said the count while this was being read: its
|
||||
// word is the newer one, and a slow read does not write over it.
|
||||
val newer = reportsTold != told
|
||||
_state.value = ChatsState(
|
||||
chats = page.chats,
|
||||
more = page.more,
|
||||
folders = folders,
|
||||
unreadReports = unread.getOrDefault(_state.value.unreadReports),
|
||||
reports = has,
|
||||
unreadReports = if (newer) _state.value.unreadReports else unread.getOrDefault(_state.value.unreadReports),
|
||||
reports = has || (newer && _state.value.reports),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
@@ -165,13 +252,134 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow the person's events route while the app is in front, for its `reports` frame: the
|
||||
* badge on Reports moves when a report arrives or is read anywhere, not only when the drawer
|
||||
* opens. Runs until cancelled. An older server has no such route, or no such frame: the
|
||||
* badge is then what the drawer's own read said.
|
||||
*/
|
||||
suspend fun watchReports() {
|
||||
val app = getApplication<Application>().lembas
|
||||
// What one instance proved about its frames says nothing of another.
|
||||
val instance = app.instances.current()?.id
|
||||
if (instance != endsOf) {
|
||||
ends = ReplyEnds()
|
||||
endsOf = instance
|
||||
}
|
||||
val frames = runCatching { app.eventFrames() }.getOrNull() ?: return
|
||||
try {
|
||||
frames.collect { frame ->
|
||||
// An instance this app refuses shows its refusal and nothing else.
|
||||
if (frame.event == "reports" && refused == null) {
|
||||
reportsTold++
|
||||
_state.update { it.reported(frame.data) }
|
||||
}
|
||||
if (frame.event == "reply" && refused == null) replySaid(frame.data)
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
// Nothing to say: the count is read when the drawer opens, as before.
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the list is on screen (the drawer is open): only then is it read again by itself. */
|
||||
private var shown = false
|
||||
|
||||
/** The chat open on screen, by its id: the end of its reply is not something new. */
|
||||
var open: String? = null
|
||||
|
||||
/** Whether this instance says when replies end; until it has, a running row is read again now and then. */
|
||||
private var ends = ReplyEnds()
|
||||
|
||||
/** The instance [ends] is about, by its id. */
|
||||
private var endsOf: String? = null
|
||||
|
||||
fun shown(now: Boolean) {
|
||||
shown = now
|
||||
// What was asked for while it was open is the next opening's read.
|
||||
if (!now) soon.forget()
|
||||
}
|
||||
|
||||
/**
|
||||
* The events route said a reply started or ended in one of the person's chats. An end is
|
||||
* marked on the chat's row at once, with no read; a start in a chat the list does not show
|
||||
* as running moves that chat up and gives it its dot at the list's next read, shortly --
|
||||
* while the drawer is open. Closed, nothing is read: it reads the list when it opens.
|
||||
*/
|
||||
private fun replySaid(data: String) {
|
||||
val said = runCatching { LembasJson.decodeFromString(ReplyFrame.serializer(), data) }.getOrNull() ?: return
|
||||
ends.hear(said)
|
||||
val reads = _state.value.readsFor(said, shown)
|
||||
if (!said.live) _state.update { it.ended(said, open) }
|
||||
if (reads) soon.ask()
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest page of the list, read once things have been quiet for a moment: several
|
||||
* replies starting together (a queue, a team) are one read, and a run of them that never
|
||||
* falls quiet still gets one every few seconds. It waits at the gate, so a frame heard just
|
||||
* before the phone locked or the app left the front is one read on the return, not a
|
||||
* request behind the lock. A read under way is never cut short by the next frame.
|
||||
*/
|
||||
private val soon by lazy {
|
||||
Soon(viewModelScope, LIST_PAUSE_MS, LIST_MOST_MS, before = { getApplication<Application>().lembas.gate.pass() }) { readNewest() }
|
||||
}
|
||||
|
||||
private val reading = Mutex()
|
||||
|
||||
/** The list's newest page, merged into what is shown. A list not read yet is left to its first read. */
|
||||
private suspend fun readNewest() = reading.withLock {
|
||||
if (refused != null || _state.value.chats.isEmpty()) return@withLock
|
||||
val page = try {
|
||||
getApplication<Application>().lembas.instances.client()?.chats()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
} ?: return@withLock
|
||||
_state.update { it.withNewest(page) }
|
||||
}
|
||||
|
||||
/**
|
||||
* While the list is on screen and the app in front: an instance that does not say when a
|
||||
* reply ends leaves a row's running mark as old as the list's last read, so while any row
|
||||
* shows one the list is read again at a bounded rate ([runningPause]), at the gate, and no
|
||||
* more once none does. An instance that says the ends ([ReplyEnds]) is never asked: its
|
||||
* frames clear the marks. Runs until cancelled (the drawer closed, the app left the front).
|
||||
*/
|
||||
suspend fun watchRunning() {
|
||||
val gate = getApplication<Application>().lembas.gate
|
||||
var round = 0
|
||||
while (true) {
|
||||
_state.first { state -> state.chats.any { it.running } }
|
||||
if (ends.said) return
|
||||
delay(runningPause(round))
|
||||
gate.pass()
|
||||
if (ends.said) return
|
||||
if (_state.value.chats.none { it.running }) {
|
||||
round = 0
|
||||
continue
|
||||
}
|
||||
round++
|
||||
readNewest()
|
||||
}
|
||||
}
|
||||
|
||||
/** How many `reports` frames have come: a list read that began before the last one is older than it. */
|
||||
private var reportsTold = 0
|
||||
|
||||
private var moreRead: Job? = null
|
||||
|
||||
/** The page after the last row. One read at a time, and no chat twice ([appended]): the list asks again whenever its end comes into view. */
|
||||
fun more() {
|
||||
if (moreRead?.isActive == true) return
|
||||
val last = _state.value.chats.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
moreRead = 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) }
|
||||
_state.update { it.copy(chats = appended(it.chats, page.chats) { chat -> chat.id }, more = page.more) }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -271,6 +479,12 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private const val SEARCH_PAUSE_MS = 400L
|
||||
|
||||
/** Between a `reply` frame and the list's read: a reply is said about a quarter of a second after it starts. */
|
||||
private const val LIST_PAUSE_MS = 1500L
|
||||
|
||||
/** The longest a read of the list waits for the replies' frames to fall quiet. */
|
||||
private const val LIST_MOST_MS = 6000L
|
||||
|
||||
/** Where the drawer can go, besides a chat. */
|
||||
interface DrawerActions {
|
||||
fun newChat() {}
|
||||
@@ -289,6 +503,8 @@ interface DrawerActions {
|
||||
fun archived() {}
|
||||
fun memory() {}
|
||||
fun settings() {}
|
||||
fun useInstance(instance: Instance) {}
|
||||
fun addInstance() {}
|
||||
fun more() {}
|
||||
fun retry() {}
|
||||
fun search(query: String) {}
|
||||
@@ -310,9 +526,13 @@ fun DrawerContent(
|
||||
today: LocalDate = LocalDate.now(),
|
||||
zone: ZoneId = ZoneId.systemDefault(),
|
||||
initialQuery: String = "",
|
||||
instances: List<Instance> = emptyList(),
|
||||
activeInstance: Instance? = null,
|
||||
defaultInstanceId: String? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
var query by rememberSaveable { mutableStateOf(initialQuery) }
|
||||
var switchingInstance by remember { mutableStateOf(false) }
|
||||
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.
|
||||
@@ -416,10 +636,74 @@ fun DrawerContent(
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = palette.border)
|
||||
DrawerItem(Icons.Filled.Settings, stringResource(R.string.settings), subtitle = account.ifBlank { null }, onClick = actions::settings)
|
||||
if (instances.isNotEmpty() && activeInstance != null) {
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp)
|
||||
.clip(RoundedCornerShape(20.dp))
|
||||
.clickable { switchingInstance = true }
|
||||
.heightIn(min = 52.dp)
|
||||
.padding(horizontal = 14.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
activeInstance.name.ifBlank { activeInstance.base },
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = palette.ink,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (activeInstance.email.isNotBlank()) {
|
||||
Text(
|
||||
activeInstance.email,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
Icons.Filled.UnfoldMore,
|
||||
contentDescription = stringResource(R.string.instance_switch),
|
||||
tint = palette.inkMuted,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
DrawerItem(
|
||||
Icons.Filled.Settings,
|
||||
stringResource(R.string.settings),
|
||||
subtitle = if (instances.isEmpty()) account.ifBlank { null } else null,
|
||||
onClick = actions::settings,
|
||||
)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
}
|
||||
}
|
||||
if (switchingInstance) {
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { switchingInstance = false },
|
||||
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
|
||||
) {
|
||||
InstanceSwitcherSheet(
|
||||
instances = instances,
|
||||
activeId = activeInstance?.id,
|
||||
defaultId = defaultInstanceId,
|
||||
onPick = { picked ->
|
||||
switchingInstance = false
|
||||
if (picked.id != activeInstance?.id) actions.useInstance(picked)
|
||||
},
|
||||
onAdd = {
|
||||
switchingInstance = false
|
||||
actions.addInstance()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
moving?.let { chat ->
|
||||
MoveDialog(
|
||||
chat,
|
||||
@@ -499,6 +783,95 @@ private data class FolderNaming(val folder: Folder? = null, val then: Chat? = nu
|
||||
/** 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)
|
||||
|
||||
@Composable
|
||||
private fun InstanceSwitcherSheet(instances: List<Instance>, activeId: String?, defaultId: String?, onPick: (Instance) -> Unit, onAdd: () -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.settings_instances),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
items(instances, key = { it.id }) { item ->
|
||||
val inUse = item.id == activeId
|
||||
val isDefault = item.id == defaultId
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onPick(item) }
|
||||
.heightIn(min = 64.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
item.name.ifBlank { item.base },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = palette.ink,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (isDefault) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.instance_default),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.email.isNotBlank()) {
|
||||
Text(
|
||||
item.email,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
item.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,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
HorizontalDivider(color = palette.border, modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp))
|
||||
Row(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onAdd)
|
||||
.heightIn(min = 56.dp)
|
||||
.padding(horizontal = 24.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(Icons.Filled.Add, contentDescription = null, tint = palette.accent)
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Text(stringResource(R.string.add_instance), style = MaterialTheme.typography.bodyLarge, color = palette.ink)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun LazyListScope.section(title: Int, chats: List<Chat>, current: String?, actions: ChatRowActions, key: String = "c") {
|
||||
if (chats.isEmpty()) return
|
||||
item(key = "h$title") {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
package eu.llembas.android.ui.home
|
||||
|
||||
import eu.llembas.android.api.ReplyFrame
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* Something done shortly after it was asked for, once for many askings: [work] runs when nobody
|
||||
* has asked for [pause] milliseconds, and at the latest [most] milliseconds after the first
|
||||
* asking -- so a stream of askings closer together than the pause (a team's replies starting
|
||||
* one after another) still gets its work, every [most], instead of none until it falls quiet.
|
||||
*
|
||||
* Work under way is never cancelled by a new asking; an asking that comes while it runs is
|
||||
* answered by one more run after it. [before] is what the work waits for before it starts (its
|
||||
* turn at the gate): an asking during that wait is still answered by the run it waits for.
|
||||
*
|
||||
* Everything here runs on [scope]'s one thread.
|
||||
*/
|
||||
class Soon(
|
||||
private val scope: CoroutineScope,
|
||||
private val pause: Long,
|
||||
private val most: Long,
|
||||
private val before: suspend () -> Unit = {},
|
||||
private val work: suspend () -> Unit,
|
||||
) {
|
||||
private var quiet: Job? = null
|
||||
private var latest: Job? = null
|
||||
|
||||
/** Whether a run is under way, from before its turn to its end. */
|
||||
private var running = false
|
||||
|
||||
/** Whether the run under way has started its work: an asking from then on is newer than it. */
|
||||
private var started = false
|
||||
private var again = false
|
||||
|
||||
fun ask() {
|
||||
if (running) {
|
||||
if (started) again = true
|
||||
return
|
||||
}
|
||||
quiet?.cancel()
|
||||
quiet = scope.launch {
|
||||
delay(pause)
|
||||
run()
|
||||
}
|
||||
if (latest?.isActive != true) {
|
||||
latest = scope.launch {
|
||||
delay(most)
|
||||
run()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** What was asked for and has not started is dropped (nobody is looking any more); work under way finishes. */
|
||||
fun forget() {
|
||||
quiet?.cancel()
|
||||
latest?.cancel()
|
||||
quiet = null
|
||||
latest = null
|
||||
again = false
|
||||
}
|
||||
|
||||
private fun run() {
|
||||
if (running) return
|
||||
val timers = listOf(quiet, latest)
|
||||
quiet = null
|
||||
latest = null
|
||||
started = false
|
||||
running = true
|
||||
// Not a child of either timer: cancelling them below must not reach the work.
|
||||
scope.launch {
|
||||
try {
|
||||
before()
|
||||
started = true
|
||||
work()
|
||||
} finally {
|
||||
running = false
|
||||
if (again) {
|
||||
again = false
|
||||
ask()
|
||||
}
|
||||
}
|
||||
}
|
||||
// One of the two is the caller; it has nothing left to do.
|
||||
timers.forEach { it?.cancel() }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the instance says when a reply ends: the events route's `reply` frame with `live`
|
||||
* false, for a reply it had said was being written. One such frame is the proof, and from then
|
||||
* on the list's running marks are cleared by the frames alone. An instance from before that
|
||||
* never proves it, and the list is read again now and then instead ([runningPause]).
|
||||
*/
|
||||
class ReplyEnds {
|
||||
private val started = LinkedHashSet<String>()
|
||||
|
||||
var said = false
|
||||
private set
|
||||
|
||||
fun hear(frame: ReplyFrame) {
|
||||
if (frame.messageId.isBlank()) return
|
||||
if (frame.live) {
|
||||
started += frame.messageId
|
||||
if (started.size > REMEMBERED) started.remove(started.first())
|
||||
} else if (started.remove(frame.messageId)) {
|
||||
said = true
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val REMEMBERED = 64
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How long to wait before the list is read again because a row shows a reply being written and
|
||||
* nothing has said it ended: 5, 10, 20, 40 seconds, then every minute ([round] counts the
|
||||
* reads since a row last showed one). A bounded rate, and only while such a row is on screen.
|
||||
*/
|
||||
fun runningPause(round: Int): Long = (5_000L shl round.coerceIn(0, 4)).coerceAtMost(60_000L)
|
||||
@@ -39,6 +39,7 @@ 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.api.SchedulingModel
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.chat.LocalCopy
|
||||
import eu.llembas.android.ui.chat.RichMarkdown
|
||||
@@ -49,7 +50,14 @@ 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)
|
||||
data class RunState(
|
||||
val title: String = "",
|
||||
val result: RunResult? = null,
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
/** The models scheduled work may run on, for naming the run's by its connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow(RunState())
|
||||
@@ -64,6 +72,7 @@ class RunViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val result = api.scheduleRun(schedule, run)
|
||||
val title = runCatching { api.schedule(schedule).title }.getOrDefault("")
|
||||
_state.update { it.copy(result = result, title = title, loading = false) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
@@ -128,7 +137,7 @@ fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) ->
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
RunFacts(run, withPreview = false)
|
||||
RunFacts(run, withPreview = false, models = state.models)
|
||||
// What the run filed for the person, when it filed anything.
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ 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.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -24,6 +26,7 @@ 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.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
@@ -31,6 +34,7 @@ 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.Folder
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
@@ -41,6 +45,7 @@ import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExtendedFloatingActionButton
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -67,7 +72,9 @@ 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.LocalInspectionMode
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -79,16 +86,27 @@ 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.DeviceDirectory
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.LinkedDevice
|
||||
import eu.llembas.android.api.RanOn
|
||||
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.SchedulingModel
|
||||
import eu.llembas.android.api.WatchCommand
|
||||
import eu.llembas.android.api.WhereToRun
|
||||
import eu.llembas.android.api.agentic
|
||||
import eu.llembas.android.api.computerAway
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.notifyChoice
|
||||
import eu.llembas.android.api.saidWithConnection
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.DirectoryPicker
|
||||
import eu.llembas.android.ui.appended
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.progressLineOf
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
@@ -100,6 +118,9 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** Whether the Scheduled list starts listening to the events route now: only [inFront], and only once ([listening]). */
|
||||
fun listens(inFront: Boolean, listening: Boolean): Boolean = inFront && !listening
|
||||
|
||||
/** 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)
|
||||
|
||||
@@ -120,6 +141,19 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
private var live: Job? = null
|
||||
|
||||
/**
|
||||
* Whether the list is on screen, in front. The events route is listened to only then: a read
|
||||
* that comes back after the screen was left (or the phone locked) must not open it, for
|
||||
* nothing would close it again while this model lives.
|
||||
*/
|
||||
private var front = false
|
||||
|
||||
/** The screen came to the front: the list is read, and followed until [stop]. */
|
||||
fun shown() {
|
||||
front = true
|
||||
load()
|
||||
}
|
||||
|
||||
fun load() {
|
||||
viewModelScope.launch {
|
||||
_state.update { it.copy(loading = true, error = null) }
|
||||
@@ -147,11 +181,12 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
* Without it the list is what the last read said, and a pull reads it again.
|
||||
*/
|
||||
private fun watch() {
|
||||
if (live?.isActive == true) return
|
||||
if (!listens(front, live?.isActive == true)) return
|
||||
live = viewModelScope.launch {
|
||||
val client = runCatching { getApplication<Application>().api() }.getOrNull() ?: return@launch
|
||||
// The one connection the drawer's badge listens on too (`EventsHub`).
|
||||
val frames = runCatching { getApplication<Application>().lembas.eventFrames() }.getOrNull() ?: return@launch
|
||||
try {
|
||||
StreamClient(client).watch { client.events() }.collect { frame ->
|
||||
frames.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) }
|
||||
@@ -165,6 +200,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
front = false
|
||||
live?.cancel()
|
||||
live = null
|
||||
}
|
||||
@@ -192,7 +228,7 @@ class ScheduledViewModel(app: Application) : AndroidViewModel(app) {
|
||||
fun ScheduledScreen(onBack: () -> Unit, onOpen: (String) -> Unit, onNew: () -> Unit, onModels: () -> Unit, model: ScheduledViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LifecycleResumeEffect(Unit) {
|
||||
model.load()
|
||||
model.shown()
|
||||
onPauseOrDispose { model.stop() }
|
||||
}
|
||||
ScheduledContent(state, onBack = onBack, onOpen = onOpen, onNew = onNew, onModels = onModels, onPause = model::pause, onRetry = model::load)
|
||||
@@ -364,6 +400,8 @@ data class ScheduleState(
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
/** The models scheduled work may run on: what tells two with one id apart by their connection. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
)
|
||||
|
||||
class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
@@ -380,18 +418,23 @@ class ScheduleViewModel(app: Application) : AndroidViewModel(app) {
|
||||
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) }
|
||||
runCatching { api.schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
} catch (e: Exception) {
|
||||
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var moreRead: Job? = null
|
||||
|
||||
/** The runs before the last row: one read at a time, and no run twice ([appended]). */
|
||||
fun more() {
|
||||
if (moreRead?.isActive == true) return
|
||||
val schedule = _state.value.schedule ?: return
|
||||
val last = _state.value.runs.lastOrNull() ?: return
|
||||
viewModelScope.launch {
|
||||
moreRead = 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) } }
|
||||
.onSuccess { page -> _state.update { it.copy(runs = appended(it.runs, page.runs) { row -> row.id }, more = page.more) } }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,7 +584,14 @@ private fun ScheduleBody(
|
||||
}
|
||||
Text(schedule.instruction, style = MaterialTheme.typography.bodyMedium)
|
||||
val facts = listOfNotNull(
|
||||
schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) },
|
||||
stringResource(R.string.schedule_type) + ": " +
|
||||
stringResource(if (schedule.agentic) R.string.schedule_agentic else R.string.schedule_chat),
|
||||
// An Agentic schedule with no model of its own runs on the folder's usual one.
|
||||
stringResource(
|
||||
R.string.schedule_model,
|
||||
state.models.saidWithConnection(schedule.modelRef, schedule.model)
|
||||
?: stringResource(if (schedule.agentic) R.string.schedule_folder_model else R.string.schedule_first_free_model),
|
||||
),
|
||||
modeWords(schedule.mode),
|
||||
notifyWords(schedule),
|
||||
)
|
||||
@@ -604,7 +654,9 @@ private fun ScheduleBody(
|
||||
)
|
||||
}
|
||||
}
|
||||
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport) }
|
||||
items(state.runs, key = { it.id }) { run ->
|
||||
RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport, models = state.models)
|
||||
}
|
||||
if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } }
|
||||
}
|
||||
}
|
||||
@@ -663,6 +715,23 @@ private fun ComputerLine(on: RunsOn, away: Boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A run's own line for where it ran: the computer and the folder there. The folder gives first. */
|
||||
@Composable
|
||||
private fun RanOnLine(on: RanOn) {
|
||||
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(
|
||||
listOf(on.deviceName.ifBlank { stringResource(R.string.schedule_computer_gone) }, on.cwd).filter { it.isNotBlank() }.joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
maxLines = 2,
|
||||
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) {
|
||||
@@ -716,7 +785,7 @@ internal fun Header(text: String) {
|
||||
* whole row opens the run.
|
||||
*/
|
||||
@Composable
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}) {
|
||||
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(
|
||||
onClick = onOpen,
|
||||
@@ -729,9 +798,14 @@ private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpen
|
||||
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)
|
||||
// Where the run ran (its own word, spec 3.9.0), else which computer it was for --
|
||||
// and whether that was away.
|
||||
val ran = run.ranOn?.takeIf { it.device.isNotBlank() }
|
||||
when {
|
||||
ran != null -> RanOnLine(ran)
|
||||
runsOn != null -> ComputerName(runsOn, away = run.computerAway)
|
||||
}
|
||||
RunFacts(run, maxLines = 2, models = models)
|
||||
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
|
||||
}
|
||||
}
|
||||
@@ -754,13 +828,16 @@ internal fun ReportLink(onClick: () -> Unit) {
|
||||
|
||||
/** Under a run's time: the model and why, what it is doing or the trouble, then its note (or the result's first lines). */
|
||||
@Composable
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true) {
|
||||
internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPreview: Boolean = true, models: List<SchedulingModel> = emptyList()) {
|
||||
val palette = LocalPalette.current
|
||||
val name = run.model.label
|
||||
// Which connection ran it, where the run says so and two models here share the id.
|
||||
val name = models.saidWithConnection(run.model.ref, run.model.label)
|
||||
val from = run.model.switchedFrom
|
||||
val why = runModelWhy(run.model.reason)
|
||||
val model = when {
|
||||
name == null -> null
|
||||
run.model.reason == "switched" && from != null -> stringResource(R.string.run_model_instead, name, from)
|
||||
why != null -> name + " · " + stringResource(why)
|
||||
else -> name
|
||||
}
|
||||
model?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
@@ -788,6 +865,18 @@ internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPrevi
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How a run's model was chosen, where that is worth a word (spec 3.9.0): the folder's usual
|
||||
* one, the person's default where the folder had none, or a continued conversation's own. A
|
||||
* pinned model needs none, and a switched one has its own sentence.
|
||||
*/
|
||||
fun runModelWhy(reason: String?): Int? = when (reason) {
|
||||
"directory" -> R.string.run_model_directory
|
||||
"default" -> R.string.run_model_default
|
||||
"session" -> R.string.run_model_session
|
||||
else -> null
|
||||
}
|
||||
|
||||
// --- Create and edit ------------------------------------------------------------------------
|
||||
|
||||
data class EditState(
|
||||
@@ -809,8 +898,148 @@ data class EditState(
|
||||
val loadFailed: Boolean = false,
|
||||
/** The person chose a "notify when" themselves. */
|
||||
val notifyTouched: Boolean = false,
|
||||
/** The type (spec 3.9.0): Agentic runs on [device], in [cwd]; Chat on the server. */
|
||||
val agentic: Boolean = false,
|
||||
/** The linked computers, and -- for a schedule being edited -- its own, linked now or not. */
|
||||
val devices: List<LinkedDevice> = emptyList(),
|
||||
val device: String = "",
|
||||
val cwd: String = "",
|
||||
/** The agent's mode on the computer: `manual`, `edit` or `auto`. */
|
||||
val agentMode: String = "edit",
|
||||
/** How long an approval waits, in minutes, as typed; empty: the instance's own. */
|
||||
val wait: String = "",
|
||||
/** An Agentic schedule's model; empty: the folder's usual model. */
|
||||
val model: String = "",
|
||||
/** [model] is the schedule's own `model_ref` as read: looked up as a ref alone ([modelInfo]). A pick is not. */
|
||||
val modelIsRef: Boolean = false,
|
||||
/** The models scheduled work may run on (`GET /schedules/models`): never an interactive-only one. */
|
||||
val models: List<SchedulingModel> = emptyList(),
|
||||
/** The person changed the type or one of its fields themselves. */
|
||||
val whereTouched: Boolean = false,
|
||||
/** What the schedule being edited was when it was read: Agentic or Chat. */
|
||||
val wasAgentic: Boolean = false,
|
||||
/** Where the schedule being edited ran, its model and its watched command, as they were read: a save says only what differs. */
|
||||
val readWhere: WhereToRun.Computer? = null,
|
||||
val readModel: String = "",
|
||||
val readWatch: WatchCommand = WatchCommand("", null),
|
||||
/** An Agentic schedule's watched command (empty: none), and the seconds it may take, as typed. */
|
||||
val watchCommand: String = "",
|
||||
val watchTimeout: String = "",
|
||||
)
|
||||
|
||||
/** The agent modes, narrowest first. */
|
||||
val AGENT_MODES = listOf("manual", "edit", "auto")
|
||||
|
||||
/**
|
||||
* The modes the form offers for a computer whose widest is [maxMode]: none wider than it
|
||||
* (every one where it names none, as an older computer does), and the mode the schedule
|
||||
* already has ([current]) whatever the computer says now -- it lowers it itself.
|
||||
*/
|
||||
fun modesOffered(maxMode: String, current: String): List<String> {
|
||||
val widest = AGENT_MODES.indexOf(maxMode).takeIf { it >= 0 } ?: AGENT_MODES.lastIndex
|
||||
return AGENT_MODES.filterIndexed { i, mode -> i <= widest || mode == current }
|
||||
}
|
||||
|
||||
/** Where the form says the schedule runs, as a save would say it. */
|
||||
val EditState.computer: WhereToRun.Computer get() = WhereToRun.Computer(device, cwd.trim(), agentMode, waitMinutes)
|
||||
|
||||
/** The watched command as the form holds it: the seconds only between 1 and 600, and only with a command. */
|
||||
val EditState.watched: WatchCommand
|
||||
get() = watchCommand.trim().let { command -> WatchCommand(command, watchTimeout.trim().toIntOrNull()?.takeIf { command.isNotEmpty() && it in 1..600 }) }
|
||||
|
||||
/** An Agentic schedule that watches a command is being made a Chat one: the command cannot go with it. */
|
||||
val EditState.dropsWatch: Boolean get() = !agentic && wasAgentic && readWatch.command.isNotEmpty()
|
||||
|
||||
/** Agentic is offered only while one of the person's computers accepts scheduled work. */
|
||||
val EditState.agenticOffered: Boolean get() = devices.any { it.scheduled }
|
||||
|
||||
/** The computer chosen, when it is one of those listed. */
|
||||
val EditState.chosenDevice: LinkedDevice? get() = devices.firstOrNull { it.id == device }
|
||||
|
||||
/** An approval's wait as a number of minutes, or null for the instance's own (empty, or not a number). */
|
||||
val EditState.waitMinutes: Int? get() = wait.trim().toIntOrNull()?.takeIf { it > 0 }
|
||||
|
||||
/** What an Agentic schedule still lacks before it can be saved: a computer and a full path. */
|
||||
val EditState.whereComplete: Boolean get() = !agentic || (device.isNotBlank() && cwd.isNotBlank())
|
||||
|
||||
/**
|
||||
* Where a save says the schedule runs -- its type. A new schedule says a computer when it is
|
||||
* Agentic and nothing otherwise (the server's own default is Chat). An edit says only what
|
||||
* the form knows and what differs from what it read: nothing where the schedule could not be
|
||||
* read, nothing for a schedule whose computer, folder, mode and wait are as they were (so its
|
||||
* words can be put right while its computer is not linked), and "the server" only when an
|
||||
* Agentic schedule was made a Chat one.
|
||||
*/
|
||||
fun whereToSend(state: EditState, editing: Boolean): WhereToRun = when {
|
||||
editing && !state.loaded -> WhereToRun.Leave
|
||||
state.agentic -> state.computer.takeUnless { editing && it == state.readWhere } ?: WhereToRun.Leave
|
||||
editing && state.wasAgentic -> WhereToRun.Server
|
||||
else -> WhereToRun.Leave
|
||||
}
|
||||
|
||||
/**
|
||||
* The model a save says, or null for none: an Agentic schedule's, when it is new and one was
|
||||
* chosen, or when it differs from the one read (the empty one is then said too: back to the
|
||||
* folder's usual model). A Chat schedule's model is not this form's to change.
|
||||
*/
|
||||
fun modelToSend(state: EditState, editing: Boolean): String? = when {
|
||||
!state.agentic || (editing && !state.loaded) -> null
|
||||
editing -> state.model.takeIf { it != state.readModel }
|
||||
else -> state.model.ifBlank { null }
|
||||
}
|
||||
|
||||
/**
|
||||
* The watched command a save says, or null for none: an Agentic schedule's when it differs
|
||||
* from the one read (an emptied field is said: watch nothing), a new one's when one was
|
||||
* written -- and "watch nothing" for a schedule made Chat that watched a command, which the
|
||||
* server would otherwise refuse.
|
||||
*/
|
||||
fun watchToSend(state: EditState, editing: Boolean): WatchCommand? = when {
|
||||
editing && !state.loaded -> null
|
||||
state.agentic -> state.watched.takeIf { if (editing) it != state.readWatch else it.command.isNotEmpty() }
|
||||
state.dropsWatch -> WatchCommand("", null)
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** The form's model among the models offered: by its ref alone where the schedule itself said one. */
|
||||
val EditState.modelInfo: SchedulingModel? get() = models.named(model, modelIsRef)
|
||||
|
||||
/** A schedule as the form holds where it runs; what the person changed meanwhile stays changed. */
|
||||
fun EditState.read(s: Schedule): EditState {
|
||||
val on = s.runsOn
|
||||
val known = devices.any { it.id == on?.device }
|
||||
val watch = s.watch?.takeIf { it.kind == "command" }?.let { WatchCommand(it.command.ifBlank { it.target }.trim(), it.timeoutS) } ?: WatchCommand("", null)
|
||||
return copy(
|
||||
wasAgentic = on != null,
|
||||
readWhere = on?.let {
|
||||
WhereToRun.Computer(it.device, it.cwd.trim(), it.mode.ifBlank { "edit" }, it.approvalWaitMinutes?.takeIf { minutes -> minutes > 0 })
|
||||
},
|
||||
readModel = s.modelKey.orEmpty(),
|
||||
readWatch = watch,
|
||||
// Its own computer is in the list also when it is not linked now, so it can stay chosen.
|
||||
devices = if (on == null || known) devices else devices + LinkedDevice(id = on.device, name = on.deviceName),
|
||||
agentic = if (whereTouched) agentic else on != null,
|
||||
device = if (whereTouched || on == null) device else on.device,
|
||||
cwd = if (whereTouched || on == null) cwd else on.cwd,
|
||||
agentMode = if (whereTouched || on == null) agentMode else on.mode.ifBlank { agentMode },
|
||||
wait = if (whereTouched || on == null) wait else on.approvalWaitMinutes?.toString().orEmpty(),
|
||||
// A Chat schedule's own model too: made Agentic, it is shown as the model it keeps.
|
||||
// By its connection where the server says it: the form then ticks the right one of two with one id.
|
||||
model = if (whereTouched) model else s.modelKey.orEmpty(),
|
||||
modelIsRef = if (whereTouched) modelIsRef else !s.modelRef.isNullOrBlank(),
|
||||
watchCommand = if (whereTouched) watchCommand else watch.command,
|
||||
watchTimeout = if (whereTouched) watchTimeout else watch.timeoutS?.toString().orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** The linked computers as the form lists them, keeping a schedule's own that is not among them. */
|
||||
fun EditState.listed(linked: List<LinkedDevice>): EditState {
|
||||
val own = devices.filter { mine -> linked.none { it.id == mine.id } && mine.id == device }
|
||||
val all = linked + own
|
||||
// A new Agentic schedule starts on the first computer that accepts scheduled work.
|
||||
return copy(devices = all, device = device.ifBlank { all.firstOrNull { it.scheduled }?.id.orEmpty() })
|
||||
}
|
||||
|
||||
/**
|
||||
* The `notify` a save sends, or null for none: only to an instance with Reports, and when
|
||||
* [editing] only what the form really knows -- the schedule's own value once it was read, or the
|
||||
@@ -841,11 +1070,19 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
val has = runCatching { getApplication<Application>().api().reports(unread = true) }.isSuccess
|
||||
_state.update { it.copy(reports = has) }
|
||||
}
|
||||
// The type's choices: the computers (Agentic is offered while one accepts scheduled
|
||||
// work) and the models a schedule may run on. Either may be missing on an older server.
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().devices() }.onSuccess { linked -> _state.update { it.listed(linked) } }
|
||||
}
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedulingModels() }.onSuccess { m -> _state.update { it.copy(models = m.models) } }
|
||||
}
|
||||
if (id == null) return
|
||||
viewModelScope.launch {
|
||||
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
|
||||
_state.update {
|
||||
it.copy(
|
||||
it.read(s).copy(
|
||||
words = s.request.ifBlank { s.instruction },
|
||||
// What the person chose while it was read stays chosen.
|
||||
notify = if (it.notifyTouched) it.notify else notifyChoice(s.notify),
|
||||
@@ -867,6 +1104,15 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text, notifyTouched = true) }
|
||||
|
||||
/** A change to the type or one of its fields: the person's, so a schedule read later does not undo it. */
|
||||
fun where(change: (EditState) -> EditState) = _state.update { change(it).copy(whereTouched = true, error = null) }
|
||||
|
||||
/** The chosen computer, asked for a directory (`""`: its places), for the folder picker. */
|
||||
suspend fun directories(path: String): DeviceDirectory {
|
||||
val device = _state.value.device.ifBlank { return DeviceDirectory(code = "device_not_linked") }
|
||||
return getApplication<Application>().api().deviceDirectories(device, path)
|
||||
}
|
||||
|
||||
/** The server reads the words: the title, the instruction, the rule and the next runs. */
|
||||
fun preview() {
|
||||
val words = _state.value.words.trim()
|
||||
@@ -896,6 +1142,9 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
|
||||
editing,
|
||||
notify = notifyToSend(now, editing = editing != null),
|
||||
notifyWhen = now.notifyWhen,
|
||||
where = whereToSend(now, editing = editing != null),
|
||||
model = modelToSend(now, editing = editing != null),
|
||||
watch = watchToSend(now, editing = editing != null),
|
||||
)
|
||||
then(saved.id)
|
||||
} catch (e: Exception) {
|
||||
@@ -923,6 +1172,8 @@ fun ScheduleEditScreen(
|
||||
onSave = { model.save(onSaved) },
|
||||
onNotify = model::notify,
|
||||
onNotifyWhen = model::notifyWhen,
|
||||
onWhere = model::where,
|
||||
directories = model::directories,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -942,6 +1193,8 @@ fun ScheduleEditContent(
|
||||
onSave: () -> Unit = {},
|
||||
onNotify: (String) -> Unit = {},
|
||||
onNotifyWhen: (String) -> Unit = {},
|
||||
onWhere: ((EditState) -> EditState) -> Unit = {},
|
||||
directories: suspend (String) -> DeviceDirectory = { DeviceDirectory() },
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
Scaffold(
|
||||
@@ -951,7 +1204,7 @@ fun ScheduleEditContent(
|
||||
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
|
||||
Button(
|
||||
onClick = onSave,
|
||||
enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed,
|
||||
enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed && state.whereComplete,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||
) { Text(stringResource(R.string.save)) }
|
||||
}
|
||||
@@ -961,6 +1214,10 @@ fun ScheduleEditContent(
|
||||
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
// The type comes first: it decides where the task runs and what else the form asks.
|
||||
// Not until a schedule being edited has been read: a choice made before would be the form's guess.
|
||||
TypeChoice(state, onWhere, ready = !editing || state.loaded)
|
||||
if (state.agentic) OnComputer(state, onWhere, directories)
|
||||
Text(stringResource(R.string.schedule_words_hint), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
|
||||
OutlinedTextField(
|
||||
value = state.words,
|
||||
@@ -990,6 +1247,242 @@ fun ScheduleEditContent(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The type (spec 3.9.0): Chat runs on the server, Agentic on one of the person's computers, each
|
||||
* with one line saying what that means. Agentic cannot be chosen while no computer accepts
|
||||
* scheduled work, and says so; one that is Agentic already stays shown as it is.
|
||||
*/
|
||||
@Composable
|
||||
private fun TypeChoice(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, ready: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
val offered = ready && (state.agenticOffered || state.agentic)
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 12.dp)) {
|
||||
Row(Modifier.padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_type),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
// The schedule is still being read: its type is not known yet, and not to be chosen.
|
||||
// (Not in a preview or a screenshot: an animation that never ends never lets the picture be taken.)
|
||||
if (!ready && !state.loadFailed && !LocalInspectionMode.current) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(16.dp))
|
||||
}
|
||||
ChoiceRow(
|
||||
selected = ready && !state.agentic,
|
||||
enabled = ready,
|
||||
title = stringResource(R.string.schedule_chat),
|
||||
line = stringResource(R.string.schedule_chat_line),
|
||||
onClick = { onWhere { it.copy(agentic = false) } },
|
||||
)
|
||||
ChoiceRow(
|
||||
selected = ready && state.agentic,
|
||||
enabled = offered,
|
||||
title = stringResource(R.string.schedule_agentic),
|
||||
line = stringResource(if (offered || !ready) R.string.schedule_agentic_line else R.string.schedule_agentic_unavailable),
|
||||
onClick = { onWhere { it.copy(agentic = true) } },
|
||||
)
|
||||
if (state.dropsWatch) {
|
||||
Text(
|
||||
stringResource(R.string.schedule_chat_drops_watch),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.warning,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One choice of a few: the radio button keeps its size, the words give. The whole row is the target. */
|
||||
@Composable
|
||||
private fun ChoiceRow(selected: Boolean, title: String, line: String?, onClick: () -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable(
|
||||
enabled = enabled,
|
||||
onClick = onClick,
|
||||
).heightIn(min = 56.dp).padding(start = 4.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(selected = selected, onClick = onClick, enabled = enabled)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = if (enabled) palette.ink else palette.inkFaint)
|
||||
line?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An Agentic schedule's own fields: the computer, the folder there (the picker, or a typed
|
||||
* path), the mode, how long an approval waits, and the model -- the folder's usual one unless
|
||||
* another is chosen.
|
||||
*/
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun OnComputer(state: EditState, onWhere: ((EditState) -> EditState) -> Unit, directories: suspend (String) -> DeviceDirectory) {
|
||||
val palette = LocalPalette.current
|
||||
var browsing by remember { mutableStateOf(false) }
|
||||
var choosingModel by remember { mutableStateOf(false) }
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(vertical = 12.dp)) {
|
||||
FieldLabel(stringResource(R.string.schedule_computer))
|
||||
state.devices.forEach { d ->
|
||||
// A computer that does not accept scheduled work cannot be chosen; the one the
|
||||
// schedule already has stays shown, whatever it says now.
|
||||
val mine = d.id == state.device
|
||||
ChoiceRow(
|
||||
selected = mine,
|
||||
enabled = d.scheduled || mine,
|
||||
title = d.label,
|
||||
line = if (d.scheduled) null else stringResource(R.string.schedule_computer_refuses),
|
||||
onClick = { onWhere { it.copy(device = d.id) } },
|
||||
)
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.schedule_computer_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_folder))
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = state.cwd,
|
||||
onValueChange = { text -> onWhere { it.copy(cwd = text) } },
|
||||
singleLine = true,
|
||||
placeholder = { Text(stringResource(R.string.directory_path)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
IconButton(onClick = { browsing = true }, enabled = state.device.isNotBlank()) {
|
||||
Icon(Icons.Filled.Folder, contentDescription = stringResource(R.string.directory_browse), tint = palette.accent)
|
||||
}
|
||||
}
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_agent_mode))
|
||||
FlowRow(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
// Only the modes the chosen computer allows, and the one the schedule has.
|
||||
modesOffered(state.chosenDevice?.maxMode.orEmpty(), state.agentMode).forEach { value ->
|
||||
FilterChip(
|
||||
selected = state.agentMode == value,
|
||||
onClick = { onWhere { it.copy(agentMode = value) } },
|
||||
label = { Text(agentModeWords(value) ?: value) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.schedule_agent_mode_hint),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_approval_wait))
|
||||
OutlinedTextField(
|
||||
value = state.wait,
|
||||
onValueChange = { text -> onWhere { it.copy(wait = text.filter(Char::isDigit).take(4)) } },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
supportingText = { Text(stringResource(R.string.schedule_approval_wait_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
|
||||
FieldLabel(stringResource(R.string.schedule_watching_command))
|
||||
OutlinedTextField(
|
||||
value = state.watchCommand,
|
||||
onValueChange = { text -> onWhere { it.copy(watchCommand = text.take(1000)) } },
|
||||
singleLine = true,
|
||||
supportingText = { Text(stringResource(R.string.schedule_watch_command_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
if (state.watchCommand.isNotBlank()) {
|
||||
FieldLabel(stringResource(R.string.schedule_watch_timeout))
|
||||
OutlinedTextField(
|
||||
value = state.watchTimeout,
|
||||
onValueChange = { text -> onWhere { it.copy(watchTimeout = text.filter(Char::isDigit).take(3)) } },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
supportingText = { Text(stringResource(R.string.schedule_watch_timeout_hint)) },
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
|
||||
)
|
||||
}
|
||||
|
||||
FieldLabel(stringResource(R.string.model))
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { choosingModel = true }.heightIn(min = 56.dp).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.modelInfo?.titleAmong(state.models)
|
||||
?: state.model.ifBlank { stringResource(R.string.schedule_folder_model) },
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
)
|
||||
Text(stringResource(R.string.schedule_folder_model_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Icon(Icons.Filled.Tune, contentDescription = null, tint = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (browsing) {
|
||||
DirectoryPicker(
|
||||
title = state.chosenDevice?.label ?: stringResource(R.string.schedule_folder),
|
||||
initial = state.cwd,
|
||||
load = directories,
|
||||
onPick = { path ->
|
||||
onWhere { it.copy(cwd = path) }
|
||||
browsing = false
|
||||
},
|
||||
onDismiss = { browsing = false },
|
||||
)
|
||||
}
|
||||
if (choosingModel) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { choosingModel = false },
|
||||
title = { Text(stringResource(R.string.model)) },
|
||||
text = {
|
||||
Column(Modifier.verticalScroll(rememberScrollState())) {
|
||||
// A row of the list is picked by its key; the schedule's own model stays the ref it was read as.
|
||||
val pick: (String, Boolean) -> Unit = { id, isRef ->
|
||||
onWhere { it.copy(model = id, modelIsRef = isRef) }
|
||||
choosingModel = false
|
||||
}
|
||||
ChoiceRow(selected = state.model.isBlank(), title = stringResource(R.string.schedule_folder_model), line = null, onClick = {
|
||||
pick("", false)
|
||||
})
|
||||
// The schedule's own model stays offered where the instance no longer lists it: the server says why on Save.
|
||||
val own = state.model.takeIf { m -> m.isNotBlank() && state.modelInfo == null }
|
||||
own?.let { ChoiceRow(selected = true, title = it, line = null, onClick = { pick(it, state.modelIsRef) }) }
|
||||
// A schedule that says its connection ticks that row or none; one that says only an id, the first with it.
|
||||
val chosen = state.modelInfo?.key
|
||||
state.models.distinctBy { it.key }.forEach { m ->
|
||||
ChoiceRow(selected = chosen == m.key, title = m.titleAmong(state.models), line = null, onClick = { pick(m.key, false) })
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = { choosingModel = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FieldLabel(text: String) {
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = LocalPalette.current.accent,
|
||||
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify when: every run, when the person's own words hold, or never -- each with one line
|
||||
* saying what it does. A report is what tells the person; a run without one is a line in the
|
||||
|
||||
@@ -133,7 +133,7 @@ fun SchedulingModelsContent(state: ModelsState, onBack: () -> Unit = {}, onToggl
|
||||
)
|
||||
}
|
||||
state.error?.let { item { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) } }
|
||||
items(models, key = { it.id }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
items(models.distinctBy { it.key }, key = { it.key }) { m -> ModelRow(m, onToggle = { onToggle(m) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.settings
|
||||
|
||||
import androidx.compose.foundation.border
|
||||
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.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.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.McpServer
|
||||
import eu.llembas.android.api.signInAddress
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.scheduled.ScheduleLogic
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.viewer.openOutside
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** The instance's MCP servers as the page draws them: on their way, refused, or the list. */
|
||||
data class McpState(val servers: List<McpServer> = emptyList(), val loading: Boolean = true, val error: String? = null)
|
||||
|
||||
/**
|
||||
* Settings › MCP servers: the servers whose tools the person's chats may be offered, and how
|
||||
* each is signed in to. One that waits for a sign-in has a button that opens the instance's own
|
||||
* sign-in page **in the browser** -- the sign-in happens there, against the instance, with the
|
||||
* person signed in to the instance by its cookie. The app starts and finishes nothing, and sees,
|
||||
* sends and stores no token of a server; its own token is in no address it opens. The list is
|
||||
* read again whenever the page comes back to the front, which is when the browser was left.
|
||||
*/
|
||||
@Composable
|
||||
fun McpScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var state by remember { mutableStateOf(McpState()) }
|
||||
var reads by remember { mutableIntStateOf(0) }
|
||||
var base by remember { mutableStateOf("") }
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { reads++ }
|
||||
LaunchedEffect(reads) {
|
||||
state = state.copy(loading = true, error = null)
|
||||
state = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
base = api.base
|
||||
McpState(api.mcpServers(), loading = false)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
state.copy(loading = false, error = context.filesSay(e))
|
||||
}
|
||||
}
|
||||
McpContent(
|
||||
state,
|
||||
onBack = onBack,
|
||||
onReload = { reads++ },
|
||||
// Only a page of the instance the app is signed in to is ever opened (signInAddress).
|
||||
onSignIn = { server -> signInAddress(base, server.auth.signinUrl)?.let { openOutside(context, it) } },
|
||||
)
|
||||
}
|
||||
|
||||
/** The words for how a server is signed in to; a state this app does not know is said as the instance says it. */
|
||||
@Composable
|
||||
internal fun mcpState(server: McpServer): String = when (server.auth.state) {
|
||||
"ready" -> stringResource(R.string.mcp_ready)
|
||||
"signed_in" -> stringResource(R.string.mcp_signed_in)
|
||||
"signed_out" -> stringResource(R.string.mcp_signed_out)
|
||||
"needs_signin" -> stringResource(R.string.mcp_needs_signin)
|
||||
else -> server.auth.state
|
||||
}
|
||||
|
||||
/** The page, from [state] alone. Each server is a card: its words stacked, and under them the one button, the card's whole width. */
|
||||
@Composable
|
||||
fun McpContent(state: McpState, onBack: () -> Unit = {}, onReload: () -> Unit = {}, onSignIn: (McpServer) -> 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.mcp_title), maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
|
||||
},
|
||||
actions = { IconButton(onClick = onReload) { Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.reload)) } },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when {
|
||||
state.error != null -> Text(state.error, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
|
||||
|
||||
state.loading && state.servers.isEmpty() -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
|
||||
state.servers.isEmpty() -> Text(
|
||||
stringResource(R.string.mcp_none),
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.align(Alignment.Center).padding(32.dp),
|
||||
)
|
||||
|
||||
else -> LazyColumn(
|
||||
Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item { Text(stringResource(R.string.mcp_intro), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
items(state.servers, key = { it.id }) { server -> McpCard(server, onSignIn) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun McpCard(server: McpServer, onSignIn: (McpServer) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val auth = server.auth
|
||||
Column(
|
||||
Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text(server.label, style = MaterialTheme.typography.titleMedium, color = palette.ink)
|
||||
Text(
|
||||
listOf(mcpState(server), stringResource(R.string.mcp_tools, server.tools.toString())).joinToString(" · "),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (auth.needsSignIn) palette.danger else palette.inkMuted,
|
||||
)
|
||||
// Who the provider says signed in: a stranger's text, drawn as plain text.
|
||||
if (auth.account.isNotBlank()) {
|
||||
Text(stringResource(R.string.mcp_account, auth.account), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
if (!auth.needsSignIn) {
|
||||
ScheduleLogic.moment(auth.expiresAt)?.let {
|
||||
Text(stringResource(R.string.mcp_until, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
if (auth.needsSignIn) {
|
||||
if (auth.signinUrl.isNullOrBlank()) {
|
||||
// One sign-in for everyone, which only an administrator makes: nothing for this person to do.
|
||||
Text(stringResource(R.string.mcp_shared_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
} else {
|
||||
Text(stringResource(R.string.mcp_browser_note), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
Button(
|
||||
onClick = { onSignIn(server) },
|
||||
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 8.dp).heightIn(min = 48.dp),
|
||||
) { Text(stringResource(R.string.mcp_sign_in)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,27 +36,33 @@ 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.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Extension
|
||||
import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
import androidx.compose.material.icons.filled.History
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.MyLocation
|
||||
import androidx.compose.material.icons.filled.Navigation
|
||||
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.Psychology
|
||||
import androidx.compose.material.icons.filled.RecordVoiceOver
|
||||
import androidx.compose.material.icons.filled.Science
|
||||
import androidx.compose.material.icons.filled.ScreenLockPortrait
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material.icons.filled.Star
|
||||
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.Tune
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
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
|
||||
@@ -93,6 +99,9 @@ import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.assist.LembasAssistService
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
@@ -100,6 +109,7 @@ import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import eu.llembas.android.push.Push
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.update.AppVersion
|
||||
import eu.llembas.android.update.ReleaseCheck
|
||||
@@ -122,13 +132,18 @@ import eu.llembas.android.wake.WakeWordService
|
||||
import eu.llembas.android.wake.WakeWords
|
||||
import eu.llembas.android.wake.wakeAttemptWords
|
||||
import eu.llembas.android.wake.wakeTitle
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/** What the settings page does; every action has a do-nothing default for the screenshots. */
|
||||
interface SettingsActions {
|
||||
fun use(instance: Instance) {}
|
||||
fun setDefault(instance: Instance) {}
|
||||
fun add() {}
|
||||
|
||||
/** The instance's MCP servers and their sign-ins. */
|
||||
fun mcpServers() {}
|
||||
fun signOut(instance: Instance) {}
|
||||
fun theme(value: String) {}
|
||||
fun language(value: String) {}
|
||||
@@ -136,6 +151,7 @@ interface SettingsActions {
|
||||
fun notificationSettings() {}
|
||||
fun assistantSettings() {}
|
||||
fun assistantTemporary(on: Boolean) {}
|
||||
fun assistantModel(id: String) {}
|
||||
fun voiceInput(value: String) {}
|
||||
fun assistantListens(on: Boolean) {}
|
||||
fun assistantConversation(on: Boolean) {}
|
||||
@@ -165,6 +181,7 @@ data class WakeTestShown(val running: Boolean = false, val done: Boolean = false
|
||||
data class SettingsState(
|
||||
val instances: List<Instance> = emptyList(),
|
||||
val active: Instance? = null,
|
||||
val defaultInstance: Instance? = null,
|
||||
val prefs: Prefs = Prefs(),
|
||||
val hasDistributor: Boolean = false,
|
||||
val pushNote: String? = null,
|
||||
@@ -195,15 +212,18 @@ data class SettingsState(
|
||||
val notificationsBuild: Boolean = false,
|
||||
/** The navigation apps installed: NavApp ids. */
|
||||
val navApps: List<String> = emptyList(),
|
||||
/** The instance's models, for Settings › Assistant › Assistant model; empty until (or unless) it said them. */
|
||||
val assistantModels: List<ModelInfo> = emptyList(),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit, onMcp: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val store = context.lembas.instances
|
||||
val scope = rememberCoroutineScope()
|
||||
val instances by store.instances.collectAsState(initial = emptyList())
|
||||
val active by store.active.collectAsState(initial = null)
|
||||
val defaultInstance by store.defaultInstance.collectAsState(initial = null)
|
||||
val prefs by store.prefs.collectAsState(initial = Prefs())
|
||||
val wakeState by WakeStatus.state.collectAsState()
|
||||
val assistantConnected by AssistLink.connected.collectAsState()
|
||||
@@ -218,6 +238,19 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
}
|
||||
clock = SystemClock.elapsedRealtime()
|
||||
}
|
||||
// The default instance's models, for the assistant's: asked for each time Settings opens on an instance.
|
||||
val assistInstance = defaultInstance ?: active
|
||||
var models by remember { mutableStateOf(emptyList<ModelInfo>()) }
|
||||
LaunchedEffect(assistInstance?.id) {
|
||||
models = try {
|
||||
assistInstance?.let { store.clientFor(it).models() }.orEmpty()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// Not reachable now: the row keeps what was chosen and offers the instance's default.
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
var pushNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateNote by remember { mutableStateOf<String?>(null) }
|
||||
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
|
||||
@@ -235,16 +268,28 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
val actions = remember {
|
||||
object : SettingsActions {
|
||||
override fun use(instance: Instance) {
|
||||
scope.launch { store.use(instance.id) }
|
||||
scope.launch {
|
||||
store.use(instance.id)
|
||||
// Copies of one instance's files are not kept around while another is in use.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
override fun setDefault(instance: Instance) {
|
||||
scope.launch { store.setDefault(instance.id) }
|
||||
}
|
||||
|
||||
override fun add() = onAddInstance()
|
||||
|
||||
override fun mcpServers() = onMcp()
|
||||
|
||||
override fun signOut(instance: Instance) {
|
||||
scope.launch {
|
||||
Push.disable(context, instance)
|
||||
runCatching { store.clientFor(instance).signOut() }
|
||||
store.remove(instance.id)
|
||||
// The copies of the account's files this phone held for a viewer or another app go with it.
|
||||
FileCache.clear(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,6 +324,13 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } }
|
||||
}
|
||||
|
||||
override fun assistantModel(id: String) {
|
||||
scope.launch {
|
||||
val target = (store.default() ?: store.current())?.id
|
||||
store.savePrefs { p -> p.withInstance(target) { it.copy(assistantModel = id) } }
|
||||
}
|
||||
}
|
||||
|
||||
override fun voiceInput(value: String) {
|
||||
scope.launch { store.savePrefs { it.copy(voiceInput = value) } }
|
||||
}
|
||||
@@ -400,6 +452,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
SettingsState(
|
||||
instances = instances,
|
||||
active = active,
|
||||
defaultInstance = defaultInstance,
|
||||
prefs = prefs,
|
||||
hasDistributor = distributors.isNotEmpty(),
|
||||
pushNote = pushNote,
|
||||
@@ -420,6 +473,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
notificationAccess = NotificationAccess.granted(context),
|
||||
notificationsBuild = NotificationAccess.AVAILABLE,
|
||||
navApps = remember { NavApp.installedApps(context).map { it.id } },
|
||||
assistantModels = models,
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
@@ -444,6 +498,15 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
})
|
||||
}
|
||||
}
|
||||
var choosingModel by remember { mutableStateOf(false) }
|
||||
if (choosingModel) {
|
||||
ModalBottomSheet(onDismissRequest = { choosingModel = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
AssistantModelChoices(state, onPick = {
|
||||
choosingModel = false
|
||||
actions.assistantModel(it)
|
||||
})
|
||||
}
|
||||
}
|
||||
if (choosingLanguage) {
|
||||
ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
|
||||
LanguageChoices(state.prefs, onPick = {
|
||||
@@ -470,21 +533,41 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
state.instances.forEachIndexed { i, instance ->
|
||||
if (i > 0) Rule()
|
||||
val inUse = instance.id == state.active?.id
|
||||
val isDefault = instance.id == (state.defaultInstance?.id ?: state.instances.firstOrNull()?.id)
|
||||
var menuOpen by remember(instance.id) { mutableStateOf(false) }
|
||||
Row(
|
||||
Modifier.fillMaxWidth().clickable { actions.use(instance) }.heightIn(min = 72.dp).padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { actions.use(instance) }
|
||||
.heightIn(min = 72.dp)
|
||||
.padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 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,
|
||||
)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
instance.name.ifBlank {
|
||||
instance.base
|
||||
},
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (isDefault) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Surface(color = palette.accentSoft, shape = RoundedCornerShape(8.dp)) {
|
||||
Text(
|
||||
stringResource(R.string.instance_default),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
instance.email,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
@@ -501,14 +584,42 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
)
|
||||
}
|
||||
if (inUse) {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.Filled.CheckCircle, contentDescription = stringResource(R.string.instance_in_use), tint = palette.accent)
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { menuOpen = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more), tint = palette.inkMuted)
|
||||
}
|
||||
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
|
||||
if (!isDefault) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.instance_set_default)) },
|
||||
leadingIcon = { Icon(Icons.Filled.Star, contentDescription = null) },
|
||||
onClick = {
|
||||
menuOpen = false
|
||||
actions.setDefault(instance)
|
||||
},
|
||||
)
|
||||
}
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.sign_out), color = palette.danger) },
|
||||
leadingIcon = { Icon(Icons.AutoMirrored.Filled.Logout, contentDescription = null, tint = palette.danger) },
|
||||
onClick = {
|
||||
menuOpen = false
|
||||
actions.signOut(instance)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.instances.isNotEmpty()) Rule()
|
||||
SettingRow(Icons.Filled.Add, stringResource(R.string.add_instance), onClick = actions::add)
|
||||
state.active?.let { current ->
|
||||
Rule()
|
||||
// The MCP servers of the instance in use, and which of them wait for a sign-in.
|
||||
SettingRow(Icons.Filled.Extension, stringResource(R.string.mcp_title), onClick = actions::mcpServers)
|
||||
Rule()
|
||||
SettingRow(Icons.AutoMirrored.Filled.Logout, stringResource(R.string.sign_out), tint = palette.danger, onClick = {
|
||||
actions.signOut(current)
|
||||
@@ -567,6 +678,15 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
onClick = actions::assistantSettings,
|
||||
)
|
||||
Rule()
|
||||
// The model the assistant's new chats start on: the instance's default may be
|
||||
// a large one, and a spoken question wants a quick answer.
|
||||
SettingRow(
|
||||
Icons.Filled.Psychology,
|
||||
stringResource(R.string.assistant_model),
|
||||
subtitle = assistantModelLabel(state),
|
||||
onClick = { choosingModel = true },
|
||||
)
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.Timer,
|
||||
stringResource(R.string.assistant_temporary),
|
||||
@@ -577,6 +697,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
SettingRow(
|
||||
Icons.Filled.Mic,
|
||||
stringResource(R.string.assistant_listens),
|
||||
badge = stringResource(R.string.experimental),
|
||||
onClick = { actions.assistantListens(!state.prefs.assistantListens) },
|
||||
trailing = { Switch(checked = state.prefs.assistantListens, onCheckedChange = actions::assistantListens) },
|
||||
)
|
||||
@@ -592,6 +713,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
Icons.Filled.Forum,
|
||||
stringResource(R.string.assistant_conversation),
|
||||
subtitle = stringResource(R.string.assistant_conversation_line),
|
||||
badge = stringResource(R.string.experimental),
|
||||
enabled = state.prefs.readAloudSpoken,
|
||||
onClick = { actions.assistantConversation(!state.prefs.assistantConversation) },
|
||||
trailing = {
|
||||
@@ -603,6 +725,13 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
},
|
||||
)
|
||||
}
|
||||
// Said plainly: which parts of the voice assistant are not to be relied on yet.
|
||||
Text(
|
||||
stringResource(R.string.assistant_voice_experimental_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp),
|
||||
)
|
||||
Text(
|
||||
stringResource(R.string.assistant_samsung),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -706,11 +835,15 @@ enum class WakeChoice { Greeting, Name, Sensitivity }
|
||||
internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onChoose: (WakeChoice) -> Unit) {
|
||||
val palette = LocalPalette.current
|
||||
val on = state.prefs.wakeWord && state.wakeAvailable
|
||||
Group(stringResource(R.string.wake_word)) {
|
||||
Group(stringResource(R.string.wake_word), badge = stringResource(R.string.experimental)) {
|
||||
SettingRow(
|
||||
Icons.Filled.Hearing,
|
||||
stringResource(R.string.wake_word_listen),
|
||||
subtitle = stringResource(if (state.wakeAvailable) R.string.wake_word_line else R.string.wake_word_unavailable),
|
||||
subtitle = if (state.wakeAvailable) {
|
||||
stringResource(R.string.wake_word_line) + "\n" + stringResource(R.string.wake_experimental_line)
|
||||
} else {
|
||||
stringResource(R.string.wake_word_unavailable)
|
||||
},
|
||||
enabled = state.wakeAvailable,
|
||||
onClick = { actions.wakeWord(!on) },
|
||||
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
|
||||
@@ -924,21 +1057,38 @@ internal fun NotificationSummaryGroup(state: SettingsState, actions: SettingsAct
|
||||
}
|
||||
}
|
||||
|
||||
/** A group's header and its rows; [badge] is a label beside the title ("Experimental"). */
|
||||
@Composable
|
||||
private fun Group(title: String, content: @Composable () -> Unit) {
|
||||
private fun Group(title: String, badge: String? = null, 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),
|
||||
)
|
||||
// The title gives when the two do not fit; the label keeps its size.
|
||||
Row(Modifier.padding(start = 16.dp, end = 16.dp, top = 24.dp, bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = palette.accent,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
)
|
||||
if (badge != null) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Badge(badge)
|
||||
}
|
||||
}
|
||||
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
|
||||
Column { content() }
|
||||
}
|
||||
}
|
||||
|
||||
/** A small label: "Experimental". */
|
||||
@Composable
|
||||
private fun Badge(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Surface(shape = RoundedCornerShape(8.dp), color = palette.accentSoft, contentColor = palette.accent) {
|
||||
Text(text, style = MaterialTheme.typography.labelSmall, maxLines = 1, modifier = Modifier.padding(horizontal = 8.dp, vertical = 2.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Rule() = HorizontalDivider(color = LocalPalette.current.border, modifier = Modifier.padding(start = 56.dp))
|
||||
|
||||
@@ -955,6 +1105,7 @@ private fun SettingRow(
|
||||
tint: Color? = null,
|
||||
enabled: Boolean = true,
|
||||
showIcon: Boolean = true,
|
||||
badge: String? = null,
|
||||
trailing: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val palette = LocalPalette.current
|
||||
@@ -973,6 +1124,8 @@ private fun SettingRow(
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = ink)
|
||||
// On a line of its own, under the title: nothing has to fit beside words that wrap.
|
||||
badge?.let { Box(Modifier.padding(top = 2.dp, bottom = 2.dp)) { Badge(it) } }
|
||||
subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
|
||||
}
|
||||
if (trailing != null) {
|
||||
@@ -1109,6 +1262,43 @@ fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> U
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the assistant's model row says: the chosen model by its name, or "Instance default" --
|
||||
* also for a model the instance no longer has, since that is what the assistant then uses.
|
||||
*/
|
||||
@Composable
|
||||
private fun assistantModelLabel(state: SettingsState): String {
|
||||
val target = (state.defaultInstance ?: state.active)?.id
|
||||
val chosen = state.prefs.forInstance(target).assistantModel
|
||||
val model = state.assistantModels.named(chosen)
|
||||
// While the list is not read yet, or could not be: the choice as it was saved.
|
||||
return when {
|
||||
chosen.isBlank() -> stringResource(R.string.assistant_model_default)
|
||||
model != null -> model.titleAmong(state.assistantModels)
|
||||
state.assistantModels.isEmpty() -> chosen
|
||||
else -> stringResource(R.string.assistant_model_default)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings › Assistant › Assistant model, as a sheet: "Instance default" (the account's default
|
||||
* model, as in a new chat in the app), then the instance's models. The choice is the model a new
|
||||
* assistant chat starts on, from every way in -- the sheet, the wake word, Share.
|
||||
*/
|
||||
@Composable
|
||||
fun AssistantModelChoices(state: SettingsState, onPick: (String) -> Unit) {
|
||||
// A choice saved before models had refs is an id: it still finds its model.
|
||||
val target = (state.defaultInstance ?: state.active)?.id
|
||||
val chosen = state.assistantModels.named(state.prefs.forInstance(target).assistantModel)?.key.orEmpty()
|
||||
val choices = listOf(
|
||||
Choice(INSTANCE_DEFAULT, stringResource(R.string.assistant_model_default), stringResource(R.string.assistant_model_default_line), chosen.isEmpty()),
|
||||
) + state.assistantModels.distinctBy { it.key }.map { Choice(it.key, it.titleAmong(state.assistantModels), null, it.key == chosen) }
|
||||
ChoiceList(stringResource(R.string.assistant_model), choices) { id -> onPick(if (id == INSTANCE_DEFAULT) "" else id) }
|
||||
}
|
||||
|
||||
/** The list's key for "Instance default": a key cannot be empty, and no model is named so. */
|
||||
private const val INSTANCE_DEFAULT = " default"
|
||||
|
||||
private data class Choice(val id: String, val title: String, val subtitle: String?, val chosen: Boolean)
|
||||
|
||||
/** A sheet's list of choices: a title, then rows of words that give and a radio button that keeps its size. */
|
||||
|
||||
@@ -3,27 +3,35 @@
|
||||
package eu.llembas.android.ui.signin
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import androidx.browser.customtabs.CustomTabsIntent
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.safeDrawingPadding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.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.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -41,18 +49,28 @@ import androidx.lifecycle.AndroidViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.Address
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Discovery
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.ServerFit
|
||||
import eu.llembas.android.api.address
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.api.normaliseBase
|
||||
import eu.llembas.android.api.minClient
|
||||
import eu.llembas.android.api.olderThan
|
||||
import eu.llembas.android.api.onOrigin
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import java.io.IOException
|
||||
|
||||
/** Where the sign-in is. The token arrives once, by device code, as `lembas login` gets it. */
|
||||
sealed interface SignInState {
|
||||
@@ -63,28 +81,84 @@ sealed interface SignInState {
|
||||
data object Done : SignInState
|
||||
}
|
||||
|
||||
/** The sentence for a server this app will not work with, or null when it fits. */
|
||||
/**
|
||||
* The sentence for a server this app will not work with, or null when it fits. Each reason has
|
||||
* its own, and each says which side is the old one: another service is not "an older LLeMbas".
|
||||
*/
|
||||
fun refusal(fit: ServerFit): Int? = when (fit) {
|
||||
ServerFit.FITS -> null
|
||||
ServerFit.NOT_LEMBAS, ServerFit.TOO_OLD -> R.string.signin_too_old
|
||||
ServerFit.NOT_LEMBAS -> R.string.signin_not_lembas
|
||||
ServerFit.TOO_OLD -> R.string.signin_too_old
|
||||
ServerFit.TOO_NEW -> R.string.signin_too_new
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the instance [found] describes asks for a newer app than [version]: the version it
|
||||
* needs, or null. Asked only of a LLeMbas instance -- what another service says is not a rule.
|
||||
*/
|
||||
fun newerAppNeeded(found: Discovery, version: String): String? = found.minClient()?.takeIf { found.service == "lembas" && olderThan(version, it) }
|
||||
|
||||
/**
|
||||
* Why this app will not work with the instance [found] describes, in words, or null when it
|
||||
* will. An instance that names an oldest version for this app, above [version], says so with
|
||||
* both versions -- "update the app" -- before anything else is asked of it.
|
||||
*/
|
||||
fun Context.unfit(found: Discovery, version: String = BuildConfig.VERSION_NAME): String? {
|
||||
newerAppNeeded(found, version)?.let { needed -> return getString(R.string.signin_app_too_old, needed, version) }
|
||||
return refusal(fit(found))?.let { getString(it) }
|
||||
}
|
||||
|
||||
/** The sentence for an address that cannot be used as it was typed, or null for one that can (or for none yet). */
|
||||
fun refusal(read: Address): Int? = when (read) {
|
||||
is Address.Base, Address.Empty -> null
|
||||
Address.NeedsHttps -> R.string.address_needs_https
|
||||
Address.NotHttp, Address.Unreadable -> R.string.address_unreadable
|
||||
}
|
||||
|
||||
/**
|
||||
* The sentence a poll's `error` ends the sign-in with, or null while it goes on (still waiting,
|
||||
* or asked to wait longer). Each end by its real reason: only an expired code is "expired".
|
||||
*/
|
||||
fun pollEnd(error: String?): Int? = when (error) {
|
||||
"authorization_pending", "slow_down" -> null
|
||||
"access_denied" -> R.string.signin_denied
|
||||
"expired_token" -> R.string.signin_expired
|
||||
else -> R.string.signin_failed
|
||||
}
|
||||
|
||||
class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
private val _state = MutableStateFlow<SignInState>(SignInState.Address)
|
||||
val state = _state.asStateFlow()
|
||||
private var polling: Job? = null
|
||||
|
||||
fun start(typed: String) {
|
||||
// The address is read before anything is asked: what is wrong with it is said at this step.
|
||||
val read = address(typed)
|
||||
val base = (read as? Address.Base)?.url
|
||||
if (base == null) {
|
||||
refusal(read)?.let { said ->
|
||||
polling?.cancel()
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
|
||||
}
|
||||
return
|
||||
}
|
||||
polling?.cancel()
|
||||
polling = viewModelScope.launch {
|
||||
_state.value = SignInState.Finding
|
||||
val doorstep = Doorstep()
|
||||
try {
|
||||
val base = normaliseBase(typed)
|
||||
val found = doorstep.discover(base)
|
||||
refusal(fit(found))?.let { said ->
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(said))
|
||||
getApplication<Application>().unfit(found)?.let { said ->
|
||||
_state.value = SignInState.Failed(said)
|
||||
return@launch
|
||||
}
|
||||
// The sign-in goes to the address that was typed and to no other host: where the
|
||||
// document names its doors elsewhere (a proxy that does not pass the address on),
|
||||
// that is said, rather than a code asked of a host the person never named.
|
||||
val doors = found.login.device
|
||||
if (!onOrigin(base, doors.code) || !onOrigin(base, doors.token)) {
|
||||
val named = doors.code.ifBlank { found.baseUrl }
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_other_origin, named))
|
||||
return@launch
|
||||
}
|
||||
val device = getApplication<Application>().getString(R.string.device_name)
|
||||
@@ -92,14 +166,34 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
_state.value = SignInState.Code(code.userCode, code.verificationUriComplete.ifEmpty { code.verificationUri })
|
||||
var interval = code.interval.coerceAtLeast(2) * 1000L
|
||||
val until = System.currentTimeMillis() + code.expiresIn * 1000L
|
||||
// What last went wrong with a poll, if the code runs out with nothing better to say.
|
||||
var trouble: Exception? = null
|
||||
while (System.currentTimeMillis() < until) {
|
||||
delay(interval)
|
||||
val answer = doorstep.deviceToken(found.login.device.token, code.deviceCode)
|
||||
val answer = try {
|
||||
doorstep.deviceToken(found.login.device.token, code.deviceCode).also { trouble = null }
|
||||
} catch (e: ApiException) {
|
||||
// "Too many requests" is asked again, later; a server in trouble (5xx) may
|
||||
// be back before the code runs out. Any other answer ends the sign-in.
|
||||
if (e.status == 429) {
|
||||
interval = maxOf(interval + 5000L, (e.retryAfter ?: 0L) * 1000L)
|
||||
} else if (e.status < 500) {
|
||||
throw e
|
||||
}
|
||||
trouble = e
|
||||
continue
|
||||
} catch (e: IOException) {
|
||||
// The phone was away for a moment (the browser came to the front, the
|
||||
// network changed): the approval may still come, so the next poll asks.
|
||||
trouble = e
|
||||
continue
|
||||
}
|
||||
when {
|
||||
answer.accessToken != null -> {
|
||||
val account = answer.account
|
||||
getApplication<Application>().lembas.instances.add(
|
||||
base = found.baseUrl.ifEmpty { base }.trimEnd('/'),
|
||||
base = base,
|
||||
said = found.baseUrl,
|
||||
name = found.name,
|
||||
email = account?.email.orEmpty(),
|
||||
token = answer.accessToken,
|
||||
@@ -110,20 +204,19 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
|
||||
answer.error == "slow_down" -> interval += 5000L
|
||||
|
||||
answer.error == "authorization_pending" -> Unit
|
||||
|
||||
answer.error == "access_denied" -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_denied))
|
||||
return@launch
|
||||
}
|
||||
|
||||
else -> {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
else -> pollEnd(answer.error)?.let { said ->
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(said, answer.error.orEmpty()))
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
_state.value = SignInState.Failed(getApplication<Application>().getString(R.string.signin_expired))
|
||||
val last = trouble
|
||||
_state.value = SignInState.Failed(
|
||||
if (last != null) getApplication<Application>().explain(last) else getApplication<Application>().getString(R.string.signin_expired),
|
||||
)
|
||||
} catch (e: CancellationException) {
|
||||
// Given up (Cancel, or a new start): not a failure, and nothing to say.
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
_state.value = SignInState.Failed(getApplication<Application>().explain(e))
|
||||
}
|
||||
@@ -134,16 +227,25 @@ class SignInViewModel(app: Application) : AndroidViewModel(app) {
|
||||
polling?.cancel()
|
||||
_state.value = SignInState.Address
|
||||
}
|
||||
|
||||
/** A sign-in that was finished the last time this page was up starts from the address again. */
|
||||
fun fresh() {
|
||||
if (_state.value == SignInState.Done) _state.value = SignInState.Address
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel()) {
|
||||
fun SignInScreen(onDone: () -> Unit = {}, onCancel: (() -> Unit)? = null, model: SignInViewModel = viewModel()) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(state) { if (state == SignInState.Done) onDone() }
|
||||
LaunchedEffect(Unit) { model.fresh() }
|
||||
var address by rememberSaveable { mutableStateOf("") }
|
||||
val context = LocalContext.current
|
||||
val knownBases by context.lembas.instances.instances.collectAsState(initial = emptyList())
|
||||
val distinctBases = knownBases.map { it.base }.distinct()
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().padding(24.dp),
|
||||
// It scrolls: a long sentence about a certificate, large type and the keyboard up must not push Continue out of reach.
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().imePadding().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
@@ -166,24 +268,98 @@ fun SignInScreen(onDone: () -> Unit = {}, model: SignInViewModel = viewModel())
|
||||
keyboardActions = KeyboardActions(onGo = { if (address.isNotBlank()) model.start(address) }),
|
||||
modifier = Modifier.fillMaxWidth().widthIn(max = 420.dp),
|
||||
)
|
||||
if (distinctBases.isNotEmpty() && onCancel != null) {
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = 420.dp).horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
distinctBases.forEach { base ->
|
||||
OutlinedButton(onClick = { address = base }) {
|
||||
Text(base.removePrefix("https://").removePrefix("http://"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s is SignInState.Failed) {
|
||||
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
|
||||
}
|
||||
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
|
||||
Text(stringResource(R.string.signin_continue))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (onCancel != null) {
|
||||
TextButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
Button(onClick = { model.start(address) }, enabled = address.isNotBlank()) {
|
||||
Text(stringResource(R.string.signin_continue))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
|
||||
|
||||
is SignInState.Code -> {
|
||||
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
|
||||
Text(s.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
|
||||
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(s.verify)) }) {
|
||||
Text(stringResource(R.string.signin_open_browser))
|
||||
is SignInState.Code -> CodeStep(s, onCancel = { model.reset() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The code to approve in the browser, and the way there. Laid out by the column it is put in. */
|
||||
@Composable
|
||||
private fun CodeStep(code: SignInState.Code, onCancel: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
Text(stringResource(R.string.signin_code_intro), modifier = Modifier.widthIn(max = 420.dp))
|
||||
Text(code.userCode, fontFamily = FontFamily.Monospace, fontSize = 32.sp, style = MaterialTheme.typography.headlineLarge)
|
||||
Button(onClick = { CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(code.verify)) }) {
|
||||
Text(stringResource(R.string.signin_open_browser))
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
OutlinedButton(onClick = onCancel) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance signed this phone out (it refused the token: revoked there, or expired). Shown
|
||||
* over the instance's pages, which stay as they were underneath -- what was being written is
|
||||
* still there after the sign-in. One step back in: the address is known, so "Sign in again"
|
||||
* goes straight to the code. The other instances stay a tap away, and this one can be removed.
|
||||
*/
|
||||
@Composable
|
||||
fun SignedOutScreen(
|
||||
instance: Instance,
|
||||
others: List<Instance>,
|
||||
onUse: (Instance) -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
model: SignInViewModel = viewModel(key = "signed-out:" + instance.id),
|
||||
) {
|
||||
val state by model.state.collectAsStateWithLifecycle()
|
||||
LaunchedEffect(Unit) { model.fresh() }
|
||||
Surface(modifier = Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
// It scrolls: several other instances, large type or a small screen must not push a button out of reach.
|
||||
modifier = Modifier.fillMaxSize().safeDrawingPadding().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.headlineMedium)
|
||||
Text(
|
||||
stringResource(R.string.signed_out, instance.name.ifBlank { instance.base }),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.widthIn(max = 420.dp),
|
||||
)
|
||||
when (val s = state) {
|
||||
SignInState.Address, is SignInState.Failed -> {
|
||||
if (s is SignInState.Failed) {
|
||||
Text(s.message, color = MaterialTheme.colorScheme.error, modifier = Modifier.widthIn(max = 420.dp))
|
||||
}
|
||||
Button(onClick = { model.start(instance.base) }) { Text(stringResource(R.string.signed_out_again)) }
|
||||
others.forEach { other ->
|
||||
OutlinedButton(onClick = { onUse(other) }) {
|
||||
Text(stringResource(R.string.signed_out_use, other.name.ifBlank { other.base }))
|
||||
}
|
||||
}
|
||||
TextButton(onClick = onRemove) { Text(stringResource(R.string.signed_out_remove)) }
|
||||
}
|
||||
CircularProgressIndicator()
|
||||
OutlinedButton(onClick = { model.reset() }) { Text(stringResource(R.string.cancel)) }
|
||||
|
||||
SignInState.Finding, SignInState.Done -> CircularProgressIndicator()
|
||||
|
||||
is SignInState.Code -> CodeStep(s, onCancel = { model.reset() })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12. Do not edit.
|
||||
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19. Do not edit.
|
||||
package eu.llembas.android.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@@ -0,0 +1,394 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.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.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Pause
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.FilledIconButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
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.clipToBounds
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ArchiveListing
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import java.util.Locale
|
||||
|
||||
// What the viewer draws for each kind of file, each from its state alone (the screenshot tests
|
||||
// draw these). Everything a file holds is drawn as text or as pixels the app decoded itself:
|
||||
// nothing here interprets a file -- no HTML, no script, no WebView.
|
||||
|
||||
/** What the details page can do; nothing by default, for the screenshot tests. */
|
||||
interface FileActions {
|
||||
fun download() {}
|
||||
|
||||
fun openWith() {}
|
||||
|
||||
fun share() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file there is nothing to draw of (an archive, a 3D model, a binary, or one a viewer could
|
||||
* not show): what it is, [note] saying why it is not shown, and the three ways out. The
|
||||
* buttons stack: their words are of unknown length in nine languages.
|
||||
*/
|
||||
@Composable
|
||||
fun DetailsBody(name: String, type: String, size: Long, note: String?, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
Column(
|
||||
Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.size(56.dp))
|
||||
Text(name, style = MaterialTheme.typography.titleMedium, textAlign = TextAlign.Center)
|
||||
Column(Modifier.fillMaxWidth().border(1.dp, palette.border, RoundedCornerShape(16.dp)).padding(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
Fact(stringResource(R.string.files_type), type)
|
||||
Fact(stringResource(R.string.files_size), Formatter.formatShortFileSize(context, size))
|
||||
}
|
||||
note?.takeIf { it.isNotBlank() }?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, textAlign = TextAlign.Center) }
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.download)) }
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.files_open_with)) }
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text(stringResource(R.string.report_share)) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What an archive holds, as the instance lists it: every name is the archive's own text and is
|
||||
* drawn as text; nothing is unpacked, here or there. How many, the names with their sizes (a
|
||||
* name wraps, its size keeps its width), a line when there are more than are listed, and the
|
||||
* three ways out.
|
||||
*/
|
||||
@Composable
|
||||
fun ArchiveBody(archive: ArchiveListing, actions: FileActions) {
|
||||
val palette = LocalPalette.current
|
||||
val context = LocalContext.current
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp)) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_entries, (archive.total ?: archive.entries.size).toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(bottom = 8.dp),
|
||||
)
|
||||
}
|
||||
itemsIndexed(archive.entries) { _, entry ->
|
||||
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp).padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
if (entry.dir) Icons.Filled.Folder else Icons.AutoMirrored.Filled.InsertDriveFile,
|
||||
contentDescription = null,
|
||||
tint = palette.inkFaint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(entry.name, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
entry.size?.takeIf { !entry.dir }?.let {
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(Formatter.formatShortFileSize(context, it), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (archive.truncated) {
|
||||
item {
|
||||
Text(
|
||||
stringResource(R.string.archive_cut, archive.entries.size.toString()),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
item {
|
||||
Column(Modifier.fillMaxWidth().padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(onClick = actions::download, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.download))
|
||||
}
|
||||
OutlinedButton(onClick = actions::openWith, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.files_open_with))
|
||||
}
|
||||
OutlinedButton(onClick = actions::share, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||
Text(stringResource(R.string.report_share))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A label and its value on one line: the label keeps its width, the value takes the rest and wraps. */
|
||||
@Composable
|
||||
private fun Fact(label: String, value: String) {
|
||||
val palette = LocalPalette.current
|
||||
Row(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, modifier = Modifier.width(96.dp))
|
||||
Text(value, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
/** The width every column of a table has: fixed, so a row's cells line up whatever they hold. */
|
||||
private val COLUMN = 148.dp
|
||||
|
||||
/**
|
||||
* A CSV or TSV file as a grid: every cell one line in a column of one width, the first row as
|
||||
* the heading, the whole grid scrolling sideways as one and down as a list. Cells are text.
|
||||
*/
|
||||
@Composable
|
||||
fun TableBody(table: Table) {
|
||||
val palette = LocalPalette.current
|
||||
val sideways = rememberScrollState()
|
||||
val style = TextStyle(fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
if (table.cut) Note(stringResource(R.string.table_cut))
|
||||
Box(Modifier.fillMaxSize().horizontalScroll(sideways)) {
|
||||
LazyColumn(Modifier.width(COLUMN * table.columns.coerceAtLeast(1))) {
|
||||
itemsIndexed(table.rows) { i, row ->
|
||||
Row(Modifier.background(if (i == 0) palette.bgSunken else palette.bg)) {
|
||||
for (c in 0 until table.columns.coerceAtLeast(1)) {
|
||||
Text(
|
||||
row.getOrElse(c) { "" },
|
||||
style = if (i == 0) style.copy(fontWeight = FontWeight.SemiBold) else style,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.width(COLUMN).border(0.5.dp, palette.border).padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A quiet line above a body, saying what is not shown. */
|
||||
@Composable
|
||||
internal fun Note(text: String) {
|
||||
val palette = LocalPalette.current
|
||||
Text(
|
||||
text,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** A notebook, read-only: each cell's source as text, and under it the plain text it printed. */
|
||||
@Composable
|
||||
fun NotebookBody(notebook: Notebook) {
|
||||
val palette = LocalPalette.current
|
||||
val mono = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
|
||||
if (notebook.cells.isEmpty()) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.notebook_empty), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
return
|
||||
}
|
||||
LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
itemsIndexed(notebook.cells) { _, cell ->
|
||||
Column(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
if (cell.count != null) "${cell.kind} [${cell.count}]" else cell.kind,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(bottom = 4.dp),
|
||||
)
|
||||
val code = cell.kind == "code"
|
||||
Text(
|
||||
cell.source.ifEmpty { " " },
|
||||
style = if (code) mono else MaterialTheme.typography.bodyMedium.copy(color = palette.ink),
|
||||
// Code sits on the code's ground; a cell of prose is prose on the page.
|
||||
modifier = Modifier.fillMaxWidth().then(
|
||||
if (code) Modifier.background(palette.codeBg, RoundedCornerShape(8.dp)).padding(10.dp) else Modifier,
|
||||
),
|
||||
)
|
||||
if (cell.output.isNotEmpty()) {
|
||||
Text(cell.output, style = mono.copy(color = palette.inkMuted), modifier = Modifier.fillMaxWidth().padding(start = 10.dp, top = 6.dp))
|
||||
}
|
||||
if (cell.cut) Text(stringResource(R.string.notebook_cell_cut), style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
|
||||
}
|
||||
}
|
||||
if (notebook.more > 0) {
|
||||
item {
|
||||
Text(stringResource(R.string.notebook_more, notebook.more.toString()), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How far a picture zoomed to [scale] may be moved inside a view of [size]: never past its own edge. */
|
||||
fun clampPan(offset: Offset, scale: Float, size: IntSize): Offset {
|
||||
val x = size.width * (scale - 1f) / 2f
|
||||
val y = size.height * (scale - 1f) / 2f
|
||||
return Offset(offset.x.coerceIn(-x, x), offset.y.coerceIn(-y, y))
|
||||
}
|
||||
|
||||
const val ZOOM_MAX = 8f
|
||||
|
||||
/** A picture, whole: two fingers zoom and move it, a double tap zooms in and back. */
|
||||
@Composable
|
||||
fun ZoomableImage(bitmap: ImageBitmap, description: String) {
|
||||
val palette = LocalPalette.current
|
||||
var scale by remember(bitmap) { mutableFloatStateOf(1f) }
|
||||
var offset by remember(bitmap) { mutableStateOf(Offset.Zero) }
|
||||
var size by remember { mutableStateOf(IntSize.Zero) }
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxSize()
|
||||
.background(palette.bgSunken)
|
||||
.clipToBounds()
|
||||
.onSizeChanged { size = it }
|
||||
.pointerInput(bitmap) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, ZOOM_MAX)
|
||||
offset = clampPan(offset + pan, scale, size)
|
||||
}
|
||||
}
|
||||
.pointerInput(bitmap) {
|
||||
detectTapGestures(
|
||||
onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 3f
|
||||
offset = Offset.Zero
|
||||
},
|
||||
)
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Image(
|
||||
bitmap,
|
||||
contentDescription = description,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
translationX = offset.x
|
||||
translationY = offset.y
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player shows: whether it can play yet, is playing, where it is and how long the file is. */
|
||||
data class PlayerUi(val ready: Boolean = false, val playing: Boolean = false, val positionMs: Int = 0, val durationMs: Int = 0)
|
||||
|
||||
/** `m:ss`, or `h:mm:ss` from an hour on: a time read off a player, the same in every language. */
|
||||
fun playTime(ms: Int): String {
|
||||
val all = (ms.coerceAtLeast(0) / 1000)
|
||||
val h = all / 3600
|
||||
val m = all % 3600 / 60
|
||||
val s = all % 60
|
||||
return if (h > 0) String.format(Locale.ROOT, "%d:%02d:%02d", h, m, s) else String.format(Locale.ROOT, "%d:%02d", m, s)
|
||||
}
|
||||
|
||||
/**
|
||||
* A player's controls: the place in the file as a slider the whole width, the two times under
|
||||
* its two ends, and Play or Pause in the middle (56 dp). Nothing here depends on a text's length.
|
||||
*/
|
||||
@Composable
|
||||
fun PlayerControls(ui: PlayerUi, onToggle: () -> Unit, onSeek: (Int) -> Unit, modifier: Modifier = Modifier) {
|
||||
val palette = LocalPalette.current
|
||||
var dragging by remember { mutableStateOf<Float?>(null) }
|
||||
val length = ui.durationMs.coerceAtLeast(1).toFloat()
|
||||
Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Slider(
|
||||
value = (dragging ?: ui.positionMs.toFloat()).coerceIn(0f, length),
|
||||
onValueChange = { dragging = it },
|
||||
onValueChangeFinished = {
|
||||
dragging?.let { onSeek(it.toInt()) }
|
||||
dragging = null
|
||||
},
|
||||
valueRange = 0f..length,
|
||||
enabled = ui.ready && ui.durationMs > 0,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
Text(playTime((dragging ?: ui.positionMs.toFloat()).toInt()), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(playTime(ui.durationMs), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
FilledIconButton(
|
||||
onClick = onToggle,
|
||||
enabled = ui.ready,
|
||||
colors = IconButtonDefaults.filledIconButtonColors(containerColor = palette.accent, contentColor = palette.accentInk),
|
||||
modifier = Modifier.size(56.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (ui.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
|
||||
contentDescription = stringResource(if (ui.playing) R.string.pause else R.string.play),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A text file being edited: the whole text in one field, in the code's type. The field is the
|
||||
* screen; saving and leaving are the bar's.
|
||||
*/
|
||||
@Composable
|
||||
fun EditorBody(text: String, onChange: (String) -> Unit, enabled: Boolean = true) {
|
||||
val palette = LocalPalette.current
|
||||
BasicTextField(
|
||||
value = text,
|
||||
onValueChange = onChange,
|
||||
enabled = enabled,
|
||||
textStyle = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp, lineHeight = 20.sp, color = palette.ink),
|
||||
cursorBrush = SolidColor(palette.accent),
|
||||
modifier = Modifier.fillMaxSize().background(palette.codeBg).padding(12.dp),
|
||||
)
|
||||
}
|
||||
@@ -112,31 +112,6 @@ fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, file.language)
|
||||
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
|
||||
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
|
||||
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
|
||||
}
|
||||
},
|
||||
onClose = onClose,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load: suspend (ApiClient, Context) -> Loaded, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
@@ -321,12 +296,12 @@ private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
|
||||
}
|
||||
}
|
||||
|
||||
private fun copy(context: Context, label: String, text: String) {
|
||||
internal 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) {
|
||||
internal 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,582 @@
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.AudioAttributes
|
||||
import android.media.MediaDataSource
|
||||
import android.media.MediaPlayer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.SurfaceView
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
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.PaddingValues
|
||||
import androidx.compose.foundation.layout.aspectRatio
|
||||
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.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.derivedStateOf
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
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.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.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.compose.LifecycleEventEffect
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.files.FileCache
|
||||
import eu.llembas.android.ui.files.copyInto
|
||||
import eu.llembas.android.ui.files.stepped
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import eu.llembas.android.ui.unreachable
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
|
||||
// The viewers that need the file's bytes: a picture, a PDF, sound and video. The bytes come
|
||||
// from the instance the app is signed in to, with the token in the Authorization header -- the
|
||||
// address handed to nothing: the platform's player reads through [RemoteMedia], which asks the
|
||||
// app's own HTTP client for each piece. No player library is added for this.
|
||||
|
||||
/** The most a picture's file may weigh to be decoded on the phone, and a PDF's to be copied for its pages. */
|
||||
const val IMAGE_MAX_BYTES = 64L * 1024 * 1024
|
||||
const val PDF_MAX_BYTES = 100L * 1024 * 1024
|
||||
|
||||
/** The most pages of a PDF that are laid out; a longer one is read to there and downloaded for the rest. */
|
||||
const val PDF_MAX_PAGES = 2000
|
||||
|
||||
/** How a viewer's bytes came: on their way ([done] of [total], -1 unknown), there, or not shown. */
|
||||
sealed interface Fetched<out T> {
|
||||
data class Loading(val done: Long = 0, val total: Long = -1) : Fetched<Nothing>
|
||||
|
||||
data class Ready<T>(val value: T) : Fetched<T>
|
||||
|
||||
/** [message]: the server's sentence or the network's; null: this phone could not draw it. */
|
||||
data class Failed(val message: String?) : Fetched<Nothing>
|
||||
}
|
||||
|
||||
/**
|
||||
* [file] decoded for the screen: its bounds are read first, and it is sampled down
|
||||
* ([sampleFor]) so neither edge nor the pixel count is more than a phone shows -- a picture
|
||||
* that claims a huge size costs a bounded amount of memory, or is not decoded at all.
|
||||
*/
|
||||
fun decodeCapped(file: File): Bitmap? {
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.path, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
|
||||
var sample = sampleFor(bounds.outWidth, bounds.outHeight)
|
||||
repeat(3) {
|
||||
try {
|
||||
return BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
|
||||
} catch (e: OutOfMemoryError) {
|
||||
sample *= 2
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** A picture of the tree: copied into the private cache (at most [IMAGE_MAX_BYTES]), decoded small, and the copy deleted at once. */
|
||||
@Composable
|
||||
fun ImageBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val picture by produceState<Fetched<ImageBitmap>>(Fetched.Loading(), path) {
|
||||
if (size > IMAGE_MAX_BYTES) {
|
||||
value = Fetched.Failed(null)
|
||||
return@produceState
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw IOException(context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.rawFile(path), copy, IMAGE_MAX_BYTES, stepped { done, total -> value = Fetched.Loading(done, total) })
|
||||
val bitmap = withContext(Dispatchers.Default) { decodeCapped(copy) }
|
||||
if (bitmap == null) Fetched.Failed(null) else Fetched.Ready(bitmap.asImageBitmap())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(viewerSays(context, e))
|
||||
} finally {
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
when (val now = picture) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> ZoomableImage(now.value, name)
|
||||
}
|
||||
}
|
||||
|
||||
/** A transfer under way, in the middle of the page: how far, when the size is known. */
|
||||
@Composable
|
||||
internal fun Progress(now: Fetched.Loading) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
if (now.total > 0) CircularProgressIndicator(progress = { (now.done.toFloat() / now.total).coerceIn(0f, 1f) }) else CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A PDF's pages, drawn by the platform's own renderer from a copy in the private cache. One page
|
||||
* is open at a time, and at most [PDF_MAX_PAGES] are offered. The renderer cannot be stopped in
|
||||
* the middle of a page, and closing it waits for the page being drawn: so [close] is never
|
||||
* called on the main thread -- [closeLater] is.
|
||||
*/
|
||||
class PdfPages(private val copy: File) {
|
||||
private val descriptor = ParcelFileDescriptor.open(copy, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
private val renderer = try {
|
||||
PdfRenderer(descriptor)
|
||||
} catch (e: Throwable) {
|
||||
descriptor.close()
|
||||
throw e
|
||||
}
|
||||
|
||||
/** Set before the lock is asked for: a page not yet begun is not begun any more. */
|
||||
@Volatile
|
||||
private var closing = false
|
||||
private var closed = false
|
||||
val count: Int = renderer.pageCount.coerceAtMost(PDF_MAX_PAGES)
|
||||
|
||||
/** Page [index] as pixels [width] wide; null once closed or when it cannot be drawn. */
|
||||
fun page(index: Int, width: Int): ImageBitmap? {
|
||||
if (closing || index !in 0 until count || width <= 0) return null
|
||||
return synchronized(this) {
|
||||
if (closed || closing) return@synchronized null
|
||||
runCatching {
|
||||
renderer.openPage(index).use { page ->
|
||||
var w = width
|
||||
var h = (page.height.toLong() * w / page.width.coerceAtLeast(1)).toInt().coerceAtLeast(1)
|
||||
// A page of an odd shape (a long receipt) is drawn smaller rather than as a huge bitmap.
|
||||
while (w.toLong() * h > PAGE_MAX_PIXELS) {
|
||||
w /= 2
|
||||
h /= 2
|
||||
}
|
||||
val bitmap = Bitmap.createBitmap(w.coerceAtLeast(1), h.coerceAtLeast(1), Bitmap.Config.ARGB_8888)
|
||||
// The paper: a PDF draws on transparent, and print is read on white in either theme.
|
||||
bitmap.eraseColor(PAPER)
|
||||
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bitmap.asImageBitmap()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets go of the renderer, the descriptor and the copy, after the page being drawn. Blocks for that long. */
|
||||
fun close() {
|
||||
closing = true
|
||||
synchronized(this) {
|
||||
if (closed) return
|
||||
closed = true
|
||||
runCatching { renderer.close() }
|
||||
runCatching { descriptor.close() }
|
||||
copy.delete()
|
||||
}
|
||||
}
|
||||
|
||||
/** [close] from the main thread: no page is begun from now on, and the rest happens on a thread of its own. */
|
||||
fun closeLater() {
|
||||
closing = true
|
||||
Thread({ close() }, "pdf-close").start()
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val PAGE_MAX_PIXELS = 6_000_000L
|
||||
const val PAPER = android.graphics.Color.WHITE
|
||||
}
|
||||
}
|
||||
|
||||
/** A PDF of the tree, page by page, as wide as the screen. */
|
||||
@Composable
|
||||
fun PdfBody(path: String, name: String, size: Long, fallback: @Composable (String?) -> Unit) =
|
||||
PdfBody(Raw.Path(path), name, size, gone = null, fallback = fallback)
|
||||
|
||||
/**
|
||||
* The same for any [Raw]: a file a chat names by its node id is copied and laid out as one of
|
||||
* the tree is. [gone] is what to say of a file that is no longer there, where the instance's own
|
||||
* refusal would name an id.
|
||||
*/
|
||||
@Composable
|
||||
fun PdfBody(what: Raw, name: String, size: Long, gone: String? = null, fallback: @Composable (String?) -> Unit) {
|
||||
val path = what
|
||||
val context = LocalContext.current
|
||||
var pages by remember(path) { mutableStateOf<Fetched<PdfPages>>(Fetched.Loading()) }
|
||||
DisposableEffect(path) {
|
||||
// Back during a slow page must not wait for it: the closing is not done on this thread.
|
||||
onDispose { (pages as? Fetched.Ready)?.value?.closeLater() }
|
||||
}
|
||||
LaunchedEffect(path) {
|
||||
if (size > PDF_MAX_BYTES) {
|
||||
pages = Fetched.Failed(null)
|
||||
return@LaunchedEffect
|
||||
}
|
||||
val copy = FileCache.viewing(context, name)
|
||||
// Held here too: a viewer closed while the renderer is being made never sees it in `pages`.
|
||||
var made: PdfPages? = null
|
||||
pages = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.raw(what), copy, PDF_MAX_BYTES, stepped { done, total -> pages = Fetched.Loading(done, total) })
|
||||
withContext(Dispatchers.IO) { made = PdfPages(copy) }
|
||||
Fetched.Ready(checkNotNull(made))
|
||||
} catch (e: CancellationException) {
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
made?.closeLater()
|
||||
copy.delete()
|
||||
// A password, or not a PDF after all: the renderer's own words are for a developer.
|
||||
Fetched.Failed(
|
||||
when {
|
||||
gone != null && e is ApiException && e.status == 404 -> gone
|
||||
e is ApiException || unreachable(e) -> viewerSays(context, e)
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
when (val now = pages) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> fallback(now.message)
|
||||
is Fetched.Ready -> PdfPagesList(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PdfPagesList(pages: PdfPages) {
|
||||
val palette = LocalPalette.current
|
||||
val list = rememberLazyListState()
|
||||
// Read through a derived state: the line is drawn again when the page changes, not at every pixel of a scroll.
|
||||
val first by remember { derivedStateOf { list.firstVisibleItemIndex + 1 } }
|
||||
Column(Modifier.fillMaxSize().background(palette.bgSunken)) {
|
||||
BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {
|
||||
val width = with(LocalDensity.current) { maxWidth.toPx() }.toInt().coerceIn(1, 1600)
|
||||
LazyColumn(
|
||||
state = list,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
items(pages.count) { index ->
|
||||
val page by produceState<ImageBitmap?>(null, pages, index, width) {
|
||||
value = withContext(Dispatchers.Default) { pages.page(index, width) }
|
||||
}
|
||||
val drawn = page
|
||||
if (drawn != null) {
|
||||
Image(drawn, contentDescription = null, contentScale = ContentScale.FillWidth, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
// Until it is drawn: a sheet of the usual shape, so the list does not jump far.
|
||||
Box(Modifier.fillMaxWidth().aspectRatio(0.707f).background(palette.surfaceRaised))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.viewer_page, first.toString(), pages.count.toString()),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = palette.inkMuted,
|
||||
modifier = Modifier.fillMaxWidth().background(palette.bg).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A file on the instance as the platform's player reads it: piece by piece, each a `Range`
|
||||
* request made by the app's own HTTP client with the token in its header. The player is never
|
||||
* given an address, so the token is never in one. [what] is a file by its path or by its node
|
||||
* id (what a generated file's result carries).
|
||||
*/
|
||||
class RemoteMedia(api: ApiClient, what: Raw, private val length: Long) : MediaDataSource() {
|
||||
private val reader = RangeReader(length) { from, to -> api.rawBytes(what, from, to) }
|
||||
|
||||
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int = reader.read(position, buffer, offset, size)
|
||||
|
||||
override fun getSize(): Long = length
|
||||
|
||||
override fun close() = reader.close()
|
||||
}
|
||||
|
||||
/** The most a chat's attachment may weigh to be copied for the player. */
|
||||
const val ATTACHED_MAX_BYTES = 512L * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Sound or video, played by the platform's player. A file of the tree ([Raw.Path], [Raw.Node])
|
||||
* is streamed: it starts before the file is there, and seeking asks for the piece it lands in.
|
||||
* A chat's attachment ([Raw.Attached]) is answered whole by the instance, so it is copied into
|
||||
* the private cache first and played from there; the copy goes when the player does. Leaving
|
||||
* the app pauses it; leaving the viewer lets go of it.
|
||||
*/
|
||||
@Composable
|
||||
fun MediaBody(what: Raw, size: Long, video: Boolean, fallback: @Composable (String?) -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var ui by remember(what) { mutableStateOf(PlayerUi()) }
|
||||
var failed by remember(what) { mutableStateOf(false) }
|
||||
var said by remember(what) { mutableStateOf<String?>(null) }
|
||||
var player by remember(what) { mutableStateOf<MediaPlayer?>(null) }
|
||||
var surface by remember(what) { mutableStateOf<SurfaceHolder?>(null) }
|
||||
var ratio by remember(what) { mutableStateOf(16f / 9f) }
|
||||
|
||||
DisposableEffect(what) {
|
||||
var held: MediaPlayer? = null
|
||||
var source: RemoteMedia? = null
|
||||
var copy: File? = null
|
||||
val starting = scope.launch {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null || (size <= 0 && what !is Raw.Attached)) {
|
||||
failed = true
|
||||
return@launch
|
||||
}
|
||||
try {
|
||||
val made = MediaPlayer().also { held = it }
|
||||
made.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(if (video) AudioAttributes.CONTENT_TYPE_MOVIE else AudioAttributes.CONTENT_TYPE_MUSIC)
|
||||
.build(),
|
||||
)
|
||||
if (what is Raw.Attached) {
|
||||
val local = FileCache.viewing(context, "attachment").also { copy = it }
|
||||
// A copy is a request with the account's file in it: not while the phone is locked.
|
||||
context.lembas.gate.pass()
|
||||
api.copyInto(api.raw(what), local, ATTACHED_MAX_BYTES)
|
||||
made.setDataSource(local.path)
|
||||
} else {
|
||||
made.setDataSource(RemoteMedia(api, what, size).also { source = it })
|
||||
}
|
||||
made.setOnPreparedListener {
|
||||
ui = ui.copy(ready = true, durationMs = it.duration.coerceAtLeast(0))
|
||||
player = it
|
||||
}
|
||||
made.setOnCompletionListener { ui = ui.copy(playing = false, positionMs = ui.durationMs) }
|
||||
made.setOnErrorListener { _, _, _ ->
|
||||
failed = true
|
||||
true
|
||||
}
|
||||
made.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = (w.toFloat() / h).coerceIn(0.3f, 4f) }
|
||||
made.prepareAsync()
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// The instance's refusal of a copy is a sentence to read; the player's own failure is not.
|
||||
said = if (e is ApiException || unreachable(e)) viewerSays(context, e) else null
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
onDispose {
|
||||
starting.cancel()
|
||||
player = null
|
||||
held?.runCatching { release() }
|
||||
source?.runCatching { close() }
|
||||
copy?.runCatching { delete() }
|
||||
}
|
||||
}
|
||||
|
||||
// The picture goes where the surface is, for as long as there is one.
|
||||
LaunchedEffect(player, surface) { player?.runCatching { setDisplay(surface) } }
|
||||
LaunchedEffect(player, ui.playing) {
|
||||
while (ui.playing) {
|
||||
player?.runCatching { currentPosition }?.getOrNull()?.let { ui = ui.copy(positionMs = it) }
|
||||
delay(500)
|
||||
}
|
||||
}
|
||||
LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
|
||||
player?.runCatching { if (isPlaying) pause() }
|
||||
ui = ui.copy(playing = false)
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
fallback(said)
|
||||
return
|
||||
}
|
||||
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
if (video) {
|
||||
AndroidView(
|
||||
factory = { viewContext ->
|
||||
SurfaceView(viewContext).apply {
|
||||
holder.addCallback(
|
||||
object : SurfaceHolder.Callback {
|
||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||
surface = holder
|
||||
}
|
||||
|
||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
player?.runCatching { setDisplay(null) }
|
||||
surface = null
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().weight(1f, fill = false).aspectRatio(ratio),
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.MusicNote, contentDescription = null, tint = palette.inkFaint, modifier = Modifier.padding(24.dp).size(72.dp))
|
||||
}
|
||||
PlayerControls(
|
||||
ui,
|
||||
onToggle = {
|
||||
val now = player ?: return@PlayerControls
|
||||
runCatching {
|
||||
if (now.isPlaying) {
|
||||
now.pause()
|
||||
ui = ui.copy(playing = false)
|
||||
} else {
|
||||
if (ui.durationMs > 0 && ui.positionMs >= ui.durationMs) now.seekTo(0)
|
||||
now.start()
|
||||
ui = ui.copy(playing = true)
|
||||
}
|
||||
}
|
||||
},
|
||||
onSeek = { to ->
|
||||
player?.runCatching { seekTo(to) }
|
||||
ui = ui.copy(positionMs = to)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** What a player opened over a chat plays: which bytes, what it is called, how large, and whether there is a picture. */
|
||||
data class Playing(val what: Raw, val title: String, val size: Long, val video: Boolean)
|
||||
|
||||
/** A document a chat names, to be laid out over it: a PDF an agent showed. */
|
||||
data class Reading(val what: Raw, val title: String, val size: Long)
|
||||
|
||||
/**
|
||||
* A PDF over the whole screen, for a file a chat names by its node id: its pages as the tree's
|
||||
* viewer lays them out, from a copy in the private cache. One that is no longer there says so
|
||||
* ([gone]); one this phone cannot lay out says that it can still be downloaded. Back or the cross
|
||||
* closes it.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DocumentDialog(reading: Reading, onClose: () -> Unit, gone: String) {
|
||||
val palette = LocalPalette.current
|
||||
val unreadable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(reading.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
PdfBody(reading.what, reading.title, reading.size, gone = gone, fallback = unreadable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How a player's file was found before it was handed to the player. */
|
||||
private sealed interface Probed {
|
||||
data object Asking : Probed
|
||||
|
||||
data object There : Probed
|
||||
|
||||
data class Refused(val message: String?) : Probed
|
||||
}
|
||||
|
||||
/**
|
||||
* A player over the whole screen, for a file a chat names: a generated video or track (by its
|
||||
* node id) or an attachment. A file of the tree is asked for its first byte before the player
|
||||
* gets it, so one that is no longer there says so in a sentence rather than as a player that
|
||||
* does not start. Back or the cross closes it and lets go of the player.
|
||||
*/
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun PlayerDialog(playing: Playing, onClose: () -> Unit, gone: String) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val probed by produceState<Probed>(Probed.Asking, playing.what) {
|
||||
if (playing.what is Raw.Attached) {
|
||||
value = Probed.There
|
||||
return@produceState
|
||||
}
|
||||
value = try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
context.lembas.gate.pass()
|
||||
withContext(Dispatchers.IO) { api.rawBytes(playing.what, 0, 0) }
|
||||
Probed.There
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
// By its id the instance's own refusal names the id; "no longer there" is what a person reads.
|
||||
Probed.Refused(if (e is ApiException && e.status == 404) gone else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
val unplayable: @Composable (String?) -> Unit = { note ->
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(note ?: stringResource(R.string.files_not_shown), color = palette.inkMuted, modifier = Modifier.padding(32.dp))
|
||||
}
|
||||
}
|
||||
Dialog(onDismissRequest = onClose, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = { Text(playing.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Box(Modifier.padding(padding).fillMaxSize()) {
|
||||
when (val now = probed) {
|
||||
Probed.Asking -> Progress(Fetched.Loading())
|
||||
is Probed.Refused -> unplayable(now.message)
|
||||
Probed.There -> MediaBody(playing.what, playing.size, playing.video, unplayable)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package eu.llembas.android.ui.viewer
|
||||
|
||||
import android.content.Context
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
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.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
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.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.Notebook
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.api.Table
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.ui.explain
|
||||
import eu.llembas.android.ui.files.CreateFile
|
||||
import eu.llembas.android.ui.files.SaidDialog
|
||||
import eu.llembas.android.ui.files.TransferHost
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.VersionsDialog
|
||||
import eu.llembas.android.ui.files.filesSay
|
||||
import eu.llembas.android.ui.files.noSuchRoute
|
||||
import eu.llembas.android.ui.files.rememberSaver
|
||||
import eu.llembas.android.ui.theme.LocalPalette
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/** What a viewer says of a failure: the server's or the network's sentence; null for "too large for this phone". */
|
||||
internal fun viewerSays(context: Context, e: Throwable): String? {
|
||||
val tooLarge = e is ApiException && e.status == 413 && e.message.isNullOrBlank()
|
||||
return if (tooLarge) null else context.explain(e)
|
||||
}
|
||||
|
||||
/**
|
||||
* The text being edited, kept apart from the screen: a megabyte does not fit what Android saves
|
||||
* of a screen when the phone is turned, and unsaved words must not go with it. [draft] is null
|
||||
* while nothing is edited; [touched] once a key was pressed.
|
||||
*/
|
||||
class EditViewModel : ViewModel() {
|
||||
var draft by mutableStateOf<String?>(null)
|
||||
private set
|
||||
var touched by mutableStateOf(false)
|
||||
private set
|
||||
|
||||
/** The `sha` the text had when it was read: a save says it, so somebody else's change is not written over. */
|
||||
var base: String = ""
|
||||
private set
|
||||
|
||||
fun start(text: String, sha: String) {
|
||||
draft = text
|
||||
base = sha
|
||||
touched = false
|
||||
}
|
||||
|
||||
fun type(text: String) {
|
||||
draft = text
|
||||
touched = true
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
draft = null
|
||||
touched = false
|
||||
}
|
||||
}
|
||||
|
||||
/** A file of the tree, opened: on its way, not to be had, or what the server says of it. */
|
||||
private sealed interface Opened {
|
||||
data object Loading : Opened
|
||||
|
||||
data class Failed(val message: String) : Opened
|
||||
|
||||
data class Ready(val file: FileContent) : Opened
|
||||
}
|
||||
|
||||
/**
|
||||
* A file of the person's tree, full screen, drawn by what the server says it is (`file_kind`):
|
||||
* text kinds as text (and edited as text), a picture, a PDF's pages, sound and video streamed, a
|
||||
* table's grid, a notebook's cells, and for the rest what it is with Download, Open with and
|
||||
* Share. The person's own files are no more trusted than a model's, since a model may have
|
||||
* written them: **nothing is rendered as HTML and nothing a file holds is run** -- an HTML page
|
||||
* and an SVG are their source. [onChanged]: the file was saved or a version restored, so a
|
||||
* listing behind this is stale.
|
||||
*/
|
||||
@Composable
|
||||
fun TreeFileViewer(path: String, onClose: () -> Unit, startEditing: Boolean = false, onChanged: () -> Unit = {}) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val edit: EditViewModel = viewModel(key = "edit:$path")
|
||||
// Its own, not the Files page's: two hosts of one would each open the other app.
|
||||
val transfers: TransferViewModel = viewModel(key = "viewer-transfers")
|
||||
var opened by remember(path) { mutableStateOf<Opened>(Opened.Loading) }
|
||||
var reads by remember(path) { mutableIntStateOf(0) }
|
||||
var web by remember(path) { mutableStateOf<String?>(null) }
|
||||
var menu by remember { mutableStateOf(false) }
|
||||
var versions by remember { mutableStateOf(false) }
|
||||
var leaving by remember { mutableStateOf(false) }
|
||||
var saving by remember { mutableStateOf(false) }
|
||||
var conflict by remember { mutableStateOf<String?>(null) }
|
||||
var said by remember { mutableStateOf<String?>(null) }
|
||||
var wantsEdit by remember(path) { mutableStateOf(startEditing) }
|
||||
// A table can be read as the text it is, as well as laid out.
|
||||
var tableAsText by remember(path) { mutableStateOf(false) }
|
||||
val saveVersion = rememberSaver(transfers)
|
||||
val name = FileKinds.name(path)
|
||||
|
||||
LaunchedEffect(path, reads) {
|
||||
val api = context.lembas.instances.client()
|
||||
if (api == null) {
|
||||
opened = Opened.Failed(context.getString(R.string.assist_signed_out))
|
||||
return@LaunchedEffect
|
||||
}
|
||||
web = api.webFile(path)
|
||||
opened = try {
|
||||
val file = api.fileContent(path)
|
||||
// A new file opens ready to be written in; so does one whose text was read again after a conflict.
|
||||
if (wantsEdit && FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) edit.start(file.text, file.sha)
|
||||
wantsEdit = false
|
||||
Opened.Ready(file)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Opened.Failed(context.filesSay(e))
|
||||
}
|
||||
}
|
||||
|
||||
val file = (opened as? Opened.Ready)?.file
|
||||
val draft = edit.draft
|
||||
val saveTo = rememberLauncherForActivityResult(CreateFile()) { to -> if (to != null) transfers.download(listOf(path), zip = false, to = to) }
|
||||
val actions = remember(path, file?.mime) {
|
||||
object : FileActions {
|
||||
override fun download() = saveTo.launch(CreateFile.Ask(name, file?.mime.orEmpty()))
|
||||
|
||||
override fun openWith() = transfers.openWith(path, name)
|
||||
|
||||
override fun share() = transfers.share(listOf(FileEntry(name = name, path = path, mime = file?.mime.orEmpty())))
|
||||
}
|
||||
}
|
||||
|
||||
fun save(force: Boolean) {
|
||||
val text = edit.draft ?: return
|
||||
saving = true
|
||||
scope.launch {
|
||||
try {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
val saved = api.saveFile(path, text, base = edit.base, force = force)
|
||||
edit.stop()
|
||||
opened = Opened.Ready(saved)
|
||||
onChanged()
|
||||
} catch (e: SaveConflict) {
|
||||
// Nothing was written. The server's sentence, with the two ways on.
|
||||
conflict = e.message?.ifBlank { null } ?: context.getString(R.string.files_conflict)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
said = context.filesSay(e)
|
||||
} finally {
|
||||
saving = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving with words that were not saved asks first: Back, the cross, and a tap outside all come here.
|
||||
fun close() {
|
||||
when {
|
||||
draft != null && edit.touched -> leaving = true
|
||||
draft != null -> edit.stop()
|
||||
else -> onClose()
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = { close() }, properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)) {
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = { IconButton(onClick = { close() }) { Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.close)) } },
|
||||
title = {
|
||||
Column {
|
||||
Text(name, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
path,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = palette.inkFaint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.StartEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
if (draft != null) {
|
||||
IconButton(onClick = { save(force = false) }, enabled = !saving && edit.touched) {
|
||||
Icon(Icons.Filled.Check, contentDescription = stringResource(R.string.save))
|
||||
}
|
||||
} else if (file != null) {
|
||||
if (FileKinds.editable(file.fileKind, file.writable, file.withheld != null)) {
|
||||
IconButton(onClick = {
|
||||
edit.start(file.text, file.sha)
|
||||
}) { Icon(Icons.Filled.Edit, contentDescription = stringResource(R.string.edit)) }
|
||||
}
|
||||
Box {
|
||||
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = stringResource(R.string.more)) }
|
||||
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
|
||||
val then: (() -> Unit) -> (() -> Unit) = { act ->
|
||||
{
|
||||
menu = false
|
||||
act()
|
||||
}
|
||||
}
|
||||
val text = file.text.takeIf { file.withheld == null && it.isNotEmpty() }
|
||||
if (text != null) MenuEntry(R.string.viewer_copy, then { copy(context, name, text) })
|
||||
if (text != null && FileKinds.viewer(file.fileKind) == FileView.Table) {
|
||||
MenuEntry(if (tableAsText) R.string.table_as_table else R.string.table_as_text, then { tableAsText = !tableAsText })
|
||||
}
|
||||
if (file.fileKind != null) {
|
||||
MenuEntry(R.string.download, then { actions.download() })
|
||||
MenuEntry(R.string.files_open_with, then { actions.openWith() })
|
||||
MenuEntry(R.string.report_share, then { actions.share() })
|
||||
MenuEntry(R.string.versions, then { versions = true })
|
||||
}
|
||||
web?.let { url -> MenuEntry(R.string.viewer_open_browser, then { openOutside(context, url) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(Modifier.padding(padding).fillMaxSize()) {
|
||||
if (saving) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp))
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
when (val now = opened) {
|
||||
Opened.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))
|
||||
is Opened.Failed -> Text(now.message, color = palette.inkMuted, modifier = Modifier.align(Alignment.Center).padding(32.dp))
|
||||
is Opened.Ready -> if (draft != null) EditorBody(draft, edit::type, enabled = !saving) else Shown(path, now.file, actions, tableAsText)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (leaving) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { leaving = false },
|
||||
text = { Text(stringResource(R.string.files_unsaved)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
leaving = false
|
||||
edit.stop()
|
||||
},
|
||||
) { Text(stringResource(R.string.discard)) }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = { leaving = false }) { Text(stringResource(R.string.cancel)) } },
|
||||
)
|
||||
}
|
||||
conflict?.let { sentence ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { conflict = null },
|
||||
text = { Text(sentence) },
|
||||
// Two ways on, and neither is the default: the words stack, so each is a whole row.
|
||||
confirmButton = {
|
||||
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End) {
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
// What the file holds now, in place of what was typed here.
|
||||
edit.stop()
|
||||
wantsEdit = true
|
||||
reads++
|
||||
},
|
||||
) { Text(stringResource(R.string.reload)) }
|
||||
TextButton(
|
||||
onClick = {
|
||||
conflict = null
|
||||
save(force = true)
|
||||
},
|
||||
) { Text(stringResource(R.string.files_save_anyway)) }
|
||||
TextButton(onClick = { conflict = null }) { Text(stringResource(R.string.cancel)) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
said?.let { SaidDialog(it, onClose = { said = null }) }
|
||||
if (versions) {
|
||||
VersionsDialog(
|
||||
path,
|
||||
onDownload = { version -> saveVersion(Raw.Path(path, version.id), name, file?.mime.orEmpty()) },
|
||||
onClose = { versions = false },
|
||||
onRestored = {
|
||||
versions = false
|
||||
reads++
|
||||
onChanged()
|
||||
},
|
||||
)
|
||||
}
|
||||
TransferHost(transfers)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MenuEntry(label: Int, onClick: () -> Unit) = DropdownMenuItem(text = { Text(stringResource(label)) }, onClick = onClick)
|
||||
|
||||
/** A file that was read, by its kind. What cannot be drawn falls back to the details page, saying why. */
|
||||
@Composable
|
||||
private fun Shown(path: String, file: FileContent, actions: FileActions, tableAsText: Boolean = false) {
|
||||
val context = LocalContext.current
|
||||
val name = file.name.ifBlank { FileKinds.name(path) }
|
||||
val type = listOf(file.fileKind.orEmpty(), file.mime).filter { it.isNotBlank() }.joinToString(" · ")
|
||||
val details: @Composable (String?) -> Unit = { note -> DetailsBody(name, type, file.size, note ?: stringResource(R.string.files_not_shown), actions) }
|
||||
val withheld = file.withheld
|
||||
when (FileKinds.viewer(file.fileKind)) {
|
||||
FileView.Text -> when {
|
||||
withheld != null -> {
|
||||
val why = if (withheld.reason == "too_large") R.string.viewer_too_large else R.string.viewer_not_text
|
||||
details(withheld.message.ifBlank { stringResource(why) })
|
||||
}
|
||||
|
||||
file.fileKind == "svg" -> Column(Modifier.fillMaxSize()) {
|
||||
Note(stringResource(R.string.files_svg_source))
|
||||
FileBody("code", "xml", 0, file.text)
|
||||
}
|
||||
|
||||
else -> FileBody(file.viewKind, file.language, 0, file.text)
|
||||
}
|
||||
|
||||
FileView.Image -> ImageBody(path, name, file.size, details)
|
||||
|
||||
FileView.Pdf -> PdfBody(path, name, file.size, details)
|
||||
|
||||
FileView.Audio -> MediaBody(Raw.Path(path), file.size, video = false, fallback = details)
|
||||
|
||||
FileView.Video -> MediaBody(Raw.Path(path), file.size, video = true, fallback = details)
|
||||
|
||||
FileView.Table -> if (tableAsText && withheld == null) {
|
||||
FileBody("text", "", 0, file.text)
|
||||
} else {
|
||||
val table by produceState<Fetched<Table>>(Fetched.Loading(), path, file.sha) {
|
||||
value = try {
|
||||
// Up to 1 MB the server sent the text; of a longer table the first megabyte is asked for.
|
||||
val text = if (withheld == null) {
|
||||
file.text
|
||||
} else {
|
||||
val api = context.lembas.instances.client() ?: throw ApiException(401, context.getString(R.string.assist_signed_out))
|
||||
withContext(Dispatchers.IO) { api.rawBytes(path, 0, TABLE_HEAD - 1).toString(Charsets.UTF_8) }
|
||||
}
|
||||
Fetched.Ready(withContext(Dispatchers.Default) { parseTable(text, tableDelimiter(name, text), partial = withheld != null) })
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Fetched.Failed(if (noSuchRoute(e)) null else viewerSays(context, e))
|
||||
}
|
||||
}
|
||||
when (val now = table) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> if (now.value.rows.isEmpty()) FileBody("text", "", 0, file.text) else TableBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Notebook -> {
|
||||
// Up to a megabyte of JSON: read off the main thread, not while the page is being drawn.
|
||||
val notebook by produceState<Fetched<Notebook>>(Fetched.Loading(), file.sha, file.text) {
|
||||
val parsed = if (withheld == null) withContext(Dispatchers.Default) { parseNotebook(file.text) } else null
|
||||
value = if (parsed != null) Fetched.Ready(parsed) else Fetched.Failed(withheld?.message?.ifBlank { null })
|
||||
}
|
||||
when (val now = notebook) {
|
||||
is Fetched.Loading -> Progress(now)
|
||||
is Fetched.Failed -> details(now.message)
|
||||
is Fetched.Ready -> NotebookBody(now.value)
|
||||
}
|
||||
}
|
||||
|
||||
FileView.Details -> {
|
||||
val archive = file.archive
|
||||
when {
|
||||
// An instance that lists what the archive holds: the names, as text, and nothing unpacked.
|
||||
archive != null && archive.problem == null -> ArchiveBody(archive, actions)
|
||||
|
||||
archive != null -> details(archive.message.ifBlank { stringResource(R.string.archive_unreadable) })
|
||||
|
||||
else -> details(stringResource(if (file.fileKind == "archive") R.string.archive_note else R.string.files_no_viewer))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** How much of a table too long to be sent as text is read for its first rows. */
|
||||
private const val TABLE_HEAD = 1024L * 1024
|
||||
@@ -14,6 +14,7 @@ import eu.llembas.android.api.AppRelease
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.SharedHttp
|
||||
import eu.llembas.android.api.await
|
||||
import eu.llembas.android.api.olderThan
|
||||
import eu.llembas.android.lembas
|
||||
import eu.llembas.android.notify.NotificationAccess
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -98,8 +99,9 @@ class Updater(private val context: Context) {
|
||||
}
|
||||
install(apk)
|
||||
context.getString(R.string.update_installing, latest.version)
|
||||
} catch (e: Exception) {
|
||||
e.message ?: context.getString(R.string.update_unreachable)
|
||||
} catch (_: Exception) {
|
||||
// Never a library's own words on the screen: the manifest or the file did not come.
|
||||
context.getString(R.string.update_unreachable)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,17 +148,12 @@ class Updater(private val context: Context) {
|
||||
companion object {
|
||||
const val MANIFEST = "https://llembas.eu/android/latest.json"
|
||||
|
||||
/** Whether `a` is a later x.y.z than `b`. */
|
||||
fun newer(a: String, b: String): Boolean {
|
||||
val left = a.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
val right = b.split(".").map { it.toIntOrNull() ?: 0 }
|
||||
for (i in 0 until maxOf(left.size, right.size)) {
|
||||
val l = left.getOrElse(i) { 0 }
|
||||
val r = right.getOrElse(i) { 0 }
|
||||
if (l != r) return l > r
|
||||
}
|
||||
return false
|
||||
}
|
||||
/**
|
||||
* Whether the version `a` is later than `b`, by the one rule the app compares versions
|
||||
* with ([olderThan]): a release is later than every beta of itself, so a beta is offered
|
||||
* the release it was a test of. A version that cannot be read is never later.
|
||||
*/
|
||||
fun newer(a: String, b: String): Boolean = olderThan(b, a)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package eu.llembas.android.widget
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ShortcutInfo
|
||||
@@ -34,10 +35,21 @@ class AskWidget : AppWidgetProvider() {
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private companion object {
|
||||
const val REQUEST_ASK = 1
|
||||
const val REQUEST_LISTEN = 2
|
||||
const val REQUEST_CONTINUE = 3
|
||||
companion object {
|
||||
private const val REQUEST_ASK = 1
|
||||
private const val REQUEST_LISTEN = 2
|
||||
private const val REQUEST_CONTINUE = 3
|
||||
|
||||
/**
|
||||
* Give every placed widget its buttons again. Nothing on it changes -- but the intents
|
||||
* behind the buttons carry the app's own mark ([eu.llembas.android.assist.OwnIntents]),
|
||||
* and a widget placed by an older version has buttons without it.
|
||||
*/
|
||||
fun refresh(context: Context) {
|
||||
val manager = AppWidgetManager.getInstance(context) ?: return
|
||||
val ids = runCatching { manager.getAppWidgetIds(ComponentName(context, AskWidget::class.java)) }.getOrNull() ?: return
|
||||
if (ids.isNotEmpty()) AskWidget().onUpdate(context, manager, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M15,1h1v1h-1z M6,2h2v1h-2z M15,2h1v1h-1z M5,3h1v1h-1z M15,3h1v1h-1z M5,4h1v1h-1z M14,4h1v1h-1z M4,5h1v1h-1z M14,5h1v1h-1z M4,6h1v1h-1z M14,6h1v1h-1z M3,7h1v1h-1z M13,7h1v1h-1z M3,8h1v1h-1z M12,8h1v1h-1z M3,9h1v1h-1z M11,9h1v1h-1z M3,10h1v1h-1z M10,10h1v1h-1z M3,11h1v1h-1z M7,11h3v1h-3z M2,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M14,2h1v1h-1z M13,3h2v1h-2z M12,4h2v1h-2z M11,5h3v1h-3z M10,6h4v1h-4z M9,7h4v1h-4z M8,8h4v1h-4z M7,9h4v1h-4z M6,10h4v1h-4z M5,11h2v1h-2z M3,12h1v1h-1z M2,13h1v1h-1z M1,14h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M11,1h4v1h-4z M10,2h2v1h-2z M9,3h2v1h-2z M8,4h2v1h-2z M7,5h2v1h-2z M6,6h2v1h-2z M5,7h2v1h-2z M4,8h2v1h-2z M4,9h1v1h-1z M4,11h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M10,1h1v1h-1z M8,2h2v1h-2z M6,3h3v1h-3z M6,4h2v1h-2z M5,5h2v1h-2z M5,6h1v1h-1z M4,7h1v1h-1z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M12,2h2v1h-2z M11,3h2v1h-2z M10,4h2v1h-2z M9,5h2v1h-2z M8,6h2v1h-2z M7,7h2v1h-2z M6,8h2v1h-2z M5,9h2v1h-2z M4,10h2v1h-2z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#0B0D10" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M17,3h1v1h-1z M8,4h2v1h-2z M17,4h1v1h-1z M7,5h1v1h-1z M17,5h1v1h-1z M7,6h1v1h-1z M16,6h1v1h-1z M6,7h1v1h-1z M16,7h1v1h-1z M6,8h1v1h-1z M16,8h1v1h-1z M5,9h1v1h-1z M15,9h1v1h-1z M5,10h1v1h-1z M14,10h1v1h-1z M5,11h1v1h-1z M13,11h1v1h-1z M5,12h1v1h-1z M12,12h1v1h-1z M5,13h1v1h-1z M9,13h3v1h-3z M4,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z"/>
|
||||
<path android:fillColor="#4FAE5A" android:pathData="M16,4h1v1h-1z M15,5h2v1h-2z M14,6h2v1h-2z M13,7h3v1h-3z M12,8h4v1h-4z M11,9h4v1h-4z M10,10h4v1h-4z M9,11h4v1h-4z M8,12h4v1h-4z M7,13h2v1h-2z M5,14h1v1h-1z M4,15h1v1h-1z M3,16h1v1h-1z"/>
|
||||
<path android:fillColor="#7EE081" android:pathData="M13,3h4v1h-4z M12,4h2v1h-2z M11,5h2v1h-2z M10,6h2v1h-2z M9,7h2v1h-2z M8,8h2v1h-2z M7,9h2v1h-2z M6,10h2v1h-2z M6,11h1v1h-1z M6,13h1v1h-1z"/>
|
||||
<path android:fillColor="#B6F2A6" android:pathData="M12,3h1v1h-1z M10,4h2v1h-2z M8,5h3v1h-3z M8,6h2v1h-2z M7,7h2v1h-2z M7,8h1v1h-1z M6,9h1v1h-1z"/>
|
||||
<path android:fillColor="#C792EA" android:pathData="M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
<path android:fillColor="#D8FFD0" android:pathData="M14,4h2v1h-2z M13,5h2v1h-2z M12,6h2v1h-2z M11,7h2v1h-2z M10,8h2v1h-2z M9,9h2v1h-2z M8,10h2v1h-2z M7,11h2v1h-2z M6,12h2v1h-2z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -3,7 +3,7 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp" android:height="108dp"
|
||||
android:viewportWidth="108" android:viewportHeight="108">
|
||||
<group android:translateX="26" android:translateY="26" android:scaleX="3.5" android:scaleY="3.5">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M10,0h5v1h-5z M8,1h2v1h-2z M10,1h1v1h-1z M11,1h4v1h-4z M15,1h1v1h-1z M6,2h2v1h-2z M8,2h2v1h-2z M10,2h2v1h-2z M12,2h2v1h-2z M14,2h1v1h-1z M15,2h1v1h-1z M5,3h1v1h-1z M6,3h3v1h-3z M9,3h2v1h-2z M11,3h2v1h-2z M13,3h2v1h-2z M15,3h1v1h-1z M5,4h1v1h-1z M6,4h2v1h-2z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h1v1h-1z M4,5h1v1h-1z M5,5h2v1h-2z M7,5h2v1h-2z M9,5h2v1h-2z M11,5h3v1h-3z M14,5h1v1h-1z M4,6h1v1h-1z M5,6h1v1h-1z M6,6h2v1h-2z M8,6h2v1h-2z M10,6h4v1h-4z M14,6h1v1h-1z M3,7h1v1h-1z M4,7h1v1h-1z M5,7h2v1h-2z M7,7h2v1h-2z M9,7h4v1h-4z M13,7h1v1h-1z M3,8h1v1h-1z M4,8h2v1h-2z M6,8h2v1h-2z M8,8h4v1h-4z M12,8h1v1h-1z M3,9h1v1h-1z M4,9h1v1h-1z M5,9h2v1h-2z M7,9h4v1h-4z M11,9h1v1h-1z M3,10h1v1h-1z M4,10h2v1h-2z M6,10h4v1h-4z M10,10h1v1h-1z M3,11h1v1h-1z M4,11h1v1h-1z M5,11h2v1h-2z M7,11h3v1h-3z M2,12h1v1h-1z M3,12h1v1h-1z M4,12h3v1h-3z M1,13h1v1h-1z M2,13h1v1h-1z M3,13h1v1h-1z M0,14h1v1h-1z M1,14h1v1h-1z M2,14h1v1h-1z M1,15h1v1h-1z"/>
|
||||
<group android:translateX="21" android:translateY="21" android:scaleX="2.75" android:scaleY="2.75">
|
||||
<path android:fillColor="#FFFFFFFF" android:pathData="M12,2h5v1h-5z M10,3h2v1h-2z M12,3h1v1h-1z M13,3h4v1h-4z M17,3h1v1h-1z M8,4h2v1h-2z M10,4h2v1h-2z M12,4h2v1h-2z M14,4h2v1h-2z M16,4h1v1h-1z M17,4h1v1h-1z M7,5h1v1h-1z M8,5h3v1h-3z M11,5h2v1h-2z M13,5h2v1h-2z M15,5h2v1h-2z M17,5h1v1h-1z M7,6h1v1h-1z M8,6h2v1h-2z M10,6h2v1h-2z M12,6h2v1h-2z M14,6h2v1h-2z M16,6h1v1h-1z M6,7h1v1h-1z M7,7h2v1h-2z M9,7h2v1h-2z M11,7h2v1h-2z M13,7h3v1h-3z M16,7h1v1h-1z M6,8h1v1h-1z M7,8h1v1h-1z M8,8h2v1h-2z M10,8h2v1h-2z M12,8h4v1h-4z M16,8h1v1h-1z M5,9h1v1h-1z M6,9h1v1h-1z M7,9h2v1h-2z M9,9h2v1h-2z M11,9h4v1h-4z M15,9h1v1h-1z M5,10h1v1h-1z M6,10h2v1h-2z M8,10h2v1h-2z M10,10h4v1h-4z M14,10h1v1h-1z M5,11h1v1h-1z M6,11h1v1h-1z M7,11h2v1h-2z M9,11h4v1h-4z M13,11h1v1h-1z M5,12h1v1h-1z M6,12h2v1h-2z M8,12h4v1h-4z M12,12h1v1h-1z M5,13h1v1h-1z M6,13h1v1h-1z M7,13h2v1h-2z M9,13h3v1h-3z M4,14h1v1h-1z M5,14h1v1h-1z M6,14h3v1h-3z M3,15h1v1h-1z M4,15h1v1h-1z M5,15h1v1h-1z M2,16h1v1h-1z M3,16h1v1h-1z M4,16h1v1h-1z M3,17h1v1h-1z M15,14h5v1h-5z M15,15h1v1h-1z M19,15h1v1h-1z M15,16h1v1h-1z M19,16h1v1h-1z M15,17h1v1h-1z M19,17h1v1h-1z M15,18h1v1h-1z M19,18h1v1h-1z M15,19h1v1h-1z M17,19h1v1h-1z M19,19h1v1h-1z M15,20h5v1h-5z"/>
|
||||
</group>
|
||||
</vector>
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas pro Android</string>
|
||||
<string name="share_label">Zeptat se LLeMbas</string>
|
||||
<string name="tile_ask">Zeptat se LLeMbas</string>
|
||||
<string name="signin_intro">Přihlaste se k instanci LLeMbas. Tento telefon schválíte v prohlížeči, stejně jako u CLI.</string>
|
||||
<string name="signin_intro">Přihlaste se k instanci LLeMbas. Tento telefon schválíte v prohlížeči.</string>
|
||||
<string name="signin_address">Adresa instance</string>
|
||||
<string name="signin_continue">Pokračovat</string>
|
||||
<string name="signin_code_intro">Otevřete instanci v prohlížeči, přihlaste se a schvalte tento kód:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Tato instance je novější, než s jakou tato aplikace umí pracovat. Aktualizujte aplikaci.</string>
|
||||
<string name="signin_not_lembas">Na této adrese není žádná instance LLeMbas.</string>
|
||||
<string name="signin_failed">Přihlášení se nepodařilo dokončit (%1$s). Zkuste to znovu.</string>
|
||||
<string name="signin_app_too_old">Tato instance potřebuje LLeMbas pro Android %1$s nebo novější, a toto je %2$s. Aktualizujte aplikaci.</string>
|
||||
<string name="signin_other_origin">Tato instance uvádí pro přihlášení jinou adresu (%1$s), než jakou jste zadali. Její proxy musí předávat adresu, na které je dostupná.</string>
|
||||
<string name="address_needs_https">Tato aplikace potřebuje adresu https://: prosté http není podporováno.</string>
|
||||
<string name="address_unreadable">Tuto adresu aplikace nedokáže použít. Zadejte adresu instance, například llm.example.org.</string>
|
||||
<string name="server_answered">Server odpověděl %1$s.</string>
|
||||
<string name="timed_out">Instance neodpověděla včas.</string>
|
||||
<string name="not_trusted">Tento telefon nedůvěřuje certifikátu instance: nainstalujte certifikát její certifikační autority mezi uživatelské certifikáty Androidu (Nastavení, Zabezpečení, Šifrování a pověření, Instalovat certifikát).</string>
|
||||
<string name="signed_out">%1$s tento telefon odhlásila. Přihlaste se znovu a pokračujte: vaše konverzace i zdejší nastavení zůstávají.</string>
|
||||
<string name="signed_out_again">Přihlásit se znovu</string>
|
||||
<string name="signed_out_use">Použít %1$s</string>
|
||||
<string name="signed_out_remove">Odebrat tuto instanci</string>
|
||||
<string name="new_chat">Nová konverzace</string>
|
||||
<string name="empty_chats">Zatím žádné konverzace. Ne všichni, kdo bloudí, jsou ztraceni — založte jednu.</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="agent_device">Počítač</string>
|
||||
<string name="agent_no_device">Právě není propojený žádný počítač. Spusťte službu LLeMbas CLI (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 počítači</string>
|
||||
<string name="agent_directory_hint">Prázdné: první složka počítače</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>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Pokračovat</string>
|
||||
<string name="older">Starší zprávy</string>
|
||||
<string name="queued">Čeká na odeslání</string>
|
||||
<string name="fate_unknown">Není známo, zda se tato zpráva dostala do počítače. Odešlete ji znovu, nebo ji zahoďte.</string>
|
||||
<string name="fate_carried">Počítač tuto zprávu má a převezme ji při svém dalším tahu.</string>
|
||||
<string name="send_now">Odeslat teď</string>
|
||||
<string name="discard_message_confirm">Zahodit tuto zprávu?</string>
|
||||
<string name="reply_unrecorded">Odpověď na toto nebyla zaznamenána.</string>
|
||||
<string name="thinking">Přemýšlí</string>
|
||||
<string name="thought">Přemýšlel</string>
|
||||
<string name="output_cut">Výstup je zde zkrácen. Celý ho najdete na webové stránce.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Přepsal %1$s: vlastní model řeči této konverzace neodpověděl.</string>
|
||||
<string name="read_by_fallback">Přečetl %1$s: vlastní model řeči této konverzace neodpověděl.</string>
|
||||
<string name="remove">Odebrat</string>
|
||||
<string name="more">Více</string>
|
||||
<string name="back">Zpět</string>
|
||||
@@ -136,19 +156,19 @@
|
||||
<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_hint">Čísla počítají i vlastního agenta této konverzace: 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="subagents_named_only">Tento model obslouží jen jeden požadavek najednou: podagenti potřebují jiný model, na jiném serveru, pojmenovaný v konverzaci.</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_open">Otevřít konverzace</string>
|
||||
<string name="chats_search">Hledat v konverzacích</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_agents">Agentní konverzace</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="chats_none_found">Žádná konverzace 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>
|
||||
@@ -191,7 +211,7 @@
|
||||
<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">Nastavení upozornění</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>
|
||||
@@ -208,7 +228,7 @@
|
||||
<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_delete_confirm">Smazat tento plán? Jeho dřívější výsledky zůstanou ve svých konverzacích.</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>
|
||||
@@ -234,8 +254,8 @@
|
||||
<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="mode_fresh">Pokaždé nová konverzace</string>
|
||||
<string name="mode_continue">Jedna konverzace, 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>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Tato instance 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="files_upload">Nahrát</string>
|
||||
<string name="files_new_file">Nový soubor</string>
|
||||
<string name="files_new_file_ask">Jak se má soubor jmenovat? I s příponou, například notes.md.</string>
|
||||
<string name="files_new_folder_ask">Jak se má složka jmenovat?</string>
|
||||
<string name="files_bad_name">Název nesmí být prázdný ani obsahovat lomítko.</string>
|
||||
<string name="files_taken">Něco s názvem %1$s tu už je.</string>
|
||||
<string name="rename">Přejmenovat</string>
|
||||
<string name="files_new_name">Nový název</string>
|
||||
<string name="files_move">Přesunout</string>
|
||||
<string name="files_copy_to">Kopírovat do…</string>
|
||||
<string name="files_move_here">Přesunout sem</string>
|
||||
<string name="files_copy_here">Kopírovat sem</string>
|
||||
<string name="files_move_which">Do které složky přesunout?</string>
|
||||
<string name="files_copy_which">Do které složky kopírovat?</string>
|
||||
<string name="files_choose_folder">Vybrat složku</string>
|
||||
<string name="files_save_here">Uložit sem</string>
|
||||
<string name="files_no_folders">Nejsou tu žádné složky.</string>
|
||||
<string name="files_to_trash">Přesunout do koše</string>
|
||||
<string name="files_trash_one">Přesunout „%1$s“ do koše? Odtamtud ho lze obnovit.</string>
|
||||
<string name="files_trash_many">Přesunout vybrané (%1$s) do koše? Odtud je lze obnovit.</string>
|
||||
<string name="files_trashed">Přesunuto do koše.</string>
|
||||
<string name="files_selected">Vybráno: %1$s</string>
|
||||
<string name="files_select_all">Vybrat vše</string>
|
||||
<string name="download">Stáhnout</string>
|
||||
<string name="files_download_zip">Stáhnout jako zip</string>
|
||||
<string name="files_downloading">Stahuje se…</string>
|
||||
<string name="files_downloaded">Staženo.</string>
|
||||
<string name="files_uploading">Nahrává se %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Nahráno.</string>
|
||||
<string name="files_open_with">Otevřít v…</string>
|
||||
<string name="files_no_app">Žádná aplikace v tomto telefonu tento druh souboru neotevře.</string>
|
||||
<string name="trash">Koš</string>
|
||||
<string name="trash_is_empty">Koš je prázdný.</string>
|
||||
<string name="trash_empty">Vysypat koš</string>
|
||||
<string name="trash_empty_confirm">Trvale odstranit vše v koši? Nelze to vrátit zpět.</string>
|
||||
<string name="trash_remove">Odstranit trvale</string>
|
||||
<string name="trash_remove_confirm">Trvale odstranit „%1$s“? Nelze to vrátit zpět.</string>
|
||||
<string name="restore">Obnovit</string>
|
||||
<string name="versions">Verze</string>
|
||||
<string name="version_restore">Obnovit tuto verzi</string>
|
||||
<string name="version_restore_confirm">Udělat z této verze aktuální? Ta současná zůstane v seznamu.</string>
|
||||
<string name="version_current">Aktuální</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Velikost</string>
|
||||
<string name="files_no_viewer">Pro tento druh souboru není prohlížeč.</string>
|
||||
<string name="files_not_shown">Tento soubor se zde nepodařilo zobrazit. Stále jej lze stáhnout.</string>
|
||||
<string name="files_svg_source">Toto je zdroj obrázku. Chcete-li vidět obrázek, otevřete jej v jiné aplikaci.</string>
|
||||
<string name="archive_note">Obsah tohoto druhu archivu zde nelze vypsat.</string>
|
||||
<string name="archive_entries">Položek: %1$s. Nic se zde nerozbaluje.</string>
|
||||
<string name="archive_cut">Vypsáno je jen prvních %1$s položek.</string>
|
||||
<string name="archive_unreadable">Tento archiv se nepodařilo přečíst.</string>
|
||||
<string name="files_waiting">Čeká se, až bude aplikace otevřená a telefon odemčený.</string>
|
||||
<string name="share_refused">Něco ze sdíleného odsud odeslat nelze a bylo vynecháno.</string>
|
||||
<string name="media_in_trash">Tento soubor je v koši.</string>
|
||||
<string name="table_cut">Do tabulky jsou rozloženy jen první řádky a sloupce. Text obsahuje vše.</string>
|
||||
<string name="table_as_text">Zobrazit jako text</string>
|
||||
<string name="table_as_table">Zobrazit jako tabulku</string>
|
||||
<string name="media_open_in_files">Otevřít v Souborech</string>
|
||||
<string name="media_image">Obrázek</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Zvuk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiv</string>
|
||||
<string name="media_text">Textový soubor</string>
|
||||
<string name="media_binary">Soubor</string>
|
||||
<string name="diff_deleted">Smazáno</string>
|
||||
<string name="diff_counts">Přidané řádky: %1$s, odebrané: %2$s</string>
|
||||
<string name="diff_show_all">Zobrazit všechny řádky (%1$s)</string>
|
||||
<string name="diff_show_less">Zobrazit méně</string>
|
||||
<string name="diff_more">Další řádky, které se zde nezobrazují: %1$s.</string>
|
||||
<string name="diff_endings">Konce řádků se mění z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Tato změna je příliš dlouhá na to, aby se zde porovnala. Zobrazen je jen její začátek.</string>
|
||||
<string name="media_gone">Tento soubor už neexistuje.</string>
|
||||
<string name="job_queued">Ve frontě</string>
|
||||
<string name="job_running">Běží</string>
|
||||
<string name="job_done">Hotovo</string>
|
||||
<string name="job_failed">Selhalo</string>
|
||||
<string name="job_cancelled">Zrušeno</string>
|
||||
<string name="job_expired">Vypršelo</string>
|
||||
<string name="mcp_title">Servery MCP</string>
|
||||
<string name="mcp_intro">Servery, jejichž nástroje mohou být nabídnuty ve vašich konverzacích. Některé se používají s vaším vlastním účtem u nich: jejich nástroje jsou nabízeny, dokud jste přihlášeni.</string>
|
||||
<string name="mcp_none">Na této instanci vám nejsou nabízeny žádné servery MCP.</string>
|
||||
<string name="mcp_ready">Připraveno</string>
|
||||
<string name="mcp_signed_in">Přihlášeno</string>
|
||||
<string name="mcp_signed_out">Nepřihlášeno</string>
|
||||
<string name="mcp_needs_signin">Je potřeba nové přihlášení</string>
|
||||
<string name="mcp_tools">Nástroje: %1$s</string>
|
||||
<string name="mcp_account">Přihlášeno jako %1$s</string>
|
||||
<string name="mcp_until">Přihlášeno do %1$s</string>
|
||||
<string name="mcp_shared_note">Tento server má jedno společné přihlášení, které provádí správce.</string>
|
||||
<string name="mcp_browser_note">Přihlášení probíhá v prohlížeči, přímo na instanci. Pokud prohlížeč není k instanci přihlášen, nejprve si to vyžádá. Potom se vraťte sem.</string>
|
||||
<string name="mcp_sign_in">Přihlásit se</string>
|
||||
<string name="notebook_empty">Tento zápisník nemá žádné buňky.</string>
|
||||
<string name="notebook_more">Dalších %1$s buněk se nezobrazuje.</string>
|
||||
<string name="notebook_cell_cut">Tato buňka je delší, než se zde zobrazuje.</string>
|
||||
<string name="viewer_page">Strana %1$s z %2$s</string>
|
||||
<string name="play">Přehrát</string>
|
||||
<string name="pause">Pozastavit</string>
|
||||
<string name="files_conflict">Soubor se od otevření změnil. Načtěte ho znovu, nebo přesto uložte.</string>
|
||||
<string name="files_save_anyway">Přesto uložit</string>
|
||||
<string name="reload">Načíst znovu</string>
|
||||
<string name="discard">Zahodit</string>
|
||||
<string name="files_unsaved">Zahodit změny v tomto souboru?</string>
|
||||
<string name="share_to_files">Uložit do Souborů</string>
|
||||
<string name="settings">Nastavení</string>
|
||||
<string name="settings_instances">Instance</string>
|
||||
<string name="sign_out">Odhlásit se</string>
|
||||
<string name="add_instance">Přidat instanci</string>
|
||||
<string name="instance_default">Výchozí</string>
|
||||
<string name="instance_set_default">Nastavit jako výchozí</string>
|
||||
<string name="instance_switch">Přepnout instanci</string>
|
||||
<string name="settings_theme">Vzhled</string>
|
||||
<string name="theme_system">Podle systému</string>
|
||||
<string name="theme_moria">Moria (temná)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.</string>
|
||||
<string name="assistant_open_settings">Otevřít nastavení asistenta</string>
|
||||
<string name="assistant_model">Model asistenta</string>
|
||||
<string name="assistant_model_default">Výchozí model instance</string>
|
||||
<string name="assistant_model_default_line">Model, se kterým začínají vaše nové konverzace. Je-li na mluvenou otázku příliš pomalý, vyberte níže rychlejší.</string>
|
||||
<string name="assistant_samsung">Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.</string>
|
||||
<string name="assistant_temporary">Konverzace s asistentem jsou dočasné</string>
|
||||
<string name="assistant_read_aloud">Přečíst odpověď nahlas, když se zeptáte hlasem</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Nejvýš jednou denně, při spuštění, se aplikace zeptá vaší instance, které vydání k ní patří — nebo si přečte seznam vydání na GitHubu, když to instance říct neumí — a upozorněním vám dá vědět, když je k dispozici novější. S žádným z těch dotazů se o vás nic 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>
|
||||
@@ -421,13 +553,20 @@
|
||||
<string name="assist_say_it">Řekněte to a odmlčte se</string>
|
||||
<string name="assist_type">Raději psát</string>
|
||||
<string name="assist_writing_down">Zapisuji, co jste řekli…</string>
|
||||
<string name="assist_unlock_to_send">Odemknout a odeslat</string>
|
||||
<string name="assist_question_heard">Otázka zaznamenána</string>
|
||||
<string name="assist_recording_waits_line">Telefon je zamčený. Vaše otázka čeká v tomto telefonu jako nahrávka; nic se neodeslalo. Po odemknutí se odešle vaší instanci, která ji přepíše a odpoví.</string>
|
||||
<string name="assist_locked_line">Telefon je zamčený. Dokud ho neodemknete, nic se neodešle a žádná odpověď se nezobrazí.</string>
|
||||
<string name="assist_conversation">Rozhovor</string>
|
||||
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
|
||||
<string name="assist_conversation_end">Ukončit</string>
|
||||
<string name="assist_stop_words">stop|dost|to je vše|to je všechno|konec|nashledanou|díky to je vše|zrušit|stop stop</string>
|
||||
<string name="assistant_conversation">Pokračovat v mluveném rozhovoru</string>
|
||||
<string name="assistant_conversation_line">Po přečtení mluvené odpovědi asistent znovu poslouchá — dokud neřeknete „stop“, neklepnete na Ukončit nebo pár sekund nic neřeknete. Funguje i se sluchátky.</string>
|
||||
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Asistent › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
|
||||
<string name="experimental">Experimentální</string>
|
||||
<string name="wake_experimental_line">Novinka, zatím vyzkoušená jen na několika telefonech. Může frázi přeslechnout, spustit se omylem, nebo vás uslyšet a asistenta přesto neotevřít.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimentální: samočinné poslouchání po otevření asistenta, rozpoznání, že jste domluvili, a mluvený rozhovor jsou nové a zatím nefungují dobře na každém telefonu. Napsat otázku a tlačítko mikrofonu fungují vždy.</string>
|
||||
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
|
||||
<string name="channel_wake">Budicí slovo</string>
|
||||
<string name="wake_word">Budicí slovo</string>
|
||||
<string name="wake_word_listen">Naslouchat budicímu slovu</string>
|
||||
@@ -454,8 +593,8 @@
|
||||
<string name="wake_screen_only_line">Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie.</string>
|
||||
<string name="wake_battery">Nechat běžet na pozadí</string>
|
||||
<string name="wake_battery_line">Některé telefony (Samsung, Xiaomi, Huawei, OnePlus a další) kvůli baterii zastavují aplikace na pozadí, a s nimi i budicí slovo. Zde vyjměte LLeMbas z optimalizace baterie; dontkillmyapp.com vysvětluje nastavení vašeho telefonu.</string>
|
||||
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět oznámení. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.</string>
|
||||
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět upozornění. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na upozornění.</string>
|
||||
<string name="wake_listening_for">Naslouchám frázi „%1$s“</string>
|
||||
<string name="wake_off">Budicí slovo neposlouchá</string>
|
||||
<string name="wake_tap_to_start">Klepnutím ho znovu spustíte. Pokud se Android zeptá, povolte mikrofon.</string>
|
||||
@@ -476,7 +615,7 @@
|
||||
<string name="channel_wake_heard">Budicí slovo zaznělo</string>
|
||||
<string name="wake_heard_line">LLeMbas se umí sám otevřít nad jinými aplikacemi jen jako aplikace digitálního asistenta v telefonu.</string>
|
||||
<string name="wake_not_assistant">LLeMbas není aplikací digitálního asistenta</string>
|
||||
<string name="wake_not_assistant_line">Budicí slovo proto nemůže otevřít asistenta nad jinými aplikacemi: dostanete oznámení, na které klepnete. Chcete-li otevírat hlasem kdekoli, klepněte sem a vyberte LLeMbas jako aplikaci digitálního asistenta.</string>
|
||||
<string name="wake_not_assistant_line">Budicí slovo proto nemůže otevřít asistenta nad jinými aplikacemi: dostanete upozornění, na které klepnete. Chcete-li otevírat hlasem kdekoli, klepněte sem a vyberte LLeMbas jako aplikaci digitálního asistenta.</string>
|
||||
<string name="wake_last">Poslední probuzení</string>
|
||||
<string name="wake_last_none">Frázi zatím neslyšel.</string>
|
||||
<string name="wake_out_opened">Otevřel asistenta.</string>
|
||||
@@ -484,7 +623,7 @@
|
||||
<string name="wake_out_not_connected">Android neměl LLeMbas připojený jako asistenta, proto panel nemohl otevřít.</string>
|
||||
<string name="wake_out_refused">Android odmítl otevřít asistenta: %1$s</string>
|
||||
<string name="wake_out_activity">Místo toho ho otevřel jako obrazovku aplikace.</string>
|
||||
<string name="wake_out_notification">Místo toho poslal oznámení, na které je třeba klepnout.</string>
|
||||
<string name="wake_out_notification">Místo toho poslal upozornění, na které je třeba klepnout.</string>
|
||||
<string name="wake_out_tested">Slyšeno při zkoušce: nebylo co otevírat.</string>
|
||||
<string name="wake_role_held">LLeMbas byl aplikací digitálního asistenta.</string>
|
||||
<string name="wake_role_not_held">LLeMbas nebyl aplikací digitálního asistenta.</string>
|
||||
@@ -498,24 +637,24 @@
|
||||
<string name="wake_waited">Chvíli čekal, až ho Android připojí.</string>
|
||||
<string name="wake_show_failed">Android oznámil, že panel asistenta nedokázal zobrazit.</string>
|
||||
<string name="wake_assistant_inactive">Android právě nepoužívá LLeMbas jako hlasového asistenta</string>
|
||||
<string name="wake_assistant_inactive_line">Vyberte LLeMbas jako aplikaci digitálního asistenta znovu: klepněte sem, zvolte jinou aplikaci a potom LLeMbas. Do té doby ho dlouhé stisknutí otevírá jako běžnou obrazovku a budicí slovo může poslat jen oznámení.</string>
|
||||
<string name="wake_assistant_inactive_line">Vyberte LLeMbas jako aplikaci digitálního asistenta znovu: klepněte sem, zvolte jinou aplikaci a potom LLeMbas. Do té doby ho dlouhé stisknutí otevírá jako běžnou obrazovku a budicí slovo může poslat jen upozornění.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas je asistent, ale Android ho právě nemá připojeného</string>
|
||||
<string name="wake_assistant_unbound_line">Dokud ho nepřipojí, budicí slovo nemůže panel otevřít samo. Klepnutím otevřete systémové nastavení asistenta: vyberte jinou aplikaci a potom znovu LLeMbas, tím se připojí.</string>
|
||||
<string name="wake_heard_could_not">Nepodařilo se otevřít samo — klepněte a ptejte se</string>
|
||||
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
|
||||
<string name="wake_resume_line">Telefon se restartoval. Klepnutím znovu spustíte naslouchání.</string>
|
||||
<string name="assist_notifications">Shrnout má oznámení</string>
|
||||
<string name="assist_notifications_prompt">Shrň moje oznámení: co potřebuje mou pozornost?</string>
|
||||
<string name="assist_notifications_phrases">moje oznámení|má oznámení|mých oznámení|moje notifikace</string>
|
||||
<string name="notification_summaries">Shrnutí oznámení</string>
|
||||
<string name="notification_summaries_switch">Dovolit asistentovi číst má oznámení, když o to požádám</string>
|
||||
<string name="notification_summaries_line">Řekněte „shrň moje oznámení“, nebo klepněte na tlačítko v asistentovi.</string>
|
||||
<string name="notification_summaries_unavailable">V tomto sestavení není. Čtení oznámení vyžaduje sestavení LLeMbas „notifications“, protože Google Play Protect blokuje instalaci aplikace mimo Obchod Play, která je umí číst. Je to stejná aplikace se stejným podpisem: na stránce vydání se soubor končící na -notifications.apk nainstaluje přes tuto.</string>
|
||||
<string name="assist_notifications">Shrnout má upozornění</string>
|
||||
<string name="assist_notifications_prompt">Shrň moje upozornění: co potřebuje mou pozornost?</string>
|
||||
<string name="assist_notifications_phrases">moje upozornění|má upozornění|mých upozornění|moje oznámení|má oznámení|mých oznámení|moje notifikace</string>
|
||||
<string name="notification_summaries">Shrnutí upozornění</string>
|
||||
<string name="notification_summaries_switch">Dovolit asistentovi číst má upozornění, když o to požádám</string>
|
||||
<string name="notification_summaries_line">Řekněte „shrň moje upozornění“, nebo klepněte na tlačítko v asistentovi.</string>
|
||||
<string name="notification_summaries_unavailable">V tomto sestavení není. Čtení upozornění vyžaduje sestavení LLeMbas „notifications“, protože Google Play Protect blokuje instalaci aplikace mimo Obchod Play, která je umí číst. Je to stejná aplikace se stejným podpisem: na stránce vydání se soubor končící na -notifications.apk nainstaluje přes tuto.</string>
|
||||
<string name="update_notifications_manual">Toto je sestavení „notifications“: aktualizaci nainstalujte ze stránky vydání, soubor končící na -notifications.apk.</string>
|
||||
<string name="notification_access">Přístup k oznámením</string>
|
||||
<string name="notification_access">Přístup k upozorněním</string>
|
||||
<string name="notification_access_on">Uděleno. Přepínač Androidu je v systémovém nastavení.</string>
|
||||
<string name="notification_access_off">Zatím neuděleno. Klepnutím otevřete přepínač Androidu pro LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Ve výchozím stavu vypnuto. Když požádáte, text oznámení, která jsou v telefonu právě teď (aplikace, název, text), půjde s touto jedinou otázkou na vaši instanci a její model. Dřív se nic nečte, aplikace si nic neponechá a při zamčeném telefonu se nečte nic. Přístup k oznámením v Androidu dovolí aplikaci vidět každé oznámení, proto je na vás, zda ho dáte a zase vezmete.</string>
|
||||
<string name="notification_summaries_privacy">Ve výchozím stavu vypnuto. Když požádáte, text upozornění, která jsou v telefonu právě teď (aplikace, název, text), půjde s touto jedinou otázkou na vaši instanci a její model. Dřív se nic nečte, aplikace si nic neponechá a při zamčeném telefonu se nečte nic. Přístup k upozorněním v Androidu dovolí aplikaci vidět každé upozornění, proto je na vás, zda ho dáte a zase vezmete.</string>
|
||||
<string name="nav_app">Navigační aplikace</string>
|
||||
<string name="nav_app_auto">Ta, která je nainstalovaná</string>
|
||||
<string name="nav_app_google">Mapy Google</string>
|
||||
@@ -546,16 +685,53 @@
|
||||
<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_lembas_line">Převod řeči na text vaší instance. Tento telefon posílá nahrávku jen vaší instanci; ta ji přepíše modelem řeči, který je v ní nastaven.</string>
|
||||
<string name="voice_input_phone">Telefon (Google nebo systémový)</string>
|
||||
<string name="voice_input_phone_line">Vlastní rozpoznávání řeči v telefonu. Slova se objevují, jak mluvíte; nahrávka jde tam, kam ji to rozpoznávání pošle.</string>
|
||||
<string name="voice_input_phone_none">Tento telefon nemá vlastní rozpoznávání řeči.</string>
|
||||
<string name="voice_input_hint">Používá ho asistent i mikrofon v konverzaci. S LLeMbas asistent ukazuje slova s malým zpožděním a pauza je odešle, konverzace je zapíše, když přestanete; s rozpoznáváním v telefonu se objevují, jak mluvíte.</string>
|
||||
<string name="share_sending">Odesílá se do LLeMbas…</string>
|
||||
<string name="share_default_prompt">Podívejte se na tohle.</string>
|
||||
<string name="share_default_prompt">Podívej se na tohle.</string>
|
||||
<string name="share_ask_hint">Co s tím má LLeMbas udělat? (nepovinné)</string>
|
||||
<string name="widget_hint">Zeptejte se na cokoli</string>
|
||||
<string name="directory_places">Místa na tomto zařízení</string>
|
||||
<string name="directory_last_used">Naposledy zde použitý: %1$s. Nový chat v této složce začne na něm, pokud nevyberete jiný.</string>
|
||||
<string name="directory_refused">Zařízení tu relaci neotevře.</string>
|
||||
<string name="directory_up">O úroveň výš</string>
|
||||
<string name="directory_all_places">Všechna místa</string>
|
||||
<string name="directory_not_trusted">Na zařízení není důvěryhodné</string>
|
||||
<string name="directory_empty">Nejsou tu žádné složky.</string>
|
||||
<string name="directory_no_places">Toto zařízení nenabízí žádné složky: jeho vzdálené kořeny jsou prázdné nebo chybějí.</string>
|
||||
<string name="directory_browse">Procházet</string>
|
||||
<string name="directory_path">Úplná cesta</string>
|
||||
<string name="directory_choose">Vybrat</string>
|
||||
<string name="directory_no_listing">Adresáře tohoto zařízení teď nelze vypsat. Napište cestu níže.</string>
|
||||
<string name="model">Model</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Konverzace</string>
|
||||
<string name="schedule_chat_line">Běží na tomto serveru jako chat: s nástroji serveru (vyhledávání, vaše soubory zde, paměť) a na modelu určeném pro plánování.</string>
|
||||
<string name="schedule_agentic">Agentní</string>
|
||||
<string name="schedule_agentic_line">Běží na jednom z vašich počítačů, v jedné složce na něm, jako agent: s nástroji agenta na tom počítači — jeho soubory a jeho shellem — v rámci vlastních omezení počítače. Patří k tomu počítači a složce.</string>
|
||||
<string name="schedule_agentic_unavailable">Žádný z vašich počítačů teď nepřijímá naplánovanou práci. Propojte některý a zapněte „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nepřijímá plánovanou práci</string>
|
||||
<string name="schedule_computer_hint">Počítač to musí povolit: „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). Když v čase spuštění není propojen, spuštění na něj počká; pokud se nevrátí, než čas spuštění uplyne, spuštění se zaznamená jako zmeškané a dozvíte se o tom.</string>
|
||||
<string name="schedule_computer_gone">počítač, který už není přihlášen</string>
|
||||
<string name="schedule_folder">Složka na počítači</string>
|
||||
<string name="schedule_agent_mode">Režim</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, pokud nezvolíte jinak; Auto spouští příkazy bez ptaní. Počítač ho může snížit.</string>
|
||||
<string name="schedule_approval_wait">Schválení čeká (minuty)</string>
|
||||
<string name="schedule_approval_wait_hint">Příkaz, který spuštění potřebuje schválit, přijde do telefonu jako karta. Pokud do té doby nebude zodpovězen, počítá se jako zamítnutý.</string>
|
||||
<string name="schedule_watch_command_hint">Volitelné, na počítači. Spustí se ve složce před každým spuštěním; když je jeho výstup stejný jako minule, spuštění tam skončí. Příkaz, na který by se režim ptal, se odmítne.</string>
|
||||
<string name="schedule_watch_timeout">Příkaz může trvat (sekundy)</string>
|
||||
<string name="schedule_watch_timeout_hint">Pak se zastaví a spuštění selže.</string>
|
||||
<string name="schedule_chat_drops_watch">Tato úloha sleduje příkaz na svém počítači. Jako úloha typu Konverzace už ne: spustí se pokaždé.</string>
|
||||
<string name="schedule_folder_model">Obvyklý model složky</string>
|
||||
<string name="schedule_folder_model_hint">Obvyklý model složky je ten, který jste v té složce na tom počítači použili naposledy — počítač si ho pamatuje a každé spuštění se ho na něj zeptá — nebo váš výchozí model, pokud žádný není. Model vybraný zde je modelem spuštění, ať je model složky jakýkoli. Spuštění nikdy nemění model složky.</string>
|
||||
<string name="schedule_first_free_model">První volný z vašich modelů pro plánování</string>
|
||||
<string name="run_model_directory">obvyklý model složky</string>
|
||||
<string name="run_model_default">váš výchozí model</string>
|
||||
<string name="run_model_session">vlastní model konverzace</string>
|
||||
<string name="widget_speak">Mluvit</string>
|
||||
<string name="widget_description">Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.</string>
|
||||
<string name="shortcut_last">Poslední chat</string>
|
||||
<string name="shortcut_last">Poslední konverzace</string>
|
||||
</resources>
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas für Android</string>
|
||||
<string name="share_label">LLeMbas fragen</string>
|
||||
<string name="tile_ask">LLeMbas fragen</string>
|
||||
<string name="signin_intro">Melden Sie sich bei einer LLeMbas-Instanz an. Sie bestätigen dieses Telefon im Browser, genau wie bei der CLI.</string>
|
||||
<string name="signin_intro">Melden Sie sich bei einer LLeMbas-Instanz an. Sie bestätigen dieses Telefon im Browser.</string>
|
||||
<string name="signin_address">Adresse der Instanz</string>
|
||||
<string name="signin_continue">Fortsetzen</string>
|
||||
<string name="signin_code_intro">Öffnen Sie die Instanz im Browser, melden Sie sich an und bestätigen Sie diesen Code:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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">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="signin_too_new">Diese Instanz ist neuer, als diese App es unterstützt. Aktualisieren Sie die App.</string>
|
||||
<string name="signin_not_lembas">Unter dieser Adresse gibt es keine LLeMbas-Instanz.</string>
|
||||
<string name="signin_failed">Die Anmeldung konnte nicht abgeschlossen werden (%1$s). Versuchen Sie es erneut.</string>
|
||||
<string name="signin_app_too_old">Diese Instanz braucht LLeMbas für Android %1$s oder neuer, und dies ist %2$s. Aktualisieren Sie die App.</string>
|
||||
<string name="signin_other_origin">Diese Instanz nennt für die Anmeldung eine andere Adresse (%1$s) als die eingegebene. Ihr Proxy muss die Adresse weitergeben, unter der sie erreicht wird.</string>
|
||||
<string name="address_needs_https">Diese App braucht eine https://-Adresse: einfaches http wird nicht unterstützt.</string>
|
||||
<string name="address_unreadable">Diese Adresse kann die App nicht verwenden. Geben Sie die Adresse der Instanz ein, zum Beispiel llm.example.org.</string>
|
||||
<string name="server_answered">Der Server hat mit %1$s geantwortet.</string>
|
||||
<string name="timed_out">Die Instanz hat nicht rechtzeitig geantwortet.</string>
|
||||
<string name="not_trusted">Dieses Telefon vertraut dem Zertifikat der Instanz nicht: Installieren Sie das Zertifikat ihrer Zertifizierungsstelle unter den Nutzerzertifikaten von Android (Einstellungen, Sicherheit, Verschlüsselung & Anmeldedaten, Zertifikat installieren).</string>
|
||||
<string name="signed_out">%1$s hat dieses Telefon abgemeldet. Melden Sie sich erneut an, um fortzufahren: Ihre Chats und Ihre Einstellungen hier bleiben erhalten.</string>
|
||||
<string name="signed_out_again">Erneut anmelden</string>
|
||||
<string name="signed_out_use">%1$s verwenden</string>
|
||||
<string name="signed_out_remove">Diese Instanz entfernen</string>
|
||||
<string name="new_chat">Neuer Chat</string>
|
||||
<string name="empty_chats">Noch keine Chats. Nicht jeder, der wandert, ist verloren — fangen Sie einen an.</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="agent_device">Computer</string>
|
||||
<string name="agent_no_device">Gerade ist kein Computer verknüpft. Starten Sie den Dienst der LLeMbas-CLI (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 Computer</string>
|
||||
<string name="agent_directory_hint">Leer: der erste Ordner des Computers</string>
|
||||
<string name="empty_chat">Worüber sprechen wir?</string>
|
||||
<string name="loading_line">Lembas wird gebacken…</string>
|
||||
<string name="archive">Archivieren</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Fortsetzen</string>
|
||||
<string name="older">Frühere Nachrichten</string>
|
||||
<string name="queued">Wartet auf das Senden</string>
|
||||
<string name="fate_unknown">Es ist nicht bekannt, ob dies den Computer erreicht hat. Senden Sie es erneut oder verwerfen Sie es.</string>
|
||||
<string name="fate_carried">Der Computer hat diese Nachricht und übernimmt sie bei seinem nächsten Zug.</string>
|
||||
<string name="send_now">Jetzt senden</string>
|
||||
<string name="discard_message_confirm">Diese Nachricht verwerfen?</string>
|
||||
<string name="reply_unrecorded">Die Antwort darauf wurde nicht aufgezeichnet.</string>
|
||||
<string name="thinking">Denkt nach</string>
|
||||
<string name="thought">Nachgedacht</string>
|
||||
<string name="output_cut">Die Ausgabe ist hier verkürzt. Vollständig finden Sie sie auf der Webseite.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Transkribiert von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.</string>
|
||||
<string name="read_by_fallback">Vorgelesen von %1$s: Das eigene Sprachmodell dieses Chats hat nicht geantwortet.</string>
|
||||
<string name="remove">Entfernen</string>
|
||||
<string name="more">Mehr</string>
|
||||
<string name="back">Zurück</string>
|
||||
@@ -150,12 +170,12 @@
|
||||
<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="composer_hint_agent">Sagen Sie 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="plan_first_hint">Das Modell schreibt einen Plan, den Sie genehmigen, 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>
|
||||
@@ -209,7 +229,7 @@
|
||||
<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_hint">Sagen Sie in eigenen Worten, wann und was. Bevor etwas gespeichert wird, sehen Sie, 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>
|
||||
@@ -245,11 +265,11 @@
|
||||
<string name="scheduled_result_public">Eine geplante Aufgabe hat ein Ergebnis.</string>
|
||||
<string name="scheduled_failed_public">Eine geplante Aufgabe ist fehlgeschlagen.</string>
|
||||
<string name="page_note">Diese Antwort hat eine Seite: %1$s</string>
|
||||
<string name="page_where">Öffne sie im Web oder in LLeMbas Desktop, um sie zu sehen.</string>
|
||||
<string name="page_where">Öffnen Sie sie im Web oder in LLeMbas Desktop, um sie zu sehen.</string>
|
||||
<string name="page_untitled">Seite</string>
|
||||
<string name="reports">Berichte</string>
|
||||
<string name="report">Bericht</string>
|
||||
<string name="reports_none">Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie dir etwas zu sagen hat.</string>
|
||||
<string name="reports_none">Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie Ihnen etwas zu sagen hat.</string>
|
||||
<string name="reports_unsupported">Auf dieser Instanz läuft ein LLeMbas, das noch keine Berichte hat.</string>
|
||||
<string name="report_untitled">Bericht ohne Titel</string>
|
||||
<string name="report_delete_title">Diesen Bericht löschen?</string>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Diese Instanz 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="files_upload">Hochladen</string>
|
||||
<string name="files_new_file">Neue Datei</string>
|
||||
<string name="files_new_file_ask">Wie soll die Datei heißen? Mit Endung, etwa notes.md.</string>
|
||||
<string name="files_new_folder_ask">Wie soll der Ordner heißen?</string>
|
||||
<string name="files_bad_name">Ein Name darf weder leer sein noch einen Schrägstrich enthalten.</string>
|
||||
<string name="files_taken">Hier gibt es schon etwas namens %1$s.</string>
|
||||
<string name="rename">Umbenennen</string>
|
||||
<string name="files_new_name">Neuer Name</string>
|
||||
<string name="files_move">Verschieben</string>
|
||||
<string name="files_copy_to">Kopieren nach…</string>
|
||||
<string name="files_move_here">Hierher verschieben</string>
|
||||
<string name="files_copy_here">Hierher kopieren</string>
|
||||
<string name="files_move_which">In welchen Ordner verschieben?</string>
|
||||
<string name="files_copy_which">In welchen Ordner kopieren?</string>
|
||||
<string name="files_choose_folder">Ordner wählen</string>
|
||||
<string name="files_save_here">Hier speichern</string>
|
||||
<string name="files_no_folders">Hier gibt es keine Ordner.</string>
|
||||
<string name="files_to_trash">In den Papierkorb</string>
|
||||
<string name="files_trash_one">„%1$s“ in den Papierkorb verschieben? Von dort lässt es sich wiederherstellen.</string>
|
||||
<string name="files_trash_many">Die %1$s ausgewählten in den Papierkorb verschieben? Von dort lassen sie sich wiederherstellen.</string>
|
||||
<string name="files_trashed">In den Papierkorb verschoben.</string>
|
||||
<string name="files_selected">%1$s ausgewählt</string>
|
||||
<string name="files_select_all">Alle auswählen</string>
|
||||
<string name="download">Herunterladen</string>
|
||||
<string name="files_download_zip">Als Zip herunterladen</string>
|
||||
<string name="files_downloading">Wird heruntergeladen…</string>
|
||||
<string name="files_downloaded">Heruntergeladen.</string>
|
||||
<string name="files_uploading">%1$s von %2$s wird hochgeladen…</string>
|
||||
<string name="files_uploaded">Hochgeladen.</string>
|
||||
<string name="files_open_with">Öffnen mit…</string>
|
||||
<string name="files_no_app">Keine App auf diesem Telefon öffnet diese Art von Datei.</string>
|
||||
<string name="trash">Papierkorb</string>
|
||||
<string name="trash_is_empty">Der Papierkorb ist leer.</string>
|
||||
<string name="trash_empty">Papierkorb leeren</string>
|
||||
<string name="trash_empty_confirm">Alles im Papierkorb endgültig entfernen? Das lässt sich nicht rückgängig machen.</string>
|
||||
<string name="trash_remove">Endgültig entfernen</string>
|
||||
<string name="trash_remove_confirm">„%1$s“ endgültig entfernen? Das lässt sich nicht rückgängig machen.</string>
|
||||
<string name="restore">Wiederherstellen</string>
|
||||
<string name="versions">Versionen</string>
|
||||
<string name="version_restore">Diese Version wiederherstellen</string>
|
||||
<string name="version_restore_confirm">Diese Version zur aktuellen machen? Die jetzige bleibt in der Liste.</string>
|
||||
<string name="version_current">Aktuell</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Größe</string>
|
||||
<string name="files_no_viewer">Für diese Art von Datei gibt es keinen Betrachter.</string>
|
||||
<string name="files_not_shown">Diese Datei konnte hier nicht gezeigt werden. Sie lässt sich weiterhin herunterladen.</string>
|
||||
<string name="files_svg_source">Das ist der Quelltext des Bildes. Öffnen Sie es mit einer anderen App, um das Bild zu sehen.</string>
|
||||
<string name="archive_note">Der Inhalt dieser Art von Archiv kann hier nicht aufgelistet werden.</string>
|
||||
<string name="archive_entries">%1$s Einträge. Hier wird nichts entpackt.</string>
|
||||
<string name="archive_cut">Nur die ersten %1$s Einträge sind aufgelistet.</string>
|
||||
<string name="archive_unreadable">Dieses Archiv konnte nicht gelesen werden.</string>
|
||||
<string name="files_waiting">Wartet, bis die App geöffnet und das Telefon entsperrt ist.</string>
|
||||
<string name="share_refused">Etwas vom Geteilten kann von hier nicht gesendet werden und wurde ausgelassen.</string>
|
||||
<string name="media_in_trash">Diese Datei liegt im Papierkorb.</string>
|
||||
<string name="table_cut">Nur die ersten Zeilen und Spalten sind als Tabelle gesetzt. Der Text enthält alles.</string>
|
||||
<string name="table_as_text">Als Text zeigen</string>
|
||||
<string name="table_as_table">Als Tabelle zeigen</string>
|
||||
<string name="media_open_in_files">In Dateien öffnen</string>
|
||||
<string name="media_image">Bild</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musik</string>
|
||||
<string name="media_model">3D-Modell</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiv</string>
|
||||
<string name="media_text">Textdatei</string>
|
||||
<string name="media_binary">Datei</string>
|
||||
<string name="diff_deleted">Gelöscht</string>
|
||||
<string name="diff_counts">Zeilen hinzugefügt: %1$s, entfernt: %2$s</string>
|
||||
<string name="diff_show_all">Alle %1$s Zeilen anzeigen</string>
|
||||
<string name="diff_show_less">Weniger anzeigen</string>
|
||||
<string name="diff_more">%1$s weitere Zeilen werden hier nicht angezeigt.</string>
|
||||
<string name="diff_endings">Die Zeilenenden ändern sich von %1$s zu %2$s.</string>
|
||||
<string name="diff_cut">Diese Änderung ist zu lang, um hier verglichen zu werden. Nur ihr Anfang wird angezeigt.</string>
|
||||
<string name="media_gone">Diese Datei gibt es nicht mehr.</string>
|
||||
<string name="job_queued">In der Warteschlange</string>
|
||||
<string name="job_running">Läuft</string>
|
||||
<string name="job_done">Fertig</string>
|
||||
<string name="job_failed">Fehlgeschlagen</string>
|
||||
<string name="job_cancelled">Abgebrochen</string>
|
||||
<string name="job_expired">Abgelaufen</string>
|
||||
<string name="mcp_title">MCP-Server</string>
|
||||
<string name="mcp_intro">Die Server, deren Werkzeuge in den eigenen Chats angeboten werden können. Manche werden mit einem eigenen Konto dort genutzt: Deren Werkzeuge werden angeboten, solange die Anmeldung besteht.</string>
|
||||
<string name="mcp_none">Auf dieser Instanz werden keine MCP-Server angeboten.</string>
|
||||
<string name="mcp_ready">Bereit</string>
|
||||
<string name="mcp_signed_in">Angemeldet</string>
|
||||
<string name="mcp_signed_out">Nicht angemeldet</string>
|
||||
<string name="mcp_needs_signin">Neue Anmeldung nötig</string>
|
||||
<string name="mcp_tools">Werkzeuge: %1$s</string>
|
||||
<string name="mcp_account">Angemeldet als %1$s</string>
|
||||
<string name="mcp_until">Angemeldet bis %1$s</string>
|
||||
<string name="mcp_shared_note">Dieser Server hat eine gemeinsame Anmeldung, die ein Administrator vornimmt.</string>
|
||||
<string name="mcp_browser_note">Die Anmeldung geschieht im Browser, auf der Instanz selbst. Ist der Browser dort nicht angemeldet, wird zuerst danach gefragt. Danach hierher zurückkehren.</string>
|
||||
<string name="mcp_sign_in">Anmelden</string>
|
||||
<string name="notebook_empty">Dieses Notebook hat keine Zellen.</string>
|
||||
<string name="notebook_more">%1$s weitere Zellen werden nicht gezeigt.</string>
|
||||
<string name="notebook_cell_cut">Diese Zelle ist länger, als hier gezeigt wird.</string>
|
||||
<string name="viewer_page">Seite %1$s von %2$s</string>
|
||||
<string name="play">Abspielen</string>
|
||||
<string name="pause">Pausieren</string>
|
||||
<string name="files_conflict">Die Datei hat sich geändert, seit Sie sie geöffnet haben. Laden Sie sie neu oder speichern Sie trotzdem.</string>
|
||||
<string name="files_save_anyway">Trotzdem speichern</string>
|
||||
<string name="reload">Neu laden</string>
|
||||
<string name="discard">Verwerfen</string>
|
||||
<string name="files_unsaved">Die Änderungen an dieser Datei verwerfen?</string>
|
||||
<string name="share_to_files">In Dateien speichern</string>
|
||||
<string name="settings">Einstellungen</string>
|
||||
<string name="settings_instances">Instanzen</string>
|
||||
<string name="sign_out">Abmelden</string>
|
||||
<string name="add_instance">Instanz hinzufügen</string>
|
||||
<string name="instance_default">Standard</string>
|
||||
<string name="instance_set_default">Als Standard festlegen</string>
|
||||
<string name="instance_switch">Instanz wechseln</string>
|
||||
<string name="settings_theme">Design</string>
|
||||
<string name="theme_system">Wie das System</string>
|
||||
<string name="theme_moria">Moria (dunkel)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Assistent</string>
|
||||
<string name="assistant_explained">Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.</string>
|
||||
<string name="assistant_open_settings">Assistenten-Einstellungen öffnen</string>
|
||||
<string name="assistant_model">Modell des Assistenten</string>
|
||||
<string name="assistant_model_default">Standard der Instanz</string>
|
||||
<string name="assistant_model_default_line">Das Modell, mit dem Ihre neuen Chats beginnen. Ist es für eine gesprochene Frage zu langsam, wählen Sie unten ein schnelleres.</string>
|
||||
<string name="assistant_samsung">Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.</string>
|
||||
<string name="assistant_temporary">Assistenten-Chats sind temporär</string>
|
||||
<string name="assistant_read_aloud">Antwort vorlesen, wenn per Sprache gefragt wurde</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Höchstens einmal am Tag, beim Start, fragt die App Ihre Instanz, welches Release zu ihr passt — oder liest die Liste der Releases auf GitHub, wenn die Instanz es nicht sagen kann — und meldet per Benachrichtigung, wenn es ein neueres gibt. Mit keiner der beiden Anfragen wird etwas über Sie 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>
|
||||
@@ -421,44 +553,51 @@
|
||||
<string name="assist_say_it">Sprechen Sie, dann kurz Pause</string>
|
||||
<string name="assist_type">Lieber tippen</string>
|
||||
<string name="assist_writing_down">Ihr Gesagtes wird aufgeschrieben…</string>
|
||||
<string name="assist_unlock_to_send">Entsperren und senden</string>
|
||||
<string name="assist_question_heard">Frage aufgenommen</string>
|
||||
<string name="assist_recording_waits_line">Das Telefon ist gesperrt. Ihre Frage wartet als Aufnahme auf diesem Telefon; es wurde nichts gesendet. Nach dem Entsperren geht sie an Ihre Instanz, die sie aufschreibt und beantwortet.</string>
|
||||
<string name="assist_locked_line">Das Telefon ist gesperrt. Bis Sie es entsperren, wird nichts gesendet und keine Antwort angezeigt.</string>
|
||||
<string name="assist_conversation">Im Gespräch</string>
|
||||
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sag „Stopp“, um zu beenden.</string>
|
||||
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sagen Sie „Stopp“, um zu beenden.</string>
|
||||
<string name="assist_conversation_end">Beenden</string>
|
||||
<string name="assist_stop_words">stopp|stop|das wars|das war\'s|das ist alles|genug|ende|tschüss|auf wiedersehen|danke das wars|abbrechen</string>
|
||||
<string name="assistant_conversation">Ein gesprochenes Gespräch fortführen</string>
|
||||
<string name="assistant_conversation_line">Nachdem eine gesprochene Antwort vorgelesen wurde, hört der Assistent wieder zu — bis du „Stopp“ sagst, auf Beenden tippst oder ein paar Sekunden nichts sagst. Funktioniert mit einem Headset.</string>
|
||||
<string name="assist_wake_word_hint">Kein Aktivierungswort, außer du willst eines: Einstellungen › Assistent › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
|
||||
<string name="assistant_conversation_line">Nachdem eine gesprochene Antwort vorgelesen wurde, hört der Assistent wieder zu — bis Sie „Stopp“ sagen, auf Beenden tippen oder ein paar Sekunden nichts sagen. Funktioniert mit einem Headset.</string>
|
||||
<string name="experimental">Experimentell</string>
|
||||
<string name="wake_experimental_line">Neu und bisher nur auf wenigen Telefonen erprobt. Es kann den Satz überhören, versehentlich starten oder Sie hören und den Assistenten trotzdem nicht öffnen.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimentell: Das selbstständige Zuhören beim Öffnen des Assistenten, das Erkennen, wann Sie fertig gesprochen haben, und das gesprochene Gespräch sind neu und funktionieren noch nicht auf jedem Telefon gut. Eine Frage tippen und die Mikrofontaste funktionieren immer.</string>
|
||||
<string name="assist_wake_word_hint">Kein Aktivierungswort, außer Sie wollen eines: Einstellungen › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
|
||||
<string name="channel_wake">Aktivierungswort</string>
|
||||
<string name="wake_word">Aktivierungswort</string>
|
||||
<string name="wake_word_listen">Auf ein Aktivierungswort hören</string>
|
||||
<string name="wake_word_line">Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.</string>
|
||||
<string name="wake_word_line">Standardmäßig aus. Sagen Sie den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.</string>
|
||||
<string name="wake_word_unavailable">Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.</string>
|
||||
<string name="wake_phrase_line">Das sagst du, dann eine kurze Pause: Es zählt, sobald du aufhörst. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache.</string>
|
||||
<string name="wake_phrase_line">Das sagen Sie, dann eine kurze Pause: Es zählt, sobald Sie aufhören. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache.</string>
|
||||
<string name="wake_greeting">Anrede</string>
|
||||
<string name="wake_name">Name</string>
|
||||
<string name="wake_name_google_line">Ein Google-Telefon oder -Lautsprecher in der Nähe antwortet ebenfalls.</string>
|
||||
<string name="wake_sensitivity">Empfindlichkeit</string>
|
||||
<string name="wake_sensitivity_low">Niedrig</string>
|
||||
<string name="wake_sensitivity_low_line">Startet am seltensten versehentlich. Du musst den Satz vielleicht deutlicher oder zweimal sagen.</string>
|
||||
<string name="wake_sensitivity_low_line">Startet am seltensten versehentlich. Sie müssen den Satz vielleicht deutlicher oder zweimal sagen.</string>
|
||||
<string name="wake_sensitivity_normal">Normal</string>
|
||||
<string name="wake_sensitivity_normal_line">Die eigene Einstellung der Engine.</string>
|
||||
<string name="wake_sensitivity_high">Hoch</string>
|
||||
<string name="wake_sensitivity_high_line">Hört dich am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich.</string>
|
||||
<string name="wake_sensitivity_high_line">Hört Sie am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich.</string>
|
||||
<string name="wake_test">Aktivierungswort testen</string>
|
||||
<string name="wake_test_line">Zeigt zehn Sekunden lang, ob dein Satz gehört wird, ohne den Assistenten zu öffnen.</string>
|
||||
<string name="wake_test_say">Sag jetzt „%1$s“, dann eine Pause…</string>
|
||||
<string name="wake_test_line">Zeigt zehn Sekunden lang, ob Ihr Satz gehört wird, ohne den Assistenten zu öffnen.</string>
|
||||
<string name="wake_test_say">Sagen Sie jetzt „%1$s“, dann eine Pause…</string>
|
||||
<string name="wake_test_heard">Gehört</string>
|
||||
<string name="wake_test_missed">In zehn Sekunden nicht gehört. Versuch es näher am Telefon, in einem ruhigeren Moment oder mit höherer Empfindlichkeit.</string>
|
||||
<string name="wake_test_off">Schalte zuerst das Aktivierungswort ein.</string>
|
||||
<string name="wake_test_missed">In zehn Sekunden nicht gehört. Versuchen Sie es näher am Telefon, in einem ruhigeren Moment oder mit höherer Empfindlichkeit.</string>
|
||||
<string name="wake_test_off">Schalten Sie zuerst das Aktivierungswort ein.</string>
|
||||
<string name="wake_screen_only">Nur bei eingeschaltetem Bildschirm</string>
|
||||
<string name="wake_screen_only_line">Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet.</string>
|
||||
<string name="wake_battery">Im Hintergrund laufen lassen</string>
|
||||
<string name="wake_battery_line">Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nimm LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen deines Telefons.</string>
|
||||
<string name="wake_battery_line">Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nehmen Sie LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen Ihres Telefons.</string>
|
||||
<string name="wake_word_privacy">Vor dem Wort verlässt nichts das Telefon. Der Ton des Mikrofons geht nur an die Aktivierungswort-Engine auf dem Telefon und wird nicht gespeichert; die Benachrichtigung bleibt sichtbar, solange es zuhört. Die Sätze sind englisch; die Engine ist sherpa-onnx (Open Source).</string>
|
||||
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.</string>
|
||||
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn Sie es nicht ändern, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippen Sie auf seine Benachrichtigung, um es wieder zu starten.</string>
|
||||
<string name="wake_listening_for">Hört auf „%1$s“</string>
|
||||
<string name="wake_off">Das Aktivierungswort hört nicht zu</string>
|
||||
<string name="wake_tap_to_start">Tippe, um es wieder zu starten. Wenn Android fragt, erlaube das Mikrofon.</string>
|
||||
<string name="wake_tap_to_start">Tippen Sie, um es wieder zu starten. Wenn Android fragt, erlauben Sie das Mikrofon.</string>
|
||||
<string name="wake_starting">Aktivierungswort wird gestartet…</string>
|
||||
<string name="wake_paused_silent">Aktivierungswort hört nichts: Eine andere App hat das Mikrofon, oder das Mikrofon des Telefons ist ausgeschaltet</string>
|
||||
<string name="wake_failed_no_engine">Aktivierungswort funktioniert nicht: Dieser Build hat keine Engine</string>
|
||||
@@ -466,17 +605,17 @@
|
||||
<string name="wake_failed_engine">Aktivierungswort funktioniert nicht: Die Engine ist nicht gestartet</string>
|
||||
<string name="wake_failed_microphone">Aktivierungswort funktioniert nicht: Das Mikrofon ist nicht gestartet</string>
|
||||
<string name="wake_failed_line">Es hört nicht zu. Es versucht es von selbst erneut.</string>
|
||||
<string name="wake_notification_line">Bis du es sagst, verlässt nichts das Telefon.</string>
|
||||
<string name="wake_notification_line">Bis Sie es sagen, verlässt nichts das Telefon.</string>
|
||||
<string name="wake_paused_screen">Aktivierungswort pausiert: Bildschirm aus</string>
|
||||
<string name="wake_paused_battery">Aktivierungswort pausiert: Energiesparmodus ist an</string>
|
||||
<string name="wake_paused_assistant">Aktivierungswort pausiert, solange der Assistent offen ist</string>
|
||||
<string name="wake_paused_microphone">Aktivierungswort pausiert: LLeMbas darf das Mikrofon nicht verwenden</string>
|
||||
<string name="wake_stop">Nicht mehr zuhören</string>
|
||||
<string name="wake_heard">Gehört. Tippe, um zu fragen.</string>
|
||||
<string name="wake_heard">Gehört. Zum Fragen tippen.</string>
|
||||
<string name="channel_wake_heard">Aktivierungswort gehört</string>
|
||||
<string name="wake_heard_line">LLeMbas kann sich nur als App für den digitalen Assistenten des Telefons selbst über anderen Apps öffnen.</string>
|
||||
<string name="wake_not_assistant">LLeMbas ist nicht die App für den digitalen Assistenten</string>
|
||||
<string name="wake_not_assistant_line">Deshalb kann das Aktivierungswort den Assistenten nicht über anderen Apps öffnen: Du bekommst eine Benachrichtigung zum Antippen. Um überall per Stimme zu öffnen, tippe hier und wähle LLeMbas als App für den digitalen Assistenten.</string>
|
||||
<string name="wake_not_assistant_line">Deshalb kann das Aktivierungswort den Assistenten nicht über anderen Apps öffnen: Sie bekommen eine Benachrichtigung zum Antippen. Um überall per Stimme zu öffnen, tippen Sie hier und wählen Sie LLeMbas als App für den digitalen Assistenten.</string>
|
||||
<string name="wake_last">Letztes Aufwecken</string>
|
||||
<string name="wake_last_none">Der Satz wurde noch nicht gehört.</string>
|
||||
<string name="wake_out_opened">Assistent geöffnet.</string>
|
||||
@@ -498,24 +637,24 @@
|
||||
<string name="wake_waited">Kurz gewartet, bis Android ihn verbindet.</string>
|
||||
<string name="wake_show_failed">Android meldete, dass es das Blatt des Assistenten nicht anzeigen konnte.</string>
|
||||
<string name="wake_assistant_inactive">Android nutzt LLeMbas gerade nicht als Sprachassistenten</string>
|
||||
<string name="wake_assistant_inactive_line">Wähle LLeMbas erneut als App für den digitalen Assistenten: Tippe hier, wähle eine andere App und dann LLeMbas. Bis dahin öffnet langes Drücken es als gewöhnlichen Bildschirm, und das Aktivierungswort kann nur eine Benachrichtigung senden.</string>
|
||||
<string name="wake_assistant_inactive_line">Wählen Sie LLeMbas erneut als App für den digitalen Assistenten: Tippen Sie hier, wählen Sie eine andere App und dann LLeMbas. Bis dahin öffnet langes Drücken es als gewöhnlichen Bildschirm, und das Aktivierungswort kann nur eine Benachrichtigung senden.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas ist der Assistent, aber Android hat ihn gerade nicht verbunden</string>
|
||||
<string name="wake_assistant_unbound_line">Solange das so ist, kann das Aktivierungswort das Blatt nicht selbst öffnen. Tippe für die Assistenten-Einstellung des Systems: Eine andere App und dann wieder LLeMbas zu wählen verbindet ihn.</string>
|
||||
<string name="wake_heard_could_not">Ließ sich nicht selbst öffnen — tippe, um zu fragen</string>
|
||||
<string name="wake_assistant_unbound_line">Solange das so ist, kann das Aktivierungswort das Blatt nicht selbst öffnen. Tippen Sie für die Assistenten-Einstellung des Systems: Eine andere App und dann wieder LLeMbas zu wählen verbindet ihn.</string>
|
||||
<string name="wake_heard_could_not">Ließ sich nicht selbst öffnen — zum Fragen tippen</string>
|
||||
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
|
||||
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.</string>
|
||||
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippen Sie, um wieder zuzuhören.</string>
|
||||
<string name="assist_notifications">Meine Benachrichtigungen zusammenfassen</string>
|
||||
<string name="assist_notifications_prompt">Fasse meine Benachrichtigungen zusammen: Was braucht meine Aufmerksamkeit?</string>
|
||||
<string name="assist_notifications_phrases">meine benachrichtigungen|meinen benachrichtigungen|meiner benachrichtigungen</string>
|
||||
<string name="notification_summaries">Zusammenfassungen der Benachrichtigungen</string>
|
||||
<string name="notification_summaries_switch">Den Assistenten meine Benachrichtigungen lesen lassen, wenn ich frage</string>
|
||||
<string name="notification_summaries_line">Sag „fasse meine Benachrichtigungen zusammen“ oder tippe auf den Chip im Assistenten.</string>
|
||||
<string name="notification_summaries_line">Sagen Sie „fasse meine Benachrichtigungen zusammen“ oder tippen Sie auf den Chip im Assistenten.</string>
|
||||
<string name="notification_summaries_unavailable">Nicht in diesem Build. Das Lesen von Benachrichtigungen braucht den „notifications“-Build von LLeMbas, weil Google Play Protect die Installation einer App von außerhalb des Play Store blockiert, die sie lesen kann. Es ist dieselbe App mit derselben Signatur: Auf der Release-Seite lässt sich die Datei, die auf -notifications.apk endet, über diese installieren.</string>
|
||||
<string name="update_notifications_manual">Dies ist der „notifications“-Build: Installiere das Update von der Release-Seite, die Datei, die auf -notifications.apk endet.</string>
|
||||
<string name="notification_access">Zugriff auf Benachrichtigungen</string>
|
||||
<string name="notification_access_on">Erteilt. Der Schalter dafür ist in den Android-Einstellungen.</string>
|
||||
<string name="notification_access_off">Noch nicht erteilt. Tippe, um den Android-Schalter für LLeMbas zu öffnen.</string>
|
||||
<string name="notification_summaries_privacy">Standardmäßig aus. Wenn du fragst, geht der Text der Benachrichtigungen, die gerade auf deinem Telefon sind (App, Titel, Text), mit dieser einen Frage an deine Instanz und ihr Modell. Vorher wird nichts gelesen, die App behält nichts davon, und bei gesperrtem Telefon wird nichts gelesen. Der Benachrichtigungszugriff von Android lässt eine App jede Benachrichtigung sehen; ihn zu erteilen und zu entziehen liegt bei dir.</string>
|
||||
<string name="notification_access_off">Noch nicht erteilt. Tippen Sie, um den Android-Schalter für LLeMbas zu öffnen.</string>
|
||||
<string name="notification_summaries_privacy">Standardmäßig aus. Wenn Sie fragen, geht der Text der Benachrichtigungen, die gerade auf Ihrem Telefon sind (App, Titel, Text), mit dieser einen Frage an Ihre Instanz und ihr Modell. Vorher wird nichts gelesen, die App behält nichts davon, und bei gesperrtem Telefon wird nichts gelesen. Der Benachrichtigungszugriff von Android lässt eine App jede Benachrichtigung sehen; ihn zu erteilen und zu entziehen liegt bei Ihnen.</string>
|
||||
<string name="nav_app">Navigations-App</string>
|
||||
<string name="nav_app_auto">Die installierte</string>
|
||||
<string name="nav_app_google">Google Maps</string>
|
||||
@@ -523,38 +662,75 @@
|
||||
<string name="nav_app_ask">Jedes Mal fragen</string>
|
||||
<string name="nav_app_not_installed">Nicht installiert</string>
|
||||
<string name="osmand_info">OsmAnd nach der Route fragen</string>
|
||||
<string name="osmand_info_line">Damit „Zwischenstopp hinzufügen“ und die Suche in der Nähe auch mit einer in OsmAnd geplanten Route gehen: LLeMbas fragt OsmAnd, wo du bist und wohin die Route führt. Erlaube LLeMbas zuerst in OsmAnd (verbundene Apps, mit Standort); OsmAnd sagt Bescheid, wenn es nicht erlaubt ist.</string>
|
||||
<string name="phone_actions_line">Ein Modell kann anbieten, etwas auf diesem Telefon zu tun — einen Wecker stellen, einen Termin eintragen, eine Nachricht entwerfen, eine Route starten. Nichts passiert, bevor du auf seiner Karte auf Ausführen tippst, und nie bei gesperrtem Telefon. Google Maps startet eine Route mit ein paar Stopps, kann aber keinen in eine laufende Route einfügen und nicht angehalten werden; OsmAnd kann das.</string>
|
||||
<string name="action_card_title">Das auf deinem Telefon tun?</string>
|
||||
<string name="osmand_info_line">Damit „Zwischenstopp hinzufügen“ und die Suche in der Nähe auch mit einer in OsmAnd geplanten Route gehen: LLeMbas fragt OsmAnd, wo Sie sind und wohin die Route führt. Erlauben Sie LLeMbas zuerst in OsmAnd (verbundene Apps, mit Standort); OsmAnd sagt Bescheid, wenn es nicht erlaubt ist.</string>
|
||||
<string name="phone_actions_line">Ein Modell kann anbieten, etwas auf diesem Telefon zu tun — einen Wecker stellen, einen Termin eintragen, eine Nachricht entwerfen, eine Route starten. Nichts passiert, bevor Sie auf seiner Karte auf Ausführen tippen, und nie bei gesperrtem Telefon. Google Maps startet eine Route mit ein paar Stopps, kann aber keinen in eine laufende Route einfügen und nicht angehalten werden; OsmAnd kann das.</string>
|
||||
<string name="action_card_title">Das auf Ihrem Telefon tun?</string>
|
||||
<string name="action_do">Ausführen</string>
|
||||
<string name="action_running">Wird ausgeführt…</string>
|
||||
<string name="action_unlock">Entsperre zuerst das Telefon und tippe dann auf Ausführen.</string>
|
||||
<string name="action_unlock">Entsperren Sie zuerst das Telefon und tippen Sie dann auf Ausführen.</string>
|
||||
<string name="action_failed">Hat nicht geklappt: %1$s</string>
|
||||
<string name="nav_app_pick">Mit welcher Karten-App?</string>
|
||||
<string name="action_google_add_stop">Google Maps kann keinen Stopp in eine laufende Route einfügen: Es startet die Route neu, über den Stopp.</string>
|
||||
<string name="action_google_no_stop">Google Maps lässt sich nicht von außen anhalten: Beende die Route dort.</string>
|
||||
<string name="action_line_clock">Die Uhr-App stellt es ein.</string>
|
||||
<string name="action_line_calendar">Der Kalender öffnet sich mit dem ausgefüllten Termin; du speicherst ihn.</string>
|
||||
<string name="action_line_draft">Öffnet einen Entwurf; du sendest ihn selbst.</string>
|
||||
<string name="action_line_dial">Die Telefon-App öffnet sich mit der Nummer; du rufst an.</string>
|
||||
<string name="action_line_calendar">Der Kalender öffnet sich mit dem ausgefüllten Termin; Sie speichern ihn.</string>
|
||||
<string name="action_line_draft">Öffnet einen Entwurf; Sie senden ihn selbst.</string>
|
||||
<string name="action_line_dial">Die Telefon-App öffnet sich mit der Nummer; Sie rufen an.</string>
|
||||
<string name="action_line_map">%1$s übernimmt die Route.</string>
|
||||
<string name="action_line_now">Passiert sofort.</string>
|
||||
<string name="action_line_settings">Öffnet die Einstellung; du änderst sie.</string>
|
||||
<string name="action_line_automation">Startet deine Automatisierung (Tasker, wenn keine andere App genannt ist).</string>
|
||||
<string name="action_line_settings">Öffnet die Einstellung; Sie ändern sie.</string>
|
||||
<string name="action_line_automation">Startet Ihre Automatisierung (Tasker, wenn keine andere App genannt ist).</string>
|
||||
<string name="action_line_open">Öffnet es.</string>
|
||||
<string name="assist_recogniser_failed">Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.</string>
|
||||
<string name="assistant_listens">Beim Öffnen des Assistenten zuhören</string>
|
||||
<string name="voice_input">Spracheingabe</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">Die Spracherkennung Ihrer Instanz, über den Server. Die Aufnahme geht an Ihre Instanz und nirgendwo sonst hin.</string>
|
||||
<string name="voice_input_lembas_line">Die Spracherkennung Ihrer Instanz. Dieses Telefon sendet die Aufnahme nur an Ihre Instanz; die Instanz schreibt sie mit dem dort eingerichteten Sprachmodell auf.</string>
|
||||
<string name="voice_input_phone">Telefon (Google oder das System)</string>
|
||||
<string name="voice_input_phone_line">Die eigene Spracherkennung des Telefons. Die Wörter erscheinen beim Sprechen; die Aufnahme geht dorthin, wohin diese Erkennung sie schickt.</string>
|
||||
<string name="voice_input_phone_none">Dieses Telefon hat keine eigene Spracherkennung.</string>
|
||||
<string name="voice_input_hint">Wird vom Assistenten und vom Mikrofon im Chat genutzt. Mit LLeMbas zeigt der Assistent die Wörter einen Moment später, und eine Pause sendet sie, ein Chat schreibt sie auf, wenn Sie aufhören; mit der Erkennung des Telefons erscheinen sie beim Sprechen.</string>
|
||||
<string name="share_sending">Wird an LLeMbas gesendet…</string>
|
||||
<string name="share_default_prompt">Schauen Sie sich das an.</string>
|
||||
<string name="share_default_prompt">Schau dir das an.</string>
|
||||
<string name="share_ask_hint">Was soll LLeMbas damit tun? (optional)</string>
|
||||
<string name="widget_hint">Frag mich alles</string>
|
||||
<string name="widget_hint">Fragen Sie irgendetwas</string>
|
||||
<string name="directory_places">Orte auf diesem Gerät</string>
|
||||
<string name="directory_last_used">Hier zuletzt verwendet: %1$s. Ein neuer Chat in diesem Verzeichnis beginnt damit, sofern Sie kein anderes wählen.</string>
|
||||
<string name="directory_refused">Das Gerät öffnet hier keine Sitzung.</string>
|
||||
<string name="directory_up">Eine Ebene höher</string>
|
||||
<string name="directory_all_places">Alle Orte</string>
|
||||
<string name="directory_not_trusted">Auf dem Gerät nicht vertrauenswürdig</string>
|
||||
<string name="directory_empty">Hier gibt es keine Ordner.</string>
|
||||
<string name="directory_no_places">Dieses Gerät bietet keine Ordner an: Seine Remote-Wurzeln sind leer oder fehlen.</string>
|
||||
<string name="directory_browse">Durchsuchen</string>
|
||||
<string name="directory_path">Ein vollständiger Pfad</string>
|
||||
<string name="directory_choose">Auswählen</string>
|
||||
<string name="directory_no_listing">Die Verzeichnisse dieses Geräts können gerade nicht aufgelistet werden. Geben Sie den Pfad unten ein.</string>
|
||||
<string name="model">Modell</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Läuft auf diesem Server wie ein Chat: mit den Werkzeugen des Servers (Suche, Ihre Dateien hier, Gedächtnis) und auf einem Planungsmodell.</string>
|
||||
<string name="schedule_agentic">Agentisch</string>
|
||||
<string name="schedule_agentic_line">Läuft auf einem Ihrer Computer, in einem Ordner dort, als Agent: mit den Werkzeugen des Agenten auf diesem Computer — seinen Dateien und seiner Shell — innerhalb der eigenen Grenzen des Computers. Er gehört zu diesem Computer und Ordner.</string>
|
||||
<string name="schedule_agentic_unavailable">Keiner Ihrer Computer nimmt jetzt geplante Arbeit an. Verbinden Sie einen und schalten Sie „Accept scheduled work“ in seinem LLeMbas CLI ein (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nimmt keine geplante Arbeit an</string>
|
||||
<string name="schedule_computer_hint">Der Computer muss es erlauben: „Accept scheduled work“ in seinem LLeMbas CLI (lembas service scheduled on). Ist er zur Zeit eines Laufs nicht verbunden, wartet der Lauf auf ihn; ist er nicht zurück, bevor die Zeit des Laufs vorbei ist, wird der Lauf als verpasst vermerkt und Sie erfahren es.</string>
|
||||
<string name="schedule_computer_gone">ein Computer, der nicht mehr angemeldet ist</string>
|
||||
<string name="schedule_folder">Ordner auf dem Computer</string>
|
||||
<string name="schedule_agent_mode">Modus</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, sofern Sie nichts anderes wählen; Auto führt Befehle ohne Nachfrage aus. Der Computer kann ihn herabsetzen.</string>
|
||||
<string name="schedule_approval_wait">Eine Genehmigung wartet (Minuten)</string>
|
||||
<string name="schedule_approval_wait_hint">Ein Befehl, den der Lauf genehmigt braucht, kommt als Karte auf Ihr Telefon. Bis dahin unbeantwortet, gilt er als abgelehnt.</string>
|
||||
<string name="schedule_watch_command_hint">Optional, auf dem Computer. Läuft vor jedem Lauf im Ordner; ist seine Ausgabe dieselbe wie beim letzten Mal, endet der Lauf dort. Ein Befehl, bei dem der Modus nachfragen würde, wird abgelehnt.</string>
|
||||
<string name="schedule_watch_timeout">Der Befehl darf dauern (Sekunden)</string>
|
||||
<string name="schedule_watch_timeout_hint">Danach wird er gestoppt, und der Lauf schlägt fehl.</string>
|
||||
<string name="schedule_chat_drops_watch">Diese Aufgabe überwacht einen Befehl auf ihrem Computer. Als Chat-Aufgabe tut sie das nicht mehr: Sie läuft jedes Mal.</string>
|
||||
<string name="schedule_folder_model">Das übliche Modell des Ordners</string>
|
||||
<string name="schedule_folder_model_hint">Das übliche Modell des Ordners ist das, das Sie in diesem Ordner auf diesem Computer zuletzt verwendet haben — der Computer merkt es sich, und jeder Lauf fragt ihn danach — oder Ihr Standardmodell, wo es keines gibt. Ein hier gewähltes Modell ist das des Laufs, was auch immer das des Ordners ist. Ein Lauf ändert das Modell des Ordners nie.</string>
|
||||
<string name="schedule_first_free_model">Das erste freie Ihrer Modelle für geplante Aufgaben</string>
|
||||
<string name="run_model_directory">das übliche Modell des Ordners</string>
|
||||
<string name="run_model_default">Ihr Standardmodell</string>
|
||||
<string name="run_model_session">das eigene Modell der Unterhaltung</string>
|
||||
<string name="widget_speak">Sprechen</string>
|
||||
<string name="widget_description">Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.</string>
|
||||
<string name="shortcut_last">Letzter Chat</string>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas para Android</string>
|
||||
<string name="share_label">Preguntar a LLeMbas</string>
|
||||
<string name="tile_ask">Preguntar a LLeMbas</string>
|
||||
<string name="signin_intro">Inicie sesión en una instancia de LLeMbas. Aprobará este teléfono en el navegador, igual que haría con la CLI.</string>
|
||||
<string name="signin_intro">Inicie sesión en una instancia de LLeMbas. Aprobará este teléfono en el navegador.</string>
|
||||
<string name="signin_address">Dirección de la instancia</string>
|
||||
<string name="signin_continue">Continuar</string>
|
||||
<string name="signin_code_intro">Abra la instancia en el navegador, inicie sesión y apruebe este código:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Esta instancia es más reciente de lo que esta aplicación admite. Actualice la aplicación.</string>
|
||||
<string name="signin_not_lembas">No hay ninguna instancia de LLeMbas en esa dirección.</string>
|
||||
<string name="signin_failed">No se pudo completar el inicio de sesión (%1$s). Inténtelo de nuevo.</string>
|
||||
<string name="signin_app_too_old">Esta instancia necesita LLeMbas para Android %1$s o posterior, y esta es la %2$s. Actualice la aplicación.</string>
|
||||
<string name="signin_other_origin">Esta instancia indica para iniciar sesión otra dirección (%1$s) que la que escribió. Su proxy debe transmitir la dirección por la que se accede a ella.</string>
|
||||
<string name="address_needs_https">Esta aplicación necesita una dirección https://: no se admite http sin cifrar.</string>
|
||||
<string name="address_unreadable">La aplicación no puede usar esa dirección. Escriba la dirección de la instancia, por ejemplo llm.example.org.</string>
|
||||
<string name="server_answered">El servidor respondió %1$s.</string>
|
||||
<string name="timed_out">La instancia no respondió a tiempo.</string>
|
||||
<string name="not_trusted">Este teléfono no confía en el certificado de la instancia: instale el certificado de su autoridad de certificación entre los certificados de usuario de Android (Ajustes, Seguridad, Cifrado y credenciales, Instalar un certificado).</string>
|
||||
<string name="signed_out">%1$s cerró la sesión de este teléfono. Inicie sesión de nuevo para continuar: sus chats y lo que configuró aquí se conservan.</string>
|
||||
<string name="signed_out_again">Iniciar sesión de nuevo</string>
|
||||
<string name="signed_out_use">Usar %1$s</string>
|
||||
<string name="signed_out_remove">Quitar esta instancia</string>
|
||||
<string name="new_chat">Nuevo chat</string>
|
||||
<string name="empty_chats">Aún no hay chats. No todos los que vagan están perdidos — empiece uno.</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="agent_device">Ordenador</string>
|
||||
<string name="agent_no_device">Ahora no hay ningún ordenador vinculado. Inicie el servicio de la CLI de LLeMbas (lembas service) en un ordenador con sesión iniciada en esta instancia y vuelva.</string>
|
||||
<string name="agent_directory">Carpeta en el ordenador</string>
|
||||
<string name="agent_directory_hint">Vacío: la primera carpeta del ordenador</string>
|
||||
<string name="empty_chat">¿De qué hablamos?</string>
|
||||
<string name="loading_line">Horneando lembas…</string>
|
||||
<string name="archive">Archivar</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Continuar</string>
|
||||
<string name="older">Mensajes anteriores</string>
|
||||
<string name="queued">Esperando para enviarse</string>
|
||||
<string name="fate_unknown">No se sabe si esto llegó al ordenador. Envíalo de nuevo o descártalo.</string>
|
||||
<string name="fate_carried">El ordenador tiene este mensaje y lo incorporará en su próximo turno.</string>
|
||||
<string name="send_now">Enviar ahora</string>
|
||||
<string name="discard_message_confirm">¿Descartar este mensaje?</string>
|
||||
<string name="reply_unrecorded">La respuesta a esto no se registró.</string>
|
||||
<string name="thinking">Pensando</string>
|
||||
<string name="thought">Pensamiento</string>
|
||||
<string name="output_cut">La salida está acortada aquí. La tiene completa en la página web.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Transcrito por %1$s: el modelo de voz propio de este chat no respondió.</string>
|
||||
<string name="read_by_fallback">Leído por %1$s: el modelo de voz propio de este chat no respondió.</string>
|
||||
<string name="remove">Quitar</string>
|
||||
<string name="more">Más</string>
|
||||
<string name="back">Volver</string>
|
||||
@@ -155,7 +175,7 @@
|
||||
<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="plan_first_hint">El modelo escribe un plan que usted aprueba 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>
|
||||
@@ -209,7 +229,7 @@
|
||||
<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_hint">Diga cuándo y qué, con sus palabras. Verá 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>
|
||||
@@ -245,11 +265,11 @@
|
||||
<string name="scheduled_result_public">Una tarea programada tiene un resultado.</string>
|
||||
<string name="scheduled_failed_public">Una tarea programada falló.</string>
|
||||
<string name="page_note">Esta respuesta tiene una página: %1$s</string>
|
||||
<string name="page_where">Ábrela en la web o en LLeMbas Desktop para verla.</string>
|
||||
<string name="page_where">Ábrala en la web o en LLeMbas Desktop para verla.</string>
|
||||
<string name="page_untitled">Página</string>
|
||||
<string name="reports">Informes</string>
|
||||
<string name="report">Informe</string>
|
||||
<string name="reports_none">Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirte.</string>
|
||||
<string name="reports_none">Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirle.</string>
|
||||
<string name="reports_unsupported">Esta instancia ejecuta un LLeMbas que todavía no tiene Informes.</string>
|
||||
<string name="report_untitled">Informe sin título</string>
|
||||
<string name="report_delete_title">¿Eliminar este informe?</string>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Esta instancia 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="files_upload">Subir</string>
|
||||
<string name="files_new_file">Nuevo archivo</string>
|
||||
<string name="files_new_file_ask">¿Cómo debe llamarse el archivo? Con su extensión, por ejemplo notes.md.</string>
|
||||
<string name="files_new_folder_ask">¿Cómo debe llamarse la carpeta?</string>
|
||||
<string name="files_bad_name">Un nombre no puede estar vacío ni contener una barra.</string>
|
||||
<string name="files_taken">Ya hay algo llamado %1$s aquí.</string>
|
||||
<string name="rename">Renombrar</string>
|
||||
<string name="files_new_name">Nombre nuevo</string>
|
||||
<string name="files_move">Mover</string>
|
||||
<string name="files_copy_to">Copiar a…</string>
|
||||
<string name="files_move_here">Mover aquí</string>
|
||||
<string name="files_copy_here">Copiar aquí</string>
|
||||
<string name="files_move_which">¿A qué carpeta mover?</string>
|
||||
<string name="files_copy_which">¿A qué carpeta copiar?</string>
|
||||
<string name="files_choose_folder">Elegir una carpeta</string>
|
||||
<string name="files_save_here">Guardar aquí</string>
|
||||
<string name="files_no_folders">Aquí no hay carpetas.</string>
|
||||
<string name="files_to_trash">Mover a la papelera</string>
|
||||
<string name="files_trash_one">¿Mover «%1$s» a la papelera? Se puede restaurar desde allí.</string>
|
||||
<string name="files_trash_many">¿Mover los %1$s seleccionados a la papelera? Desde allí se pueden restaurar.</string>
|
||||
<string name="files_trashed">Movido a la papelera.</string>
|
||||
<string name="files_selected">Seleccionados: %1$s</string>
|
||||
<string name="files_select_all">Seleccionar todo</string>
|
||||
<string name="download">Descargar</string>
|
||||
<string name="files_download_zip">Descargar como zip</string>
|
||||
<string name="files_downloading">Descargando…</string>
|
||||
<string name="files_downloaded">Descargado.</string>
|
||||
<string name="files_uploading">Subiendo %1$s de %2$s…</string>
|
||||
<string name="files_uploaded">Subido.</string>
|
||||
<string name="files_open_with">Abrir con…</string>
|
||||
<string name="files_no_app">Ninguna aplicación de este teléfono abre este tipo de archivo.</string>
|
||||
<string name="trash">Papelera</string>
|
||||
<string name="trash_is_empty">La papelera está vacía.</string>
|
||||
<string name="trash_empty">Vaciar la papelera</string>
|
||||
<string name="trash_empty_confirm">¿Eliminar para siempre todo lo que hay en la papelera? No se puede deshacer.</string>
|
||||
<string name="trash_remove">Eliminar para siempre</string>
|
||||
<string name="trash_remove_confirm">¿Eliminar «%1$s» para siempre? No se puede deshacer.</string>
|
||||
<string name="restore">Restaurar</string>
|
||||
<string name="versions">Versiones</string>
|
||||
<string name="version_restore">Restaurar esta versión</string>
|
||||
<string name="version_restore_confirm">¿Hacer actual esta versión? La actual se queda en la lista.</string>
|
||||
<string name="version_current">Actual</string>
|
||||
<string name="files_type">Tipo</string>
|
||||
<string name="files_size">Tamaño</string>
|
||||
<string name="files_no_viewer">No hay visor para este tipo de archivo.</string>
|
||||
<string name="files_not_shown">Este archivo no se pudo mostrar aquí. Aún se puede descargar.</string>
|
||||
<string name="files_svg_source">Este es el código fuente de la imagen. Ábrela con otra aplicación para ver la imagen.</string>
|
||||
<string name="archive_note">El contenido de este tipo de archivo comprimido no se puede listar aquí.</string>
|
||||
<string name="archive_entries">%1$s entradas. Aquí no se descomprime nada.</string>
|
||||
<string name="archive_cut">Solo se listan las primeras %1$s entradas.</string>
|
||||
<string name="archive_unreadable">No se pudo leer este archivo comprimido.</string>
|
||||
<string name="files_waiting">Esperando a que la aplicación esté abierta y el teléfono desbloqueado.</string>
|
||||
<string name="share_refused">Algo de lo compartido no se puede enviar desde aquí y se ha omitido.</string>
|
||||
<string name="media_in_trash">Ese archivo está en la papelera.</string>
|
||||
<string name="table_cut">Solo las primeras filas y columnas se disponen como tabla. El texto lo contiene todo.</string>
|
||||
<string name="table_as_text">Mostrar como texto</string>
|
||||
<string name="table_as_table">Mostrar como tabla</string>
|
||||
<string name="media_open_in_files">Abrir en Archivos</string>
|
||||
<string name="media_image">Imagen</string>
|
||||
<string name="media_video">Vídeo</string>
|
||||
<string name="media_music">Música</string>
|
||||
<string name="media_model">Modelo 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archivo comprimido</string>
|
||||
<string name="media_text">Archivo de texto</string>
|
||||
<string name="media_binary">Archivo</string>
|
||||
<string name="diff_deleted">Eliminado</string>
|
||||
<string name="diff_counts">Líneas añadidas: %1$s, eliminadas: %2$s</string>
|
||||
<string name="diff_show_all">Mostrar las %1$s líneas</string>
|
||||
<string name="diff_show_less">Mostrar menos</string>
|
||||
<string name="diff_more">Aquí no se muestran %1$s líneas más.</string>
|
||||
<string name="diff_endings">Los finales de línea cambian de %1$s a %2$s.</string>
|
||||
<string name="diff_cut">Este cambio es demasiado largo para compararlo aquí. Solo se muestra su comienzo.</string>
|
||||
<string name="media_gone">Ese archivo ya no existe.</string>
|
||||
<string name="job_queued">En cola</string>
|
||||
<string name="job_running">En ejecución</string>
|
||||
<string name="job_done">Hecho</string>
|
||||
<string name="job_failed">Fallidos</string>
|
||||
<string name="job_cancelled">Cancelado</string>
|
||||
<string name="job_expired">Caducado</string>
|
||||
<string name="mcp_title">Servidores MCP</string>
|
||||
<string name="mcp_intro">Los servidores cuyas herramientas pueden ofrecerse en sus chats. Algunos se usan con una cuenta propia en ellos: sus herramientas se ofrecen mientras la sesión esté iniciada.</string>
|
||||
<string name="mcp_none">En esta instancia no se le ofrece ningún servidor MCP.</string>
|
||||
<string name="mcp_ready">Listo</string>
|
||||
<string name="mcp_signed_in">Sesión iniciada</string>
|
||||
<string name="mcp_signed_out">Sin sesión iniciada</string>
|
||||
<string name="mcp_needs_signin">Hace falta iniciar sesión de nuevo</string>
|
||||
<string name="mcp_tools">Herramientas: %1$s</string>
|
||||
<string name="mcp_account">Sesión iniciada como %1$s</string>
|
||||
<string name="mcp_until">Sesión iniciada hasta %1$s</string>
|
||||
<string name="mcp_shared_note">Este servidor tiene un inicio de sesión compartido, que hace un administrador.</string>
|
||||
<string name="mcp_browser_note">El inicio de sesión se hace en el navegador, en la propia instancia. Si el navegador no tiene la sesión iniciada en la instancia, primero la pide. Después, vuelva aquí.</string>
|
||||
<string name="mcp_sign_in">Iniciar sesión</string>
|
||||
<string name="notebook_empty">Este cuaderno no tiene celdas.</string>
|
||||
<string name="notebook_more">No se muestran %1$s celdas más.</string>
|
||||
<string name="notebook_cell_cut">Esta celda es más larga de lo que se muestra aquí.</string>
|
||||
<string name="viewer_page">Página %1$s de %2$s</string>
|
||||
<string name="play">Reproducir</string>
|
||||
<string name="pause">Pausar</string>
|
||||
<string name="files_conflict">El archivo ha cambiado desde que lo abrió. Vuelva a cargarlo o guárdelo de todos modos.</string>
|
||||
<string name="files_save_anyway">Guardar de todos modos</string>
|
||||
<string name="reload">Recargar</string>
|
||||
<string name="discard">Descartar</string>
|
||||
<string name="files_unsaved">¿Descartar los cambios en este archivo?</string>
|
||||
<string name="share_to_files">Guardar en Archivos</string>
|
||||
<string name="settings">Ajustes</string>
|
||||
<string name="settings_instances">Instancias</string>
|
||||
<string name="sign_out">Cerrar sesión</string>
|
||||
<string name="add_instance">Añadir una instancia</string>
|
||||
<string name="instance_default">Predeterminado</string>
|
||||
<string name="instance_set_default">Establecer como predeterminada</string>
|
||||
<string name="instance_switch">Cambiar de instancia</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Como el sistema</string>
|
||||
<string name="theme_moria">Moria (oscuro)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Asistente</string>
|
||||
<string name="assistant_explained">Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.</string>
|
||||
<string name="assistant_open_settings">Abrir los ajustes del asistente</string>
|
||||
<string name="assistant_model">Modelo del asistente</string>
|
||||
<string name="assistant_model_default">Predeterminado de la instancia</string>
|
||||
<string name="assistant_model_default_line">El modelo con el que empiezan sus chats nuevos. Si es demasiado lento para una pregunta hablada, elija abajo uno más rápido.</string>
|
||||
<string name="assistant_samsung">En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.</string>
|
||||
<string name="assistant_temporary">Los chats del asistente son temporales</string>
|
||||
<string name="assistant_read_aloud">Leer la respuesta en voz alta cuando se pregunte por voz</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Como mucho una vez al día, al iniciarse, la aplicación pregunta a su instancia qué versión le corresponde —o lee la lista de versiones en GitHub cuando la instancia no puede decirlo— y le avisa con una notificación cuando hay una más reciente. Con ninguna de las dos consultas se envía nada sobre usted. 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>
|
||||
@@ -421,44 +553,51 @@
|
||||
<string name="assist_say_it">Dígalo y haga una pausa</string>
|
||||
<string name="assist_type">Escribir en su lugar</string>
|
||||
<string name="assist_writing_down">Escribiendo lo que ha dicho…</string>
|
||||
<string name="assist_unlock_to_send">Desbloquear para enviar</string>
|
||||
<string name="assist_question_heard">Pregunta oída</string>
|
||||
<string name="assist_recording_waits_line">El teléfono está bloqueado. Su pregunta espera en este teléfono como grabación; no se ha enviado nada. Al desbloquear se envía a su instancia para transcribirla y responderla.</string>
|
||||
<string name="assist_locked_line">El teléfono está bloqueado. Hasta que lo desbloquee no se envía nada ni se muestra ninguna respuesta.</string>
|
||||
<string name="assist_conversation">En conversación</string>
|
||||
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Di «para» para terminar.</string>
|
||||
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Diga «para» para terminar.</string>
|
||||
<string name="assist_conversation_end">Terminar</string>
|
||||
<string name="assist_stop_words">para|stop|basta|eso es todo|ya está|adiós|terminar|fin|gracias eso es todo|cancelar</string>
|
||||
<string name="assistant_conversation">Mantener una conversación hablada</string>
|
||||
<string name="assistant_conversation_line">Después de leer en voz alta una respuesta hablada, el asistente vuelve a escuchar, hasta que digas «para», toques Terminar o no digas nada durante unos segundos. Funciona con auriculares.</string>
|
||||
<string name="assist_wake_word_hint">Sin palabra de activación salvo que quieras una: Ajustes › Asistente › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
|
||||
<string name="assistant_conversation_line">Después de leer en voz alta una respuesta hablada, el asistente vuelve a escuchar, hasta que diga «para», toque Terminar o no diga nada durante unos segundos. Funciona con auriculares.</string>
|
||||
<string name="experimental">Experimental</string>
|
||||
<string name="wake_experimental_line">Nuevo y probado por ahora en pocos teléfonos. Puede no oír la frase, activarse por error u oírle y aun así no abrir el asistente.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimental: escuchar por sí solo al abrir el asistente, notar cuándo ha terminado de hablar y la conversación hablada son nuevos y todavía no funcionan bien en todos los teléfonos. Escribir una pregunta y el botón del micrófono funcionan siempre.</string>
|
||||
<string name="assist_wake_word_hint">Sin palabra de activación salvo que quiera una: Ajustes › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
|
||||
<string name="channel_wake">Palabra de activación</string>
|
||||
<string name="wake_word">Palabra de activación</string>
|
||||
<string name="wake_word_listen">Escuchar una palabra de activación</string>
|
||||
<string name="wake_word_line">Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.</string>
|
||||
<string name="wake_word_line">Desactivado por defecto. Diga la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.</string>
|
||||
<string name="wake_word_unavailable">No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.</string>
|
||||
<string name="wake_phrase_line">Lo que dices, y después una pausa breve: cuenta cuando te callas. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa.</string>
|
||||
<string name="wake_phrase_line">Lo que dice, y después una pausa breve: cuenta cuando se calla. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa.</string>
|
||||
<string name="wake_greeting">Saludo</string>
|
||||
<string name="wake_name">Nombre</string>
|
||||
<string name="wake_name_google_line">Un teléfono o altavoz de Google cercano también responderá.</string>
|
||||
<string name="wake_sensitivity">Sensibilidad</string>
|
||||
<string name="wake_sensitivity_low">Baja</string>
|
||||
<string name="wake_sensitivity_low_line">Es la que menos se activa por error. Puede que tengas que decir la frase con más claridad, o dos veces.</string>
|
||||
<string name="wake_sensitivity_low_line">Es la que menos se activa por error. Puede que tenga que decir la frase con más claridad, o dos veces.</string>
|
||||
<string name="wake_sensitivity_normal">Normal</string>
|
||||
<string name="wake_sensitivity_normal_line">El ajuste propio del motor.</string>
|
||||
<string name="wake_sensitivity_high">Alta</string>
|
||||
<string name="wake_sensitivity_high_line">Te oye con más facilidad, también desde más lejos. Se activa por error más a menudo.</string>
|
||||
<string name="wake_sensitivity_high_line">Le oye con más facilidad, también desde más lejos. Se activa por error más a menudo.</string>
|
||||
<string name="wake_test">Probar la palabra de activación</string>
|
||||
<string name="wake_test_line">Durante diez segundos muestra si se oye tu frase, sin abrir el asistente.</string>
|
||||
<string name="wake_test_say">Di «%1$s» ahora y haz una pausa…</string>
|
||||
<string name="wake_test_line">Durante diez segundos muestra si se oye su frase, sin abrir el asistente.</string>
|
||||
<string name="wake_test_say">Diga «%1$s» ahora y haga una pausa…</string>
|
||||
<string name="wake_test_heard">Oída</string>
|
||||
<string name="wake_test_missed">No se ha oído en diez segundos. Prueba más cerca del teléfono, en un momento más tranquilo o con más sensibilidad.</string>
|
||||
<string name="wake_test_off">Activa primero la palabra de activación.</string>
|
||||
<string name="wake_test_missed">No se ha oído en diez segundos. Pruebe más cerca del teléfono, en un momento más tranquilo o con más sensibilidad.</string>
|
||||
<string name="wake_test_off">Active primero la palabra de activación.</string>
|
||||
<string name="wake_screen_only">Solo con la pantalla encendida</string>
|
||||
<string name="wake_screen_only_line">Desactivado: también escucha con la pantalla apagada, con más gasto de batería.</string>
|
||||
<string name="wake_battery">Dejar que funcione en segundo plano</string>
|
||||
<string name="wake_battery_line">Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluye aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de tu teléfono.</string>
|
||||
<string name="wake_battery_line">Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluya aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de su teléfono.</string>
|
||||
<string name="wake_word_privacy">Nada sale del teléfono antes de la palabra. El sonido del micrófono va solo al motor de palabra de activación del teléfono y no se guarda; la notificación se mantiene mientras escucha. Las frases están en inglés; el motor es sherpa-onnx (código abierto).</string>
|
||||
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.</string>
|
||||
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambie, con la pantalla apagada. Tras reiniciar, toque su notificación para volver a iniciarlo.</string>
|
||||
<string name="wake_listening_for">Escuchando «%1$s»</string>
|
||||
<string name="wake_off">La palabra de activación no está escuchando</string>
|
||||
<string name="wake_tap_to_start">Toca para iniciarla de nuevo. Si Android pregunta, permite el micrófono.</string>
|
||||
<string name="wake_tap_to_start">Toque para iniciarla de nuevo. Si Android pregunta, permita el micrófono.</string>
|
||||
<string name="wake_starting">Iniciando la palabra de activación…</string>
|
||||
<string name="wake_paused_silent">La palabra de activación no oye nada: otra app tiene el micrófono, o el micrófono del teléfono está apagado</string>
|
||||
<string name="wake_failed_no_engine">La palabra de activación no funciona: esta versión no tiene motor</string>
|
||||
@@ -466,17 +605,17 @@
|
||||
<string name="wake_failed_engine">La palabra de activación no funciona: el motor no se inició</string>
|
||||
<string name="wake_failed_microphone">La palabra de activación no funciona: el micrófono no se inició</string>
|
||||
<string name="wake_failed_line">No está escuchando. Lo intenta de nuevo por sí sola.</string>
|
||||
<string name="wake_notification_line">Nada sale del teléfono hasta que lo digas.</string>
|
||||
<string name="wake_notification_line">Nada sale del teléfono hasta que lo diga.</string>
|
||||
<string name="wake_paused_screen">Palabra de activación en pausa: la pantalla está apagada</string>
|
||||
<string name="wake_paused_battery">Palabra de activación en pausa: ahorro de batería activado</string>
|
||||
<string name="wake_paused_assistant">Palabra de activación en pausa mientras el asistente está abierto</string>
|
||||
<string name="wake_paused_microphone">Palabra de activación en pausa: LLeMbas no tiene permiso para usar el micrófono</string>
|
||||
<string name="wake_stop">Dejar de escuchar</string>
|
||||
<string name="wake_heard">Te he oído. Toca para preguntar.</string>
|
||||
<string name="wake_heard">Le he oído. Toque para preguntar.</string>
|
||||
<string name="channel_wake_heard">Palabra de activación oída</string>
|
||||
<string name="wake_heard_line">LLeMbas solo puede abrirse por sí mismo sobre otras apps si es la app de asistente digital del teléfono.</string>
|
||||
<string name="wake_not_assistant">LLeMbas no es la app de asistente digital</string>
|
||||
<string name="wake_not_assistant_line">Por eso la palabra de activación no puede abrir el asistente sobre otras apps: recibes una notificación que tocar. Para abrir con la voz en cualquier parte, toca aquí y elige LLeMbas como app de asistente digital.</string>
|
||||
<string name="wake_not_assistant_line">Por eso la palabra de activación no puede abrir el asistente sobre otras apps: recibe una notificación que tocar. Para abrir con la voz en cualquier parte, toque aquí y elija LLeMbas como app de asistente digital.</string>
|
||||
<string name="wake_last">Última activación</string>
|
||||
<string name="wake_last_none">Todavía no ha oído la frase.</string>
|
||||
<string name="wake_out_opened">Abrió el asistente.</string>
|
||||
@@ -498,24 +637,24 @@
|
||||
<string name="wake_waited">Esperó un momento a que Android lo conectara.</string>
|
||||
<string name="wake_show_failed">Android dijo que no pudo mostrar el panel del asistente.</string>
|
||||
<string name="wake_assistant_inactive">Android no está usando LLeMbas como asistente de voz ahora mismo</string>
|
||||
<string name="wake_assistant_inactive_line">Elige de nuevo LLeMbas como app de asistente digital: toca aquí, elige otra app y luego LLeMbas. Hasta entonces la pulsación larga lo abre como una pantalla normal y la palabra de activación solo puede enviar una notificación.</string>
|
||||
<string name="wake_assistant_inactive_line">Elija de nuevo LLeMbas como app de asistente digital: toque aquí, elija otra app y luego LLeMbas. Hasta entonces la pulsación larga lo abre como una pantalla normal y la palabra de activación solo puede enviar una notificación.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas es el asistente, pero Android no lo tiene conectado ahora mismo</string>
|
||||
<string name="wake_assistant_unbound_line">Hasta que lo conecte, la palabra de activación no puede abrir el panel por sí sola. Toca para ir al ajuste del asistente del sistema: elegir otra app y luego LLeMbas de nuevo lo conecta.</string>
|
||||
<string name="wake_heard_could_not">No pudo abrirse por sí solo: toca para preguntar</string>
|
||||
<string name="wake_assistant_unbound_line">Hasta que lo conecte, la palabra de activación no puede abrir el panel por sí sola. Toque para ir al ajuste del asistente del sistema: elegir otra app y luego LLeMbas de nuevo lo conecta.</string>
|
||||
<string name="wake_heard_could_not">No pudo abrirse por sí solo: toque para preguntar</string>
|
||||
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
|
||||
<string name="wake_resume_line">El teléfono se reinició. Toca para volver a escuchar.</string>
|
||||
<string name="wake_resume_line">El teléfono se reinició. Toque para volver a escuchar.</string>
|
||||
<string name="assist_notifications">Resumir mis notificaciones</string>
|
||||
<string name="assist_notifications_prompt">Resume mis notificaciones: ¿qué necesita mi atención?</string>
|
||||
<string name="assist_notifications_phrases">mis notificaciones</string>
|
||||
<string name="notification_summaries">Resúmenes de notificaciones</string>
|
||||
<string name="notification_summaries_switch">Dejar que el asistente lea mis notificaciones cuando lo pida</string>
|
||||
<string name="notification_summaries_line">Pide «resume mis notificaciones» o toca el botón en el asistente.</string>
|
||||
<string name="notification_summaries_line">Pida «resume mis notificaciones» o toque el botón en el asistente.</string>
|
||||
<string name="notification_summaries_unavailable">No en esta versión. Leer notificaciones requiere la versión «notifications» de LLeMbas, porque Google Play Protect bloquea la instalación de una app de fuera de Play Store que pueda leerlas. Es la misma app con la misma firma: en la página de la versión, el archivo que termina en -notifications.apk se instala sobre esta.</string>
|
||||
<string name="update_notifications_manual">Esta es la versión «notifications»: instala la actualización desde su página, el archivo que termina en -notifications.apk.</string>
|
||||
<string name="notification_access">Acceso a notificaciones</string>
|
||||
<string name="notification_access_on">Concedido. El interruptor de Android está en los ajustes del sistema.</string>
|
||||
<string name="notification_access_off">Aún no concedido. Toca para abrir el interruptor de Android para LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Desactivado por defecto. Cuando lo pides, el texto de las notificaciones que hay ahora en tu teléfono (app, título, texto) va con esa única pregunta a tu instancia y su modelo. No se lee nada antes, la app no guarda nada y no se lee nada con el teléfono bloqueado. El acceso a notificaciones de Android permite a una app ver todas las notificaciones; darlo y retirarlo es cosa tuya.</string>
|
||||
<string name="notification_access_off">Aún no concedido. Toque para abrir el interruptor de Android para LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Desactivado por defecto. Cuando lo pide, el texto de las notificaciones que hay ahora en su teléfono (app, título, texto) va con esa única pregunta a su instancia y su modelo. No se lee nada antes, la app no guarda nada y no se lee nada con el teléfono bloqueado. El acceso a notificaciones de Android permite a una app ver todas las notificaciones; darlo y retirarlo es cosa suya.</string>
|
||||
<string name="nav_app">App de navegación</string>
|
||||
<string name="nav_app_auto">La que esté instalada</string>
|
||||
<string name="nav_app_google">Google Maps</string>
|
||||
@@ -523,39 +662,76 @@
|
||||
<string name="nav_app_ask">Preguntar cada vez</string>
|
||||
<string name="nav_app_not_installed">No instalada</string>
|
||||
<string name="osmand_info">Preguntar a OsmAnd por la ruta</string>
|
||||
<string name="osmand_info_line">Permite «añadir una parada» y buscar cerca de ti con una ruta creada en el propio OsmAnd: LLeMbas pregunta a OsmAnd dónde estás y adónde va la ruta. Primero permite LLeMbas en OsmAnd (apps conectadas, con ubicación); OsmAnd te avisa si no está permitido.</string>
|
||||
<string name="phone_actions_line">Un modelo puede ofrecer hacer cosas en este teléfono: poner una alarma, añadir un evento, redactar un mensaje, iniciar una ruta. No pasa nada hasta que tocas Hacerlo en su tarjeta, y nunca con el teléfono bloqueado. Google Maps inicia una ruta con unas pocas paradas, pero no puede añadir una a una ruta en curso ni detenerse a petición; OsmAnd sí.</string>
|
||||
<string name="action_card_title">¿Hacer esto en tu teléfono?</string>
|
||||
<string name="osmand_info_line">Permite «añadir una parada» y buscar cerca de usted con una ruta creada en el propio OsmAnd: LLeMbas pregunta a OsmAnd dónde está usted y adónde va la ruta. Primero permita LLeMbas en OsmAnd (apps conectadas, con ubicación); OsmAnd le avisa si no está permitido.</string>
|
||||
<string name="phone_actions_line">Un modelo puede ofrecer hacer cosas en este teléfono: poner una alarma, añadir un evento, redactar un mensaje, iniciar una ruta. No pasa nada hasta que toca Hacerlo en su tarjeta, y nunca con el teléfono bloqueado. Google Maps inicia una ruta con unas pocas paradas, pero no puede añadir una a una ruta en curso ni detenerse a petición; OsmAnd sí.</string>
|
||||
<string name="action_card_title">¿Hacer esto en su teléfono?</string>
|
||||
<string name="action_do">Hacerlo</string>
|
||||
<string name="action_running">Haciéndolo…</string>
|
||||
<string name="action_unlock">Desbloquea primero el teléfono y luego toca Hacerlo.</string>
|
||||
<string name="action_unlock">Desbloquee primero el teléfono y luego toque Hacerlo.</string>
|
||||
<string name="action_failed">No funcionó: %1$s</string>
|
||||
<string name="nav_app_pick">¿Con qué app de mapas?</string>
|
||||
<string name="action_google_add_stop">Google Maps no puede añadir una parada a una ruta en curso: vuelve a iniciar la ruta, pasando por la parada.</string>
|
||||
<string name="action_google_no_stop">A Google Maps no se le puede pedir que pare: termina la ruta allí.</string>
|
||||
<string name="action_line_clock">La app de reloj lo programa.</string>
|
||||
<string name="action_line_calendar">El calendario se abre con el evento rellenado; tú lo guardas.</string>
|
||||
<string name="action_line_draft">Abre un borrador; lo envías tú.</string>
|
||||
<string name="action_line_dial">El marcador se abre con el número; tú haces la llamada.</string>
|
||||
<string name="action_line_calendar">El calendario se abre con el evento rellenado; usted lo guarda.</string>
|
||||
<string name="action_line_draft">Abre un borrador; lo envía usted.</string>
|
||||
<string name="action_line_dial">El marcador se abre con el número; usted hace la llamada.</string>
|
||||
<string name="action_line_map">%1$s se encarga de la ruta.</string>
|
||||
<string name="action_line_now">Ocurre al instante.</string>
|
||||
<string name="action_line_settings">Abre el ajuste; tú lo cambias.</string>
|
||||
<string name="action_line_automation">Ejecuta tu automatización (Tasker salvo que se indique otra app).</string>
|
||||
<string name="action_line_settings">Abre el ajuste; usted lo cambia.</string>
|
||||
<string name="action_line_automation">Ejecuta su automatización (Tasker salvo que se indique otra app).</string>
|
||||
<string name="action_line_open">Lo abre.</string>
|
||||
<string name="assist_recogniser_failed">El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.</string>
|
||||
<string name="assistant_listens">Empezar a escuchar al abrir el asistente</string>
|
||||
<string name="voice_input">Entrada de voz</string>
|
||||
<string name="voice_input_lembas">LLeMbas</string>
|
||||
<string name="voice_input_lembas_line">La conversión de voz a texto de su instancia, a través del servidor. La grabación va a su instancia y a ningún otro sitio.</string>
|
||||
<string name="voice_input_lembas_line">La conversión de voz a texto de su instancia. Este teléfono envía la grabación solo a su instancia; la instancia la transcribe con el modelo de voz configurado en ella.</string>
|
||||
<string name="voice_input_phone">Teléfono (Google o el del sistema)</string>
|
||||
<string name="voice_input_phone_line">El reconocimiento de voz del propio teléfono. Las palabras aparecen mientras habla; la grabación va adonde ese reconocimiento la envíe.</string>
|
||||
<string name="voice_input_phone_none">Este teléfono no tiene reconocimiento de voz propio.</string>
|
||||
<string name="voice_input_hint">La usan el asistente y el micrófono de un chat. Con LLeMbas el asistente muestra las palabras un momento después y una pausa las envía, y un chat las escribe cuando usted para; con el reconocimiento del teléfono aparecen mientras habla.</string>
|
||||
<string name="share_sending">Enviando a LLeMbas…</string>
|
||||
<string name="share_default_prompt">Échele un vistazo a esto.</string>
|
||||
<string name="share_default_prompt">Échale un vistazo a esto.</string>
|
||||
<string name="share_ask_hint">¿Qué debe hacer LLeMbas con esto? (opcional)</string>
|
||||
<string name="widget_hint">Pregunta lo que quieras</string>
|
||||
<string name="widget_hint">Pregunte lo que quiera</string>
|
||||
<string name="directory_places">Lugares de este dispositivo</string>
|
||||
<string name="directory_last_used">Último usado aquí: %1$s. Un chat nuevo en este directorio empieza con él salvo que elija otro.</string>
|
||||
<string name="directory_refused">El dispositivo no abrirá una sesión aquí.</string>
|
||||
<string name="directory_up">Subir un nivel</string>
|
||||
<string name="directory_all_places">Todos los lugares</string>
|
||||
<string name="directory_not_trusted">No es de confianza en el dispositivo</string>
|
||||
<string name="directory_empty">Aquí no hay carpetas.</string>
|
||||
<string name="directory_no_places">Este dispositivo no ofrece carpetas: sus raíces remotas están vacías o no existen.</string>
|
||||
<string name="directory_browse">Examinar</string>
|
||||
<string name="directory_path">Una ruta completa</string>
|
||||
<string name="directory_choose">Elegir</string>
|
||||
<string name="directory_no_listing">Ahora no se pueden listar las carpetas de este dispositivo. Escriba la ruta abajo.</string>
|
||||
<string name="model">Modelo</string>
|
||||
<string name="schedule_type">Tipo</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Se ejecuta en este servidor, como un chat: con las herramientas del servidor (búsqueda, sus archivos aquí, memoria) y en un modelo de programación.</string>
|
||||
<string name="schedule_agentic">Agéntico</string>
|
||||
<string name="schedule_agentic_line">Se ejecuta en uno de sus ordenadores, en una carpeta de él, como agente: con las herramientas del agente en ese ordenador — sus archivos y su shell — dentro de los límites propios del ordenador. Pertenece a ese ordenador y a esa carpeta.</string>
|
||||
<string name="schedule_agentic_unavailable">Ninguno de sus ordenadores acepta trabajo programado ahora. Vincule uno y active «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">no acepta trabajo programado</string>
|
||||
<string name="schedule_computer_hint">El ordenador debe permitirlo: «Accept scheduled work» en su LLeMbas CLI (lembas service scheduled on). Si no está vinculado en el momento de una ejecución, la ejecución lo espera; si no ha vuelto antes de que pase su hora, la ejecución se registra como perdida y se le avisa.</string>
|
||||
<string name="schedule_computer_gone">un ordenador que ya no tiene sesión iniciada</string>
|
||||
<string name="schedule_folder">Carpeta en el ordenador</string>
|
||||
<string name="schedule_agent_mode">Modo</string>
|
||||
<string name="schedule_agent_mode_hint">Edit salvo que elijas otro; Auto ejecuta comandos sin preguntar. El ordenador puede rebajarlo.</string>
|
||||
<string name="schedule_approval_wait">Una aprobación espera (minutos)</string>
|
||||
<string name="schedule_approval_wait_hint">Un comando que la ejecución necesita aprobar llega a tu teléfono como tarjeta. Sin respuesta para entonces, cuenta como denegado.</string>
|
||||
<string name="schedule_watch_command_hint">Opcional, en el ordenador. Se ejecuta en la carpeta antes de cada ejecución; cuando su salida es la misma que la última vez, la ejecución se detiene ahí. Se rechaza un comando por el que el modo preguntaría.</string>
|
||||
<string name="schedule_watch_timeout">El comando puede tardar (segundos)</string>
|
||||
<string name="schedule_watch_timeout_hint">Después se detiene y la ejecución falla.</string>
|
||||
<string name="schedule_chat_drops_watch">Esta tarea vigila un comando en su ordenador. Como tarea de tipo Chat ya no lo hace: se ejecuta siempre.</string>
|
||||
<string name="schedule_folder_model">El modelo habitual de la carpeta</string>
|
||||
<string name="schedule_folder_model_hint">El modelo habitual de la carpeta es el último que usó en esa carpeta de ese ordenador — el ordenador lo recuerda y cada ejecución se lo pregunta — o su modelo predeterminado donde no hay ninguno. Un modelo elegido aquí es el de la ejecución, sea cual sea el de la carpeta. Una ejecución nunca cambia el modelo de la carpeta.</string>
|
||||
<string name="schedule_first_free_model">El primero libre de sus modelos para programación</string>
|
||||
<string name="run_model_directory">el modelo habitual de la carpeta</string>
|
||||
<string name="run_model_default">su modelo predeterminado</string>
|
||||
<string name="run_model_session">el modelo propio de la conversación</string>
|
||||
<string name="widget_speak">Hablar</string>
|
||||
<string name="widget_description">Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.</string>
|
||||
<string name="widget_description">Pregunte por voz o por texto, o continúe el último chat del asistente. No muestra nada de su cuenta.</string>
|
||||
<string name="shortcut_last">Último chat</string>
|
||||
</resources>
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas pour Android</string>
|
||||
<string name="share_label">Demander à LLeMbas</string>
|
||||
<string name="tile_ask">Demander à LLeMbas</string>
|
||||
<string name="signin_intro">Connectez-vous à une instance LLeMbas. Vous approuvez ce téléphone dans le navigateur, comme vous le feriez pour la CLI.</string>
|
||||
<string name="signin_intro">Connectez-vous à une instance LLeMbas. Vous approuvez ce téléphone dans le navigateur.</string>
|
||||
<string name="signin_address">Adresse de l\'instance</string>
|
||||
<string name="signin_continue">Continuer</string>
|
||||
<string name="signin_code_intro">Ouvrez l\'instance dans le navigateur, connectez-vous et approuvez ce code :</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Cette instance est plus récente que ce que cette application prend en charge. Mettez à jour l\'application.</string>
|
||||
<string name="signin_not_lembas">Il n\'y a pas d\'instance LLeMbas à cette adresse.</string>
|
||||
<string name="signin_failed">La connexion n\'a pas pu aboutir (%1$s). Réessayez.</string>
|
||||
<string name="signin_app_too_old">Cette instance nécessite LLeMbas pour Android %1$s ou plus récent, et ceci est la version %2$s. Mettez à jour l\'application.</string>
|
||||
<string name="signin_other_origin">Cette instance indique pour la connexion une autre adresse (%1$s) que celle que vous avez saisie. Son proxy doit transmettre l\'adresse par laquelle elle est jointe.</string>
|
||||
<string name="address_needs_https">Cette application a besoin d\'une adresse https:// : le simple http n\'est pas pris en charge.</string>
|
||||
<string name="address_unreadable">L\'application ne peut pas utiliser cette adresse. Saisissez l\'adresse de l\'instance, par exemple llm.example.org.</string>
|
||||
<string name="server_answered">Le serveur a répondu %1$s.</string>
|
||||
<string name="timed_out">L\'instance n\'a pas répondu à temps.</string>
|
||||
<string name="not_trusted">Ce téléphone ne fait pas confiance au certificat de l\'instance : installez le certificat de son autorité de certification parmi les certificats utilisateur d\'Android (Paramètres, Sécurité, Chiffrement et identifiants, Installer un certificat).</string>
|
||||
<string name="signed_out">%1$s a déconnecté ce téléphone. Reconnectez-vous pour continuer : vos conversations et vos réglages ici sont conservés.</string>
|
||||
<string name="signed_out_again">Se reconnecter</string>
|
||||
<string name="signed_out_use">Utiliser %1$s</string>
|
||||
<string name="signed_out_remove">Retirer cette instance</string>
|
||||
<string name="new_chat">Nouvelle conversation</string>
|
||||
<string name="empty_chats">Pas encore de conversation. Tous ceux qui errent ne sont pas perdus — commencez-en une.</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="agent_device">Ordinateur</string>
|
||||
<string name="agent_no_device">Aucun ordinateur n\'est associé pour l\'instant. Lancez le service de la CLI LLeMbas (lembas service) sur un ordinateur connecté à cette instance, puis revenez.</string>
|
||||
<string name="agent_directory">Dossier sur l’ordinateur</string>
|
||||
<string name="agent_directory_hint">Vide : le premier dossier de l\'ordinateur</string>
|
||||
<string name="empty_chat">De quoi allons-nous parler ?</string>
|
||||
<string name="loading_line">Cuisson des lembas…</string>
|
||||
<string name="archive">Archiver</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Continuer</string>
|
||||
<string name="older">Messages précédents</string>
|
||||
<string name="queued">En attente d\'envoi</string>
|
||||
<string name="fate_unknown">On ne sait pas si ce message est parvenu à l’ordinateur. Renvoyez-le ou supprimez-le.</string>
|
||||
<string name="fate_carried">L’ordinateur a ce message et le prendra en compte à son prochain tour.</string>
|
||||
<string name="send_now">Envoyer maintenant</string>
|
||||
<string name="discard_message_confirm">Abandonner ce message ?</string>
|
||||
<string name="reply_unrecorded">La réponse à ceci n’a pas été enregistrée.</string>
|
||||
<string name="thinking">Réflexion</string>
|
||||
<string name="thought">Réflexion</string>
|
||||
<string name="output_cut">La sortie est raccourcie ici. Vous la trouverez en entier sur la page web.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Transcrit par %1$s : le modèle vocal propre à cette conversation n\'a pas répondu.</string>
|
||||
<string name="read_by_fallback">Lu par %1$s : le modèle vocal propre à cette conversation n\'a pas répondu.</string>
|
||||
<string name="remove">Retirer</string>
|
||||
<string name="more">Plus</string>
|
||||
<string name="back">Retour</string>
|
||||
@@ -136,19 +156,19 @@
|
||||
<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_hint">Les nombres comptent l\'agent de cette conversation : 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="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 la conversation.</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_open">Ouvrir les conversations</string>
|
||||
<string name="chats_search">Rechercher dans les conversations</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_agents">Conversations 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="chats_none_found">Aucune conversation 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>
|
||||
@@ -208,7 +228,7 @@
|
||||
<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_delete_confirm">Supprimer cette planification ? Ses résultats passés restent dans leurs conversations.</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>
|
||||
@@ -234,8 +254,8 @@
|
||||
<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="mode_fresh">Une nouvelle conversation à chaque fois</string>
|
||||
<string name="mode_continue">Une conversation 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>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Cette instance 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="files_upload">Envoyer</string>
|
||||
<string name="files_new_file">Nouveau fichier</string>
|
||||
<string name="files_new_file_ask">Comment le fichier doit-il s’appeler ? Avec son extension, par exemple notes.md.</string>
|
||||
<string name="files_new_folder_ask">Comment le dossier doit-il s\'appeler ?</string>
|
||||
<string name="files_bad_name">Un nom ne peut être ni vide ni contenir de barre oblique.</string>
|
||||
<string name="files_taken">Il y a déjà quelque chose nommé %1$s ici.</string>
|
||||
<string name="rename">Renommer</string>
|
||||
<string name="files_new_name">Nouveau nom</string>
|
||||
<string name="files_move">Déplacer</string>
|
||||
<string name="files_copy_to">Copier vers…</string>
|
||||
<string name="files_move_here">Déplacer ici</string>
|
||||
<string name="files_copy_here">Copier ici</string>
|
||||
<string name="files_move_which">Déplacer vers quel dossier ?</string>
|
||||
<string name="files_copy_which">Copier vers quel dossier ?</string>
|
||||
<string name="files_choose_folder">Choisir un dossier</string>
|
||||
<string name="files_save_here">Enregistrer ici</string>
|
||||
<string name="files_no_folders">Aucun dossier ici.</string>
|
||||
<string name="files_to_trash">Placer dans la corbeille</string>
|
||||
<string name="files_trash_one">Placer « %1$s » dans la corbeille ? On peut l\'y restaurer.</string>
|
||||
<string name="files_trash_many">Placer les %1$s éléments sélectionnés dans la corbeille ? Ils peuvent y être restaurés.</string>
|
||||
<string name="files_trashed">Placé dans la corbeille.</string>
|
||||
<string name="files_selected">Sélectionnés : %1$s</string>
|
||||
<string name="files_select_all">Tout sélectionner</string>
|
||||
<string name="download">Télécharger</string>
|
||||
<string name="files_download_zip">Télécharger en zip</string>
|
||||
<string name="files_downloading">Téléchargement…</string>
|
||||
<string name="files_downloaded">Téléchargé.</string>
|
||||
<string name="files_uploading">Envoi de %1$s sur %2$s…</string>
|
||||
<string name="files_uploaded">Envoyé.</string>
|
||||
<string name="files_open_with">Ouvrir avec…</string>
|
||||
<string name="files_no_app">Aucune application de ce téléphone n’ouvre ce type de fichier.</string>
|
||||
<string name="trash">Corbeille</string>
|
||||
<string name="trash_is_empty">La corbeille est vide.</string>
|
||||
<string name="trash_empty">Vider la corbeille</string>
|
||||
<string name="trash_empty_confirm">Supprimer définitivement tout le contenu de la corbeille ? C’est irréversible.</string>
|
||||
<string name="trash_remove">Supprimer définitivement</string>
|
||||
<string name="trash_remove_confirm">Supprimer définitivement « %1$s » ? C’est irréversible.</string>
|
||||
<string name="restore">Restaurer</string>
|
||||
<string name="versions">Versions</string>
|
||||
<string name="version_restore">Restaurer cette version</string>
|
||||
<string name="version_restore_confirm">Faire de cette version l\'actuelle ? L\'actuelle reste dans la liste.</string>
|
||||
<string name="version_current">Actuelle</string>
|
||||
<string name="files_type">Type</string>
|
||||
<string name="files_size">Taille</string>
|
||||
<string name="files_no_viewer">Il n\'y a pas de visionneuse pour ce type de fichier.</string>
|
||||
<string name="files_not_shown">Ce fichier n\'a pas pu être affiché ici. Il peut toujours être téléchargé.</string>
|
||||
<string name="files_svg_source">Ceci est la source de l’image. Ouvrez-la avec une autre application pour voir l’image.</string>
|
||||
<string name="archive_note">Le contenu de ce type d\'archive ne peut pas être listé ici.</string>
|
||||
<string name="archive_entries">%1$s entrées. Rien n\'est décompressé ici.</string>
|
||||
<string name="archive_cut">Seules les %1$s premières entrées sont listées.</string>
|
||||
<string name="archive_unreadable">Cette archive n\'a pas pu être lue.</string>
|
||||
<string name="files_waiting">En attente que l\'application soit ouverte et le téléphone déverrouillé.</string>
|
||||
<string name="share_refused">Un élément partagé ne peut pas être envoyé d\'ici et a été laissé de côté.</string>
|
||||
<string name="media_in_trash">Ce fichier est dans la corbeille.</string>
|
||||
<string name="table_cut">Seules les premières lignes et colonnes sont mises en tableau. Le texte contient tout.</string>
|
||||
<string name="table_as_text">Afficher comme texte</string>
|
||||
<string name="table_as_table">Afficher comme tableau</string>
|
||||
<string name="media_open_in_files">Ouvrir dans Fichiers</string>
|
||||
<string name="media_image">Image</string>
|
||||
<string name="media_video">Vidéo</string>
|
||||
<string name="media_music">Musique</string>
|
||||
<string name="media_model">Modèle 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archive</string>
|
||||
<string name="media_text">Fichier texte</string>
|
||||
<string name="media_binary">Fichier</string>
|
||||
<string name="diff_deleted">Supprimé</string>
|
||||
<string name="diff_counts">Lignes ajoutées : %1$s, supprimées : %2$s</string>
|
||||
<string name="diff_show_all">Afficher les %1$s lignes</string>
|
||||
<string name="diff_show_less">Afficher moins</string>
|
||||
<string name="diff_more">%1$s lignes de plus ne sont pas affichées ici.</string>
|
||||
<string name="diff_endings">Les fins de ligne passent de %1$s à %2$s.</string>
|
||||
<string name="diff_cut">Cette modification est trop longue pour être comparée ici. Seul son début est affiché.</string>
|
||||
<string name="media_gone">Ce fichier n\'existe plus.</string>
|
||||
<string name="job_queued">En file d’attente</string>
|
||||
<string name="job_running">En cours</string>
|
||||
<string name="job_done">Terminé</string>
|
||||
<string name="job_failed">Échecs</string>
|
||||
<string name="job_cancelled">Annulé</string>
|
||||
<string name="job_expired">Expiré</string>
|
||||
<string name="mcp_title">Serveurs MCP</string>
|
||||
<string name="mcp_intro">Les serveurs dont les outils peuvent être proposés dans vos conversations. Certains s’utilisent avec un compte à vous chez eux : leurs outils sont proposés tant que vous y êtes connecté.</string>
|
||||
<string name="mcp_none">Aucun serveur MCP ne vous est proposé sur cette instance.</string>
|
||||
<string name="mcp_ready">Prêt</string>
|
||||
<string name="mcp_signed_in">Connecté</string>
|
||||
<string name="mcp_signed_out">Non connecté</string>
|
||||
<string name="mcp_needs_signin">Nouvelle connexion nécessaire</string>
|
||||
<string name="mcp_tools">Outils : %1$s</string>
|
||||
<string name="mcp_account">Connecté en tant que %1$s</string>
|
||||
<string name="mcp_until">Connecté jusqu’au %1$s</string>
|
||||
<string name="mcp_shared_note">Ce serveur a une connexion partagée, établie par un administrateur.</string>
|
||||
<string name="mcp_browser_note">La connexion se fait dans le navigateur, sur l’instance elle-même. Si le navigateur n’y est pas connecté, il le demande d’abord. Revenez ensuite ici.</string>
|
||||
<string name="mcp_sign_in">Se connecter</string>
|
||||
<string name="notebook_empty">Ce notebook n\'a aucune cellule.</string>
|
||||
<string name="notebook_more">%1$s autres cellules ne sont pas affichées.</string>
|
||||
<string name="notebook_cell_cut">Cette cellule est plus longue que ce qui est affiché ici.</string>
|
||||
<string name="viewer_page">Page %1$s sur %2$s</string>
|
||||
<string name="play">Lire</string>
|
||||
<string name="pause">Mettre en pause</string>
|
||||
<string name="files_conflict">Le fichier a changé depuis que vous l\'avez ouvert. Rechargez-le, ou enregistrez quand même.</string>
|
||||
<string name="files_save_anyway">Enregistrer quand même</string>
|
||||
<string name="reload">Recharger</string>
|
||||
<string name="discard">Abandonner</string>
|
||||
<string name="files_unsaved">Abandonner les modifications de ce fichier ?</string>
|
||||
<string name="share_to_files">Enregistrer dans Fichiers</string>
|
||||
<string name="settings">Paramètres</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Se déconnecter</string>
|
||||
<string name="add_instance">Ajouter une instance</string>
|
||||
<string name="instance_default">Par défaut</string>
|
||||
<string name="instance_set_default">Définir par défaut</string>
|
||||
<string name="instance_switch">Changer d’instance</string>
|
||||
<string name="settings_theme">Thème</string>
|
||||
<string name="theme_system">Comme le système</string>
|
||||
<string name="theme_moria">Moria (sombre)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Faites de LLeMbas l\'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d\'assistance numérique. Maintenir le bouton d\'alimentation, le geste d\'assistance ou le raccourci de l\'écran de verrouillage l\'ouvrira alors par-dessus ce qui est affiché.</string>
|
||||
<string name="assistant_open_settings">Ouvrir les paramètres de l\'assistant</string>
|
||||
<string name="assistant_model">Modèle de l’assistant</string>
|
||||
<string name="assistant_model_default">Modèle par défaut de l’instance</string>
|
||||
<string name="assistant_model_default_line">Le modèle avec lequel commencent vos nouvelles conversations. S’il est trop lent pour une question orale, choisissez-en un plus rapide ci-dessous.</string>
|
||||
<string name="assistant_samsung">Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.</string>
|
||||
<string name="assistant_temporary">Les conversations de l\'assistant sont temporaires</string>
|
||||
<string name="assistant_read_aloud">Lire la réponse à voix haute en cas de question orale</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Au plus une fois par jour, au démarrage, l’application demande à votre instance quelle version lui correspond — ou lit la liste des versions sur GitHub quand l’instance ne peut pas le dire — et vous prévient par une notification lorsqu’il en existe une plus récente. Aucune de ces deux requêtes n’envoie quoi que ce soit sur vous. 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>
|
||||
@@ -421,13 +553,20 @@
|
||||
<string name="assist_say_it">Dites-le, puis marquez une pause</string>
|
||||
<string name="assist_type">Taper plutôt</string>
|
||||
<string name="assist_writing_down">Transcription de ce que vous avez dit…</string>
|
||||
<string name="assist_unlock_to_send">Déverrouiller pour envoyer</string>
|
||||
<string name="assist_question_heard">Question entendue</string>
|
||||
<string name="assist_recording_waits_line">Le téléphone est verrouillé. Votre question attend sur ce téléphone sous forme d’enregistrement ; rien n’a été envoyé. Au déverrouillage, elle est envoyée à votre instance pour être transcrite et recevoir une réponse.</string>
|
||||
<string name="assist_locked_line">Le téléphone est verrouillé. Rien n’est envoyé et aucune réponse n’est affichée tant que vous ne l’avez pas déverrouillé.</string>
|
||||
<string name="assist_conversation">En conversation</string>
|
||||
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
|
||||
<string name="assist_conversation_end">Terminer</string>
|
||||
<string name="assist_stop_words">stop|arrête|c\'est tout|ça suffit|au revoir|fin|terminé|merci c\'est tout|annuler</string>
|
||||
<string name="assistant_conversation">Poursuivre une conversation orale</string>
|
||||
<string name="assistant_conversation_line">Après la lecture d’une réponse orale, l’assistant écoute à nouveau — jusqu’à ce que vous disiez « stop », touchiez Terminer ou ne disiez rien pendant quelques secondes. Fonctionne avec un casque.</string>
|
||||
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Assistant › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
|
||||
<string name="experimental">Expérimental</string>
|
||||
<string name="wake_experimental_line">Nouveau, et essayé sur peu de téléphones pour l’instant. Il peut ne pas entendre la phrase, se déclencher par erreur, ou vous entendre sans pour autant ouvrir l’assistant.</string>
|
||||
<string name="assistant_voice_experimental_line">Expérimental : l’écoute automatique à l’ouverture de l’assistant, la détection de la fin de votre phrase et la conversation orale sont nouvelles et ne fonctionnent pas encore bien sur tous les téléphones. Écrire une question et le bouton du micro fonctionnent toujours.</string>
|
||||
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
|
||||
<string name="channel_wake">Mot d’activation</string>
|
||||
<string name="wake_word">Mot d’activation</string>
|
||||
<string name="wake_word_listen">Écouter un mot d’activation</string>
|
||||
@@ -546,16 +685,53 @@
|
||||
<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_lembas_line">La transcription de votre instance. Ce téléphone n’envoie l’enregistrement qu’à votre instance ; l’instance le transcrit avec le modèle vocal qui y est configuré.</string>
|
||||
<string name="voice_input_phone">Téléphone (Google ou celui du système)</string>
|
||||
<string name="voice_input_phone_line">La reconnaissance vocale du téléphone. Les mots apparaissent pendant que vous parlez ; l’enregistrement va là où cette reconnaissance l’envoie.</string>
|
||||
<string name="voice_input_phone_none">Ce téléphone n’a pas de reconnaissance vocale propre.</string>
|
||||
<string name="voice_input_hint">Utilisée par l’assistant et par le micro d’une conversation. Avec LLeMbas, l’assistant affiche les mots avec un léger décalage et une pause les envoie, et une conversation les écrit quand vous vous arrêtez ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez.</string>
|
||||
<string name="share_sending">Envoi à LLeMbas…</string>
|
||||
<string name="share_default_prompt">Jetez un œil à ceci.</string>
|
||||
<string name="share_default_prompt">Jette un œil à ceci.</string>
|
||||
<string name="share_ask_hint">Que doit en faire LLeMbas ? (facultatif)</string>
|
||||
<string name="widget_hint">Posez une question</string>
|
||||
<string name="directory_places">Emplacements sur cet appareil</string>
|
||||
<string name="directory_last_used">Dernier utilisé ici : %1$s. Une nouvelle conversation dans ce dossier commence avec lui, sauf si vous en choisissez un autre.</string>
|
||||
<string name="directory_refused">L\'appareil n\'ouvrira pas de session ici.</string>
|
||||
<string name="directory_up">Remonter d\'un niveau</string>
|
||||
<string name="directory_all_places">Tous les emplacements</string>
|
||||
<string name="directory_not_trusted">Non approuvé sur l\'appareil</string>
|
||||
<string name="directory_empty">Aucun dossier ici.</string>
|
||||
<string name="directory_no_places">Cet appareil ne propose aucun dossier : ses racines distantes sont vides ou absentes.</string>
|
||||
<string name="directory_browse">Parcourir</string>
|
||||
<string name="directory_path">Un chemin complet</string>
|
||||
<string name="directory_choose">Choisir</string>
|
||||
<string name="directory_no_listing">Les dossiers de cet appareil ne peuvent pas être listés pour le moment. Saisissez le chemin ci-dessous.</string>
|
||||
<string name="model">Modèle</string>
|
||||
<string name="schedule_type">Type</string>
|
||||
<string name="schedule_chat">Conversation</string>
|
||||
<string name="schedule_chat_line">S\'exécute sur ce serveur, comme une conversation : avec les outils du serveur (recherche, vos fichiers ici, mémoire) et sur un modèle de planification.</string>
|
||||
<string name="schedule_agentic">Agentique</string>
|
||||
<string name="schedule_agentic_line">S\'exécute sur l\'un de vos ordinateurs, dans un dossier de celui-ci, en tant qu\'agent : avec les outils de l\'agent sur cet ordinateur — ses fichiers et son shell — dans les limites propres à l\'ordinateur. Elle appartient à cet ordinateur et à ce dossier.</string>
|
||||
<string name="schedule_agentic_unavailable">Aucun de vos ordinateurs n\'accepte de travail planifié pour l\'instant. Reliez-en un et activez « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">n’accepte pas le travail planifié</string>
|
||||
<string name="schedule_computer_hint">L\'ordinateur doit l\'autoriser : « Accept scheduled work » dans son LLeMbas CLI (lembas service scheduled on). S\'il n\'est pas relié au moment d\'une exécution, l\'exécution l\'attend ; s\'il n\'est pas revenu avant que son heure soit passée, l\'exécution est enregistrée comme manquée et vous en êtes informé.</string>
|
||||
<string name="schedule_computer_gone">un ordinateur qui n’est plus connecté</string>
|
||||
<string name="schedule_folder">Dossier sur l’ordinateur</string>
|
||||
<string name="schedule_agent_mode">Mode</string>
|
||||
<string name="schedule_agent_mode_hint">Edit sauf choix contraire ; Auto exécute les commandes sans demander. L’ordinateur peut l’abaisser.</string>
|
||||
<string name="schedule_approval_wait">Une approbation attend (minutes)</string>
|
||||
<string name="schedule_approval_wait_hint">Une commande que l’exécution doit faire approuver arrive sur votre téléphone sous forme de carte. Sans réponse d’ici là, elle compte comme refusée.</string>
|
||||
<string name="schedule_watch_command_hint">Facultatif, sur l’ordinateur. Exécutée dans le dossier avant chaque exécution ; quand sa sortie est la même que la dernière fois, l’exécution s’arrête là. Une commande pour laquelle le mode demanderait est refusée.</string>
|
||||
<string name="schedule_watch_timeout">La commande peut durer (secondes)</string>
|
||||
<string name="schedule_watch_timeout_hint">Arrêtée au-delà ; l’exécution échoue alors.</string>
|
||||
<string name="schedule_chat_drops_watch">Cette tâche surveille une commande sur son ordinateur. En tâche de type Conversation, elle ne le fait plus : elle s’exécute à chaque fois.</string>
|
||||
<string name="schedule_folder_model">Le modèle habituel du dossier</string>
|
||||
<string name="schedule_folder_model_hint">Le modèle habituel du dossier est celui que vous avez utilisé en dernier dans ce dossier sur cet ordinateur — l\'ordinateur s\'en souvient et chaque exécution le lui demande — ou votre modèle par défaut s\'il n\'y en a pas. Un modèle choisi ici est celui de l\'exécution, quel que soit celui du dossier. Une exécution ne change jamais le modèle du dossier.</string>
|
||||
<string name="schedule_first_free_model">Le premier libre de vos modèles de planification</string>
|
||||
<string name="run_model_directory">le modèle habituel du dossier</string>
|
||||
<string name="run_model_default">votre modèle par défaut</string>
|
||||
<string name="run_model_session">le modèle propre à la conversation</string>
|
||||
<string name="widget_speak">Parler</string>
|
||||
<string name="widget_description">Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.</string>
|
||||
<string name="shortcut_last">Dernière discussion</string>
|
||||
<string name="widget_description">Demandez à la voix ou par écrit, ou reprenez la dernière conversation de l’assistant. N’affiche rien de votre compte.</string>
|
||||
<string name="shortcut_last">Dernière conversation</string>
|
||||
</resources>
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas Androidra</string>
|
||||
<string name="share_label">Kérdés az LLeMbas-tól</string>
|
||||
<string name="tile_ask">Kérdés az LLeMbas-tól</string>
|
||||
<string name="signin_intro">Jelentkezzen be egy LLeMbas példányba. Ezt a telefont a böngészőben hagyja jóvá, ahogyan a CLI-t is tenné.</string>
|
||||
<string name="signin_intro">Jelentkezzen be egy LLeMbas példányba. Ezt a telefont a böngészőben hagyja jóvá.</string>
|
||||
<string name="signin_address">A példány címe</string>
|
||||
<string name="signin_continue">Folytatás</string>
|
||||
<string name="signin_code_intro">Nyissa meg a példányt a böngészőben, jelentkezzen be, és hagyja jóvá ezt a kódot:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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">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="signin_too_new">Ez a példány újabb annál, mint amivel ez az alkalmazás működni tud. Frissítse az alkalmazást.</string>
|
||||
<string name="signin_not_lembas">Ezen a címen nincs LLeMbas példány.</string>
|
||||
<string name="signin_failed">A bejelentkezést nem sikerült befejezni (%1$s). Próbálja újra.</string>
|
||||
<string name="signin_app_too_old">Ehhez a példányhoz az Androidos LLeMbas %1$s vagy újabb verziója kell, ez pedig a %2$s. Frissítse az alkalmazást.</string>
|
||||
<string name="signin_other_origin">Ez a példány más címet ad meg a bejelentkezéshez (%1$s), mint amit beírt. A proxyjának tovább kell adnia azt a címet, amelyen elérik.</string>
|
||||
<string name="address_needs_https">Ehhez az alkalmazáshoz https:// cím kell: a sima http nem támogatott.</string>
|
||||
<string name="address_unreadable">Ezt a címet az alkalmazás nem tudja használni. Írja be a példány címét, például llm.example.org.</string>
|
||||
<string name="server_answered">A kiszolgáló válasza: %1$s.</string>
|
||||
<string name="timed_out">A példány nem válaszolt időben.</string>
|
||||
<string name="not_trusted">Ez a telefon nem bízik a példány tanúsítványában: telepítse a hitelesítésszolgáltatója tanúsítványát az Android felhasználói tanúsítványai közé (Beállítások, Biztonság, Titkosítás és hitelesítési adatok, Tanúsítvány telepítése).</string>
|
||||
<string name="signed_out">%1$s kijelentkeztette ezt a telefont. A folytatáshoz jelentkezzen be újra: a csevegései és az itteni beállításai megmaradnak.</string>
|
||||
<string name="signed_out_again">Bejelentkezés újra</string>
|
||||
<string name="signed_out_use">%1$s használata</string>
|
||||
<string name="signed_out_remove">Példány eltávolítása</string>
|
||||
<string name="new_chat">Új csevegés</string>
|
||||
<string name="empty_chats">Még nincs csevegés. Nem mindenki van elveszve, aki bolyong — kezdjen el egyet.</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="agent_device">Számítógép</string>
|
||||
<string name="agent_no_device">Jelenleg nincs összekapcsolt számítógép. Indítsa el a LLeMbas CLI szolgáltatását (lembas service) egy ebbe a példányba bejelentkezett számítógépen, majd térjen vissza.</string>
|
||||
<string name="agent_directory">Mappa a számítógépen</string>
|
||||
<string name="agent_directory_hint">Üres: a számítógép 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>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Folytatás</string>
|
||||
<string name="older">Korábbi üzenetek</string>
|
||||
<string name="queued">Küldésre vár</string>
|
||||
<string name="fate_unknown">Nem tudni, hogy ez eljutott-e a számítógéphez. Küldje el újra, vagy vesse el.</string>
|
||||
<string name="fate_carried">A számítógépnél van ez az üzenet, és a következő körében veszi figyelembe.</string>
|
||||
<string name="send_now">Küldés most</string>
|
||||
<string name="discard_message_confirm">Elveti ezt az üzenetet?</string>
|
||||
<string name="reply_unrecorded">Az erre adott válasz nem lett rögzítve.</string>
|
||||
<string name="thinking">Gondolkodás</string>
|
||||
<string name="thought">Gondolkodott</string>
|
||||
<string name="output_cut">A kimenet itt lerövidítve jelenik meg. A teljes szöveg a weblapon található.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Átírta: %1$s — a csevegés saját beszédmodellje nem válaszolt.</string>
|
||||
<string name="read_by_fallback">Felolvasta: %1$s — a csevegés saját beszédmodellje nem válaszolt.</string>
|
||||
<string name="remove">Eltávolítás</string>
|
||||
<string name="more">Továbbiak</string>
|
||||
<string name="back">Vissza</string>
|
||||
@@ -245,11 +265,11 @@
|
||||
<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="page_note">Ebben a válaszban van egy oldal: %1$s</string>
|
||||
<string name="page_where">A megtekintéséhez nyisd meg a weben vagy a LLeMbas Desktopban.</string>
|
||||
<string name="page_where">A megtekintéséhez nyissa meg a weben vagy a LLeMbas Desktopban.</string>
|
||||
<string name="page_untitled">Oldal</string>
|
||||
<string name="reports">Jelentések</string>
|
||||
<string name="report">Jelentés</string>
|
||||
<string name="reports_none">Még nincsenek jelentések. Egy ütemezett feladat akkor ír egyet, ha van mit mondania neked.</string>
|
||||
<string name="reports_none">Még nincsenek jelentések. Egy ütemezett feladat akkor ír egyet, ha van mit mondania Önnek.</string>
|
||||
<string name="reports_unsupported">Ezen a példányon olyan LLeMbas fut, amelyben még nincsenek Jelentések.</string>
|
||||
<string name="report_untitled">Cím nélküli jelentés</string>
|
||||
<string name="report_delete_title">Törlöd ezt a jelentést?</string>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Ez a példány 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="files_upload">Feltöltés</string>
|
||||
<string name="files_new_file">Új fájl</string>
|
||||
<string name="files_new_file_ask">Mi legyen a fájl neve? Kiterjesztéssel együtt, például notes.md.</string>
|
||||
<string name="files_new_folder_ask">Mi legyen a mappa neve?</string>
|
||||
<string name="files_bad_name">A név nem lehet üres, és nem tartalmazhat perjelet.</string>
|
||||
<string name="files_taken">Már van itt valami %1$s néven.</string>
|
||||
<string name="rename">Átnevezés</string>
|
||||
<string name="files_new_name">Új név</string>
|
||||
<string name="files_move">Áthelyezés</string>
|
||||
<string name="files_copy_to">Másolás ide…</string>
|
||||
<string name="files_move_here">Áthelyezés ide</string>
|
||||
<string name="files_copy_here">Másolás ide</string>
|
||||
<string name="files_move_which">Melyik mappába kerüljön át?</string>
|
||||
<string name="files_copy_which">Melyik mappába másolja?</string>
|
||||
<string name="files_choose_folder">Mappa választása</string>
|
||||
<string name="files_save_here">Mentés ide</string>
|
||||
<string name="files_no_folders">Itt nincsenek könyvtárak.</string>
|
||||
<string name="files_to_trash">Áthelyezés a lomtárba</string>
|
||||
<string name="files_trash_one">Áthelyezi a lomtárba: „%1$s”? Onnan visszaállítható.</string>
|
||||
<string name="files_trash_many">A lomtárba helyezi a kijelölteket (%1$s)? Onnan visszaállíthatók.</string>
|
||||
<string name="files_trashed">A lomtárba került.</string>
|
||||
<string name="files_selected">Kijelölve: %1$s</string>
|
||||
<string name="files_select_all">Összes kijelölése</string>
|
||||
<string name="download">Letöltés</string>
|
||||
<string name="files_download_zip">Letöltés zipként</string>
|
||||
<string name="files_downloading">Letöltés…</string>
|
||||
<string name="files_downloaded">Letöltve.</string>
|
||||
<string name="files_uploading">Feltöltés: %1$s / %2$s…</string>
|
||||
<string name="files_uploaded">Feltöltve.</string>
|
||||
<string name="files_open_with">Megnyitás ezzel…</string>
|
||||
<string name="files_no_app">Ezen a telefonon egyetlen alkalmazás sem nyitja meg az ilyen fájlt.</string>
|
||||
<string name="trash">Lomtár</string>
|
||||
<string name="trash_is_empty">A lomtár üres.</string>
|
||||
<string name="trash_empty">Lomtár ürítése</string>
|
||||
<string name="trash_empty_confirm">Véglegesen eltávolítja a lomtár teljes tartalmát? Ez nem vonható vissza.</string>
|
||||
<string name="trash_remove">Végleges eltávolítás</string>
|
||||
<string name="trash_remove_confirm">Véglegesen eltávolítja ezt: „%1$s”? Ez nem vonható vissza.</string>
|
||||
<string name="restore">Visszaállítás</string>
|
||||
<string name="versions">Változatok</string>
|
||||
<string name="version_restore">Változat visszaállítása</string>
|
||||
<string name="version_restore_confirm">Legyen ez az aktuális változat? A mostani a listában marad.</string>
|
||||
<string name="version_current">Jelenlegi</string>
|
||||
<string name="files_type">Típus</string>
|
||||
<string name="files_size">Méret</string>
|
||||
<string name="files_no_viewer">Ehhez a fájlfajtához nincs megjelenítő.</string>
|
||||
<string name="files_not_shown">Ezt a fájlt itt nem sikerült megjeleníteni. Továbbra is letölthető.</string>
|
||||
<string name="files_svg_source">Ez a kép forrása. A kép megtekintéséhez nyissa meg egy másik alkalmazással.</string>
|
||||
<string name="archive_note">Az ilyen fajta archívum tartalma itt nem listázható.</string>
|
||||
<string name="archive_entries">%1$s bejegyzés. Itt semmi sincs kicsomagolva.</string>
|
||||
<string name="archive_cut">Csak az első %1$s bejegyzés szerepel a listában.</string>
|
||||
<string name="archive_unreadable">Ezt az archívumot nem sikerült beolvasni.</string>
|
||||
<string name="files_waiting">Várakozás, amíg az alkalmazás meg van nyitva és a telefon fel van oldva.</string>
|
||||
<string name="share_refused">A megosztottak közül valami innen nem küldhető el, ezért kimaradt.</string>
|
||||
<string name="media_in_trash">Ez a fájl a lomtárban van.</string>
|
||||
<string name="table_cut">Csak az első sorok és oszlopok kerültek táblázatba. A szöveg mindent tartalmaz.</string>
|
||||
<string name="table_as_text">Megjelenítés szövegként</string>
|
||||
<string name="table_as_table">Megjelenítés táblázatként</string>
|
||||
<string name="media_open_in_files">Megnyitás a Fájlokban</string>
|
||||
<string name="media_image">Kép</string>
|
||||
<string name="media_video">Videó</string>
|
||||
<string name="media_music">Zene</string>
|
||||
<string name="media_model">3D-modell</string>
|
||||
<string name="media_audio">Hang</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archívum</string>
|
||||
<string name="media_text">Szövegfájl</string>
|
||||
<string name="media_binary">Fájl</string>
|
||||
<string name="diff_deleted">Törölve</string>
|
||||
<string name="diff_counts">Hozzáadott sorok: %1$s, eltávolított: %2$s</string>
|
||||
<string name="diff_show_all">Mind a(z) %1$s sor megjelenítése</string>
|
||||
<string name="diff_show_less">Kevesebb megjelenítése</string>
|
||||
<string name="diff_more">További %1$s sor itt nem látható.</string>
|
||||
<string name="diff_endings">A sorvégek megváltoznak: %1$s helyett %2$s.</string>
|
||||
<string name="diff_cut">Ez a változás túl hosszú ahhoz, hogy itt össze lehessen hasonlítani. Csak az eleje látható.</string>
|
||||
<string name="media_gone">Ez a fájl már nem létezik.</string>
|
||||
<string name="job_queued">Sorban áll</string>
|
||||
<string name="job_running">Fut</string>
|
||||
<string name="job_done">Kész</string>
|
||||
<string name="job_failed">Sikertelen</string>
|
||||
<string name="job_cancelled">Megszakítva</string>
|
||||
<string name="job_expired">Lejárt</string>
|
||||
<string name="mcp_title">MCP-szerverek</string>
|
||||
<string name="mcp_intro">Azok a szerverek, amelyek eszközei felkínálhatók a csevegéseiben. Némelyik az ottani saját fiókjával használható: az eszközeik addig érhetők el, amíg be van jelentkezve.</string>
|
||||
<string name="mcp_none">Ezen a példányon nincs Önnek felkínált MCP-szerver.</string>
|
||||
<string name="mcp_ready">Kész</string>
|
||||
<string name="mcp_signed_in">Bejelentkezve</string>
|
||||
<string name="mcp_signed_out">Nincs bejelentkezve</string>
|
||||
<string name="mcp_needs_signin">Új bejelentkezés szükséges</string>
|
||||
<string name="mcp_tools">Eszközök: %1$s</string>
|
||||
<string name="mcp_account">Bejelentkezve mint %1$s</string>
|
||||
<string name="mcp_until">Bejelentkezve eddig: %1$s</string>
|
||||
<string name="mcp_shared_note">Ennek a szervernek egy közös bejelentkezése van, amelyet egy rendszergazda végez el.</string>
|
||||
<string name="mcp_browser_note">A bejelentkezés a böngészőben történik, magán a példányon. Ha a böngésző nincs bejelentkezve a példányba, előbb azt kéri. Utána térjen vissza ide.</string>
|
||||
<string name="mcp_sign_in">Bejelentkezés</string>
|
||||
<string name="notebook_empty">Ennek a jegyzetfüzetnek nincsenek cellái.</string>
|
||||
<string name="notebook_more">További %1$s cella nem jelenik meg.</string>
|
||||
<string name="notebook_cell_cut">Ez a cella hosszabb, mint ami itt látszik.</string>
|
||||
<string name="viewer_page">%1$s. / %2$s oldal</string>
|
||||
<string name="play">Lejátszás</string>
|
||||
<string name="pause">Szüneteltetés</string>
|
||||
<string name="files_conflict">A fájl megváltozott, mióta megnyitotta. Töltse be újra, vagy mentse mégis.</string>
|
||||
<string name="files_save_anyway">Mentés mégis</string>
|
||||
<string name="reload">Újratöltés</string>
|
||||
<string name="discard">Elvetés</string>
|
||||
<string name="files_unsaved">Elveti a fájl módosításait?</string>
|
||||
<string name="share_to_files">Mentés a Fájlokba</string>
|
||||
<string name="settings">Beállítások</string>
|
||||
<string name="settings_instances">Példányok</string>
|
||||
<string name="sign_out">Kijelentkezés</string>
|
||||
<string name="add_instance">Példány hozzáadása</string>
|
||||
<string name="instance_default">Alapértelmezett</string>
|
||||
<string name="instance_set_default">Beállítás alapértelmezettként</string>
|
||||
<string name="instance_switch">Példány váltása</string>
|
||||
<string name="settings_theme">Téma</string>
|
||||
<string name="theme_system">A rendszer szerint</string>
|
||||
<string name="theme_moria">Moria (sötét)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Asszisztens</string>
|
||||
<string name="assistant_explained">Tegye az LLeMbas-t a telefon digitális asszisztensévé: válassza ki az Alapértelmezett alkalmazások › Digitális asszisztens alkalmazás alatt. A bekapcsológomb lenyomva tartása, az asszisztens-gesztus vagy a lezárási képernyő parancsikonja ezután a képernyőn lévő tartalom felett nyitja meg.</string>
|
||||
<string name="assistant_open_settings">Asszisztens beállításainak megnyitása</string>
|
||||
<string name="assistant_model">Az asszisztens modellje</string>
|
||||
<string name="assistant_model_default">A példány alapértelmezése</string>
|
||||
<string name="assistant_model_default_line">Az a modell, amellyel az új csevegései indulnak. Ha egy kimondott kérdéshez túl lassú, válasszon lent gyorsabbat.</string>
|
||||
<string name="assistant_samsung">Samsung telefonokon: Beállítások › Speciális funkciók › Oldalgomb › Nyomva tartás › Digitális asszisztens.</string>
|
||||
<string name="assistant_temporary">Az asszisztenses csevegések ideiglenesek</string>
|
||||
<string name="assistant_read_aloud">Olvassa fel a választ, ha hangos kérdés érkezett</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Naponta legfeljebb egyszer, induláskor az alkalmazás megkérdezi a példányát, melyik kiadás illik hozzá — vagy a GitHubon lévő kiadások listáját olvassa be, ha a példány ezt nem tudja megmondani —, és értesítésben jelzi, ha van újabb. Egyik kéréssel sem megy Önről semmi. 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>
|
||||
@@ -421,44 +553,51 @@
|
||||
<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_unlock_to_send">Feloldás és küldés</string>
|
||||
<string name="assist_question_heard">Kérdés rögzítve</string>
|
||||
<string name="assist_recording_waits_line">A telefon zárolva van. A kérdése felvételként ezen a telefonon vár; semmi sem ment el. Feloldás után a példányához kerül, amely leírja és megválaszolja.</string>
|
||||
<string name="assist_locked_line">A telefon zárolva van. Amíg fel nem oldja, semmi sem megy el, és válasz sem jelenik meg.</string>
|
||||
<string name="assist_conversation">Beszélgetés</string>
|
||||
<string name="assist_conversation_line">Minden válasz után újra figyelek. A befejezéshez mondd: „állj”.</string>
|
||||
<string name="assist_conversation_line">Minden válasz után újra figyelek. A befejezéshez mondja: „állj”.</string>
|
||||
<string name="assist_conversation_end">Befejezés</string>
|
||||
<string name="assist_stop_words">állj|stop|ennyi|ennyi volt|elég|vége|viszlát|köszönöm ennyi|mégse</string>
|
||||
<string name="assistant_conversation">Szóbeli beszélgetés folytatása</string>
|
||||
<string name="assistant_conversation_line">Egy szóbeli válasz felolvasása után az asszisztens újra figyel — amíg nem mondod, hogy „állj”, nem koppintasz a Befejezésre, vagy néhány másodpercig nem szólsz. Headsettel is működik.</string>
|
||||
<string name="assist_wake_word_hint">Nincs ébresztőszó, hacsak nem kérsz: Beállítások › Asszisztens › Ébresztőszó bekapcsolja a LLeMbas sajátját, ezen a telefonon.</string>
|
||||
<string name="assistant_conversation_line">Egy szóbeli válasz felolvasása után az asszisztens újra figyel — amíg nem mondja, hogy „állj”, nem koppint a Befejezésre, vagy néhány másodpercig nem szól. Headsettel is működik.</string>
|
||||
<string name="experimental">Kísérleti</string>
|
||||
<string name="wake_experimental_line">Új, és eddig csak néhány telefonon próbáltuk ki. Előfordulhat, hogy nem hallja meg a kifejezést, tévedésből elindul, vagy meghallja Önt, és mégsem nyitja meg az asszisztenst.</string>
|
||||
<string name="assistant_voice_experimental_line">Kísérleti: az önálló hallgatás az asszisztens megnyitásakor, annak észlelése, hogy befejezte a beszédet, és a szóbeli beszélgetés új, és még nem minden telefonon működik jól. Kérdést beírni és a mikrofon gombot használni mindig lehet.</string>
|
||||
<string name="assist_wake_word_hint">Nincs ébresztőszó, hacsak nem kér: a Beállítások › Ébresztőszó bekapcsolja a LLeMbas sajátját, ezen a telefonon.</string>
|
||||
<string name="channel_wake">Ébresztőszó</string>
|
||||
<string name="wake_word">Ébresztőszó</string>
|
||||
<string name="wake_word_listen">Ébresztőszó figyelése</string>
|
||||
<string name="wake_word_line">Alapból ki van kapcsolva. Mondd ki a kifejezést, és az asszisztens figyelve megnyílik a képernyőn lévő alkalmazás fölött.</string>
|
||||
<string name="wake_word_line">Alapból ki van kapcsolva. Mondja ki a kifejezést, és az asszisztens figyelve megnyílik a képernyőn lévő alkalmazás fölött.</string>
|
||||
<string name="wake_word_unavailable">Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van.</string>
|
||||
<string name="wake_phrase_line">Ezt mondod, utána rövid szünet: akkor számít, amikor elhallgatsz. Angolul, bármilyen nyelvű is az alkalmazás: a motor csak az angol beszédet ismeri.</string>
|
||||
<string name="wake_phrase_line">Ezt mondja, utána rövid szünet: akkor számít, amikor elhallgat. Angolul, bármilyen nyelvű is az alkalmazás: a motor csak az angol beszédet ismeri.</string>
|
||||
<string name="wake_greeting">Megszólítás</string>
|
||||
<string name="wake_name">Név</string>
|
||||
<string name="wake_name_google_line">A közelben lévő Google-telefon vagy -hangszóró is válaszolni fog.</string>
|
||||
<string name="wake_sensitivity">Érzékenység</string>
|
||||
<string name="wake_sensitivity_low">Alacsony</string>
|
||||
<string name="wake_sensitivity_low_line">A legritkábban indul el tévedésből. Lehet, hogy tisztábban vagy kétszer kell kimondanod a kifejezést.</string>
|
||||
<string name="wake_sensitivity_low_line">A legritkábban indul el tévedésből. Lehet, hogy tisztábban vagy kétszer kell kimondania a kifejezést.</string>
|
||||
<string name="wake_sensitivity_normal">Normál</string>
|
||||
<string name="wake_sensitivity_normal_line">A motor saját beállítása.</string>
|
||||
<string name="wake_sensitivity_high">Magas</string>
|
||||
<string name="wake_sensitivity_high_line">A legkönnyebben hall meg, távolabbról is. Gyakrabban indul el tévedésből.</string>
|
||||
<string name="wake_sensitivity_high_line">A legkönnyebben hallja meg Önt, távolabbról is. Gyakrabban indul el tévedésből.</string>
|
||||
<string name="wake_test">Ébresztőszó kipróbálása</string>
|
||||
<string name="wake_test_line">Tíz másodpercig mutatja, hogy hallja-e a kifejezésedet, az asszisztens megnyitása nélkül.</string>
|
||||
<string name="wake_test_say">Most mondd: „%1$s”, aztán tarts szünetet…</string>
|
||||
<string name="wake_test_line">Tíz másodpercig mutatja, hogy hallja-e a kifejezését, az asszisztens megnyitása nélkül.</string>
|
||||
<string name="wake_test_say">Most mondja: „%1$s”, aztán tartson szünetet…</string>
|
||||
<string name="wake_test_heard">Hallottam</string>
|
||||
<string name="wake_test_missed">Tíz másodperc alatt nem hallottam. Próbáld közelebb a telefonhoz, csendesebb pillanatban vagy nagyobb érzékenységgel.</string>
|
||||
<string name="wake_test_off">Előbb kapcsold be az ébresztőszót.</string>
|
||||
<string name="wake_test_missed">Tíz másodperc alatt nem hallottam. Próbálja közelebb a telefonhoz, csendesebb pillanatban vagy nagyobb érzékenységgel.</string>
|
||||
<string name="wake_test_off">Előbb kapcsolja be az ébresztőszót.</string>
|
||||
<string name="wake_screen_only">Csak bekapcsolt képernyőnél</string>
|
||||
<string name="wake_screen_only_line">Kikapcsolva kikapcsolt képernyőnél is figyel, ami több akkumulátort fogyaszt.</string>
|
||||
<string name="wake_battery">Futhasson a háttérben</string>
|
||||
<string name="wake_battery_line">Egyes telefonok (Samsung, Xiaomi, Huawei, OnePlus és mások) az akkumulátor kímélése miatt leállítják a háttéralkalmazásokat, és velük az ébresztőszót is. Itt vedd ki a LLeMbast az akkumulátor-optimalizálásból; a dontkillmyapp.com elmagyarázza a telefonod beállításait.</string>
|
||||
<string name="wake_battery_line">Egyes telefonok (Samsung, Xiaomi, Huawei, OnePlus és mások) az akkumulátor kímélése miatt leállítják a háttéralkalmazásokat, és velük az ébresztőszót is. Itt vegye ki a LLeMbast az akkumulátor-optimalizálásból; a dontkillmyapp.com elmagyarázza a telefonja beállításait.</string>
|
||||
<string name="wake_word_privacy">A szó előtt semmi nem hagyja el a telefont. A mikrofon hangja csak a telefonon futó ébresztőszó-motorhoz jut, és nem tárolódik; amíg figyel, az értesítés végig látható. A kifejezések angolok; a motor a sherpa-onnx (nyílt forráskódú).</string>
|
||||
<string name="wake_word_cost">Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatod meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppints az értesítésére az újraindításhoz.</string>
|
||||
<string name="wake_word_cost">Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatja meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppintson az értesítésére az újraindításhoz.</string>
|
||||
<string name="wake_listening_for">Figyeli: „%1$s”</string>
|
||||
<string name="wake_off">Az ébresztőszó nem figyel</string>
|
||||
<string name="wake_tap_to_start">Koppints az újraindításához. Ha az Android rákérdez, engedélyezd a mikrofont.</string>
|
||||
<string name="wake_tap_to_start">Koppintson az újraindításához. Ha az Android rákérdez, engedélyezze a mikrofont.</string>
|
||||
<string name="wake_starting">Az ébresztőszó indul…</string>
|
||||
<string name="wake_paused_silent">Az ébresztőszó semmit nem hall: másik alkalmazás használja a mikrofont, vagy a telefon mikrofonja ki van kapcsolva</string>
|
||||
<string name="wake_failed_no_engine">Az ébresztőszó nem működik: ebben a változatban nincs motor</string>
|
||||
@@ -466,17 +605,17 @@
|
||||
<string name="wake_failed_engine">Az ébresztőszó nem működik: a motor nem indult el</string>
|
||||
<string name="wake_failed_microphone">Az ébresztőszó nem működik: a mikrofon nem indult el</string>
|
||||
<string name="wake_failed_line">Nem figyel. Magától újrapróbálja.</string>
|
||||
<string name="wake_notification_line">Amíg ki nem mondod, semmi nem hagyja el a telefont.</string>
|
||||
<string name="wake_notification_line">Amíg ki nem mondja, semmi nem hagyja el a telefont.</string>
|
||||
<string name="wake_paused_screen">Ébresztőszó szünetel: a képernyő ki van kapcsolva</string>
|
||||
<string name="wake_paused_battery">Ébresztőszó szünetel: be van kapcsolva az energiatakarékos mód</string>
|
||||
<string name="wake_paused_assistant">Az ébresztőszó szünetel, amíg az asszisztens nyitva van</string>
|
||||
<string name="wake_paused_microphone">Ébresztőszó szünetel: a LLeMbas nem használhatja a mikrofont</string>
|
||||
<string name="wake_stop">Figyelés leállítása</string>
|
||||
<string name="wake_heard">Hallottalak. Koppints a kérdezéshez.</string>
|
||||
<string name="wake_heard">Hallottam. Koppintson a kérdezéshez.</string>
|
||||
<string name="channel_wake_heard">Ébresztőszó elhangzott</string>
|
||||
<string name="wake_heard_line">A LLeMbas csak a telefon digitális asszisztens alkalmazásaként tud magától megnyílni más alkalmazások fölött.</string>
|
||||
<string name="wake_not_assistant">A LLeMbas nem a digitális asszisztens alkalmazás</string>
|
||||
<string name="wake_not_assistant_line">Ezért az ébresztőszó nem tudja megnyitni az asszisztenst más alkalmazások fölött: értesítést kapsz, amelyre koppinthatsz. Ha bárhol hanggal szeretnéd megnyitni, koppints ide, és válaszd a LLeMbast digitális asszisztens alkalmazásnak.</string>
|
||||
<string name="wake_not_assistant_line">Ezért az ébresztőszó nem tudja megnyitni az asszisztenst más alkalmazások fölött: értesítést kap, amelyre koppinthat. Ha bárhol hanggal szeretné megnyitni, koppintson ide, és válassza a LLeMbast digitális asszisztens alkalmazásnak.</string>
|
||||
<string name="wake_last">Utolsó ébresztés</string>
|
||||
<string name="wake_last_none">Még nem hallotta a kifejezést.</string>
|
||||
<string name="wake_out_opened">Megnyitotta az asszisztenst.</string>
|
||||
@@ -498,24 +637,24 @@
|
||||
<string name="wake_waited">Várt egy pillanatot, hogy az Android csatlakoztassa.</string>
|
||||
<string name="wake_show_failed">Az Android jelezte, hogy nem tudta megjeleníteni az asszisztens paneljét.</string>
|
||||
<string name="wake_assistant_inactive">Az Android most nem használja a LLeMbast hangasszisztensként</string>
|
||||
<string name="wake_assistant_inactive_line">Válaszd újra a LLeMbast digitális asszisztens alkalmazásnak: koppints ide, válassz másik alkalmazást, majd a LLeMbast. Addig a hosszú nyomás közönséges képernyőként nyitja meg, az ébresztőszó pedig csak értesítést tud küldeni.</string>
|
||||
<string name="wake_assistant_inactive_line">Válassza újra a LLeMbast digitális asszisztens alkalmazásnak: koppintson ide, válasszon másik alkalmazást, majd a LLeMbast. Addig a hosszú nyomás közönséges képernyőként nyitja meg, az ébresztőszó pedig csak értesítést tud küldeni.</string>
|
||||
<string name="wake_assistant_unbound">A LLeMbas az asszisztens, de az Android most nem csatlakoztatta</string>
|
||||
<string name="wake_assistant_unbound_line">Amíg nem csatlakoztatja, az ébresztőszó nem tudja magától megnyitni a panelt. Koppints a rendszer asszisztensbeállításához: ha másik alkalmazást, majd újra a LLeMbast választod, csatlakozik.</string>
|
||||
<string name="wake_heard_could_not">Nem tudott magától megnyílni — koppints a kérdezéshez</string>
|
||||
<string name="wake_assistant_unbound_line">Amíg nem csatlakoztatja, az ébresztőszó nem tudja magától megnyitni a panelt. Koppintson a rendszer asszisztensbeállításához: ha másik alkalmazást, majd újra a LLeMbast választja, csatlakozik.</string>
|
||||
<string name="wake_heard_could_not">Nem tudott magától megnyílni — koppintson a kérdezéshez</string>
|
||||
<string name="wake_resume">Ébresztőszó figyelése újra</string>
|
||||
<string name="wake_resume_line">A telefon újraindult. Koppints a figyelés folytatásához.</string>
|
||||
<string name="wake_resume_line">A telefon újraindult. Koppintson a figyelés folytatásához.</string>
|
||||
<string name="assist_notifications">Értesítéseim összefoglalása</string>
|
||||
<string name="assist_notifications_prompt">Foglald össze az értesítéseimet: mi igényli a figyelmemet?</string>
|
||||
<string name="assist_notifications_phrases">értesítéseim|értesítéseimet|az értesítéseimről</string>
|
||||
<string name="notification_summaries">Értesítések összefoglalása</string>
|
||||
<string name="notification_summaries_switch">Az asszisztens kérésemre elolvashatja az értesítéseimet</string>
|
||||
<string name="notification_summaries_line">Kérd, hogy „foglald össze az értesítéseimet”, vagy koppints a gombra az asszisztensben.</string>
|
||||
<string name="notification_summaries_line">Kérje, hogy „foglald össze az értesítéseimet”, vagy koppintson a gombra az asszisztensben.</string>
|
||||
<string name="notification_summaries_unavailable">Ebben a változatban nincs. Az értesítések olvasásához a LLeMbas „notifications” változata kell, mert a Google Play Protect letiltja az olyan, Play Áruházon kívüli alkalmazás telepítését, amely olvasni tudja őket. Ugyanaz az alkalmazás ugyanazzal az aláírással: a kiadás oldalán a -notifications.apk végű fájl erre telepíthető rá.</string>
|
||||
<string name="update_notifications_manual">Ez a „notifications” változat: a frissítést a kiadás oldaláról telepítsd, a -notifications.apk végű fájlt.</string>
|
||||
<string name="notification_access">Hozzáférés az értesítésekhez</string>
|
||||
<string name="notification_access_on">Megadva. Az Android kapcsolója a rendszerbeállításokban van.</string>
|
||||
<string name="notification_access_off">Még nincs megadva. Koppints az Android LLeMbas-kapcsolójának megnyitásához.</string>
|
||||
<string name="notification_summaries_privacy">Alapból ki van kapcsolva. Ha kéred, a telefonon éppen látható értesítések szövege (alkalmazás, cím, szöveg) ezzel az egy kérdéssel együtt a példányodhoz és a modelljéhez kerül. Előtte semmit nem olvas, az alkalmazás semmit nem tart meg, és zárolt telefonnál semmit nem olvas. Az Android értesítés-hozzáférése minden értesítést láthatóvá tesz egy alkalmazásnak, ezért rajtad múlik, megadod-e, és visszavonod-e.</string>
|
||||
<string name="notification_access_off">Még nincs megadva. Koppintson az Android LLeMbas-kapcsolójának megnyitásához.</string>
|
||||
<string name="notification_summaries_privacy">Alapból ki van kapcsolva. Ha kéri, a telefonon éppen látható értesítések szövege (alkalmazás, cím, szöveg) ezzel az egy kérdéssel együtt a példányához és a modelljéhez kerül. Előtte semmit nem olvas, az alkalmazás semmit nem tart meg, és zárolt telefonnál semmit nem olvas. Az Android értesítés-hozzáférése minden értesítést láthatóvá tesz egy alkalmazásnak, ezért Önön múlik, megadja-e, és visszavonja-e.</string>
|
||||
<string name="nav_app">Navigációs alkalmazás</string>
|
||||
<string name="nav_app_auto">Amelyik telepítve van</string>
|
||||
<string name="nav_app_google">Google Térkép</string>
|
||||
@@ -523,39 +662,76 @@
|
||||
<string name="nav_app_ask">Mindig kérdezzen</string>
|
||||
<string name="nav_app_not_installed">Nincs telepítve</string>
|
||||
<string name="osmand_info">Útvonal lekérdezése az OsmAndtól</string>
|
||||
<string name="osmand_info_line">Így a „megálló hozzáadása” és a közeli keresés az OsmAndban beállított útvonallal is működik: a LLeMbas megkérdezi az OsmAndot, hol vagy és hová tart az útvonal. Előbb engedélyezd a LLeMbast az OsmAndban (csatlakoztatott alkalmazások, helyadattal); az OsmAnd szól, ha nincs engedélyezve.</string>
|
||||
<string name="phone_actions_line">Egy modell felajánlhatja, hogy tesz valamit ezen a telefonon — ébresztőt állít, eseményt vesz fel, üzenetet fogalmaz, útvonalat indít. Semmi sem történik, amíg a kártyáján nem koppintasz a Mehet gombra, és zárolt telefonnál soha. A Google Térkép néhány megállós útvonalat indít, de futó útvonalhoz nem ad megállót és nem állítható le; az OsmAnd igen.</string>
|
||||
<string name="action_card_title">Megtegyem ezt a telefonodon?</string>
|
||||
<string name="osmand_info_line">Így a „megálló hozzáadása” és a közeli keresés az OsmAndban beállított útvonallal is működik: a LLeMbas megkérdezi az OsmAndot, hol tartózkodik Ön, és hová tart az útvonal. Előbb engedélyezze a LLeMbast az OsmAndban (csatlakoztatott alkalmazások, helyadattal); az OsmAnd szól, ha nincs engedélyezve.</string>
|
||||
<string name="phone_actions_line">Egy modell felajánlhatja, hogy tesz valamit ezen a telefonon — ébresztőt állít, eseményt vesz fel, üzenetet fogalmaz, útvonalat indít. Semmi sem történik, amíg a kártyáján nem koppint a Mehet gombra, és zárolt telefonnál soha. A Google Térkép néhány megállós útvonalat indít, de futó útvonalhoz nem ad megállót és nem állítható le; az OsmAnd igen.</string>
|
||||
<string name="action_card_title">Megtegyem ezt a telefonján?</string>
|
||||
<string name="action_do">Mehet</string>
|
||||
<string name="action_running">Folyamatban…</string>
|
||||
<string name="action_unlock">Előbb oldd fel a telefont, aztán koppints a Mehet gombra.</string>
|
||||
<string name="action_unlock">Előbb oldja fel a telefont, aztán koppintson a Mehet gombra.</string>
|
||||
<string name="action_failed">Nem sikerült: %1$s</string>
|
||||
<string name="nav_app_pick">Melyik térképalkalmazással?</string>
|
||||
<string name="action_google_add_stop">A Google Térkép nem tud megállót adni egy futó útvonalhoz: újraindítja az útvonalat a megállón át.</string>
|
||||
<string name="action_google_no_stop">A Google Térképet nem lehet kívülről leállítani: ott fejezd be az útvonalat.</string>
|
||||
<string name="action_line_clock">Az Óra alkalmazás beállítja.</string>
|
||||
<string name="action_line_calendar">Megnyílik a naptár a kitöltött eseménnyel; te mented el.</string>
|
||||
<string name="action_line_draft">Megnyit egy piszkozatot; te küldöd el.</string>
|
||||
<string name="action_line_dial">Megnyílik a tárcsázó a számmal; te indítod a hívást.</string>
|
||||
<string name="action_line_calendar">Megnyílik a naptár a kitöltött eseménnyel; Ön menti el.</string>
|
||||
<string name="action_line_draft">Megnyit egy piszkozatot; Ön küldi el.</string>
|
||||
<string name="action_line_dial">Megnyílik a tárcsázó a számmal; Ön indítja a hívást.</string>
|
||||
<string name="action_line_map">Az útvonalat a(z) %1$s kapja.</string>
|
||||
<string name="action_line_now">Azonnal megtörténik.</string>
|
||||
<string name="action_line_settings">Megnyitja a beállítást; te módosítod.</string>
|
||||
<string name="action_line_automation">Lefuttatja az automatizálásodat (Tasker, ha nincs más alkalmazás megadva).</string>
|
||||
<string name="action_line_settings">Megnyitja a beállítást; Ön módosítja.</string>
|
||||
<string name="action_line_automation">Lefuttatja az automatizálását (Tasker, ha nincs más alkalmazás megadva).</string>
|
||||
<string name="action_line_open">Megnyitja.</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_lembas_line">A példánya beszédfelismerése. Ez a telefon a felvételt csak a példányának küldi el; a példány az ott beállított beszédmodellel írja le.</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>
|
||||
<string name="share_default_prompt">Nézd meg ezt.</string>
|
||||
<string name="share_ask_hint">Mit kezdjen vele a LLeMbas? (nem kötelező)</string>
|
||||
<string name="widget_hint">Kérdezz bármit</string>
|
||||
<string name="widget_hint">Kérdezzen bármit</string>
|
||||
<string name="directory_places">Helyek ezen az eszközön</string>
|
||||
<string name="directory_last_used">Itt legutóbb használt: %1$s. Egy új csevegés ebben a mappában ezzel indul, hacsak nem választ másikat.</string>
|
||||
<string name="directory_refused">Az eszköz itt nem nyit munkamenetet.</string>
|
||||
<string name="directory_up">Egy szinttel feljebb</string>
|
||||
<string name="directory_all_places">Minden hely</string>
|
||||
<string name="directory_not_trusted">Nem megbízható az eszközön</string>
|
||||
<string name="directory_empty">Itt nincsenek könyvtárak.</string>
|
||||
<string name="directory_no_places">Ez az eszköz nem kínál könyvtárakat: a távoli gyökerei üresek vagy hiányoznak.</string>
|
||||
<string name="directory_browse">Tallózás</string>
|
||||
<string name="directory_path">Teljes elérési út</string>
|
||||
<string name="directory_choose">Kiválasztás</string>
|
||||
<string name="directory_no_listing">Az eszköz könyvtárai most nem listázhatók. Adja meg az elérési utat lent.</string>
|
||||
<string name="model">Modell</string>
|
||||
<string name="schedule_type">Típus</string>
|
||||
<string name="schedule_chat">Csevegés</string>
|
||||
<string name="schedule_chat_line">Ezen a szerveren fut, mint egy csevegés: a szerver eszközeivel (keresés, az itteni fájljai, memória) és egy ütemezési modellen.</string>
|
||||
<string name="schedule_agentic">Ügynöki</string>
|
||||
<string name="schedule_agentic_line">Az egyik számítógépén fut, annak egy mappájában, ügynökként: az ügynök eszközeivel azon a számítógépen — a fájljaival és a shelljével — a számítógép saját korlátain belül. Ahhoz a számítógéphez és mappához tartozik.</string>
|
||||
<string name="schedule_agentic_unavailable">Egyik számítógépe sem fogad most ütemezett munkát. Kapcsoljon össze egyet, és kapcsolja be az „Accept scheduled work” beállítást a LLeMbas CLI-jében (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nem fogad ütemezett munkát</string>
|
||||
<string name="schedule_computer_hint">A számítógépnek engedélyeznie kell: „Accept scheduled work” a LLeMbas CLI-jében (lembas service scheduled on). Ha egy futás idején nincs összekapcsolva, a futás megvárja; ha nem tér vissza, mielőtt a futás ideje letelik, a futás kihagyottként kerül feljegyzésre, és erről értesítést kap.</string>
|
||||
<string name="schedule_computer_gone">egy már nem bejelentkezett számítógép</string>
|
||||
<string name="schedule_folder">Mappa a számítógépen</string>
|
||||
<string name="schedule_agent_mode">Mód</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, hacsak mást nem választ; az Auto kérdezés nélkül futtat parancsokat. A számítógép csökkentheti.</string>
|
||||
<string name="schedule_approval_wait">Egy jóváhagyás vár (perc)</string>
|
||||
<string name="schedule_approval_wait_hint">A futás által jóváhagyást igénylő parancs kártyaként érkezik a telefonjára. Ha addig nem válaszol, elutasítottnak számít.</string>
|
||||
<string name="schedule_watch_command_hint">Nem kötelező, a számítógépen. Minden futás előtt lefut a mappában; ha a kimenete ugyanaz, mint legutóbb, a futás ott leáll. Az a parancs, amelyre a mód rákérdezne, elutasításra kerül.</string>
|
||||
<string name="schedule_watch_timeout">A parancs ennyi ideig tarthat (másodperc)</string>
|
||||
<string name="schedule_watch_timeout_hint">Ezután leáll, és a futás sikertelen.</string>
|
||||
<string name="schedule_chat_drops_watch">Ez a feladat egy parancsot figyel a számítógépén. Csevegés típusú feladatként már nem teszi: minden alkalommal lefut.</string>
|
||||
<string name="schedule_folder_model">A mappa szokásos modellje</string>
|
||||
<string name="schedule_folder_model_hint">A mappa szokásos modellje az, amelyet abban a mappában azon a számítógépen legutóbb használt — a számítógép megjegyzi, és minden futás megkérdezi tőle —, vagy az alapértelmezett modellje, ha nincs ilyen. Az itt választott modell a futásé, bármi is a mappáé. Egy futás soha nem változtatja meg a mappa modelljét.</string>
|
||||
<string name="schedule_first_free_model">Az ütemezési modelljei közül az első szabad</string>
|
||||
<string name="run_model_directory">a mappa szokásos modellje</string>
|
||||
<string name="run_model_default">az Ön alapértelmezett modellje</string>
|
||||
<string name="run_model_session">a beszélgetés saját modellje</string>
|
||||
<string name="widget_speak">Beszéd</string>
|
||||
<string name="widget_description">Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat.</string>
|
||||
<string name="widget_description">Kérdezzen hanggal vagy szöveggel, vagy folytassa az asszisztens legutóbbi csevegését. A fiókjából semmit sem mutat.</string>
|
||||
<string name="shortcut_last">Utolsó csevegés</string>
|
||||
</resources>
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas per Android</string>
|
||||
<string name="share_label">Chiedi a LLeMbas</string>
|
||||
<string name="tile_ask">Chiedi a LLeMbas</string>
|
||||
<string name="signin_intro">Accedi a un\'istanza LLeMbas. Approvi questo telefono nel browser, come faresti con la CLI.</string>
|
||||
<string name="signin_intro">Accedi a un\'istanza LLeMbas. Approvi questo telefono nel browser.</string>
|
||||
<string name="signin_address">Indirizzo dell\'istanza</string>
|
||||
<string name="signin_continue">Continua</string>
|
||||
<string name="signin_code_intro">Apri l\'istanza nel browser, accedi e approva questo codice:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Questa istanza è più recente di quanto questa app supporti. Aggiorna l\'app.</string>
|
||||
<string name="signin_not_lembas">Non c\'è nessuna istanza LLeMbas a quell\'indirizzo.</string>
|
||||
<string name="signin_failed">Non è stato possibile completare l\'accesso (%1$s). Riprova.</string>
|
||||
<string name="signin_app_too_old">Questa istanza richiede LLeMbas per Android %1$s o successivo, e questa è la %2$s. Aggiorna l\'app.</string>
|
||||
<string name="signin_other_origin">Questa istanza indica per l\'accesso un indirizzo diverso (%1$s) da quello che hai scritto. Il suo proxy deve inoltrare l\'indirizzo con cui viene raggiunta.</string>
|
||||
<string name="address_needs_https">Questa app richiede un indirizzo https://: il semplice http non è supportato.</string>
|
||||
<string name="address_unreadable">L\'app non può usare questo indirizzo. Scrivi l\'indirizzo dell\'istanza, ad esempio llm.example.org.</string>
|
||||
<string name="server_answered">Il server ha risposto %1$s.</string>
|
||||
<string name="timed_out">L\'istanza non ha risposto in tempo.</string>
|
||||
<string name="not_trusted">Questo telefono non considera attendibile il certificato dell\'istanza: installa il certificato della sua autorità di certificazione tra i certificati utente di Android (Impostazioni, Sicurezza, Crittografia e credenziali, Installa un certificato).</string>
|
||||
<string name="signed_out">%1$s ha disconnesso questo telefono. Accedi di nuovo per continuare: le tue chat e le impostazioni fatte qui restano.</string>
|
||||
<string name="signed_out_again">Accedi di nuovo</string>
|
||||
<string name="signed_out_use">Usa %1$s</string>
|
||||
<string name="signed_out_remove">Rimuovi questa istanza</string>
|
||||
<string name="new_chat">Nuova chat</string>
|
||||
<string name="empty_chats">Ancora nessuna chat. Non tutti quelli che vagano sono perduti — iniziane una.</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="agent_device">Computer</string>
|
||||
<string name="agent_no_device">Nessun computer è collegato ora. Avvia il servizio della CLI di LLeMbas (lembas service) su un computer connesso a questa istanza, poi torna qui.</string>
|
||||
<string name="agent_directory">Cartella sul computer</string>
|
||||
<string name="agent_directory_hint">Vuoto: la prima cartella del computer</string>
|
||||
<string name="empty_chat">Di cosa parliamo?</string>
|
||||
<string name="loading_line">I lembas stanno cuocendo…</string>
|
||||
<string name="archive">Archivia</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Continua</string>
|
||||
<string name="older">Messaggi precedenti</string>
|
||||
<string name="queued">In attesa di invio</string>
|
||||
<string name="fate_unknown">Non si sa se questo messaggio abbia raggiunto il computer. Invialo di nuovo o scartalo.</string>
|
||||
<string name="fate_carried">Il computer ha questo messaggio e lo accoglierà al suo prossimo turno.</string>
|
||||
<string name="send_now">Invia ora</string>
|
||||
<string name="discard_message_confirm">Scartare questo messaggio?</string>
|
||||
<string name="reply_unrecorded">La risposta a questo non è stata registrata.</string>
|
||||
<string name="thinking">Ragionamento</string>
|
||||
<string name="thought">Ha ragionato</string>
|
||||
<string name="output_cut">L\'output qui è abbreviato. Lo trovi per intero sulla pagina web.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Trascritto da %1$s: il modello vocale proprio di questa chat non ha risposto.</string>
|
||||
<string name="read_by_fallback">Letto da %1$s: il modello vocale proprio di questa chat non ha risposto.</string>
|
||||
<string name="remove">Rimuovi</string>
|
||||
<string name="more">Altro</string>
|
||||
<string name="back">Indietro</string>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Questa istanza 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="files_upload">Carica</string>
|
||||
<string name="files_new_file">Nuovo file</string>
|
||||
<string name="files_new_file_ask">Come deve chiamarsi il file? Con l’estensione, ad esempio notes.md.</string>
|
||||
<string name="files_new_folder_ask">Come deve chiamarsi la cartella?</string>
|
||||
<string name="files_bad_name">Un nome non può essere vuoto né contenere una barra.</string>
|
||||
<string name="files_taken">Qui c’è già qualcosa chiamato %1$s.</string>
|
||||
<string name="rename">Rinomina</string>
|
||||
<string name="files_new_name">Nuovo nome</string>
|
||||
<string name="files_move">Sposta</string>
|
||||
<string name="files_copy_to">Copia in…</string>
|
||||
<string name="files_move_here">Sposta qui</string>
|
||||
<string name="files_copy_here">Copia qui</string>
|
||||
<string name="files_move_which">In quale cartella spostare?</string>
|
||||
<string name="files_copy_which">In quale cartella copiare?</string>
|
||||
<string name="files_choose_folder">Scegli una cartella</string>
|
||||
<string name="files_save_here">Salva qui</string>
|
||||
<string name="files_no_folders">Nessuna cartella qui.</string>
|
||||
<string name="files_to_trash">Sposta nel cestino</string>
|
||||
<string name="files_trash_one">Spostare «%1$s» nel cestino? Si può ripristinare da lì.</string>
|
||||
<string name="files_trash_many">Spostare i %1$s selezionati nel cestino? Da lì si possono ripristinare.</string>
|
||||
<string name="files_trashed">Spostato nel cestino.</string>
|
||||
<string name="files_selected">Selezionati: %1$s</string>
|
||||
<string name="files_select_all">Seleziona tutto</string>
|
||||
<string name="download">Scarica</string>
|
||||
<string name="files_download_zip">Scarica come zip</string>
|
||||
<string name="files_downloading">Download in corso…</string>
|
||||
<string name="files_downloaded">Scaricato.</string>
|
||||
<string name="files_uploading">Caricamento di %1$s su %2$s…</string>
|
||||
<string name="files_uploaded">Caricato.</string>
|
||||
<string name="files_open_with">Apri con…</string>
|
||||
<string name="files_no_app">Nessuna app su questo telefono apre questo tipo di file.</string>
|
||||
<string name="trash">Cestino</string>
|
||||
<string name="trash_is_empty">Il cestino è vuoto.</string>
|
||||
<string name="trash_empty">Svuota il cestino</string>
|
||||
<string name="trash_empty_confirm">Rimuovere definitivamente tutto ciò che è nel cestino? Non si può annullare.</string>
|
||||
<string name="trash_remove">Rimuovi definitivamente</string>
|
||||
<string name="trash_remove_confirm">Rimuovere definitivamente «%1$s»? Non si può annullare.</string>
|
||||
<string name="restore">Ripristina</string>
|
||||
<string name="versions">Versioni</string>
|
||||
<string name="version_restore">Ripristina questa versione</string>
|
||||
<string name="version_restore_confirm">Rendere questa versione quella attuale? Quella attuale resta nell\'elenco.</string>
|
||||
<string name="version_current">Attuale</string>
|
||||
<string name="files_type">Tipo</string>
|
||||
<string name="files_size">Dimensione</string>
|
||||
<string name="files_no_viewer">Non c\'è un visualizzatore per questo tipo di file.</string>
|
||||
<string name="files_not_shown">Non è stato possibile mostrare qui questo file. Si può comunque scaricare.</string>
|
||||
<string name="files_svg_source">Questo è il sorgente dell’immagine. Aprila con un’altra app per vedere l’immagine.</string>
|
||||
<string name="archive_note">Il contenuto di questo tipo di archivio non può essere elencato qui.</string>
|
||||
<string name="archive_entries">%1$s voci. Qui non viene estratto nulla.</string>
|
||||
<string name="archive_cut">Sono elencate solo le prime %1$s voci.</string>
|
||||
<string name="archive_unreadable">Non è stato possibile leggere questo archivio.</string>
|
||||
<string name="files_waiting">In attesa che l\'app sia aperta e il telefono sbloccato.</string>
|
||||
<string name="share_refused">Qualcosa di ciò che è stato condiviso non può essere inviato da qui ed è stato escluso.</string>
|
||||
<string name="media_in_trash">Questo file è nel cestino.</string>
|
||||
<string name="table_cut">Solo le prime righe e colonne sono disposte in tabella. Il testo contiene tutto.</string>
|
||||
<string name="table_as_text">Mostra come testo</string>
|
||||
<string name="table_as_table">Mostra come tabella</string>
|
||||
<string name="media_open_in_files">Apri in File</string>
|
||||
<string name="media_image">Immagine</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Musica</string>
|
||||
<string name="media_model">Modello 3D</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archivio</string>
|
||||
<string name="media_text">File di testo</string>
|
||||
<string name="media_binary">File</string>
|
||||
<string name="diff_deleted">Eliminato</string>
|
||||
<string name="diff_counts">Righe aggiunte: %1$s, rimosse: %2$s</string>
|
||||
<string name="diff_show_all">Mostra tutte le %1$s righe</string>
|
||||
<string name="diff_show_less">Mostra meno</string>
|
||||
<string name="diff_more">Altre %1$s righe non sono mostrate qui.</string>
|
||||
<string name="diff_endings">I fine riga cambiano da %1$s a %2$s.</string>
|
||||
<string name="diff_cut">Questa modifica è troppo lunga per essere confrontata qui. Ne è mostrato solo l’inizio.</string>
|
||||
<string name="media_gone">Questo file non esiste più.</string>
|
||||
<string name="job_queued">In coda</string>
|
||||
<string name="job_running">In esecuzione</string>
|
||||
<string name="job_done">Fatto</string>
|
||||
<string name="job_failed">Non riusciti</string>
|
||||
<string name="job_cancelled">Annullato</string>
|
||||
<string name="job_expired">Scaduto</string>
|
||||
<string name="mcp_title">Server MCP</string>
|
||||
<string name="mcp_intro">I server i cui strumenti possono essere offerti nelle tue chat. Alcuni si usano con un tuo account presso di loro: i loro strumenti sono offerti finché hai effettuato l’accesso.</string>
|
||||
<string name="mcp_none">Su questa istanza non ti è offerto alcun server MCP.</string>
|
||||
<string name="mcp_ready">Pronto</string>
|
||||
<string name="mcp_signed_in">Accesso effettuato</string>
|
||||
<string name="mcp_signed_out">Accesso non effettuato</string>
|
||||
<string name="mcp_needs_signin">Serve un nuovo accesso</string>
|
||||
<string name="mcp_tools">Strumenti: %1$s</string>
|
||||
<string name="mcp_account">Accesso effettuato come %1$s</string>
|
||||
<string name="mcp_until">Accesso valido fino a %1$s</string>
|
||||
<string name="mcp_shared_note">Questo server ha un accesso condiviso, che viene eseguito da un amministratore.</string>
|
||||
<string name="mcp_browser_note">L’accesso avviene nel browser, sull’istanza stessa. Se il browser non ha effettuato l’accesso all’istanza, prima lo chiede. Poi torna qui.</string>
|
||||
<string name="mcp_sign_in">Accedi</string>
|
||||
<string name="notebook_empty">Questo notebook non ha celle.</string>
|
||||
<string name="notebook_more">Altre %1$s celle non vengono mostrate.</string>
|
||||
<string name="notebook_cell_cut">Questa cella è più lunga di quanto mostrato qui.</string>
|
||||
<string name="viewer_page">Pagina %1$s di %2$s</string>
|
||||
<string name="play">Riproduci</string>
|
||||
<string name="pause">Metti in pausa</string>
|
||||
<string name="files_conflict">Il file è cambiato da quando l\'hai aperto. Ricaricalo o salva comunque.</string>
|
||||
<string name="files_save_anyway">Salva comunque</string>
|
||||
<string name="reload">Ricarica</string>
|
||||
<string name="discard">Scarta</string>
|
||||
<string name="files_unsaved">Scartare le modifiche a questo file?</string>
|
||||
<string name="share_to_files">Salva in File</string>
|
||||
<string name="settings">Impostazioni</string>
|
||||
<string name="settings_instances">Istanze</string>
|
||||
<string name="sign_out">Esci</string>
|
||||
<string name="add_instance">Aggiungi un\'istanza</string>
|
||||
<string name="instance_default">Predefinito</string>
|
||||
<string name="instance_set_default">Imposta come predefinita</string>
|
||||
<string name="instance_switch">Cambia istanza</string>
|
||||
<string name="settings_theme">Tema</string>
|
||||
<string name="theme_system">Come il sistema</string>
|
||||
<string name="theme_moria">Moria (scuro)</string>
|
||||
@@ -358,7 +487,7 @@
|
||||
<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_account_unknown">Non ancora letta dalla tua 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>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Assistente</string>
|
||||
<string name="assistant_explained">Rendi LLeMbas l\'assistente digitale del telefono: selezionalo in App predefinite › App di assistenza digitale. Tenendo premuto il tasto di accensione, il gesto di assistenza o la scorciatoia della schermata di blocco lo apre quindi sopra qualsiasi cosa sia a schermo.</string>
|
||||
<string name="assistant_open_settings">Apri le impostazioni dell\'assistente</string>
|
||||
<string name="assistant_model">Modello dell’assistente</string>
|
||||
<string name="assistant_model_default">Predefinito dell’istanza</string>
|
||||
<string name="assistant_model_default_line">Il modello con cui iniziano le tue nuove chat. Se è troppo lento per una domanda a voce, scegline sotto uno più rapido.</string>
|
||||
<string name="assistant_samsung">Sui telefoni Samsung: Impostazioni › Funzioni avanzate › Tasto laterale › Pressione prolungata › Assistente digitale.</string>
|
||||
<string name="assistant_temporary">Le chat dell\'assistente sono temporanee</string>
|
||||
<string name="assistant_read_aloud">Leggi la risposta ad alta voce quando la domanda è vocale</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Al massimo una volta al giorno, all’avvio, l’app chiede alla tua istanza quale release le corrisponde — oppure legge l’elenco delle release su GitHub quando l’istanza non sa dirlo — e ti avvisa con una notifica quando ce n’è una più recente. Con nessuna delle due richieste viene inviato qualcosa su di te. 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>
|
||||
@@ -398,9 +530,9 @@
|
||||
<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_screen_both">Il testo dello schermo e uno screenshot accompagnano la tua prossima domanda.</string>
|
||||
<string name="assist_screen_text">Il testo dello schermo accompagna la tua prossima domanda.</string>
|
||||
<string name="assist_screen_shot">Uno screenshot accompagna la tua 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>
|
||||
@@ -416,18 +548,25 @@
|
||||
<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_answer_in_app">Questa risposta attende una tua decisione: aprila 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_unlock_to_send">Sblocca per inviare</string>
|
||||
<string name="assist_question_heard">Domanda sentita</string>
|
||||
<string name="assist_recording_waits_line">Il telefono è bloccato. La tua domanda attende su questo telefono come registrazione; non è stato inviato nulla. Allo sblocco viene inviata alla tua istanza per essere trascritta e ricevere risposta.</string>
|
||||
<string name="assist_locked_line">Il telefono è bloccato. Finché non lo sblocchi non viene inviato nulla e non viene mostrata alcuna risposta.</string>
|
||||
<string name="assist_conversation">In conversazione</string>
|
||||
<string name="assist_conversation_line">Ascolto di nuovo dopo ogni risposta. Di’ «basta» per finire.</string>
|
||||
<string name="assist_conversation_end">Termina</string>
|
||||
<string name="assist_stop_words">basta|stop|è tutto|fine|ciao|arrivederci|grazie è tutto|annulla|smetti</string>
|
||||
<string name="assistant_conversation">Continuare una conversazione a voce</string>
|
||||
<string name="assistant_conversation_line">Dopo aver letto ad alta voce una risposta a voce, l’assistente ascolta di nuovo, finché non dici «basta», tocchi Termina o non dici nulla per qualche secondo. Funziona con le cuffie.</string>
|
||||
<string name="assist_wake_word_hint">Nessuna parola di attivazione, a meno che tu non la voglia: Impostazioni › Assistente › Parola di attivazione attiva quella di LLeMbas, su questo telefono.</string>
|
||||
<string name="experimental">Sperimentale</string>
|
||||
<string name="wake_experimental_line">Nuovo e provato finora su pochi telefoni. Può non sentire la frase, attivarsi per errore, oppure sentirti e non aprire comunque l’assistente.</string>
|
||||
<string name="assistant_voice_experimental_line">Sperimentale: l’ascolto automatico all’apertura dell’assistente, il riconoscimento di quando hai finito di parlare e la conversazione a voce sono nuovi e non funzionano ancora bene su tutti i telefoni. Scrivere una domanda e il pulsante del microfono funzionano sempre.</string>
|
||||
<string name="assist_wake_word_hint">Nessuna parola di attivazione, a meno che tu non la voglia: Impostazioni › Parola di attivazione attiva quella di LLeMbas, su questo telefono.</string>
|
||||
<string name="channel_wake">Parola di attivazione</string>
|
||||
<string name="wake_word">Parola di attivazione</string>
|
||||
<string name="wake_word_listen">Ascolta una parola di attivazione</string>
|
||||
@@ -546,15 +685,52 @@
|
||||
<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_lembas_line">La trascrizione della tua istanza. Questo telefono invia la registrazione solo alla tua istanza; l’istanza la trascrive con il modello vocale configurato lì.</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_line">Il riconoscimento vocale del telefono. Le parole appaiono mentre parli; 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>
|
||||
<string name="share_ask_hint">Cosa deve farne LLeMbas? (facoltativo)</string>
|
||||
<string name="widget_hint">Chiedi qualsiasi cosa</string>
|
||||
<string name="directory_places">Posizioni su questo dispositivo</string>
|
||||
<string name="directory_last_used">Ultimo usato qui: %1$s. Una nuova chat in questa cartella parte da questo, a meno che non ne scegliate un altro.</string>
|
||||
<string name="directory_refused">Il dispositivo non aprirà una sessione qui.</string>
|
||||
<string name="directory_up">Su di un livello</string>
|
||||
<string name="directory_all_places">Tutte le posizioni</string>
|
||||
<string name="directory_not_trusted">Non attendibile sul dispositivo</string>
|
||||
<string name="directory_empty">Nessuna cartella qui.</string>
|
||||
<string name="directory_no_places">Questo dispositivo non offre cartelle: le sue radici remote sono vuote o mancanti.</string>
|
||||
<string name="directory_browse">Sfoglia</string>
|
||||
<string name="directory_path">Un percorso completo</string>
|
||||
<string name="directory_choose">Scegli</string>
|
||||
<string name="directory_no_listing">Le cartelle di questo dispositivo non si possono elencare adesso. Scrivi il percorso qui sotto.</string>
|
||||
<string name="model">Modello</string>
|
||||
<string name="schedule_type">Tipo</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Viene eseguita su questo server, come una chat: con gli strumenti del server (ricerca, i vostri file qui, memoria) e su un modello di pianificazione.</string>
|
||||
<string name="schedule_agentic">Agentico</string>
|
||||
<string name="schedule_agentic_line">Viene eseguita su uno dei vostri computer, in una cartella lì, come agente: con gli strumenti dell\'agente su quel computer — i suoi file e la sua shell — entro i limiti propri del computer. Appartiene a quel computer e a quella cartella.</string>
|
||||
<string name="schedule_agentic_unavailable">Nessuno dei vostri computer accetta ora lavoro pianificato. Collegatene uno e attivate «Accept scheduled work» nel suo LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">non accetta lavoro pianificato</string>
|
||||
<string name="schedule_computer_hint">Il computer deve consentirlo: «Accept scheduled work» nel suo LLeMbas CLI (lembas service scheduled on). Se non è collegato al momento di un\'esecuzione, l\'esecuzione lo attende; se non è tornato prima che il suo orario sia passato, l\'esecuzione viene registrata come mancata e ne venite informati.</string>
|
||||
<string name="schedule_computer_gone">un computer non più connesso</string>
|
||||
<string name="schedule_folder">Cartella sul computer</string>
|
||||
<string name="schedule_agent_mode">Modalità</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, salvo diversa scelta; Auto esegue i comandi senza chiedere. Il computer può abbassarla.</string>
|
||||
<string name="schedule_approval_wait">Un\'approvazione attende (minuti)</string>
|
||||
<string name="schedule_approval_wait_hint">Un comando che l\'esecuzione deve far approvare arriva al tuo telefono come scheda. Senza risposta entro allora, conta come negato.</string>
|
||||
<string name="schedule_watch_command_hint">Facoltativo, sul computer. Eseguito nella cartella prima di ogni esecuzione; quando il suo output è uguale all\'ultima volta, l\'esecuzione si ferma lì. Un comando per cui la modalità chiederebbe viene rifiutato.</string>
|
||||
<string name="schedule_watch_timeout">Il comando può durare (secondi)</string>
|
||||
<string name="schedule_watch_timeout_hint">Poi viene fermato e l\'esecuzione fallisce.</string>
|
||||
<string name="schedule_chat_drops_watch">Questa attività controlla un comando sul suo computer. Come attività di tipo Chat non lo fa più: viene eseguita ogni volta.</string>
|
||||
<string name="schedule_folder_model">Il modello abituale della cartella</string>
|
||||
<string name="schedule_folder_model_hint">Il modello abituale della cartella è quello che avete usato per ultimo in quella cartella su quel computer — il computer lo ricorda e ogni esecuzione glielo chiede — oppure il vostro modello predefinito dove non ce n\'è. Un modello scelto qui è quello dell\'esecuzione, qualunque sia quello della cartella. Un\'esecuzione non cambia mai il modello della cartella.</string>
|
||||
<string name="schedule_first_free_model">Il primo libero dei tuoi modelli per la pianificazione</string>
|
||||
<string name="run_model_directory">il modello abituale della cartella</string>
|
||||
<string name="run_model_default">il tuo modello predefinito</string>
|
||||
<string name="run_model_session">il modello proprio della conversazione</string>
|
||||
<string name="widget_speak">Parla</string>
|
||||
<string name="widget_description">Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account.</string>
|
||||
<string name="shortcut_last">Ultima chat</string>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12 (moria). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (moria). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FF0B0D10</color>
|
||||
<color name="token_surface">#FF11151A</color>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas na Androida</string>
|
||||
<string name="share_label">Zapytaj LLeMbas</string>
|
||||
<string name="tile_ask">Zapytaj LLeMbas</string>
|
||||
<string name="signin_intro">Zaloguj się do instancji LLeMbas. Ten telefon zatwierdza się w przeglądarce, tak jak CLI.</string>
|
||||
<string name="signin_intro">Zaloguj się do instancji LLeMbas. Ten telefon zatwierdza się w przeglądarce.</string>
|
||||
<string name="signin_address">Adres instancji</string>
|
||||
<string name="signin_continue">Kontynuuj</string>
|
||||
<string name="signin_code_intro">Otwórz instancję w przeglądarce, zaloguj się i zatwierdź ten kod:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Ta instancja jest nowsza, niż obsługuje ta aplikacja. Zaktualizuj aplikację.</string>
|
||||
<string name="signin_not_lembas">Pod tym adresem nie ma instancji LLeMbas.</string>
|
||||
<string name="signin_failed">Nie udało się dokończyć logowania (%1$s). Spróbuj ponownie.</string>
|
||||
<string name="signin_app_too_old">Ta instancja wymaga LLeMbas dla Androida %1$s lub nowszego, a to jest %2$s. Zaktualizuj aplikację.</string>
|
||||
<string name="signin_other_origin">Ta instancja podaje do logowania inny adres (%1$s) niż wpisany. Jej proxy musi przekazywać adres, pod którym jest dostępna.</string>
|
||||
<string name="address_needs_https">Ta aplikacja wymaga adresu https://: zwykłe http nie jest obsługiwane.</string>
|
||||
<string name="address_unreadable">Aplikacja nie może użyć tego adresu. Wpisz adres instancji, na przykład llm.example.org.</string>
|
||||
<string name="server_answered">Serwer odpowiedział: %1$s.</string>
|
||||
<string name="timed_out">Instancja nie odpowiedziała na czas.</string>
|
||||
<string name="not_trusted">Ten telefon nie ufa certyfikatowi instancji: zainstaluj certyfikat jej urzędu certyfikacji wśród certyfikatów użytkownika Androida (Ustawienia, Bezpieczeństwo, Szyfrowanie i dane logowania, Zainstaluj certyfikat).</string>
|
||||
<string name="signed_out">%1$s wylogowała ten telefon. Zaloguj się ponownie, aby kontynuować: Twoje czaty i tutejsze ustawienia zostają.</string>
|
||||
<string name="signed_out_again">Zaloguj się ponownie</string>
|
||||
<string name="signed_out_use">Użyj %1$s</string>
|
||||
<string name="signed_out_remove">Usuń tę instancję</string>
|
||||
<string name="new_chat">Nowy czat</string>
|
||||
<string name="empty_chats">Nie ma jeszcze czatów. Nie każdy, kto błądzi, jest zgubiony — zacznij jeden.</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="agent_device">Komputer</string>
|
||||
<string name="agent_no_device">Żaden komputer nie jest teraz połączony. Uruchom usługę LLeMbas CLI (lembas service) na komputerze zalogowanym do tej instancji i wróć.</string>
|
||||
<string name="agent_directory">Folder na komputerze</string>
|
||||
<string name="agent_directory_hint">Puste: pierwszy folder komputera</string>
|
||||
<string name="empty_chat">O czym porozmawiamy?</string>
|
||||
<string name="loading_line">Lembasy się pieczą…</string>
|
||||
<string name="archive">Archiwizuj</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Kontynuuj</string>
|
||||
<string name="older">Wcześniejsze wiadomości</string>
|
||||
<string name="queued">Czeka na wysłanie</string>
|
||||
<string name="fate_unknown">Nie wiadomo, czy ta wiadomość dotarła do komputera. Wyślij ją ponownie albo odrzuć.</string>
|
||||
<string name="fate_carried">Komputer ma tę wiadomość i uwzględni ją w swojej następnej turze.</string>
|
||||
<string name="send_now">Wyślij teraz</string>
|
||||
<string name="discard_message_confirm">Odrzucić tę wiadomość?</string>
|
||||
<string name="reply_unrecorded">Odpowiedź na to nie została zapisana.</string>
|
||||
<string name="thinking">Rozumowanie</string>
|
||||
<string name="thought">Rozumowanie</string>
|
||||
<string name="output_cut">Wynik jest tu skrócony. Cały znajduje się na stronie internetowej.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Transkrybował %1$s: własny model mowy tego czatu nie odpowiedział.</string>
|
||||
<string name="read_by_fallback">Przeczytał %1$s: własny model mowy tego czatu nie odpowiedział.</string>
|
||||
<string name="remove">Usuń</string>
|
||||
<string name="more">Więcej</string>
|
||||
<string name="back">Wstecz</string>
|
||||
@@ -340,16 +360,125 @@
|
||||
<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_unavailable">Ta instancja 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="files_upload">Prześlij</string>
|
||||
<string name="files_new_file">Nowy plik</string>
|
||||
<string name="files_new_file_ask">Jak ma się nazywać plik? Z rozszerzeniem, na przykład notes.md.</string>
|
||||
<string name="files_new_folder_ask">Jak ma się nazywać folder?</string>
|
||||
<string name="files_bad_name">Nazwa nie może być pusta ani zawierać ukośnika.</string>
|
||||
<string name="files_taken">Coś o nazwie %1$s już tu jest.</string>
|
||||
<string name="rename">Zmień nazwę</string>
|
||||
<string name="files_new_name">Nowa nazwa</string>
|
||||
<string name="files_move">Przenieś</string>
|
||||
<string name="files_copy_to">Kopiuj do…</string>
|
||||
<string name="files_move_here">Przenieś tutaj</string>
|
||||
<string name="files_copy_here">Kopiuj tutaj</string>
|
||||
<string name="files_move_which">Do którego folderu przenieść?</string>
|
||||
<string name="files_copy_which">Do którego folderu skopiować?</string>
|
||||
<string name="files_choose_folder">Wybierz folder</string>
|
||||
<string name="files_save_here">Zapisz tutaj</string>
|
||||
<string name="files_no_folders">Brak katalogów.</string>
|
||||
<string name="files_to_trash">Przenieś do kosza</string>
|
||||
<string name="files_trash_one">Przenieść „%1$s” do kosza? Można go stamtąd przywrócić.</string>
|
||||
<string name="files_trash_many">Przenieść zaznaczone (%1$s) do kosza? Stamtąd można je przywrócić.</string>
|
||||
<string name="files_trashed">Przeniesiono do kosza.</string>
|
||||
<string name="files_selected">Zaznaczone: %1$s</string>
|
||||
<string name="files_select_all">Zaznacz wszystko</string>
|
||||
<string name="download">Pobierz</string>
|
||||
<string name="files_download_zip">Pobierz jako zip</string>
|
||||
<string name="files_downloading">Pobieranie…</string>
|
||||
<string name="files_downloaded">Pobrano.</string>
|
||||
<string name="files_uploading">Przesyłanie %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Przesłano.</string>
|
||||
<string name="files_open_with">Otwórz za pomocą…</string>
|
||||
<string name="files_no_app">Żadna aplikacja na tym telefonie nie otwiera tego rodzaju pliku.</string>
|
||||
<string name="trash">Kosz</string>
|
||||
<string name="trash_is_empty">Kosz jest pusty.</string>
|
||||
<string name="trash_empty">Opróżnij kosz</string>
|
||||
<string name="trash_empty_confirm">Usunąć na stałe wszystko z kosza? Tego nie da się cofnąć.</string>
|
||||
<string name="trash_remove">Usuń na stałe</string>
|
||||
<string name="trash_remove_confirm">Usunąć „%1$s” na stałe? Tego nie da się cofnąć.</string>
|
||||
<string name="restore">Przywróć</string>
|
||||
<string name="versions">Wersje</string>
|
||||
<string name="version_restore">Przywróć tę wersję</string>
|
||||
<string name="version_restore_confirm">Uczynić tę wersję bieżącą? Obecna zostanie na liście.</string>
|
||||
<string name="version_current">Bieżąca</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Rozmiar</string>
|
||||
<string name="files_no_viewer">Nie ma przeglądarki dla tego rodzaju pliku.</string>
|
||||
<string name="files_not_shown">Nie udało się tu pokazać tego pliku. Nadal można go pobrać.</string>
|
||||
<string name="files_svg_source">To jest źródło obrazu. Otwórz je w innej aplikacji, aby zobaczyć obraz.</string>
|
||||
<string name="archive_note">Zawartości tego rodzaju archiwum nie można tu wypisać.</string>
|
||||
<string name="archive_entries">Pozycji: %1$s. Nic nie jest tu rozpakowywane.</string>
|
||||
<string name="archive_cut">Wypisano tylko pierwszych %1$s pozycji.</string>
|
||||
<string name="archive_unreadable">Nie udało się odczytać tego archiwum.</string>
|
||||
<string name="files_waiting">Oczekiwanie, aż aplikacja będzie otwarta, a telefon odblokowany.</string>
|
||||
<string name="share_refused">Czegoś z udostępnionych rzeczy nie można stąd wysłać i zostało pominięte.</string>
|
||||
<string name="media_in_trash">Ten plik jest w koszu.</string>
|
||||
<string name="table_cut">W tabeli ułożono tylko pierwsze wiersze i kolumny. Tekst zawiera wszystko.</string>
|
||||
<string name="table_as_text">Pokaż jako tekst</string>
|
||||
<string name="table_as_table">Pokaż jako tabelę</string>
|
||||
<string name="media_open_in_files">Otwórz w Plikach</string>
|
||||
<string name="media_image">Obraz</string>
|
||||
<string name="media_video">Wideo</string>
|
||||
<string name="media_music">Muzyka</string>
|
||||
<string name="media_model">Model 3D</string>
|
||||
<string name="media_audio">Dźwięk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archiwum</string>
|
||||
<string name="media_text">Plik tekstowy</string>
|
||||
<string name="media_binary">Plik</string>
|
||||
<string name="diff_deleted">Usunięto</string>
|
||||
<string name="diff_counts">Dodane wiersze: %1$s, usunięte: %2$s</string>
|
||||
<string name="diff_show_all">Pokaż wszystkie wiersze (%1$s)</string>
|
||||
<string name="diff_show_less">Pokaż mniej</string>
|
||||
<string name="diff_more">Dalsze wiersze, których tu nie pokazano: %1$s.</string>
|
||||
<string name="diff_endings">Końce wierszy zmieniają się z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Ta zmiana jest zbyt długa, by ją tu porównać. Pokazano tylko jej początek.</string>
|
||||
<string name="media_gone">Ten plik już nie istnieje.</string>
|
||||
<string name="job_queued">W kolejce</string>
|
||||
<string name="job_running">Działa</string>
|
||||
<string name="job_done">Gotowe</string>
|
||||
<string name="job_failed">Nieudane</string>
|
||||
<string name="job_cancelled">Anulowane</string>
|
||||
<string name="job_expired">Wygasło</string>
|
||||
<string name="mcp_title">Serwery MCP</string>
|
||||
<string name="mcp_intro">Serwery, których narzędzia mogą być oferowane w Twoich czatach. Niektóre działają z Twoim własnym kontem u nich: ich narzędzia są oferowane, dopóki trwa zalogowanie.</string>
|
||||
<string name="mcp_none">Na tej instancji nie są oferowane żadne serwery MCP.</string>
|
||||
<string name="mcp_ready">Gotowy</string>
|
||||
<string name="mcp_signed_in">Zalogowano</string>
|
||||
<string name="mcp_signed_out">Nie zalogowano</string>
|
||||
<string name="mcp_needs_signin">Wymaga ponownego zalogowania</string>
|
||||
<string name="mcp_tools">Narzędzia: %1$s</string>
|
||||
<string name="mcp_account">Zalogowano jako %1$s</string>
|
||||
<string name="mcp_until">Zalogowano do %1$s</string>
|
||||
<string name="mcp_shared_note">Ten serwer ma jedno wspólne logowanie, które wykonuje administrator.</string>
|
||||
<string name="mcp_browser_note">Logowanie odbywa się w przeglądarce, na samej instancji. Jeśli przeglądarka nie jest zalogowana do instancji, najpierw o to poprosi. Potem wróć tutaj.</string>
|
||||
<string name="mcp_sign_in">Zaloguj się</string>
|
||||
<string name="notebook_empty">Ten notatnik nie ma komórek.</string>
|
||||
<string name="notebook_more">Kolejnych %1$s komórek nie pokazano.</string>
|
||||
<string name="notebook_cell_cut">Ta komórka jest dłuższa, niż tu pokazano.</string>
|
||||
<string name="viewer_page">Strona %1$s z %2$s</string>
|
||||
<string name="play">Odtwórz</string>
|
||||
<string name="pause">Wstrzymaj</string>
|
||||
<string name="files_conflict">Plik zmienił się od otwarcia. Wczytaj go ponownie albo zapisz mimo to.</string>
|
||||
<string name="files_save_anyway">Zapisz mimo to</string>
|
||||
<string name="reload">Przeładuj</string>
|
||||
<string name="discard">Odrzuć</string>
|
||||
<string name="files_unsaved">Odrzucić zmiany w tym pliku?</string>
|
||||
<string name="share_to_files">Zapisz w Plikach</string>
|
||||
<string name="settings">Ustawienia</string>
|
||||
<string name="settings_instances">Instancje</string>
|
||||
<string name="sign_out">Wyloguj się</string>
|
||||
<string name="add_instance">Dodaj instancję</string>
|
||||
<string name="instance_default">Domyślny</string>
|
||||
<string name="instance_set_default">Ustaw jako domyślną</string>
|
||||
<string name="instance_switch">Przełącz instancję</string>
|
||||
<string name="settings_theme">Motyw</string>
|
||||
<string name="theme_system">Jak system</string>
|
||||
<string name="theme_moria">Moria (ciemny)</string>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Asystent</string>
|
||||
<string name="assistant_explained">Ustaw LLeMbas jako cyfrowego asystenta telefonu: wybierz go w Domyślne aplikacje › Aplikacja asystenta cyfrowego. Przytrzymanie przycisku zasilania, gest asystenta lub skrót z ekranu blokady otwiera go wtedy nad tym, co jest na ekranie.</string>
|
||||
<string name="assistant_open_settings">Otwórz ustawienia asystenta</string>
|
||||
<string name="assistant_model">Model asystenta</string>
|
||||
<string name="assistant_model_default">Domyślny model instancji</string>
|
||||
<string name="assistant_model_default_line">Model, od którego zaczynają się Twoje nowe czaty. Jeśli jest za wolny na pytanie zadane głosem, wybierz poniżej szybszy.</string>
|
||||
<string name="assistant_samsung">W telefonach Samsung: Ustawienia › Funkcje zaawansowane › Przycisk boczny › Naciśnięcie i przytrzymanie › Asystent cyfrowy.</string>
|
||||
<string name="assistant_temporary">Czaty asystenta są tymczasowe</string>
|
||||
<string name="assistant_read_aloud">Odczytaj odpowiedź na głos, gdy pytanie było głosowe</string>
|
||||
@@ -387,7 +519,7 @@
|
||||
<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_auto_line">Najwyżej raz dziennie, przy uruchomieniu, aplikacja pyta Twoją instancję, które wydanie do niej pasuje — albo odczytuje listę wydań z GitHuba, gdy instancja nie potrafi tego powiedzieć — i daje znać powiadomieniem, gdy jest nowsze. Z żadnym z tych zapytań nie jest wysyłane nic o Tobie. 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>
|
||||
@@ -421,13 +553,20 @@
|
||||
<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_unlock_to_send">Odblokuj, aby wysłać</string>
|
||||
<string name="assist_question_heard">Pytanie usłyszane</string>
|
||||
<string name="assist_recording_waits_line">Telefon jest zablokowany. Twoje pytanie czeka w tym telefonie jako nagranie; nic nie zostało wysłane. Po odblokowaniu trafi do Twojej instancji, która je zapisze i na nie odpowie.</string>
|
||||
<string name="assist_locked_line">Telefon jest zablokowany. Dopóki go nie odblokujesz, nic nie zostanie wysłane ani żadna odpowiedź nie zostanie pokazana.</string>
|
||||
<string name="assist_conversation">Rozmowa</string>
|
||||
<string name="assist_conversation_line">Po każdej odpowiedzi słucham znowu. Powiedz „stop”, aby zakończyć.</string>
|
||||
<string name="assist_conversation_end">Zakończ</string>
|
||||
<string name="assist_stop_words">stop|wystarczy|to wszystko|koniec|do widzenia|dzięki to wszystko|anuluj|przestań</string>
|
||||
<string name="assistant_conversation">Prowadź rozmowę głosową</string>
|
||||
<string name="assistant_conversation_line">Po odczytaniu odpowiedzi na głos asystent znów słucha — dopóki nie powiesz „stop”, nie dotkniesz Zakończ albo nie będziesz milczeć przez kilka sekund. Działa ze słuchawkami.</string>
|
||||
<string name="assist_wake_word_hint">Bez słowa aktywującego, chyba że chcesz: Ustawienia › Asystent › Słowo aktywujące włącza własne słowo LLeMbas, na tym telefonie.</string>
|
||||
<string name="experimental">Eksperymentalne</string>
|
||||
<string name="wake_experimental_line">Nowość, sprawdzona na razie na niewielu telefonach. Może nie usłyszeć frazy, uruchomić się przez pomyłkę albo usłyszeć Cię i mimo to nie otworzyć asystenta.</string>
|
||||
<string name="assistant_voice_experimental_line">Eksperymentalne: samoczynne słuchanie po otwarciu asystenta, rozpoznawanie, że skończyłeś mówić, oraz rozmowa głosowa są nowe i nie na każdym telefonie działają jeszcze dobrze. Wpisanie pytania i przycisk mikrofonu działają zawsze.</string>
|
||||
<string name="assist_wake_word_hint">Bez słowa aktywującego, chyba że chcesz: Ustawienia › Słowo aktywujące włącza własne słowo LLeMbas, na tym telefonie.</string>
|
||||
<string name="channel_wake">Słowo aktywujące</string>
|
||||
<string name="wake_word">Słowo aktywujące</string>
|
||||
<string name="wake_word_listen">Nasłuchuj słowa aktywującego</string>
|
||||
@@ -546,7 +685,7 @@
|
||||
<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_lembas_line">Zamiana mowy na tekst Twojej instancji. Ten telefon wysyła nagranie tylko do Twojej instancji; instancja zapisuje je modelem mowy, który jest w niej ustawiony.</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>
|
||||
@@ -555,6 +694,43 @@
|
||||
<string name="share_default_prompt">Zobacz to.</string>
|
||||
<string name="share_ask_hint">Co LLeMbas ma z tym zrobić? (opcjonalnie)</string>
|
||||
<string name="widget_hint">Zapytaj o cokolwiek</string>
|
||||
<string name="directory_places">Miejsca na tym urządzeniu</string>
|
||||
<string name="directory_last_used">Ostatnio używany tutaj: %1$s. Nowy czat w tym folderze zaczyna się od niego, chyba że wybierzesz inny.</string>
|
||||
<string name="directory_refused">Urządzenie nie otworzy tutaj sesji.</string>
|
||||
<string name="directory_up">Poziom wyżej</string>
|
||||
<string name="directory_all_places">Wszystkie miejsca</string>
|
||||
<string name="directory_not_trusted">Niezaufane na urządzeniu</string>
|
||||
<string name="directory_empty">Brak katalogów.</string>
|
||||
<string name="directory_no_places">To urządzenie nie udostępnia żadnych katalogów: jego zdalne katalogi główne są puste lub ich brak.</string>
|
||||
<string name="directory_browse">Przeglądaj</string>
|
||||
<string name="directory_path">Pełna ścieżka</string>
|
||||
<string name="directory_choose">Wybierz</string>
|
||||
<string name="directory_no_listing">Katalogów tego urządzenia nie można teraz wyświetlić. Wpisz ścieżkę poniżej.</string>
|
||||
<string name="model">Model</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Czat</string>
|
||||
<string name="schedule_chat_line">Działa na tym serwerze, jak czat: z narzędziami serwera (wyszukiwanie, twoje pliki tutaj, pamięć) i na modelu do planowania.</string>
|
||||
<string name="schedule_agentic">Agentowy</string>
|
||||
<string name="schedule_agentic_line">Działa na jednym z twoich komputerów, w jednym folderze na nim, jako agent: z narzędziami agenta na tym komputerze — jego plikami i jego powłoką — w ramach własnych ograniczeń komputera. Należy do tego komputera i folderu.</string>
|
||||
<string name="schedule_agentic_unavailable">Żaden z twoich komputerów nie przyjmuje teraz zaplanowanej pracy. Połącz któryś i włącz „Accept scheduled work” w jego LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">nie przyjmuje zaplanowanej pracy</string>
|
||||
<string name="schedule_computer_hint">Komputer musi na to pozwolić: „Accept scheduled work” w jego LLeMbas CLI (lembas service scheduled on). Gdy w czasie uruchomienia nie jest połączony, uruchomienie na niego czeka; jeśli nie wróci, zanim minie czas uruchomienia, zostaje ono zapisane jako pominięte i dostajesz o tym informację.</string>
|
||||
<string name="schedule_computer_gone">komputer, który nie jest już zalogowany</string>
|
||||
<string name="schedule_folder">Folder na komputerze</string>
|
||||
<string name="schedule_agent_mode">Tryb</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, chyba że wybierzesz inaczej; Auto uruchamia polecenia bez pytania. Komputer może go obniżyć.</string>
|
||||
<string name="schedule_approval_wait">Zatwierdzenie czeka (minuty)</string>
|
||||
<string name="schedule_approval_wait_hint">Polecenie, które uruchomienie musi zatwierdzić, trafia na Twój telefon jako karta. Bez odpowiedzi do tego czasu liczy się jako odrzucone.</string>
|
||||
<string name="schedule_watch_command_hint">Opcjonalne, na komputerze. Uruchamiane w folderze przed każdym uruchomieniem; gdy jego wynik jest taki sam jak ostatnio, uruchomienie kończy się w tym miejscu. Polecenie, o które tryb by zapytał, jest odrzucane.</string>
|
||||
<string name="schedule_watch_timeout">Polecenie może trwać (sekundy)</string>
|
||||
<string name="schedule_watch_timeout_hint">Potem jest zatrzymywane, a uruchomienie kończy się błędem.</string>
|
||||
<string name="schedule_chat_drops_watch">To zadanie obserwuje polecenie na swoim komputerze. Jako zadanie typu Czat już tego nie robi: uruchamia się za każdym razem.</string>
|
||||
<string name="schedule_folder_model">Zwykły model folderu</string>
|
||||
<string name="schedule_folder_model_hint">Zwykły model folderu to ten, którego ostatnio użyłeś w tym folderze na tym komputerze — komputer go pamięta, a każde uruchomienie go o niego pyta — albo twój model domyślny, gdy takiego nie ma. Model wybrany tutaj jest modelem uruchomienia, niezależnie od modelu folderu. Uruchomienie nigdy nie zmienia modelu folderu.</string>
|
||||
<string name="schedule_first_free_model">Pierwszy wolny z modeli do harmonogramów</string>
|
||||
<string name="run_model_directory">zwykły model folderu</string>
|
||||
<string name="run_model_default">Twój domyślny model</string>
|
||||
<string name="run_model_session">własny model rozmowy</string>
|
||||
<string name="widget_speak">Mów</string>
|
||||
<string name="widget_description">Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta.</string>
|
||||
<string name="shortcut_last">Ostatni czat</string>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<string name="device_name">LLeMbas pre Android</string>
|
||||
<string name="share_label">Spýtať sa LLeMbas</string>
|
||||
<string name="tile_ask">Spýtať sa LLeMbas</string>
|
||||
<string name="signin_intro">Prihláste sa do inštancie LLeMbas. Tento telefón schválite v prehliadači, tak ako by ste schválili CLI.</string>
|
||||
<string name="signin_intro">Prihláste sa do inštancie LLeMbas. Tento telefón schválite v prehliadači.</string>
|
||||
<string name="signin_address">Adresa inštancie</string>
|
||||
<string name="signin_continue">Pokračovať</string>
|
||||
<string name="signin_code_intro">Otvorte inštanciu v prehliadači, prihláste sa a schváľte tento kód:</string>
|
||||
@@ -12,14 +12,27 @@
|
||||
<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 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="signin_too_new">Táto inštancia je novšia, než s akou táto aplikácia vie pracovať. Aktualizujte aplikáciu.</string>
|
||||
<string name="signin_not_lembas">Na tejto adrese nie je žiadna inštancia LLeMbas.</string>
|
||||
<string name="signin_failed">Prihlásenie sa nepodarilo dokončiť (%1$s). Skúste to znova.</string>
|
||||
<string name="signin_app_too_old">Táto inštancia potrebuje LLeMbas pre Android %1$s alebo novší, a toto je %2$s. Aktualizujte aplikáciu.</string>
|
||||
<string name="signin_other_origin">Táto inštancia uvádza na prihlásenie inú adresu (%1$s), než akú ste zadali. Jej proxy musí odovzdávať adresu, na ktorej je dostupná.</string>
|
||||
<string name="address_needs_https">Táto aplikácia potrebuje adresu https://: obyčajné http nie je podporované.</string>
|
||||
<string name="address_unreadable">Túto adresu aplikácia nevie použiť. Zadajte adresu inštancie, napríklad llm.example.org.</string>
|
||||
<string name="server_answered">Server odpovedal %1$s.</string>
|
||||
<string name="timed_out">Inštancia neodpovedala včas.</string>
|
||||
<string name="not_trusted">Tento telefón nedôveruje certifikátu inštancie: nainštalujte certifikát jej certifikačnej autority medzi používateľské certifikáty Androidu (Nastavenia, Zabezpečenie, Šifrovanie a poverenia, Inštalovať certifikát).</string>
|
||||
<string name="signed_out">%1$s tento telefón odhlásila. Prihláste sa znova a pokračujte: vaše konverzácie aj tunajšie nastavenia zostávajú.</string>
|
||||
<string name="signed_out_again">Prihlásiť sa znova</string>
|
||||
<string name="signed_out_use">Použiť %1$s</string>
|
||||
<string name="signed_out_remove">Odstrániť túto inštanciu</string>
|
||||
<string name="new_chat">Nová konverzácia</string>
|
||||
<string name="empty_chats">Zatiaľ žiadne konverzácie. Nie všetci, čo blúdia, sú stratení — začnite jednu.</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="agent_device">Počítač</string>
|
||||
<string name="agent_no_device">Práve nie je prepojený žiadny počítač. Spustite službu LLeMbas CLI (lembas service) na počítači prihlásenom do tejto inštancie a vráťte sa.</string>
|
||||
<string name="agent_directory">Priečinok na počítači</string>
|
||||
<string name="agent_directory_hint">Prázdne: prvý priečinok počítača</string>
|
||||
<string name="empty_chat">O čom sa pozhovárame?</string>
|
||||
<string name="loading_line">Pečú sa lembasy…</string>
|
||||
<string name="archive">Archivovať</string>
|
||||
@@ -51,6 +64,11 @@
|
||||
<string name="continue_reply">Pokračovať</string>
|
||||
<string name="older">Staršie správy</string>
|
||||
<string name="queued">Čaká na odoslanie</string>
|
||||
<string name="fate_unknown">Nie je známe, či sa táto správa dostala do počítača. Odošlite ju znova alebo ju zahoďte.</string>
|
||||
<string name="fate_carried">Počítač túto správu má a prevezme ju pri svojom ďalšom ťahu.</string>
|
||||
<string name="send_now">Poslať teraz</string>
|
||||
<string name="discard_message_confirm">Zahodiť túto správu?</string>
|
||||
<string name="reply_unrecorded">Odpoveď na toto nebola zaznamenaná.</string>
|
||||
<string name="thinking">Premýšľa</string>
|
||||
<string name="thought">Premýšľal</string>
|
||||
<string name="output_cut">Výstup je tu skrátený. Celý nájdete na webovej stránke.</string>
|
||||
@@ -71,6 +89,8 @@
|
||||
<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="transcribed_by_fallback">Prepísal %1$s: vlastný model reči tejto konverzácie neodpovedal.</string>
|
||||
<string name="read_by_fallback">Prečítal %1$s: vlastný model reči tejto konverzácie neodpovedal.</string>
|
||||
<string name="remove">Odstrániť</string>
|
||||
<string name="more">Viac</string>
|
||||
<string name="back">Späť</string>
|
||||
@@ -136,19 +156,19 @@
|
||||
<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_hint">Čísla rátajú aj vlastného agenta tejto konverzácie: 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="subagents_named_only">Tento model obslúži len jednu požiadavku naraz: podagenti potrebujú iný model, na inom serveri, pomenovaný v konverzácii.</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_open">Otvoriť konverzácie</string>
|
||||
<string name="chats_search">Hľadať v konverzáciách</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_agents">Agentské konverzácie</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="chats_none_found">Žiadna konverzácia 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>
|
||||
@@ -208,7 +228,7 @@
|
||||
<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_delete_confirm">Zmazať tento plán? Jeho doterajšie výsledky zostanú vo svojich konverzáciách.</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>
|
||||
@@ -340,24 +360,133 @@
|
||||
<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_unavailable">Táto inštancia 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="files_upload">Nahrať</string>
|
||||
<string name="files_new_file">Nový súbor</string>
|
||||
<string name="files_new_file_ask">Ako sa má súbor volať? Aj s príponou, napríklad notes.md.</string>
|
||||
<string name="files_new_folder_ask">Ako sa má priečinok volať?</string>
|
||||
<string name="files_bad_name">Názov nesmie byť prázdny ani obsahovať lomku.</string>
|
||||
<string name="files_taken">Niečo s názvom %1$s tu už je.</string>
|
||||
<string name="rename">Premenovať</string>
|
||||
<string name="files_new_name">Nový názov</string>
|
||||
<string name="files_move">Presunúť</string>
|
||||
<string name="files_copy_to">Kopírovať do…</string>
|
||||
<string name="files_move_here">Presunúť sem</string>
|
||||
<string name="files_copy_here">Kopírovať sem</string>
|
||||
<string name="files_move_which">Do ktorého priečinka presunúť?</string>
|
||||
<string name="files_copy_which">Do ktorého priečinka kopírovať?</string>
|
||||
<string name="files_choose_folder">Vybrať priečinok</string>
|
||||
<string name="files_save_here">Uložiť sem</string>
|
||||
<string name="files_no_folders">Nie sú tu žiadne priečinky.</string>
|
||||
<string name="files_to_trash">Presunúť do koša</string>
|
||||
<string name="files_trash_one">Presunúť „%1$s“ do koša? Odtiaľ sa dá obnoviť.</string>
|
||||
<string name="files_trash_many">Presunúť vybrané (%1$s) do koša? Odtiaľ sa dajú obnoviť.</string>
|
||||
<string name="files_trashed">Presunuté do koša.</string>
|
||||
<string name="files_selected">Vybrané: %1$s</string>
|
||||
<string name="files_select_all">Vybrať všetko</string>
|
||||
<string name="download">Stiahnuť</string>
|
||||
<string name="files_download_zip">Stiahnuť ako zip</string>
|
||||
<string name="files_downloading">Sťahuje sa…</string>
|
||||
<string name="files_downloaded">Stiahnuté.</string>
|
||||
<string name="files_uploading">Nahráva sa %1$s z %2$s…</string>
|
||||
<string name="files_uploaded">Nahrané.</string>
|
||||
<string name="files_open_with">Otvoriť v…</string>
|
||||
<string name="files_no_app">Žiadna aplikácia v tomto telefóne tento druh súboru neotvorí.</string>
|
||||
<string name="trash">Kôš</string>
|
||||
<string name="trash_is_empty">Kôš je prázdny.</string>
|
||||
<string name="trash_empty">Vyprázdniť kôš</string>
|
||||
<string name="trash_empty_confirm">Natrvalo odstrániť všetko v koši? Nedá sa to vrátiť späť.</string>
|
||||
<string name="trash_remove">Odstrániť natrvalo</string>
|
||||
<string name="trash_remove_confirm">Natrvalo odstrániť „%1$s“? Nedá sa to vrátiť späť.</string>
|
||||
<string name="restore">Obnoviť</string>
|
||||
<string name="versions">Verzie</string>
|
||||
<string name="version_restore">Obnoviť túto verziu</string>
|
||||
<string name="version_restore_confirm">Urobiť z tejto verzie aktuálnu? Súčasná zostane v zozname.</string>
|
||||
<string name="version_current">Aktuálna</string>
|
||||
<string name="files_type">Typ</string>
|
||||
<string name="files_size">Veľkosť</string>
|
||||
<string name="files_no_viewer">Pre tento druh súboru nie je prehliadač.</string>
|
||||
<string name="files_not_shown">Tento súbor sa tu nepodarilo zobraziť. Stále sa dá stiahnuť.</string>
|
||||
<string name="files_svg_source">Toto je zdroj obrázka. Ak chcete vidieť obrázok, otvorte ho v inej aplikácii.</string>
|
||||
<string name="archive_note">Obsah tohto druhu archívu sa tu nedá vypísať.</string>
|
||||
<string name="archive_entries">Položiek: %1$s. Nič sa tu nerozbaľuje.</string>
|
||||
<string name="archive_cut">Vypísaných je len prvých %1$s položiek.</string>
|
||||
<string name="archive_unreadable">Tento archív sa nepodarilo prečítať.</string>
|
||||
<string name="files_waiting">Čaká sa, kým bude aplikácia otvorená a telefón odomknutý.</string>
|
||||
<string name="share_refused">Niečo zo zdieľaného sa odtiaľto nedá odoslať a bolo vynechané.</string>
|
||||
<string name="media_in_trash">Tento súbor je v koši.</string>
|
||||
<string name="table_cut">Do tabuľky sú rozložené len prvé riadky a stĺpce. Text obsahuje všetko.</string>
|
||||
<string name="table_as_text">Zobraziť ako text</string>
|
||||
<string name="table_as_table">Zobraziť ako tabuľku</string>
|
||||
<string name="media_open_in_files">Otvoriť v Súboroch</string>
|
||||
<string name="media_image">Obrázok</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Hudba</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Zvuk</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archív</string>
|
||||
<string name="media_text">Textový súbor</string>
|
||||
<string name="media_binary">Súbor</string>
|
||||
<string name="diff_deleted">Zmazané</string>
|
||||
<string name="diff_counts">Pridané riadky: %1$s, odobraté: %2$s</string>
|
||||
<string name="diff_show_all">Zobraziť všetky riadky (%1$s)</string>
|
||||
<string name="diff_show_less">Zobraziť menej</string>
|
||||
<string name="diff_more">Ďalšie riadky, ktoré sa tu nezobrazujú: %1$s.</string>
|
||||
<string name="diff_endings">Konce riadkov sa menia z %1$s na %2$s.</string>
|
||||
<string name="diff_cut">Táto zmena je príliš dlhá na to, aby sa tu porovnala. Zobrazený je len jej začiatok.</string>
|
||||
<string name="media_gone">Tento súbor už neexistuje.</string>
|
||||
<string name="job_queued">Vo fronte</string>
|
||||
<string name="job_running">Beží</string>
|
||||
<string name="job_done">Hotovo</string>
|
||||
<string name="job_failed">Zlyhalo</string>
|
||||
<string name="job_cancelled">Zrušené</string>
|
||||
<string name="job_expired">Vypršalo</string>
|
||||
<string name="mcp_title">Servery MCP</string>
|
||||
<string name="mcp_intro">Servery, ktorých nástroje môžu byť ponúknuté vo vašich konverzáciách. Niektoré sa používajú s vaším vlastným účtom u nich: ich nástroje sú ponúkané, kým ste prihlásení.</string>
|
||||
<string name="mcp_none">Na tejto inštancii vám nie sú ponúkané žiadne servery MCP.</string>
|
||||
<string name="mcp_ready">Pripravené</string>
|
||||
<string name="mcp_signed_in">Prihlásené</string>
|
||||
<string name="mcp_signed_out">Neprihlásené</string>
|
||||
<string name="mcp_needs_signin">Je potrebné nové prihlásenie</string>
|
||||
<string name="mcp_tools">Nástroje: %1$s</string>
|
||||
<string name="mcp_account">Prihlásené ako %1$s</string>
|
||||
<string name="mcp_until">Prihlásené do %1$s</string>
|
||||
<string name="mcp_shared_note">Tento server má jedno spoločné prihlásenie, ktoré robí správca.</string>
|
||||
<string name="mcp_browser_note">Prihlásenie prebieha v prehliadači, priamo na inštancii. Ak prehliadač nie je do inštancie prihlásený, najprv si to vyžiada. Potom sa vráťte sem.</string>
|
||||
<string name="mcp_sign_in">Prihlásiť sa</string>
|
||||
<string name="notebook_empty">Tento zápisník nemá žiadne bunky.</string>
|
||||
<string name="notebook_more">Ďalších %1$s buniek sa nezobrazuje.</string>
|
||||
<string name="notebook_cell_cut">Táto bunka je dlhšia, než sa tu zobrazuje.</string>
|
||||
<string name="viewer_page">Strana %1$s z %2$s</string>
|
||||
<string name="play">Prehrať</string>
|
||||
<string name="pause">Pozastaviť</string>
|
||||
<string name="files_conflict">Súbor sa od otvorenia zmenil. Načítajte ho znova alebo ho napriek tomu uložte.</string>
|
||||
<string name="files_save_anyway">Napriek tomu uložiť</string>
|
||||
<string name="reload">Znova načítať</string>
|
||||
<string name="discard">Zahodiť</string>
|
||||
<string name="files_unsaved">Zahodiť zmeny v tomto súbore?</string>
|
||||
<string name="share_to_files">Uložiť do Súborov</string>
|
||||
<string name="settings">Nastavenia</string>
|
||||
<string name="settings_instances">Inštancie</string>
|
||||
<string name="sign_out">Odhlásiť sa</string>
|
||||
<string name="add_instance">Pridať inštanciu</string>
|
||||
<string name="instance_default">Predvolené</string>
|
||||
<string name="instance_set_default">Nastaviť ako predvolenú</string>
|
||||
<string name="instance_switch">Prepnúť inštanciu</string>
|
||||
<string name="settings_theme">Vzhľad</string>
|
||||
<string name="theme_system">Podľa systému</string>
|
||||
<string name="theme_moria">Moria (tmavá)</string>
|
||||
<string name="theme_shire">Shire (svetlá)</string>
|
||||
<string name="settings_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">Rovnaký ako v mojom účte</string>
|
||||
<string name="language_account_is">Rovnaký ako v mojom účte: %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>
|
||||
@@ -372,6 +501,9 @@
|
||||
<string name="settings_assistant">Asistent</string>
|
||||
<string name="assistant_explained">Nastavte LLeMbas ako digitálneho asistenta telefónu: zvoľte ho v Predvolené aplikácie › Digitálny asistent. Podržanie tlačidla napájania, gesto asistenta alebo skratka na uzamknutej obrazovke ho potom otvorí nad tým, čo je práve na obrazovke.</string>
|
||||
<string name="assistant_open_settings">Otvoriť nastavenia asistenta</string>
|
||||
<string name="assistant_model">Model asistenta</string>
|
||||
<string name="assistant_model_default">Predvolený model inštancie</string>
|
||||
<string name="assistant_model_default_line">Model, s ktorým sa začínajú vaše nové konverzácie. Ak je na hovorenú otázku príliš pomalý, vyberte nižšie rýchlejší.</string>
|
||||
<string name="assistant_samsung">Na telefónoch Samsung: Nastavenia › Rozšírené funkcie › Tlačidlo na boku › Stlačenie a podržanie › Digitálny asistent.</string>
|
||||
<string name="assistant_temporary">Konverzácie s asistentom sú dočasné</string>
|
||||
<string name="assistant_read_aloud">Prečítať odpoveď nahlas, keď sa spýtate hlasom</string>
|
||||
@@ -380,14 +512,14 @@
|
||||
<string name="update_check">Skontrolovať aktualizáciu</string>
|
||||
<string name="update_none">Toto je najnovšia verzia.</string>
|
||||
<string name="update_unreachable">Aktualizáciu sa nepodarilo stiahnuť.</string>
|
||||
<string name="update_allow_installs">Povoľte aplikácii LLeMbas instalovať aktualizácie a potom to skontrolujte znova.</string>
|
||||
<string name="update_allow_installs">Povoľte aplikácii LLeMbas inštalovať 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_auto_line">Najviac raz denne, pri spustení, sa aplikácia opýta vašej inštancie, ktoré vydanie k nej patrí — alebo si prečíta zoznam vydaní na GitHube, keď to inštancia povedať nevie — a upozornením vám dá vedieť, keď je dostupné novšie. So žiadnou z týchto požiadaviek sa o vás nič 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>
|
||||
@@ -421,13 +553,20 @@
|
||||
<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_unlock_to_send">Odomknúť a odoslať</string>
|
||||
<string name="assist_question_heard">Otázka zaznamenaná</string>
|
||||
<string name="assist_recording_waits_line">Telefón je zamknutý. Vaša otázka čaká v tomto telefóne ako nahrávka; nič sa neodoslalo. Po odomknutí sa odošle vašej inštancii, ktorá ju prepíše a odpovie.</string>
|
||||
<string name="assist_locked_line">Telefón je zamknutý. Kým ho neodomknete, nič sa neodošle a žiadna odpoveď sa nezobrazí.</string>
|
||||
<string name="assist_conversation">Rozhovor</string>
|
||||
<string name="assist_conversation_line">Po každej odpovedi znova počúvam. Povedzte „stop“ a skončíme.</string>
|
||||
<string name="assist_conversation_end">Ukončiť</string>
|
||||
<string name="assist_stop_words">stop|dosť|to je všetko|koniec|dovidenia|ďakujem to je všetko|zrušiť|prestaň</string>
|
||||
<string name="assistant_conversation">Pokračovať v hovorenom rozhovore</string>
|
||||
<string name="assistant_conversation_line">Po prečítaní hovorenej odpovede asistent znova počúva — kým nepoviete „stop“, neťuknete na Ukončiť alebo pár sekúnd nič nepoviete. Funguje aj so slúchadlami.</string>
|
||||
<string name="assist_wake_word_hint">Budiace slovo len ak chcete: Nastavenia › Asistent › Budiace slovo zapne vlastné slovo LLeMbas, priamo v tomto telefóne.</string>
|
||||
<string name="experimental">Experimentálne</string>
|
||||
<string name="wake_experimental_line">Novinka, zatiaľ vyskúšaná len na niekoľkých telefónoch. Môže frázu prepočuť, spustiť sa omylom, alebo vás začuť a asistenta aj tak neotvoriť.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimentálne: samočinné počúvanie po otvorení asistenta, rozpoznanie, že ste dohovorili, a hovorený rozhovor sú nové a zatiaľ nefungujú dobre na každom telefóne. Napísať otázku a tlačidlo mikrofónu fungujú vždy.</string>
|
||||
<string name="assist_wake_word_hint">Budiace slovo len ak chcete: Nastavenia › Budiace slovo zapne vlastné slovo LLeMbas, priamo v tomto telefóne.</string>
|
||||
<string name="channel_wake">Budiace slovo</string>
|
||||
<string name="wake_word">Budiace slovo</string>
|
||||
<string name="wake_word_listen">Počúvať budiace slovo</string>
|
||||
@@ -454,8 +593,8 @@
|
||||
<string name="wake_screen_only_line">Vypnuté: počúva aj pri zhasnutej obrazovke, za cenu vyššej spotreby batérie.</string>
|
||||
<string name="wake_battery">Nechať bežať na pozadí</string>
|
||||
<string name="wake_battery_line">Niektoré telefóny (Samsung, Xiaomi, Huawei, OnePlus a ďalšie) kvôli batérii zastavujú aplikácie na pozadí, a s nimi aj budiace slovo. Tu vyjmite LLeMbas z optimalizácie batérie; dontkillmyapp.com vysvetľuje nastavenia vášho telefónu.</string>
|
||||
<string name="wake_word_privacy">Pred vyslovením slova nič neopustí telefón. Zvuk z mikrofónu ide len do modulu pre budiace slovo v telefóne a neukladá sa; počas celého počúvania je viditeľné oznámenie. Frázy sú anglické; modul je sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na oznámenie.</string>
|
||||
<string name="wake_word_privacy">Pred vyslovením slova nič neopustí telefón. Zvuk z mikrofónu ide len do modulu pre budiace slovo v telefóne a neukladá sa; počas celého počúvania je viditeľné upozornenie. Frázy sú anglické; modul je sherpa-onnx (open source).</string>
|
||||
<string name="wake_word_cost">Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na upozornenie.</string>
|
||||
<string name="wake_listening_for">Počúvam frázu „%1$s“</string>
|
||||
<string name="wake_off">Budiace slovo nepočúva</string>
|
||||
<string name="wake_tap_to_start">Ťuknutím ho znova spustíte. Ak sa Android opýta, povoľte mikrofón.</string>
|
||||
@@ -476,7 +615,7 @@
|
||||
<string name="channel_wake_heard">Budiace slovo zaznelo</string>
|
||||
<string name="wake_heard_line">LLeMbas sa dokáže sám otvoriť nad inými aplikáciami len ako aplikácia digitálneho asistenta v telefóne.</string>
|
||||
<string name="wake_not_assistant">LLeMbas nie je aplikáciou digitálneho asistenta</string>
|
||||
<string name="wake_not_assistant_line">Budiace slovo preto nemôže otvoriť asistenta nad inými aplikáciami: dostanete oznámenie, na ktoré ťuknete. Ak chcete otvárať hlasom kdekoľvek, ťuknite sem a vyberte LLeMbas ako aplikáciu digitálneho asistenta.</string>
|
||||
<string name="wake_not_assistant_line">Budiace slovo preto nemôže otvoriť asistenta nad inými aplikáciami: dostanete upozornenie, na ktoré ťuknete. Ak chcete otvárať hlasom kdekoľvek, ťuknite sem a vyberte LLeMbas ako aplikáciu digitálneho asistenta.</string>
|
||||
<string name="wake_last">Posledné zobudenie</string>
|
||||
<string name="wake_last_none">Frázu zatiaľ nepočul.</string>
|
||||
<string name="wake_out_opened">Otvoril asistenta.</string>
|
||||
@@ -484,7 +623,7 @@
|
||||
<string name="wake_out_not_connected">Android nemal LLeMbas pripojený ako asistenta, preto panel nemohol otvoriť.</string>
|
||||
<string name="wake_out_refused">Android odmietol otvoriť asistenta: %1$s</string>
|
||||
<string name="wake_out_activity">Namiesto toho ho otvoril ako obrazovku aplikácie.</string>
|
||||
<string name="wake_out_notification">Namiesto toho poslal oznámenie, na ktoré treba ťuknúť.</string>
|
||||
<string name="wake_out_notification">Namiesto toho poslal upozornenie, na ktoré treba ťuknúť.</string>
|
||||
<string name="wake_out_tested">Počuté pri skúške: nebolo čo otvárať.</string>
|
||||
<string name="wake_role_held">LLeMbas bol aplikáciou digitálneho asistenta.</string>
|
||||
<string name="wake_role_not_held">LLeMbas nebol aplikáciou digitálneho asistenta.</string>
|
||||
@@ -498,24 +637,24 @@
|
||||
<string name="wake_waited">Chvíľu čakal, kým ho Android pripojí.</string>
|
||||
<string name="wake_show_failed">Android oznámil, že panel asistenta nedokázal zobraziť.</string>
|
||||
<string name="wake_assistant_inactive">Android práve nepoužíva LLeMbas ako hlasového asistenta</string>
|
||||
<string name="wake_assistant_inactive_line">Vyberte LLeMbas ako aplikáciu digitálneho asistenta znova: ťuknite sem, zvoľte inú aplikáciu a potom LLeMbas. Dovtedy ho dlhé stlačenie otvára ako bežnú obrazovku a budiace slovo môže poslať len oznámenie.</string>
|
||||
<string name="wake_assistant_inactive_line">Vyberte LLeMbas ako aplikáciu digitálneho asistenta znova: ťuknite sem, zvoľte inú aplikáciu a potom LLeMbas. Dovtedy ho dlhé stlačenie otvára ako bežnú obrazovku a budiace slovo môže poslať len upozornenie.</string>
|
||||
<string name="wake_assistant_unbound">LLeMbas je asistent, no Android ho práve nemá pripojeného</string>
|
||||
<string name="wake_assistant_unbound_line">Kým ho nepripojí, budiace slovo nemôže panel otvoriť samo. Ťuknutím otvoríte systémové nastavenie asistenta: vyberte inú aplikáciu a potom znova LLeMbas, tým sa pripojí.</string>
|
||||
<string name="wake_heard_could_not">Nepodarilo sa otvoriť samo — ťuknite a pýtajte sa</string>
|
||||
<string name="wake_resume">Znova počúvať budiace slovo</string>
|
||||
<string name="wake_resume_line">Telefón sa reštartoval. Ťuknutím znova spustíte počúvanie.</string>
|
||||
<string name="assist_notifications">Zhrnúť moje oznámenia</string>
|
||||
<string name="assist_notifications_prompt">Zhrň moje oznámenia: čo potrebuje moju pozornosť?</string>
|
||||
<string name="assist_notifications_phrases">moje oznámenia|mojich oznámení|moje notifikácie</string>
|
||||
<string name="notification_summaries">Zhrnutia oznámení</string>
|
||||
<string name="notification_summaries_switch">Dovoliť asistentovi čítať moje oznámenia, keď o to požiadam</string>
|
||||
<string name="notification_summaries_line">Povedzte „zhrň moje oznámenia“, alebo ťuknite na tlačidlo v asistentovi.</string>
|
||||
<string name="notification_summaries_unavailable">V tomto zostavení nie je. Čítanie oznámení vyžaduje zostavenie LLeMbas „notifications“, pretože Google Play Protect blokuje inštaláciu aplikácie mimo Obchodu Play, ktorá ich dokáže čítať. Je to tá istá aplikácia s tým istým podpisom: na stránke vydania sa súbor končiaci na -notifications.apk nainštaluje cez túto.</string>
|
||||
<string name="assist_notifications">Zhrnúť moje upozornenia</string>
|
||||
<string name="assist_notifications_prompt">Zhrň moje upozornenia: čo potrebuje moju pozornosť?</string>
|
||||
<string name="assist_notifications_phrases">moje upozornenia|mojich upozornení|moje oznámenia|mojich oznámení|moje notifikácie</string>
|
||||
<string name="notification_summaries">Zhrnutia upozornení</string>
|
||||
<string name="notification_summaries_switch">Dovoliť asistentovi čítať moje upozornenia, keď o to požiadam</string>
|
||||
<string name="notification_summaries_line">Povedzte „zhrň moje upozornenia“, alebo ťuknite na tlačidlo v asistentovi.</string>
|
||||
<string name="notification_summaries_unavailable">V tomto zostavení nie je. Čítanie upozornení vyžaduje zostavenie LLeMbas „notifications“, pretože Google Play Protect blokuje inštaláciu aplikácie mimo Obchodu Play, ktorá ich dokáže čítať. Je to tá istá aplikácia s tým istým podpisom: na stránke vydania sa súbor končiaci na -notifications.apk nainštaluje cez túto.</string>
|
||||
<string name="update_notifications_manual">Toto je zostavenie „notifications“: aktualizáciu nainštalujte zo stránky vydania, súbor končiaci na -notifications.apk.</string>
|
||||
<string name="notification_access">Prístup k oznámeniam</string>
|
||||
<string name="notification_access">Prístup k upozorneniam</string>
|
||||
<string name="notification_access_on">Udelený. Prepínač Androidu je v systémových nastaveniach.</string>
|
||||
<string name="notification_access_off">Zatiaľ neudelený. Ťuknutím otvoríte prepínač Androidu pre LLeMbas.</string>
|
||||
<string name="notification_summaries_privacy">Predvolene vypnuté. Keď požiadate, text oznámení, ktoré sú v telefóne práve teraz (aplikácia, názov, text), pôjde s touto jedinou otázkou na vašu inštanciu a jej model. Predtým sa nič nečíta, aplikácia si nič neponechá a pri zamknutom telefóne sa nečíta nič. Prístup k oznámeniam v Androide dovolí aplikácii vidieť každé oznámenie, preto je na vás, či ho dáte a znova vezmete.</string>
|
||||
<string name="notification_summaries_privacy">Predvolene vypnuté. Keď požiadate, text upozornení, ktoré sú v telefóne práve teraz (aplikácia, názov, text), pôjde s touto jedinou otázkou na vašu inštanciu a jej model. Predtým sa nič nečíta, aplikácia si nič neponechá a pri zamknutom telefóne sa nečíta nič. Prístup k upozorneniam v Androide dovolí aplikácii vidieť každé upozornenie, preto je na vás, či ho dáte a znova vezmete.</string>
|
||||
<string name="nav_app">Navigačná aplikácia</string>
|
||||
<string name="nav_app_auto">Tá, ktorá je nainštalovaná</string>
|
||||
<string name="nav_app_google">Mapy Google</string>
|
||||
@@ -546,16 +685,53 @@
|
||||
<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_lembas_line">Prevod reči na text vašej inštancie. Tento telefón posiela nahrávku len vašej inštancii; tá ju prepíše modelom reči, ktorý je v nej nastavený.</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>
|
||||
<string name="share_default_prompt">Pozri sa na toto.</string>
|
||||
<string name="share_ask_hint">Čo s tým má LLeMbas urobiť? (nepovinné)</string>
|
||||
<string name="widget_hint">Opýtajte sa na čokoľvek</string>
|
||||
<string name="widget_hint">Spýtajte sa na čokoľvek</string>
|
||||
<string name="directory_places">Miesta na tomto zariadení</string>
|
||||
<string name="directory_last_used">Naposledy tu použitý: %1$s. Nový chat v tomto priečinku začne na ňom, ak nevyberiete iný.</string>
|
||||
<string name="directory_refused">Zariadenie tu reláciu neotvorí.</string>
|
||||
<string name="directory_up">O úroveň vyššie</string>
|
||||
<string name="directory_all_places">Všetky miesta</string>
|
||||
<string name="directory_not_trusted">Na zariadení nie je dôveryhodné</string>
|
||||
<string name="directory_empty">Nie sú tu žiadne priečinky.</string>
|
||||
<string name="directory_no_places">Toto zariadenie neponúka žiadne priečinky: jeho vzdialené korene sú prázdne alebo chýbajú.</string>
|
||||
<string name="directory_browse">Prehľadávať</string>
|
||||
<string name="directory_path">Úplná cesta</string>
|
||||
<string name="directory_choose">Vybrať</string>
|
||||
<string name="directory_no_listing">Adresáre tohto zariadenia sa teraz nedajú vypísať. Napíšte cestu nižšie.</string>
|
||||
<string name="model">Model</string>
|
||||
<string name="schedule_type">Typ</string>
|
||||
<string name="schedule_chat">Konverzácia</string>
|
||||
<string name="schedule_chat_line">Beží na tomto serveri ako chat: s nástrojmi servera (vyhľadávanie, vaše súbory tu, pamäť) a na modeli určenom na plánovanie.</string>
|
||||
<string name="schedule_agentic">Agentický</string>
|
||||
<string name="schedule_agentic_line">Beží na jednom z vašich počítačov, v jednom priečinku na ňom, ako agent: s nástrojmi agenta na tom počítači — jeho súbormi a jeho shellom — v rámci vlastných obmedzení počítača. Patrí k tomu počítaču a priečinku.</string>
|
||||
<string name="schedule_agentic_unavailable">Žiadny z vašich počítačov teraz neprijíma naplánovanú prácu. Prepojte niektorý a zapnite „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">neprijíma plánovanú prácu</string>
|
||||
<string name="schedule_computer_hint">Počítač to musí povoliť: „Accept scheduled work“ v jeho LLeMbas CLI (lembas service scheduled on). Keď v čase spustenia nie je prepojený, spustenie naň počká; ak sa nevráti, kým čas spustenia neuplynie, spustenie sa zaznamená ako zmeškané a dozviete sa o tom.</string>
|
||||
<string name="schedule_computer_gone">počítač, ktorý už nie je prihlásený</string>
|
||||
<string name="schedule_folder">Priečinok na počítači</string>
|
||||
<string name="schedule_agent_mode">Režim</string>
|
||||
<string name="schedule_agent_mode_hint">Edit, ak nevyberiete inak; Auto spúšťa príkazy bez pýtania. Počítač ho môže znížiť.</string>
|
||||
<string name="schedule_approval_wait">Schválenie čaká (minúty)</string>
|
||||
<string name="schedule_approval_wait_hint">Príkaz, ktorý spustenie potrebuje schváliť, príde do telefónu ako karta. Ak do tej doby nebude zodpovedaný, počíta sa ako zamietnutý.</string>
|
||||
<string name="schedule_watch_command_hint">Voliteľné, na počítači. Spustí sa v priečinku pred každým spustením; keď je jeho výstup rovnaký ako minule, spustenie sa tam skončí. Príkaz, na ktorý by sa režim pýtal, sa odmietne.</string>
|
||||
<string name="schedule_watch_timeout">Príkaz môže trvať (sekundy)</string>
|
||||
<string name="schedule_watch_timeout_hint">Potom sa zastaví a spustenie zlyhá.</string>
|
||||
<string name="schedule_chat_drops_watch">Táto úloha sleduje príkaz na svojom počítači. Ako úloha typu Konverzácia už nie: spustí sa zakaždým.</string>
|
||||
<string name="schedule_folder_model">Zvyčajný model priečinka</string>
|
||||
<string name="schedule_folder_model_hint">Zvyčajný model priečinka je ten, ktorý ste v tom priečinku na tom počítači použili naposledy — počítač si ho pamätá a každé spustenie sa ho naň opýta — alebo váš predvolený model, ak žiadny nie je. Model vybraný tu je modelom spustenia, nech je model priečinka akýkoľvek. Spustenie nikdy nemení model priečinka.</string>
|
||||
<string name="schedule_first_free_model">Prvý voľný z vašich modelov na plánovanie</string>
|
||||
<string name="run_model_directory">zvyčajný model priečinka</string>
|
||||
<string name="run_model_default">váš predvolený model</string>
|
||||
<string name="run_model_session">vlastný model konverzácie</string>
|
||||
<string name="widget_speak">Hovoriť</string>
|
||||
<string name="widget_description">Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu.</string>
|
||||
<string name="shortcut_last">Posledný chat</string>
|
||||
<string name="shortcut_last">Posledná konverzácia</string>
|
||||
</resources>
|
||||
@@ -5,7 +5,7 @@
|
||||
<string name="device_name">LLeMbas for Android</string>
|
||||
<string name="share_label">Ask LLeMbas</string>
|
||||
<string name="tile_ask">Ask LLeMbas</string>
|
||||
<string name="signin_intro">Sign in to a LLeMbas instance. You approve this phone in the browser, as you would the CLI.</string>
|
||||
<string name="signin_intro">Sign in to a LLeMbas instance. You approve this phone in the browser.</string>
|
||||
<string name="signin_address">Instance address</string>
|
||||
<string name="signin_continue">Continue</string>
|
||||
<string name="signin_code_intro">Open the instance in the browser, sign in, and approve this code:</string>
|
||||
@@ -13,14 +13,27 @@
|
||||
<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 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="signin_too_new">This instance is newer than this app can work with. Update the app.</string>
|
||||
<string name="signin_not_lembas">There is no LLeMbas instance at that address.</string>
|
||||
<string name="signin_failed">The sign-in could not be completed (%1$s). Try again.</string>
|
||||
<string name="signin_app_too_old">This instance needs LLeMbas for Android %1$s or newer, and this is %2$s. Update the app.</string>
|
||||
<string name="signin_other_origin">This instance names another address for signing in (%1$s) than the one you typed. Its proxy has to pass on the address it is reached by.</string>
|
||||
<string name="address_needs_https">This app needs an https:// address: plain http is not supported.</string>
|
||||
<string name="address_unreadable">That is not an address this app can use. Type the instance\'s address, like llm.example.org.</string>
|
||||
<string name="server_answered">The server answered %1$s.</string>
|
||||
<string name="timed_out">The instance did not answer in time.</string>
|
||||
<string name="not_trusted">This phone does not trust the instance\'s certificate: install its CA certificate among Android\'s user certificates (Settings, Security, Encryption & credentials, Install a certificate).</string>
|
||||
<string name="signed_out">%1$s signed this phone out. Sign in again to go on: your chats and what you set up here are kept.</string>
|
||||
<string name="signed_out_again">Sign in again</string>
|
||||
<string name="signed_out_use">Use %1$s</string>
|
||||
<string name="signed_out_remove">Remove this instance</string>
|
||||
<string name="new_chat">New chat</string>
|
||||
<string name="empty_chats">No chats yet. Not all those who wander are lost — start one.</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="agent_device">Computer</string>
|
||||
<string name="agent_no_device">No computer is linked right now. Start the LLeMbas CLI\'s service (lembas service) on a computer signed in to this instance, then come back.</string>
|
||||
<string name="agent_directory">Folder on the computer</string>
|
||||
<string name="agent_directory_hint">Empty: the computer\'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>
|
||||
@@ -52,6 +65,11 @@
|
||||
<string name="continue_reply">Continue</string>
|
||||
<string name="older">Earlier messages</string>
|
||||
<string name="queued">Waiting to be sent</string>
|
||||
<string name="fate_unknown">It is not known whether this reached the computer. Send it again, or discard it.</string>
|
||||
<string name="fate_carried">The computer has this message and takes it in with its next turn.</string>
|
||||
<string name="send_now">Send now</string>
|
||||
<string name="discard_message_confirm">Discard this message?</string>
|
||||
<string name="reply_unrecorded">The reply to this was not recorded.</string>
|
||||
<string name="thinking">Thinking</string>
|
||||
<string name="thought">Thought</string>
|
||||
<string name="output_cut">Output shortened here. The whole of it is on the web page.</string>
|
||||
@@ -72,6 +90,8 @@
|
||||
<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="transcribed_by_fallback">Transcribed by %1$s: this chat\'s own speech model did not answer.</string>
|
||||
<string name="read_by_fallback">Read by %1$s: this chat\'s own speech model did not answer.</string>
|
||||
<string name="remove">Remove</string>
|
||||
<string name="more">More</string>
|
||||
<string name="back">Back</string>
|
||||
@@ -342,16 +362,125 @@
|
||||
<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_unavailable">This instance 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="files_upload">Upload</string>
|
||||
<string name="files_new_file">New file</string>
|
||||
<string name="files_new_file_ask">What should the file be called? With its extension, such as notes.md.</string>
|
||||
<string name="files_new_folder_ask">What should the folder be called?</string>
|
||||
<string name="files_bad_name">A name cannot be empty or hold a slash.</string>
|
||||
<string name="files_taken">There is already something called %1$s here.</string>
|
||||
<string name="rename">Rename</string>
|
||||
<string name="files_new_name">New name</string>
|
||||
<string name="files_move">Move</string>
|
||||
<string name="files_copy_to">Copy to…</string>
|
||||
<string name="files_move_here">Move here</string>
|
||||
<string name="files_copy_here">Copy here</string>
|
||||
<string name="files_move_which">Move to which folder?</string>
|
||||
<string name="files_copy_which">Copy to which folder?</string>
|
||||
<string name="files_choose_folder">Choose a folder</string>
|
||||
<string name="files_save_here">Save here</string>
|
||||
<string name="files_no_folders">No directories here.</string>
|
||||
<string name="files_to_trash">Move to the trash</string>
|
||||
<string name="files_trash_one">Move “%1$s” to the trash? It can be restored from there.</string>
|
||||
<string name="files_trash_many">Move the %1$s selected to the trash? They can be restored from there.</string>
|
||||
<string name="files_trashed">Moved to the trash.</string>
|
||||
<string name="files_selected">%1$s selected</string>
|
||||
<string name="files_select_all">Select all</string>
|
||||
<string name="download">Download</string>
|
||||
<string name="files_download_zip">Download as a zip</string>
|
||||
<string name="files_downloading">Downloading…</string>
|
||||
<string name="files_downloaded">Downloaded.</string>
|
||||
<string name="files_uploading">Uploading %1$s of %2$s…</string>
|
||||
<string name="files_uploaded">Uploaded.</string>
|
||||
<string name="files_open_with">Open with…</string>
|
||||
<string name="files_no_app">No app on this phone opens this kind of file.</string>
|
||||
<string name="trash">Trash</string>
|
||||
<string name="trash_is_empty">The trash is empty.</string>
|
||||
<string name="trash_empty">Empty the trash</string>
|
||||
<string name="trash_empty_confirm">Remove everything in the trash for good? This cannot be undone.</string>
|
||||
<string name="trash_remove">Remove for good</string>
|
||||
<string name="trash_remove_confirm">Remove “%1$s” for good? This cannot be undone.</string>
|
||||
<string name="restore">Restore</string>
|
||||
<string name="versions">Versions</string>
|
||||
<string name="version_restore">Restore this version</string>
|
||||
<string name="version_restore_confirm">Make this version the current one? The current one stays in the list.</string>
|
||||
<string name="version_current">Current</string>
|
||||
<string name="files_type">Type</string>
|
||||
<string name="files_size">Size</string>
|
||||
<string name="files_no_viewer">There is no viewer for this kind of file.</string>
|
||||
<string name="files_not_shown">This file could not be shown here. It can still be downloaded.</string>
|
||||
<string name="files_svg_source">This is the picture\'s source. Open it with another app to see the picture.</string>
|
||||
<string name="archive_note">What is inside this kind of archive cannot be listed here.</string>
|
||||
<string name="archive_entries">%1$s entries. Nothing is unpacked here.</string>
|
||||
<string name="archive_cut">Only the first %1$s entries are listed.</string>
|
||||
<string name="archive_unreadable">This archive could not be read.</string>
|
||||
<string name="files_waiting">Waiting until the app is open and the phone is unlocked.</string>
|
||||
<string name="share_refused">Something that was shared cannot be sent from here and was left out.</string>
|
||||
<string name="media_in_trash">That file is in the trash.</string>
|
||||
<string name="table_cut">Only the first rows and columns are laid out. The text has all of it.</string>
|
||||
<string name="table_as_text">Show as text</string>
|
||||
<string name="table_as_table">Show as a table</string>
|
||||
<string name="media_open_in_files">Open in Files</string>
|
||||
<string name="media_image">Image</string>
|
||||
<string name="media_video">Video</string>
|
||||
<string name="media_music">Music</string>
|
||||
<string name="media_model">3D model</string>
|
||||
<string name="media_audio">Audio</string>
|
||||
<string name="media_pdf">PDF</string>
|
||||
<string name="media_archive">Archive</string>
|
||||
<string name="media_text">Text file</string>
|
||||
<string name="media_binary">File</string>
|
||||
<string name="diff_deleted">Deleted</string>
|
||||
<string name="diff_counts">Lines added: %1$s, removed: %2$s</string>
|
||||
<string name="diff_show_all">Show all %1$s lines</string>
|
||||
<string name="diff_show_less">Show less</string>
|
||||
<string name="diff_more">%1$s more lines are not shown here.</string>
|
||||
<string name="diff_endings">The line endings change from %1$s to %2$s.</string>
|
||||
<string name="diff_cut">This change is too long to compare here. Only its beginning is shown.</string>
|
||||
<string name="media_gone">That file no longer exists.</string>
|
||||
<string name="job_queued">Queued</string>
|
||||
<string name="job_running">Running</string>
|
||||
<string name="job_done">Done</string>
|
||||
<string name="job_failed">Failed</string>
|
||||
<string name="job_cancelled">Cancelled</string>
|
||||
<string name="job_expired">Expired</string>
|
||||
<string name="mcp_title">MCP servers</string>
|
||||
<string name="mcp_intro">The servers whose tools your chats may be offered. Some are used with an account of your own there: their tools are offered while you are signed in.</string>
|
||||
<string name="mcp_none">No MCP servers are offered to you on this instance.</string>
|
||||
<string name="mcp_ready">Ready</string>
|
||||
<string name="mcp_signed_in">Signed in</string>
|
||||
<string name="mcp_signed_out">Not signed in</string>
|
||||
<string name="mcp_needs_signin">Needs a new sign-in</string>
|
||||
<string name="mcp_tools">Tools: %1$s</string>
|
||||
<string name="mcp_account">Signed in as %1$s</string>
|
||||
<string name="mcp_until">Signed in until %1$s</string>
|
||||
<string name="mcp_shared_note">This server has one shared sign-in, which an administrator makes.</string>
|
||||
<string name="mcp_browser_note">Signing in happens in the browser, on the instance itself. If the browser is not signed in to the instance, it asks for that first. Come back here afterwards.</string>
|
||||
<string name="mcp_sign_in">Sign in</string>
|
||||
<string name="notebook_empty">This notebook has no cells.</string>
|
||||
<string name="notebook_more">%1$s more cells are not shown.</string>
|
||||
<string name="notebook_cell_cut">This cell is longer than is shown here.</string>
|
||||
<string name="viewer_page">Page %1$s of %2$s</string>
|
||||
<string name="play">Play</string>
|
||||
<string name="pause">Pause</string>
|
||||
<string name="files_conflict">This file changed since you opened it. Reload it, or save anyway.</string>
|
||||
<string name="files_save_anyway">Save anyway</string>
|
||||
<string name="reload">Reload</string>
|
||||
<string name="discard">Discard</string>
|
||||
<string name="files_unsaved">Discard your changes to this file?</string>
|
||||
<string name="share_to_files">Save to Files</string>
|
||||
<string name="settings">Settings</string>
|
||||
<string name="settings_instances">Instances</string>
|
||||
<string name="sign_out">Sign out</string>
|
||||
<string name="add_instance">Add an instance</string>
|
||||
<string name="instance_default">Default</string>
|
||||
<string name="instance_set_default">Set as default</string>
|
||||
<string name="instance_switch">Switch instance</string>
|
||||
<string name="settings_theme">Theme</string>
|
||||
<string name="theme_system">As the system</string>
|
||||
<string name="theme_moria">Moria (dark)</string>
|
||||
@@ -374,6 +503,9 @@
|
||||
<string name="settings_assistant">Assistant</string>
|
||||
<string name="assistant_explained">Make LLeMbas the phone\'s digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen\'s shortcut opens it over whatever is on screen.</string>
|
||||
<string name="assistant_open_settings">Open the assistant settings</string>
|
||||
<string name="assistant_model">Assistant model</string>
|
||||
<string name="assistant_model_default">Instance default</string>
|
||||
<string name="assistant_model_default_line">The model your new chats start on. Choose a quick one below if it is too slow for a spoken question.</string>
|
||||
<string name="assistant_samsung">On Samsung phones: Settings › Advanced features › Side button › Press and hold › Digital assistant.</string>
|
||||
<string name="assistant_temporary">Assistant chats are temporary</string>
|
||||
<string name="assistant_read_aloud">Read the answer aloud when asked by voice</string>
|
||||
@@ -389,7 +521,7 @@
|
||||
<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_auto_line">At most once a day, when the app starts, it asks your instance which release goes with it — or reads the list of releases on GitHub when the instance cannot say — and tells you in a notification when there is a newer one. Nothing about you is sent with either request. 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>
|
||||
@@ -423,13 +555,20 @@
|
||||
<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_unlock_to_send">Unlock to send</string>
|
||||
<string name="assist_question_heard">Question heard</string>
|
||||
<string name="assist_recording_waits_line">The phone is locked. Your question waits on this phone as a recording; nothing has been sent. Unlocking sends it to your instance to be written down and answered.</string>
|
||||
<string name="assist_locked_line">The phone is locked. Nothing is sent, and no answer is shown, until you unlock it.</string>
|
||||
<string name="assist_conversation">In conversation</string>
|
||||
<string name="assist_conversation_line">I listen again after each answer. Say “stop” to end.</string>
|
||||
<string name="assist_conversation_end">End</string>
|
||||
<string name="assist_stop_words">stop|that\'s all|that is all|that\'s it|goodbye|bye|enough|end|thank you that\'s all|cancel</string>
|
||||
<string name="assistant_conversation">Keep a spoken conversation going</string>
|
||||
<string name="assistant_conversation_line">After a spoken answer is read aloud, the assistant listens again — until you say “stop”, tap End, or say nothing for a few seconds. Works with a headset.</string>
|
||||
<string name="assist_wake_word_hint">No wake word unless you want one: Settings › Assistant › Wake word turns on LLeMbas\'s own, on this phone.</string>
|
||||
<string name="experimental">Experimental</string>
|
||||
<string name="wake_experimental_line">New, and tried on few phones so far. It may miss the phrase, start by mistake, or hear you and still not open the assistant.</string>
|
||||
<string name="assistant_voice_experimental_line">Experimental: listening by itself when the assistant opens, noticing when you have finished speaking, and the spoken conversation are new and do not work well on every phone yet. Typing a question and the microphone button always work.</string>
|
||||
<string name="assist_wake_word_hint">No wake word unless you want one: Settings › Wake word turns on LLeMbas\'s own, on this phone.</string>
|
||||
<string name="channel_wake">Wake word</string>
|
||||
<string name="wake_word">Wake word</string>
|
||||
<string name="wake_word_listen">Listen for a wake word</string>
|
||||
@@ -548,7 +687,7 @@
|
||||
<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_lembas_line">Your instance\'s speech-to-text. This phone sends the recording to your instance only; the instance writes it down with the speech model set up there.</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>
|
||||
@@ -557,6 +696,43 @@
|
||||
<string name="share_default_prompt">Have a look at this.</string>
|
||||
<string name="share_ask_hint">What should LLeMbas do with it? (optional)</string>
|
||||
<string name="widget_hint">Ask anything</string>
|
||||
<string name="directory_places">Places on this device</string>
|
||||
<string name="directory_last_used">Last used here: %1$s. A new chat in this directory starts on it unless you choose another.</string>
|
||||
<string name="directory_refused">The device will not open a session here.</string>
|
||||
<string name="directory_up">Up a level</string>
|
||||
<string name="directory_all_places">All places</string>
|
||||
<string name="directory_not_trusted">Not trusted on the device</string>
|
||||
<string name="directory_empty">No directories here.</string>
|
||||
<string name="directory_no_places">This device offers no directories: its remote roots are empty or missing.</string>
|
||||
<string name="directory_browse">Browse</string>
|
||||
<string name="directory_path">A full path</string>
|
||||
<string name="directory_choose">Choose</string>
|
||||
<string name="directory_no_listing">This device\'s directories cannot be listed right now. Type the path below.</string>
|
||||
<string name="model">Model</string>
|
||||
<string name="schedule_type">Type</string>
|
||||
<string name="schedule_chat">Chat</string>
|
||||
<string name="schedule_chat_line">Runs on this server, like a chat: with the server\'s tools (search, your files here, memory) and on a scheduling model.</string>
|
||||
<string name="schedule_agentic">Agentic</string>
|
||||
<string name="schedule_agentic_line">Runs on one of your computers, in one folder there, as an agent: with the agent\'s tools on that computer — its files and its shell — under the computer\'s own limits. It belongs to that computer and folder.</string>
|
||||
<string name="schedule_agentic_unavailable">None of your computers accepts scheduled work now. Link one and switch on “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on).</string>
|
||||
<string name="schedule_computer_refuses">does not accept scheduled work</string>
|
||||
<string name="schedule_computer_hint">The computer must allow it: “Accept scheduled work” in its LLeMbas CLI (lembas service scheduled on). When it is not linked at the time of a run, the run waits for it; if it has not come back before the run\'s time has passed, the run is recorded as missed and you are told.</string>
|
||||
<string name="schedule_computer_gone">a computer no longer signed in</string>
|
||||
<string name="schedule_folder">Folder on the computer</string>
|
||||
<string name="schedule_agent_mode">Mode</string>
|
||||
<string name="schedule_agent_mode_hint">Edit unless you choose otherwise; Auto runs commands without asking. The computer may lower it.</string>
|
||||
<string name="schedule_approval_wait">An approval waits (minutes)</string>
|
||||
<string name="schedule_approval_wait_hint">A command the run needs approved comes to your phone as a card. Unanswered by then, it counts as denied.</string>
|
||||
<string name="schedule_watch_command_hint">Optional, on the computer. Run in the folder before each run; when its output is the same as last time, the run stops there. A command the mode would ask about is refused.</string>
|
||||
<string name="schedule_watch_timeout">The command may take (seconds)</string>
|
||||
<string name="schedule_watch_timeout_hint">Stopped after this; the run then fails.</string>
|
||||
<string name="schedule_chat_drops_watch">This task watches a command on its computer. As a Chat task it no longer does: it runs every time.</string>
|
||||
<string name="schedule_folder_model">The folder\'s usual model</string>
|
||||
<string name="schedule_folder_model_hint">The folder\'s usual model is the one you last used in that folder on that computer — the computer remembers it, and each run asks it — or your default model where there is none. A model chosen here is the run\'s, whatever the folder\'s is. A run never changes the folder\'s model.</string>
|
||||
<string name="schedule_first_free_model">The first free one of your scheduling models</string>
|
||||
<string name="run_model_directory">the folder\'s usual model</string>
|
||||
<string name="run_model_default">your default model</string>
|
||||
<string name="run_model_session">the conversation\'s own model</string>
|
||||
<string name="widget_speak">Speak</string>
|
||||
<string name="widget_description">Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account.</string>
|
||||
<string name="shortcut_last">Last chat</string>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12 (shire). Do not edit. -->
|
||||
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.19 (shire). Do not edit. -->
|
||||
<resources>
|
||||
<color name="token_bg">#FFF1EAD6</color>
|
||||
<color name="token_surface">#FFF8F3E5</color>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<?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. -->
|
||||
<!-- The two folders of the private cache another app may be handed one file of, and nothing
|
||||
else: `camera/`, the one file a photo for the composer is taken into (the camera app may
|
||||
write it); `shared/`, the copy of one of the account's files that Open with or Share hands
|
||||
over, read-only, for that one grant (ui/files/Transfers.kt deletes them). -->
|
||||
<paths>
|
||||
<cache-path name="camera" path="camera/" />
|
||||
<cache-path name="shared" path="shared/" />
|
||||
</paths>
|
||||
@@ -1,13 +1,23 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.LiveReply
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.Step
|
||||
import eu.llembas.android.api.Tail
|
||||
import eu.llembas.android.assist.AssistActivity
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.assist.AssistHandOff
|
||||
import eu.llembas.android.assist.AssistTurn
|
||||
import eu.llembas.android.assist.AssistUiState
|
||||
import eu.llembas.android.assist.Held
|
||||
import eu.llembas.android.assist.LockedStart
|
||||
import eu.llembas.android.assist.Opening
|
||||
import eu.llembas.android.assist.Recognise
|
||||
import eu.llembas.android.assist.Recorder
|
||||
import eu.llembas.android.assist.SheetStop
|
||||
import eu.llembas.android.assist.isStopPhrase
|
||||
import eu.llembas.android.assist.lockedStart
|
||||
import eu.llembas.android.assist.recogniseWith
|
||||
import eu.llembas.android.assist.settle
|
||||
import eu.llembas.android.assist.usePhoneRecognizer
|
||||
import eu.llembas.android.auth.Prefs
|
||||
@@ -53,6 +63,85 @@ class AssistTest {
|
||||
assertEquals("Because.", earlier.steps.single().markdown)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAssistantsModelIsTheOneChosenInSettings() {
|
||||
val models = listOf(ModelInfo("large"), ModelInfo("standard", default = true), ModelInfo("quick"))
|
||||
// The choice, whatever the account's and the instance's defaults are.
|
||||
assertEquals("quick", AssistController.assistantModelFor("quick", "large", models))
|
||||
// "Instance default": the account's default, as a new chat in the app starts.
|
||||
assertEquals("large", AssistController.assistantModelFor("", "large", models))
|
||||
// No account default (or one that is gone): the instance's, then its first.
|
||||
assertEquals("standard", AssistController.assistantModelFor("", null, models))
|
||||
assertEquals("standard", AssistController.assistantModelFor("", "retired", models))
|
||||
assertEquals("large", AssistController.assistantModelFor("", null, models.map { it.copy(default = false) }))
|
||||
// A chosen model the instance no longer has falls back the same way, and none is none.
|
||||
assertEquals("large", AssistController.assistantModelFor("retired", "large", models))
|
||||
assertEquals(null, AssistController.assistantModelFor("quick", null, emptyList()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun overTheLockScreenAWayInThatMeansToSpeakStaysAndListens() {
|
||||
// The wake word with the screen off: nobody is there to unlock. It listens; sending waits.
|
||||
assertEquals(LockedStart.Listen, lockedStart(locked = true, Opening.Listen, question = false, micAllowed = true))
|
||||
// A question handed over (heard by the assistant's own sheet, or typed there) is held, not dropped.
|
||||
assertEquals(LockedStart.Hold, lockedStart(locked = true, Opening.Sheet, question = true, micAllowed = true))
|
||||
assertEquals(LockedStart.Hold, lockedStart(locked = true, Opening.Listen, question = true, micAllowed = false))
|
||||
// Anything else over the lock screen asks to unlock first, as before: the plain sheet,
|
||||
// the last chat (which is the account's), and the microphone's permission prompt.
|
||||
assertEquals(LockedStart.Unlock, lockedStart(locked = true, Opening.Sheet, question = false, micAllowed = true))
|
||||
assertEquals(LockedStart.Unlock, lockedStart(locked = true, Opening.Continue, question = false, micAllowed = true))
|
||||
assertEquals(LockedStart.Unlock, lockedStart(locked = true, Opening.Listen, question = false, micAllowed = false))
|
||||
// Unlocked, the way in decides alone.
|
||||
for (opening in Opening.entries) {
|
||||
assertEquals(LockedStart.Go, lockedStart(locked = false, opening, question = false, micAllowed = true))
|
||||
assertEquals(LockedStart.Go, lockedStart(locked = false, opening, question = true, micAllowed = false))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyTheAppsOwnIntentsAskForMoreThanTheSheet() {
|
||||
val voiceButton = "android.intent.action.VOICE_COMMAND"
|
||||
val handsFree = "android.speech.action.VOICE_SEARCH_HANDS_FREE"
|
||||
// The app's own: the widget's microphone, the last chat, the session's "listen".
|
||||
assertEquals(Opening.Listen, Opening.of(AssistActivity.ACTION_LISTEN, listenExtra = false, own = true))
|
||||
assertEquals(Opening.Continue, Opening.of(AssistActivity.ACTION_CONTINUE, listenExtra = false, own = true))
|
||||
assertEquals(Opening.Listen, Opening.of(null, listenExtra = true, own = true))
|
||||
// The same from any other app: just the sheet.
|
||||
assertEquals(Opening.Sheet, Opening.of(AssistActivity.ACTION_LISTEN, listenExtra = true, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of(AssistActivity.ACTION_CONTINUE, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of("android.intent.action.ASSIST", listenExtra = true, own = false))
|
||||
// Android's own actions for a headset's button are anybody's, and listen.
|
||||
assertEquals(Opening.Listen, Opening.of(voiceButton, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Listen, Opening.of(handsFree, listenExtra = false, own = false))
|
||||
assertEquals(Opening.Sheet, Opening.of("android.intent.action.ASSIST", listenExtra = false, own = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aHandedOverQuestionIsTakenOnceAndOnlyWithItsTicket() {
|
||||
val question = Held("How far is it to the next town?", null, spoken = true)
|
||||
val ticket = AssistHandOff.leave(question)
|
||||
// No ticket, a made-up one, one of another length: nothing.
|
||||
assertEquals(null, AssistHandOff.take(null))
|
||||
assertEquals(null, AssistHandOff.take("0".repeat(ticket.length)))
|
||||
assertEquals(null, AssistHandOff.take(ticket.dropLast(1)))
|
||||
// The ticket: the question, once.
|
||||
assertTrue(AssistHandOff.take(ticket) === question)
|
||||
assertEquals(null, AssistHandOff.take(ticket))
|
||||
// A newer question takes the older one's place, and the older ticket is worth nothing.
|
||||
val older = AssistHandOff.leave(question)
|
||||
val newer = AssistHandOff.leave(Held("", ByteArray(4), spoken = true))
|
||||
assertTrue(older != newer)
|
||||
assertEquals(null, AssistHandOff.take(older))
|
||||
assertTrue(AssistHandOff.take(newer)?.wav != null)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aQuestionWaitsAsWordsOrAsARecording() {
|
||||
assertFalse(AssistUiState().held)
|
||||
assertTrue(AssistUiState(waiting = "Why?").held)
|
||||
assertTrue(AssistUiState(waitingRecording = true).held)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aVoiceReadsOnlyTheWords() {
|
||||
val steps = listOf(
|
||||
@@ -126,4 +215,14 @@ class AssistTest {
|
||||
assertTrue(NotificationReader.asksAbout("Anything urgent in My Notifications?", phrases))
|
||||
assertFalse(NotificationReader.asksAbout("How do notifications work on Android?", phrases))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSystemRecogniserSendsNothingToTheInstanceFromALockedPhone() {
|
||||
// Unlocked: the instance writes it down, whatever else the phone has.
|
||||
assertEquals(Recognise.Instance, recogniseWith(locked = false, onDevice = false))
|
||||
assertEquals(Recognise.Instance, recogniseWith(locked = false, onDevice = true))
|
||||
// Locked: the phone's own recogniser, or nobody -- never the instance.
|
||||
assertEquals(Recognise.OnDevice, recogniseWith(locked = true, onDevice = true))
|
||||
assertEquals(Recognise.Refuse, recogniseWith(locked = true, onDevice = false))
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,25 @@ 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.ChatDetail
|
||||
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.MessagePage
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Step
|
||||
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.closedUnfinished
|
||||
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 eu.llembas.android.ui.chat.withOlder
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
@@ -30,7 +37,8 @@ class ChatStateTest {
|
||||
|
||||
@Test
|
||||
fun theModelIsTheChatsThenTheDraftsThenTheDefault() {
|
||||
assertEquals("qwen", ChatState(models = models).modelId)
|
||||
// A model is named by its ref; a chat and an older choice still name it by its id.
|
||||
assertEquals("local/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)
|
||||
}
|
||||
@@ -84,4 +92,60 @@ class ChatStateTest {
|
||||
assertEquals("8K", compactContext(8192))
|
||||
assertEquals("1M", compactContext(1_000_000))
|
||||
}
|
||||
|
||||
private fun said(id: String, role: String = "user") = Message(id = id, role = role)
|
||||
|
||||
@Test
|
||||
fun anOlderPageIsPutAboveOnceHoweverOftenItArrives() {
|
||||
val shown = ChatState(messages = listOf(said("m3"), said("m4")), more = true)
|
||||
val page = MessagePage(messages = listOf(said("m1"), said("m2")), more = false)
|
||||
val once = shown.withOlder("m3", page)
|
||||
assertEquals(listOf("m1", "m2", "m3", "m4"), once.messages.map { it.id })
|
||||
assertFalse(once.more)
|
||||
// The same page a second time (two taps, two answers): m3 is no longer the first row.
|
||||
assertEquals(once, once.withOlder("m3", page))
|
||||
// A page that overlaps what is shown, or names a row twice, adds each row once.
|
||||
val overlapping = MessagePage(messages = listOf(said("m2"), said("m2"), said("m3")), more = true)
|
||||
assertEquals(listOf("m2", "m3", "m4"), shown.withOlder("m3", overlapping).messages.map { it.id })
|
||||
// The transcript was read again meanwhile: the page belongs above another first row.
|
||||
val moved = ChatState(messages = listOf(said("m7"), said("m8")), more = true)
|
||||
assertEquals(moved, moved.withOlder("m3", page))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStreamThatClosesWithoutDoneLeavesWhatWasWritten() {
|
||||
val chat = Chat(id = "c")
|
||||
val live = LiveReply("m2")
|
||||
.apply("steps", """{"steps":[{"index":0,"kind":"thinking","text":"Flour first."}],"tail":{"thinking":"","text":"Mix the","label":""}}""")
|
||||
.apply("status", """{"text":"Stopped","progress":{"phase":"stopped","reason":"person"}}""")
|
||||
val writing = ChatState(chat = chat, messages = listOf(said("m1"), said("m2", "assistant")), live = live)
|
||||
|
||||
// Read again: the transcript is the server's, with the reply as it stored it.
|
||||
val stored = said("m2", "assistant").copy(stopped = true, steps = listOf(Step(index = 0, kind = "text", markdown = "Mix the")))
|
||||
val reread = writing.closedUnfinished("m2", ChatDetail(chat = chat.copy(title = "Waybread"), messages = listOf(said("m1"), stored), more = true))
|
||||
assertNull(reread.live)
|
||||
assertEquals(stored, reread.messages.last())
|
||||
assertEquals("Waybread", reread.chat?.title)
|
||||
assertTrue(reread.more)
|
||||
|
||||
// It could not be read: the steps the stream had shown stay on the row, closed, with
|
||||
// the end the stream said.
|
||||
val kept = writing.closedUnfinished("m2", null)
|
||||
assertNull(kept.live)
|
||||
assertEquals(listOf("thinking", "text"), kept.messages.last().steps.map { it.kind })
|
||||
assertEquals("Mix the", kept.messages.last().steps.last().markdown)
|
||||
assertTrue(kept.messages.last().steps.none { it.open })
|
||||
assertEquals("stopped", kept.messages.last().progress?.phase)
|
||||
assertEquals(said("m1"), kept.messages.first())
|
||||
|
||||
// Nothing had been written: nothing is invented, and nothing is live.
|
||||
val empty = writing.copy(live = LiveReply("m2")).closedUnfinished("m2", null)
|
||||
assertNull(empty.live)
|
||||
assertEquals(writing.messages, empty.messages)
|
||||
|
||||
// Another reply is followed by now: this stream's end is not its business.
|
||||
val next = writing.copy(live = LiveReply("m9"))
|
||||
assertEquals(next, next.closedUnfinished("m2", null))
|
||||
assertEquals(next, next.closedUnfinished("m2", ChatDetail(chat = chat)))
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ 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
|
||||
@@ -33,12 +32,6 @@ class ClientTest {
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
@Test
|
||||
fun anAddressBecomesABase() {
|
||||
assertEquals("https://llm.example.org", normaliseBase(" llm.example.org/ "))
|
||||
assertEquals("http://10.1.2.3:8080", normaliseBase("http://10.1.2.3:8080"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAgentChatNamesItsDeviceAndFolder() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody("""{"chat":{"id":"c1","kind":"agent"}}"""))
|
||||
@@ -131,4 +124,38 @@ class ClientTest {
|
||||
assertEquals("hi", api.fileContent("/home/frodo/a b.md").text)
|
||||
assertEquals("/api/v2/files/content?path=%2Fhome%2Ffrodo%2Fa%20b.md", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyRequestThatStartsAReplySaysWhatTheAppCanDo() = runTest {
|
||||
val api = client()
|
||||
val declared = "\"client\":[\"phone_actions\"]"
|
||||
val answer = """{"chat":{"id":"c1"}}"""
|
||||
repeat(7) { server.enqueue(MockResponse().setResponseCode(201).setBody(answer)) }
|
||||
api.createChat("Hello")
|
||||
api.sendMessage("c1", "And then?")
|
||||
api.edit("c1", "m1", "Hello again")
|
||||
api.regenerate("c1", "m2")
|
||||
api.continueChat("c1")
|
||||
api.executePlan("c1")
|
||||
api.sendWaiting("c1", "m3")
|
||||
val paths = listOf(
|
||||
"/api/v2/chats",
|
||||
"/api/v2/chats/c1/messages",
|
||||
"/api/v2/chats/c1/messages/m1/edit",
|
||||
"/api/v2/chats/c1/messages/m2/regenerate",
|
||||
"/api/v2/chats/c1/continue",
|
||||
"/api/v2/chats/c1/plan/execute",
|
||||
"/api/v2/chats/c1/messages/m3/send",
|
||||
)
|
||||
for (path in paths) {
|
||||
val request = server.takeRequest()
|
||||
assertEquals(path, request.path)
|
||||
val body = request.body.readUtf8()
|
||||
assertTrue("$path: $body", body.contains(declared))
|
||||
}
|
||||
// An edit still carries its words.
|
||||
server.enqueue(MockResponse().setBody("{}"))
|
||||
api.edit("c1", "m1", "Hello again")
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains("\"text\":\"Hello again\""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Address
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Discovery
|
||||
import eu.llembas.android.api.Doorstep
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.NotLembas
|
||||
import eu.llembas.android.api.Outcome
|
||||
import eu.llembas.android.api.Reconnect
|
||||
import eu.llembas.android.api.RefusedTokens
|
||||
import eu.llembas.android.api.ServerFit
|
||||
import eu.llembas.android.api.StreamClient
|
||||
import eu.llembas.android.api.USER_AGENT
|
||||
import eu.llembas.android.api.address
|
||||
import eu.llembas.android.api.fit
|
||||
import eu.llembas.android.api.minClient
|
||||
import eu.llembas.android.api.olderThan
|
||||
import eu.llembas.android.api.onOrigin
|
||||
import eu.llembas.android.api.refusedToken
|
||||
import eu.llembas.android.api.reopened
|
||||
import eu.llembas.android.api.retryAfterSeconds
|
||||
import eu.llembas.android.api.sameBase
|
||||
import eu.llembas.android.api.userAgent
|
||||
import eu.llembas.android.api.versionNumbers
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.InstanceLogic
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import eu.llembas.android.ui.Trouble
|
||||
import eu.llembas.android.ui.signin.newerAppNeeded
|
||||
import eu.llembas.android.ui.signin.pollEnd
|
||||
import eu.llembas.android.ui.signin.refusal
|
||||
import eu.llembas.android.ui.trouble
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.toList
|
||||
import kotlinx.coroutines.test.currentTime
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
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.assertNotEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.IOException
|
||||
import java.io.InterruptedIOException
|
||||
import java.net.ConnectException
|
||||
import java.net.SocketTimeoutException
|
||||
import java.net.UnknownHostException
|
||||
import java.net.UnknownServiceException
|
||||
import java.security.cert.CertPathValidatorException
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import javax.net.ssl.SSLHandshakeException
|
||||
import javax.net.ssl.SSLPeerUnverifiedException
|
||||
|
||||
/**
|
||||
* How this app connects to an instance, by the rules every LLeMbas client keeps: one way to read
|
||||
* an address, one name on every request, one meaning of a refused token, one reconnect schedule,
|
||||
* and a sentence of its own for each thing that can go wrong.
|
||||
*/
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
class ConnectionTest {
|
||||
private lateinit var server: MockWebServer
|
||||
private var heardBefore: ((String) -> Unit)? = null
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
heardBefore = RefusedTokens.heard
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() {
|
||||
RefusedTokens.heard = heardBefore
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
private fun base() = server.url("/").toString().trimEnd('/')
|
||||
|
||||
private fun client(token: String = "lmb_test") = ApiClient(base(), token)
|
||||
|
||||
// --- The address ---------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun anAddressIsReadByTheOneRule() {
|
||||
val cases = listOf(
|
||||
" Example.org " to Address.Base("https://example.org"),
|
||||
"HTTPS://Example.org/" to Address.Base("https://example.org"),
|
||||
"https://example.org/chat?x=1#y" to Address.Base("https://example.org"),
|
||||
"example.org:8443/" to Address.Base("https://example.org:8443"),
|
||||
"https://example.org:443" to Address.Base("https://example.org"),
|
||||
"http://example.org" to Address.NeedsHttps,
|
||||
"ftp://example.org" to Address.NotHttp,
|
||||
"" to Address.Empty,
|
||||
// The same rule, a little further: only blanks, an http address in capitals, no host, a port that is none.
|
||||
" " to Address.Empty,
|
||||
"HTTP://Example.org:8080/x" to Address.NeedsHttps,
|
||||
"https://" to Address.Unreadable,
|
||||
"example.org:port" to Address.Unreadable,
|
||||
"llm.example.org/some/page/" to Address.Base("https://llm.example.org"),
|
||||
)
|
||||
for ((typed, expected) in cases) assertEquals("\"$typed\"", expected, address(typed))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAddressThatCannotBeUsedIsSaidAtTheAddressStep() {
|
||||
assertEquals(R.string.address_needs_https, refusal(Address.NeedsHttps))
|
||||
assertEquals(R.string.address_unreadable, refusal(Address.NotHttp))
|
||||
assertEquals(R.string.address_unreadable, refusal(Address.Unreadable))
|
||||
assertNull(refusal(Address.Empty))
|
||||
assertNull(refusal(Address.Base("https://example.org")))
|
||||
}
|
||||
|
||||
// --- Which address is kept, and which instance a sign-in is ---------------------------------
|
||||
|
||||
private val listed = ListSerializer(Instance.serializer())
|
||||
|
||||
/** What a version of the app before this one stored: the instance's own word for its address, and an id made of it. */
|
||||
private val stored = """[
|
||||
{"id":"alice@https://home.example","base":"https://home.example","name":"Home","email":"alice","sealedToken":"t1"},
|
||||
{"id":"bob@https://Work.example:8443","base":"https://Work.example:8443","name":"Work","email":"bob","sealedToken":"t2"}
|
||||
]"""
|
||||
|
||||
@Test
|
||||
fun anInstanceFromBeforeIsUntouchedByTheUpgrade() {
|
||||
val read = LembasJson.decodeFromString(listed, stored)
|
||||
// Nothing is made again on reading: the id, the base and the token are what was stored, to the letter.
|
||||
assertEquals(listOf("alice@https://home.example", "bob@https://Work.example:8443"), read.map { it.id })
|
||||
assertEquals(listOf("https://home.example", "https://Work.example:8443"), read.map { it.base })
|
||||
assertEquals(listOf("t1", "t2"), read.map { it.sealedToken })
|
||||
assertTrue(read.none { it.signedOut })
|
||||
// Which one is in use and which is the default are found by those same ids.
|
||||
assertEquals(read[1], InstanceLogic.pickActive(read, "bob@https://Work.example:8443", "alice@https://home.example"))
|
||||
assertEquals(read[0], InstanceLogic.pickDefault(read, "alice@https://home.example"))
|
||||
// And what is kept per instance is still found under them.
|
||||
val prefs = Prefs().withInstance(read[1].id) { it.copy(assistantModel = "fast-work") }
|
||||
assertEquals("fast-work", prefs.forInstance(LembasJson.decodeFromString(listed, stored)[1].id).assistantModel)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSignInToAnInstanceAlreadyHereRefreshesItAndAddsNoTwin() {
|
||||
val before = LembasJson.decodeFromString(listed, stored)
|
||||
// Typed by another name than the one stored; the instance still says the old one of itself.
|
||||
val again = InstanceLogic.signedIn(
|
||||
before,
|
||||
typed = "https://home.example.net",
|
||||
said = "https://home.example/",
|
||||
name = "Home",
|
||||
email = "Alice",
|
||||
sealedToken = "t9",
|
||||
)
|
||||
assertEquals("alice@https://home.example", again.id)
|
||||
assertEquals("https://home.example.net", again.base)
|
||||
assertEquals("t9", again.sealedToken)
|
||||
assertEquals("alice", again.email)
|
||||
val (list, active, default) = InstanceLogic.afterAdd(before, again, "bob@https://Work.example:8443")
|
||||
assertEquals(2, list.size)
|
||||
assertEquals(setOf("alice@https://home.example", "bob@https://Work.example:8443"), list.map { it.id }.toSet())
|
||||
assertEquals("alice@https://home.example", active)
|
||||
assertEquals("bob@https://Work.example:8443", default)
|
||||
// Another account at the same address is another instance, as it always was.
|
||||
val carol = InstanceLogic.signedIn(
|
||||
before,
|
||||
typed = "https://home.example",
|
||||
said = "https://home.example",
|
||||
name = "Home",
|
||||
email = "carol",
|
||||
sealedToken = "t3",
|
||||
)
|
||||
assertEquals("carol@https://home.example", carol.id)
|
||||
assertEquals(3, InstanceLogic.afterAdd(before, carol, null).first.size)
|
||||
// And the same account somewhere else is a new one too: its id is made of the typed address.
|
||||
val elsewhere = InstanceLogic.signedIn(before, typed = "https://other.example", said = "", name = "Other", email = "alice", sealedToken = "t4")
|
||||
assertEquals("alice@https://other.example", elsewhere.id)
|
||||
assertEquals("https://other.example", elsewhere.base)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSignedOutInstanceSignedInToAgainIsItselfAgain() {
|
||||
val before = LembasJson.decodeFromString(listed, stored).map { it.copy(signedOut = true) }
|
||||
val again = InstanceLogic.signedIn(before, typed = "https://home.example", said = "", name = "Home", email = "alice", sealedToken = "t9")
|
||||
assertEquals("alice@https://home.example", again.id)
|
||||
assertFalse(again.signedOut)
|
||||
assertTrue(InstanceLogic.afterAdd(before, again, null).first.single { it.id == "bob@https://Work.example:8443" }.signedOut)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAddressTypedInItsVariantsIsOneInstance() {
|
||||
val before = LembasJson.decodeFromString(listed, stored)
|
||||
val variants = listOf("work.example:8443", "HTTPS://WORK.example:8443/", "https://work.example:8443/chat?x=1#y", " https://Work.Example:8443 ")
|
||||
for (typed in variants) {
|
||||
val base = (address(typed) as Address.Base).url
|
||||
assertEquals(typed, "https://work.example:8443", base)
|
||||
val again = InstanceLogic.signedIn(before, typed = base, said = "", name = "Work", email = "bob", sealedToken = "t9")
|
||||
// The entry stored with a capital in its base is found, and keeps its id as it was stored.
|
||||
assertEquals(typed, "bob@https://Work.example:8443", again.id)
|
||||
assertEquals(typed, 2, InstanceLogic.afterAdd(before, again, null).first.size)
|
||||
}
|
||||
assertTrue(sameBase("https://example.org", "https://EXAMPLE.org:443/"))
|
||||
assertFalse(sameBase("https://example.org", "https://example.org:8443"))
|
||||
assertFalse(sameBase("https://example.org", "https://www.example.org"))
|
||||
// A base the rule does not read (an older version stored what the instance said) is compared as it stands.
|
||||
assertTrue(sameBase("http://inside.example:8000", "http://Inside.example:8000/"))
|
||||
assertFalse(sameBase("http://inside.example:8000", "https://inside.example:8000"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSignInGoesOnlyToTheAddressThatWasTyped() {
|
||||
assertTrue(onOrigin("https://llm.example.org", "https://llm.example.org/api/device/code"))
|
||||
assertTrue(onOrigin("https://llm.example.org", "https://LLM.example.org:443/api/device/token"))
|
||||
assertFalse(onOrigin("https://llm.example.org", "https://other.example.org/api/device/code"))
|
||||
assertFalse(onOrigin("https://llm.example.org", "http://llm.example.org/api/device/code"))
|
||||
assertFalse(onOrigin("https://llm.example.org", "https://llm.example.org:8443/api/device/code"))
|
||||
assertFalse(onOrigin("https://llm.example.org", ""))
|
||||
}
|
||||
|
||||
// --- An instance that needs a newer app ------------------------------------------------------
|
||||
|
||||
private fun found(json: String) = LembasJson.decodeFromString(Discovery.serializer(), json)
|
||||
|
||||
@Test
|
||||
fun versionsCompareByTheirNumbers() {
|
||||
assertTrue(olderThan("1.0.0-beta.9", "1.0.0-beta.10"))
|
||||
assertFalse(olderThan("1.0.0-beta.10", "1.0.0-beta.9"))
|
||||
assertTrue(olderThan("1.0.0-beta.16", "1.0.0"))
|
||||
assertFalse(olderThan("1.0.0", "1.0.0-beta.99"))
|
||||
assertFalse(olderThan("1.0.0-beta.16", "1.0.0-beta.16"))
|
||||
assertTrue(olderThan("1.9.9", "1.10.0"))
|
||||
assertTrue(olderThan("1.0.0", "2.0.0-beta.1"))
|
||||
assertFalse(olderThan("2.0.0-beta.1", "1.99.99"))
|
||||
// A build's own mark is left off: a test build of beta.16 is beta.16.
|
||||
assertFalse(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.16"))
|
||||
assertTrue(olderThan("1.0.0-beta.16-debug.412", "1.0.0-beta.17"))
|
||||
assertFalse(olderThan("1.0.0-notifications", "1.0.0"))
|
||||
assertEquals(versionNumbers("1.0.0"), versionNumbers("v1.0.0"))
|
||||
// Nonsense locks nobody out.
|
||||
assertFalse(olderThan("1.0.0", "newest"))
|
||||
assertFalse(olderThan("dev", "9.9.9"))
|
||||
assertNull(versionNumbers("1.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstanceMaySayWhichAppIsTooOld() {
|
||||
val says = found("""{"service":"lembas","min_clients":{"android":"1.0.0","desktop":"1.2.0"},"something_new":{"a":[1,2]}}""")
|
||||
assertEquals("1.0.0", says.minClient())
|
||||
assertEquals("1.0.0", newerAppNeeded(says, "1.0.0-beta.16"))
|
||||
assertNull(newerAppNeeded(says, "1.0.0"))
|
||||
assertNull(newerAppNeeded(says, "1.0.1-debug.3"))
|
||||
// Said of other products only, or not at all: nothing is asked of this app.
|
||||
assertNull(found("""{"service":"lembas","min_clients":{"desktop":"9.0.0"}}""").minClient())
|
||||
assertNull(found("""{"service":"lembas"}""").minClient())
|
||||
// A shape this app does not expect is "says nothing" -- the document is still read.
|
||||
assertNull(found("""{"service":"lembas","min_clients":["android"]}""").minClient())
|
||||
assertNull(found("""{"service":"lembas","min_clients":{"android":7}}""").minClient())
|
||||
assertNull(found("""{"service":"lembas","min_clients":{"android":null}}""").minClient())
|
||||
assertNull(found("""{"service":"lembas","min_clients":null}""").minClient())
|
||||
// Another service's rule is not a rule.
|
||||
assertNull(newerAppNeeded(found("""{"service":"other","min_clients":{"android":"9.0.0"}}"""), "1.0.0"))
|
||||
}
|
||||
|
||||
// --- Who asks ------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun theAppNamesItselfWithItsVersion() {
|
||||
assertEquals("llembas-android/1.2.3-beta.4", userAgent("1.2.3-beta.4"))
|
||||
assertEquals(userAgent(BuildConfig.VERSION_NAME), USER_AGENT)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun everyRequestCarriesTheAppsName() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"api":2,"account":{"name":"Frodo","email":"f@shire.test"}}"""))
|
||||
client().me()
|
||||
assertEquals(USER_AGENT, server.takeRequest().getHeader("User-Agent"))
|
||||
// The calls without a token too: finding the instance.
|
||||
server.enqueue(MockResponse().setBody("""{"service":"lembas"}"""))
|
||||
Doorstep().discover(base())
|
||||
assertEquals(USER_AGENT, server.takeRequest().getHeader("User-Agent"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSignInNamesTheSameProgram() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"device_code":"d","user_code":"ABCD-EFGH"}"""))
|
||||
Doorstep().deviceCode(server.url("/api/device/code").toString(), "LLeMbas for Android", "Maker Model")
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertTrue(body, body.contains("\"client_id\":\"$USER_AGENT\""))
|
||||
}
|
||||
|
||||
// --- A refused token -------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun onlyTheInstancesOwnRefusalNamesAToken() {
|
||||
val challenge = "Bearer realm=\"lembas\""
|
||||
assertEquals("lmb_a", refusedToken(401, challenge, "Bearer lmb_a"))
|
||||
// Not allowed is not signed out; nor is "slow down", nor a server in trouble.
|
||||
assertNull(refusedToken(403, challenge, "Bearer lmb_a"))
|
||||
assertNull(refusedToken(429, challenge, "Bearer lmb_a"))
|
||||
assertNull(refusedToken(500, challenge, "Bearer lmb_a"))
|
||||
// A 401 passed on from elsewhere (a provider behind the instance) has no challenge of the instance's.
|
||||
assertNull(refusedToken(401, null, "Bearer lmb_a"))
|
||||
assertNull(refusedToken(401, "Basic realm=\"proxy\"", "Bearer lmb_a"))
|
||||
assertNull(refusedToken(401, "Bearer realm=\"other\"", "Bearer lmb_a"))
|
||||
// A request that carried no token signs nobody out.
|
||||
assertNull(refusedToken(401, challenge, null))
|
||||
assertNull(refusedToken(401, challenge, "Bearer "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedTokenIsHeardWithThatTokenOnAnyRequest() = runTest {
|
||||
val heard = CopyOnWriteArrayList<String>()
|
||||
RefusedTokens.heard = { token -> heard += token }
|
||||
val said = """{"detail":"That token is not valid, has expired or was revoked."}"""
|
||||
server.enqueue(MockResponse().setResponseCode(401).setHeader("WWW-Authenticate", "Bearer realm=\"lembas\"").setBody(said))
|
||||
try {
|
||||
client("lmb_revoked").me()
|
||||
fail("a 401 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(401, e.status)
|
||||
assertEquals("That token is not valid, has expired or was revoked.", e.message)
|
||||
}
|
||||
assertEquals(listOf("lmb_revoked"), heard.toList())
|
||||
// A 403 is the server's sentence and nothing more.
|
||||
server.enqueue(MockResponse().setResponseCode(403).setBody("""{"detail":"This token was not given the app scope."}"""))
|
||||
try {
|
||||
client("lmb_narrow").me()
|
||||
fail("a 403 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals("This token was not given the app scope.", e.message)
|
||||
}
|
||||
// A 401 that is not the instance's own (no challenge) signs nobody out.
|
||||
server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"message":"Incorrect API key provided."}}"""))
|
||||
try {
|
||||
client("lmb_fine").me()
|
||||
fail("a 401 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(401, e.status)
|
||||
}
|
||||
assertEquals(listOf("lmb_revoked"), heard.toList())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusalSignsOutThatInstanceAndTouchesNothingElse() {
|
||||
val home = Instance(id = "alice@https://home.example", base = "https://home.example", name = "Home", email = "alice", sealedToken = "t1")
|
||||
val work = Instance(id = "bob@https://work.example", base = "https://work.example", name = "Work", email = "bob", sealedToken = "t2")
|
||||
val after = InstanceLogic.afterRefusal(listOf(home, work)) { it.sealedToken == "t2" }
|
||||
assertEquals(listOf(home, work.copy(signedOut = true)), after)
|
||||
// A token that is nobody's any more (signed in again meanwhile, or removed) changes nothing.
|
||||
assertNull(InstanceLogic.afterRefusal(listOf(home, work)) { it.sealedToken == "gone" })
|
||||
// Said twice, written once.
|
||||
assertNull(InstanceLogic.afterRefusal(after!!) { it.sealedToken == "t2" })
|
||||
// The signed-out one keeps its place as the one in use and as the default: nothing is promoted over it.
|
||||
assertEquals(work.copy(signedOut = true), InstanceLogic.pickActive(after, work.id, work.id))
|
||||
// Signing in again replaces the entry under the same id, signed in, and the default stays whose it was.
|
||||
val again = work.copy(sealedToken = "t9")
|
||||
val (list, active, default) = InstanceLogic.afterAdd(after, again, home.id)
|
||||
assertEquals(listOf(home, again), list)
|
||||
assertFalse(list.last().signedOut)
|
||||
assertEquals(work.id, active)
|
||||
assertEquals(home.id, default)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anInstanceStoredBeforeTheMarkIsSignedIn() {
|
||||
val stored = """[{"id":"alice@https://home.example","base":"https://home.example","name":"Home","email":"alice","sealedToken":"t1"}]"""
|
||||
val read = LembasJson.decodeFromString(ListSerializer(Instance.serializer()), stored)
|
||||
assertFalse(read.single().signedOut)
|
||||
val marked = LembasJson.encodeToString(ListSerializer(Instance.serializer()), listOf(read.single().copy(signedOut = true)))
|
||||
assertTrue(LembasJson.decodeFromString(ListSerializer(Instance.serializer()), marked).single().signedOut)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theEventsLineIsTheTokensNotOnlyTheInstances() {
|
||||
assertEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("alice@https://home.example", "sealed-a"))
|
||||
assertNotEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("alice@https://home.example", "sealed-b"))
|
||||
assertNotEquals(eventsKey("alice@https://home.example", "sealed-a"), eventsKey("bob@https://home.example", "sealed-a"))
|
||||
}
|
||||
|
||||
// --- Streams ---------------------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun aSilentStreamCountsAsBrokenWithinAMinute() {
|
||||
// The server's keepalive comes every 15 seconds: silence for three of them is a dead connection.
|
||||
assertTrue(StreamClient.SILENCE_SECONDS in 45L..60L)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePauseDoublesFromOneSecondToSixty() {
|
||||
val schedule = Reconnect { 0.5 }
|
||||
val pauses = (1..9).map { schedule.pause(healthyMs = 0) }
|
||||
assertEquals(listOf(1_000L, 2_000L, 4_000L, 8_000L, 16_000L, 32_000L, 60_000L, 60_000L, 60_000L), pauses)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePauseIsJitteredByAFifthEachWay() {
|
||||
assertEquals(800L, Reconnect { 0.0 }.pause(healthyMs = 0))
|
||||
assertEquals(1_200L, Reconnect { 1.0 }.pause(healthyMs = 0))
|
||||
// A source that strays outside 0..1 does not stretch the pause further.
|
||||
assertEquals(800L, Reconnect { -3.0 }.pause(healthyMs = 0))
|
||||
assertEquals(1_200L, Reconnect { 7.0 }.pause(healthyMs = 0))
|
||||
val drawn = Reconnect()
|
||||
repeat(50) {
|
||||
val pause = drawn.pause(healthyMs = Reconnect.HEALTHY_MS)
|
||||
assertTrue("$pause", pause in 800L..1_200L)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePauseIsShortAgainOnlyAfterHalfAMinuteOfHealth() {
|
||||
val schedule = Reconnect { 0.5 }
|
||||
assertEquals(1_000L, schedule.pause(healthyMs = 0))
|
||||
assertEquals(2_000L, schedule.pause(healthyMs = 0))
|
||||
// It opened and said something, and broke again soon: the pause goes on growing.
|
||||
assertEquals(4_000L, schedule.pause(healthyMs = 29_999))
|
||||
assertEquals(1_000L, schedule.pause(healthyMs = 30_000))
|
||||
assertEquals(2_000L, schedule.pause(healthyMs = 5))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRetryAfterIsHonouredWhenItIsTheLongerWait() {
|
||||
assertEquals(10_000L, Reconnect { 0.5 }.pause(healthyMs = 0, retryAfterMs = 10_000))
|
||||
// The schedule's own pause, when that is longer.
|
||||
val grown = Reconnect { 0.5 }
|
||||
repeat(5) { grown.pause(healthyMs = 0) }
|
||||
assertEquals(32_000L, grown.pause(healthyMs = 0, retryAfterMs = 10_000))
|
||||
// An hour asked for is looked at again within five minutes.
|
||||
assertEquals(Reconnect.MOST_ASKED_MS, Reconnect { 0.5 }.pause(healthyMs = 0, retryAfterMs = 3_600_000))
|
||||
assertEquals(30L, retryAfterSeconds("30"))
|
||||
assertEquals(5L, retryAfterSeconds(" 5 "))
|
||||
assertNull(retryAfterSeconds(null))
|
||||
assertNull(retryAfterSeconds("-1"))
|
||||
assertNull(retryAfterSeconds("Wed, 21 Oct 2015 07:28:00 GMT"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStreamThatKeepsBreakingIsOpenedAgainEverMoreSlowly() = runTest {
|
||||
var opened = 0
|
||||
val at = mutableListOf<Long>()
|
||||
val frames = reopened(turn = {}, schedule = Reconnect { 0.5 }, clock = { 0L }) {
|
||||
opened++
|
||||
at += currentTime
|
||||
// One frame and gone, three times: by the clock no connection lasted at all.
|
||||
if (opened <= 3) flow<Outcome> { emit(Outcome.Event(Frame("tail", "{}"))) } else flow<Outcome> { emit(Outcome.Event(Frame("close", "{}"))) }
|
||||
}.toList()
|
||||
assertEquals(listOf("tail", "tail", "tail", "close"), frames.map { it.event })
|
||||
assertEquals(listOf(0L, 1_000L, 3_000L, 7_000L), at)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aStreamThatHeldIsOpenedAgainAfterOneSecond() = runTest {
|
||||
var opened = 0
|
||||
var now = 0L
|
||||
val at = mutableListOf<Long>()
|
||||
reopened(turn = {}, schedule = Reconnect { 0.5 }, clock = { now }) {
|
||||
opened++
|
||||
at += currentTime
|
||||
when (opened) {
|
||||
// Broke at once, twice: 1 second, then 2.
|
||||
1, 2 -> flow<Outcome> { emit(Outcome.Dropped) }
|
||||
|
||||
// Then held for half a minute before it broke: 1 second again, not 4.
|
||||
3 -> flow<Outcome> {
|
||||
emit(Outcome.Event(Frame("tail", "{}")))
|
||||
now += 30_000L
|
||||
emit(Outcome.Dropped)
|
||||
}
|
||||
|
||||
// "Too many requests", come back in 7 seconds: that is the wait.
|
||||
4 -> flow<Outcome> { emit(Outcome.Slowed(7)) }
|
||||
|
||||
else -> flow<Outcome> { emit(Outcome.Event(Frame("close", "{}"))) }
|
||||
}
|
||||
}.toList()
|
||||
assertEquals(listOf(0L, 1_000L, 3_000L, 4_000L, 11_000L), at)
|
||||
}
|
||||
|
||||
// --- What went wrong, in its own words -----------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun eachKindOfTroubleIsToldApart() {
|
||||
assertEquals(Trouble.UNREACHABLE, trouble(UnknownHostException("llm.example.org")))
|
||||
assertEquals(Trouble.UNREACHABLE, trouble(ConnectException("Connection refused")))
|
||||
assertEquals(Trouble.TIMEOUT, trouble(SocketTimeoutException("timeout")))
|
||||
assertEquals(Trouble.TIMEOUT, trouble(InterruptedIOException("timeout")))
|
||||
val untrusted = SSLHandshakeException("java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.")
|
||||
untrusted.initCause(CertPathValidatorException("Trust anchor for certification path not found."))
|
||||
assertEquals(Trouble.NOT_TRUSTED, trouble(untrusted))
|
||||
assertEquals(Trouble.NOT_TRUSTED, trouble(SSLPeerUnverifiedException("Hostname llm.example.org not verified")))
|
||||
// A handshake that failed for another reason is not a matter of trust.
|
||||
assertEquals(Trouble.OTHER, trouble(SSLHandshakeException("Handshake failed")))
|
||||
val cleartext = UnknownServiceException("CLEARTEXT communication to llm.example.org not permitted by network security policy")
|
||||
assertEquals(Trouble.NEEDS_HTTPS, trouble(cleartext))
|
||||
assertEquals(Trouble.NOT_LEMBAS, trouble(NotLembas()))
|
||||
// Whatever the server answered is the server's answer: never "unreachable", never "not LLeMbas".
|
||||
assertEquals(Trouble.ANSWERED, trouble(ApiException(502, "")))
|
||||
assertEquals(Trouble.ANSWERED, trouble(ApiException(403, "This token was not given the app scope.")))
|
||||
assertEquals(Trouble.OTHER, trouble(IOException("unexpected end of stream")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anAddressWithoutTheDocumentIsNotLembasAndAServerInTroubleIsItsNumber() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("Not Found"))
|
||||
try {
|
||||
Doorstep().discover(base())
|
||||
fail("a 404 is not a LLeMbas instance")
|
||||
} catch (e: NotLembas) {
|
||||
// As it should be.
|
||||
}
|
||||
server.enqueue(MockResponse().setResponseCode(502).setBody("<html>Bad Gateway</html>"))
|
||||
try {
|
||||
Doorstep().discover(base())
|
||||
fail("a 502 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(502, e.status)
|
||||
}
|
||||
// A page where the document should be: something else answers there.
|
||||
server.enqueue(MockResponse().setBody("<html>Welcome</html>"))
|
||||
try {
|
||||
Doorstep().discover(base())
|
||||
fail("a page is not a LLeMbas instance")
|
||||
} catch (e: NotLembas) {
|
||||
// As it should be.
|
||||
}
|
||||
// Another service's document is read, and refused by what it says.
|
||||
server.enqueue(MockResponse().setBody("""{"service":"other"}"""))
|
||||
assertEquals(ServerFit.NOT_LEMBAS, fit(Doorstep().discover(base())))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eachReasonAServerDoesNotFitHasItsOwnSentence() {
|
||||
assertNull(refusal(ServerFit.FITS))
|
||||
assertEquals(R.string.signin_not_lembas, refusal(ServerFit.NOT_LEMBAS))
|
||||
// The direction is the sentence's whole point: an old server is not "update the app".
|
||||
assertEquals(R.string.signin_too_old, refusal(ServerFit.TOO_OLD))
|
||||
assertEquals(R.string.signin_too_new, refusal(ServerFit.TOO_NEW))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPollEndsByItsRealReason() {
|
||||
assertNull(pollEnd("authorization_pending"))
|
||||
assertNull(pollEnd("slow_down"))
|
||||
assertEquals(R.string.signin_denied, pollEnd("access_denied"))
|
||||
assertEquals(R.string.signin_expired, pollEnd("expired_token"))
|
||||
// Anything else is not "the code expired".
|
||||
assertEquals(R.string.signin_failed, pollEnd("invalid_grant"))
|
||||
assertEquals(R.string.signin_failed, pollEnd(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPollIsReadByWhatTheServerSaid() = runTest {
|
||||
val url = server.url("/api/device/token").toString()
|
||||
server.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"authorization_pending"}"""))
|
||||
assertEquals("authorization_pending", Doorstep().deviceToken(url, "d").error)
|
||||
server.enqueue(MockResponse().setBody("""{"access_token":"lmb_new","account":{"email":"frodo@example.org"}}"""))
|
||||
assertEquals("lmb_new", Doorstep().deviceToken(url, "d").accessToken)
|
||||
// A proxy's page while the server restarts: the server's number, to be asked again.
|
||||
server.enqueue(MockResponse().setResponseCode(502).setBody("<html>Bad Gateway</html>"))
|
||||
try {
|
||||
Doorstep().deviceToken(url, "d")
|
||||
fail("a 502 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(502, e.status)
|
||||
assertNull(e.retryAfter)
|
||||
}
|
||||
// "Too many requests" carries how long to wait.
|
||||
server.enqueue(MockResponse().setResponseCode(429).setHeader("Retry-After", "7").setBody("""{"detail":"Slow down."}"""))
|
||||
try {
|
||||
Doorstep().deviceToken(url, "d")
|
||||
fail("a 429 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(429, e.status)
|
||||
assertEquals(7L, e.retryAfter)
|
||||
assertEquals("Slow down.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tooManySignInsIsTheServersOwnSentence() = runTest {
|
||||
val said = """{"error":"slow_down","error_description":"Too many device logins from this address."}"""
|
||||
server.enqueue(MockResponse().setResponseCode(429).setBody(said))
|
||||
try {
|
||||
Doorstep().deviceCode(server.url("/api/device/code").toString(), "LLeMbas for Android", "Maker Model")
|
||||
fail("a 429 must throw")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(429, e.status)
|
||||
assertEquals("Too many device logins from this address.", e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ class ContractTest {
|
||||
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 })
|
||||
assertEquals(listOf("recipes", "lembas.md", "map.png"), listing.entries.map { it.name })
|
||||
assertTrue(listing.entries[0].isFolder)
|
||||
val file = listing.entries[1]
|
||||
assertFalse(file.isFolder)
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.DeviceDirectory
|
||||
import eu.llembas.android.api.DeviceList
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.StartModel
|
||||
import eu.llembas.android.api.named
|
||||
import eu.llembas.android.api.titleAmong
|
||||
import eu.llembas.android.assist.AssistController
|
||||
import eu.llembas.android.ui.PICKER_ENTRIES
|
||||
import eu.llembas.android.ui.PICKER_WORDS
|
||||
import eu.llembas.android.ui.PickerState
|
||||
import eu.llembas.android.ui.asking
|
||||
import eu.llembas.android.ui.back
|
||||
import eu.llembas.android.ui.canChoose
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.chat.folderModel
|
||||
import eu.llembas.android.ui.chat.modelId
|
||||
import eu.llembas.android.ui.chat.modelInfo
|
||||
import eu.llembas.android.ui.refusedHere
|
||||
import eu.llembas.android.ui.took
|
||||
import eu.llembas.android.ui.unanswered
|
||||
import eu.llembas.android.ui.up
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.KSerializer
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* A linked device's directories and the folder's usual model (harness spec 3.9.0), from the
|
||||
* server's own fixtures (`contract/device_directories*.json`, `models_agent_directory.json`):
|
||||
* the shapes, the picker's walk, and which model a new agent chat shows.
|
||||
*/
|
||||
class DirectoriesTest {
|
||||
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))
|
||||
|
||||
private val project = read("device_directories", DeviceDirectory.serializer())
|
||||
private val places = read("device_directories_places", DeviceDirectory.serializer())
|
||||
|
||||
@Test
|
||||
fun aDirectoryItsEntriesAndTheModelsLastUsedThere() {
|
||||
assertEquals("/home/user/project", project.path)
|
||||
assertEquals("/home/user", project.parent)
|
||||
assertTrue(project.accepted)
|
||||
assertTrue(project.listed)
|
||||
assertFalse(project.places)
|
||||
assertEquals("Qwen", project.model?.label)
|
||||
val (docs, server, vendor) = project.entries
|
||||
assertNull(docs.model)
|
||||
assertEquals("gpt-oss", server.model?.label)
|
||||
assertFalse(vendor.accepted)
|
||||
assertEquals("This directory is not trusted on the device.", vendor.reason)
|
||||
// Without a path: the device's places, each a directory to walk into.
|
||||
assertTrue(places.places)
|
||||
assertEquals(listOf("/home/user", "/home/user/project"), places.entries.map { it.path })
|
||||
assertEquals("Qwen", places.entries.last().model?.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noListingIsACodeAndASentence() {
|
||||
val away = read("device_directories_not_linked", DeviceDirectory.serializer())
|
||||
assertFalse(away.listed)
|
||||
assertEquals("device_not_linked", away.code)
|
||||
assertEquals("This device is not linked right now.", away.error)
|
||||
val old = read("device_directories_cli_too_old", DeviceDirectory.serializer())
|
||||
assertEquals("cli_too_old", old.code)
|
||||
assertTrue(old.error.isNotBlank())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePickerWalksDownAndUpAndClosesAtTheTop() {
|
||||
val start = PickerState(loading = true).took(places)
|
||||
assertFalse(start.loading)
|
||||
// At the places there is no "up": back closes. And no path yet, so nothing to choose.
|
||||
assertNull(start.up)
|
||||
assertEquals("", start.typed)
|
||||
assertFalse(start.canChoose)
|
||||
val inside = start.took(project)
|
||||
assertEquals("/home/user/project", inside.typed)
|
||||
assertEquals("/home/user", inside.up)
|
||||
assertTrue(inside.canChoose)
|
||||
// A directory with no parent leads back to the places.
|
||||
assertEquals("", inside.took(project.copy(path = "/home/user", parent = "")).up)
|
||||
// Back at the places the field keeps the last path: it is still what would be chosen.
|
||||
assertEquals("/home/user/project", inside.took(places).typed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDirectoryTheDeviceRefusesCannotBeChosenButATypedPathCan() {
|
||||
val refused = PickerState().took(
|
||||
project.copy(path = "/home/user/project/vendor", accepted = false, reason = "This directory is not trusted on the device."),
|
||||
)
|
||||
assertTrue(refused.refusedHere)
|
||||
assertFalse(refused.canChoose)
|
||||
// Another path written over it has not been refused by anybody: the instance checks it.
|
||||
val typed = refused.copy(typed = "/srv/garden")
|
||||
assertFalse(typed.refusedHere)
|
||||
assertTrue(typed.canChoose)
|
||||
assertFalse(typed.copy(typed = " ").canChoose)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeviceThatCannotListKeepsTheTypedPathAndSaysWhy() {
|
||||
val typed = PickerState(typed = "/home/user/garden", loading = true)
|
||||
for (name in listOf("device_directories_not_linked", "device_directories_cli_too_old")) {
|
||||
val answer = read(name, DeviceDirectory.serializer())
|
||||
val after = typed.took(answer, fallback = "It cannot be listed.")
|
||||
assertEquals("/home/user/garden", after.typed)
|
||||
assertEquals(answer.error, after.error)
|
||||
assertFalse(after.loading)
|
||||
assertTrue(after.canChoose)
|
||||
}
|
||||
// The listing shown before stays where it was; a code without a sentence gets the app's own.
|
||||
val walked = PickerState().took(project)
|
||||
val silent = walked.took(DeviceDirectory(code = "no_answer"), fallback = "It cannot be listed.")
|
||||
assertEquals(project, silent.listing)
|
||||
assertEquals("It cannot be listed.", silent.error)
|
||||
// The next listing clears the sentence.
|
||||
assertNull(silent.took(places).error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatWasTypedWhileTheDeviceAnsweredStays() {
|
||||
// Asked, then typed in before the answer came: the answer's path does not write over it.
|
||||
val typing = PickerState(typed = "/home/user").asking().copy(typed = "/srv/garden", edited = true)
|
||||
val answered = typing.took(project)
|
||||
assertEquals("/srv/garden", answered.typed)
|
||||
assertEquals(project.path, answered.listing?.path)
|
||||
// The next question starts afresh: its answer is followed again.
|
||||
assertEquals("/home/user/project", answered.asking().took(project).typed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backClosesWhenTheDeviceWentAwayMidWalk() {
|
||||
val inside = PickerState().took(project)
|
||||
assertEquals("/home/user", inside.back)
|
||||
// The parent could not be listed: "up" would ask it again and again, so Back closes.
|
||||
val away = inside.asking().took(read("device_directories_not_linked", DeviceDirectory.serializer()))
|
||||
assertTrue(away.failed)
|
||||
assertNull(away.back)
|
||||
assertNull(inside.asking().unanswered("Home cannot be reached.").back)
|
||||
// A listing after it: the walk goes on.
|
||||
assertEquals("/home/user", away.asking().took(project).back)
|
||||
assertNull(PickerState().took(places).back)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aListingIsBoundedBeforeItIsDrawn() {
|
||||
val entry = project.entries.first()
|
||||
val long = "x".repeat(5_000)
|
||||
val wild = project.copy(
|
||||
reason = long,
|
||||
entries = listOf(entry, entry, entry.copy(path = "")) + (1..1_000).map { entry.copy(path = "/home/user/project/d$it", name = long, reason = long) },
|
||||
)
|
||||
val shown = PickerState().took(wild).listing!!
|
||||
// Each path once (the rows are keyed by it), none without one, and no more than the cap.
|
||||
assertEquals(PICKER_ENTRIES, shown.entries.size)
|
||||
assertEquals(shown.entries.size, shown.entries.map { it.path }.toSet().size)
|
||||
assertTrue(shown.entries.none { it.path.isEmpty() })
|
||||
// The device's words are cut to a length that leaves the controls on the screen.
|
||||
assertTrue(shown.reason.length <= PICKER_WORDS + 1)
|
||||
assertTrue(shown.entries.all { it.name.length <= PICKER_WORDS + 1 && it.reason.length <= PICKER_WORDS + 1 })
|
||||
assertTrue(PickerState().took(DeviceDirectory(code = "refused", error = long)).error!!.length <= PICKER_WORDS + 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aListingThatCameWithASentenceShowsBoth() {
|
||||
val partial = PickerState().took(project.copy(error = "Some directories could not be read."))
|
||||
assertEquals("Some directories could not be read.", partial.error)
|
||||
assertEquals(3, partial.listing?.entries?.size)
|
||||
assertFalse(partial.failed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewAgentChatShowsTheFoldersUsualModelUnlessOneWasPicked() {
|
||||
val list = read("models_agent_directory", ModelList.serializer())
|
||||
assertEquals(StartModel(model = "gpt-oss", from = "directory", ref = "local/gpt-oss"), list.start)
|
||||
assertTrue(list.models.none { it.interactiveOnly })
|
||||
val draft = ChatState(models = list.models, start = list.start)
|
||||
// The default is Qwen; the folder's usual model is shown instead.
|
||||
assertEquals("local/qwen", ChatState(models = list.models).modelId)
|
||||
assertEquals("local/gpt-oss", draft.modelId)
|
||||
assertEquals("gpt-oss", draft.modelInfo?.id)
|
||||
// A model the person picked in this draft is never set aside.
|
||||
assertEquals("local/vision-small", draft.copy(draft = Draft(model = "local/vision-small")).modelId)
|
||||
// A model the person no longer has is not shown, and a chat that exists has its own.
|
||||
assertNull(draft.copy(start = StartModel(model = "gone", from = "directory")).folderModel)
|
||||
assertEquals("local/qwen", draft.copy(start = StartModel(model = "gone", from = "directory")).modelId)
|
||||
assertEquals("qwen", draft.copy(chat = Chat(id = "c", model = "qwen")).modelInfo?.id)
|
||||
// A server before refs says the id alone: it still finds the row.
|
||||
assertEquals("local/gpt-oss", draft.copy(start = StartModel(model = "gpt-oss", from = "directory")).folderModel)
|
||||
// Without a directory the list says nothing of it.
|
||||
assertNull(read("models_agent", ModelList.serializer()).start)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun twoModelsWithOneIdAreToldApartByTheirRef() {
|
||||
val home = ModelInfo(id = "qwen", name = "Qwen", ref = "local/qwen", provider = "local", connection = "Local", default = true)
|
||||
val cloud = ModelInfo(id = "qwen", name = "Qwen", ref = "studio/qwen", provider = "studio", connection = "Model Studio")
|
||||
val other = ModelInfo(id = "gpt-oss", name = "gpt-oss", ref = "local/gpt-oss", connection = "Local")
|
||||
val models = listOf(home, cloud, other)
|
||||
// A ref names its own row; a bare id the first of them, as on the server.
|
||||
assertEquals(cloud, models.named("studio/qwen"))
|
||||
assertEquals(home, models.named("qwen"))
|
||||
assertNull(models.named("gone"))
|
||||
assertNull(models.named(""))
|
||||
// The twins say their connection; a model alone with its id does not.
|
||||
assertEquals("Qwen · Model Studio", cloud.titleAmong(models))
|
||||
assertEquals("Qwen · Local", home.titleAmong(models))
|
||||
assertEquals("gpt-oss", other.titleAmong(models))
|
||||
// The folder's usual model by its ref: the second twin, not the first.
|
||||
val draft = ChatState(models = models, start = StartModel(model = "qwen", from = "directory", ref = "studio/qwen"))
|
||||
assertEquals("studio/qwen", draft.modelId)
|
||||
assertEquals(cloud, draft.modelInfo)
|
||||
// A pick is kept and sent by its ref.
|
||||
assertEquals(cloud, draft.copy(start = null, draft = Draft(model = "studio/qwen")).modelInfo)
|
||||
// An open chat says the id; the ref picked here says which twin, while the id still fits.
|
||||
val open = ChatState(models = models, chat = Chat(id = "c", model = "qwen"))
|
||||
assertEquals(home, open.modelInfo)
|
||||
assertEquals(cloud, open.copy(picked = "studio/qwen").modelInfo)
|
||||
assertEquals(other, open.copy(chat = Chat(id = "c", model = "gpt-oss"), picked = "studio/qwen").modelInfo)
|
||||
// A model from a server before refs is its id.
|
||||
assertEquals("qwen", ModelInfo(id = "qwen").key)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theAssistantsSavedModelStillFindsItsRowAfterRefs() {
|
||||
val models = read("models", ModelList.serializer()).models
|
||||
// Saved as an id before refs, or as a ref since: the same model, named by its ref.
|
||||
assertEquals("local/gpt-oss", AssistController.assistantModelFor("gpt-oss", "qwen", models))
|
||||
assertEquals("local/gpt-oss", AssistController.assistantModelFor("local/gpt-oss", "qwen", models))
|
||||
// Gone, or "Instance default": the account's default, an id.
|
||||
assertEquals("local/qwen", AssistController.assistantModelFor("retired", "qwen", models))
|
||||
assertEquals("local/qwen", AssistController.assistantModelFor("", null, models))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDeviceSaysWhetherItTakesScheduledWorkAndRemembers() {
|
||||
val (workstation, laptop) = read("devices", DeviceList.serializer()).devices
|
||||
assertTrue(workstation.scheduled)
|
||||
assertEquals("edit", workstation.maxMode)
|
||||
assertTrue(workstation.directoryModel)
|
||||
assertFalse(laptop.scheduled)
|
||||
assertFalse(laptop.directoryModel)
|
||||
assertEquals("LLeMbas CLI on laptop", laptop.label)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theRoutesNameTheDeviceThePathAndTheDirectory() = runTest {
|
||||
val server = MockWebServer().apply { start() }
|
||||
try {
|
||||
val api = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
repeat(2) { server.enqueue(MockResponse().setBody(text("device_directories_places"))) }
|
||||
repeat(2) { server.enqueue(MockResponse().setBody(text("models_agent_directory"))) }
|
||||
assertTrue(api.deviceDirectories("token1").places)
|
||||
assertEquals("/api/v2/devices/token1/directories", server.takeRequest().path)
|
||||
api.deviceDirectories("token1", "/home/user/my project")
|
||||
assertEquals("/api/v2/devices/token1/directories?path=%2Fhome%2Fuser%2Fmy%20project", server.takeRequest().path)
|
||||
assertEquals("gpt-oss", api.agentModelList("token1", " /home/user/project ").start?.model)
|
||||
assertEquals("/api/v2/models?kind=agent&device=token1&directory=%2Fhome%2Fuser%2Fproject", server.takeRequest().path)
|
||||
// No folder chosen: the question is the old one.
|
||||
api.agentModelList("token1", "")
|
||||
assertEquals("/api/v2/models?kind=agent&device=token1", server.takeRequest().path)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.assist.EndOfSpeech
|
||||
import eu.llembas.android.assist.EndOfSpeech.Verdict
|
||||
import eu.llembas.android.assist.PHONE_GRACE_MS
|
||||
import eu.llembas.android.assist.PHONE_NOTHING_SAID_MS
|
||||
import eu.llembas.android.assist.PhoneWatch
|
||||
import eu.llembas.android.assist.phoneWatch
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** When the sheet stops listening, from sequences of microphone levels (one each 100 ms). */
|
||||
class EndOfSpeechTest {
|
||||
/** How it ended and after how many milliseconds. */
|
||||
private data class Ended(val verdict: Verdict, val ms: Long)
|
||||
|
||||
/**
|
||||
* Feed [start], then [rest] over and over, until a verdict; [words] are what the instance
|
||||
* has written down by each tick.
|
||||
*/
|
||||
private fun listen(start: List<Float>, rest: List<Float>, words: (Int) -> String = { "" }): Ended {
|
||||
val ear = EndOfSpeech()
|
||||
var tick = 0
|
||||
while (tick < 5_000) {
|
||||
val level = if (tick < start.size) start[tick] else rest[(tick - start.size) % rest.size]
|
||||
val verdict = ear.tick(level, words(tick))
|
||||
tick++
|
||||
if (verdict != Verdict.Listening) return Ended(verdict, tick * EndOfSpeech.TICK_MS)
|
||||
}
|
||||
error("it never stopped listening")
|
||||
}
|
||||
|
||||
/** A steady noise around [level]: no two moments quite the same. */
|
||||
private fun noise(level: Float): List<Float> = listOf(1.0f, 0.9f, 1.1f, 0.95f, 1.15f, 0.85f, 1.05f).map { it * level }
|
||||
|
||||
/** Two seconds of a voice whose loudest moments are [peak]: it rises and falls between words. */
|
||||
private fun voice(peak: Float): List<Float> {
|
||||
val second = listOf(0.6f, 1.0f, 0.8f, 0.3f, 0.9f, 1.0f, 0.5f, 0.7f, 1.0f, 0.4f)
|
||||
return (second + second).map { it * peak }
|
||||
}
|
||||
|
||||
private fun still(level: Float, ticks: Int): List<Float> = List(ticks) { level }
|
||||
|
||||
/** Ended as said, a pause after [start]'s last sound: not before it was over, and not long after. */
|
||||
private fun assertEndsAfter(start: List<Float>, ended: Ended, late: Long = 400) {
|
||||
val over = start.size * EndOfSpeech.TICK_MS
|
||||
assertEquals(Verdict.Said, ended.verdict)
|
||||
assertTrue("ended at ${ended.ms}, speech over at $over", ended.ms > over + EndOfSpeech.PAUSE_MS - 400 && ended.ms <= over + EndOfSpeech.PAUSE_MS + late)
|
||||
}
|
||||
|
||||
/** A voice that never dips far: its quietest moments are six tenths of its loudest. One second. */
|
||||
private fun steadyVoice(peak: Float): List<Float> = listOf(1.0f, 0.7f, 0.9f, 0.6f, 1.0f, 0.8f, 0.65f, 0.95f, 0.75f, 0.6f).map { it * peak }
|
||||
|
||||
@Test
|
||||
fun aSilentRoomWithNothingSaidGivesUpSoon() {
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), still(0.001f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNoisyRoomWithNothingSaidGivesUpAsSoon() {
|
||||
// Louder than any fixed "this is a voice" level could allow for: the noise is the floor.
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), noise(0.03f)))
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), noise(0.012f)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMicrophoneThatGivesNothingAtAllGivesUpToo() {
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), still(0f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun speechThenAPauseEndsAfterThePause() {
|
||||
val start = still(0.001f, 5) + voice(0.06f)
|
||||
assertEndsAfter(start, listen(start, still(0.001f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun speechInANoisyRoomEndsAfterThePauseToo() {
|
||||
val start = noise(0.03f) + voice(0.12f)
|
||||
// The room is louder than the first guess allows for: found a moment after the voice ends.
|
||||
assertEndsAfter(start, listen(start, noise(0.03f)), late = 800)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRoomThatIsNeverQuietByAFixedLevelStillEnds() {
|
||||
// The room sits at 0.015: above what used to count as quiet, so it listened to the limit.
|
||||
val start = still(0.015f, 5) + voice(0.06f)
|
||||
assertEndsAfter(start, listen(start, still(0.015f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun speakingAtOnceIsHeard() {
|
||||
// No quiet moment first to measure the room by: the first dip between words gives it.
|
||||
for (peak in listOf(0.05f, 0.08f, 0.3f)) {
|
||||
val start = voice(peak)
|
||||
assertEndsAfter(start, listen(start, still(0.002f, 1)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun silenceFromAHeadsetThatGatesItsNoiseIsAPause() {
|
||||
// After speech the microphone gives exact zeros: that is quiet, not "no microphone".
|
||||
val start = still(0.001f, 5) + voice(0.06f)
|
||||
assertEndsAfter(start, listen(start, still(0f, 1)))
|
||||
val atOnce = voice(0.06f)
|
||||
assertEndsAfter(atOnce, listen(atOnce, still(0f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun listeningThatBeginsInTheMiddleOfASentenceHearsIt() {
|
||||
// The wake word's shape: the person goes straight on, and for eight seconds the voice
|
||||
// never dips far. It must not become "the room", nor end as "nothing said" at five.
|
||||
for (peak in listOf(0.035f, 0.05f, 0.1f)) {
|
||||
var start = emptyList<Float>()
|
||||
repeat(8) { start = start + steadyVoice(peak) }
|
||||
assertEndsAfter(start, listen(start, still(0.002f, 1)))
|
||||
assertEndsAfter(start, listen(start, still(0.004f, 1)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aShortWordIsSpeech() {
|
||||
val start = still(0.001f, 10) + listOf(0.03f, 0.05f, 0.04f, 0.01f)
|
||||
assertEndsAfter(start, listen(start, still(0.001f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aClickIsNotSpeech() {
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(still(0.001f, 5) + listOf(0.3f), still(0.001f, 1)))
|
||||
val twice = still(0.001f, 5) + listOf(0.3f, 0.3f) + still(0.001f, 20) + listOf(0.3f, 0.3f)
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(twice, still(0.001f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aLongQuestionIsNotCutShort() {
|
||||
var start = still(0.001f, 5)
|
||||
repeat(10) { start = start + voice(0.06f) }
|
||||
assertEndsAfter(start, listen(start, still(0.001f, 1)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun soundThatNeverPausesEndsAtTheLimit() {
|
||||
val ended = listen(emptyList(), listOf(0.01f, 0.2f, 0.01f, 0.2f, 0.2f, 0.2f, 0.01f))
|
||||
assertEquals(Ended(Verdict.Said, EndOfSpeech.LONGEST_MS), ended)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSameWordsForAWhileEndIt() {
|
||||
// Music that never pauses, and the words stopped coming: that is the end.
|
||||
val ended = listen(still(0.001f, 5), listOf(0.01f, 0.2f, 0.01f, 0.2f, 0.2f, 0.2f, 0.01f)) { tick -> if (tick > 20) "play something" else "" }
|
||||
assertEquals(Verdict.Said, ended.verdict)
|
||||
assertTrue(ended.ms < 8_000)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wordsInventedFromSilenceAreNotSpeech() {
|
||||
// A speech-to-text model handed silence writes "Thank you." -- in a silent room and in a
|
||||
// noisy one the microphone heard nothing above the room, so nothing was said.
|
||||
val invented = { tick: Int -> if (tick > 12) "Thank you." else "" }
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), still(0.001f, 1), invented))
|
||||
assertEquals(Ended(Verdict.Nothing, EndOfSpeech.NOTHING_SAID_MS), listen(emptyList(), noise(0.03f), invented))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aQuietVoiceCountsOnceItsWordsCome() {
|
||||
// Too soft to be sure of by loudness alone, but above the room, and the instance wrote words down.
|
||||
val start = still(0.001f, 5) + still(0.0035f, 20)
|
||||
assertEndsAfter(start, listen(start, still(0.001f, 1)) { tick -> if (tick > 15) "what time is it" else "" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theFloorFollowsTheRoom() {
|
||||
val ear = EndOfSpeech()
|
||||
assertFalse(ear.heardSomething)
|
||||
repeat(30) { ear.tick(noise(0.03f)[it % 7]) }
|
||||
// Near the quietest of the noise, not at a fixed number.
|
||||
assertTrue(ear.floor > 0.02f && ear.floor < 0.03f)
|
||||
assertFalse(ear.heardSomething)
|
||||
assertFalse(ear.spoke)
|
||||
voice(0.12f).forEach { ear.tick(it) }
|
||||
assertTrue(ear.spoke)
|
||||
assertTrue(ear.heardSomething)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun thePhonesRecogniserIsWatched() {
|
||||
// It normally ends by itself; the watch is for one that does not.
|
||||
assertEquals(PhoneWatch.Wait, phoneWatch(3_000, anyWords = false, sameForMs = 3_000))
|
||||
assertEquals(PhoneWatch.GiveUp, phoneWatch(PHONE_NOTHING_SAID_MS, anyWords = false, sameForMs = PHONE_NOTHING_SAID_MS))
|
||||
// Words still coming: left alone.
|
||||
assertEquals(PhoneWatch.Wait, phoneWatch(20_000, anyWords = true, sameForMs = 400))
|
||||
// The same words for a while: asked to stop, then taken as they are.
|
||||
assertEquals(PhoneWatch.Finish, phoneWatch(20_000, anyWords = true, sameForMs = EndOfSpeech.SAME_WORDS_MS))
|
||||
assertEquals(PhoneWatch.Take, phoneWatch(20_000, anyWords = true, sameForMs = EndOfSpeech.SAME_WORDS_MS + PHONE_GRACE_MS))
|
||||
// And never past the limit.
|
||||
assertEquals(PhoneWatch.Finish, phoneWatch(EndOfSpeech.LONGEST_MS, anyWords = true, sameForMs = 0))
|
||||
assertEquals(PhoneWatch.Take, phoneWatch(EndOfSpeech.LONGEST_MS + PHONE_GRACE_MS, anyWords = true, sameForMs = 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRecogniserThatShowsNoWordsWhileOneSpeaksIsNotGivenUpOn() {
|
||||
// No partial results, but it said speech began and its level is loud: somebody speaks.
|
||||
assertEquals(PhoneWatch.Wait, phoneWatch(12_000, anyWords = false, sameForMs = 12_000, silentForMs = 300))
|
||||
// Quiet for a good while after that: asked for what it has, then given up on.
|
||||
assertEquals(PhoneWatch.Finish, phoneWatch(20_000, anyWords = false, sameForMs = 20_000, silentForMs = PHONE_NOTHING_SAID_MS))
|
||||
assertEquals(PhoneWatch.GiveUp, phoneWatch(20_000, anyWords = false, sameForMs = 20_000, silentForMs = PHONE_NOTHING_SAID_MS + PHONE_GRACE_MS))
|
||||
// Words that stopped changing while the level is still loud: not cut off yet.
|
||||
assertEquals(PhoneWatch.Wait, phoneWatch(20_000, anyWords = true, sameForMs = EndOfSpeech.SAME_WORDS_MS, silentForMs = 200))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.EventsHub
|
||||
import eu.llembas.android.api.Frame
|
||||
import eu.llembas.android.api.reopenAtOnce
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/** The person's events route: one connection for all who watch it, and no tight loop on a route that only closes. */
|
||||
class EventsTest {
|
||||
@Test
|
||||
fun twoWatchersShareOneConnectionAndALateOneIsToldTheLastFrame() = runTest {
|
||||
var opened = 0
|
||||
val one = Frame("reports", """{"unread":1}""")
|
||||
val two = Frame("reports", """{"unread":2}""")
|
||||
// The server says the state at once to a new connection: the first frame is there to be read.
|
||||
val route = MutableSharedFlow<Frame>(replay = 1)
|
||||
route.emit(one)
|
||||
val hub = EventsHub(backgroundScope)
|
||||
val open = {
|
||||
flow {
|
||||
opened++
|
||||
emitAll(route)
|
||||
}
|
||||
}
|
||||
val drawer = Channel<Frame>(Channel.UNLIMITED)
|
||||
val list = Channel<Frame>(Channel.UNLIMITED)
|
||||
val first = launch { hub.frames("instance", open).collect { drawer.send(it) } }
|
||||
assertEquals(one, drawer.receive())
|
||||
// A second watcher joins the connection already open, and is told what it missed.
|
||||
val second = launch { hub.frames("instance", open).collect { list.send(it) } }
|
||||
assertEquals(one, list.receive())
|
||||
route.emit(two)
|
||||
assertEquals(two, drawer.receive())
|
||||
assertEquals(two, list.receive())
|
||||
assertEquals(1, opened)
|
||||
first.cancel()
|
||||
second.cancel()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRouteThatOnlyClosesIsNotAskedInATightLoop() {
|
||||
// Closed after it said something: opened again at once, as the activity route means it.
|
||||
assertTrue(reopenAtOnce(closed = true, said = true))
|
||||
// Closed having said nothing, or dropped: a pause first.
|
||||
assertFalse(reopenAtOnce(closed = true, said = false))
|
||||
assertFalse(reopenAtOnce(closed = false, said = true))
|
||||
assertFalse(reopenAtOnce(closed = false, said = false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.unit.IntSize
|
||||
import eu.llembas.android.api.BatchAnswer
|
||||
import eu.llembas.android.api.FileContent
|
||||
import eu.llembas.android.api.FileEntry
|
||||
import eu.llembas.android.api.FileKinds
|
||||
import eu.llembas.android.api.FileListing
|
||||
import eu.llembas.android.api.FileVersions
|
||||
import eu.llembas.android.api.FileView
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.TrashList
|
||||
import eu.llembas.android.api.parseNotebook
|
||||
import eu.llembas.android.api.parseTable
|
||||
import eu.llembas.android.api.sampleFor
|
||||
import eu.llembas.android.api.tableDelimiter
|
||||
import eu.llembas.android.share.sharedNoteName
|
||||
import eu.llembas.android.ui.files.FilesState
|
||||
import eu.llembas.android.ui.files.TransferViewModel
|
||||
import eu.llembas.android.ui.files.asZip
|
||||
import eu.llembas.android.ui.files.outcome
|
||||
import eu.llembas.android.ui.viewer.clampPan
|
||||
import eu.llembas.android.ui.viewer.playTime
|
||||
import kotlinx.serialization.KSerializer
|
||||
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
|
||||
import org.junit.Test
|
||||
import java.time.LocalDateTime
|
||||
|
||||
/** What the file manager decides without a phone: the viewer for a kind, a table, a notebook, what is chosen, what a batch said. */
|
||||
class FileLogicTest {
|
||||
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(
|
||||
serializer,
|
||||
requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText(),
|
||||
)
|
||||
|
||||
@Test
|
||||
fun thePinnedFilesContract() {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
assertEquals(listOf(null, "markdown", "image"), listing.entries.map { it.fileKind })
|
||||
assertNull(listing.copied)
|
||||
val copied = read("files_copied", FileListing.serializer())
|
||||
assertEquals("lembas (2).md", copied.copied!!.name)
|
||||
assertEquals("/home/frodo/lembas (2).md", copied.copied!!.path)
|
||||
|
||||
val file = read("file_content", FileContent.serializer())
|
||||
assertEquals("markdown", file.fileKind)
|
||||
assertEquals(true, file.writable)
|
||||
assertEquals("ab".repeat(32), file.sha)
|
||||
val picture = read("file_content_withheld", FileContent.serializer())
|
||||
assertEquals("image", picture.fileKind)
|
||||
assertEquals(false, picture.writable)
|
||||
|
||||
val trash = read("files_trash", TrashList.serializer())
|
||||
assertEquals("node5", trash.items.single().id)
|
||||
assertEquals("/home/frodo/old.md", trash.items.single().path)
|
||||
assertEquals(12L, trash.items.single().size)
|
||||
assertEquals("/home/frodo/old.md", read("files_restored", TrashList.serializer()).restored)
|
||||
assertEquals(1, read("files_trash_emptied", TrashList.serializer()).removed)
|
||||
|
||||
val versions = read("file_versions", FileVersions.serializer())
|
||||
assertEquals(listOf("ver2", "ver1"), versions.versions.map { it.id })
|
||||
assertTrue(versions.versions[0].current)
|
||||
assertFalse(versions.versions[1].current)
|
||||
assertEquals("Frodo", versions.versions[1].by)
|
||||
assertNull(versions.versions[1].chatId)
|
||||
|
||||
// A batch is answered path by path: one moved, one refused in the server's own sentence.
|
||||
val batch = read("files_batch", BatchAnswer.serializer())
|
||||
assertEquals(1, batch.done)
|
||||
assertEquals(1, batch.failed)
|
||||
assertEquals("/home/frodo/recipes/lembas.md", batch.results[0].to)
|
||||
val said = outcome(batch)
|
||||
assertEquals(1, said.done)
|
||||
assertEquals("Read-only: /home/frodo/map.png can be read in this session but not changed.", said.said)
|
||||
assertNull(outcome(batch.copy(failed = 0)).said)
|
||||
// Without a sentence, at least which one.
|
||||
assertEquals("map.png", outcome(batch.copy(results = batch.results.map { it.copy(error = null) })).said)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aKindChoosesItsViewer() {
|
||||
for (kind in listOf("markdown", "code", "text", "html", "svg")) assertEquals(kind, FileView.Text, FileKinds.viewer(kind))
|
||||
assertEquals(FileView.Image, FileKinds.viewer("image"))
|
||||
assertEquals(FileView.Pdf, FileKinds.viewer("pdf"))
|
||||
assertEquals(FileView.Audio, FileKinds.viewer("audio"))
|
||||
assertEquals(FileView.Video, FileKinds.viewer("video"))
|
||||
assertEquals(FileView.Table, FileKinds.viewer("table"))
|
||||
assertEquals(FileView.Notebook, FileKinds.viewer("notebook"))
|
||||
for (kind in listOf("archive", "model3d", "binary", "something-new")) assertEquals(kind, FileView.Details, FileKinds.viewer(kind))
|
||||
// A server that does not say the kind is read as before: as text.
|
||||
assertEquals(FileView.Text, FileKinds.viewer(null))
|
||||
|
||||
// Editing: a text kind (a table too) the person may change, and nothing withheld or unsaid.
|
||||
assertTrue(FileKinds.editable("markdown", writable = true, withheld = false))
|
||||
assertTrue(FileKinds.editable("svg", writable = true, withheld = false))
|
||||
assertTrue(FileKinds.editable("table", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = false, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = null, withheld = false))
|
||||
assertFalse(FileKinds.editable("markdown", writable = true, withheld = true))
|
||||
assertFalse(FileKinds.editable("notebook", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable("image", writable = true, withheld = false))
|
||||
assertFalse(FileKinds.editable(null, writable = true, withheld = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun namesAndPaths() {
|
||||
assertTrue(FileKinds.badName(""))
|
||||
assertTrue(FileKinds.badName(" "))
|
||||
assertTrue(FileKinds.badName("a/b"))
|
||||
assertTrue(FileKinds.badName(".."))
|
||||
assertFalse(FileKinds.badName("notes.md"))
|
||||
assertEquals("/home/frodo/notes.md", FileKinds.child("/home/frodo/", " notes.md "))
|
||||
assertEquals("/notes.md", FileKinds.child("/", "notes.md"))
|
||||
assertEquals("/home/frodo", FileKinds.parent("/home/frodo/notes.md"))
|
||||
assertEquals("/", FileKinds.parent("/home"))
|
||||
assertEquals("notes.md", FileKinds.name("/home/frodo/notes.md"))
|
||||
assertEquals("recipes", FileKinds.name("/home/frodo/recipes/"))
|
||||
// What another app is told a file is called holds no way out of its folder.
|
||||
assertEquals("_.._etc_passwd", FileKinds.safeName("../../etc/passwd"))
|
||||
assertEquals("file", FileKinds.safeName(".."))
|
||||
assertEquals("file", FileKinds.safeName(" "))
|
||||
assertEquals("a_b", FileKinds.safeName("a\\b"))
|
||||
assertEquals("map.png", FileKinds.safeName("map.png"))
|
||||
|
||||
assertFalse(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md"))))
|
||||
assertTrue(asZip(listOf(FileEntry(name = "r", path = "/h/r", kind = "dir"))))
|
||||
assertTrue(asZip(listOf(FileEntry(name = "a.md", path = "/h/a.md"), FileEntry(name = "b.md", path = "/h/b.md"))))
|
||||
assertEquals("recipes.zip", TransferViewModel.zipName(listOf("/home/frodo/recipes")))
|
||||
assertEquals("frodo.zip", TransferViewModel.zipName(listOf("/home/frodo/a.md", "/home/frodo/b.md")))
|
||||
assertEquals("files.zip", TransferViewModel.zipName(emptyList()))
|
||||
assertEquals("shared-20260102-030405.txt", sharedNoteName(LocalDateTime.of(2026, 1, 2, 3, 4, 5)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whatIsChosenInADirectory() {
|
||||
val listing = read("files_listing", FileListing.serializer())
|
||||
var state = FilesState(path = "/home/frodo").listed(listing)
|
||||
assertFalse(state.selecting)
|
||||
state = state.toggled("/home/frodo/lembas.md").toggled("/home/frodo/map.png")
|
||||
assertTrue(state.selecting)
|
||||
assertEquals(listOf("lembas.md", "map.png"), state.chosen.map { it.name })
|
||||
assertEquals(listOf("map.png"), state.toggled("/home/frodo/lembas.md").chosen.map { it.name })
|
||||
assertEquals(3, state.allSelected().selected.size)
|
||||
// The same directory read again keeps what is still there; another directory keeps nothing.
|
||||
val without = listing.copy(entries = listing.entries.filter { it.name != "map.png" })
|
||||
assertEquals(setOf("/home/frodo/lembas.md"), state.listed(without).selected)
|
||||
assertTrue(state.listed(listing.copy(path = "/home/frodo/recipes")).selected.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTableIsCutIntoCells() {
|
||||
val table = parseTable("name,what\r\n\"Baggins, Frodo\",\"says \"\"hello\"\"\"\nSam,\"two\nlines\"\n\nlast,row", ',')
|
||||
assertEquals(
|
||||
listOf(listOf("name", "what"), listOf("Baggins, Frodo", "says \"hello\""), listOf("Sam", "two\nlines"), listOf("last", "row")),
|
||||
table.rows,
|
||||
)
|
||||
assertEquals(2, table.columns)
|
||||
assertFalse(table.cut)
|
||||
// Tabs, a ragged row, and a quote inside a bare cell left as it is.
|
||||
val tabs = parseTable("a\tb\tc\n1\t2\n5\" pipe\tx\ty\n", '\t')
|
||||
assertEquals(listOf(listOf("a", "b", "c"), listOf("1", "2"), listOf("5\" pipe", "x", "y")), tabs.rows)
|
||||
assertEquals(3, tabs.columns)
|
||||
// Caps: rows, columns and a cell's length; what was left out is said.
|
||||
val many = parseTable((1..10).joinToString("\n") { "$it,x,y,z" }, ',', maxRows = 3, maxColumns = 2, maxCell = 1)
|
||||
assertEquals(listOf(listOf("1", "x"), listOf("2", "x"), listOf("3", "x")), many.rows)
|
||||
assertTrue(many.cut)
|
||||
assertEquals("a", parseTable("abcdef,2", ',', maxCell = 1).rows[0][0])
|
||||
// Only the beginning of a long file: its last, half line is not shown as a row.
|
||||
val head = parseTable("a,b\n1,2\n3,", ',', partial = true)
|
||||
assertEquals(listOf(listOf("a", "b"), listOf("1", "2")), head.rows)
|
||||
assertTrue(head.cut)
|
||||
assertTrue(parseTable("", ',').rows.isEmpty())
|
||||
|
||||
assertEquals('\t', tableDelimiter("list.tsv", "a,b"))
|
||||
assertEquals('\t', tableDelimiter("list.csv", "a\tb\n1\t2"))
|
||||
assertEquals(';', tableDelimiter("list.csv", "a;b\n1;2"))
|
||||
assertEquals(',', tableDelimiter("list.csv", "a,b;c"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNotebookIsItsCellsAsText() {
|
||||
val text = """
|
||||
{"metadata": {"kernelspec": {"language": "python"}}, "cells": [
|
||||
{"cell_type": "markdown", "source": ["# Waybread\n", "Notes."]},
|
||||
{"cell_type": "code", "execution_count": 3, "source": "print('hi')",
|
||||
"outputs": [
|
||||
{"output_type": "stream", "text": ["hi\n"]},
|
||||
{"output_type": "execute_result", "data": {"text/plain": "42", "text/html": "<b onclick=x>42</b>", "image/png": "AAAA"}},
|
||||
{"output_type": "error", "ename": "ValueError", "evalue": "no"}
|
||||
]},
|
||||
{"cell_type": "code", "execution_count": null, "source": []}
|
||||
]}
|
||||
""".trimIndent()
|
||||
val notebook = parseNotebook(text)
|
||||
assertNotNull(notebook)
|
||||
assertEquals("python", notebook!!.language)
|
||||
assertEquals(listOf("markdown", "code", "code"), notebook.cells.map { it.kind })
|
||||
assertEquals("# Waybread\nNotes.", notebook.cells[0].source)
|
||||
assertEquals(3, notebook.cells[1].count)
|
||||
// Only what is plain text of an output is kept: no HTML, no picture.
|
||||
assertEquals("hi\n42\nValueError: no", notebook.cells[1].output)
|
||||
assertFalse(notebook.cells[1].output.contains("onclick"))
|
||||
assertNull(notebook.cells[2].count)
|
||||
assertEquals("", notebook.cells[2].source)
|
||||
assertEquals(0, notebook.more)
|
||||
|
||||
val long = parseNotebook(text, maxCells = 1, maxChars = 4)!!
|
||||
assertEquals(2, long.more)
|
||||
assertEquals("# Wa", long.cells.single().source)
|
||||
assertTrue(long.cells.single().cut)
|
||||
// Not a notebook: nothing to draw as one.
|
||||
assertNull(parseNotebook("[1, 2]"))
|
||||
assertNull(parseNotebook("{\"cells\": 3}"))
|
||||
assertNull(parseNotebook("not json"))
|
||||
assertTrue(parseNotebook("{\"cells\": []}")!!.cells.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPictureIsDecodedSmallWhateverItClaims() {
|
||||
assertEquals(1, sampleFor(1920, 1080))
|
||||
assertEquals(2, sampleFor(4000, 3000))
|
||||
// 30 000 px square: at most a few megapixels are ever decoded.
|
||||
val sample = sampleFor(30_000, 30_000)
|
||||
assertTrue((30_000L / sample) * (30_000L / sample) <= 8_000_000)
|
||||
assertTrue(30_000 / sample <= 2560)
|
||||
// A ribbon: its long edge decides.
|
||||
assertTrue(100_000 / sampleFor(100_000, 10) <= 2560)
|
||||
assertEquals(1, sampleFor(0, 0))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aZoomedPictureStaysInItsFrameAndAPlayerSaysItsTime() {
|
||||
val size = IntSize(1000, 500)
|
||||
// Not zoomed: it does not move. Zoomed twice: half its size either way, and no further.
|
||||
val still = clampPan(Offset(300f, -80f), 1f, size)
|
||||
assertEquals(0f, still.x, 0f)
|
||||
assertEquals(0f, still.y, 0f)
|
||||
val right = clampPan(Offset(900f, -80f), 2f, size)
|
||||
assertEquals(500f, right.x, 0f)
|
||||
assertEquals(-80f, right.y, 0f)
|
||||
val corner = clampPan(Offset(-900f, 400f), 2f, size)
|
||||
assertEquals(-500f, corner.x, 0f)
|
||||
assertEquals(250f, corner.y, 0f)
|
||||
|
||||
assertEquals("0:00", playTime(0))
|
||||
assertEquals("0:00", playTime(-5))
|
||||
assertEquals("1:05", playTime(65_400))
|
||||
assertEquals("1:00:07", playTime(3_607_000))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.RangeReader
|
||||
import eu.llembas.android.api.SaveConflict
|
||||
import eu.llembas.android.ui.files.StreamBody
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import okio.Buffer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
/** The file manager's calls, against a server that answers as the pinned contract says. */
|
||||
class FilesClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun anUploadIsStreamedIntoItsFolderAndSaysHowFarItIs() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody(contract("files_listing")))
|
||||
val bytes = ByteArray(300_000) { (it % 251).toByte() }
|
||||
val heard = mutableListOf<Long>()
|
||||
val body = StreamBody("application/octet-stream".toMediaType(), bytes.size.toLong(), { heard += it }) { ByteArrayInputStream(bytes) }
|
||||
val listing = client().uploadFile("/home/frodo", "big.bin", body)
|
||||
assertEquals("/home/frodo", listing.path)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("POST", request.method)
|
||||
assertEquals("/api/v2/files/upload?path=%2Fhome%2Ffrodo", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
val sent = request.body.readByteArray()
|
||||
val head = String(sent, 0, 400, Charsets.ISO_8859_1)
|
||||
assertTrue(head, head.contains("name=\"files\"; filename=\"big.bin\""))
|
||||
// Every byte went, in pieces, and the last word on progress is the whole file.
|
||||
assertTrue(sent.size > bytes.size)
|
||||
assertTrue(heard.size > 1)
|
||||
assertEquals(bytes.size.toLong(), heard.last())
|
||||
assertTrue(body.isOneShot())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFileOverTheLimitIsRefusedInTheServersSentence() = runTest {
|
||||
val sentence = "big.bin is larger than 50 MB, the most that can be uploaded here."
|
||||
server.enqueue(MockResponse().setResponseCode(413).setBody("""{"detail":"$sentence"}"""))
|
||||
try {
|
||||
client().uploadFile("/home/frodo", "big.bin", StreamBody(null, 3, {}) { ByteArrayInputStream(byteArrayOf(1, 2, 3)) })
|
||||
fail("a 413 is a refusal")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(413, e.status)
|
||||
assertEquals(sentence, e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSaveSaysWhatItOpenedAndAConflictWritesNothing() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
val saved = api.saveFile("/home/frodo/lembas.md", "# Lembas\n", base = "abab")
|
||||
assertEquals("markdown", saved.fileKind)
|
||||
assertEquals(true, saved.writable)
|
||||
val first = server.takeRequest()
|
||||
assertEquals("PUT", first.method)
|
||||
assertEquals("/api/v2/files/content", first.path)
|
||||
val said = first.body.readUtf8()
|
||||
assertTrue(said, said.contains("\"base\":\"abab\""))
|
||||
assertTrue(said, said.contains("\"path\":\"/home/frodo/lembas.md\""))
|
||||
assertFalse(said, said.contains("force"))
|
||||
|
||||
// The file changed meanwhile: the server's sentence and what the file holds now.
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_save_conflict")))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab")
|
||||
fail("a conflict is not a save")
|
||||
} catch (e: SaveConflict) {
|
||||
assertEquals("This file changed since you opened it. Reload it, or save anyway.", e.message)
|
||||
assertEquals("ab".repeat(32), e.sha)
|
||||
}
|
||||
server.takeRequest()
|
||||
|
||||
// Save anyway says so; a new file says no base at all.
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab", force = true)
|
||||
assertTrue(server.takeRequest().body.readUtf8().contains("\"force\":true"))
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/new.md", "")
|
||||
assertFalse(server.takeRequest().body.readUtf8().contains("base"))
|
||||
|
||||
// Any other 409 is a refusal like any other.
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody("""{"detail":"Not now."}"""))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "mine", base = "abab")
|
||||
fail("a refusal")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals("Not now.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aDownloadIsCopiedAsItComesWithTheTokenInItsHeaderOnly() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
val out = ByteArrayOutputStream()
|
||||
var last = 0L to 0L
|
||||
val done = api.download(api.rawFile("/home/frodo/map of the road.png"), out) { now, total -> last = now to total }
|
||||
assertEquals(11L, done)
|
||||
assertEquals("hello world", out.toString("UTF-8"))
|
||||
assertEquals(11L to 11L, last)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fmap%20of%20the%20road.png", request.path)
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
assertFalse(request.requestUrl.toString().contains("lmb_test"))
|
||||
assertNull(request.getHeader("Range"))
|
||||
|
||||
// More than the caller will take is refused before it is copied.
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
try {
|
||||
api.download(api.rawFile("/home/frodo/map.png"), ByteArrayOutputStream(), most = 4)
|
||||
fail("too much")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(413, e.status)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPieceOfAFileIsARangeRequest() {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setResponseCode(206).setHeader("Content-Range", "bytes 4-7/11").setBody("o wo"))
|
||||
assertEquals("o wo", api.rawBytes("/home/frodo/song.mp3", 4, 7).toString(Charsets.UTF_8))
|
||||
val request = server.takeRequest()
|
||||
assertEquals("bytes=4-7", request.getHeader("Range"))
|
||||
assertEquals("Bearer lmb_test", request.getHeader("Authorization"))
|
||||
assertFalse(request.requestUrl.toString().contains("lmb_test"))
|
||||
|
||||
// A server that ignores the range would hand the wrong bytes: refused, not played.
|
||||
server.enqueue(MockResponse().setBody("hello world"))
|
||||
try {
|
||||
api.rawBytes("/home/frodo/song.mp3", 4, 7)
|
||||
fail("the whole file is not the piece asked for")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(416, e.status)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPlayerReadsBlockByBlockAndABlockIsFetchedOnce() {
|
||||
val file = ByteArray(10) { it.toByte() }
|
||||
val asked = mutableListOf<Pair<Long, Long>>()
|
||||
val reader = RangeReader(file.size.toLong(), block = 4, keep = 2) { from, to ->
|
||||
asked += from to to
|
||||
file.copyOfRange(from.toInt(), to.toInt() + 1)
|
||||
}
|
||||
val buffer = ByteArray(8)
|
||||
// A read ends at its block's end; the player asks again for the rest.
|
||||
assertEquals(4, reader.read(0, buffer, 0, 8))
|
||||
assertArrayEquals(byteArrayOf(0, 1, 2, 3), buffer.copyOf(4))
|
||||
assertEquals(2, reader.read(2, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L), asked)
|
||||
// The last block is short, and the end is the end.
|
||||
assertEquals(2, reader.read(8, buffer, 3, 5))
|
||||
assertArrayEquals(byteArrayOf(8, 9), buffer.copyOfRange(3, 5))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L), asked)
|
||||
assertEquals(-1, reader.read(10, buffer, 0, 8))
|
||||
assertEquals(-1, reader.read(-1, buffer, 0, 8))
|
||||
assertEquals(0, reader.read(1, buffer, 0, 0))
|
||||
// A seek back to a block still kept asks nothing; one that fell out is asked for again.
|
||||
assertEquals(1, reader.read(3, buffer, 0, 8))
|
||||
assertEquals(2, asked.size)
|
||||
assertEquals(4, reader.read(4, buffer, 0, 8))
|
||||
assertEquals(4, reader.read(0, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L), asked)
|
||||
assertEquals(2, reader.read(8, buffer, 0, 8))
|
||||
assertEquals(listOf(0L to 3L, 8L to 9L, 4L to 7L, 8L to 9L), asked)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aBatchTheTrashAndTheVersions() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("files_batch")))
|
||||
val answer = api.batchFiles("move", listOf("/home/frodo/lembas.md", "/home/frodo/map.png"), "/home/frodo/recipes")
|
||||
assertEquals(1, answer.done)
|
||||
assertEquals(1, answer.failed)
|
||||
val batch = server.takeRequest()
|
||||
assertEquals("/api/v2/files/batch", batch.path)
|
||||
val body = batch.body.readUtf8()
|
||||
assertTrue(body, body.contains("\"op\":\"move\""))
|
||||
assertTrue(body, body.contains("\"paths\":[\"/home/frodo/lembas.md\",\"/home/frodo/map.png\"]"))
|
||||
assertTrue(body, body.contains("\"to\":\"/home/frodo/recipes\""))
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("files_trash_emptied")))
|
||||
assertEquals(1, api.removeTrashed().removed)
|
||||
val emptied = server.takeRequest()
|
||||
assertEquals("DELETE", emptied.method)
|
||||
assertEquals("/api/v2/files/trash", emptied.path)
|
||||
server.enqueue(MockResponse().setBody(contract("files_trash_emptied")))
|
||||
api.removeTrashed("node5")
|
||||
assertEquals("/api/v2/files/trash?id=node5", server.takeRequest().path)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("file_versions")))
|
||||
api.restoreVersion("/home/frodo/lembas.md", "ver1")
|
||||
val restored = server.takeRequest()
|
||||
assertEquals("/api/v2/files/versions/restore", restored.path)
|
||||
assertTrue(restored.body.readUtf8().contains("\"version\":\"ver1\""))
|
||||
|
||||
// A zip is asked for by its paths, in the body: nothing of the account is in the address.
|
||||
val zip = api.zipFiles(listOf("/home/frodo/recipes"))
|
||||
assertEquals("POST", zip.method)
|
||||
assertTrue(zip.url.toString().endsWith("/api/v2/files/zip"))
|
||||
val asked = Buffer().also { zip.body!!.writeTo(it) }.readUtf8()
|
||||
assertEquals("""{"paths":["/home/frodo/recipes"]}""", asked)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.Message
|
||||
import eu.llembas.android.ui.chat.TranscriptChange
|
||||
import eu.llembas.android.ui.chat.followsAt
|
||||
import eu.llembas.android.ui.chat.keptRow
|
||||
import eu.llembas.android.ui.chat.movesToEnd
|
||||
import eu.llembas.android.ui.chat.transcriptChange
|
||||
import eu.llembas.android.ui.chat.yielding
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.test.runTest
|
||||
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 view follows a reply only for a person who is at the end; scrolled away, it stays where
|
||||
* they are, whatever the transcript does; back at the end, it follows again.
|
||||
*/
|
||||
class FollowTest {
|
||||
private fun person(id: String) = Message(id = id, role = "user", text = "A question")
|
||||
|
||||
private fun reply(id: String, text: String = "") = Message(id = id, role = "assistant", text = text)
|
||||
|
||||
private fun note(id: String) = Message(id = id, role = "user", machine = true, text = "A task finished")
|
||||
|
||||
private val talk = listOf(person("q1"), reply("a1"), person("q2"), reply("a2"))
|
||||
|
||||
@Test
|
||||
fun aChatOpenedGoesToItsEnd() {
|
||||
assertEquals(TranscriptChange.Opened, transcriptChange(null, talk))
|
||||
assertEquals(TranscriptChange.Opened, transcriptChange(emptyList(), talk))
|
||||
// Another chat in the same place is opened too: nothing of the old one is left.
|
||||
assertEquals(TranscriptChange.Opened, transcriptChange(talk, listOf(person("x1"), reply("y1"))))
|
||||
assertTrue(movesToEnd(TranscriptChange.Opened, following = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRotationKeepsThePlaceOfAPersonWhoScrolledAway() {
|
||||
val change = transcriptChange(null, talk, restored = true)
|
||||
assertEquals(TranscriptChange.Changed, change)
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
assertTrue(movesToEnd(change, following = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMessageSentAlwaysShows() {
|
||||
val change = transcriptChange(talk, talk + person("q3") + reply("a3"), sent = "q3")
|
||||
assertEquals(TranscriptChange.Sent, change)
|
||||
assertTrue(movesToEnd(change, following = false))
|
||||
// A prompt queued behind a running reply: the person's row alone.
|
||||
assertEquals(TranscriptChange.Sent, transcriptChange(talk, talk + person("q3"), sent = "q3"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aMessageWrittenElsewhereDoesNotDragAReaderDown() {
|
||||
// The person's row arrives from the page or another device: this app did not send it.
|
||||
val elsewhere = transcriptChange(talk, talk + person("q3") + reply("a3"))
|
||||
assertEquals(TranscriptChange.Appended, elsewhere)
|
||||
assertFalse(movesToEnd(elsewhere, following = false))
|
||||
assertTrue(movesToEnd(elsewhere, following = true))
|
||||
// Nor is it "sent" because this app sent something earlier.
|
||||
assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk + person("q3"), sent = "q2"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aScrollAFingerInterruptsDoesNotEndTheFollower() = runTest {
|
||||
// Compose ends a scroll of ours by cancelling it: the follower goes on.
|
||||
var after = false
|
||||
yielding { throw CancellationException("a finger took the list") }
|
||||
after = true
|
||||
assertTrue(after)
|
||||
// The follower itself cancelled: it ends.
|
||||
var went = false
|
||||
val follower = launch(start = CoroutineStart.UNDISPATCHED) {
|
||||
yielding { awaitCancellation() }
|
||||
went = true
|
||||
}
|
||||
follower.cancelAndJoin()
|
||||
assertFalse(went)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyTheQueueStartedDoesNotDragAReaderDown() {
|
||||
// The transcript read again after `done` with a `next`: the queued prompt was there, its reply is new.
|
||||
val queued = talk + person("q3")
|
||||
val change = transcriptChange(queued, queued + reply("a3"))
|
||||
assertEquals(TranscriptChange.Appended, change)
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
assertTrue(movesToEnd(change, following = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theInstancesOwnLineIsNotThePersonSending() {
|
||||
val change = transcriptChange(talk, talk + note("n1") + reply("a3"))
|
||||
assertEquals(TranscriptChange.Appended, change)
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anOlderPageNeverMovesToTheEnd() {
|
||||
val older = listOf(person("q0"), reply("a0"))
|
||||
val change = transcriptChange(talk, older + talk)
|
||||
assertEquals(TranscriptChange.Older, change)
|
||||
assertFalse(movesToEnd(change, following = true))
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
// The row that was first keeps its place.
|
||||
assertEquals(2, keptRow(talk, older + talk))
|
||||
assertNull(keptRow(talk, older))
|
||||
assertNull(keptRow(emptyList(), talk))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theFinishedReplyInPlaceOfTheWrittenOneFollowsOnlyAtTheEnd() {
|
||||
val done = talk.dropLast(1) + reply("a2", text = "The whole answer.")
|
||||
val change = transcriptChange(talk, done)
|
||||
assertEquals(TranscriptChange.Changed, change)
|
||||
assertFalse(movesToEnd(change, following = false))
|
||||
assertTrue(movesToEnd(change, following = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aReplyMadeAgainIsNotAMessageSent() {
|
||||
// Regenerate puts a new row where the old reply was; an edit cuts the turns after it.
|
||||
assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk.dropLast(1) + reply("a2b")))
|
||||
assertEquals(TranscriptChange.Appended, transcriptChange(talk, talk.take(1) + reply("a1b")))
|
||||
assertEquals(TranscriptChange.Changed, transcriptChange(talk, talk.take(2)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nothingChangedMovesNothing() {
|
||||
assertEquals(TranscriptChange.None, transcriptChange(talk, talk.toList()))
|
||||
assertEquals(TranscriptChange.None, transcriptChange(talk, emptyList()))
|
||||
assertEquals(TranscriptChange.None, transcriptChange(null, emptyList()))
|
||||
assertFalse(movesToEnd(TranscriptChange.None, following = true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theEndIsTakenUpAgainWhereTheScrollCameToRest() {
|
||||
assertTrue(followsAt(distance = 0, slack = 96))
|
||||
// A line that arrived while the list was settling is still the end.
|
||||
assertTrue(followsAt(distance = 96, slack = 96))
|
||||
assertFalse(followsAt(distance = 97, slack = 96))
|
||||
// The last row not on screen at all.
|
||||
assertFalse(followsAt(distance = Int.MAX_VALUE, slack = 96))
|
||||
// Overscrolled past the end, or a list shorter than its window.
|
||||
assertTrue(followsAt(distance = -24, slack = 96))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.InstanceLogic
|
||||
import eu.llembas.android.auth.Prefs
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
|
||||
class InstanceStoreTest {
|
||||
private val home = Instance(id = "alice@https://home.example", base = "https://home.example", name = "Home", email = "alice", sealedToken = "t1")
|
||||
private val work = Instance(id = "bob@https://work.example", base = "https://work.example", name = "Work", email = "bob", sealedToken = "t2")
|
||||
private val homeAlt = Instance(id = "carol@https://home.example", base = "https://home.example", name = "Home", email = "carol", sealedToken = "t3")
|
||||
|
||||
@Test
|
||||
fun firstAddedBecomesDefaultAndSecondKeepsIt() {
|
||||
val (list1, active1, default1) = InstanceLogic.afterAdd(emptyList(), home, null)
|
||||
assertEquals(listOf(home), list1)
|
||||
assertEquals(home.id, active1)
|
||||
assertEquals(home.id, default1)
|
||||
|
||||
val (list2, active2, default2) = InstanceLogic.afterAdd(list1, work, default1)
|
||||
assertEquals(listOf(home, work), list2)
|
||||
assertEquals(work.id, active2)
|
||||
assertEquals(home.id, default2)
|
||||
|
||||
// Two accounts on the same server keep distinct ids.
|
||||
val (list3, active3, default3) = InstanceLogic.afterAdd(list2, homeAlt, default2)
|
||||
assertEquals(listOf(home, work, homeAlt), list3)
|
||||
assertEquals(homeAlt.id, active3)
|
||||
assertEquals(home.id, default3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun activeFallsBackToDefaultThenFirst() {
|
||||
val all = listOf(home, work)
|
||||
assertEquals(work, InstanceLogic.pickActive(all, work.id, home.id))
|
||||
assertEquals(work, InstanceLogic.pickActive(all, null, work.id))
|
||||
assertEquals(home, InstanceLogic.pickActive(all, "gone", null))
|
||||
assertNull(InstanceLogic.pickActive(emptyList(), home.id, home.id))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removingDefaultOrActivePromotesSurvivingInstance() {
|
||||
val all = listOf(home, work)
|
||||
val (rem1, active1, default1) = InstanceLogic.afterRemove(all, home.id, home.id, home.id)
|
||||
assertEquals(listOf(work), rem1)
|
||||
assertEquals(work.id, active1)
|
||||
assertEquals(work.id, default1)
|
||||
|
||||
val (rem2, active2, default2) = InstanceLogic.afterRemove(all, work.id, work.id, home.id)
|
||||
assertEquals(listOf(home), rem2)
|
||||
assertEquals(home.id, active2)
|
||||
assertEquals(home.id, default2)
|
||||
|
||||
val (rem3, active3, default3) = InstanceLogic.afterRemove(listOf(home), home.id, home.id, home.id)
|
||||
assertEquals(emptyList<Instance>(), rem3)
|
||||
assertNull(active3)
|
||||
assertNull(default3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun perInstancePrefsStayIsolated() {
|
||||
val base = Prefs(assistantModel = "legacy-model", lastAssistChat = "legacy-chat")
|
||||
// Unknown instance falls back to legacy flat fields.
|
||||
assertEquals("legacy-model", base.forInstance(home.id).assistantModel)
|
||||
|
||||
val updated = base
|
||||
.withInstance(home.id) { it.copy(assistantModel = "fast-home", lastAssistChat = "c-home") }
|
||||
.withInstance(work.id) { it.copy(assistantModel = "fast-work", lastAssistChat = "c-work") }
|
||||
assertEquals("fast-home", updated.forInstance(home.id).assistantModel)
|
||||
assertEquals("c-home", updated.forInstance(home.id).lastAssistChat)
|
||||
assertEquals("fast-work", updated.forInstance(work.id).assistantModel)
|
||||
assertEquals("c-work", updated.forInstance(work.id).lastAssistChat)
|
||||
|
||||
val cleaned = updated.withoutInstance(home.id)
|
||||
assertEquals("fast-work", cleaned.forInstance(work.id).assistantModel)
|
||||
assertEquals("legacy-model", cleaned.forInstance(home.id).assistantModel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.FileExists
|
||||
import eu.llembas.android.api.LembasJson
|
||||
import eu.llembas.android.api.McpServerList
|
||||
import eu.llembas.android.api.MediaJob
|
||||
import eu.llembas.android.api.MediaJobList
|
||||
import eu.llembas.android.api.MediaView
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.ModelList
|
||||
import eu.llembas.android.api.Raw
|
||||
import eu.llembas.android.api.ToolCall
|
||||
import eu.llembas.android.api.forChat
|
||||
import eu.llembas.android.api.signInAddress
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.builtins.ListSerializer
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
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.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Generated media, its jobs, a new file that must be new, what a model is for and the MCP
|
||||
* servers, as the pinned contract has them and as the client asks for them.
|
||||
*/
|
||||
class MediaContractTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
private fun contract(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) {
|
||||
"contract/$name.json is missing"
|
||||
}.readText()
|
||||
|
||||
@Test
|
||||
fun aCallCarriesItsFileOrItsJob() {
|
||||
val calls = LembasJson.parseToJsonElement(contract("tool_media")).jsonObject.getValue("calls")
|
||||
val (picture, video) = LembasJson.decodeFromJsonElement(ListSerializer(ToolCall.serializer()), calls)
|
||||
// A picture is an attachment as before, and a file of the tree as well.
|
||||
assertEquals("att1", picture.image!!.id)
|
||||
val media = picture.media!!
|
||||
assertEquals(MediaView.Picture, media.view)
|
||||
assertEquals("node8", media.nodeId)
|
||||
assertEquals("/home/frodo/Generated/image-20260102-030405.png", media.path)
|
||||
assertEquals("image-20260102-030405.png", media.title)
|
||||
assertEquals(180_000L, media.size)
|
||||
assertEquals(1024, media.width)
|
||||
assertEquals(0.0, media.seconds, 0.0)
|
||||
assertNull(picture.mediaJob)
|
||||
// A video is a job: the call says which, and that it was running when it returned.
|
||||
assertNull(video.media)
|
||||
assertNull(video.image)
|
||||
val job = MediaJob.of(video.mediaJob!!)
|
||||
assertEquals("mjob1", job.id)
|
||||
assertEquals("video", job.kind)
|
||||
assertTrue(job.underWay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theCardIsChosenByWhatWasAskedFor() {
|
||||
fun view(kind: String) = LembasJson.decodeFromString(eu.llembas.android.api.GeneratedMedia.serializer(), """{"kind":"$kind"}""").view
|
||||
assertEquals(MediaView.Picture, view("image"))
|
||||
assertEquals(MediaView.Picture, view("image_edit"))
|
||||
assertEquals(MediaView.Video, view("video"))
|
||||
assertEquals(MediaView.Sound, view("music"))
|
||||
assertEquals(MediaView.Details, view("model3d"))
|
||||
// A kind this app does not know is a file with details, never something played or drawn.
|
||||
assertEquals(MediaView.Details, view("hologram"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aJobUnderWayDoneAndFailed() {
|
||||
val running = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job"))
|
||||
assertTrue(running.underWay)
|
||||
assertFalse(running.unsuccessful)
|
||||
assertEquals(42.0, running.seconds, 0.0)
|
||||
assertNull(running.result)
|
||||
assertFalse(running.told)
|
||||
|
||||
val done = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_done"))
|
||||
assertFalse(done.underWay)
|
||||
assertFalse(done.unsuccessful)
|
||||
assertEquals(MediaView.Video, done.result!!.view)
|
||||
assertEquals("node7", done.result!!.nodeId)
|
||||
assertEquals(5.0, done.result!!.seconds, 0.0)
|
||||
assertEquals(0.1, done.cost!!.amount, 1e-9)
|
||||
assertTrue(done.told)
|
||||
|
||||
val failed = LembasJson.decodeFromString(MediaJob.serializer(), contract("media_job_failed"))
|
||||
assertTrue(failed.unsuccessful)
|
||||
assertEquals("ComfyUI ran out of video memory in KSampler.", failed.error)
|
||||
|
||||
assertEquals(listOf("running", "done", "failed"), LembasJson.decodeFromString(MediaJobList.serializer(), contract("media_jobs")).jobs.map { it.state })
|
||||
// A state this app does not know ends the following unless the server says it is still active.
|
||||
assertFalse(MediaJob(id = "j", state = "paused").underWay)
|
||||
assertTrue(MediaJob(id = "j", state = "paused", active = true).underWay)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theJobsAreAskedForReadAndCancelled() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(contract("media_jobs")))
|
||||
assertEquals(3, api.mediaJobs("chat1").size)
|
||||
assertEquals("/api/v2/media/jobs?chat_id=chat1", server.takeRequest().path)
|
||||
server.enqueue(MockResponse().setBody(contract("media_jobs")))
|
||||
api.mediaJobs("chat1", active = true)
|
||||
assertEquals("/api/v2/media/jobs?chat_id=chat1&active=true", server.takeRequest().path)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("media_job")))
|
||||
assertEquals("mjob1", api.mediaJob("mjob1").id)
|
||||
val read = server.takeRequest()
|
||||
assertEquals("GET", read.method)
|
||||
assertEquals("/api/v2/media/jobs/mjob1", read.path)
|
||||
assertEquals("Bearer lmb_test", read.getHeader("Authorization"))
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("media_job_failed")))
|
||||
assertEquals("failed", api.cancelMediaJob("mjob3").state)
|
||||
val cancel = server.takeRequest()
|
||||
assertEquals("DELETE", cancel.method)
|
||||
assertEquals("/api/v2/media/jobs/mjob3", cancel.path)
|
||||
|
||||
// Somebody else's job, or one that is gone: the server's sentence.
|
||||
server.enqueue(MockResponse().setResponseCode(404).setBody("""{"detail":"That job no longer exists."}"""))
|
||||
try {
|
||||
api.mediaJob("mjob9")
|
||||
fail("a 404 is no job")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals("That job no longer exists.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun bytesAreAskedForByPathByVersionByNodeAndByAttachment() {
|
||||
val api = client()
|
||||
fun path(what: Raw, inline: Boolean = false) = api.raw(what, inline = inline).url.let { it.encodedPath + "?" + it.encodedQuery }
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.mp4", path(Raw.Path("/home/frodo/a.mp4")))
|
||||
assertEquals("/api/v2/files/raw?path=%2Fhome%2Ffrodo%2Fa.md&version=ver3", path(Raw.Path("/home/frodo/a.md", "ver3")))
|
||||
assertEquals("/api/v2/files/raw?node=node7&inline=1", path(Raw.Node("node7"), inline = true))
|
||||
assertEquals("/api/v2/attachments/att1", api.raw(Raw.Attached("att1")).url.encodedPath)
|
||||
// The token is in the header of each, and in the address of none.
|
||||
for (what in listOf(Raw.Path("/a"), Raw.Node("node7"), Raw.Attached("att1"))) {
|
||||
val request = api.raw(what, range = 0L..9L)
|
||||
assertEquals("Bearer lmb_test", request.header("Authorization"))
|
||||
assertEquals("bytes=0-9", request.header("Range"))
|
||||
assertFalse(request.url.toString().contains("lmb_test"))
|
||||
}
|
||||
// A piece of a file by its id is the same Range request a piece by its path is.
|
||||
server.enqueue(MockResponse().setResponseCode(206).setBody("0123456789"))
|
||||
assertEquals("0123456789", api.rawBytes(Raw.Node("node7"), 10, 19).toString(Charsets.UTF_8))
|
||||
val piece = server.takeRequest()
|
||||
assertEquals("/api/v2/files/raw?node=node7", piece.path)
|
||||
assertEquals("bytes=10-19", piece.getHeader("Range"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aNewFileIsNeverWrittenOverAnother() = runTest {
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setResponseCode(201).setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/new.md", "", create = true)
|
||||
val said = server.takeRequest().body.readUtf8()
|
||||
assertTrue(said, said.contains("\"create\":true"))
|
||||
assertFalse(said, said.contains("base"))
|
||||
|
||||
server.enqueue(MockResponse().setResponseCode(409).setBody(contract("file_create_exists")))
|
||||
try {
|
||||
api.saveFile("/home/frodo/lembas.md", "", create = true)
|
||||
fail("a name that is taken makes no file")
|
||||
} catch (e: FileExists) {
|
||||
assertEquals("There is already something called lembas.md here.", e.message)
|
||||
}
|
||||
server.takeRequest()
|
||||
// A save that is not a new file does not say `create`.
|
||||
server.enqueue(MockResponse().setBody(contract("file_content")))
|
||||
api.saveFile("/home/frodo/lembas.md", "x", base = "abab")
|
||||
assertFalse(server.takeRequest().body.readUtf8().contains("create"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyAModelToChatWithIsOffered() = runTest {
|
||||
// The pinned lists say `chat` for every model; a list that named another kind loses it here.
|
||||
assertTrue(LembasJson.decodeFromString(ModelList.serializer(), contract("models")).models.all { it.capability == "chat" && it.forChat })
|
||||
val mixed = """{"models": [
|
||||
{"id": "qwen", "capability": "chat"},
|
||||
{"id": "embedder", "capability": "embedding"},
|
||||
{"id": "painter", "capability": "image"},
|
||||
{"id": "old"},
|
||||
{"id": "novel", "capability": "something-new"}], "subagents_cap": 4}"""
|
||||
val list = LembasJson.decodeFromString(ModelList.serializer(), mixed)
|
||||
assertEquals(listOf("qwen", "old"), list.models.forChat().map { it.id })
|
||||
assertEquals(listOf("qwen", "old"), list.forChat().models.map { it.id })
|
||||
assertEquals(4, list.forChat().subagentsCap)
|
||||
// What the pickers and the assistant's setting are filled from is already narrowed.
|
||||
val api = client()
|
||||
server.enqueue(MockResponse().setBody(mixed))
|
||||
assertEquals(listOf("qwen", "old"), api.models().map(ModelInfo::id))
|
||||
server.enqueue(MockResponse().setBody(mixed))
|
||||
assertEquals(listOf("qwen", "old"), api.agentModelList("dev1").models.map(ModelInfo::id))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theMcpServersAndWhoHasToSignIn() = runTest {
|
||||
val servers = LembasJson.decodeFromString(McpServerList.serializer(), contract("mcp_servers")).servers
|
||||
assertEquals(listOf("Tracker", "Mail", "Notes", "Wiki"), servers.map { it.label })
|
||||
assertEquals(listOf("ready", "signed_in", "signed_out", "needs_signin"), servers.map { it.auth.state })
|
||||
assertEquals(listOf(false, false, true, true), servers.map { it.auth.needsSignIn })
|
||||
assertEquals("frodo@example.org", servers[1].auth.account)
|
||||
assertTrue(servers[1].auth.renews)
|
||||
// One's own sign-in has a page; a shared one has none for a person who is no administrator.
|
||||
assertEquals("https://lembas.example.org/settings/mcp/mcp3/sign-in", servers[2].auth.signinUrl)
|
||||
assertTrue(servers[3].auth.shared)
|
||||
assertNull(servers[3].auth.signinUrl)
|
||||
|
||||
server.enqueue(MockResponse().setBody(contract("mcp_servers")))
|
||||
assertEquals(4, client().mcpServers().size)
|
||||
assertEquals("/api/v2/mcp", server.takeRequest().path)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aSignInOpensAPageOfTheInstanceAndNothingElse() {
|
||||
val base = "https://lembas.example.org"
|
||||
val page = "/settings/mcp/mcp3/sign-in"
|
||||
assertEquals(base + page, signInAddress(base, base + page))
|
||||
assertEquals(base + page, signInAddress(base, page))
|
||||
assertEquals(base + page, signInAddress("$base/", page))
|
||||
// The instance named itself otherwise (another name, another port): the same page, on the instance the app knows.
|
||||
assertEquals(base + page, signInAddress(base, "https://other.example.net$page"))
|
||||
assertEquals("$base$page?x=1", signInAddress(base, "http://lembas.example.org:8080$page?x=1"))
|
||||
assertEquals("http://lembas.example.org:8080$page", signInAddress("http://lembas.example.org:8080", "http://lembas.example.org:8080$page"))
|
||||
// Nothing that is not a page, and never a host hidden in a path or before an @.
|
||||
assertNull(signInAddress(base, null))
|
||||
assertNull(signInAddress(base, " "))
|
||||
assertNull(signInAddress(base, "javascript:alert(1)"))
|
||||
assertNull(signInAddress(base, "intent://settings#Intent;end"))
|
||||
assertEquals("$base/settings", signInAddress(base, "//other.example.net/settings"))
|
||||
assertEquals("$base/settings", signInAddress(base, "https://lembas.example.org@other.example.net/settings"))
|
||||
// The app's token is in none of them: there is no place for one.
|
||||
assertFalse(signInAddress(base, base + page)!!.contains("token"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package eu.llembas.android
|
||||
|
||||
import eu.llembas.android.api.ApiClient
|
||||
import eu.llembas.android.api.ApiException
|
||||
import eu.llembas.android.api.Chat
|
||||
import eu.llembas.android.api.MediaFor
|
||||
import eu.llembas.android.api.ModelInfo
|
||||
import eu.llembas.android.api.refusal
|
||||
import eu.llembas.android.ui.chat.ChatState
|
||||
import eu.llembas.android.ui.chat.Draft
|
||||
import eu.llembas.android.ui.chat.MEDIA_DICTATION
|
||||
import eu.llembas.android.ui.chat.MEDIA_SPEECH
|
||||
import eu.llembas.android.ui.chat.fallbackToSay
|
||||
import eu.llembas.android.ui.chat.mediaFor
|
||||
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.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Speech follows the chat's model (server 2.0.0-beta.15): a transcription or a speech request
|
||||
* says which chat it is for -- `chat_id`, or `chat_model` before the chat exists -- and never
|
||||
* both; another app's dictation says neither.
|
||||
*/
|
||||
class MediaForTest {
|
||||
private lateinit var server: MockWebServer
|
||||
|
||||
@Before
|
||||
fun up() {
|
||||
server = MockWebServer().apply { start() }
|
||||
}
|
||||
|
||||
@After
|
||||
fun down() = server.shutdown()
|
||||
|
||||
private fun client() = ApiClient(server.url("/").toString().trimEnd('/'), "lmb_test")
|
||||
|
||||
@Test
|
||||
fun aChatThatExistsIsNamedByItsIdAlone() {
|
||||
assertEquals(MediaFor(chatId = "c1"), MediaFor.of("c1", "shire/pippin"))
|
||||
assertEquals(MediaFor(chatModel = "shire/pippin"), MediaFor.of(null, "shire/pippin"))
|
||||
assertEquals(MediaFor(chatModel = "shire/pippin"), MediaFor.of(" ", "shire/pippin"))
|
||||
assertEquals(MediaFor.DEFAULT, MediaFor.of(null, null))
|
||||
assertEquals(MediaFor.DEFAULT, MediaFor.of("", " "))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theTranscriptionFieldsSayWhichChat() {
|
||||
assertEquals(listOf("chat_id" to "c1"), ApiClient.transcriptionFields(null, MediaFor.of("c1", "shire/pippin")))
|
||||
assertEquals(
|
||||
listOf("language" to "sk", "chat_model" to "shire/pippin"),
|
||||
ApiClient.transcriptionFields("sk", MediaFor.of(null, "shire/pippin")),
|
||||
)
|
||||
assertEquals(emptyList<Pair<String, String>>(), ApiClient.transcriptionFields(null, MediaFor.DEFAULT))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theSpeechBodySaysWhichChat() {
|
||||
val inChat = ApiClient.speechBody("Hello", MediaFor.of("c1", "shire/pippin")).toString()
|
||||
assertTrue(inChat, inChat.contains("\"chat_id\":\"c1\""))
|
||||
assertFalse(inChat, inChat.contains("chat_model"))
|
||||
assertTrue(inChat, inChat.contains("\"input\":\"Hello\""))
|
||||
val before = ApiClient.speechBody("Hello", MediaFor.of(null, "shire/pippin")).toString()
|
||||
assertTrue(before, before.contains("\"chat_model\":\"shire/pippin\""))
|
||||
assertFalse(before, before.contains("chat_id"))
|
||||
val none = ApiClient.speechBody("Hello", MediaFor.DEFAULT).toString()
|
||||
assertFalse(none, none.contains("chat_"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTranscriptionCarriesTheChatAndReadsTheFallback() = runTest {
|
||||
server.enqueue(
|
||||
MockResponse().setBody("""{"text":"Second breakfast"}""")
|
||||
.setHeader("X-Lembas-Source", "Bree%20%2B%20Inn").setHeader("X-Lembas-Fallback", "1"),
|
||||
)
|
||||
val heard = client().transcribe(ByteArray(64), media = MediaFor.of("c1", null))
|
||||
assertEquals("Second breakfast", heard.text)
|
||||
assertEquals("Bree + Inn", heard.fallback)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/v1/audio/transcriptions", request.path)
|
||||
val body = request.body.readUtf8()
|
||||
assertTrue(body, body.contains("name=\"chat_id\""))
|
||||
assertFalse(body, body.contains("chat_model"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun anotherAppsDictationNamesNoChat() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"text":"Elevenses"}""").setHeader("X-Lembas-Source", "stt%2Fsmall"))
|
||||
val heard = client().transcribe(ByteArray(64))
|
||||
assertEquals("Elevenses", heard.text)
|
||||
// The source is named, and it is the one expected: nothing to say.
|
||||
assertNull(heard.fallback)
|
||||
val body = server.takeRequest().body.readUtf8()
|
||||
assertFalse(body, body.contains("chat_id"))
|
||||
assertFalse(body, body.contains("chat_model"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun speechCarriesTheModelOfAChatNotMadeYet() = runTest {
|
||||
server.enqueue(MockResponse().setBody("mp3"))
|
||||
val spoken = client().speech("Hello", MediaFor.of(null, "shire/pippin"))
|
||||
// An older server names no source at all.
|
||||
assertNull(spoken.fallback)
|
||||
assertEquals(3, spoken.audio.size)
|
||||
val request = server.takeRequest()
|
||||
assertEquals("/v1/audio/speech", request.path)
|
||||
assertTrue(request.body.readUtf8().contains("\"chat_model\":\"shire/pippin\""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusedTranscriptionSaysTheServersSentence() = runTest {
|
||||
// `/v1` refuses in OpenAI's shape, not `/api/v2`'s `detail`.
|
||||
server.enqueue(
|
||||
MockResponse().setResponseCode(502)
|
||||
.setBody("""{"error":{"message":"The speech model did not answer.","type":"upstream_error","code":502}}"""),
|
||||
)
|
||||
try {
|
||||
client().transcribe(ByteArray(64), media = MediaFor.of("c1", null))
|
||||
fail("a 502 is a refusal")
|
||||
} catch (e: ApiException) {
|
||||
assertEquals(502, e.status)
|
||||
assertEquals("The speech model did not answer.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aRefusalIsReadInBothShapes() {
|
||||
assertEquals("No.", refusal("""{"detail":"No."}"""))
|
||||
assertEquals("Too long.", refusal("""{"error":{"message":"Too long.","code":413}}"""))
|
||||
assertNull(refusal("""{"error":"plain"}"""))
|
||||
assertNull(refusal("<html>Bad gateway</html>"))
|
||||
assertNull(refusal(""))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFallbackIsNamedOnlyWhenTheServerSaysBoth() {
|
||||
assertEquals("Bree", ApiClient.fallbackSource("1", "Bree"))
|
||||
assertNull(ApiClient.fallbackSource(null, "Bree"))
|
||||
assertNull(ApiClient.fallbackSource("1", null))
|
||||
assertNull(ApiClient.fallbackSource("0", "Bree"))
|
||||
// A name that is not percent-encoding stays as it came.
|
||||
assertEquals("100%", ApiClient.fallbackSource("1", "100%"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theChatScreenNamesItsChatOrTheModelItWillBeOn() {
|
||||
val models = listOf(ModelInfo(id = "pippin", ref = "shire/pippin", default = true), ModelInfo(id = "merry", ref = "buckland/merry"))
|
||||
assertEquals(MediaFor(chatModel = "shire/pippin"), ChatState(models = models).mediaFor)
|
||||
assertEquals(MediaFor(chatModel = "buckland/merry"), ChatState(models = models, draft = Draft(model = "buckland/merry")).mediaFor)
|
||||
assertEquals(MediaFor(chatId = "c1"), ChatState(models = models, chat = Chat(id = "c1", model = "merry")).mediaFor)
|
||||
assertEquals(MediaFor.DEFAULT, ChatState().mediaFor)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFallbackIsSaidOncePerKind() {
|
||||
assertTrue(fallbackToSay(emptySet(), MEDIA_DICTATION))
|
||||
assertFalse(fallbackToSay(setOf(MEDIA_DICTATION), MEDIA_DICTATION))
|
||||
assertTrue(fallbackToSay(setOf(MEDIA_DICTATION), MEDIA_SPEECH))
|
||||
}
|
||||
}
|
||||
Loaded 100 of 192 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user