Compare commits

...
Author SHA1 Message Date
HomerandClaude Fable 5.2 4344b35a27 1.0.0-beta.10: contract and tokens pinned from LLeMbas v2.0.0-beta.13
Release / release (push) Canceled after 0s
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 16:15:51 +00:00
HomerandClaude Fable 5.2 6540d160df Locked means nothing to the instance; the lock is followed; no question by intent
CI / check (push) Canceled after 0s
Review M1, M2, M3, S1, S4, S5, S6 and the notes.

M1. While the phone is locked nothing goes to the instance from the sheet.
The controller asks the keyguard itself: ask() holds instead of asking,
the recording is not written down while it runs, and a question heard with
the instance's speech-to-text waits on the phone as a recording ("Question
heard", no words) to be written down and asked on unlock. me() and models()
wait for the unlock too; the microphone opens without them.

M2. The screen going off stops the microphone and the voice whatever the
lock says, and takes the conversation out of the last frame; found locked
(then, or on the way back) the controller drops the listening, stops
following the answer and ends the conversation. No answer is read aloud and
no conversation goes on over the lock. The screen stays on while speaking.

M3. AssistActivity is exported and believed its extras. A handed-over
question now waits in process memory (AssistHandOff) and the intent carries
a one-time ticket; ACTION_LISTEN, ACTION_CONTINUE, EXTRA_LISTEN, EXTRA_WAKE
and the ticket count only on an intent with the app's own mark (OwnIntents:
a random value kept in private storage, carried by the widget's and the
shortcuts' intents). Android's VOICE_COMMAND actions stay public.

S1 Recorder.stopNow() for close(). S4 the activity handles configuration
changes itself, take() runs once, a held question is saved. S5 a typed
question replaces the held one before the unlock is asked for, so one is
asked once. S6 the recogniser's "speech began" and loud level reach the
watch. Notes: no failure text over the lock, Share checks the model still
exists, USER_PRESENT re-reads the keyguard.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 15:42:04 +00:00
HomerandClaude Fable 5.2 a4a5c5dba1 End of speech: digital silence is a pause, a steady voice is not the room
Review S2, S3, S6.

A zero level after sound was skipped as "no microphone yet", so speech into
a headset that gates its noise to exact zeros never counted a pause and ran
to the limit. Once a floor is known a zero tick is quiet.

Listening that began in the middle of a sentence with shallow dips let the
floor creep up to the voice: no speech was ever seen and it gave up as
"nothing said" while the person talked. The floor now rises only in calm
moments (the last half second within half again of itself), a first sound
louder than any room is kept as a guess until a dip or a calm moment shows
the room, and sound that stays above the floor without being steady is
speech. Words count as speech from four ticks above the room, not two.

phoneWatch takes how long ago the recogniser last gave a sign of somebody
speaking: no words is no longer "nothing said" while it reports speech.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 15:42:04 +00:00
HomerandClaude Fable 5.2 cdb6a35371 Settings: the wake word and the hands-free assistant are marked Experimental
CI / check (push) Canceled after 0s
An "Experimental" label on the Wake word group and on the assistant's
"Start listening when the assistant opens" and "Keep a spoken conversation
going", each with one plain line about what may go wrong. The same in the
changelog and the README.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:31:25 +00:00
HomerandClaude Fable 5.2 5e45293462 Wake word with the screen off: the sheet stays over the lock screen and listens
CI / check (push) Canceled after 0s
A phone whose screen is off is locked. AssistActivity.take() sent every
locked opening through requestDismissKeyguard and finished the activity on
onDismissCancelled / onDismissError -- which is Android's answer when nobody
unlocks. So the wake word lit the screen, showed the sheet, and closed it.

lockedStart() decides now: a way in that means to speak (the wake word, a
headset's button) stays and listens; what is heard is held in the state
(waiting), shown as the person's own question with "Unlock to send", and
Android is asked to unlock at once. Not unlocking leaves the sheet as it is.
The question is asked on unlock (the dismiss callback or USER_PRESENT). The
other locked openings ask to unlock first, as before.

Nothing from the account over the lock screen still holds, and a little more
than before: turns that were on the sheet when the phone locked are not
drawn while it is locked (onStart reads the keyguard again), and a sheet
over the lock screen goes when the screen goes off. The screen is kept on
while it listens or works.

The session (screen on, locked) listens over the lock screen as well and
hands what it heard to the activity.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:30:41 +00:00
HomerandClaude Fable 5.2 7ca44ef5e2 Settings: the assistant's model, and it holds for every new chat
CI / check (push) Canceled after 0s
Settings › Assistant › Assistant model: "Instance default" or one of the
instance's models, saved as the existing assistantModel preference.

The controller keeps the model for new chats apart from the model of the
chat the sheet is in: New chat after "Continue the last chat" goes back to
it, a change in Settings reaches a sheet that is still alive, and a question
asked before the model list was read waits for it (and falls back to the
saved choice, not to the instance's default, when the list cannot be read).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:17:27 +00:00
HomerandClaude Fable 5.2 2f43b94e56 Listening ends by the room's own level, not by two fixed ones
CI / check (push) Canceled after 0s
The sheet's end of speech (instance speech-to-text) was "level >= 0.02 is
speech, level < 0.01 is quiet". A room between the two never counted as a
pause, so once anything had counted as speech it listened to the 120 s limit;
and words the speech-to-text made of silence counted as speech too.

EndOfSpeech follows the noise floor (the quietest of the last two seconds,
down at once, up slowly) and judges speech and pause against it: three loud
ticks in eight begin speech, 1.5 s back near the floor end it, nothing said
gives up after 5 s, words count only when the microphone heard something
above the room, and the limit is 60 s. Tested with level sequences.

The recording is not written down before anything was heard. The phone's
recogniser gets the silence extras and a watch for one that never calls
back; the recognition service ends at the pause instead of always at 15 s.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 14:13:37 +00:00
HomerandClaude Fable 5.2 472aff6b22 LLeMbas for Android 1.0.0-beta.9: pinned to LLeMbas 2.0.0-beta.12
Release / release (push) Canceled after 0s
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 12:16:45 +00:00
HomerandClaude Fable 5.2 f9cca74af5 Which fence is a page is the server's to say; the build's missing constant
CI / check (push) Canceled after 0s
- A closed step and a report are drawn from the server's text, where a page
  is the one line "[page: Title]" (the card). An `html-view` fence the
  server does not list -- written while pages were not offered -- is the
  code block it is. Only the open step of a reply as it streams takes the
  fence for a page, so that a page being written is not source scrolling by.
- The events' reports frame carries latest_created; a report its pages.
- FEATURE_VOICE_RECOGNIZERS is not in the SDK for apps: the feature is
  asked for by its name (CI run 88 failed to compile on it).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 11:42:48 +00:00
HomerandClaude Fable 5.2 af290cd7d5 Review: a report's conversation, ids from outside, the form's notify, the drawer, the channels
CI / check (push) Canceled after 0s
Contract at server dev 40813d1 (84 files): a chat's `controls` and `report`,
a text step's `pages` and `text`, a report's `schedule_title`.

- B1 (must): a `user` row the server wrote (`machine`) is never the person's
  bubble -- a quiet note; in a report's conversation the first such line is
  left out. A report chat's bar takes its title from the chat's own `report`
  (so it survives the app being closed), and its menu offers only what
  `controls` allows.
- A1: ids from a push payload or an intent extra pass `safeId`
  (^[A-Za-z0-9_-]{1,64}$) before they become a route: chat, schedule, run,
  report.
- C1-C3: an empty "When..." is sent empty (the server's default) and the
  field shows the default as a placeholder; editing sends `notify` only once
  the schedule was read or the person chose, and a failed read says so and
  disables Save.
- B2: Reports is in the drawer only where the instance has the route.
- A text step with pages is drawn from the server's `text`; a report from
  its `text`. A fence with a space before `html-view` is a code block, as
  the spec has it.
- A push of a kind the app does not know shows nothing. An important report
  uses a channel of high importance. A report read or deleted in the app
  cancels its notification.
- stop() and compact() post an empty body again: a search-and-replace in
  adc1c4f had changed them to "{}" by mistake.

One commit: the model, the screens and the push share these files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 11:38:14 +00:00
HomerandClaude Fable 5.2 24669b7cd6 Wake word: the wake runs outside the loop it pauses; what Android says is recorded
CI / check (push) Canceled after 0s
Review W1 (must): wake() was a suspend function run inside the hearing job,
and its own first step -- holding the microphone for the sheet -- paused the
listener, which cancelled that job: no wait for the sheet, no fallback, and
no "Last wake" record for a real wake.

- WakeListener hands `heard` to the scope beside the listening, so a pause
  never cancels the answer (test: a suspending heard that pauses the plan).
  The service runs the wake on the app's own scope, one at a time, holds the
  microphone for the whole attempt, and writes the record NonCancellable.
- WakeOpener holds the order of what is tried, apart from Android, with
  tests: wait up to 1 s for the connection when Android says the service is
  active; "opened" only once a sheet says it is up; a session that was not
  refused gets a second wait before anything else is shown (W3: never two
  sheets -- and the session closes a sheet the wake word opened in its
  place); the activity counts only where Android will start it.
- The record gains isActiveService, FEATURE_VOICE_RECOGNIZERS, screen,
  keyguard, app visible, ms until the sheet, the service's onCreate and
  onDestroy times, onPrepareToShowSession / onShowSessionFailed (API 34+),
  and whether the connection was waited for. Settings says when the role is
  held but Android does not use LLeMbas as its voice assistant.
- AssistLink.shutdown is guarded by instance. W2: a session counts as up
  once per show; the activity from onStart to onStop. W4: the activity says
  it is up from onStart and onNewIntent, and turns the screen on there too.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 11:32:31 +00:00
HomerandClaude Fable 5.2 80ba7f70b9 Wake word: what it tried and how it went is kept and shown; the screen comes on
CI / check (push) Canceled after 0s
The phrase was heard, LLeMbas was the assistant, and still only "Heard you.
Tap to ask." came: wake() reached the notification when the assistant
service was not connected or showSession threw, and kept neither reason.

- WakeAttempt: when, the phrase, the way tried (wakeWay: session, the
  sheet's activity through the assistant service when the screen is off,
  the activity while the app is on screen, a notification), the outcome
  (opened / not connected / refused with the exception / no sheet came),
  the fallback, whether the role was held, and when Android last connected
  and disconnected the service in this process. The last five live in the
  settings, are logged under LLeMbasWake, and are shown as "Last wake".
  An attempt that found the service not connected is told when a later
  onReady arrives.
- "Opened" is counted only once a sheet says it is up (AssistLink.shown,
  2.5 s); otherwise the fallback follows.
- Settings says when LLeMbas holds the role but the service is not
  connected, with the way to the system's assistant setting.
- The sheet opened by the wake word turns the screen on: setTurnScreenOn on
  the activity; with the screen off and the service connected the activity
  is started through the service instead of a session, whose window wakes
  nothing.
- The fallback notification says "Could not open by itself -- tap to ask"
  when LLeMbas is the assistant.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 10:30:02 +00:00
HomerandClaude Fable 5.2 613eba4154 Contract at server dev ee74edc: the reports routes, pinned
CI / check (push) Canceled after 0s
79 files; the provisional shapes held, with these taken from the fixtures:

- GET /reports carries `unread`, the count the drawer's badge shows
  (ApiClient.unreadReports); GET /reports/{id} answers {report: ...} with
  `text` (the body with each page as its one line), which Share uses.
- A schedule carries `notify_default`, the default condition in the
  account's language: what "When..." starts from and what the task's page
  says while the person wrote none.
- The events' `reports` frame (unread, newest) has its model; nothing
  follows it yet.
- push_schedule.json is gone (a finished run sends a report's push now);
  the test of an older server's payload keeps it written out.
- ReportsContractTest reads reports, report, report_reply, push_report and
  event_reports; ScheduleContractTest follows the new values (notify
  "when", the run's note and report, the frame's version).

Tokens and strings are unchanged at this ref.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 10:10:02 +00:00
HomerandClaude Fable 5.2 ca1ace2987 "Notify when" is offered and sent only where the instance has Reports
CI / check (push) Canceled after 0s
An instance before 2.0.0-beta.12 knows other values for notify and would
refuse the new ones; the form asks for the reports route first.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:57:34 +00:00
HomerandClaude Fable 5.2 dcd5adf491 A report's push: its words are in the payload's notification
CI / check (push) Canceled after 0s
The payload's top says only the app's name and "New report"; the title,
the summary and the importance are read from its notification, and from
the top only where there is none.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:56:15 +00:00
HomerandClaude Fable 5.2 adc1c4fe3e Reports, "notify when", report notifications, and a page as a card (spec 3.8.0)
CI / check (push) Canceled after 0s
Built against the provisional /api/v2 shapes of the round's brief; the
server's fixtures are pinned when its reports routes are on its dev.

- Reports in the drawer with an unread badge; routes reports and
  report/{id}. The list: unread first, title, the schedule's name, when,
  importance marked; pull to refresh; swipe to mark read or to delete (asks
  once). A report reads as a page (Markdown as the chat draws it) and is
  marked read on open; Share hands over its text; Reply asks the server for
  the report's chat and opens the ordinary chat screen entered from the
  report: "Report: <title>" in the bar, Back to the report, never added to
  the chats list.
- Scheduled: "Notify when" on the form -- Every run / When... (the default
  prefilled) / Never, each with its line; sent as notify and notify_when. A
  run shows its note and a row to its report; the run's chat stays openable.
- Push kind `report`: a Reports channel; unlocked the title and summary,
  on the lock screen only the app's name and "New report"; tap and Open go
  to the report, Mark read needs the phone unlocked. `schedule` and
  `schedule_failed` from an older server are handled as before.
- A page in an answer (an html-view fence, the server's "[page: Title]"
  line, or a `page` step) is one quiet card; no web view, never the source,
  in a chat and in a report. Copy and Share take the one-line projection.
- An id that may come as a string or as an object (a report's chat, a run's
  report) is read either way.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-13 09:38:58 +00:00
91 changed files with 5824 additions and 391 deletions

No files matched your search

+144
View File
@@ -3,6 +3,150 @@
What changed in each release of LLeMbas for Android. Versions follow SemVer; until 1.0.0 the app
is in alpha and releases come off `main`.
## [Unreleased]
## [1.0.0-beta.10] — 2026-11-13
### Added
- **Assistant model** in Settings › Assistant: the model the assistant's new chats start on --
*Instance default* (your account's default, as before) or any model of the instance. A large
default model is slow to answer a spoken question; a quick one can be chosen for the assistant
alone. It holds for every way in: the sheet, the wake word, Share. Picking a model in the
sheet still changes it too.
### Changed
- **The wake word and the hands-free parts of the voice assistant are marked Experimental** in
Settings: the wake word as a whole, and with the assistant *Start listening when the
assistant opens* and *Keep a spoken conversation going*. They are new and have been tried on
few phones: the wake word may miss the phrase, start by mistake, or hear you and still not
open the assistant; listening may stop too early or too late. Typing a question and the
microphone button are the parts to rely on.
### Fixed
- **The wake word with the screen off: the sheet showed for a moment and was gone.** A phone
whose screen is off is locked, and a sheet opened over the lock screen asked Android to unlock
first and closed itself when that was turned down -- which is what happens when nobody is
there to unlock. Opened to listen (the wake word, a headset's button), the sheet now stays up
over the lock screen and listens, and Android is asked to unlock once it has heard you: a face
or a fingerprint sends the question. Leave it, and it stays until the screen goes off.
- **Nothing goes to your instance while the phone is locked.** Not the question, not the
recording, not even "which models are there". With Voice input › LLeMbas the question waits on
the phone as a recording -- the sheet says *Question heard*, with no words, and **Unlock to
send** -- and is written down and asked once you unlock. With Voice input › Phone the phone's
own recogniser writes it down (the recording goes wherever that recogniser sends it, as
always) and the words are shown while they wait. No answer is shown or spoken over the lock
screen, and an answer over the lock screen is not offered.
- **A phone that locks while the assistant is open stops there.** The screen going off stops the
microphone and the voice at once; a question still being listened to is dropped; an answer is
no longer read aloud on a locked phone, a spoken conversation does not go on, and the
conversation that was on the sheet is not readable over the lock screen -- nor a failure's
words, which may name the instance. The screen stays on while an answer is read aloud.
- **Another app can no longer put a question into the assistant.** The
sheet's screen has to be startable by Android (the assist action, a headset's button), so any
app can start it. A question handed from the assistant's own sheet no longer travels in the
intent, where any app could have written one to be asked on your account (or to wait for your
next unlock): it stays in the app's memory and the intent carries a one-time ticket. Opening
listening, the last chat and turning the screen on are honoured only on intents the app made
itself. Android's own headset actions still open it listening, as they must.
- The sheet no longer asks its question a second time, or loses the one that waits, when the
phone is turned, folded or switches theme while it is up.
- Closing the sheet lets go of the microphone at once, also when it was closed in the middle of
listening.
- Listening no longer runs to the limit after speech into a headset that gates its noise to
exact silence, and no longer gives up as "nothing said" on someone who goes straight on after
the wake word in a steady voice. The phone's recogniser is not given up on while it reports
speech but shows no words yet.
- **A new assistant chat could start on the wrong model.** After *Continue the last chat*, *New
chat* kept that chat's model instead of going back to the assistant's own; and a question
sent the moment the sheet opened, before the instance had said which models it has, went to
the instance's default whatever was chosen.
- **Listening went on and on in a quiet room.** With the instance's speech-to-text the sheet
decided "somebody is speaking" and "it is quiet again" by two fixed loudness levels. A phone
whose room noise sat above the quiet level never heard a pause, so it listened until the
two-minute limit; and words the speech-to-text invented from silence counted as speech. Now
the room's own level is measured from the first moment and followed all the time, and speech
and quiet are judged against it: nothing said ends after five seconds, a question ends a
second and a half after you stop, a click or a knock is not speech, and the limit is one
minute. Silence is no longer sent to be written down while you have said nothing.
- The phone's own recogniser (Voice input › Phone) is asked for the same pause, and is watched:
one that never answers no longer leaves the sheet listening for good.
- An app that uses the system's recogniser while LLeMbas is the assistant no longer waits the
full fifteen seconds every time: it ends at the pause after speech, or says that nothing was
said.
## [1.0.0-beta.9] — 2026-11-13
For LLeMbas server 2.0.0-beta.12 or later.
For LLeMbas server 2.0.0-beta.12 (harness spec 3.8.0); an older instance works as before.
### Added
- **Reports.** A scheduled task no longer answers into a chat: it files a report when it has
something to tell you, or leaves a line in its history. *Reports* is in the drawer, with a
count of the unread. The list has the unread first -- title, the task it came from, when, and
a mark where the model called it important; pull to read it again, swipe a row one way to mark
it read and the other to delete it (which asks once). A report reads as a page and is marked
read when opened; **Share** hands its text to another app; **Reply** continues it as a
conversation that stays with the report -- its bar says *Report: …*, Back returns to the
report, and it is not among your chats.
- **Notify when** on a scheduled task's form: *Every run* (the model writes a report every
time, also when nothing was found), *When…* (only when your own words hold; "something needs
my attention" to start from) or *Never* (runs are kept in the task's history only). Offered
where the instance has Reports.
- A task's runs show the run's own note -- what it found, or why it filed no report -- and a way
to its report when it filed one. The run's working chat can still be opened from the run.
- **Last wake** in Settings › Wake word: when the phrase was last heard, what the app tried
(the assistant's sheet, the sheet as a screen of the app, a notification) and exactly how it
went -- opened, and after how long; Android had not connected LLeMbas as the assistant;
Android refused, in its own words; or it did not refuse and still no sheet came -- with what
Android itself said at that moment: whether LLeMbas was the digital assistant app, whether
Android was really using it as its voice assistant, and when it had connected or dropped it.
A tap shows the last five. Nothing from your account is in it.
### Fixed
- **The wake word heard you and only a notification came, though LLeMbas is the assistant.**
The app can open the sheet from the background only through a connection Android keeps to
the assistant app, and it threw away the reason when that was missing or refused. It now
keeps it (*Last wake*), says in Settings when LLeMbas is the assistant but Android has not
connected it right now -- with the way to the system's setting -- and checks that the sheet
really came up before it counts the wake as opened; when it did not, the notification follows
and says *Could not open by itself — tap to ask*. What makes a phone drop that connection is
not fixed by this: the record is there to find out.
- Settings says so when LLeMbas is chosen as the digital assistant app but Android is not using
it as its voice assistant (which Android can undo at a restart): the long press then opens
it as an ordinary screen, and the wake word can only send a notification until LLeMbas is
chosen again.
- The wake word stayed paused "while the assistant is open" after the sheet was left with the
Home button, or after the assistant was asked for twice in a row.
- A report's conversation showed the line the server opens it with as if you had written it;
such lines are a quiet note now, and that first one is left out.
- The screen is turned on when the wake word opens the sheet (with *Only while the screen is
on* switched off, the phrase can come while it is dark).
### Changed
- **Notifications come from a report, not from a run**, on a *Reports* channel of their own:
unlocked, the report's title and summary; on the lock screen only "New report". A tap opens
the report; *Mark read* asks for the phone to be unlocked. A run that filed no report notifies
nothing; a failed run still says that it failed. An instance on 2.0.0-beta.11 keeps sending
its runs' notifications, and they work as before.
- A report the model called important arrives on a channel of its own, *Important reports*,
which may come up over what is on screen. A report read or deleted in the app takes its
notification away. *Reports* is in the drawer only where the instance has reports. An empty
*When…* means the instance's own default, which the field shows as a placeholder.
- **A page in an answer is not drawn on the phone** (LLeMbas 2.0.0-beta.12 can let a model add
HTML pages to an answer; the web and LLeMbas Desktop show them). The phone shows one quiet
card -- *This answer has a page: …*, and where to open it -- in a chat and in a report, never
the page's source. What you copy or share says `[page: …]` in its place. The phone's chat
settings do not offer the switch.
## [1.0.0-beta.8] — 2026-11-12
For LLeMbas server 2.0.0-beta.11 or later. Three files now: the standard app, `-notifications` (the same app with notification summaries) and `-fdroid`.
+7
View File
@@ -46,6 +46,13 @@ hotword detection for the system's own preinstalled assistant, so LLeMbas listen
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
+1 -1
View File
@@ -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.8"
versionName = "1.0.0-beta.10"
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
+10 -1
View File
@@ -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=""
@@ -197,6 +201,11 @@
android:name=".push.CardActionReceiver"
android:exported="false" />
<!-- A report's Mark read, from its notification. -->
<receiver
android:name=".push.ReportActionReceiver"
android:exported="false" />
<!-- A scheduled task's Pause, from its notification. -->
<receiver
android:name=".push.ScheduleActionReceiver"
@@ -42,15 +42,18 @@ class LembasApp : Application() {
NotificationChannel(CHANNEL_ASKS, getString(R.string.channel_asks), NotificationManager.IMPORTANCE_HIGH),
NotificationChannel(CHANNEL_SCHEDULED, getString(R.string.channel_scheduled), NotificationManager.IMPORTANCE_DEFAULT),
NotificationChannel(CHANNEL_SCHEDULED_FAILURES, getString(R.string.channel_scheduled_failures), NotificationManager.IMPORTANCE_HIGH),
NotificationChannel(CHANNEL_REPORTS, getString(R.string.channel_reports), NotificationManager.IMPORTANCE_DEFAULT),
NotificationChannel(CHANNEL_REPORTS_HIGH, getString(R.string.channel_reports_high), NotificationManager.IMPORTANCE_HIGH),
).onEach { it.lockscreenVisibility = android.app.Notification.VISIBILITY_PRIVATE } +
// A new version of the app says nothing about the account.
NotificationChannel(CHANNEL_UPDATES, getString(R.string.channel_updates), NotificationManager.IMPORTANCE_LOW),
)
// LLeMbas 2.0 has no reports, so 0.1's channel for them goes rather than sit empty in
// the system's settings.
// 0.1's channel for its reports goes rather than sit empty in the system's settings;
// the reports of LLeMbas 2.0 have a channel of their own (CHANNEL_REPORTS).
manager.deleteNotificationChannel("reports")
// The launcher's long-press shortcuts, in the app's language as it is now.
eu.llembas.android.widget.Shortcuts.publish(this)
eu.llembas.android.widget.AskWidget.refresh(this)
}
companion object {
@@ -58,6 +61,8 @@ class LembasApp : Application() {
const val CHANNEL_ASKS = "asks"
const val CHANNEL_SCHEDULED = "scheduled_results"
const val CHANNEL_SCHEDULED_FAILURES = "scheduled_failures"
const val CHANNEL_REPORTS = "reports_filed"
const val CHANNEL_REPORTS_HIGH = "reports_important"
const val CHANNEL_UPDATES = "updates"
}
}
@@ -20,6 +20,7 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -34,6 +35,7 @@ import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Folder
import eu.llembas.android.api.safeId
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.push.Notifications
@@ -45,6 +47,8 @@ import eu.llembas.android.ui.home.ChatsViewModel
import eu.llembas.android.ui.home.DrawerActions
import eu.llembas.android.ui.home.DrawerContent
import eu.llembas.android.ui.memory.MemoryScreen
import eu.llembas.android.ui.reports.ReportScreen
import eu.llembas.android.ui.reports.ReportsScreen
import eu.llembas.android.ui.scheduled.RunScreen
import eu.llembas.android.ui.scheduled.ScheduleEditScreen
import eu.llembas.android.ui.scheduled.ScheduleScreen
@@ -65,7 +69,7 @@ import kotlinx.coroutines.launch
private data class Loaded(val instance: Instance?)
/** Where a notification (or the assistant, or a share) asked the app to open. */
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null)
private data class Opening(val chat: String?, val schedule: String?, val run: String? = null, val instance: String? = null, val report: String? = null)
class MainActivity : ComponentActivity() {
/** A chat or a schedule a notification, the assistant or a share asked to open; consumed once. */
@@ -135,12 +139,15 @@ class MainActivity : ComponentActivity() {
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
}
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
// Extras are whatever the sender put there (this activity can be started from outside):
// only ids that look like ids go on to become routes.
val chat = safeId(intent?.getStringExtra(Notifications.EXTRA_CHAT))
val schedule = safeId(intent?.getStringExtra(Notifications.EXTRA_SCHEDULE))
val run = safeId(intent?.getStringExtra(Notifications.EXTRA_RUN))
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
if (chat == null && schedule == null) return
opening.value = Opening(chat, schedule, run, instance)
val report = safeId(intent?.getStringExtra(Notifications.EXTRA_REPORT))
if (chat == null && schedule == null && report == null) return
opening.value = Opening(chat, schedule, run, instance, report)
// A notification from another of the person's instances: that one comes into use, and
// its pages (keyed by the instance) open what was asked.
if (instance != null) {
@@ -208,6 +215,8 @@ class MainActivity : ComponentActivity() {
when {
it.chat != null -> top("chat/${it.chat}")
it.report != null -> over("report/${it.report}")
it.schedule != null -> {
over("schedule/${it.schedule}")
it.run?.let { run -> over("schedule/${it.schedule}/run/$run") }
@@ -242,6 +251,8 @@ class MainActivity : ComponentActivity() {
override fun scheduled() = over("scheduled")
override fun reports() = over("reports")
override fun archived() = over("archived")
override fun memory() = over("memory")
@@ -255,6 +266,8 @@ class MainActivity : ComponentActivity() {
override fun search(query: String) = chats.search(query)
}
}
// The title of each report whose conversation was opened, by its chat: what that chat's bar says.
val reportTitles = remember { mutableStateMapOf<String, String>() }
val menu: () -> Unit = { scope.launch { drawer.open() } }
ModalNavigationDrawer(
drawerState = drawer,
@@ -299,6 +312,30 @@ class MainActivity : ComponentActivity() {
ArchivedScreen(onBack = { nav.popBackStack() }, onOpen = { top("chat/$it") }, onRestored = { chats.load() })
}
composable("memory") { MemoryScreen(onBack = { nav.popBackStack() }) }
composable("reports") { ReportsScreen(onBack = { nav.popBackStack() }, onOpen = { over("report/$it") }) }
composable("report/{id}") { e ->
ReportScreen(
e.arguments?.getString("id").orEmpty(),
onBack = { nav.popBackStack() },
onReply = { chat, title ->
reportTitles[chat] = title
over("report-chat/$chat")
},
)
}
// A report's conversation: the ordinary chat screen, entered from the report and
// left back to it. It is not among the chats (the server keeps it under Reports),
// so nothing here puts it into the drawer's list either.
composable("report-chat/{id}") { e ->
val id = e.arguments?.getString("id")
ChatScreen(
chatId = id,
onMenu = { nav.popBackStack() },
onNewChat = { top("new") },
onLeave = { nav.popBackStack() },
report = reportTitles[id].orEmpty(),
)
}
composable("scheduled") {
ScheduledScreen(
onBack = { nav.popBackStack() },
@@ -317,6 +354,7 @@ class MainActivity : ComponentActivity() {
onBack = { nav.popBackStack() },
onEdit = { over("schedule-edit/$it") },
onOpenRun = { run -> over("schedule/$id/run/$run") },
onOpenReport = { report -> over("report/$report") },
)
}
composable("schedule/{id}/run/{run}") { e ->
@@ -325,6 +363,7 @@ class MainActivity : ComponentActivity() {
e.arguments?.getString("run").orEmpty(),
onBack = { nav.popBackStack() },
onOpenChat = { top("chat/$it") },
onOpenReport = { over("report/$it") },
)
}
composable("schedule-new") {
@@ -371,13 +371,19 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
* Save what the compile made of [words]: a new schedule (201), or with [id] the one being
* edited. The words go along as the schedule's `request`, so editing starts from them.
*/
suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null): Schedule {
suspend fun saveSchedule(compiled: ScheduleCompiled, words: String, id: String? = null, notify: String? = null, notifyWhen: String = ""): Schedule {
val body = buildJsonObject {
put("title", compiled.title)
put("instruction", compiled.instruction)
put("rule", compiled.rule)
put("target", compiled.target)
if (id == null) put("request", words)
// Notify when (spec 3.8.0): left out where the form did not say, so an older server is sent nothing new.
if (notify != null) {
put("notify", notify)
// The person's own words, or none: an empty condition is the server's default, in its own words.
if (notify == "when") put("notify_when", notifyWhen.trim())
}
}
return if (id == null) {
send<ScheduleEnvelope>("POST", "/schedules", body).schedule
@@ -386,6 +392,30 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
}
}
// --- Reports (`schedule.use`) ---------------------------------------------------------------
/** The reports, newest first; [unread] only those not read yet, [schedule] only one schedule's. */
suspend fun reports(unread: Boolean = false, schedule: String? = null): List<Report> {
val asked = listOfNotNull(if (unread) "unread=1" else null, schedule?.let { "schedule=" + segment(it) }).joinToString("&")
return get<ReportList>(if (asked.isEmpty()) "/reports" else "/reports?" + asked).reports
}
/** How many reports are unread: the drawer's badge. */
suspend fun unreadReports(): Int = get<ReportList>("/reports?unread=1").unreadCount
/** One report with its body. Read as the report itself, or as `{report: …}` around it. */
suspend fun report(id: String): Report {
val answer = get<JsonObject>("/reports/${segment(id)}")
return LembasJson.decodeFromJsonElement(Report.serializer(), answer["report"] as? JsonObject ?: answer)
}
suspend fun readReport(id: String) = empty(authed("$v2/reports/${segment(id)}/read").post("{}".toRequestBody(JSON)).build())
suspend fun deleteReport(id: String) = empty(authed("$v2/reports/${segment(id)}").delete().build())
/** Continue the report as a conversation: the chat it is in, which stays under Reports. */
suspend fun replyToReport(id: String): String? = send<ReportReply>("POST", "/reports/${segment(id)}/reply", null).chatId
suspend fun pauseSchedule(id: String, paused: Boolean): Schedule =
send<ScheduleEnvelope>("POST", "/schedules/${segment(id)}/" + if (paused) "pause" else "resume", null).schedule
@@ -115,3 +115,32 @@ fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
format.roundingMode = java.math.RoundingMode.HALF_UP
return format.format(n)
}
/** How a message is drawn in the transcript. */
enum class Drawn {
/** The person's own words: their bubble. */
Person,
/** The model's reply. */
Reply,
/** A line the server wrote in the person's place (`machine`): a quiet note, never their bubble. */
Note,
/** Not drawn at all. */
Hidden,
}
/**
* How [message] is drawn. A `user` row the server wrote itself (`machine`: a schedule's
* instruction, the line that opens a report's conversation) is not something the person said,
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
* [first] such line, which only tells the model what the conversation continues, is left out,
* since the report itself is one tap back.
*/
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
!message.isUser -> Drawn.Reply
!message.machine -> Drawn.Person
reportChat && first -> Drawn.Hidden
else -> Drawn.Note
}
@@ -314,6 +314,10 @@ data class Chat(
@SerialName("created_at") val createdAt: String? = null,
@SerialName("updated_at") val updatedAt: String? = null,
@SerialName("system_prompt") val systemPrompt: String? = null,
/** What may be done to this chat (`rename`, `delete`, `archive`, `pin`, `folder`); null from a server that does not say: everything. */
val controls: List<String>? = null,
/** The report this chat continues (`kind` `report`): such a chat lives under Reports, not among the chats. */
val report: ChatReport? = null,
val plan: JsonObject? = null,
/** The team's size: how many agents, its own included, the chat may have. */
val agents: AgentsSetting? = null,
@@ -321,8 +325,14 @@ data class Chat(
val subagents: SubagentsOffer? = null,
) {
val isAgent: Boolean get() = kind == "agent"
fun allows(control: String): Boolean = controls?.contains(control) ?: true
}
/** The report a chat continues: its id and title. */
@Serializable
data class ChatReport(val id: String = "", val title: String = "")
/** A chat's `agents {min, max}` (harness spec 3.2.0): `1 ≤ min ≤ max ≤` the instance's cap. */
@Serializable
data class AgentsSetting(val min: Int = 1, val max: Int = 4) {
@@ -512,7 +522,7 @@ data class FileContent(
@Serializable
data class SteerNote(val id: String = "", val text: String = "")
/** One step of a reply: `thinking`, `text`, `tools` or `steer`. */
/** One step of a reply: `thinking`, `text`, `tools`, `steer` or `page`. */
@Serializable
data class Step(
val index: Int = 0,
@@ -521,6 +531,10 @@ data class Step(
val text: String? = null,
val label: String? = null,
val markdown: String? = null,
/** A `page` step's title (spec 3.8.0): the page itself is not sent to a client that does not draw it. */
val title: String? = null,
/** A `text` step's pages (spec 3.8.0): where it has any, [text] is its markdown with each page as the one line `[page: Title]`. */
val pages: List<StepPage> = emptyList(),
val calls: List<ToolCall> = emptyList(),
val messages: List<SteerNote> = emptyList(),
)
@@ -533,6 +547,16 @@ data class Step(
@Serializable
data class MessageEnd(val phase: String = "", val reason: String = "", val text: String = "")
/** A page in a reply's text: its title (the page itself is fetched by its digest, by a client that draws pages). */
@Serializable
data class StepPage(val title: String = "", val digest: String = "")
/**
* What a client that draws no pages shows of a `text` step: the server's own text where the step
* has pages (each page its one line), else the markdown as it is.
*/
val Step.shownMarkdown: String get() = text?.takeIf { pages.isNotEmpty() && it.isNotBlank() } ?: markdown.orEmpty()
@Serializable
data class Message(
val id: String,
@@ -715,6 +739,10 @@ data class PushPayload(
*/
@SerialName("schedule_id") val scheduleId: String? = null,
@SerialName("run_id") val runId: String? = null,
/** A report was filed (`kind` `report`, spec 3.8.0): its id; [title] and [body] are its title and summary, [url] `/reports/{id}`. */
@SerialName("report_id") val reportId: String? = null,
/** A report's `normal` or `high`. */
val importance: String? = null,
val status: String? = null,
val visibility: String? = null,
val actions: List<String> = emptyList(),
@@ -0,0 +1,103 @@
package eu.llembas.android.api
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNames
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
// --- Reports (`/api/v2/reports`, harness spec 3.8.0 `reports.md`) -----------------------------
//
// A schedule's run does not answer into a chat: it files a report, or it does not. The server
// stores the reports and lists them; a report's body is Markdown, as a reply is.
//
// The shapes are read leniently where an id may come as a string or as an object carrying one
// ([chat], a run's `report`), so that a server that says a little more still parses; the
// contract fixtures (`contract/report*.json`) pin what it says.
/** The schedule a report came from: its id and its name. */
@Serializable
data class ReportSchedule(val id: String = "", val title: String = "")
/**
* One report: [title] a headline, [summary] a sentence or two for a list or a notification,
* [importance] `normal` or `high` (look now), the [schedule] that filed it, [created] when, and
* whether it is still [unread]. Read alone it also carries its [body] (Markdown a model wrote:
* untrusted) and the [chat] a reply continues in, once there is one.
*/
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class Report(
val id: String,
val title: String = "",
val summary: String = "",
val importance: String = "normal",
val schedule: ReportSchedule? = null,
/** The schedule's name as it was when the report was filed: what is left once the schedule itself is gone. */
@SerialName("schedule_title") val scheduleTitle: String = "",
@JsonNames("created_at") val created: String? = null,
val unread: Boolean = false,
val body: String? = null,
/** The body as text: every page in it replaced by its one line, `[page: Title]`; the body itself where it has none. */
val text: String? = null,
/** The pages the body has: only these are pages -- an `html-view` fence the server does not list is a code block. */
val pages: List<StepPage> = emptyList(),
val model: String? = null,
val chat: JsonElement? = null,
) {
val high: Boolean get() = importance == "high"
/** The name of the task it came from: the schedule's as it is now, else as it was. */
val from: String get() = schedule?.title?.ifBlank { null } ?: scheduleTitle
/** The chat a reply to this report continues in; null before the first reply. */
val chatId: String? get() = idOf(chat)
}
@Serializable
data class ReportList(val reports: List<Report> = emptyList(), val unread: Int? = null) {
/** How many reports are unread: the server's count, else as many as it listed unread. */
val unreadCount: Int get() = unread ?: reports.count { it.unread }
}
/** `GET /events`, frame `reports`: the count of the unread, and the newest report. */
@Serializable
data class ReportsFrame(val unread: Int = 0, val newest: Report? = null, @SerialName("latest_created") val latestCreated: String? = null)
/** `POST /reports/{id}/reply`: the chat the conversation about the report is in. */
@Serializable
data class ReportReply(val chat: JsonElement? = null) {
val chatId: String? get() = idOf(chat)
}
/** An id that came as a string, or as an object with an `id`; null for anything else. */
internal fun idOf(element: JsonElement?): String? = when (element) {
is JsonPrimitive -> element.contentOrNull?.takeIf { element.isString && it.isNotBlank() }
is JsonObject -> idOf(element["id"])
else -> null
}
/** Reports as the list shows them: the unread first, then the newest first within each half. */
fun sortedReports(reports: List<Report>): List<Report> = reports.sortedWith(compareByDescending<Report> { it.unread }.thenByDescending { it.created.orEmpty() })
/**
* When a schedule's owner wants to hear from it (`loop.json` `scheduled.notify`): `always` (a
* report every run), `when` (only when the person's own words hold) or `never` (history only).
* A server before 3.8.0 said `matters` for what is now `when`; anything else is the default.
*/
fun notifyChoice(notify: String): String = when (notify) {
"always", "never" -> notify
else -> "when"
}
/**
* An id as the server makes them -- letters, digits, `_` and `-`, at most 64 -- or null. Anything
* that came from outside the app (a push payload, an intent's extra) is passed through this
* before it becomes part of a route or an address: a `/` in it must not open another page.
*/
fun safeId(id: String?): String? = id?.takeIf { SAFE_ID.matches(it) }
private val SAFE_ID = Regex("^[A-Za-z0-9_-]{1,64}$")
@@ -2,6 +2,7 @@ package eu.llembas.android.api
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
// --- Scheduled tasks (`/api/v2/schedules`) ------------------------------------------------
@@ -67,13 +68,20 @@ data class ScheduleRun(
val notification: RunNotification? = null,
/** A watching schedule's look at its address on this run (`unchanged` when nothing moved). */
val watch: RunWatch? = null,
)
/** The run's line in the history (spec 3.8.0): the answer's first line, or why no report was filed. */
val note: String = "",
/** The report this run filed, when it filed one: its id (or an object carrying it). */
val report: JsonElement? = null,
) {
val reportId: String? get() = idOf(report)
}
/**
* A scheduled task. [description] is the rule in words, as the server says it ("On the second
* Monday of each month at 07:30"), in [timezone]; [rule] the server's own form of it; [request]
* the person's words it was made from; [instruction] what the model is asked each time.
* [notify] is `always`, `matters` or `never`; [mode] `fresh` (a chat per run) or `continue`.
* [notify] is `always`, `when` or `never` (spec 3.8.0; `matters` before it) and [notifyWhen] the
* person's own words for `when`; [mode] `fresh` (a chat per run) or `continue`.
*/
@Serializable
data class Schedule(
@@ -90,6 +98,9 @@ data class Schedule(
val target: String = "chat",
val mode: String = "",
val notify: String = "",
@SerialName("notify_when") val notifyWhen: String = "",
/** What "When…" means while [notifyWhen] is empty, in the account's language. */
@SerialName("notify_default") val notifyDefault: String = "",
@SerialName("catch_up") val catchUp: String = "",
@SerialName("grace_minutes") val graceMinutes: Int? = null,
val model: String? = null,
@@ -206,6 +217,8 @@ data class RunNotification(
val actions: List<String> = emptyList(),
val labels: Map<String, String> = emptyMap(),
val ask: String = "",
/** A report's notification: `normal` or `high`. */
val importance: String = "",
)
/**
@@ -3,9 +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
@@ -13,13 +17,19 @@ 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
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.wake.AssistLink
import eu.llembas.android.wake.AssistPresence
import eu.llembas.android.wake.WakeWordService
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
/** What a way into the sheet asks for. */
enum class Opening {
@@ -31,34 +41,73 @@ 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
private lateinit var keyguard: KeyguardManager
private var started = false
private var byWake = false
/** The screen went off since the sheet was last seen: on the way back, the lock is looked at again. */
private var wentOff = false
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
private val locked = mutableStateOf(false)
@@ -66,6 +115,29 @@ class AssistActivity : ComponentActivity() {
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?) {
@@ -75,10 +147,39 @@ class AssistActivity : ComponentActivity() {
controller = AssistController(this, lifecycleScope)
keyguard = getSystemService(KeyguardManager::class.java)
locked.value = keyguard.isKeyguardLocked
AssistPresence.shown()
// The sheet is up: "Heard you. Tap to ask." has been answered, however it was opened.
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
take(intent)
ContextCompat.registerReceiver(
this,
screen,
IntentFilter().apply {
addAction(Intent.ACTION_USER_PRESENT)
addAction(Intent.ACTION_SCREEN_OFF)
},
ContextCompat.RECEIVER_NOT_EXPORTED,
)
// A question waits for the unlock: Android is asked for it at once (a face or a
// fingerprint is then enough), and the sheet stays if nobody answers.
lifecycleScope.launch {
controller.state.map { it.held }.distinctUntilChanged().collect { held ->
if (held && locked.value) askToUnlock()
}
}
// The lock screen turns the display off after a few seconds: not in the middle of a
// question, and not in the middle of an answer read aloud (the screen going off stops it).
lifecycleScope.launch {
controller.state.map { it.listening || it.busy || it.speaking }.distinctUntilChanged().collect { on ->
if (on) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
// so nothing else has woken the phone).
woken(intent)
// Once: made again by Android (after the app was put away and brought back), the sheet
// must not ask the same question a second time. What waited for the unlock is kept.
if (savedInstanceState == null) {
take(intent)
} else {
savedInstanceState.getString(STATE_WAITING)?.let { controller.hold(Held(it, null, savedInstanceState.getBoolean(STATE_SPOKEN))) }
}
setContent {
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
LembasTheme(prefs.theme) {
@@ -86,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())
@@ -102,42 +201,100 @@ class AssistActivity : ComponentActivity() {
},
onNeedMic = { mic.launch(Manifest.permission.RECORD_AUDIO) },
onDismiss = { finish() },
onUnlock = { askToUnlock() },
)
}
}
}
/** Opened again while it is up -- the headset's button pressed twice, the tile again. */
/** Opened again while it is up -- the headset's button pressed twice, the tile again, the wake word. */
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
woken(intent)
// The same sheet answers again: it is up, and whoever asked for it is told so.
if (started) AssistLink.sheetShown(SystemClock.elapsedRealtime())
take(intent)
}
/**
* 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.
* Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch, so
* nothing else has woken the phone), and the sheet is remembered as the wake word's, so that
* the assistant's own sheet can take its place if that one comes after all.
*/
private fun woken(intent: Intent?) {
byWake = OwnIntents.isOwn(this, intent) && intent?.getBooleanExtra(EXTRA_WAKE, false) == true
if (byWake) setTurnScreenOn(true)
}
/**
* On screen: only now is the sheet "up" -- for the wake word's pause (which must end when the
* sheet is left with Home, not only when it is destroyed) and for whoever waits to hear that
* it opened.
*/
override fun onStart() {
super.onStart()
started = true
// The phone may have locked, or been unlocked, while the sheet was out of sight.
if (keyguard.isKeyguardLocked) {
// Found locked: the controller is told, unless the sheet was opened over the lock
// screen in the first place (and is listening there).
if (!locked.value || wentOff) controller.lockedNow()
locked.value = true
} else {
unlockedNow()
}
wentOff = false
open = WeakReference(this)
AssistPresence.shown()
AssistLink.sheetShown(SystemClock.elapsedRealtime())
// "Heard you. Tap to ask." has been answered, however the sheet was opened.
getSystemService(NotificationManager::class.java).cancel(WakeWordService.HEARD_ID)
}
override fun onStop() {
started = false
if (open?.get() === this) open = null
AssistPresence.hidden()
super.onStop()
}
/**
* What the way in asked for: a question handed over by the session ([AssistHandOff]),
* listening (the headset's voice button, the widget's microphone, the Speak shortcut, the
* wake word), the last assistant chat (the widget, the shortcut), or just the sheet. Over
* the lock screen: [lockedStart]. Only an intent the app made itself ([OwnIntents]) can
* hand over a question or ask for more than Android's own actions do.
*/
private fun take(intent: Intent) {
val 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()
}
@@ -146,19 +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() {
AssistPresence.hidden()
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"
@@ -170,9 +366,30 @@ 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
private var open: WeakReference<AssistActivity>? = null
/** The assistant's own sheet came up: a sheet the wake word had opened in its place goes. */
fun closeWoken() {
open?.get()?.takeIf { it.byWake }?.finish()
}
/** On the intent the wake word opens the sheet with: turn the screen on. */
const val EXTRA_WAKE = "eu.llembas.android.WAKE"
/** The sheet, listening, as the wake word opens it. */
fun woken(context: Context): Intent = listening(context).putExtra(EXTRA_WAKE, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** The sheet, at the last assistant chat. */
fun continuing(context: Context): Intent = 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
@@ -22,13 +24,17 @@ 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 +51,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 }
@@ -85,7 +97,21 @@ 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 empty: Boolean get() = turns.isEmpty()
@@ -127,7 +153,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,18 +170,65 @@ 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 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.assistantModel }.distinctUntilChanged().drop(1).collect { chosen ->
ready()
newChatModel = assistantModelFor(chosen, accountDefault, _state.value.models) ?: chosen.ifBlank { null }
_state.update { if (it.chatId == null) it.copy(modelId = newChatModel) else it }
}
}
}
/** 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 prefs = store.prefs.first()
@@ -161,15 +242,23 @@ class AssistController(private val context: Context, private val scope: Coroutin
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.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 = prefs.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 api = store.current()?.let { store.clientFor(it) } ?: return
try {
val me = api.me()
val models = api.models()
stt = me.speechToText
val chosen = prefs.assistantModel.takeIf { id -> models.any { it.id == id } }
?: me.defaultModel?.takeIf { id -> models.any { it.id == id } }
?: models.firstOrNull { it.default }?.id
?: models.firstOrNull()?.id
accountDefault = me.defaultModel
val chosen = assistantModelFor(prefs.assistantModel, me.defaultModel, models)
newChatModel = chosen
_state.update {
it.copy(
connection = Connection.Online,
@@ -186,26 +275,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.client()?.transcribe(wav).orEmpty()
_state.update { it.copy(busy = false) }
if (text.isNotBlank()) ask(text, spoken = true)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_state.update { it.copy(busy = false, error = context.explain(e)) }
}
}
}
/**
* 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 +402,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 +424,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,7 +441,9 @@ 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
@@ -279,44 +451,75 @@ class AssistController(private val context: Context, private val scope: Coroutin
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()
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,6 +539,13 @@ 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()
@@ -361,6 +571,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 +592,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 {
@@ -396,6 +612,8 @@ class AssistController(private val context: Context, private val scope: Coroutin
val store = context.lembas.instances
val api = store.client() ?: throw ApiException(401, "Not signed in.")
val prefs = store.prefs.first()
// A question typed the moment the sheet opened: the model is known first.
ready()
val now = _state.value
val withScreen = now.includeScreen
val attachments = buildList {
@@ -424,7 +642,7 @@ 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) }
@@ -455,7 +673,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 {
@@ -528,11 +746,13 @@ 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) }
}
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
override fun pickModel(id: String) {
newChatModel = id
_state.update { it.copy(modelId = id) }
scope.launch {
context.lembas.instances.savePrefs { it.copy(assistantModel = id) }
@@ -560,7 +780,8 @@ class AssistController(private val context: Context, private val scope: Coroutin
/** 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))
@@ -582,7 +803,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 +823,21 @@ 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? {
val has = { id: String? -> !id.isNullOrBlank() && models.any { it.id == id } }
return chosen.takeIf(has) ?: accountDefault?.takeIf(has) ?: models.firstOrNull { it.default }?.id ?: models.firstOrNull()?.id
}
/** 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 {
@@ -2,14 +2,17 @@ package eu.llembas.android.assist
import android.app.KeyguardManager
import android.app.assist.AssistStructure
import android.app.role.RoleManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.SystemClock
import android.service.voice.VoiceInteractionService
import android.service.voice.VoiceInteractionSession
import android.service.voice.VoiceInteractionSessionService
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.compose.runtime.mutableStateOf
@@ -27,12 +30,16 @@ import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import eu.llembas.android.AppLanguage
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.wake.AssistLink
import eu.llembas.android.wake.AssistPresence
import eu.llembas.android.wake.wakeLogConnected
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
@@ -43,16 +50,50 @@ import kotlinx.coroutines.runBlocking
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
*/
class LembasAssistService : VoiceInteractionService() {
override fun onCreate() {
super.onCreate()
AssistLink.created(System.currentTimeMillis())
}
override fun onReady() {
super.onReady()
current = this
// When Android connected it is kept: the wake word's record says whether it was, and an
// attempt that found it not connected is told that it came later.
val now = System.currentTimeMillis()
AssistLink.ready(now)
Log.i(TAG, "assistant service connected by Android")
background.launch { runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogConnected(it.wakeLog, now)) } } }
}
override fun onShutdown() {
if (current === this) current = null
// Only the instance that is the current one disconnects it: an old one going away late
// must not say "not connected" over a new one.
if (current === this) {
current = null
AssistLink.shutdown(System.currentTimeMillis())
}
Log.i(TAG, "assistant service disconnected by Android")
super.onShutdown()
}
override fun onDestroy() {
AssistLink.destroyed(System.currentTimeMillis())
super.onDestroy()
}
/** Android 14+: Android is about to show a session it was asked for -- or, below, could not. Kept for the wake word's record. */
override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
AssistLink.prepared(SystemClock.elapsedRealtime())
super.onPrepareToShowSession(args, showFlags)
}
override fun onShowSessionFailed(args: Bundle) {
AssistLink.showFailed(SystemClock.elapsedRealtime())
Log.w(TAG, "Android could not show the assistant's session")
super.onShowSessionFailed(args)
}
companion object {
/**
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
@@ -62,6 +103,23 @@ class LembasAssistService : VoiceInteractionService() {
@Volatile
var current: LembasAssistService? = null
private set
private const val TAG = "LLeMbasWake"
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
/**
* Whether Android itself uses this service as its voice-interaction service right now.
* Holding the assistant role is not the same: Android keeps the service only while a
* speech recogniser is set that it accepts, and resets it at start-up otherwise -- the
* long press then opens the assistant as an ordinary screen, and nothing is connected
* that could open it from the background.
*/
fun isActive(context: Context): Boolean =
runCatching { VoiceInteractionService.isActiveService(context, ComponentName(context, LembasAssistService::class.java)) }.getOrDefault(false)
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
fun holdsRole(context: Context): Boolean =
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
}
}
@@ -83,6 +141,12 @@ class LembasAssistSession(context: Context) :
private var controller = AssistController(context, scope)
private val current = mutableStateOf(controller)
/** Whether this session's sheet is up, as far as the wake word's pause is concerned. */
private var up = false
/** Over the lock screen: waiting for what is heard, to hand it to the sheet's activity. */
private var handing: Job? = null
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
@@ -115,12 +179,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() },
)
}
@@ -131,9 +195,28 @@ class LembasAssistSession(context: Context) :
override fun onShow(args: Bundle?, showFlags: Int) {
super.onShow(args, showFlags)
registry.currentState = Lifecycle.State.RESUMED
AssistPresence.shown()
// The wake word asks for the sheet listening, whatever Settings says about opening.
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
// Android calls this again for a show asked for while the sheet is up, and hides once:
// the sheet is counted as up once.
if (!up) {
up = true
AssistPresence.shown()
}
AssistLink.sheetShown(SystemClock.elapsedRealtime())
// One sheet, never two: a sheet the wake word opened as a screen of the app, because
// this one was slow to come, goes now that this one is here.
AssistActivity.closeWoken()
// The wake word asks for the sheet listening, whatever Settings says about opening --
// over the lock screen too, where what it hears is held and not asked.
val showing = controller
showing.opened(listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
// A question that waits for the unlock (heard, or typed, over the lock screen) goes to
// the sheet's activity, which can ask Android to unlock. Once: Android may call onShow
// again while the sheet is up.
handing?.cancel()
handing = scope.launch {
showing.state.first { it.held && locked() }
showing.takeHeld()?.let { handOff(it) }
}
}
/**
@@ -143,7 +226,10 @@ class LembasAssistSession(context: Context) :
*/
override fun onHide() {
super.onHide()
AssistPresence.hidden()
if (up) {
up = false
AssistPresence.hidden()
}
controller.close()
scope.cancel()
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
@@ -185,16 +271,12 @@ class LembasAssistSession(context: Context) :
/**
* Over the lock screen nothing is sent from here: the question goes to [AssistActivity],
* which asks Android to unlock first and only then sends it. The microphone's permission
* which asks Android to unlock first and only then sends it. It is left in the app's own
* memory ([AssistHandOff]) and the intent carries its ticket. The microphone's permission
* prompt needs an activity too.
*/
private fun handOff(text: String, 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()
}
}
@@ -46,6 +46,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
@@ -197,7 +198,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,6 +210,7 @@ fun ColumnScope.AssistSheetContent(
locked: Boolean,
handle: Modifier = Modifier,
onOpenApp: () -> Unit = {},
onUnlock: () -> Unit = {},
onSend: (String) -> Unit = actions::ask,
onMic: () -> Unit = actions::listen,
) {
@@ -267,14 +272,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.
@@ -468,6 +479,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
@@ -19,7 +19,8 @@ import kotlinx.coroutines.launch
* Speech recognition through the instance (`/v1/audio/transcriptions`). Android requires a
* digital assistant to name a recognition service; this is it, and any app that asks the
* system's recognizer while LLeMbas is the assistant is answered by the instance's
* speech-to-text. Listening ends when the caller says stop, or after [LIMIT_MS].
* 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].
*/
class LembasRecognitionService : RecognitionService() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
@@ -37,7 +38,23 @@ class LembasRecognitionService : RecognitionService() {
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()
}
}
@@ -52,6 +69,16 @@ class LembasRecognitionService : RecognitionService() {
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
@@ -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.wake.WakeAttempt
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
@@ -93,6 +94,8 @@ data class Prefs(
val wakePhrase: String = "hey_assistant",
/** WakeSensitivity's id: low, normal or high. */
val wakeSensitivity: String = "normal",
/** What happened the last times the wake word was heard (WakeLog): shown in Settings, nothing of the account in it. */
val wakeLog: List<WakeAttempt> = emptyList(),
/** Listen only while the screen is on. */
val wakeScreenOnly: Boolean = true,
/** The assistant may read the notifications when asked (with Android's notification access). */
+102 -13
View File
@@ -17,6 +17,7 @@ import eu.llembas.android.R
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
import eu.llembas.android.auth.Instance
import eu.llembas.android.lembas
import kotlinx.coroutines.CoroutineScope
@@ -100,11 +101,18 @@ object Notifications {
const val EXTRA_SCHEDULE = "eu.llembas.android.SCHEDULE"
const val EXTRA_RUN = "eu.llembas.android.RUN"
const val EXTRA_REPORT = "eu.llembas.android.REPORT"
/** Whether [kind] is about a chat: a finished reply (which older payloads leave unnamed) or a question or an approval. */
fun chatKind(kind: String): Boolean = kind == "" || kind == "reply" || kind == "ask"
fun show(context: Context, instance: String, payload: PushPayload) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return
if (payload.kind == "schedule" || payload.kind == "schedule_failed") return scheduled(context, instance, payload)
val chatId = payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") }
if (payload.kind == ReportNotice.KIND) return report(context, instance, payload)
// A kind this app does not know -- a newer server's -- is not guessed at: no notification.
if (!chatKind(payload.kind)) return
val chatId = safeId(payload.chatId ?: payload.url.removePrefix("/chat/").takeIf { payload.url.startsWith("/chat/") })
val id = (chatId ?: payload.url).hashCode()
val open = opener(context, instance, id, chatId = chatId)
val channel = when (payload.kind) {
@@ -176,22 +184,85 @@ object Notifications {
NotificationManagerCompat.from(context).notify(notice.id, builder.build())
}
/**
* A report was filed (spec 3.8.0): what a scheduled task has to tell, on the Reports channel.
* Unlocked: the report's title and its summary. On the lock screen only the public version:
* the app's name and "New report" -- nothing from the account (Working-notes rule 5). A tap
* and Open go to the report; Mark read marks it, once the phone is unlocked. A run that
* filed no report sends nothing, so there is nothing to show for it; a failed run still has
* its own notification ([scheduled]).
*/
private fun report(context: Context, instance: String, payload: PushPayload) {
val notice = ReportNotice.from(payload) ?: return
NotificationManagerCompat.from(context).notify(notice.id, reportNotification(context, instance, notice))
}
/** The report's notification, apart from posting it, so a test can read both of its faces. */
fun reportNotification(context: Context, instance: String, notice: ReportNotice): Notification {
val fixed = context.getString(R.string.report_new_public)
val open = opener(context, instance, notice.id, chatId = null, reportId = notice.reportId)
// A report the model called important goes on a channel of its own that may come up over
// what is on screen: on Android 8 and later the channel decides that, not the notification.
val channel = if (notice.high) LembasApp.CHANNEL_REPORTS_HIGH else LembasApp.CHANNEL_REPORTS
val public = NotificationCompat.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(fixed)
.build()
val read = PendingIntent.getBroadcast(
context,
("read" + notice.reportId).hashCode(),
Intent(context, ReportActionReceiver::class.java)
.putExtra("instance", instance)
.putExtra("report", notice.reportId)
.putExtra("notification", notice.id),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
return NotificationCompat.Builder(context, channel)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(notice.title.ifBlank { fixed })
.setContentText(notice.summary)
.setStyle(NotificationCompat.BigTextStyle().bigText(notice.summary))
.setAutoCancel(true)
.setContentIntent(open)
.setCategory(Notification.CATEGORY_STATUS)
.setPriority(if (notice.high) NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_DEFAULT)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(public)
.addAction(0, context.getString(R.string.viewer_open), open)
.addAction(unlocked(context.getString(R.string.report_mark_read), read))
.build()
}
/** The report was read or deleted in the app: its notification has nothing left to say. */
fun reportSeen(context: Context, reportId: String) {
NotificationManagerCompat.from(context).cancel(ReportNotice.notificationId(reportId))
}
/** A notification action Android runs only once the phone is unlocked. */
private fun unlocked(title: String, intent: PendingIntent): NotificationCompat.Action =
NotificationCompat.Action.Builder(0, title, intent).setAuthenticationRequired(true).build()
private fun opener(context: Context, instance: String, id: Int, chatId: String?, scheduleId: String? = null, runId: String? = null): PendingIntent =
PendingIntent.getActivity(
context,
id,
Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(EXTRA_CHAT, chatId)
.putExtra(EXTRA_SCHEDULE, scheduleId)
.putExtra(EXTRA_RUN, runId)
.putExtra(EXTRA_INSTANCE, instance),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
private fun opener(
context: Context,
instance: String,
id: Int,
chatId: String?,
scheduleId: String? = null,
runId: String? = null,
reportId: String? = null,
): PendingIntent = PendingIntent.getActivity(
context,
id,
Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(EXTRA_CHAT, chatId)
.putExtra(EXTRA_SCHEDULE, scheduleId)
.putExtra(EXTRA_RUN, runId)
.putExtra(EXTRA_REPORT, reportId)
.putExtra(EXTRA_INSTANCE, instance),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
private fun scheduleAction(context: Context, instance: String, schedule: String, notification: Int, action: String): PendingIntent =
PendingIntent.getBroadcast(
@@ -242,6 +313,24 @@ class CardActionReceiver : BroadcastReceiver() {
}
}
/** A report's Mark read, from its notification. */
class ReportActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pending = goAsync()
val instance = intent.getStringExtra("instance") ?: return pending.finish()
val report = intent.getStringExtra("report") ?: return pending.finish()
background.launch {
try {
// A report that is gone is as good as read; the notification goes either way.
Push.instance(context, instance)?.let { found -> runCatching { context.lembas.instances.clientFor(found).readReport(report) } }
NotificationManagerCompat.from(context).cancel(intent.getIntExtra("notification", 0))
} finally {
pending.finish()
}
}
}
}
/** A scheduled task's Pause or Run again, from its notification. */
class ScheduleActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
@@ -0,0 +1,45 @@
package eu.llembas.android.push
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
/**
* What a filed report's push asks the app to show (harness spec 3.8.0, `reports.md` §4:
* notifications come from the report, not from the run). [title] and [summary] are a model's
* words about the person's own things: for an unlocked phone only. The lock screen gets the
* app's fixed words and nothing else. A payload without the id falls back to its `url`
* (`/reports/{id}`), as a browser would open it.
*/
data class ReportNotice(val reportId: String, val title: String, val summary: String, val high: Boolean) {
/** One notification per report: a later push about the same report replaces it. */
val id: Int get() = notificationId(reportId)
companion object {
const val KIND = "report"
/** The notification of the report with this id: what is cancelled once the report is read or deleted in the app. */
fun notificationId(reportId: String): Int = "report:$reportId".hashCode()
fun from(payload: PushPayload): ReportNotice? {
if (payload.kind != KIND) return null
// Only an id that looks like one: it becomes part of a route and of an address.
val id = safeId(payload.reportId?.takeIf { it.isNotBlank() } ?: fromUrl(payload.url)) ?: return null
// The report's own words are in the payload's `notification` (the payload's top is
// what an older client would show: the app's name and "New report"). A payload
// without one is read by its top.
val words = payload.notification
return ReportNotice(
reportId = id,
title = words?.title ?: payload.title,
summary = words?.body ?: payload.body,
high = (words?.importance?.ifBlank { null } ?: payload.importance) == "high",
)
}
/** `/reports/{id}` → the id; null for anything else. */
fun fromUrl(url: String): String? {
if (!url.startsWith("/reports/")) return null
return url.removePrefix("/reports/").substringBefore('?').substringBefore('/').takeIf { it.isNotBlank() }
}
}
}
@@ -1,6 +1,7 @@
package eu.llembas.android.push
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.safeId
/**
* What a scheduled run's push asks the app to show, read from the server's payload alone
@@ -40,8 +41,9 @@ data class ScheduledNotice(
fun from(payload: PushPayload): ScheduledNotice? {
if (payload.kind != KIND_RESULT && payload.kind != KIND_FAILED) return null
val (urlSchedule, urlRun) = fromUrl(payload.url)
val schedule = payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule ?: return null
val run = payload.runId?.takeIf { it.isNotBlank() } ?: urlRun
// Only ids that look like ids: they become parts of a route and of an address.
val schedule = safeId(payload.scheduleId?.takeIf { it.isNotBlank() } ?: urlSchedule) ?: return null
val run = safeId(payload.runId?.takeIf { it.isNotBlank() } ?: urlRun)
val failed = payload.kind == KIND_FAILED
val words = payload.notification
val ask = words?.ask?.takeIf { it.isNotBlank() } ?: payload.ask
@@ -104,7 +104,11 @@ class ShareActivity :
into
} else {
val prefs = store.prefs.first()
val made = api.createChat(message, files, model = prefs.assistantModel.ifBlank { null })
// The assistant's model while the instance still has it; a model that is
// gone is not asked for (the instance's default answers instead).
val chosen = prefs.assistantModel
val gone = chosen.isNotBlank() && runCatching { api.models() }.getOrNull()?.none { it.id == chosen } == true
val made = api.createChat(message, files, model = chosen.takeIf { it.isNotBlank() && !gone })
store.savePrefs {
it.copy(
lastAssistChat = made.chat.id,
@@ -8,16 +8,54 @@ package eu.llembas.android.ui
*
* A fence that is not closed yet runs to the end: while a reply is being written, the code it
* is in the middle of is already a code block, not markdown that changes shape when it closes.
*
* **A page** (harness spec 3.8.0, `pages.md`: a whole HTML document in an `html-view` fence) is
* not drawn on a phone and its source is never shown as the answer. Which fence is a page is the
* server's to say: a block is one only in a reply written while pages were offered, and the
* server then puts the one line `[page: Title]` in its place in the text it gives a client that
* draws no pages. That line is what becomes [Segment.Page]. A fence is taken for a page here
* only where the caller says pages are being written ([splitFences]' `pages`: the open step of
* a reply as it streams, which the server has not turned into text yet); anywhere else an
* `html-view` fence is the code block it is.
*/
sealed interface Segment {
data class Prose(val markdown: String) : Segment
data class Code(val language: String, val code: String, val closed: Boolean = true) : Segment
data class Page(val title: String, val closed: Boolean = true) : Segment
}
/** `pages.fence`: the fence's word, exact. */
private const val PAGE_FENCE = "html-view"
/** `pages.title_max`. */
private const val PAGE_TITLE_MAX = 80
private val PAGE_OPENING = Regex("^ {0,3}(?:`{3,}|~{3,})$PAGE_FENCE(?:\\s+(.*))?$")
/** `pages.projection`, on a line of its own. */
private val PAGE_LINE = Regex("^\\s*\\[page: (.*)]\\s*$")
/** A page's title as written: white space collapsed, cut to the spec's length; empty when it has none. */
private fun pageTitle(raw: String?): String = raw.orEmpty().trim().replace(Regex("\\s+"), " ").take(PAGE_TITLE_MAX)
/**
* A reply's text with every page replaced by the spec's one line, `[page: Title]`: what Copy,
* Share and read-aloud take, so a page's source never leaves as "the answer". [untitled] names
* a page without a title.
*/
fun pageProjection(markdown: String, untitled: String, pages: Boolean = false): String = splitFences(markdown, pages).joinToString("\n\n") { segment ->
when (segment) {
is Segment.Prose -> segment.markdown
is Segment.Code -> "```${segment.language}\n${segment.code}\n```"
is Segment.Page -> "[page: ${segment.title.ifBlank { untitled }}]"
}
}
private val OPENING = Regex("^ {0,3}(`{3,}|~{3,})\\s*([^`\\s]*).*$")
fun splitFences(markdown: String): List<Segment> {
fun splitFences(markdown: String, pages: Boolean = false): List<Segment> {
val out = mutableListOf<Segment>()
val prose = StringBuilder()
val lines = markdown.split("\n")
@@ -32,13 +70,20 @@ fun splitFences(markdown: String): List<Segment> {
while (i < lines.size) {
val open = OPENING.matchEntire(lines[i])
if (open == null) {
prose.append(lines[i]).append('\n')
val page = PAGE_LINE.matchEntire(lines[i])
if (page != null) {
flushProse()
out += Segment.Page(pageTitle(page.groupValues[1]))
} else {
prose.append(lines[i]).append('\n')
}
i++
continue
}
flushProse()
val fence = open.groupValues[1]
val language = open.groupValues[2]
val page = if (pages) PAGE_OPENING.matchEntire(lines[i]) else null
val closing = Regex("^ {0,3}${Regex.escape(fence.substring(0, 1))}{${fence.length},}\\s*$")
val code = mutableListOf<String>()
i++
@@ -52,7 +97,7 @@ fun splitFences(markdown: String): List<Segment> {
code += lines[i]
i++
}
out += Segment.Code(language, code.joinToString("\n"), closed)
out += if (page != null) Segment.Page(pageTitle(page.groupValues[1]), closed) else Segment.Code(language, code.joinToString("\n"), closed)
}
flushProse()
return out
@@ -35,6 +35,7 @@ import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Archive
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.ChatBubbleOutline
@@ -90,8 +91,10 @@ 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.Drawn
import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.drawn
import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.theme.LocalPalette
@@ -112,6 +115,8 @@ fun ChatScreen(
onOpened: (String) -> Unit = {},
agent: Boolean = false,
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,
model: ChatViewModel = viewModel(key = chatId ?: if (agent) "new-agent" else "new"),
) {
val state by model.state.collectAsStateWithLifecycle()
@@ -155,6 +160,7 @@ fun ChatScreen(
onActivity = { activityOpen = true },
onShow = { showing = it },
onKind = onKind,
report = report,
)
}
@@ -167,6 +173,10 @@ fun ChatScreen(
}
}
/** What the bar says of a chat entered from a report: "Report: title", or "Report" when the title is not known. */
@Composable
private fun reportTitle(title: String): String = if (title.isBlank()) stringResource(R.string.report) else stringResource(R.string.report_chat_title, title)
/**
* The chat as it is drawn, from [state] alone: what the screenshot tests render with fake data.
* Everything it does goes through [actions].
@@ -183,6 +193,7 @@ fun ChatContent(
onActivity: () -> Unit = {},
onShow: (ShowCard) -> Unit = {},
onKind: ((agent: Boolean) -> Unit)? = null,
report: String? = null,
) {
val palette = LocalPalette.current
val context = LocalContext.current
@@ -224,13 +235,24 @@ fun ChatContent(
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(containerColor = palette.bg, scrolledContainerColor = palette.bg),
navigationIcon = {
IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) }
if (report != null) {
// A report's conversation is reached from the report, and Back returns there.
IconButton(onClick = onMenu) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back)) }
} else {
IconButton(onClick = onMenu) { Icon(Icons.Filled.Menu, contentDescription = stringResource(R.string.chats_open)) }
}
},
title = {
ModelTitle(
model = info,
fallback = state.modelId ?: stringResource(R.string.app_name),
subtitle = chat?.title?.ifBlank { null },
// 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) {
reportTitle(report?.ifBlank { null } ?: chat?.report?.title.orEmpty())
} else {
chat?.title?.ifBlank { null }
},
onClick = { picking = true },
)
},
@@ -250,10 +272,13 @@ fun ChatContent(
menu = false
actions.continueChat()
}
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
menu = false
actions.change("archived", "true")
onLeave()
// Only what may be done to this chat: a report's conversation is not archived.
if (chat.allows("archive")) {
MenuItem(Icons.Filled.Archive, stringResource(R.string.archive)) {
menu = false
actions.change("archived", "true")
onLeave()
}
}
MenuItem(Icons.Filled.Delete, stringResource(R.string.delete)) {
menu = false
@@ -334,20 +359,29 @@ fun ChatContent(
item { TextButton(onClick = actions::older) { Text(stringResource(R.string.older)) } }
}
items(rows, key = { it.id }) { message ->
when {
message.isUser -> UserMessage(message, canEdit = !message.machine && live == null, onEdit = { editing = message })
// 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)) {
// The server's own line in the person's place: nothing, or a note.
Drawn.Hidden -> Unit
live != null && live.messageId == message.id && live.finished == null ->
AssistantMessage(message, live.shown, writing = true, canRegenerate = false, onRegenerate = {}, onShow = onShow)
Drawn.Note -> MachineNote(message.text.orEmpty())
else -> AssistantMessage(
message,
message.steps,
writing = false,
canRegenerate = live == null && message == rows.lastOrNull(),
onRegenerate = { actions.regenerate(message) },
onShow = onShow,
)
Drawn.Person -> UserMessage(message, canEdit = live == null, onEdit = { editing = 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(
message,
message.steps,
writing = false,
canRegenerate = live == null && message == rows.lastOrNull(),
onRegenerate = { actions.regenerate(message) },
onShow = onShow,
)
}
}
}
}
@@ -45,6 +45,7 @@ import androidx.compose.material.icons.filled.Psychology
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.SelectAll
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Web
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
@@ -86,10 +87,12 @@ import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.ending
import eu.llembas.android.api.shownMarkdown
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.Segment
import eu.llembas.android.ui.highlight
import eu.llembas.android.ui.pageProjection
import eu.llembas.android.ui.progressLineOf
import eu.llembas.android.ui.splitFences
import eu.llembas.android.ui.theme.LocalPalette
@@ -168,6 +171,25 @@ fun UserMessage(message: Message, canEdit: Boolean, onEdit: () -> Unit, modifier
}
}
/**
* A line the server wrote in the person's place (a schedule's instruction, what opens a report's
* conversation): a quiet note across the width, a few lines of it -- never the person's bubble,
* and never markdown.
*/
@Composable
fun MachineNote(text: String, modifier: Modifier = Modifier) {
val palette = LocalPalette.current
if (text.isBlank()) return
Text(
text.trim(),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
maxLines = 4,
overflow = TextOverflow.Ellipsis,
modifier = modifier.fillMaxWidth().padding(horizontal = 8.dp),
)
}
/**
* The model's turn, full width and without a bubble: its steps (thinking and tools folded into
* chips that open), its words as markdown, and under it Copy, Regenerate and what it cost. While
@@ -296,8 +318,19 @@ fun AssistantMessage(
}
/** A reply's own words, as the person would copy them: its text steps, in order. */
fun replyText(message: Message): String =
message.steps.filter { it.kind == "text" }.mapNotNull { it.markdown }.joinToString("\n\n").ifBlank { message.text.orEmpty() }
fun replyText(message: Message): String = pageProjection(
message.steps.mapNotNull { step ->
when (step.kind) {
"text" -> step.shownMarkdown
"page" -> "[page: ${step.title.orEmpty()}]"
else -> null
}
}.joinToString("\n\n").ifBlank { message.text.orEmpty() },
untitled = PAGE_UNTITLED,
)
/** `pages.untitled`, for the text that is copied or read aloud (the card says it in the app's language). */
private const val PAGE_UNTITLED = "Page"
/** What a finished reply cost, in one quiet line: model, tokens, speed. Null when nothing was counted. */
private fun footLine(message: Message): String? {
@@ -354,8 +387,16 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
steps.forEach { step ->
when (step.kind) {
"thinking" -> ThinkingChip(step)
"text" -> RichMarkdown(step.markdown.orEmpty(), onLongPress = onLongPress)
// A closed step's pages are the server's to name (its `text`); in the step still
// being written a page's fence is a page already, not source scrolling by.
"text" -> RichMarkdown(step.shownMarkdown, onLongPress = onLongPress, pages = step.open)
// A page the server took out of the text as a step of its own: the same card.
"page" -> PageCard(step.title.orEmpty())
"tools" -> ToolsChip(step, onShow)
"steer" -> step.messages.forEach { Steered(it.text) }
}
}
@@ -364,18 +405,46 @@ fun StepsCompact(steps: List<Step>, modifier: Modifier = Modifier, onShow: ((Sho
/** Markdown with its fenced code taken out into [CodeBlock]s, each with its own Copy. */
@Composable
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null) {
val segments = remember(markdown) { splitFences(markdown) }
fun RichMarkdown(markdown: String, modifier: Modifier = Modifier, onLongPress: (() -> Unit)? = null, pages: Boolean = false) {
val segments = remember(markdown, pages) { splitFences(markdown, pages) }
Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
segments.forEach { segment ->
when (segment) {
is Segment.Prose -> MarkdownText(segment.markdown, modifier = Modifier.fillMaxWidth(), onLongPress = onLongPress)
is Segment.Code -> CodeBlock(segment.language, segment.code)
is Segment.Page -> PageCard(segment.title)
}
}
}
}
/**
* A page in an answer (harness spec 3.8.0, `pages.md`): not drawn on a phone -- no web view, and
* never its source. One quiet card says that there is one, by its title, and where it can be
* seen. The title is a model's: plain text.
*/
@Composable
fun PageCard(title: String, modifier: Modifier = Modifier) {
val palette = LocalPalette.current
Row(
modifier.fillMaxWidth().clip(Block).border(1.dp, palette.border, Block).padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Web, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(20.dp))
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(
stringResource(R.string.page_note, title.ifBlank { stringResource(R.string.page_untitled) }),
style = MaterialTheme.typography.bodyMedium,
color = palette.ink,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
Text(stringResource(R.string.page_where), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
}
}
}
/** A code block: its language and Copy above, the code below in its own sideways scroller. */
@Composable
fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) {
@@ -37,6 +37,7 @@ import androidx.compose.material.icons.filled.PushPin
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Summarize
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.DropdownMenu
@@ -72,6 +73,7 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Chat
import eu.llembas.android.api.Doorstep
import eu.llembas.android.api.Folder
@@ -103,6 +105,10 @@ data class ChatsState(
/** Chats whose messages hold the search words (`GET /search?in=chats`), and the words asked. */
val found: List<SearchHit> = emptyList(),
val foundFor: String = "",
/** How many reports are unread: the badge on Reports. */
val unreadReports: Int = 0,
/** Whether the instance has Reports at all: one before 2.0.0-beta.12 has no such page to open. */
val reports: Boolean = false,
)
/** The drawer's list: every chat of the instance in use, both kinds, newest first. */
@@ -135,7 +141,24 @@ class ChatsViewModel(app: Application) : AndroidViewModel(app) {
val page = api.chats()
// Folders are a side dish: the chats show without them if they cannot be read.
val folders = runCatching { api.folders() }.getOrDefault(_state.value.folders)
_state.value = ChatsState(chats = page.chats, more = page.more, folders = folders)
// So is the count of unread reports: an instance before Reports simply has none.
val unread = runCatching { api.unreadReports() }
// No such route (404, 405): no Reports. Any other trouble leaves what was known.
val refused = (unread.exceptionOrNull() as? ApiException)?.status
val has = if (unread.isSuccess) {
true
} else if (refused == 404 || refused == 405) {
false
} else {
_state.value.reports
}
_state.value = ChatsState(
chats = page.chats,
more = page.more,
folders = folders,
unreadReports = unread.getOrDefault(_state.value.unreadReports),
reports = has,
)
} catch (e: Exception) {
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
}
@@ -262,6 +285,7 @@ interface DrawerActions {
fun deleteFolder(folder: Folder) {}
fun files() {}
fun scheduled() {}
fun reports() {}
fun archived() {}
fun memory() {}
fun settings() {}
@@ -331,6 +355,9 @@ fun DrawerContent(
item { DrawerItem(Icons.Filled.EditNote, stringResource(R.string.new_chat), onClick = actions::newChat) }
item { DrawerItem(Icons.Filled.Terminal, stringResource(R.string.new_agent_chat), onClick = actions::newAgentChat) }
item { DrawerItem(Icons.Filled.Folder, stringResource(R.string.files), onClick = actions::files) }
if (state.reports) {
item { DrawerItem(Icons.Filled.Summarize, stringResource(R.string.reports), badge = state.unreadReports, onClick = actions::reports) }
}
item { DrawerItem(Icons.Filled.Schedule, stringResource(R.string.scheduled), onClick = actions::scheduled) }
item { DrawerItem(Icons.Filled.Inventory2, stringResource(R.string.archived), onClick = actions::archived) }
item { DrawerItem(Icons.Filled.Psychology, stringResource(R.string.memory), onClick = actions::memory) }
@@ -613,7 +640,7 @@ private fun FolderNameDialog(initial: String, title: Int, onSave: (String) -> Un
}
@Composable
private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, onClick: () -> Unit) {
private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = null, badge: Int = 0, onClick: () -> Unit) {
val palette = LocalPalette.current
Surface(
onClick = onClick,
@@ -628,6 +655,13 @@ private fun DrawerItem(icon: ImageVector, label: String, subtitle: String? = nul
Text(label, style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
subtitle?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 1, overflow = TextOverflow.Ellipsis) }
}
// A count of what is new: the words give, the badge keeps its size.
if (badge > 0) {
Spacer(Modifier.width(12.dp))
Box(Modifier.background(palette.accent, RoundedCornerShape(50)).padding(horizontal = 8.dp, vertical = 2.dp)) {
Text(if (badge > 99) "99+" else badge.toString(), style = MaterialTheme.typography.labelMedium, color = palette.bg, maxLines = 1)
}
}
}
}
}
@@ -0,0 +1,437 @@
@file:OptIn(ExperimentalMaterial3Api::class)
package eu.llembas.android.ui.reports
import android.app.Application
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Reply
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DoneAll
import androidx.compose.material.icons.filled.PriorityHigh
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.llembas.android.R
import eu.llembas.android.api.ApiClient
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Report
import eu.llembas.android.api.sortedReports
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.chat.RichMarkdown
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.pageProjection
import eu.llembas.android.ui.scheduled.BackBar
import eu.llembas.android.ui.scheduled.ScheduleLogic
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
private suspend fun Application.api(): ApiClient = lembas.instances.client() ?: throw ApiException(401, "Not signed in.")
/** A server without the reports routes answers 404 (or 405): it is older, not broken. */
private fun Throwable.unsupported(): Boolean = this is ApiException && (status == 404 || status == 405)
// --- The list --------------------------------------------------------------------------------
data class ReportsState(
val reports: List<Report> = emptyList(),
val loading: Boolean = false,
val error: String? = null,
/** The instance is older than Reports: said plainly, instead of an error. */
val unsupported: Boolean = false,
)
class ReportsViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow(ReportsState())
val state = _state.asStateFlow()
fun load() {
viewModelScope.launch {
_state.update { it.copy(loading = true, error = null) }
try {
val reports = getApplication<Application>().api().reports()
_state.value = ReportsState(reports = sortedReports(reports))
} catch (e: Exception) {
_state.update {
it.copy(loading = false, unsupported = e.unsupported(), error = if (e.unsupported()) null else getApplication<Application>().explain(e))
}
}
}
}
/** Read: it stays in the list, among those read. A failure is put right by reading the list again. */
fun markRead(report: Report) {
_state.update { s -> s.copy(reports = sortedReports(s.reports.map { if (it.id == report.id) it.copy(unread = false) else it })) }
Notifications.reportSeen(getApplication(), report.id)
viewModelScope.launch { runCatching { getApplication<Application>().api().readReport(report.id) }.onFailure { fail(it) } }
}
fun delete(report: Report) {
_state.update { s -> s.copy(reports = s.reports.filterNot { it.id == report.id }) }
Notifications.reportSeen(getApplication(), report.id)
viewModelScope.launch { runCatching { getApplication<Application>().api().deleteReport(report.id) }.onFailure { fail(it) } }
}
private fun fail(e: Throwable) {
_state.update { it.copy(error = getApplication<Application>().explain(e)) }
load()
}
}
interface ReportsActions {
fun open(report: Report) {}
fun markRead(report: Report) {}
fun delete(report: Report) {}
fun reload() {}
}
@Composable
fun ReportsScreen(onBack: () -> Unit, onOpen: (String) -> Unit, model: ReportsViewModel = viewModel()) {
val state by model.state.collectAsStateWithLifecycle()
// Read again each time the page comes up: a report opened and read is no longer bold on the way back.
LaunchedEffect(Unit) { model.load() }
ReportsContent(
state,
object : ReportsActions {
override fun open(report: Report) = onOpen(report.id)
override fun markRead(report: Report) = model.markRead(report)
override fun delete(report: Report) = model.delete(report)
override fun reload() = model.load()
},
onBack,
)
}
/**
* Reports: what scheduled tasks had to tell. The unread first; each row its title, the task it
* came from and when, with a mark where the model called it important. Pull to read the list
* again; swipe a row one way to mark it read, the other to delete it (which asks once).
*/
@Composable
fun ReportsContent(state: ReportsState, actions: ReportsActions, onBack: () -> Unit = {}) {
val palette = LocalPalette.current
var deleting by remember { mutableStateOf<Report?>(null) }
deleting?.let { report ->
AlertDialog(
onDismissRequest = { deleting = null },
title = { Text(stringResource(R.string.report_delete_title)) },
text = { Text(stringResource(R.string.report_delete_line, report.title.ifBlank { stringResource(R.string.report_untitled) })) },
confirmButton = {
TextButton(onClick = {
deleting = null
actions.delete(report)
}) { Text(stringResource(R.string.delete), color = palette.danger) }
},
dismissButton = { TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.cancel)) } },
)
}
Scaffold(containerColor = palette.bg, topBar = { BackBar(stringResource(R.string.reports), onBack) }) { padding ->
PullToRefreshBox(isRefreshing = state.loading, onRefresh = actions::reload, modifier = Modifier.fillMaxSize().padding(padding)) {
LazyColumn(
Modifier.fillMaxSize(),
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
state.error?.let { error ->
item {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
TextButton(onClick = actions::reload) { Text(stringResource(R.string.retry)) }
}
}
}
if (state.reports.isEmpty() && !state.loading && state.error == null) {
item {
Text(
stringResource(if (state.unsupported) R.string.reports_unsupported else R.string.reports_none),
color = palette.inkMuted,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(vertical = 16.dp),
)
}
}
items(state.reports, key = { it.id }) { report ->
ReportRow(report, onOpen = { actions.open(report) }, onRead = { actions.markRead(report) }, onDelete = { deleting = report })
}
}
}
}
}
/**
* One report in the list. Swiping never removes the row by itself: towards the end marks it read,
* towards the start asks whether to delete it, and either way the row comes back to rest.
*/
@Composable
private fun ReportRow(report: Report, onOpen: () -> Unit, onRead: () -> Unit, onDelete: () -> Unit) {
val palette = LocalPalette.current
val swipe = rememberSwipeToDismissBoxState(
confirmValueChange = { to ->
when (to) {
SwipeToDismissBoxValue.StartToEnd -> if (report.unread) onRead()
SwipeToDismissBoxValue.EndToStart -> onDelete()
SwipeToDismissBoxValue.Settled -> Unit
}
false
},
)
SwipeToDismissBox(
state = swipe,
enableDismissFromStartToEnd = report.unread,
backgroundContent = {
val deletes = swipe.dismissDirection == SwipeToDismissBoxValue.EndToStart
Row(
Modifier.fillMaxSize().background(
if (deletes) palette.dangerSoft else palette.surfaceActive,
RoundedCornerShape(16.dp),
).padding(horizontal = 20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = if (deletes) Arrangement.End else Arrangement.Start,
) {
Icon(
if (deletes) Icons.Filled.Delete else Icons.Filled.DoneAll,
contentDescription = stringResource(if (deletes) R.string.delete else R.string.report_mark_read),
tint = if (deletes) palette.danger else palette.inkMuted,
)
}
},
) {
Row(
Modifier
.fillMaxWidth()
.background(palette.surfaceRaised, RoundedCornerShape(16.dp))
.clickable(onClick = onOpen)
.heightIn(min = 72.dp)
.padding(horizontal = 14.dp, vertical = 12.dp),
verticalAlignment = Alignment.Top,
) {
// The unread dot's place is kept for a read row too, so the titles start on one line.
Box(Modifier.padding(top = 6.dp).size(10.dp).background(if (report.unread) palette.accent else palette.surfaceRaised, CircleShape))
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
report.title.ifBlank { stringResource(R.string.report_untitled) },
style = MaterialTheme.typography.bodyLarge,
fontWeight = if (report.unread) FontWeight.SemiBold else FontWeight.Normal,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
ReportFacts(report)
if (report.summary.isNotBlank()) {
Text(report.summary, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
if (report.high) {
Spacer(Modifier.width(8.dp))
Icon(
Icons.Filled.PriorityHigh,
contentDescription = stringResource(R.string.report_important),
tint = palette.warning,
modifier = Modifier.size(20.dp),
)
}
}
}
}
/** Under a report's title: the task it came from, and when. */
@Composable
private fun ReportFacts(report: Report) {
val palette = LocalPalette.current
val facts = listOfNotNull(report.from.ifBlank { null }, ScheduleLogic.moment(report.created)).joinToString(" · ")
if (facts.isNotBlank()) Text(facts, style = MaterialTheme.typography.bodySmall, color = palette.inkFaint, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
// --- One report ------------------------------------------------------------------------------
data class ReportState(val report: Report? = null, val loading: Boolean = true, val error: String? = null, val replying: Boolean = false)
class ReportViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow(ReportState())
val state = _state.asStateFlow()
/** Read the report, and mark it read: opening it is reading it. */
fun load(id: String) {
viewModelScope.launch {
_state.update { it.copy(loading = true, error = null) }
try {
val api = getApplication<Application>().api()
val report = api.report(id)
_state.value = ReportState(report = report.copy(unread = false), loading = false)
// Read here: its notification, if one is still up, goes.
Notifications.reportSeen(getApplication(), id)
if (report.unread) runCatching { api.readReport(id) }
} catch (e: Exception) {
_state.update { it.copy(loading = false, error = getApplication<Application>().explain(e)) }
}
}
}
/** Reply: the server continues the report as a conversation and says which chat it is. */
fun reply(then: (chat: String, title: String) -> Unit) {
val report = _state.value.report ?: return
// A reply that was begun before goes on in its chat: nothing is asked of the server.
report.chatId?.let { return then(it, report.title) }
viewModelScope.launch {
_state.update { it.copy(replying = true, error = null) }
try {
val chat = getApplication<Application>().api().replyToReport(report.id) ?: throw ApiException(502, "")
_state.update { it.copy(replying = false) }
then(chat, report.title)
} catch (e: Exception) {
_state.update { it.copy(replying = false, error = getApplication<Application>().explain(e)) }
}
}
}
}
@Composable
fun ReportScreen(id: String, onBack: () -> Unit, onReply: (chat: String, title: String) -> Unit, model: ReportViewModel = viewModel(key = "report-$id")) {
val state by model.state.collectAsStateWithLifecycle()
val context = LocalContext.current
LaunchedEffect(id) { model.load(id) }
ReportContent(
state,
onBack = onBack,
onRetry = { model.load(id) },
onReply = { model.reply(onReply) },
onShare = { report ->
val send = Intent(
Intent.ACTION_SEND,
).setType("text/plain").putExtra(Intent.EXTRA_SUBJECT, report.title).putExtra(Intent.EXTRA_TEXT, shareText(report))
runCatching { context.startActivity(Intent.createChooser(send, null)) }
},
)
}
/** What Share hands over: the title, then the report as text -- a page in it as its one line, never its source. */
fun shareText(report: Report): String {
// The server's own text of the body where it sends one; else the same made here.
val text = report.text?.trim()?.ifBlank { null } ?: pageProjection(report.body.orEmpty(), untitled = "Page")
return listOf(report.title, text).filter { it.isNotBlank() }.joinToString("\n\n")
}
/**
* A report, read as a page: its title, where it came from and when, then the body -- Markdown a
* model wrote, drawn as the chat draws a reply (untrusted: no images, no HTML; a page in it is a
* card, not a page). Reply stays at the foot; Share is in the bar.
*/
@Composable
fun ReportContent(state: ReportState, onBack: () -> Unit = {}, onRetry: () -> Unit = {}, onReply: () -> Unit = {}, onShare: (Report) -> Unit = {}) {
val palette = LocalPalette.current
val report = state.report
Scaffold(
containerColor = palette.bg,
topBar = {
BackBar(stringResource(R.string.report), onBack) {
if (report !=
null
) {
IconButton(onClick = { onShare(report) }) { Icon(Icons.Filled.Share, contentDescription = stringResource(R.string.report_share)) }
}
}
},
bottomBar = {
if (report != null) {
Box(Modifier.background(palette.bg).navigationBarsPadding().padding(16.dp)) {
Button(onClick = onReply, enabled = !state.replying, modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp)) {
if (state.replying) {
CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(18.dp))
} else {
Icon(Icons.AutoMirrored.Filled.Reply, contentDescription = null, modifier = Modifier.size(18.dp))
}
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.report_reply))
}
}
}
},
) { padding ->
Column(
Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
state.error?.let { error ->
Row(verticalAlignment = Alignment.CenterVertically) {
Text(error, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
if (report == null) TextButton(onClick = onRetry) { Text(stringResource(R.string.retry)) }
}
}
if (report == null) {
if (state.loading) CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.size(24.dp))
} else {
Row(verticalAlignment = Alignment.Top) {
Text(
report.title.ifBlank { stringResource(R.string.report_untitled) },
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier.weight(1f),
)
if (report.high) {
Spacer(Modifier.width(8.dp))
Icon(Icons.Filled.PriorityHigh, contentDescription = stringResource(R.string.report_important), tint = palette.warning)
}
}
ReportFacts(report)
// The server's own text of the body, where each page is its one line; else the body.
RichMarkdown((report.text?.ifBlank { null } ?: report.body.orEmpty()).ifBlank { report.summary })
}
}
}
}
@@ -77,6 +77,7 @@ fun RunScreen(
runId: String,
onBack: () -> Unit,
onOpenChat: (String) -> Unit,
onOpenReport: (String) -> Unit = {},
model: RunViewModel = viewModel(key = "run-$scheduleId-$runId"),
) {
val state by model.state.collectAsStateWithLifecycle()
@@ -84,7 +85,7 @@ fun RunScreen(
model.open(scheduleId, runId)
onPauseOrDispose { }
}
RunContent(state, onBack = onBack, onOpenChat = onOpenChat)
RunContent(state, onBack = onBack, onOpenChat = onOpenChat, onOpenReport = onOpenReport)
}
/**
@@ -93,7 +94,7 @@ fun RunScreen(
* links only outside) -- or why there is none. Open its chat goes on from there.
*/
@Composable
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}) {
fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) -> Unit = {}, onOpenReport: (String) -> Unit = {}) {
val palette = LocalPalette.current
val context = LocalContext.current
val copy: (String) -> Unit = remember(context) {
@@ -128,6 +129,8 @@ fun RunContent(state: RunState, onBack: () -> Unit = {}, onOpenChat: (String) ->
)
}
RunFacts(run, withPreview = false)
// What the run filed for the person, when it filed anything.
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
}
}
Header(stringResource(R.string.run_result))
@@ -4,6 +4,7 @@ package eu.llembas.android.ui.scheduled
import android.app.Application
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -33,6 +34,7 @@ import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Summarize
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
@@ -44,6 +46,7 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
@@ -62,6 +65,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
@@ -83,6 +87,7 @@ import eu.llembas.android.api.ScheduleRun
import eu.llembas.android.api.SchedulesFrame
import eu.llembas.android.api.StreamClient
import eu.llembas.android.api.computerAway
import eu.llembas.android.api.notifyChoice
import eu.llembas.android.lembas
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.progressLineOf
@@ -424,6 +429,7 @@ fun ScheduleScreen(
onBack: () -> Unit,
onEdit: (String) -> Unit,
onOpenRun: (String) -> Unit,
onOpenReport: (String) -> Unit = {},
model: ScheduleViewModel = viewModel(key = "schedule-$id"),
) {
val state by model.state.collectAsStateWithLifecycle()
@@ -447,6 +453,7 @@ fun ScheduleScreen(
onRunNow = model::runNow,
onPause = model::pause,
onOpenRun = { run -> onOpenRun(run.id) },
onOpenReport = onOpenReport,
onMore = model::more,
)
}
@@ -466,6 +473,7 @@ fun ScheduleContent(
onRunNow: () -> Unit = {},
onPause: (Boolean) -> Unit = {},
onOpenRun: (ScheduleRun) -> Unit = {},
onOpenReport: (String) -> Unit = {},
onMore: () -> Unit = {},
) {
val palette = LocalPalette.current
@@ -488,7 +496,7 @@ fun ScheduleContent(
if (state.loading) CircularProgressIndicator() else state.error?.let { Message(it) }
}
} else {
ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onMore)
ScheduleBody(state, schedule, padding, onRunNow, onPause, onOpenRun, onOpenReport, onMore)
}
}
if (deleting) {
@@ -514,6 +522,7 @@ private fun ScheduleBody(
onRunNow: () -> Unit,
onPause: (Boolean) -> Unit,
onOpenRun: (ScheduleRun) -> Unit,
onOpenReport: (String) -> Unit,
onMore: () -> Unit,
) {
val palette = LocalPalette.current
@@ -534,7 +543,7 @@ private fun ScheduleBody(
val facts = listOfNotNull(
schedule.model?.takeIf { it.isNotBlank() }?.let { stringResource(R.string.schedule_model, it) },
modeWords(schedule.mode),
notifyWords(schedule.notify),
notifyWords(schedule),
)
if (facts.isNotEmpty()) {
Text(facts.joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
@@ -595,16 +604,27 @@ private fun ScheduleBody(
)
}
}
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }) }
items(state.runs, key = { it.id }) { run -> RunRow(run, schedule.runsOn, onOpen = { onOpenRun(run) }, onOpenReport = onOpenReport) }
if (state.more) item { LaunchedEffect(state.runs.size) { onMore() } }
}
}
@Composable
private fun notifyWords(notify: String): String? = when (notify) {
private fun notifyWords(schedule: Schedule): String? = when (schedule.notify) {
"always" -> stringResource(R.string.notify_always)
// "When…" with the person's own words (spec 3.8.0); a server before it said "matters".
"when" -> stringResource(
R.string.notify_when_words,
schedule.notifyWhen.ifBlank {
schedule.notifyDefault.ifBlank { stringResource(R.string.notify_when_default) }
},
)
"matters" -> stringResource(R.string.notify_matters)
"never" -> stringResource(R.string.notify_never)
else -> null
}
@@ -696,7 +716,7 @@ internal fun Header(text: String) {
* whole row opens the run.
*/
@Composable
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit) {
private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit, onOpenReport: (String) -> Unit = {}) {
val palette = LocalPalette.current
Surface(
onClick = onOpen,
@@ -712,12 +732,27 @@ private fun RunRow(run: ScheduleRun, runsOn: RunsOn?, onOpen: () -> Unit) {
// Which computer the run was for, and whether it was away.
runsOn?.let { on -> ComputerName(on, away = run.computerAway) }
RunFacts(run, maxLines = 2)
run.reportId?.let { report -> ReportLink(onClick = { onOpenReport(report) }) }
}
}
}
}
/** Under a run's time: the model and why, then the result's first lines, or the trouble. */
/** A run that filed a report: the way to it, a tap target of its own inside the run's row. */
@Composable
internal fun ReportLink(onClick: () -> Unit) {
val palette = LocalPalette.current
Row(
Modifier.clip(RoundedCornerShape(12.dp)).clickable(onClick = onClick).heightIn(min = 40.dp).padding(end = 12.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Filled.Summarize, contentDescription = null, tint = palette.accent, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(stringResource(R.string.run_open_report), style = MaterialTheme.typography.labelLarge, color = palette.accent)
}
}
/** 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) {
val palette = LocalPalette.current
@@ -744,7 +779,11 @@ internal fun RunFacts(run: ScheduleRun, maxLines: Int = Int.MAX_VALUE, withPrevi
val tone = if (run.status == "waiting") palette.inkMuted else palette.danger
Text(it, style = MaterialTheme.typography.bodySmall, color = tone, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
}
if (withPreview && run.preview.isNotBlank()) {
// The run's own line for the history (spec 3.8.0): what it found, or why it filed no report.
// A model's words: plain text. A server before it sends the result's first lines instead.
if (run.note.isNotBlank()) {
Text(run.note, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
} else if (withPreview && run.preview.isNotBlank()) {
Text(run.preview, style = MaterialTheme.typography.bodySmall, color = palette.ink, maxLines = maxLines, overflow = TextOverflow.Ellipsis)
}
}
@@ -758,8 +797,33 @@ data class EditState(
val saving: Boolean = false,
val error: String? = null,
val unsupported: Boolean = false,
/** Notify when (spec 3.8.0): `always`, `when` or `never`, and the person's words for `when` (empty: the default). */
val notify: String = "when",
val notifyWhen: String = "",
/** Whether the instance has Reports (LLeMbas 2.0.0-beta.12): an older one is neither shown nor sent "notify when". */
val reports: Boolean = false,
/** The server's default condition in the account's language, when it said one. */
val notifyDefault: String = "",
/** Editing: the schedule was read, so the form shows what it really has; or reading it failed, and nothing may be saved over it. */
val loaded: Boolean = false,
val loadFailed: Boolean = false,
/** The person chose a "notify when" themselves. */
val notifyTouched: Boolean = false,
)
/**
* 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
* person's choice. A form that could not read the schedule must not write its default over an
* "every run" or a "never".
*/
fun notifyToSend(state: EditState, editing: Boolean): String? = when {
!state.reports -> null
!editing -> state.notify
state.loaded || state.notifyTouched -> state.notify
else -> null
}
class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
private val _state = MutableStateFlow(EditState())
val state = _state.asStateFlow()
@@ -771,16 +835,38 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
if (started) return
started = true
editing = id
// "Notify when" belongs to an instance that files reports; one that has no such route
// would refuse the new values, so it is asked first.
viewModelScope.launch {
val has = runCatching { getApplication<Application>().api().reports(unread = true) }.isSuccess
_state.update { it.copy(reports = has) }
}
if (id == null) return
viewModelScope.launch {
runCatching { getApplication<Application>().api().schedule(id) }.onSuccess { s ->
_state.update { it.copy(words = s.request.ifBlank { s.instruction }) }
_state.update {
it.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),
notifyWhen = if (it.notifyTouched) it.notifyWhen else s.notifyWhen,
notifyDefault = s.notifyDefault,
loaded = true,
)
}
}.onFailure { e ->
// Not read: said, and Save waits -- the form would write its own defaults over the schedule.
_state.update { it.copy(loadFailed = true, error = getApplication<Application>().explain(e)) }
}
}
}
fun words(text: String) = _state.update { it.copy(words = text, compiled = null) }
fun notify(value: String) = _state.update { it.copy(notify = notifyChoice(value), notifyTouched = true) }
fun notifyWhen(text: String) = _state.update { it.copy(notifyWhen = text, notifyTouched = true) }
/** The server reads the words: the title, the instruction, the rule and the next runs. */
fun preview() {
val words = _state.value.words.trim()
@@ -803,7 +889,14 @@ class ScheduleEditViewModel(app: Application) : AndroidViewModel(app) {
viewModelScope.launch {
_state.update { it.copy(saving = true, error = null) }
try {
val saved = getApplication<Application>().api().saveSchedule(compiled, _state.value.words.trim(), editing)
val now = _state.value
val saved = getApplication<Application>().api().saveSchedule(
compiled,
now.words.trim(),
editing,
notify = notifyToSend(now, editing = editing != null),
notifyWhen = now.notifyWhen,
)
then(saved.id)
} catch (e: Exception) {
_state.update { it.copy(saving = false, error = getApplication<Application>().explain(e)) }
@@ -821,7 +914,16 @@ fun ScheduleEditScreen(
) {
val state by model.state.collectAsStateWithLifecycle()
LaunchedEffect(id) { model.start(id) }
ScheduleEditContent(state, editing = id != null, onBack = onBack, onWords = model::words, onPreview = model::preview, onSave = { model.save(onSaved) })
ScheduleEditContent(
state,
editing = id != null,
onBack = onBack,
onWords = model::words,
onPreview = model::preview,
onSave = { model.save(onSaved) },
onNotify = model::notify,
onNotifyWhen = model::notifyWhen,
)
}
/**
@@ -838,6 +940,8 @@ fun ScheduleEditContent(
onWords: (String) -> Unit = {},
onPreview: () -> Unit = {},
onSave: () -> Unit = {},
onNotify: (String) -> Unit = {},
onNotifyWhen: (String) -> Unit = {},
) {
val palette = LocalPalette.current
Scaffold(
@@ -847,7 +951,7 @@ fun ScheduleEditContent(
Box(Modifier.background(palette.bg).navigationBarsPadding().imePadding().padding(16.dp)) {
Button(
onClick = onSave,
enabled = state.compiled?.savable == true && !state.saving,
enabled = state.compiled?.savable == true && !state.saving && !state.loadFailed,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
) { Text(stringResource(R.string.save)) }
}
@@ -880,11 +984,61 @@ fun ScheduleEditContent(
if (state.unsupported) Text(stringResource(R.string.scheduled_unsupported), color = palette.inkMuted)
state.error?.let { Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium) }
state.compiled?.let { Understood(it) }
if (state.reports) NotifyWhen(state.notify, state.notifyWhen, state.notifyDefault, onNotify, onNotifyWhen)
Spacer(Modifier.height(24.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
* task's history. "When…" opens a field with the default already in it.
*/
@Composable
private fun NotifyWhen(notify: String, words: String, default: String, onNotify: (String) -> Unit, onWords: (String) -> Unit) {
val palette = LocalPalette.current
val choices = listOf(
Triple("always", R.string.notify_every_run, R.string.notify_every_run_line),
Triple("when", R.string.notify_when_option, R.string.notify_when_line),
Triple("never", R.string.notify_never_option, R.string.notify_never_line),
)
Surface(shape = RoundedCornerShape(20.dp), color = palette.surfaceRaised, contentColor = palette.ink, modifier = Modifier.fillMaxWidth()) {
Column(Modifier.padding(vertical = 12.dp)) {
Text(
stringResource(R.string.notify_when),
style = MaterialTheme.typography.labelLarge,
color = palette.accent,
modifier = Modifier.padding(horizontal = 16.dp),
)
choices.forEach { (value, title, line) ->
Row(
Modifier.fillMaxWidth().clickable { onNotify(value) }.heightIn(min = 56.dp).padding(start = 4.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected = notify == value, onClick = { onNotify(value) })
Column(Modifier.weight(1f)) {
Text(stringResource(title), style = MaterialTheme.typography.bodyLarge)
Text(stringResource(line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
}
}
if (value == "when" && notify == "when") {
val usual = default.ifBlank { stringResource(R.string.notify_when_default) }
OutlinedTextField(
// Empty is allowed and means the default, which stands there as the placeholder.
value = words,
onValueChange = onWords,
label = { Text(stringResource(R.string.notify_when_label)) },
placeholder = { Text(usual) },
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth().padding(start = 52.dp, end = 16.dp, bottom = 8.dp),
)
}
}
}
}
}
/** What the server made of the words. The title and instruction are a model's: plain text. */
@Composable
private fun Understood(c: ScheduleCompiled) {
@@ -4,7 +4,6 @@ package eu.llembas.android.ui.settings
import android.Manifest
import android.app.Activity
import android.app.role.RoleManager
import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemClock
@@ -40,6 +39,7 @@ import androidx.compose.material.icons.filled.ErrorOutline
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.MyLocation
@@ -48,6 +48,7 @@ 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
@@ -93,6 +94,8 @@ 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.assist.LembasAssistService
import eu.llembas.android.assist.PhoneRecognizer
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
@@ -107,6 +110,8 @@ import eu.llembas.android.update.UpdateResult
import eu.llembas.android.update.Updater
import eu.llembas.android.update.checksUpdates
import eu.llembas.android.update.offersBetas
import eu.llembas.android.wake.AssistLink
import eu.llembas.android.wake.WakeAttempt
import eu.llembas.android.wake.WakeEngine
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakePause
@@ -117,7 +122,9 @@ import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeStatus
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
@@ -132,6 +139,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) {}
@@ -181,12 +189,18 @@ data class SettingsState(
val wakeTest: WakeTestShown = WakeTestShown(),
/** Whether LLeMbas is the phone's digital assistant app: only then can the wake word open it over other apps. */
val isAssistant: Boolean = true,
/** Whether Android has the assistant service connected right now: without it the wake word cannot open the sheet by itself. */
val assistantConnected: Boolean = true,
/** Whether Android itself uses LLeMbas's service as its voice assistant (the role can be held without it). */
val assistantActive: Boolean = true,
/** Whether Android's notification access is given to LLeMbas. */
val notificationAccess: Boolean = false,
/** Whether this build can read notifications at all (only the `notifications` build declares the listener). */
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
@@ -198,6 +212,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
val active by store.active.collectAsState(initial = null)
val prefs by store.prefs.collectAsState(initial = Prefs())
val wakeState by WakeStatus.state.collectAsState()
val assistantConnected by AssistLink.connected.collectAsState()
// The test's ten seconds: its deadline is WakeStatus's, the clock that watches it is here.
val trial by WakeStatus.trial.collectAsState()
var clock by remember { mutableStateOf(SystemClock.elapsedRealtime()) }
@@ -209,6 +224,18 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
}
clock = SystemClock.elapsedRealtime()
}
// The instance's models, for the assistant's: asked for each time Settings opens on an instance.
var models by remember { mutableStateOf(emptyList<ModelInfo>()) }
LaunchedEffect(active?.id) {
models = try {
store.client()?.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) }
@@ -270,6 +297,10 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
scope.launch { store.savePrefs { it.copy(assistantTemporary = on) } }
}
override fun assistantModel(id: String) {
scope.launch { store.savePrefs { it.copy(assistantModel = id) } }
}
override fun voiceInput(value: String) {
scope.launch { store.savePrefs { it.copy(voiceInput = value) } }
}
@@ -403,12 +434,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
wakeAvailable = WakeEngine.AVAILABLE,
wakeState = wakeState,
// Read again each time Settings is composed: the person comes back from the system's page.
isAssistant = context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) ?: false,
isAssistant = LembasAssistService.holdsRole(context),
assistantConnected = assistantConnected,
assistantActive = LembasAssistService.isActive(context),
wakeTest = WakeTestShown(running = clock < trial.until, done = tested && clock >= trial.until, heard = if (tested) trial.heard else 0),
// Read again each time Settings is composed: the person comes back from the system's page.
notificationAccess = NotificationAccess.granted(context),
notificationsBuild = NotificationAccess.AVAILABLE,
navApps = remember { NavApp.installedApps(context).map { it.id } },
assistantModels = models,
),
actions,
onBack,
@@ -433,6 +467,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 = {
@@ -556,6 +599,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),
@@ -566,6 +618,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) },
)
@@ -581,6 +634,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 = {
@@ -592,6 +646,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,
@@ -695,11 +756,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) },
@@ -733,6 +798,29 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
subtitle = stringResource(R.string.wake_not_assistant_line),
onClick = actions::assistantSettings,
)
} else if (!state.assistantActive) {
// Chosen as the assistant, yet Android does not run it as its voice assistant:
// the long press opens it as an ordinary screen, and nothing is connected that
// could open it from the background. Choosing it again puts that right.
Rule()
SettingRow(
Icons.Filled.Assistant,
stringResource(R.string.wake_assistant_inactive),
subtitle = stringResource(R.string.wake_assistant_inactive_line),
tint = palette.warning,
onClick = actions::assistantSettings,
)
} else if (!state.assistantConnected) {
// The assistant in name, but Android holds no connection to it at this moment:
// the one thing that lets the sheet open from the background is missing.
Rule()
SettingRow(
Icons.Filled.Assistant,
stringResource(R.string.wake_assistant_unbound),
subtitle = stringResource(R.string.wake_assistant_unbound_line),
tint = palette.warning,
onClick = actions::assistantSettings,
)
}
}
if (state.wakeAvailable) {
@@ -770,6 +858,8 @@ internal fun WakeWordGroup(state: SettingsState, actions: SettingsActions, onCho
Rule()
WakeTestRow(state, on, phrase.words, actions)
Rule()
WakeLogRow(state.prefs.wakeLog)
Rule()
SettingRow(
Icons.Filled.ScreenLockPortrait,
stringResource(R.string.wake_screen_only),
@@ -888,21 +978,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))
@@ -919,6 +1026,7 @@ private fun SettingRow(
tint: Color? = null,
enabled: Boolean = true,
showIcon: Boolean = true,
badge: String? = null,
trailing: (@Composable () -> Unit)? = null,
) {
val palette = LocalPalette.current
@@ -937,6 +1045,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) {
@@ -1005,6 +1115,28 @@ private fun WakeTestRow(state: SettingsState, on: Boolean, phrase: String, actio
)
}
/**
* "Last wake": what happened the last time the phrase was heard -- what was tried and how it
* went, in plain words, with Android's own where it refused -- and, on a tap, the few before it.
*/
@Composable
private fun WakeLogRow(log: List<WakeAttempt>) {
val context = LocalContext.current
var all by remember { mutableStateOf(false) }
val shown = if (all) log else log.take(1)
SettingRow(
Icons.Filled.History,
stringResource(R.string.wake_last),
subtitle = if (log.isEmpty()) {
stringResource(R.string.wake_last_none)
} else {
shown.joinToString("\n\n") { wakeAttemptWords(context, it).joinToString("\n") }
},
enabled = log.isNotEmpty(),
onClick = { all = !all },
)
}
private const val GOOGLE = "google"
private fun sensitivityLabel(sensitivity: WakeSensitivity): Int = when (sensitivity) {
@@ -1051,6 +1183,40 @@ 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 chosen = state.prefs.assistantModel
val model = state.assistantModels.firstOrNull { it.id == 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.name.ifBlank { model.id }
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) {
val chosen = state.prefs.assistantModel.takeIf { id -> state.assistantModels.any { it.id == id } }.orEmpty()
val choices = listOf(
Choice(INSTANCE_DEFAULT, stringResource(R.string.assistant_model_default), stringResource(R.string.assistant_model_default_line), chosen.isEmpty()),
) + state.assistantModels.map { Choice(it.id, it.name.ifBlank { it.id }, null, it.id == 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. */
@@ -1,4 +1,4 @@
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.11. Do not edit.
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.13. Do not edit.
package eu.llembas.android.ui.theme
import androidx.compose.ui.graphics.Color
@@ -14,6 +14,9 @@ import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
@@ -147,27 +150,6 @@ object AssistPresence {
}
}
/** How the assistant is opened when the word was heard, from what Android will allow. */
enum class WakeOpening {
/** LLeMbas is the phone's assistant: its voice-interaction service shows the sheet, from anywhere. */
Session,
/** The app is on screen: the sheet's activity may start. */
Activity,
/**
* Neither: Android blocks an activity started from the background, and says nothing when it
* does -- so it is not relied on, and a notification to tap is posted.
*/
Notification,
}
fun wakeOpening(isAssistant: Boolean, appVisible: Boolean): WakeOpening = when {
isAssistant -> WakeOpening.Session
appVisible -> WakeOpening.Activity
else -> WakeOpening.Notification
}
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
object AppVisibility {
private val started = AtomicInteger(0)
@@ -301,6 +283,53 @@ object WakeStatus {
const val TRIAL_MS = 10_000L
}
/**
* One [attempt] in plain words, a line each: when and for which phrase; what was tried and how it
* went (Android's own words where it refused); what was done instead; and, where the assistant
* could not be used, what Android had said of it -- whether LLeMbas held the role, and when the
* service was connected and disconnected in this run of the app.
*/
fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> {
fun time(at: Long): String = DateTimeFormatter.ofPattern("EEE d MMM, HH:mm:ss", locale).format(Instant.ofEpochMilli(at).atZone(zone))
val lines = mutableListOf("${time(attempt.at)} · “${attempt.phrase}”")
lines += when (attempt.outcome) {
WakeAttempt.OUT_OPENED -> context.getString(R.string.wake_out_opened)
WakeAttempt.OUT_TESTED -> context.getString(R.string.wake_out_tested)
WakeAttempt.OUT_NO_SHEET -> context.getString(R.string.wake_out_no_sheet)
WakeAttempt.OUT_REFUSED -> context.getString(R.string.wake_out_refused, attempt.detail)
else -> context.getString(R.string.wake_out_not_connected)
}
when (attempt.fallback) {
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
}
if (attempt.outcome == WakeAttempt.OUT_TESTED) return lines
if (attempt.sheetMs >= 0) lines += context.getString(R.string.wake_sheet_ms, attempt.sheetMs.toString())
if (attempt.outcome == WakeAttempt.OUT_OPENED) return lines
// Why the assistant's own way was not there, from what Android itself said at that moment.
lines += when {
!attempt.assistant -> context.getString(R.string.wake_role_not_held)
!attempt.recognizers -> context.getString(R.string.wake_no_recognizers)
!attempt.active -> context.getString(R.string.wake_not_active)
else -> context.getString(R.string.wake_role_held)
}
if (attempt.waited) lines += context.getString(R.string.wake_waited)
if (attempt.showFailed) lines += context.getString(R.string.wake_show_failed)
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
// The rest as it was noted, for whoever looks for the cause: names and values, not a sentence.
lines += listOf(
"screen=${if (attempt.screenOn) "on" else "off"}",
"locked=${attempt.locked}",
"visible=${attempt.visible}",
"created=${if (attempt.createdAt == 0L) "-" else time(attempt.createdAt)}",
"destroyed=${if (attempt.destroyedAt == 0L) "-" else time(attempt.destroyedAt)}",
"prepared=${attempt.prepared}",
).joinToString(" ")
return lines
}
/**
* What the service's notification says the moment Android starts it (again): what is true --
* [current], while its loop is [running]; "starting" for a service that has only just begun.
@@ -46,6 +46,8 @@ class WakeListener(
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
// Where a heard word is answered: beside the listening, so a pause does not cancel the answer.
val answers = this
var hearing: Job? = null
try {
plans.distinctUntilChanged().collect { plan ->
@@ -54,7 +56,7 @@ class WakeListener(
if (plan.pause != WakePause.None) {
say(WakeState.Paused(plan.pause))
} else {
hearing = launch { hear(plan) }
hearing = launch { hear(plan) { phrase -> answers.launch { heard(phrase) } } }
}
}
} finally {
@@ -80,14 +82,17 @@ class WakeListener(
fun retryNow() = nudges.update { it + 1 }
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
private suspend fun hear(plan: WakePlan) {
private suspend fun hear(plan: WakePlan, heardIt: (WakePhrase) -> Unit) {
var failures = 0
while (true) {
try {
listened = 0
listen(plan)
failures = 0
heard(plan.phrase)
// Handed to the caller's scope, not run here: answering the word usually pauses
// the listening (the sheet takes the microphone), which cancels this very loop --
// and must not cancel the answer with it.
heardIt(plan.phrase)
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
delay(HEARD_REST_MS)
} catch (e: CancellationException) {
@@ -0,0 +1,303 @@
package eu.llembas.android.wake
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.serialization.Serializable
/**
* What happened the last times the wake word was heard: kept (the last [WAKE_LOG_SIZE], in the
* phone's settings) and shown in Settings › Wake word, because "it heard me and nothing opened"
* cannot be put right without knowing which step said no. Nothing of the account is in it: the
* phrase, clock times, and Android's own words where it refused.
*/
@Serializable
data class WakeAttempt(
/** When the phrase was heard (wall clock, ms). */
val at: Long = 0,
val phrase: String = "",
/** What was tried first: a [WakeWay]'s id. */
val way: String = "",
/** How that went: one of the `OUT_…` words. */
val outcome: String = "",
/** Android's own words when it refused: the exception's class and message. */
val detail: String = "",
/** What was done instead, when the first way did not open the sheet: `activity`, `notification` or nothing. */
val fallback: String = "",
/** Whether Android said LLeMbas holds the assistant role at that moment. */
val assistant: Boolean = false,
/** When Android last connected the assistant service in this run of the app, and last disconnected it; 0: never. */
val readyAt: Long = 0,
val shutdownAt: Long = 0,
/** Set afterwards, when the service was not connected and Android connected it later. */
val connectedLater: Long = 0,
/**
* Whether Android itself said LLeMbas's service is its active voice-interaction service
* (`VoiceInteractionService.isActiveService`). The role can be held without it: Android then
* opens the assistant as an ordinary screen on a long press, and keeps no connection that
* could open it from the background.
*/
val active: Boolean = false,
/** Whether the phone has voice recognisers at all (`FEATURE_VOICE_RECOGNIZERS`): without it Android runs no voice-interaction service. */
val recognizers: Boolean = true,
val screenOn: Boolean = true,
val locked: Boolean = false,
/** Whether one of the app's own screens was showing. */
val visible: Boolean = false,
/** How long the sheet took to say it was up, in ms; -1 when none came. */
val sheetMs: Long = -1,
/** When the assistant service was last made and destroyed in this run of the app; 0: never. */
val createdAt: Long = 0,
val destroyedAt: Long = 0,
/** Whether the wake waited for Android to connect the service (it was active but not connected yet). */
val waited: Boolean = false,
/** What Android told the service about this show (API 34+): it prepared one, or it failed. */
val prepared: Boolean = false,
val showFailed: Boolean = false,
) {
companion object {
/** The sheet came up. */
const val OUT_OPENED = "opened"
/** Android was asked and did not refuse, but no sheet came up in time. */
const val OUT_NO_SHEET = "no_sheet"
/** The assistant service was not connected (`LembasAssistService.current` was null). */
const val OUT_NOT_CONNECTED = "not_connected"
/** Android refused, with [detail]. */
const val OUT_REFUSED = "refused"
/** A test in Settings took the word: nothing was to open. */
const val OUT_TESTED = "tested"
}
}
const val WAKE_LOG_SIZE = 5
/** [log] with [attempt] put first, cut to the last [WAKE_LOG_SIZE]. */
fun wakeLogAdd(log: List<WakeAttempt>, attempt: WakeAttempt): List<WakeAttempt> = (listOf(attempt) + log).take(WAKE_LOG_SIZE)
/**
* Android connected the assistant service at [now]: the newest attempt that found it not
* connected, and has not been answered yet, is told so. Anything else is left as it is.
*/
fun wakeLogConnected(log: List<WakeAttempt>, now: Long): List<WakeAttempt> {
val newest = log.firstOrNull() ?: return log
if (newest.outcome != WakeAttempt.OUT_NOT_CONNECTED || newest.connectedLater != 0L || now < newest.at) return log
return listOf(newest.copy(connectedLater = now)) + log.drop(1)
}
/** The ways the assistant may be opened when the word was heard, in the order they are worth trying. */
enum class WakeWay(val id: String) {
/** The assistant service is connected and the screen is on: it shows its sheet, from anywhere. */
Session("session"),
/**
* The assistant service is connected and the screen is off: a session's window turns no
* screen on, so the sheet's activity is started through the service instead (Android lets an
* app whose service the system has bound start one), and the activity turns the screen on.
*/
AssistantActivity("assistant_activity"),
/** No connected assistant service, but the app is on screen: the sheet's activity may start. */
Activity("activity"),
/**
* Neither: Android blocks an activity started from the background, and says nothing when it
* does -- so it is not relied on, and a notification to tap is posted.
*/
Notification("notification"),
// A further way (answering by voice without a sheet) would be one more entry here, chosen in
// [wakeWay] and carried out where the others are.
}
/** The first way to try, from what is true at that moment. */
fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay = when {
connected && screenOn -> WakeWay.Session
connected -> WakeWay.AssistantActivity
appVisible -> WakeWay.Activity
else -> WakeWay.Notification
}
/**
* The assistant service's life in this run of the app, as Android told it: when it was made,
* connected (`onReady`), disconnected (`onShutdown`) and destroyed, what Android said of the last
* show it was asked for, and when a sheet last came up. Written by the assistant service, the
* session and the sheet's activity; read when the word is heard.
*/
object AssistLink {
@Volatile var createdAt = 0L
private set
@Volatile var destroyedAt = 0L
private set
@Volatile var readyAt = 0L
private set
@Volatile var shutdownAt = 0L
private set
/** On the phone's elapsed clock: when Android last said it prepares to show a session, and when one failed to show. */
@Volatile var preparedAt = 0L
private set
@Volatile var showFailedAt = 0L
private set
private val _shown = MutableStateFlow(0L)
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
val shown: StateFlow<Long> = _shown.asStateFlow()
private val _connected = MutableStateFlow(false)
/** Whether Android has the assistant service connected right now. */
val connected: StateFlow<Boolean> = _connected.asStateFlow()
fun created(now: Long) {
createdAt = now
}
fun destroyed(now: Long) {
destroyedAt = now
}
fun ready(now: Long) {
readyAt = now
_connected.value = true
}
fun shutdown(now: Long) {
shutdownAt = now
_connected.value = false
}
fun prepared(elapsed: Long) {
preparedAt = elapsed
}
fun showFailed(elapsed: Long) {
showFailedAt = elapsed
}
fun sheetShown(elapsed: Long) {
_shown.value = elapsed
}
}
/** What is true of the phone and the assistant at the moment the phrase is heard. */
data class WakeFacts(
/** The assistant service is connected (`LembasAssistService.current` is there). */
val connected: Boolean,
/** Android says the service is its active voice-interaction service. */
val active: Boolean,
/** LLeMbas holds the assistant role. */
val role: Boolean,
val recognizers: Boolean = true,
val screenOn: Boolean = true,
val locked: Boolean = false,
val visible: Boolean = false,
)
/**
* Opening the assistant when the phrase was heard, apart from Android so that the order of what
* is tried -- and what is written down about it -- can be tested.
*
* 1. The assistant's own way, where its service is connected ([wakeWay]). When Android says the
* service is active but has not connected it yet, a moment is waited for the connection.
* 2. "Opened" only once a sheet says it is up ([sheetCame]).
* 3. Otherwise the sheet's activity -- relied on only where Android will start it: the service is
* connected (a bound service lets the whole app start activities) or the app is on screen. A
* session that was only slow is given a second wait first, so there are never two sheets.
* 4. Otherwise a notification to tap.
*
* [open] returns what happened, for the record.
*/
class WakeOpener(
private val facts: () -> WakeFacts,
/** Wait up to the given ms for Android to connect the service; whether it did. */
private val awaitConnected: suspend (Long) -> Boolean,
/** Ask the connected service to show its sheet; throws what Android throws. */
private val showSession: () -> Unit,
/** Start the sheet's activity; throws what Android throws. */
private val startActivity: () -> Unit,
/** Wait up to the given ms for a sheet to say it is up; how long it took, or null. */
private val sheetCame: suspend (Long) -> Long?,
private val notify: (WakeAttempt) -> Unit,
/** What Android said of the show since it was asked: prepared, failed. */
private val showSignals: () -> Pair<Boolean, Boolean> = { false to false },
private val now: () -> Long = System::currentTimeMillis,
) {
suspend fun open(phrase: String, link: WakeAttempt = WakeAttempt()): WakeAttempt {
var seen = facts()
var waited = false
if (!seen.connected && seen.active) {
// Android's own assistant, only not connected at this instant: it may be on its way.
waited = true
if (awaitConnected(CONNECT_WAIT_MS)) seen = facts().copy(connected = true)
}
val way = wakeWay(seen.connected, seen.screenOn, seen.visible)
var attempt = link.copy(
at = now(),
phrase = phrase,
way = way.id,
assistant = seen.role,
active = seen.active,
recognizers = seen.recognizers,
screenOn = seen.screenOn,
locked = seen.locked,
visible = seen.visible,
waited = waited,
)
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
val refused = runCatching { if (way == WakeWay.Session) showSession() else startActivity() }.exceptionOrNull()
val took = if (refused == null) sheetCame(SHEET_WAIT_MS) else null
val (prepared, failed) = showSignals()
attempt = attempt.copy(prepared = prepared, showFailed = failed)
if (took != null) return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = took)
attempt = if (refused != null) {
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = describe(refused))
} else {
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
}
// The activity was the way that just did not come up: starting it a second time is no fallback.
if (way == WakeWay.AssistantActivity && refused == null) return notified(attempt)
// A session Android did not refuse may only be slow: a second wait, before anything
// else is put on screen beside it.
if (refused == null) {
sheetCame(SHEET_WAIT_MS)?.let { late -> return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = SHEET_WAIT_MS + late) }
}
} else {
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
}
// The sheet's activity. Android blocks one started from the background without a word,
// so it counts only where it may start -- and only once it says it is up.
val started = runCatching { startActivity() }.isSuccess
if (started && (seen.connected || seen.visible)) {
sheetCame(SHEET_WAIT_MS)?.let { took -> return attempt.copy(fallback = WakeWay.Activity.id, sheetMs = took) }
}
return notified(attempt)
}
private fun notified(attempt: WakeAttempt): WakeAttempt {
val told = attempt.copy(fallback = WakeWay.Notification.id)
notify(told)
return told
}
private fun describe(e: Throwable): String = listOfNotNull(e.javaClass.simpleName, e.message?.takeIf { it.isNotBlank() }).joinToString(": ").take(200)
companion object {
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
const val SHEET_WAIT_MS = 2_500L
/** How long Android is given to connect a service it says is active. */
const val CONNECT_WAIT_MS = 1_000L
/** The longest an attempt can take: the connection, three waits for a sheet, and a margin. The microphone is held that long. */
const val ATTEMPT_MAX_MS = CONNECT_WAIT_MS + 3 * SHEET_WAIT_MS + 1_500L
}
}
@@ -1,6 +1,7 @@
package eu.llembas.android.wake
import android.Manifest
import android.app.KeyguardManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
@@ -31,6 +32,8 @@ import eu.llembas.android.lembas
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.drop
@@ -38,6 +41,8 @@ import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/**
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
@@ -169,7 +174,14 @@ class WakeWordService : LifecycleService() {
engine = { keywords -> WakeEngine.create(this, keywords) },
microphone = { PhoneMicrophone() },
// A test in Settings takes the word; otherwise the assistant opens.
heard = { if (!WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) wake() },
heard = { phrase ->
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
val tested = WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED)
wakeScope.launch { record(this@WakeWordService, tested) }
} else {
wake(phrase)
}
},
log = { message, cause -> Log.w(TAG, message, cause) },
)
}
@@ -197,27 +209,57 @@ class WakeWordService : LifecycleService() {
}
/**
* The word was heard: the assistant opens listening. Through the voice-interaction service
* when LLeMbas is the phone's assistant (Android lets it open the sheet from the background);
* as an activity while the app is on screen; and otherwise with a notification to tap,
* because Android blocks an activity started from the background and says nothing when it
* does ([wakeOpening]). The activity is still tried then -- where a phone allows it, it
* opens and takes the notification away.
* The word was heard: the assistant opens listening ([WakeOpener] decides how and checks that
* it did), and what was tried and how it went is written down ([WakeAttempt], kept in the
* settings and shown in Settings › Wake word), because a silent "no" here looks to the
* person like a wake word that does not work.
*
* It runs on the app's own scope, never inside the listening loop: the hold below pauses
* the listener, which cancels the loop that heard the word -- and a wake that ran in that
* loop was cancelled by its own first step. One at a time: a word heard while the last one
* is still being answered is let go.
*/
private fun wake() {
// The microphone is the sheet's from here: for a moment by this hold, then for as long as a sheet says it is up.
AssistPresence.holdFor(SHEET_GRACE_MS)
val session = LembasAssistService.current
val shownBySystem = session != null &&
runCatching { session.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0) }.isSuccess
val opening = wakeOpening(shownBySystem, AppVisibility.visible)
if (opening == WakeOpening.Session) return
val started = runCatching { startActivity(AssistActivity.listening(this).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }.isSuccess
if (opening == WakeOpening.Notification || !started) {
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this))
private fun wake(phrase: WakePhrase) {
if (waking?.isActive == true) return
// The microphone is the sheet's from here, for as long as the attempt can take; once it
// is over, for a moment more, and then for as long as a sheet says it is up.
AssistPresence.holdFor(WakeOpener.ATTEMPT_MAX_MS)
waking = wakeScope.launch {
try {
val asked = SystemClock.elapsedRealtime()
val opener = WakeOpener(
facts = { wakeFacts(this@WakeWordService) },
awaitConnected = { ms -> withTimeoutOrNull(ms) { AssistLink.connected.first { it } } != null },
showSession = {
val assistant = LembasAssistService.current ?: error("the assistant service is not connected")
assistant.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0)
},
// Through the assistant service where it is connected (the same permission either way: Android lets
// the whole app start activities while it holds the service bound).
startActivity = { (LembasAssistService.current ?: this@WakeWordService).startActivity(AssistActivity.woken(this@WakeWordService)) },
sheetCame = { ms ->
withTimeoutOrNull(ms) { AssistLink.shown.first { it >= asked } }?.let { (it - asked).coerceAtLeast(0) }
},
notify = { attempt ->
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this@WakeWordService, attempt.assistant))
},
showSignals = { (AssistLink.preparedAt >= asked) to (AssistLink.showFailedAt >= asked) },
)
val link = WakeAttempt(
createdAt = AssistLink.createdAt,
destroyedAt = AssistLink.destroyedAt,
readyAt = AssistLink.readyAt,
shutdownAt = AssistLink.shutdownAt,
)
record(this@WakeWordService, opener.open(phrase.words, link))
} finally {
AssistPresence.holdFor(SHEET_GRACE_MS)
}
}
}
private var waking: Job? = null
private fun power() = getSystemService(PowerManager::class.java)
override fun onDestroy() {
@@ -234,6 +276,33 @@ class WakeWordService : LifecycleService() {
private const val NOTIFICATION_ID = 7001
const val HEARD_ID = 7002
private const val SHEET_GRACE_MS = 3_000L
/** `PackageManager.FEATURE_VOICE_RECOGNIZERS`, which the SDK does not name for apps: without it Android runs no voice-interaction service. */
private const val FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers"
/** The app's own scope: a wake and its record outlive the listening loop, and the service too. */
private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
/** What is true at this moment, for the opener and the record. */
fun wakeFacts(context: Context): WakeFacts = WakeFacts(
connected = LembasAssistService.current != null,
active = LembasAssistService.isActive(context),
role = LembasAssistService.holdsRole(context),
recognizers = context.packageManager.hasSystemFeature(FEATURE_VOICE_RECOGNIZERS),
screenOn = context.getSystemService(PowerManager::class.java).isInteractive,
locked = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked,
visible = AppVisibility.visible,
)
/**
* Write [attempt] down: in the log under a fixed tag, and first among the last few in the
* settings. Not cancellable: what happened is kept whatever ends meanwhile.
*/
suspend fun record(context: Context, attempt: WakeAttempt) = withContext(NonCancellable) {
Log.i(TAG, "wake word heard: $attempt")
runCatching { context.lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
Unit
}
private const val TAG = "LLeMbasWake"
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
@@ -280,12 +349,14 @@ class WakeWordService : LifecycleService() {
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
*/
fun wakeHeardNotification(context: Context): Notification {
fun wakeHeardNotification(context: Context, assistant: Boolean = false): Notification {
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.wake_heard))
.setContentText(context.getString(R.string.wake_heard_line))
// Why it is a notification and not the sheet, in fixed words: LLeMbas is not the phone's
// assistant -- or it is, and could not open by itself this time (Settings says which step said no).
.setContentText(context.getString(if (assistant) R.string.wake_heard_could_not else R.string.wake_heard_line))
.setContentIntent(ask)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
@@ -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)
}
}
}
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Selhání naplánovaných úloh</string>
<string name="scheduled_result_public">Naplánovaná úloha má výsledek.</string>
<string name="scheduled_failed_public">Naplánovaná úloha selhala.</string>
<string name="page_note">Tato odpověď obsahuje stránku: %1$s</string>
<string name="page_where">Zobrazíte ji na webu nebo v aplikaci LLeMbas Desktop.</string>
<string name="page_untitled">Stránka</string>
<string name="reports">Zprávy</string>
<string name="report">Zpráva</string>
<string name="reports_none">Zatím žádné zprávy. Naplánovaná úloha ji napíše, když vám má co říct.</string>
<string name="reports_unsupported">Na této instanci běží LLeMbas, který Zprávy ještě nemá.</string>
<string name="report_untitled">Zpráva bez názvu</string>
<string name="report_delete_title">Smazat tuto zprávu?</string>
<string name="report_delete_line">Zpráva „%1$s“ se smaže natrvalo, i s rozhovorem o ní.</string>
<string name="report_mark_read">Označit jako přečtené</string>
<string name="report_important">Důležité</string>
<string name="report_share">Sdílet</string>
<string name="report_reply">Odpovědět</string>
<string name="report_chat_title">Zpráva: %1$s</string>
<string name="notify_when">Kdy dát vědět</string>
<string name="notify_every_run">Při každém běhu</string>
<string name="notify_every_run_line">Model napíše zprávu pokaždé, i když nic nenašel.</string>
<string name="notify_when_option">Když…</string>
<string name="notify_when_line">Model napíše zprávu jen tehdy, když platí tohle.</string>
<string name="notify_when_label">Když co?</string>
<string name="notify_when_default">něco vyžaduje moji pozornost</string>
<string name="notify_never_option">Nikdy</string>
<string name="notify_never_line">Žádné zprávy: běhy zůstanou jen v historii úlohy.</string>
<string name="notify_when_words">Dá vědět, když: %1$s</string>
<string name="run_open_report">Otevřít její zprávu</string>
<string name="channel_reports">Zprávy</string>
<string name="channel_reports_high">Důležité zprávy</string>
<string name="report_new_public">Nová zpráva</string>
<string name="schedule_run_again">Spustit znovu</string>
<string name="card_approval">Povolit to?</string>
<string name="card_allow_once">Povolit jednou</string>
@@ -343,6 +372,9 @@
<string name="settings_assistant">Asistent</string>
<string name="assistant_explained">Nastavte LLeMbas jako digitálního asistenta telefonu: zvolte ho v Výchozí aplikace › Digitální asistent. Podržení tlačítka napájení, gesto asistenta nebo zkratka na zamykací obrazovce ho pak otevře přes to, co je právě na obrazovce.</string>
<string name="assistant_open_settings">Otevřít nastavení asistenta</string>
<string name="assistant_model">Model asistenta</string>
<string name="assistant_model_default">Výchozí model instance</string>
<string name="assistant_model_default_line">Model, se kterým začínají vaše nové konverzace. Je-li na mluvenou otázku příliš pomalý, vyberte níže rychlejší.</string>
<string name="assistant_samsung">Na telefonech Samsung: Nastavení › Pokročilé funkce › Boční tlačítko › Stisknutí a podržení › Digitální asistent.</string>
<string name="assistant_temporary">Konverzace s asistentem jsou dočasné</string>
<string name="assistant_read_aloud">Přečíst odpověď nahlas, když se zeptáte hlasem</string>
@@ -392,12 +424,19 @@
<string name="assist_say_it">Řekněte to a odmlčte se</string>
<string name="assist_type">Raději psát</string>
<string name="assist_writing_down">Zapisuji, co jste řekli…</string>
<string name="assist_unlock_to_send">Odemknout a odeslat</string>
<string name="assist_question_heard">Otázka zaznamenána</string>
<string name="assist_recording_waits_line">Telefon je zamčený. Vaše otázka čeká v tomto telefonu jako nahrávka; nic se neodeslalo. Po odemknutí se odešle vaší instanci, která ji přepíše a odpoví.</string>
<string name="assist_locked_line">Telefon je zamčený. Dokud ho neodemknete, nic se neodešle a žádná odpověď se nezobrazí.</string>
<string name="assist_conversation">Rozhovor</string>
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
<string name="assist_conversation_end">Ukončit</string>
<string name="assist_stop_words">stop|dost|to je vše|to je všechno|konec|nashledanou|díky to je vše|zrušit|stop stop</string>
<string name="assistant_conversation">Pokračovat v mluveném rozhovoru</string>
<string name="assistant_conversation_line">Po přečtení mluvené odpovědi asistent znovu poslouchá — dokud neřeknete „stop“, neklepnete na Ukončit nebo pár sekund nic neřeknete. Funguje i se sluchátky.</string>
<string name="experimental">Experimentální</string>
<string name="wake_experimental_line">Novinka, zatím vyzkoušená jen na několika telefonech. Může frázi přeslechnout, spustit se omylem, nebo vás uslyšet a asistenta přesto neotevřít.</string>
<string name="assistant_voice_experimental_line">Experimentální: samočinné poslouchání po otevření asistenta, rozpoznání, že jste domluvili, a mluvený rozhovor jsou nové a zatím nefungují dobře na každém telefonu. Napsat otázku a tlačítko mikrofonu fungují vždy.</string>
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Asistent › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
<string name="channel_wake">Budicí slovo</string>
<string name="wake_word">Budicí slovo</string>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas se umí sám otevřít nad jinými aplikacemi jen jako aplikace digitálního asistenta v telefonu.</string>
<string name="wake_not_assistant">LLeMbas není aplikací digitálního asistenta</string>
<string name="wake_not_assistant_line">Budicí slovo proto nemůže otevřít asistenta nad jinými aplikacemi: dostanete oznámení, na které klepnete. Chcete-li otevírat hlasem kdekoli, klepněte sem a vyberte LLeMbas jako aplikaci digitálního asistenta.</string>
<string name="wake_last">Poslední probuzení</string>
<string name="wake_last_none">Frázi zatím neslyšel.</string>
<string name="wake_out_opened">Otevřel asistenta.</string>
<string name="wake_out_no_sheet">Požádal Android o otevření asistenta; neodmítl, ale panel se neobjevil.</string>
<string name="wake_out_not_connected">Android neměl LLeMbas připojený jako asistenta, proto panel nemohl otevřít.</string>
<string name="wake_out_refused">Android odmítl otevřít asistenta: %1$s</string>
<string name="wake_out_activity">Místo toho ho otevřel jako obrazovku aplikace.</string>
<string name="wake_out_notification">Místo toho poslal oznámení, na které je třeba klepnout.</string>
<string name="wake_out_tested">Slyšeno při zkoušce: nebylo co otevírat.</string>
<string name="wake_role_held">LLeMbas byl aplikací digitálního asistenta.</string>
<string name="wake_role_not_held">LLeMbas nebyl aplikací digitálního asistenta.</string>
<string name="wake_link_never">Android od spuštění aplikace asistenta nepřipojil.</string>
<string name="wake_link_ready">Android připojil asistenta v %1$s.</string>
<string name="wake_link_shutdown">Android ho odpojil v %1$s.</string>
<string name="wake_link_later">Android ho znovu připojil v %1$s.</string>
<string name="wake_sheet_ms">Panel se zobrazil po %1$s ms.</string>
<string name="wake_no_recognizers">Tento telefon nemá rozpoznávače hlasu, proto na něm Android nespouští službu hlasového asistenta.</string>
<string name="wake_not_active">LLeMbas byl vybrán jako aplikace digitálního asistenta, ale Android ho nepoužíval jako hlasového asistenta.</string>
<string name="wake_waited">Chvíli čekal, až ho Android připojí.</string>
<string name="wake_show_failed">Android oznámil, že panel asistenta nedokázal zobrazit.</string>
<string name="wake_assistant_inactive">Android právě nepoužívá LLeMbas jako hlasového asistenta</string>
<string name="wake_assistant_inactive_line">Vyberte LLeMbas jako aplikaci digitálního asistenta znovu: klepněte sem, zvolte jinou aplikaci a potom LLeMbas. Do té doby ho dlouhé stisknutí otevírá jako běžnou obrazovku a budicí slovo může poslat jen oznámení.</string>
<string name="wake_assistant_unbound">LLeMbas je asistent, ale Android ho právě nemá připojeného</string>
<string name="wake_assistant_unbound_line">Dokud ho nepřipojí, budicí slovo nemůže panel otevřít samo. Klepnutím otevřete systémové nastavení asistenta: vyberte jinou aplikaci a potom znovu LLeMbas, tím se připojí.</string>
<string name="wake_heard_could_not">Nepodařilo se otevřít samo — klepněte a ptejte se</string>
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
<string name="wake_resume_line">Telefon se restartoval. Klepnutím znovu spustíte naslouchání.</string>
<string name="assist_notifications">Shrnout má oznámení</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Geplante Fehler</string>
<string name="scheduled_result_public">Eine geplante Aufgabe hat ein Ergebnis.</string>
<string name="scheduled_failed_public">Eine geplante Aufgabe ist fehlgeschlagen.</string>
<string name="page_note">Diese Antwort hat eine Seite: %1$s</string>
<string name="page_where">Öffne sie im Web oder in LLeMbas Desktop, um sie zu sehen.</string>
<string name="page_untitled">Seite</string>
<string name="reports">Berichte</string>
<string name="report">Bericht</string>
<string name="reports_none">Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie dir etwas zu sagen hat.</string>
<string name="reports_unsupported">Auf dieser Instanz läuft ein LLeMbas, das noch keine Berichte hat.</string>
<string name="report_untitled">Bericht ohne Titel</string>
<string name="report_delete_title">Diesen Bericht löschen?</string>
<string name="report_delete_line">„%1$s“ wird endgültig gelöscht, samt der Unterhaltung darüber.</string>
<string name="report_mark_read">Als gelesen markieren</string>
<string name="report_important">Wichtig</string>
<string name="report_share">Teilen</string>
<string name="report_reply">Antworten</string>
<string name="report_chat_title">Bericht: %1$s</string>
<string name="notify_when">Benachrichtigen, wenn</string>
<string name="notify_every_run">Bei jedem Lauf</string>
<string name="notify_every_run_line">Das Modell schreibt jedes Mal einen Bericht, auch wenn nichts gefunden wurde.</string>
<string name="notify_when_option">Wenn…</string>
<string name="notify_when_line">Das Modell schreibt nur dann einen Bericht, wenn das zutrifft.</string>
<string name="notify_when_label">Wenn was?</string>
<string name="notify_when_default">etwas braucht meine Aufmerksamkeit</string>
<string name="notify_never_option">Nie</string>
<string name="notify_never_line">Keine Berichte: Läufe bleiben nur im Verlauf der Aufgabe.</string>
<string name="notify_when_words">Meldet sich, wenn: %1$s</string>
<string name="run_open_report">Zugehörigen Bericht öffnen</string>
<string name="channel_reports">Berichte</string>
<string name="channel_reports_high">Wichtige Berichte</string>
<string name="report_new_public">Neuer Bericht</string>
<string name="schedule_run_again">Erneut ausführen</string>
<string name="card_approval">Das erlauben?</string>
<string name="card_allow_once">Einmal erlauben</string>
@@ -343,6 +372,9 @@
<string name="settings_assistant">Assistent</string>
<string name="assistant_explained">Machen Sie LLeMbas zum digitalen Assistenten des Telefons: Wählen Sie ihn unter Standard-Apps › Digitaler Assistent. Das Halten der Einschalttaste, die Assistenzgeste oder die Verknüpfung auf dem Sperrbildschirm öffnet ihn dann über allem, was gerade angezeigt wird.</string>
<string name="assistant_open_settings">Assistenten-Einstellungen öffnen</string>
<string name="assistant_model">Modell des Assistenten</string>
<string name="assistant_model_default">Standard der Instanz</string>
<string name="assistant_model_default_line">Das Modell, mit dem deine neuen Chats beginnen. Ist es für eine gesprochene Frage zu langsam, wähle unten ein schnelleres.</string>
<string name="assistant_samsung">Auf Samsung-Telefonen: Einstellungen › Erweiterte Funktionen › Seitentaste › Gedrückt halten › Digitaler Assistent.</string>
<string name="assistant_temporary">Assistenten-Chats sind temporär</string>
<string name="assistant_read_aloud">Antwort vorlesen, wenn per Sprache gefragt wurde</string>
@@ -392,12 +424,19 @@
<string name="assist_say_it">Sprechen Sie, dann kurz Pause</string>
<string name="assist_type">Lieber tippen</string>
<string name="assist_writing_down">Ihr Gesagtes wird aufgeschrieben…</string>
<string name="assist_unlock_to_send">Entsperren und senden</string>
<string name="assist_question_heard">Frage aufgenommen</string>
<string name="assist_recording_waits_line">Das Telefon ist gesperrt. Deine Frage wartet als Aufnahme auf diesem Telefon; es wurde nichts gesendet. Nach dem Entsperren geht sie an deine Instanz, die sie aufschreibt und beantwortet.</string>
<string name="assist_locked_line">Das Telefon ist gesperrt. Bis du es entsperrst, wird nichts gesendet und keine Antwort angezeigt.</string>
<string name="assist_conversation">Im Gespräch</string>
<string name="assist_conversation_line">Nach jeder Antwort höre ich wieder zu. Sag „Stopp“, um zu beenden.</string>
<string name="assist_conversation_end">Beenden</string>
<string name="assist_stop_words">stopp|stop|das wars|das war\'s|das ist alles|genug|ende|tschüss|auf wiedersehen|danke das wars|abbrechen</string>
<string name="assistant_conversation">Ein gesprochenes Gespräch fortführen</string>
<string name="assistant_conversation_line">Nachdem eine gesprochene Antwort vorgelesen wurde, hört der Assistent wieder zu — bis du „Stopp“ sagst, auf Beenden tippst oder ein paar Sekunden nichts sagst. Funktioniert mit einem Headset.</string>
<string name="experimental">Experimentell</string>
<string name="wake_experimental_line">Neu und bisher nur auf wenigen Telefonen erprobt. Es kann den Satz überhören, versehentlich starten oder dich hören und den Assistenten trotzdem nicht öffnen.</string>
<string name="assistant_voice_experimental_line">Experimentell: Das selbstständige Zuhören beim Öffnen des Assistenten, das Erkennen, wann du fertig gesprochen hast, und das gesprochene Gespräch sind neu und funktionieren noch nicht auf jedem Telefon gut. Eine Frage tippen und die Mikrofontaste funktionieren immer.</string>
<string name="assist_wake_word_hint">Kein Aktivierungswort, außer du willst eines: Einstellungen › Assistent › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
<string name="channel_wake">Aktivierungswort</string>
<string name="wake_word">Aktivierungswort</string>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas kann sich nur als App für den digitalen Assistenten des Telefons selbst über anderen Apps öffnen.</string>
<string name="wake_not_assistant">LLeMbas ist nicht die App für den digitalen Assistenten</string>
<string name="wake_not_assistant_line">Deshalb kann das Aktivierungswort den Assistenten nicht über anderen Apps öffnen: Du bekommst eine Benachrichtigung zum Antippen. Um überall per Stimme zu öffnen, tippe hier und wähle LLeMbas als App für den digitalen Assistenten.</string>
<string name="wake_last">Letztes Aufwecken</string>
<string name="wake_last_none">Der Satz wurde noch nicht gehört.</string>
<string name="wake_out_opened">Assistent geöffnet.</string>
<string name="wake_out_no_sheet">Android wurde gebeten, den Assistenten zu öffnen; es hat nicht abgelehnt, aber es kam kein Blatt.</string>
<string name="wake_out_not_connected">Android hatte LLeMbas nicht als Assistenten verbunden, daher ließ sich das Blatt nicht öffnen.</string>
<string name="wake_out_refused">Android hat das Öffnen des Assistenten abgelehnt: %1$s</string>
<string name="wake_out_activity">Stattdessen als Bildschirm der App geöffnet.</string>
<string name="wake_out_notification">Stattdessen eine Benachrichtigung zum Antippen gesendet.</string>
<string name="wake_out_tested">In einem Test gehört: Es war nichts zu öffnen.</string>
<string name="wake_role_held">LLeMbas war die App für den digitalen Assistenten.</string>
<string name="wake_role_not_held">LLeMbas war nicht die App für den digitalen Assistenten.</string>
<string name="wake_link_never">Android hatte den Assistenten seit dem Start der App nicht verbunden.</string>
<string name="wake_link_ready">Android hatte den Assistenten um %1$s verbunden.</string>
<string name="wake_link_shutdown">Android hatte ihn um %1$s getrennt.</string>
<string name="wake_link_later">Android hat ihn um %1$s wieder verbunden.</string>
<string name="wake_sheet_ms">Das Blatt war nach %1$s ms da.</string>
<string name="wake_no_recognizers">Dieses Telefon hat keine Spracherkenner, daher führt Android darauf keinen Sprachassistenten-Dienst aus.</string>
<string name="wake_not_active">LLeMbas war als App für den digitalen Assistenten gewählt, aber Android nutzte es nicht als Sprachassistenten.</string>
<string name="wake_waited">Kurz gewartet, bis Android ihn verbindet.</string>
<string name="wake_show_failed">Android meldete, dass es das Blatt des Assistenten nicht anzeigen konnte.</string>
<string name="wake_assistant_inactive">Android nutzt LLeMbas gerade nicht als Sprachassistenten</string>
<string name="wake_assistant_inactive_line">Wähle LLeMbas erneut als App für den digitalen Assistenten: Tippe hier, wähle eine andere App und dann LLeMbas. Bis dahin öffnet langes Drücken es als gewöhnlichen Bildschirm, und das Aktivierungswort kann nur eine Benachrichtigung senden.</string>
<string name="wake_assistant_unbound">LLeMbas ist der Assistent, aber Android hat ihn gerade nicht verbunden</string>
<string name="wake_assistant_unbound_line">Solange das so ist, kann das Aktivierungswort das Blatt nicht selbst öffnen. Tippe für die Assistenten-Einstellung des Systems: Eine andere App und dann wieder LLeMbas zu wählen verbindet ihn.</string>
<string name="wake_heard_could_not">Ließ sich nicht selbst öffnen — tippe, um zu fragen</string>
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.</string>
<string name="assist_notifications">Meine Benachrichtigungen zusammenfassen</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Fallos programados</string>
<string name="scheduled_result_public">Una tarea programada tiene un resultado.</string>
<string name="scheduled_failed_public">Una tarea programada falló.</string>
<string name="page_note">Esta respuesta tiene una página: %1$s</string>
<string name="page_where">Ábrela en la web o en LLeMbas Desktop para verla.</string>
<string name="page_untitled">Página</string>
<string name="reports">Informes</string>
<string name="report">Informe</string>
<string name="reports_none">Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirte.</string>
<string name="reports_unsupported">Esta instancia ejecuta un LLeMbas que todavía no tiene Informes.</string>
<string name="report_untitled">Informe sin título</string>
<string name="report_delete_title">¿Eliminar este informe?</string>
<string name="report_delete_line">«%1$s» se elimina para siempre, junto con la conversación sobre él.</string>
<string name="report_mark_read">Marcar como leído</string>
<string name="report_important">Importante</string>
<string name="report_share">Compartir</string>
<string name="report_reply">Responder</string>
<string name="report_chat_title">Informe: %1$s</string>
<string name="notify_when">Avisar cuando</string>
<string name="notify_every_run">En cada ejecución</string>
<string name="notify_every_run_line">El modelo escribe un informe cada vez, también cuando no ha encontrado nada.</string>
<string name="notify_when_option">Cuando…</string>
<string name="notify_when_line">El modelo escribe un informe solo cuando esto se cumple.</string>
<string name="notify_when_label">¿Cuando qué?</string>
<string name="notify_when_default">algo necesita mi atención</string>
<string name="notify_never_option">Nunca</string>
<string name="notify_never_line">Sin informes: las ejecuciones quedan solo en el historial de la tarea.</string>
<string name="notify_when_words">Avisa cuando: %1$s</string>
<string name="run_open_report">Abrir su informe</string>
<string name="channel_reports">Informes</string>
<string name="channel_reports_high">Informes importantes</string>
<string name="report_new_public">Informe nuevo</string>
<string name="schedule_run_again">Ejecutar de nuevo</string>
<string name="card_approval">¿Permitir esto?</string>
<string name="card_allow_once">Permitir una vez</string>
@@ -343,6 +372,9 @@
<string name="settings_assistant">Asistente</string>
<string name="assistant_explained">Convierta LLeMbas en el asistente digital del teléfono: elíjalo en Aplicaciones predeterminadas › App de asistencia digital. Mantener pulsado el botón de encendido, el gesto de asistencia o el acceso directo de la pantalla de bloqueo lo abrirá entonces sobre lo que haya en pantalla.</string>
<string name="assistant_open_settings">Abrir los ajustes del asistente</string>
<string name="assistant_model">Modelo del asistente</string>
<string name="assistant_model_default">Predeterminado de la instancia</string>
<string name="assistant_model_default_line">El modelo con el que empiezan tus chats nuevos. Si es demasiado lento para una pregunta hablada, elige abajo uno más rápido.</string>
<string name="assistant_samsung">En los teléfonos Samsung: Ajustes › Funciones avanzadas › Botón lateral › Mantener pulsado › Asistente digital.</string>
<string name="assistant_temporary">Los chats del asistente son temporales</string>
<string name="assistant_read_aloud">Leer la respuesta en voz alta cuando se pregunte por voz</string>
@@ -392,12 +424,19 @@
<string name="assist_say_it">Dígalo y haga una pausa</string>
<string name="assist_type">Escribir en su lugar</string>
<string name="assist_writing_down">Escribiendo lo que ha dicho…</string>
<string name="assist_unlock_to_send">Desbloquear para enviar</string>
<string name="assist_question_heard">Pregunta oída</string>
<string name="assist_recording_waits_line">El teléfono está bloqueado. Tu pregunta espera en este teléfono como grabación; no se ha enviado nada. Al desbloquear se envía a tu instancia para transcribirla y responderla.</string>
<string name="assist_locked_line">El teléfono está bloqueado. Hasta que lo desbloquees no se envía nada ni se muestra ninguna respuesta.</string>
<string name="assist_conversation">En conversación</string>
<string name="assist_conversation_line">Vuelvo a escuchar después de cada respuesta. Di «para» para terminar.</string>
<string name="assist_conversation_end">Terminar</string>
<string name="assist_stop_words">para|stop|basta|eso es todo|ya está|adiós|terminar|fin|gracias eso es todo|cancelar</string>
<string name="assistant_conversation">Mantener una conversación hablada</string>
<string name="assistant_conversation_line">Después de leer en voz alta una respuesta hablada, el asistente vuelve a escuchar, hasta que digas «para», toques Terminar o no digas nada durante unos segundos. Funciona con auriculares.</string>
<string name="experimental">Experimental</string>
<string name="wake_experimental_line">Nuevo y probado por ahora en pocos teléfonos. Puede no oír la frase, activarse por error u oírte y aun así no abrir el asistente.</string>
<string name="assistant_voice_experimental_line">Experimental: escuchar por sí solo al abrir el asistente, notar cuándo has terminado de hablar y la conversación hablada son nuevos y todavía no funcionan bien en todos los teléfonos. Escribir una pregunta y el botón del micrófono funcionan siempre.</string>
<string name="assist_wake_word_hint">Sin palabra de activación salvo que quieras una: Ajustes › Asistente › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
<string name="channel_wake">Palabra de activación</string>
<string name="wake_word">Palabra de activación</string>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas solo puede abrirse por sí mismo sobre otras apps si es la app de asistente digital del teléfono.</string>
<string name="wake_not_assistant">LLeMbas no es la app de asistente digital</string>
<string name="wake_not_assistant_line">Por eso la palabra de activación no puede abrir el asistente sobre otras apps: recibes una notificación que tocar. Para abrir con la voz en cualquier parte, toca aquí y elige LLeMbas como app de asistente digital.</string>
<string name="wake_last">Última activación</string>
<string name="wake_last_none">Todavía no ha oído la frase.</string>
<string name="wake_out_opened">Abrió el asistente.</string>
<string name="wake_out_no_sheet">Pidió a Android que abriera el asistente; no se negó, pero no apareció el panel.</string>
<string name="wake_out_not_connected">Android no tenía LLeMbas conectado como asistente, así que no pudo abrir el panel.</string>
<string name="wake_out_refused">Android se negó a abrir el asistente: %1$s</string>
<string name="wake_out_activity">En su lugar lo abrió como una pantalla de la app.</string>
<string name="wake_out_notification">En su lugar envió una notificación para tocar.</string>
<string name="wake_out_tested">Oída en una prueba: no había nada que abrir.</string>
<string name="wake_role_held">LLeMbas era la app de asistente digital.</string>
<string name="wake_role_not_held">LLeMbas no era la app de asistente digital.</string>
<string name="wake_link_never">Android no había conectado el asistente desde que se inició la app.</string>
<string name="wake_link_ready">Android había conectado el asistente a las %1$s.</string>
<string name="wake_link_shutdown">Android lo había desconectado a las %1$s.</string>
<string name="wake_link_later">Android volvió a conectarlo a las %1$s.</string>
<string name="wake_sheet_ms">El panel apareció tras %1$s ms.</string>
<string name="wake_no_recognizers">Este teléfono no tiene reconocedores de voz, así que Android no ejecuta en él ningún servicio de asistente de voz.</string>
<string name="wake_not_active">LLeMbas estaba elegido como app de asistente digital, pero Android no lo usaba como asistente de voz.</string>
<string name="wake_waited">Esperó un momento a que Android lo conectara.</string>
<string name="wake_show_failed">Android dijo que no pudo mostrar el panel del asistente.</string>
<string name="wake_assistant_inactive">Android no está usando LLeMbas como asistente de voz ahora mismo</string>
<string name="wake_assistant_inactive_line">Elige de nuevo LLeMbas como app de asistente digital: toca aquí, elige otra app y luego LLeMbas. Hasta entonces la pulsación larga lo abre como una pantalla normal y la palabra de activación solo puede enviar una notificación.</string>
<string name="wake_assistant_unbound">LLeMbas es el asistente, pero Android no lo tiene conectado ahora mismo</string>
<string name="wake_assistant_unbound_line">Hasta que lo conecte, la palabra de activación no puede abrir el panel por sí sola. Toca para ir al ajuste del asistente del sistema: elegir otra app y luego LLeMbas de nuevo lo conecta.</string>
<string name="wake_heard_could_not">No pudo abrirse por sí solo: toca para preguntar</string>
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
<string name="wake_resume_line">El teléfono se reinició. Toca para volver a escuchar.</string>
<string name="assist_notifications">Resumir mis notificaciones</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Échecs planifiés</string>
<string name="scheduled_result_public">Une tâche planifiée a un résultat.</string>
<string name="scheduled_failed_public">Une tâche planifiée a échoué.</string>
<string name="page_note">Cette réponse contient une page : %1$s</string>
<string name="page_where">Ouvrez-la sur le web ou dans LLeMbas Desktop pour la voir.</string>
<string name="page_untitled">Page</string>
<string name="reports">Rapports</string>
<string name="report">Rapport</string>
<string name="reports_none">Pas encore de rapport. Une tâche planifiée en rédige un quand elle a quelque chose à vous dire.</string>
<string name="reports_unsupported">Cette instance utilise un LLeMbas qui n’a pas encore les Rapports.</string>
<string name="report_untitled">Rapport sans titre</string>
<string name="report_delete_title">Supprimer ce rapport ?</string>
<string name="report_delete_line">« %1$s » est supprimé définitivement, avec la conversation à son sujet.</string>
<string name="report_mark_read">Marquer comme lu</string>
<string name="report_important">Important</string>
<string name="report_share">Partager</string>
<string name="report_reply">Répondre</string>
<string name="report_chat_title">Rapport : %1$s</string>
<string name="notify_when">Prévenir quand</string>
<string name="notify_every_run">À chaque exécution</string>
<string name="notify_every_run_line">Le modèle rédige un rapport à chaque fois, même quand rien n’a été trouvé.</string>
<string name="notify_when_option">Quand…</string>
<string name="notify_when_line">Le modèle ne rédige un rapport que si ceci est vrai.</string>
<string name="notify_when_label">Quand quoi ?</string>
<string name="notify_when_default">quelque chose demande mon attention</string>
<string name="notify_never_option">Jamais</string>
<string name="notify_never_line">Aucun rapport : les exécutions restent seulement dans l’historique de la tâche.</string>
<string name="notify_when_words">Prévient quand : %1$s</string>
<string name="run_open_report">Ouvrir son rapport</string>
<string name="channel_reports">Rapports</string>
<string name="channel_reports_high">Rapports importants</string>
<string name="report_new_public">Nouveau rapport</string>
<string name="schedule_run_again">Relancer</string>
<string name="card_approval">Autoriser ceci ?</string>
<string name="card_allow_once">Autoriser une fois</string>
@@ -343,6 +372,9 @@
<string name="settings_assistant">Assistant</string>
<string name="assistant_explained">Faites de LLeMbas l\'assistant numérique du téléphone : choisissez-le dans Applications par défaut › Application d\'assistance numérique. Maintenir le bouton d\'alimentation, le geste d\'assistance ou le raccourci de l\'écran de verrouillage l\'ouvrira alors par-dessus ce qui est affiché.</string>
<string name="assistant_open_settings">Ouvrir les paramètres de l\'assistant</string>
<string name="assistant_model">Modèle de l’assistant</string>
<string name="assistant_model_default">Modèle par défaut de l’instance</string>
<string name="assistant_model_default_line">Le modèle avec lequel commencent vos nouvelles discussions. S’il est trop lent pour une question orale, choisissez-en un plus rapide ci-dessous.</string>
<string name="assistant_samsung">Sur les téléphones Samsung : Paramètres › Fonctions avancées › Bouton latéral › Maintenir enfoncé › Assistant numérique.</string>
<string name="assistant_temporary">Les conversations de l\'assistant sont temporaires</string>
<string name="assistant_read_aloud">Lire la réponse à voix haute en cas de question orale</string>
@@ -392,12 +424,19 @@
<string name="assist_say_it">Dites-le, puis marquez une pause</string>
<string name="assist_type">Taper plutôt</string>
<string name="assist_writing_down">Transcription de ce que vous avez dit…</string>
<string name="assist_unlock_to_send">Déverrouiller pour envoyer</string>
<string name="assist_question_heard">Question entendue</string>
<string name="assist_recording_waits_line">Le téléphone est verrouillé. Votre question attend sur ce téléphone sous forme d’enregistrement ; rien n’a été envoyé. Au déverrouillage, elle est envoyée à votre instance pour être transcrite et recevoir une réponse.</string>
<string name="assist_locked_line">Le téléphone est verrouillé. Rien n’est envoyé et aucune réponse n’est affichée tant que vous ne l’avez pas déverrouillé.</string>
<string name="assist_conversation">En conversation</string>
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
<string name="assist_conversation_end">Terminer</string>
<string name="assist_stop_words">stop|arrête|c\'est tout|ça suffit|au revoir|fin|terminé|merci c\'est tout|annuler</string>
<string name="assistant_conversation">Poursuivre une conversation orale</string>
<string name="assistant_conversation_line">Après la lecture d’une réponse orale, l’assistant écoute à nouveau — jusqu’à ce que vous disiez « stop », touchiez Terminer ou ne disiez rien pendant quelques secondes. Fonctionne avec un casque.</string>
<string name="experimental">Expérimental</string>
<string name="wake_experimental_line">Nouveau, et essayé sur peu de téléphones pour l’instant. Il peut ne pas entendre la phrase, se déclencher par erreur, ou vous entendre sans pour autant ouvrir l’assistant.</string>
<string name="assistant_voice_experimental_line">Expérimental : l’écoute automatique à l’ouverture de l’assistant, la détection de la fin de votre phrase et la conversation orale sont nouvelles et ne fonctionnent pas encore bien sur tous les téléphones. Écrire une question et le bouton du micro fonctionnent toujours.</string>
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Assistant › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
<string name="channel_wake">Mot d’activation</string>
<string name="wake_word">Mot d’activation</string>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas ne peut s’ouvrir de lui-même par-dessus d’autres apps que s’il est l’assistant numérique du téléphone.</string>
<string name="wake_not_assistant">LLeMbas n’est pas l’application d’assistant numérique</string>
<string name="wake_not_assistant_line">Le mot d’activation ne peut donc pas ouvrir l’assistant par-dessus d’autres apps : vous recevez une notification à toucher. Pour ouvrir à la voix partout, touchez ici et choisissez LLeMbas comme application d’assistant numérique.</string>
<string name="wake_last">Dernier réveil</string>
<string name="wake_last_none">Il n’a pas encore entendu la phrase.</string>
<string name="wake_out_opened">A ouvert l’assistant.</string>
<string name="wake_out_no_sheet">A demandé à Android d’ouvrir l’assistant ; il n’a pas refusé, mais aucun panneau n’est apparu.</string>
<string name="wake_out_not_connected">Android n’avait pas connecté LLeMbas comme assistant, le panneau n’a donc pas pu s’ouvrir.</string>
<string name="wake_out_refused">Android a refusé d’ouvrir l’assistant : %1$s</string>
<string name="wake_out_activity">L’a ouvert à la place comme un écran de l’app.</string>
<string name="wake_out_notification">A envoyé à la place une notification à toucher.</string>
<string name="wake_out_tested">Entendu pendant un test : il n’y avait rien à ouvrir.</string>
<string name="wake_role_held">LLeMbas était l’application d’assistant numérique.</string>
<string name="wake_role_not_held">LLeMbas n’était pas l’application d’assistant numérique.</string>
<string name="wake_link_never">Android n’avait pas connecté l’assistant depuis le démarrage de l’app.</string>
<string name="wake_link_ready">Android avait connecté l’assistant à %1$s.</string>
<string name="wake_link_shutdown">Android l’avait déconnecté à %1$s.</string>
<string name="wake_link_later">Android l’a reconnecté à %1$s.</string>
<string name="wake_sheet_ms">Le panneau était affiché après %1$s ms.</string>
<string name="wake_no_recognizers">Ce téléphone n’a pas de reconnaissance vocale, Android n’y exécute donc aucun service d’assistant vocal.</string>
<string name="wake_not_active">LLeMbas était choisi comme application d’assistant numérique, mais Android ne l’utilisait pas comme assistant vocal.</string>
<string name="wake_waited">A attendu un instant qu’Android le connecte.</string>
<string name="wake_show_failed">Android a indiqué qu’il n’avait pas pu afficher le panneau de l’assistant.</string>
<string name="wake_assistant_inactive">Android n’utilise pas LLeMbas comme assistant vocal pour l’instant</string>
<string name="wake_assistant_inactive_line">Choisissez de nouveau LLeMbas comme application d’assistant numérique : touchez ici, prenez une autre app, puis LLeMbas. D’ici là, l’appui long l’ouvre comme un écran ordinaire et le mot d’activation ne peut qu’envoyer une notification.</string>
<string name="wake_assistant_unbound">LLeMbas est l’assistant, mais Android ne l’a pas connecté pour l’instant</string>
<string name="wake_assistant_unbound_line">Tant que ce n’est pas fait, le mot d’activation ne peut pas ouvrir le panneau de lui-même. Touchez pour le réglage de l’assistant du système : choisir une autre app puis de nouveau LLeMbas le reconnecte.</string>
<string name="wake_heard_could_not">N’a pas pu s’ouvrir de lui-même — touchez pour demander</string>
<string name="wake_resume">Écouter à nouveau le mot d’activation</string>
<string name="wake_resume_line">Le téléphone a redémarré. Touchez pour reprendre l’écoute.</string>
<string name="assist_notifications">Résumer mes notifications</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Ütemezett hibák</string>
<string name="scheduled_result_public">Egy ütemezett feladatnak eredménye van.</string>
<string name="scheduled_failed_public">Egy ütemezett feladat sikertelen volt.</string>
<string name="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_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_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>
<string name="report_delete_line">A(z) „%1$s” véglegesen törlődik, a róla szóló beszélgetéssel együtt.</string>
<string name="report_mark_read">Megjelölés olvasottként</string>
<string name="report_important">Fontos</string>
<string name="report_share">Megosztás</string>
<string name="report_reply">Válasz</string>
<string name="report_chat_title">Jelentés: %1$s</string>
<string name="notify_when">Mikor értesítsen</string>
<string name="notify_every_run">Minden futáskor</string>
<string name="notify_every_run_line">A modell minden alkalommal ír jelentést, akkor is, ha semmit sem talált.</string>
<string name="notify_when_option">Amikor…</string>
<string name="notify_when_line">A modell csak akkor ír jelentést, ha ez teljesül.</string>
<string name="notify_when_label">Amikor mi?</string>
<string name="notify_when_default">valami a figyelmemet igényli</string>
<string name="notify_never_option">Soha</string>
<string name="notify_never_line">Nincs jelentés: a futások csak a feladat előzményeiben maradnak meg.</string>
<string name="notify_when_words">Értesít, amikor: %1$s</string>
<string name="run_open_report">A jelentésének megnyitása</string>
<string name="channel_reports">Jelentések</string>
<string name="channel_reports_high">Fontos jelentések</string>
<string name="report_new_public">Új jelentés</string>
<string name="schedule_run_again">Futtatás újra</string>
<string name="card_approval">Engedélyezzük ezt?</string>
<string name="card_allow_once">Engedélyezés egyszer</string>
@@ -343,6 +372,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éseid indulnak. Ha egy kimondott kérdéshez túl lassú, válassz 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>
@@ -392,12 +424,19 @@
<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ésed felvételként ezen a telefonon vár; semmi sem ment el. Feloldás után a példányodhoz kerül, amely leírja és megválaszolja.</string>
<string name="assist_locked_line">A telefon zárolva van. Amíg fel nem oldod, 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_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="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 meghall, é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 befejezted 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érsz: Beállítások › Asszisztens › É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>
@@ -448,6 +487,31 @@
<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_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>
<string name="wake_out_no_sheet">Megkérte az Androidot az asszisztens megnyitására; nem utasította el, de a panel nem jelent meg.</string>
<string name="wake_out_not_connected">Az Android nem csatlakoztatta a LLeMbast asszisztensként, ezért nem tudta megnyitni a panelt.</string>
<string name="wake_out_refused">Az Android elutasította az asszisztens megnyitását: %1$s</string>
<string name="wake_out_activity">Helyette az alkalmazás képernyőjeként nyitotta meg.</string>
<string name="wake_out_notification">Helyette értesítést küldött, amelyre koppintani lehet.</string>
<string name="wake_out_tested">Próba közben hallotta: nem volt mit megnyitni.</string>
<string name="wake_role_held">A LLeMbas volt a digitális asszisztens alkalmazás.</string>
<string name="wake_role_not_held">Nem a LLeMbas volt a digitális asszisztens alkalmazás.</string>
<string name="wake_link_never">Az Android az alkalmazás indulása óta nem csatlakoztatta az asszisztenst.</string>
<string name="wake_link_ready">Az Android ekkor csatlakoztatta az asszisztenst: %1$s.</string>
<string name="wake_link_shutdown">Az Android ekkor választotta le: %1$s.</string>
<string name="wake_link_later">Az Android ekkor csatlakoztatta újra: %1$s.</string>
<string name="wake_sheet_ms">A panel %1$s ms után jelent meg.</string>
<string name="wake_no_recognizers">Ezen a telefonon nincs hangfelismerő, ezért az Android nem futtat rajta hangasszisztens-szolgáltatást.</string>
<string name="wake_not_active">A LLeMbas volt kiválasztva digitális asszisztens alkalmazásnak, de az Android nem használta hangasszisztensként.</string>
<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_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_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="assist_notifications">Értesítéseim összefoglalása</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Errori pianificati</string>
<string name="scheduled_result_public">Un’attività pianificata ha un risultato.</string>
<string name="scheduled_failed_public">Un’attività pianificata non è riuscita.</string>
<string name="page_note">Questa risposta ha una pagina: %1$s</string>
<string name="page_where">Aprila sul web o in LLeMbas Desktop per vederla.</string>
<string name="page_untitled">Pagina</string>
<string name="reports">Rapporti</string>
<string name="report">Rapporto</string>
<string name="reports_none">Ancora nessun rapporto. Un’attività pianificata ne scrive uno quando ha qualcosa da dirti.</string>
<string name="reports_unsupported">Questa istanza usa un LLeMbas che non ha ancora i Rapporti.</string>
<string name="report_untitled">Rapporto senza titolo</string>
<string name="report_delete_title">Eliminare questo rapporto?</string>
<string name="report_delete_line">«%1$s» viene eliminato definitivamente, insieme alla conversazione che lo riguarda.</string>
<string name="report_mark_read">Segna come letto</string>
<string name="report_important">Importante</string>
<string name="report_share">Condividi</string>
<string name="report_reply">Rispondi</string>
<string name="report_chat_title">Rapporto: %1$s</string>
<string name="notify_when">Avvisa quando</string>
<string name="notify_every_run">A ogni esecuzione</string>
<string name="notify_every_run_line">Il modello scrive un rapporto ogni volta, anche quando non ha trovato nulla.</string>
<string name="notify_when_option">Quando…</string>
<string name="notify_when_line">Il modello scrive un rapporto solo quando questo è vero.</string>
<string name="notify_when_label">Quando cosa?</string>
<string name="notify_when_default">qualcosa richiede la mia attenzione</string>
<string name="notify_never_option">Mai</string>
<string name="notify_never_line">Nessun rapporto: le esecuzioni restano solo nella cronologia dell’attività.</string>
<string name="notify_when_words">Avvisa quando: %1$s</string>
<string name="run_open_report">Apri il suo rapporto</string>
<string name="channel_reports">Rapporti</string>
<string name="channel_reports_high">Rapporti importanti</string>
<string name="report_new_public">Nuovo rapporto</string>
<string name="schedule_run_again">Esegui di nuovo</string>
<string name="card_approval">Consentire questo?</string>
<string name="card_allow_once">Consenti una volta</string>
@@ -343,6 +372,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>
@@ -392,12 +424,19 @@
<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="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 › Assistente › 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>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas può aprirsi da solo sopra le altre app soltanto come app di assistente digitale del telefono.</string>
<string name="wake_not_assistant">LLeMbas non è l’app di assistente digitale</string>
<string name="wake_not_assistant_line">Per questo la parola di attivazione non può aprire l’assistente sopra le altre app: ricevi una notifica da toccare. Per aprire con la voce ovunque, tocca qui e scegli LLeMbas come app di assistente digitale.</string>
<string name="wake_last">Ultima attivazione</string>
<string name="wake_last_none">Non ha ancora sentito la frase.</string>
<string name="wake_out_opened">Ha aperto l’assistente.</string>
<string name="wake_out_no_sheet">Ha chiesto ad Android di aprire l’assistente; non ha rifiutato, ma il pannello non è comparso.</string>
<string name="wake_out_not_connected">Android non aveva collegato LLeMbas come assistente, quindi non ha potuto aprire il pannello.</string>
<string name="wake_out_refused">Android ha rifiutato di aprire l’assistente: %1$s</string>
<string name="wake_out_activity">Al suo posto l’ha aperto come schermata dell’app.</string>
<string name="wake_out_notification">Al suo posto ha inviato una notifica da toccare.</string>
<string name="wake_out_tested">Sentita durante una prova: non c’era nulla da aprire.</string>
<string name="wake_role_held">LLeMbas era l’app di assistente digitale.</string>
<string name="wake_role_not_held">LLeMbas non era l’app di assistente digitale.</string>
<string name="wake_link_never">Android non aveva collegato l’assistente dall’avvio dell’app.</string>
<string name="wake_link_ready">Android aveva collegato l’assistente alle %1$s.</string>
<string name="wake_link_shutdown">Android l’aveva scollegato alle %1$s.</string>
<string name="wake_link_later">Android l’ha ricollegato alle %1$s.</string>
<string name="wake_sheet_ms">Il pannello è comparso dopo %1$s ms.</string>
<string name="wake_no_recognizers">Questo telefono non ha riconoscitori vocali, quindi Android non vi esegue alcun servizio di assistente vocale.</string>
<string name="wake_not_active">LLeMbas era scelto come app di assistente digitale, ma Android non lo usava come assistente vocale.</string>
<string name="wake_waited">Ha atteso un momento che Android lo collegasse.</string>
<string name="wake_show_failed">Android ha detto di non essere riuscito a mostrare il pannello dell’assistente.</string>
<string name="wake_assistant_inactive">Android non sta usando LLeMbas come assistente vocale in questo momento</string>
<string name="wake_assistant_inactive_line">Scegli di nuovo LLeMbas come app di assistente digitale: tocca qui, scegli un’altra app e poi LLeMbas. Fino ad allora la pressione prolungata lo apre come una schermata normale e la parola di attivazione può solo inviare una notifica.</string>
<string name="wake_assistant_unbound">LLeMbas è l’assistente, ma Android non l’ha collegato in questo momento</string>
<string name="wake_assistant_unbound_line">Finché non lo collega, la parola di attivazione non può aprire il pannello da sola. Tocca per l’impostazione dell’assistente di sistema: scegliere un’altra app e poi di nuovo LLeMbas lo collega.</string>
<string name="wake_heard_could_not">Non è riuscito ad aprirsi da solo — tocca per chiedere</string>
<string name="wake_resume">Ascolta di nuovo la parola di attivazione</string>
<string name="wake_resume_line">Il telefono si è riavviato. Tocca per ricominciare ad ascoltare.</string>
<string name="assist_notifications">Riassumi le mie notifiche</string>
+1 -1
View File
@@ -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.11 (moria). Do not edit. -->
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.13 (moria). Do not edit. -->
<resources>
<color name="token_bg">#FF0B0D10</color>
<color name="token_surface">#FF11151A</color>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Błędy zaplanowanych zadań</string>
<string name="scheduled_result_public">Zaplanowane zadanie ma wynik.</string>
<string name="scheduled_failed_public">Zaplanowane zadanie się nie powiodło.</string>
<string name="page_note">Ta odpowiedź zawiera stronę: %1$s</string>
<string name="page_where">Otwórz ją w przeglądarce albo w LLeMbas Desktop, aby ją zobaczyć.</string>
<string name="page_untitled">Strona</string>
<string name="reports">Raporty</string>
<string name="report">Raport</string>
<string name="reports_none">Nie ma jeszcze raportów. Zaplanowane zadanie pisze raport, gdy ma Ci coś do powiedzenia.</string>
<string name="reports_unsupported">Na tej instancji działa LLeMbas, który nie ma jeszcze Raportów.</string>
<string name="report_untitled">Raport bez tytułu</string>
<string name="report_delete_title">Usunąć ten raport?</string>
<string name="report_delete_line">Raport „%1$s” zostanie usunięty na stałe, razem z rozmową o nim.</string>
<string name="report_mark_read">Oznacz jako przeczytany</string>
<string name="report_important">Ważne</string>
<string name="report_share">Udostępnij</string>
<string name="report_reply">Odpowiedz</string>
<string name="report_chat_title">Raport: %1$s</string>
<string name="notify_when">Powiadamiaj, gdy</string>
<string name="notify_every_run">Przy każdym uruchomieniu</string>
<string name="notify_every_run_line">Model pisze raport za każdym razem, także gdy niczego nie znalazł.</string>
<string name="notify_when_option">Gdy…</string>
<string name="notify_when_line">Model pisze raport tylko wtedy, gdy to jest spełnione.</string>
<string name="notify_when_label">Gdy co?</string>
<string name="notify_when_default">coś wymaga mojej uwagi</string>
<string name="notify_never_option">Nigdy</string>
<string name="notify_never_line">Bez raportów: uruchomienia zostają tylko w historii zadania.</string>
<string name="notify_when_words">Powiadamia, gdy: %1$s</string>
<string name="run_open_report">Otwórz jego raport</string>
<string name="channel_reports">Raporty</string>
<string name="channel_reports_high">Ważne raporty</string>
<string name="report_new_public">Nowy raport</string>
<string name="schedule_run_again">Uruchom ponownie</string>
<string name="card_approval">Zezwolić na to?</string>
<string name="card_allow_once">Zezwól raz</string>
@@ -343,6 +372,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>
@@ -392,12 +424,19 @@
<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="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 › Asystent › 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>
@@ -448,6 +487,31 @@
<string name="wake_heard_line">LLeMbas może sam otworzyć się nad innymi aplikacjami tylko jako aplikacja asystenta cyfrowego telefonu.</string>
<string name="wake_not_assistant">LLeMbas nie jest aplikacją asystenta cyfrowego</string>
<string name="wake_not_assistant_line">Dlatego słowo aktywujące nie może otworzyć asystenta nad innymi aplikacjami: dostajesz powiadomienie do dotknięcia. Aby otwierać głosem wszędzie, dotknij tutaj i wybierz LLeMbas jako aplikację asystenta cyfrowego.</string>
<string name="wake_last">Ostatnie wybudzenie</string>
<string name="wake_last_none">Jeszcze nie usłyszał frazy.</string>
<string name="wake_out_opened">Otworzył asystenta.</string>
<string name="wake_out_no_sheet">Poprosił Androida o otwarcie asystenta; nie odmówił, ale panel się nie pojawił.</string>
<string name="wake_out_not_connected">Android nie miał połączonego LLeMbas jako asystenta, więc nie mógł otworzyć panelu.</string>
<string name="wake_out_refused">Android odmówił otwarcia asystenta: %1$s</string>
<string name="wake_out_activity">Zamiast tego otworzył go jako ekran aplikacji.</string>
<string name="wake_out_notification">Zamiast tego wysłał powiadomienie do dotknięcia.</string>
<string name="wake_out_tested">Usłyszano podczas próby: nie było czego otwierać.</string>
<string name="wake_role_held">LLeMbas był aplikacją asystenta cyfrowego.</string>
<string name="wake_role_not_held">LLeMbas nie był aplikacją asystenta cyfrowego.</string>
<string name="wake_link_never">Android nie połączył asystenta od uruchomienia aplikacji.</string>
<string name="wake_link_ready">Android połączył asystenta o %1$s.</string>
<string name="wake_link_shutdown">Android rozłączył go o %1$s.</string>
<string name="wake_link_later">Android połączył go ponownie o %1$s.</string>
<string name="wake_sheet_ms">Panel pojawił się po %1$s ms.</string>
<string name="wake_no_recognizers">Ten telefon nie ma rozpoznawania mowy, więc Android nie uruchamia na nim usługi asystenta głosowego.</string>
<string name="wake_not_active">LLeMbas był wybrany jako aplikacja asystenta cyfrowego, ale Android nie używał go jako asystenta głosowego.</string>
<string name="wake_waited">Chwilę czekał, aż Android go połączy.</string>
<string name="wake_show_failed">Android zgłosił, że nie mógł pokazać panelu asystenta.</string>
<string name="wake_assistant_inactive">Android nie używa teraz LLeMbas jako asystenta głosowego</string>
<string name="wake_assistant_inactive_line">Wybierz ponownie LLeMbas jako aplikację asystenta cyfrowego: dotknij tutaj, wybierz inną aplikację, a potem LLeMbas. Do tego czasu długie naciśnięcie otwiera go jako zwykły ekran, a słowo aktywujące może tylko wysłać powiadomienie.</string>
<string name="wake_assistant_unbound">LLeMbas jest asystentem, ale Android nie ma go teraz połączonego</string>
<string name="wake_assistant_unbound_line">Dopóki go nie połączy, słowo aktywujące nie może samo otworzyć panelu. Dotknij, aby przejść do systemowego ustawienia asystenta: wybranie innej aplikacji, a potem znów LLeMbas, połączy go.</string>
<string name="wake_heard_could_not">Nie udało się otworzyć samo — dotknij, aby zapytać</string>
<string name="wake_resume">Znów nasłuchuj słowa aktywującego</string>
<string name="wake_resume_line">Telefon uruchomił się ponownie. Dotknij, aby znów słuchać.</string>
<string name="assist_notifications">Podsumuj moje powiadomienia</string>
+64
View File
@@ -244,6 +244,35 @@
<string name="channel_scheduled_failures">Zlyhania naplánovaných úloh</string>
<string name="scheduled_result_public">Naplánovaná úloha má výsledok.</string>
<string name="scheduled_failed_public">Naplánovaná úloha zlyhala.</string>
<string name="page_note">Táto odpoveď obsahuje stránku: %1$s</string>
<string name="page_where">Zobrazíte ju na webe alebo v aplikácii LLeMbas Desktop.</string>
<string name="page_untitled">Stránka</string>
<string name="reports">Správy</string>
<string name="report">Správa</string>
<string name="reports_none">Zatiaľ žiadne správy. Naplánovaná úloha ju napíše, keď vám má čo povedať.</string>
<string name="reports_unsupported">Na tejto inštancii beží LLeMbas, ktorý Správy ešte nemá.</string>
<string name="report_untitled">Správa bez názvu</string>
<string name="report_delete_title">Odstrániť túto správu?</string>
<string name="report_delete_line">Správa „%1$s“ sa odstráni natrvalo, aj s rozhovorom o nej.</string>
<string name="report_mark_read">Označiť ako prečítané</string>
<string name="report_important">Dôležité</string>
<string name="report_share">Zdieľať</string>
<string name="report_reply">Odpovedať</string>
<string name="report_chat_title">Správa: %1$s</string>
<string name="notify_when">Kedy dať vedieť</string>
<string name="notify_every_run">Pri každom behu</string>
<string name="notify_every_run_line">Model napíše správu zakaždým, aj keď nič nenašiel.</string>
<string name="notify_when_option">Keď…</string>
<string name="notify_when_line">Model napíše správu len vtedy, keď platí toto.</string>
<string name="notify_when_label">Keď čo?</string>
<string name="notify_when_default">niečo si vyžaduje moju pozornosť</string>
<string name="notify_never_option">Nikdy</string>
<string name="notify_never_line">Žiadne správy: behy zostanú len v histórii úlohy.</string>
<string name="notify_when_words">Dá vedieť, keď: %1$s</string>
<string name="run_open_report">Otvoriť jej správu</string>
<string name="channel_reports">Správy</string>
<string name="channel_reports_high">Dôležité správy</string>
<string name="report_new_public">Nová správa</string>
<string name="schedule_run_again">Spustiť znova</string>
<string name="card_approval">Povoliť to?</string>
<string name="card_allow_once">Povoliť raz</string>
@@ -343,6 +372,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>
@@ -392,12 +424,19 @@
<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="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 › Asistent › 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>
@@ -448,6 +487,31 @@
<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_last">Posledné zobudenie</string>
<string name="wake_last_none">Frázu zatiaľ nepočul.</string>
<string name="wake_out_opened">Otvoril asistenta.</string>
<string name="wake_out_no_sheet">Požiadal Android o otvorenie asistenta; neodmietol, no panel sa neobjavil.</string>
<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_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>
<string name="wake_link_never">Android od spustenia aplikácie asistenta nepripojil.</string>
<string name="wake_link_ready">Android pripojil asistenta o %1$s.</string>
<string name="wake_link_shutdown">Android ho odpojil o %1$s.</string>
<string name="wake_link_later">Android ho znova pripojil o %1$s.</string>
<string name="wake_sheet_ms">Panel sa zobrazil po %1$s ms.</string>
<string name="wake_no_recognizers">Tento telefón nemá rozpoznávače hlasu, preto na ňom Android nespúšťa službu hlasového asistenta.</string>
<string name="wake_not_active">LLeMbas bol vybraný ako aplikácia digitálneho asistenta, no Android ho nepoužíval ako hlasového asistenta.</string>
<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_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>
+64
View File
@@ -245,6 +245,35 @@
<string name="channel_scheduled_failures">Scheduled failures</string>
<string name="scheduled_result_public">A scheduled task has a result.</string>
<string name="scheduled_failed_public">A scheduled task failed.</string>
<string name="page_note">This answer has a page: %1$s</string>
<string name="page_where">Open it on the web or in LLeMbas Desktop to see it.</string>
<string name="page_untitled">Page</string>
<string name="reports">Reports</string>
<string name="report">Report</string>
<string name="reports_none">No reports yet. A scheduled task files one when it has something to tell you.</string>
<string name="reports_unsupported">This instance runs a LLeMbas that has no Reports yet.</string>
<string name="report_untitled">Untitled report</string>
<string name="report_delete_title">Delete this report?</string>
<string name="report_delete_line">“%1$s” is deleted for good, and the conversation about it with it.</string>
<string name="report_mark_read">Mark read</string>
<string name="report_important">Important</string>
<string name="report_share">Share</string>
<string name="report_reply">Reply</string>
<string name="report_chat_title">Report: %1$s</string>
<string name="notify_when">Notify when</string>
<string name="notify_every_run">Every run</string>
<string name="notify_every_run_line">The model writes a report every time, also when nothing was found.</string>
<string name="notify_when_option">When…</string>
<string name="notify_when_line">The model writes a report only when this holds.</string>
<string name="notify_when_label">When what?</string>
<string name="notify_when_default">something needs my attention</string>
<string name="notify_never_option">Never</string>
<string name="notify_never_line">No reports: runs are kept in the task\'s history only.</string>
<string name="notify_when_words">Tells you when: %1$s</string>
<string name="run_open_report">Open its report</string>
<string name="channel_reports">Reports</string>
<string name="channel_reports_high">Important reports</string>
<string name="report_new_public">New report</string>
<string name="schedule_run_again">Run again</string>
<string name="card_approval">Allow this?</string>
<string name="card_allow_once">Allow once</string>
@@ -345,6 +374,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>
@@ -394,12 +426,19 @@
<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="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 › Assistant › 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>
@@ -450,6 +489,31 @@
<string name="wake_heard_line">LLeMbas can open by itself over other apps only as the phone\'s digital assistant app.</string>
<string name="wake_not_assistant">LLeMbas is not the digital assistant app</string>
<string name="wake_not_assistant_line">So the wake word cannot open the assistant over other apps: you get a notification to tap. To open by voice anywhere, tap here and choose LLeMbas as the digital assistant app.</string>
<string name="wake_last">Last wake</string>
<string name="wake_last_none">It has not heard the phrase yet.</string>
<string name="wake_out_opened">Opened the assistant.</string>
<string name="wake_out_no_sheet">Asked Android to open the assistant; it did not refuse, but no sheet came.</string>
<string name="wake_out_not_connected">Android had not connected LLeMbas as the assistant, so it could not open the sheet.</string>
<string name="wake_out_refused">Android refused to open the assistant: %1$s</string>
<string name="wake_out_activity">Opened it as a screen of the app instead.</string>
<string name="wake_out_notification">Posted a notification to tap instead.</string>
<string name="wake_out_tested">Heard in a test: nothing was to open.</string>
<string name="wake_role_held">LLeMbas was the digital assistant app.</string>
<string name="wake_role_not_held">LLeMbas was not the digital assistant app.</string>
<string name="wake_link_never">Android had not connected the assistant since the app started.</string>
<string name="wake_link_ready">Android had connected the assistant at %1$s.</string>
<string name="wake_link_shutdown">Android had disconnected it at %1$s.</string>
<string name="wake_link_later">Android connected it again at %1$s.</string>
<string name="wake_sheet_ms">The sheet was up after %1$s ms.</string>
<string name="wake_no_recognizers">This phone has no voice recognisers, so Android runs no voice assistant service on it.</string>
<string name="wake_not_active">LLeMbas was chosen as the digital assistant app, but Android was not using it as its voice assistant.</string>
<string name="wake_waited">Waited a moment for Android to connect it.</string>
<string name="wake_show_failed">Android said it could not show the assistant\'s sheet.</string>
<string name="wake_assistant_inactive">Android is not using LLeMbas as its voice assistant right now</string>
<string name="wake_assistant_inactive_line">Choose LLeMbas as the digital assistant app again: tap here, pick another app, then LLeMbas. Until then the long press opens it as an ordinary screen, and the wake word can only send a notification.</string>
<string name="wake_assistant_unbound">LLeMbas is the assistant, but Android has not connected it right now</string>
<string name="wake_assistant_unbound_line">Until it does, the wake word cannot open the sheet by itself. Tap for the system\'s assistant setting: choosing another app and then LLeMbas again connects it.</string>
<string name="wake_heard_could_not">Could not open by itself — tap to ask</string>
<string name="wake_resume">Listen for the wake word again</string>
<string name="wake_resume_line">The phone restarted. Tap to start listening again.</string>
<string name="assist_notifications">Summarise my notifications</string>
+1 -1
View File
@@ -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.11 (shire). Do not edit. -->
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.13 (shire). Do not edit. -->
<resources>
<color name="token_bg">#FFF1EAD6</color>
<color name="token_surface">#FFF8F3E5</color>
@@ -1,13 +1,21 @@
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.Recorder
import eu.llembas.android.assist.SheetStop
import eu.llembas.android.assist.isStopPhrase
import eu.llembas.android.assist.lockedStart
import eu.llembas.android.assist.settle
import eu.llembas.android.assist.usePhoneRecognizer
import eu.llembas.android.auth.Prefs
@@ -53,6 +61,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(
@@ -1,6 +1,7 @@
package eu.llembas.android
import eu.llembas.android.api.CardItem
import eu.llembas.android.api.Drawn
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.Message
@@ -8,6 +9,7 @@ import eu.llembas.android.api.Progress
import eu.llembas.android.api.ProgressWords
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.callDuration
import eu.llembas.android.api.drawn
import eu.llembas.android.api.ending
import eu.llembas.android.api.localeNumber
import eu.llembas.android.api.progressLine
@@ -181,4 +183,20 @@ class DisplayTest {
}
}
}
@Test
fun aLineTheServerWroteIsNeverThePersonsBubble() {
val person = Message(id = "m1", role = "user", text = "How many are left?")
val machine = Message(id = "m0", role = "user", machine = true, text = "[report] This conversation continues a report.")
val reply = Message(id = "m2", role = "assistant")
assertEquals(Drawn.Person, drawn(person, first = true, reportChat = false))
assertEquals(Drawn.Reply, drawn(reply, first = false, reportChat = true))
// In any chat: a quiet note.
assertEquals(Drawn.Note, drawn(machine, first = true, reportChat = false))
assertEquals(Drawn.Note, drawn(machine, first = false, reportChat = true))
// In a report's conversation the line that opens it is left out: the report is one tap back.
assertEquals(Drawn.Hidden, drawn(machine, first = true, reportChat = true))
// What the person wrote first in such a chat is still theirs.
assertEquals(Drawn.Person, drawn(person, first = true, reportChat = true))
}
}
@@ -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,82 @@
package eu.llembas.android
import android.app.Application
import android.app.Notification
import android.app.NotificationManager
import eu.llembas.android.push.Notifications
import eu.llembas.android.push.ReportNotice
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 org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
/**
* A report's notification, both of its faces: unlocked, the report's title and summary; on the
* lock screen the app's fixed words and nothing from the account (rule 5).
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35], qualifiers = "en")
class ReportNotificationTest {
private val app: Application get() = RuntimeEnvironment.getApplication()
private val notice = ReportNotice("rep1", "Two tenders opened", "Storage bids are due in May.", high = false)
private fun Notification.words() = listOf(Notification.EXTRA_TITLE, Notification.EXTRA_TEXT, Notification.EXTRA_BIG_TEXT).map {
extras.getCharSequence(it)?.toString().orEmpty()
}
@Test
fun unlockedItSaysTheReportLockedOnlyThatThereIsOne() {
val shown = Notifications.reportNotification(app, "home", notice)
assertEquals(LembasApp.CHANNEL_REPORTS, shown.channelId)
assertEquals("Two tenders opened", shown.words()[0])
assertEquals("Storage bids are due in May.", shown.words()[1])
// Private: Android shows the public version on a locked screen.
assertEquals(Notification.VISIBILITY_PRIVATE, shown.visibility)
val locked = shown.publicVersion
assertNotNull(locked)
assertEquals(listOf("LLeMbas", "New report", ""), locked.words())
// Nothing of the report anywhere in what the lock screen gets.
val all = locked.words().joinToString(" ") + locked.extras.keySet().joinToString(" ") { locked.extras.get(it)?.toString().orEmpty() }
assertFalse(all.contains("tenders"))
assertFalse(all.contains("Storage"))
}
@Test
fun itOffersOpenAndMarkReadAndTheSecondNeedsThePhoneUnlocked() {
val shown = Notifications.reportNotification(app, "home", notice)
assertEquals(listOf("Open", "Mark read"), shown.actions.map { it.title.toString() })
assertFalse(shown.actions[0].isAuthenticationRequired)
assertTrue(shown.actions[1].isAuthenticationRequired)
assertNotNull(shown.contentIntent)
assertEquals(Notification.FLAG_AUTO_CANCEL, shown.flags and Notification.FLAG_AUTO_CANCEL)
// A report without a title still says something that is the app's own.
assertEquals("New report", Notifications.reportNotification(app, "home", notice.copy(title = "")).words()[0])
}
@Test
fun anImportantReportHasAChannelThatComesUp() {
assertEquals(LembasApp.CHANNEL_REPORTS_HIGH, Notifications.reportNotification(app, "home", notice.copy(high = true)).channelId)
val manager = app.getSystemService(NotificationManager::class.java)
assertEquals(NotificationManager.IMPORTANCE_HIGH, manager.getNotificationChannel(LembasApp.CHANNEL_REPORTS_HIGH).importance)
assertEquals(NotificationManager.IMPORTANCE_DEFAULT, manager.getNotificationChannel(LembasApp.CHANNEL_REPORTS).importance)
// Both stay private on the lock screen.
assertEquals(Notification.VISIBILITY_PRIVATE, manager.getNotificationChannel(LembasApp.CHANNEL_REPORTS_HIGH).lockscreenVisibility)
}
@Test
fun readingTheReportInTheAppTakesItsNotificationAway() {
val manager = app.getSystemService(NotificationManager::class.java)
manager.notify(notice.id, Notifications.reportNotification(app, "home", notice))
assertNotNull(shadowOf(manager).getNotification(notice.id))
Notifications.reportSeen(app, "rep1")
assertNull(shadowOf(manager).getNotification(notice.id))
}
}
@@ -0,0 +1,122 @@
package eu.llembas.android
import eu.llembas.android.api.Chat
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.Report
import eu.llembas.android.api.ReportList
import eu.llembas.android.api.ReportReply
import eu.llembas.android.api.ReportsFrame
import eu.llembas.android.api.RunResult
import eu.llembas.android.api.Step
import eu.llembas.android.api.shownMarkdown
import eu.llembas.android.push.ReportNotice
import eu.llembas.android.push.ScheduledNotice
import eu.llembas.android.ui.Segment
import eu.llembas.android.ui.reports.shareText
import eu.llembas.android.ui.splitFences
import kotlinx.serialization.KSerializer
import kotlinx.serialization.json.jsonObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The server's reports contract (`contract/report*.json`, `push_report.json`,
* `event_reports.json`, written by its own serialisers): every file read with the app's models,
* and what the app makes of each.
*/
class ReportsContractTest {
private fun text(name: String): String = requireNotNull(javaClass.classLoader!!.getResource("$name.json")) { "contract/$name.json is missing" }.readText()
private fun <T> read(name: String, serializer: KSerializer<T>): T = LembasJson.decodeFromString(serializer, text(name))
@Test
fun theListAndTheCountOfTheUnread() {
val list = read("reports", ReportList.serializer())
val report = list.reports.single()
assertEquals("rep1", report.id)
assertEquals("Two cakes are unwrapped", report.title)
assertEquals("Two of the twelve cakes have lost their leaves.", report.summary)
assertTrue(report.high)
assertTrue(report.unread)
assertEquals("Waybread check", report.schedule?.title)
assertEquals("2026-01-02T03:04:05+00:00", report.created)
assertEquals(1, list.unreadCount)
// The same for the events frame, which carries the newest one too.
val frame = read("event_reports", ReportsFrame.serializer())
assertEquals(1, frame.unread)
assertEquals("rep1", frame.newest?.id)
assertEquals("2026-01-02T03:04:05+00:00", frame.latestCreated)
}
@Test
fun oneReportIsWrappedAndItsPageIsACard() {
// `GET /reports/{id}` answers `{report: …}`: read as ApiClient.report reads it.
val report = LembasJson.decodeFromJsonElement(Report.serializer(), LembasJson.parseToJsonElement(text("report")).jsonObject.getValue("report"))
assertEquals("chat9", report.chatId)
assertEquals("gpt-oss", report.model)
// The body carries the page's source; the phone draws the server's text, where the page
// is its one line and becomes a card -- never the source.
assertEquals("Cakes", report.pages.single().title)
val drawn = splitFences(report.text!!)
assertEquals(Segment.Page("Cakes"), drawn.last())
assertFalse(drawn.any { it is Segment.Code })
// Share takes the server's own text, where the page is its one line.
assertEquals("Two cakes are unwrapped\n\n## What\n\nTwo of the twelve cakes have lost their leaves.\n\n[page: Cakes]", shareText(report))
assertFalse(shareText(report).contains("10 wrapped"))
assertEquals("chat9", read("report_reply", ReportReply.serializer()).chatId)
}
@Test
fun theReportsPush() {
val payload = read("push_report", PushPayload.serializer())
val notice = ReportNotice.from(payload)!!
assertEquals("rep1", notice.reportId)
// The words are the notification's; the payload's top is the app's name and "New report".
assertEquals("Two cakes are unwrapped", notice.title)
assertEquals("Two of the twelve cakes have lost their leaves.", notice.summary)
assertTrue(notice.high)
assertEquals("LLeMbas", payload.title)
// It is not a scheduled result, though it names the schedule and the run.
assertNull(ScheduledNotice.from(payload))
// And the run that filed it says which report.
assertEquals("rep1", read("schedule_run", RunResult.serializer()).run.reportId)
}
@Test
fun aReportsConversationSaysWhichReportAndWhatMayBeDoneToIt() {
val chat = read("chat_report", Chat.serializer())
assertEquals("report", chat.kind)
assertEquals("rep1", chat.report?.id)
assertEquals("Two cakes are unwrapped", chat.report?.title)
// Rename and delete; not archive, pin or a folder.
assertTrue(chat.allows("rename") && chat.allows("delete"))
assertFalse(chat.allows("archive") || chat.allows("pin") || chat.allows("folder"))
// An ordinary chat allows all of them, and so does a server that does not say.
assertTrue(read("chat", Chat.serializer()).allows("archive"))
assertNull(read("chat", Chat.serializer()).report)
assertTrue(LembasJson.decodeFromString(Chat.serializer(), """{"id":"c1"}""").allows("archive"))
}
@Test
fun aReportWhoseScheduleIsGoneKeepsItsName() {
val orphan = LembasJson.decodeFromJsonElement(Report.serializer(), LembasJson.parseToJsonElement(text("report_orphan")).jsonObject.getValue("report"))
assertNull(orphan.schedule)
assertEquals("Waybread check", orphan.from)
assertEquals("Waybread check", read("reports", ReportList.serializer()).reports.single().from)
}
@Test
fun aStepWithAPageIsShownByItsText() {
val step = read("step_text_page", Step.serializer())
assertEquals("Cakes", step.pages.single().title)
// The server's own text, where the page is its one line -- which the phone draws as a card.
assertEquals("Two are unwrapped.\n\n[page: Cakes]\n", step.shownMarkdown)
assertEquals(listOf(Segment.Prose("Two are unwrapped."), Segment.Page("Cakes")), splitFences(step.shownMarkdown))
// A step without pages is its markdown.
assertEquals("plain", Step(kind = "text", markdown = "plain", text = "other").shownMarkdown)
}
}
@@ -0,0 +1,246 @@
package eu.llembas.android
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PushPayload
import eu.llembas.android.api.Report
import eu.llembas.android.api.ReportList
import eu.llembas.android.api.ReportReply
import eu.llembas.android.api.Schedule
import eu.llembas.android.api.ScheduleRun
import eu.llembas.android.api.notifyChoice
import eu.llembas.android.api.safeId
import eu.llembas.android.api.sortedReports
import eu.llembas.android.push.Notifications
import eu.llembas.android.push.ReportNotice
import eu.llembas.android.push.ScheduledNotice
import eu.llembas.android.ui.Segment
import eu.llembas.android.ui.pageProjection
import eu.llembas.android.ui.reports.shareText
import eu.llembas.android.ui.scheduled.EditState
import eu.llembas.android.ui.scheduled.notifyToSend
import eu.llembas.android.ui.splitFences
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Reports (harness spec 3.8.0, `reports.md`) and pages in an answer (`pages.md`), as far as they
* need no phone: the shapes, the list's order, "notify when", the push, and a page's place in
* the text. The shapes here are written out in the test; `ReportsContractTest` reads the server's
* own fixtures once they are pinned.
*/
class ReportsTest {
private val list = """
{"reports": [
{"id": "rep1", "title": "Two tenders opened", "summary": "Storage bids are due in May.", "importance": "high",
"schedule": {"id": "s1", "title": "Morning news"}, "created": "2026-03-10T07:31:00+00:00", "unread": true},
{"id": "rep2", "title": "Nothing new on the bridge", "summary": "", "importance": "normal",
"schedule": {"id": "s2", "title": "Bridge watch"}, "created": "2026-03-11T07:31:00+00:00", "unread": false},
{"id": "rep3", "title": "Flour is back in stock", "created": "2026-03-09T07:31:00+00:00", "unread": true}
]}
""".trimIndent()
@Test
fun theListAndItsOrder() {
val reports = LembasJson.decodeFromString(ReportList.serializer(), list).reports
assertEquals("Morning news", reports[0].schedule?.title)
assertTrue(reports[0].high)
assertFalse(reports[2].high)
assertNull(reports[2].schedule)
// The unread first, the newest first within each half.
assertEquals(listOf("rep1", "rep3", "rep2"), sortedReports(reports).map { it.id })
// A server that says nothing has none.
assertTrue(LembasJson.decodeFromString(ReportList.serializer(), "{}").reports.isEmpty())
}
@Test
fun oneReportItsBodyAndTheChatAReplyContinuesIn() {
val alone = LembasJson.decodeFromString(
Report.serializer(),
"""{"id":"rep1","title":"Two tenders opened","body":"**Two** tenders.","chat":null,"unread":true,"created_at":"2026-03-10T07:31:00+00:00"}""",
)
assertEquals("**Two** tenders.", alone.body)
assertNull(alone.chatId)
// `created` under either name.
assertEquals("2026-03-10T07:31:00+00:00", alone.created)
// The chat as an id, or as an object carrying one: both are the chat.
val replied = LembasJson.decodeFromString(Report.serializer(), """{"id":"rep1","chat":"chat9"}""")
assertEquals("chat9", replied.chatId)
assertEquals("chat9", LembasJson.decodeFromString(Report.serializer(), """{"id":"rep1","chat":{"id":"chat9"}}""").chatId)
assertEquals("chat9", LembasJson.decodeFromString(ReportReply.serializer(), """{"chat":"chat9"}""").chatId)
assertNull(LembasJson.decodeFromString(ReportReply.serializer(), """{"chat":""}""").chatId)
}
@Test
fun aRunLeavesANoteAndMaybeAReport() {
val filed = LembasJson.decodeFromString(ScheduleRun.serializer(), """{"id":"r1","status":"ok","note":"Two tenders; report filed.","report":"rep1"}""")
assertEquals("Two tenders; report filed.", filed.note)
assertEquals("rep1", filed.reportId)
val quiet = LembasJson.decodeFromString(ScheduleRun.serializer(), """{"id":"r2","status":"ok","note":"Nothing changed since Monday.","report":null}""")
assertNull(quiet.reportId)
// A server before 3.8.0 says neither.
val old = LembasJson.decodeFromString(ScheduleRun.serializer(), """{"id":"r3","status":"silent"}""")
assertEquals("", old.note)
assertNull(old.reportId)
}
@Test
fun notifyWhenIsOneOfThree() {
assertEquals("always", notifyChoice("always"))
assertEquals("never", notifyChoice("never"))
assertEquals("when", notifyChoice("when"))
// What a server before 3.8.0 called "when it matters", and a schedule that says nothing: the default.
assertEquals("when", notifyChoice("matters"))
assertEquals("when", notifyChoice(""))
val schedule = LembasJson.decodeFromString(Schedule.serializer(), """{"id":"s1","notify":"when","notify_when":"the price drops below 100"}""")
assertEquals("the price drops below 100", schedule.notifyWhen)
assertEquals("", LembasJson.decodeFromString(Schedule.serializer(), """{"id":"s1","notify":"matters"}""").notifyWhen)
}
@Test
fun aReportsPushOpensTheReport() {
val payload = LembasJson.decodeFromString(
PushPayload.serializer(),
"""{"kind":"report","title":"Two tenders opened","body":"Storage bids are due in May.","url":"/reports/rep1"}""",
)
val notice = ReportNotice.from(payload)!!
assertEquals("rep1", notice.reportId)
assertEquals("Two tenders opened", notice.title)
assertEquals("Storage bids are due in May.", notice.summary)
assertFalse(notice.high)
// The id named outright wins over the address, and importance may make it urgent.
val named = payload.copy(reportId = "rep7", importance = "high")
assertEquals("rep7", ReportNotice.from(named)!!.reportId)
assertTrue(ReportNotice.from(named)!!.high)
// One notification per report.
assertEquals(notice.id, ReportNotice.from(payload)!!.id)
// Not a report: nothing; and a report is not a scheduled result.
assertNull(ReportNotice.from(payload.copy(kind = "reply")))
assertNull(ReportNotice.from(payload.copy(url = "/chat/c1")))
assertNull(ScheduledNotice.from(payload))
}
@Test
fun theReportsWordsComeFromThePayloadsNotification() {
// The payload's top is for a client that knows nothing of reports; the words are inside.
val payload = LembasJson.decodeFromString(
PushPayload.serializer(),
"""{"kind":"report","report_id":"rep1","title":"LLeMbas","body":"New report","url":"/reports/rep1",
"notification":{"title":"Two tenders opened","body":"Storage bids are due in May.","public":{"title":"New report","body":""},"importance":"high"}}""",
)
val notice = ReportNotice.from(payload)!!
assertEquals("Two tenders opened", notice.title)
assertEquals("Storage bids are due in May.", notice.summary)
assertTrue(notice.high)
}
@Test
fun anOlderServersScheduledPushStillWorks() {
// 2.0.0-beta.11 and before: a run's result is its own push, which opens the run.
val result = LembasJson.decodeFromString(
PushPayload.serializer(),
"""{"kind":"schedule","title":"Morning news","body":"Little happened.","url":"/scheduled/s1?run=r1","schedule_id":"s1","run_id":"r1"}""",
)
assertNull(ReportNotice.from(result))
val notice = ScheduledNotice.from(result)!!
assertEquals("s1", notice.scheduleId)
assertEquals("r1", notice.runId)
assertFalse(notice.failed)
// A failed run keeps its failure notification under 3.8.0 too.
assertTrue(ScheduledNotice.from(result.copy(kind = "schedule_failed"))!!.failed)
}
@Test
fun onlyWhatLooksLikeAnIdBecomesARoute() {
assertEquals("rep1", safeId("rep1"))
assertEquals("a-b_C9", safeId("a-b_C9"))
// A slash, a query, a dot, nothing, too much: none of these is an id.
for (bad in listOf("a/b", "rep1?x=1", "..", "", "rep 1", "x".repeat(65))) assertNull(bad, safeId(bad))
assertNull(safeId(null))
// A push whose id is no id shows nothing rather than open somewhere else.
val push = PushPayload(kind = "report", reportId = "rep1/../../chat/c1", url = "/reports/rep1")
assertNull(ReportNotice.from(push))
assertNull(ReportNotice.from(PushPayload(kind = "report", url = "/reports/a%2Fb")))
assertNull(ScheduledNotice.from(PushPayload(kind = "schedule", scheduleId = "s1/x")))
// The run's id alone being bad drops the run, not the notification.
assertNull(ScheduledNotice.from(PushPayload(kind = "schedule", scheduleId = "s1", runId = "r/1"))!!.runId)
}
@Test
fun aPushOfAKindThisAppDoesNotKnowIsNotAChat() {
assertTrue(Notifications.chatKind(""))
assertTrue(Notifications.chatKind("reply"))
assertTrue(Notifications.chatKind("ask"))
assertFalse(Notifications.chatKind("digest"))
assertFalse(Notifications.chatKind("report"))
}
@Test
fun theFormSendsNotifyOnlyWhenItKnowsWhatItSends() {
val fresh = EditState(reports = true)
// A new schedule: what the form shows is what is meant.
assertEquals("when", notifyToSend(fresh, editing = false))
// An instance without Reports is sent nothing new.
assertNull(notifyToSend(EditState(reports = false, notify = "never", notifyTouched = true), editing = false))
// Editing before the schedule was read (or when reading it failed): the default is not written over it...
assertNull(notifyToSend(fresh, editing = true))
assertNull(notifyToSend(fresh.copy(loadFailed = true), editing = true))
// ...unless the person chose, or it was read.
assertEquals("never", notifyToSend(fresh.copy(notify = "never", notifyTouched = true), editing = true))
assertEquals("always", notifyToSend(fresh.copy(notify = "always", loaded = true), editing = true))
}
@Test
fun aSpaceBeforeTheWordIsNotAPage() {
// The spec: `html-view` stands straight after the fence. With a space it is a code block, here as on the server.
assertEquals(listOf(Segment.Code("html-view", "<p>x</p>")), splitFences("``` html-view Cakes\n<p>x</p>\n```"))
}
@Test
fun aPageBeingWrittenIsNeverItsSource() {
// The open step of a reply as it streams, in a chat where pages are written: the fence is a page already.
val reply = "Sales by month:\n\n```html-view Monthly sales\n<!doctype html>\n<html><script>alert(1)</script></html>\n```\n\nThat is all."
val split = splitFences(reply, pages = true)
assertEquals(listOf(Segment.Prose("Sales by month:"), Segment.Page("Monthly sales"), Segment.Prose("That is all.")), split)
// The word is exact: these are ordinary code blocks.
assertEquals(listOf(Segment.Code("html", "<p>")), splitFences("```html\n<p>\n```", pages = true))
assertEquals(listOf(Segment.Code("html-views", "<p>")), splitFences("```html-views\n<p>\n```", pages = true))
// Tildes, no title, and one not closed yet.
assertEquals(listOf(Segment.Page("")), splitFences("~~~html-view\n<html></html>\n~~~", pages = true))
assertEquals(listOf(Segment.Page("Chart", closed = false)), splitFences("```html-view Chart\n<html>", pages = true))
// Backticks inside a page do not end it unless a line is the closing fence.
assertEquals(listOf(Segment.Page("T")), splitFences("````html-view T\nconst a = `x`\n```\nstill the page\n````", pages = true))
}
@Test
fun whichFenceIsAPageIsTheServersToSay() {
// Anywhere else -- a finished step, a report -- a fence is a page only if the server
// said so, and then it sent the one line in its place. A fence it did not list (written
// while pages were not offered) is the code block it is.
assertEquals(listOf(Segment.Code("html-view", "<p>x</p>")), splitFences("```html-view Cakes\n<p>x</p>\n```"))
assertEquals(
listOf(Segment.Prose("Before."), Segment.Page("Monthly sales"), Segment.Prose("After.")),
splitFences("Before.\n\n[page: Monthly sales]\n\nAfter."),
)
assertEquals(listOf(Segment.Prose("See [page: x] inline.")), splitFences("See [page: x] inline."))
}
@Test
fun whatIsCopiedOrSharedSaysThereIsAPage() {
val text = pageProjection("Sales:\n\n[page: Monthly sales]\n\n```sh\nmake\n```", untitled = "Page")
assertEquals("Sales:\n\n[page: Monthly sales]\n\n```sh\nmake\n```", text)
assertEquals("[page: Page]", pageProjection("[page: ]", untitled = "Page"))
// A report is shared by the server's text of it, where each page is its one line.
val report =
Report(
id = "rep1",
title = "Two tenders opened",
body = "Bids are due.\n\n```html-view Chart\n<svg></svg>\n```",
text = "Bids are due.\n\n[page: Chart]\n",
)
assertEquals("Two tenders opened\n\nBids are due.\n\n[page: Chart]", shareText(report))
assertFalse(shareText(report).contains("<svg>"))
}
}
@@ -51,7 +51,10 @@ class ScheduleContractTest {
assertEquals("2026-01-12T07:30:00+00:00", s.nextRun)
assertEquals(5, s.nextRuns.size)
assertEquals("fresh", s.mode)
assertEquals("matters", s.notify)
// Spec 3.8.0: when the person's own words hold -- none here, so the server's default.
assertEquals("when", s.notify)
assertEquals("", s.notifyWhen)
assertEquals("something needs my attention", s.notifyDefault)
assertEquals("one", s.catchUp)
assertNull(s.graceMinutes)
assertEquals("qwen", s.model)
@@ -80,6 +83,9 @@ class ScheduleContractTest {
assertEquals("msg2", run.messageId)
assertEquals("All the waybread is wrapped.", run.preview)
assertTrue(run.notified)
// The run filed a report, and left its line for the history.
assertEquals("rep1", run.reportId)
assertEquals("Filed a report: two cakes are unwrapped.", run.note)
}
@Test
@@ -87,7 +93,7 @@ class ScheduleContractTest {
assertWaybread(read("schedules", ScheduleList.serializer()).schedules.single())
assertWaybread(read("schedule", ScheduleEnvelope.serializer()).schedule)
val frame = read("event_schedules", SchedulesFrame.serializer())
assertEquals("8bee85746004dc19", frame.version)
assertEquals("d55e588277f6c90b", frame.version)
assertWaybread(frame.schedules.single())
}
@@ -226,9 +232,20 @@ class ScheduleContractTest {
@Test
fun theServersNotificationWordsAndRunAgain() {
// `push_schedule.json`: the task's name and first lines unlocked, Finished on the lock
// screen, Open and Run again with the owner's labels.
val done = ScheduledNotice.from(read("push_schedule", PushPayload.serializer()))!!
// What a server before 3.8.0 sent for a finished run (it sends a report's push now):
// the task's name and first lines unlocked, Finished on the lock screen, Open and Run
// again with the owner's labels. Such an instance is still talked to.
val done = ScheduledNotice.from(
LembasJson.decodeFromString(
PushPayload.serializer(),
"""{"schedule_id":"sched1","run_id":"run1","chat_id":"chat1","status":"ok","visibility":"private",
"actions":["open","run_again"],"ask":"",
"notification":{"title":"Waybread check","body":"All the waybread is wrapped.",
"public":{"title":"Waybread check","body":"Finished"},"actions":["open","run_again"],
"labels":{"open":"Open","run_again":"Run again"},"ask":""},
"title":"LLeMbas","body":"A scheduled task has finished.","url":"/scheduled/sched1?run=run1","kind":"schedule"}""",
),
)!!
assertEquals("Waybread check", done.title)
assertEquals("All the waybread is wrapped.", done.body)
assertEquals("Waybread check", done.publicTitle)
@@ -248,9 +265,10 @@ class ScheduleContractTest {
assertEquals("Failed", failed.publicBody)
assertEquals("run3", failed.runId)
// The run's own copy (the schedules frame) says the same.
// The run's own copy of its notification is the report's now: Open alone.
val run = read("schedule_run", RunResult.serializer()).run
assertEquals(listOf("open", "run_again"), run.notification!!.actions)
assertEquals(listOf("open"), run.notification!!.actions)
assertEquals("high", run.notification!!.importance)
}
@Test
@@ -13,6 +13,7 @@ import eu.llembas.android.wake.wakeKeywords
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
@@ -140,6 +141,33 @@ class WakeListenerTest {
job.cancelAndJoin()
}
@Test
fun answeringTheWordIsNotCancelledByThePauseItCauses() = runTest {
// What a real wake does: its first step pauses the listening (the sheet takes the
// microphone), then it waits for the sheet, then it writes down what happened.
val plans = MutableStateFlow(plan)
var written = false
val listener = WakeListener(
say = { states += it },
engine = { Detector(hearOn = 2) },
microphone = { Mic() },
heard = {
plans.value = plan.copy(pause = WakePause.Assistant)
delay(2_500)
written = true
},
work = StandardTestDispatcher(testScheduler),
)
val job = launch { listener.follow(plans) }
runCurrent()
// The listening is paused, as asked...
assertEquals(WakeState.Paused(WakePause.Assistant), states.last())
// ...and the answer goes on to its end all the same.
advanceTimeBy(2_501)
assertTrue(written)
job.cancelAndJoin()
}
@Test
fun aTapTriesAgainNowAndStartsTheWaitsOver() = runTest {
var opens = 0
@@ -3,10 +3,12 @@ package eu.llembas.android
import android.app.Application
import android.app.Notification
import android.app.NotificationManager
import eu.llembas.android.wake.WakeAttempt
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeWordService
import eu.llembas.android.wake.wakeAttemptWords
import eu.llembas.android.wake.wakeHeardNotification
import eu.llembas.android.wake.wakeNotification
import eu.llembas.android.wake.wakeTitle
@@ -19,6 +21,8 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.time.ZoneOffset
import java.util.Locale
/**
* What the wake word's notification says, from its state alone: the phrase only while it really
@@ -95,4 +99,82 @@ class WakeNotificationTest {
assertEquals(Notification.FLAG_AUTO_CANCEL, heard.flags and Notification.FLAG_AUTO_CANCEL)
assertNotNull(heard.contentIntent)
}
@Test
fun theFallbackSaysWhyInFixedWords() {
fun line(assistant: Boolean) = wakeHeardNotification(app, assistant).extras.getCharSequence(Notification.EXTRA_TEXT).toString()
// The assistant, and still it could not open by itself this time.
assertEquals("Could not open by itself — tap to ask", line(assistant = true))
// Not the assistant: that is the reason.
assertEquals("LLeMbas can open by itself over other apps only as the phone's digital assistant app.", line(assistant = false))
}
@Test
fun theLastWakeInPlainWords() {
val zone = ZoneOffset.UTC
val at = 1_773_129_600_000 // Tue 10 Mar 2026, 08:00:00 UTC
fun words(attempt: WakeAttempt) = wakeAttemptWords(app, attempt, zone, Locale.ENGLISH)
assertEquals(
listOf("Tue 10 Mar, 08:00:00 · “Hey Assistant”", "Opened the assistant."),
words(WakeAttempt(at = at, phrase = "Hey Assistant", way = "session", outcome = WakeAttempt.OUT_OPENED, assistant = true, readyAt = at - 60_000)),
)
// The assistant in name, but Android was not using it: said step by step.
val missed = words(
WakeAttempt(
at = at,
phrase = "Hey Assistant",
way = "notification",
outcome = WakeAttempt.OUT_NOT_CONNECTED,
fallback = "notification",
assistant = true,
connectedLater =
at + 30_000,
),
)
assertEquals(
listOf(
"Tue 10 Mar, 08:00:00 · “Hey Assistant”",
"Android had not connected LLeMbas as the assistant, so it could not open the sheet.",
"Posted a notification to tap instead.",
"LLeMbas was chosen as the digital assistant app, but Android was not using it as its voice assistant.",
"Android had not connected the assistant since the app started.",
"Android connected it again at Tue 10 Mar, 08:00:30.",
"screen=on locked=false visible=false created=- destroyed=- prepared=false",
),
missed,
)
// Active and held, and still not connected: the plain "was the assistant" line, and that it was waited for.
val waited =
words(WakeAttempt(at = at, phrase = "Hey Assistant", outcome = WakeAttempt.OUT_NOT_CONNECTED, assistant = true, active = true, waited = true))
assertEquals("LLeMbas was the digital assistant app.", waited[2])
assertEquals("Waited a moment for Android to connect it.", waited[3])
// A sheet that came says how long it took.
assertEquals(
"The sheet was up after 180 ms.",
words(WakeAttempt(at = at, phrase = "Hey Assistant", way = "session", outcome = WakeAttempt.OUT_OPENED, sheetMs = 180))[2],
)
// Android's own words where it refused, and when it had connected and dropped the service.
val refused = words(
WakeAttempt(
at = at,
phrase = "OK Computer",
way = "session",
outcome = WakeAttempt.OUT_REFUSED,
detail = "SecurityException: not the current voice interaction service",
fallback = "activity",
readyAt = at - 3_600_000,
shutdownAt = at - 60_000,
),
)
assertEquals("Android refused to open the assistant: SecurityException: not the current voice interaction service", refused[1])
assertEquals("Opened it as a screen of the app instead.", refused[2])
assertEquals("LLeMbas was not the digital assistant app.", refused[3])
assertEquals("Android had connected the assistant at Tue 10 Mar, 07:00:00.", refused[4])
assertEquals("Android had disconnected it at Tue 10 Mar, 07:59:00.", refused[5])
assertEquals("Heard in a test: nothing was to open.", words(WakeAttempt(at = at, phrase = "Hey Assistant", outcome = WakeAttempt.OUT_TESTED))[1])
assertEquals(
"Asked Android to open the assistant; it did not refuse, but no sheet came.",
words(WakeAttempt(at = at, phrase = "Hey Assistant", way = "session", outcome = WakeAttempt.OUT_NO_SHEET, fallback = "notification"))[1],
)
}
}
@@ -0,0 +1,171 @@
package eu.llembas.android
import eu.llembas.android.wake.WakeAttempt
import eu.llembas.android.wake.WakeFacts
import eu.llembas.android.wake.WakeOpener
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* What is tried when the phrase is heard, in which order, and what is written down about it --
* without a phone: Android's part is a script here (connected or not, refuses or not, a sheet
* comes on the n-th wait or never).
*/
class WakeOpenerTest {
/** One wake against a scripted Android. */
private class Phone(
var facts: WakeFacts,
/** The waits for a sheet, in order: how long each took, or null for "none came". */
val sheets: MutableList<Long?> = mutableListOf(),
val connects: Boolean = false,
val refuses: Throwable? = null,
val activityRefused: Throwable? = null,
) {
val did = mutableListOf<String>()
val opener = WakeOpener(
facts = { facts },
awaitConnected = {
did += "wait-connect"
connects
},
showSession = {
did += "session"
refuses?.let { throw it }
},
startActivity = {
did += "activity"
activityRefused?.let { throw it }
},
sheetCame = {
did += "wait-sheet"
if (sheets.isEmpty()) null else sheets.removeAt(0)
},
notify = { did += "notify" },
now = { 1_000 },
)
}
private val assistant = WakeFacts(connected = true, active = true, role = true)
@Test
fun theAssistantsSheetOpensAndIsCountedOnlyOnceItIsUp() = runTest {
val phone = Phone(assistant, sheets = mutableListOf(180))
val attempt = phone.opener.open("Hey Assistant")
assertEquals(listOf("session", "wait-sheet"), phone.did)
assertEquals(WakeAttempt.OUT_OPENED, attempt.outcome)
assertEquals("session", attempt.way)
assertEquals(180L, attempt.sheetMs)
assertEquals("", attempt.fallback)
assertEquals("Hey Assistant", attempt.phrase)
assertTrue(attempt.assistant && attempt.active)
}
@Test
fun aSlowSessionIsWaitedForAgainAndNothingElseIsPutBesideIt() = runTest {
// No sheet in the first wait, then it comes: one sheet, no activity, no notification.
val phone = Phone(assistant, sheets = mutableListOf(null, 400))
val attempt = phone.opener.open("Hey Assistant")
assertEquals(listOf("session", "wait-sheet", "wait-sheet"), phone.did)
assertEquals(WakeAttempt.OUT_OPENED, attempt.outcome)
assertEquals(WakeOpener.SHEET_WAIT_MS + 400, attempt.sheetMs)
}
@Test
fun aSessionThatNeverComesFallsToTheActivityThenToTheNotification() = runTest {
// Connected, so the activity may start: it is waited for, and counts when it comes.
val came = Phone(assistant, sheets = mutableListOf(null, null, 300))
val opened = came.opener.open("Hey Assistant")
assertEquals(listOf("session", "wait-sheet", "wait-sheet", "activity", "wait-sheet"), came.did)
assertEquals(WakeAttempt.OUT_NO_SHEET, opened.outcome)
assertEquals("activity", opened.fallback)
// Nothing comes at all: the notification, and it is said.
val never = Phone(assistant)
val told = never.opener.open("Hey Assistant")
assertEquals("notify", never.did.last())
assertEquals(1, never.did.count { it == "notify" })
assertEquals("notification", told.fallback)
assertEquals(-1L, told.sheetMs)
}
@Test
fun aRefusalIsKeptInAndroidsOwnWords() = runTest {
val phone = Phone(assistant, refuses = SecurityException("Caller is not the current voice interaction service"), sheets = mutableListOf(250))
val attempt = phone.opener.open("Hey Assistant")
// Refused: no waiting for a session that was never asked for; straight to the activity.
assertEquals(listOf("session", "activity", "wait-sheet"), phone.did)
assertEquals(WakeAttempt.OUT_REFUSED, attempt.outcome)
assertEquals("SecurityException: Caller is not the current voice interaction service", attempt.detail)
assertEquals("activity", attempt.fallback)
}
@Test
fun notConnectedAndNotOnScreenIsANotificationAndSaysWhy() = runTest {
// The role held, but Android does not use the service: nothing to wait for.
val phone = Phone(WakeFacts(connected = false, active = false, role = true, locked = true, screenOn = false))
val attempt = phone.opener.open("Hey Assistant")
// The activity is still tried (a phone may allow it), but it is not relied on or waited for.
assertEquals(listOf("activity", "notify"), phone.did)
assertEquals(WakeAttempt.OUT_NOT_CONNECTED, attempt.outcome)
assertEquals("notification", attempt.way)
assertEquals("notification", attempt.fallback)
assertTrue(attempt.assistant)
assertFalse(attempt.active)
assertFalse(attempt.waited)
assertTrue(attempt.locked)
assertFalse(attempt.screenOn)
}
@Test
fun activeButNotConnectedYetIsGivenAMomentToConnect() = runTest {
val waiting = WakeFacts(connected = false, active = true, role = true)
val phone = Phone(waiting, connects = true, sheets = mutableListOf(200))
val attempt = phone.opener.open("Hey Assistant")
assertEquals(listOf("wait-connect", "session", "wait-sheet"), phone.did)
assertEquals(WakeAttempt.OUT_OPENED, attempt.outcome)
assertTrue(attempt.waited)
// It does not connect in time: the record says that it was waited for.
val late = Phone(waiting, connects = false)
val missed = late.opener.open("Hey Assistant")
assertEquals(listOf("wait-connect", "activity", "notify"), late.did)
assertEquals(WakeAttempt.OUT_NOT_CONNECTED, missed.outcome)
assertTrue(missed.waited)
}
@Test
fun onScreenWithoutTheAssistantTheSheetIsTheAppsOwnScreen() = runTest {
val phone = Phone(WakeFacts(connected = false, active = false, role = false, visible = true), sheets = mutableListOf(120))
val attempt = phone.opener.open("Hey Assistant")
assertEquals(listOf("activity", "wait-sheet"), phone.did)
assertEquals("activity", attempt.way)
assertEquals("activity", attempt.fallback)
assertEquals(120L, attempt.sheetMs)
assertFalse(attempt.assistant)
}
@Test
fun withTheScreenOffTheSheetIsTheActivityAndItIsNotStartedTwice() = runTest {
val dark = assistant.copy(screenOn = false)
val phone = Phone(dark, sheets = mutableListOf(350))
assertEquals("assistant_activity", phone.opener.open("Hey Assistant").way)
assertEquals(listOf("activity", "wait-sheet"), phone.did)
// It does not come up: a notification, not the same activity once more.
val never = Phone(dark)
val told = never.opener.open("Hey Assistant")
assertEquals(listOf("activity", "wait-sheet", "notify"), never.did)
assertEquals(WakeAttempt.OUT_NO_SHEET, told.outcome)
}
@Test
fun theRecordCarriesWhatTheAssistantServiceHadSaid() = runTest {
val phone = Phone(WakeFacts(connected = false, active = false, role = true, recognizers = false))
val link = WakeAttempt(createdAt = 10, destroyedAt = 20, readyAt = 11, shutdownAt = 19)
val attempt = phone.opener.open("OK Computer", link)
assertEquals(1_000L, attempt.at)
assertEquals(listOf(10L, 20L, 11L, 19L), listOf(attempt.createdAt, attempt.destroyedAt, attempt.readyAt, attempt.shutdownAt))
assertFalse(attempt.recognizers)
}
}
@@ -3,23 +3,27 @@ package eu.llembas.android
import eu.llembas.android.api.LembasJson
import eu.llembas.android.auth.Prefs
import eu.llembas.android.wake.AppVisibility
import eu.llembas.android.wake.AssistLink
import eu.llembas.android.wake.AssistPresence
import eu.llembas.android.wake.WakeAttempt
import eu.llembas.android.wake.WakeError
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakeOpening
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakeSensitivity
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeStatus
import eu.llembas.android.wake.WakeWay
import eu.llembas.android.wake.WakeWords
import eu.llembas.android.wake.checkKeywords
import eu.llembas.android.wake.unpackWakeModel
import eu.llembas.android.wake.wakeBackoff
import eu.llembas.android.wake.wakeKeywords
import eu.llembas.android.wake.wakeOpening
import eu.llembas.android.wake.wakeLogAdd
import eu.llembas.android.wake.wakeLogConnected
import eu.llembas.android.wake.wakePause
import eu.llembas.android.wake.wakeStateAtStart
import eu.llembas.android.wake.wakeWay
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
@@ -160,13 +164,15 @@ class WakeTest {
@Test
fun theAssistantIsOpenedOnlyTheWayAndroidAllows() {
// The phone's assistant: its own service shows the sheet, on screen or not.
assertEquals(WakeOpening.Session, wakeOpening(isAssistant = true, appVisible = false))
assertEquals(WakeOpening.Session, wakeOpening(isAssistant = true, appVisible = true))
// Not the assistant, but on screen: the sheet's activity may start.
assertEquals(WakeOpening.Activity, wakeOpening(isAssistant = false, appVisible = true))
// Neither: an activity start is blocked without a word, so the notification is what is relied on.
assertEquals(WakeOpening.Notification, wakeOpening(isAssistant = false, appVisible = false))
// The assistant service connected and the screen on: it shows its sheet, on screen or not.
assertEquals(WakeWay.Session, wakeWay(connected = true, screenOn = true, appVisible = false))
assertEquals(WakeWay.Session, wakeWay(connected = true, screenOn = true, appVisible = true))
// Connected, the screen off: the sheet's activity through the service, which turns the screen on.
assertEquals(WakeWay.AssistantActivity, wakeWay(connected = true, screenOn = false, appVisible = false))
// Not connected -- whether or not LLeMbas is the assistant in name: only what the app itself may do.
assertEquals(WakeWay.Activity, wakeWay(connected = false, screenOn = true, appVisible = true))
assertEquals(WakeWay.Notification, wakeWay(connected = false, screenOn = true, appVisible = false))
assertEquals(WakeWay.Notification, wakeWay(connected = false, screenOn = false, appVisible = false))
repeat(3) { AppVisibility.activityStopped() }
assertFalse(AppVisibility.visible)
AppVisibility.activityStarted()
@@ -220,6 +226,45 @@ class WakeTest {
assertEquals(WakeState.Starting, wakeStateAtStart(running = true, current = WakeState.Off))
}
@Test
fun theLastFiveWakesAreKeptNewestFirst() {
var log = emptyList<WakeAttempt>()
for (i in 1..7) log = wakeLogAdd(log, WakeAttempt(at = i * 1_000L, phrase = "Hey Assistant", way = "session", outcome = WakeAttempt.OUT_OPENED))
assertEquals(listOf(7_000L, 6_000L, 5_000L, 4_000L, 3_000L), log.map { it.at })
// They live in the phone's settings, and read back as they were written.
val saved = LembasJson.encodeToString(Prefs.serializer(), Prefs(wakeLog = log))
assertEquals(log, LembasJson.decodeFromString(Prefs.serializer(), saved).wakeLog)
assertTrue(Prefs().wakeLog.isEmpty())
}
@Test
fun anAttemptThatFoundTheAssistantNotConnectedLearnsThatItCameLater() {
val missed = WakeAttempt(at = 5_000, outcome = WakeAttempt.OUT_NOT_CONNECTED, fallback = "notification", assistant = true)
val earlier = WakeAttempt(at = 1_000, outcome = WakeAttempt.OUT_NOT_CONNECTED)
val told = wakeLogConnected(listOf(missed, earlier), now = 9_000)
assertEquals(9_000L, told[0].connectedLater)
// Only the newest, only once, and never by a connection from before it.
assertEquals(0L, told[1].connectedLater)
assertEquals(told, wakeLogConnected(told, now = 12_000))
assertEquals(listOf(missed), wakeLogConnected(listOf(missed), now = 4_000))
// An attempt that opened, or an empty record, has nothing to learn.
val opened = listOf(WakeAttempt(at = 5_000, outcome = WakeAttempt.OUT_OPENED))
assertEquals(opened, wakeLogConnected(opened, now = 9_000))
assertTrue(wakeLogConnected(emptyList(), now = 9_000).isEmpty())
}
@Test
fun theAssistantsLinkIsWhatAndroidLastSaid() {
AssistLink.ready(now = 1_000)
assertTrue(AssistLink.connected.value)
assertEquals(1_000L, AssistLink.readyAt)
AssistLink.shutdown(now = 2_000)
assertFalse(AssistLink.connected.value)
assertEquals(2_000L, AssistLink.shutdownAt)
AssistLink.sheetShown(elapsed = 77)
assertEquals(77L, AssistLink.shown.value)
}
@Test
fun onlyTheNewestServiceWritesTheState() {
val old = WakeStatus.begin()
@@ -19,6 +19,8 @@ import eu.llembas.android.api.Message
import eu.llembas.android.api.Metrics
import eu.llembas.android.api.ModelList
import eu.llembas.android.api.Progress
import eu.llembas.android.api.Report
import eu.llembas.android.api.ReportSchedule
import eu.llembas.android.api.RunError
import eu.llembas.android.api.RunModel
import eu.llembas.android.api.RunResult
@@ -50,6 +52,8 @@ import eu.llembas.android.ui.chat.ChatState
import eu.llembas.android.ui.chat.Draft
import eu.llembas.android.ui.home.ChatsState
import eu.llembas.android.ui.memory.MemoryState
import eu.llembas.android.ui.reports.ReportState
import eu.llembas.android.ui.reports.ReportsState
import eu.llembas.android.ui.scheduled.EditState
import eu.llembas.android.ui.scheduled.ModelsState
import eu.llembas.android.ui.scheduled.RunState
@@ -57,8 +61,10 @@ import eu.llembas.android.ui.scheduled.ScheduleState
import eu.llembas.android.ui.scheduled.ScheduledState
import eu.llembas.android.ui.settings.SettingsState
import eu.llembas.android.ui.settings.WakeTestShown
import eu.llembas.android.wake.WakeAttempt
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakeState
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.jsonObject
import java.time.LocalDate
@@ -369,6 +375,7 @@ object Fakes {
wakeState = WakeState.Listening("OK Google"),
notificationsBuild = true,
navApps = listOf("google", "osmand"),
assistantModels = models,
)
/** The wake word in trouble, and its test having heard the phrase: what the rows say then. */
@@ -378,6 +385,24 @@ object Fakes {
wakeTest = WakeTestShown(done = true),
)
/** The assistant in name but not connected, and a last wake that says so step by step. */
val settingsWakeUnbound = settings.copy(
assistantConnected = false,
prefs = settings.prefs.copy(
wakeLog = listOf(
WakeAttempt(
at = 1_773_129_600_000,
phrase = "OK Google",
way = "notification",
outcome = WakeAttempt.OUT_NOT_CONNECTED,
fallback = "notification",
assistant = true,
),
WakeAttempt(at = 1_773_126_000_000, phrase = "OK Google", way = "session", outcome = WakeAttempt.OUT_OPENED, assistant = true),
),
),
)
/** A standard build: the test heard the phrase twice, and notification summaries are in the other build. */
val settingsWakeTested = settings.copy(wakeTest = WakeTestShown(running = true, heard = 2), notificationsBuild = false, isAssistant = false)
@@ -645,6 +670,66 @@ object Fakes {
),
)
/** Reports: two unread (one marked important), one read; a long title and a long task name. */
val reports = ReportsState(
reports = listOf(
Report(
id = "rep1",
title = "Two storage tenders opened, and one of them closes before the next run",
summary = "Austria asks for 200 MW of grid storage, bids due in May. A second, smaller one closes on Friday.",
importance = "high",
schedule = ReportSchedule("s1", "Morning news on renewables"),
created = "2026-03-10T07:31:00+00:00",
unread = true,
),
Report(
id = "rep2",
title = "Flour is back in stock",
summary = "The mill lists the stone-ground flour again.",
schedule = ReportSchedule("s2", "The mill's price list, watched every hour of every working day"),
created = "2026-03-09T16:00:00+00:00",
unread = true,
),
Report(
id = "rep3",
title = "Nothing new on the bridge",
summary = "The council has not published the minutes yet.",
schedule = ReportSchedule("s3", "Bridge watch"),
created = "2026-03-08T07:31:00+00:00",
),
),
)
/** One report read as a page: Markdown, a code block, and a page a phone does not draw. */
val report = ReportState(
loading = false,
report = reports.reports[0].copy(
unread = false,
body = """
|Two tenders for grid storage opened this week.
|
|1. **Austria**: 200 MW, bids due on 15 May.
|2. **A smaller one** closes on Friday; see the [notice](https://example.org/notice).
|
|[page: Storage tenders by month]
|
|```text
|storage tender: 200 MW, deadline 2026-05-15
|```
""".trimMargin(),
),
)
/** A task's history under spec 3.8.0: a run that filed a report, one that says why it did not, one unchanged. */
val scheduleWithReports = ScheduleState(
schedule = schedules[0].copy(notify = "when", notifyWhen = "a tender for storage opens or closes"),
runs = listOf(
ok.copy(id = "r-10", note = "Two tenders opened; the report says which.", report = JsonPrimitive("rep1"), preview = ""),
ok.copy(id = "r-11", note = "No tender opened or closed since yesterday, so there is nothing to report.", preview = ""),
ScheduleRun(id = "r-12", scheduleId = "s1", dueAt = "2026-03-06T07:30:00+00:00", status = "unchanged", note = "The page did not change."),
),
)
val schedulingModels = ModelsState(
models = SchedulingModels(
models = listOf(
@@ -657,6 +742,9 @@ object Fakes {
),
)
/** The form with "When…" chosen and the person's own words in it. */
val editingNotify: EditState get() = editing.copy(reports = true, notify = "when", notifyWhen = "a tender for storage opens or closes")
val editing = EditState(
words = "Every weekday at 7:30, sum up the news about renewable energy in five points",
compiled = ScheduleCompiled(
@@ -54,11 +54,16 @@ import eu.llembas.android.ui.home.DrawerContent
import eu.llembas.android.ui.memory.MemoryActions
import eu.llembas.android.ui.memory.MemoryContent
import eu.llembas.android.ui.memory.MemoryState
import eu.llembas.android.ui.reports.ReportContent
import eu.llembas.android.ui.reports.ReportsActions
import eu.llembas.android.ui.reports.ReportsContent
import eu.llembas.android.ui.reports.ReportsState
import eu.llembas.android.ui.scheduled.RunContent
import eu.llembas.android.ui.scheduled.ScheduleContent
import eu.llembas.android.ui.scheduled.ScheduleEditContent
import eu.llembas.android.ui.scheduled.ScheduledContent
import eu.llembas.android.ui.scheduled.SchedulingModelsContent
import eu.llembas.android.ui.settings.AssistantModelChoices
import eu.llembas.android.ui.settings.LanguageChoices
import eu.llembas.android.ui.settings.NotificationSummaryGroup
import eu.llembas.android.ui.settings.SettingsActions
@@ -88,6 +93,8 @@ private object NoActivityActions : ActivityActions
private object NoSettingsActions : SettingsActions
private object NoReportsActions : ReportsActions
private object NoAssistActions : AssistActions
private object NoShareActions : ShareActions
@@ -137,7 +144,7 @@ class ScreenShots {
drawerState = rememberDrawerState(DrawerValue.Open),
drawerContent = {
DrawerContent(
Fakes.chats,
Fakes.chats.copy(reports = true, unreadReports = 2),
current = "c1",
account = "Home · frodo@example.org",
actions = NoDrawerActions,
@@ -211,6 +218,9 @@ class ScreenShots {
shoot("08-wake-listening", Phone.Scroll) { groups(Fakes.settings) }
shoot("08-wake-failed", Phone.Scroll) { groups(Fakes.settingsWakeFailed) }
shoot("08-wake-failed", Phone.SmallScroll, fontScale = 1.5f) { groups(Fakes.settingsWakeFailed) }
// The assistant not connected right now, and the last wake that found it so.
shoot("08-wake-unbound", Phone.Scroll) { groups(Fakes.settingsWakeUnbound) }
shoot("08-wake-unbound", Phone.SmallScroll, fontScale = 1.5f) { groups(Fakes.settingsWakeUnbound) }
shoot("08-wake-tested", Phone.Scroll) { groups(Fakes.settingsWakeTested) }
shoot("08-wake-tested", Phone.SmallScroll, fontScale = 1.5f) { groups(Fakes.settingsWakeTested) }
}
@@ -224,6 +234,14 @@ class ScreenShots {
shoot("08-wake-sensitivity", Phone.Small, fontScale = 1.5f) { SheetOver { WakeChoices(WakeChoice.Sensitivity, Fakes.settings.prefs, onPick = {}) } }
}
@Test
fun assistantModel() {
// "Instance default" chosen, then one of the instance's models.
shoot("08-assistant-model", Phone.Scroll) { SheetOver { AssistantModelChoices(Fakes.settings, onPick = {}) } }
val picked = Fakes.settings.copy(prefs = Fakes.settings.prefs.copy(assistantModel = Fakes.models.last().id))
shoot("08-assistant-model-chosen", Phone.Small, fontScale = 1.5f) { SheetOver { AssistantModelChoices(picked, onPick = {}) } }
}
@Test
fun language() {
shoot("17-language", Phone.Scroll) { SheetOver { LanguageChoices(Fakes.settings.prefs, onPick = {}) } }
@@ -247,7 +265,26 @@ class ScreenShots {
}
@Test
fun scheduleEdit() = shoot("11-schedule-edit") { ScheduleEditContent(Fakes.editing, editing = false) }
fun scheduleEdit() {
shoot("11-schedule-edit", Phone.Scroll) { ScheduleEditContent(Fakes.editing, editing = false) }
// "Notify when": the three choices, and "When…" with the person's words.
shoot("11-schedule-edit-notify", Phone.Scroll) { ScheduleEditContent(Fakes.editingNotify, editing = true) }
shoot("11-schedule-edit-notify", Phone.SmallScroll, fontScale = 1.5f) { ScheduleEditContent(Fakes.editingNotify, editing = true) }
}
@Test
fun reports() {
shoot("40-reports") { ReportsContent(Fakes.reports, NoReportsActions) }
shoot("40-reports", Phone.Small, fontScale = 1.5f) { ReportsContent(Fakes.reports, NoReportsActions) }
shoot("40-reports-none") { ReportsContent(ReportsState(), NoReportsActions) }
shoot("40-reports-older-instance") { ReportsContent(ReportsState(unsupported = true), NoReportsActions) }
// One report as a page; the page in it is a card, not a page and not its source.
shoot("41-report", Phone.Scroll) { ReportContent(Fakes.report) }
shoot("41-report", Phone.Small, fontScale = 1.5f) { ReportContent(Fakes.report) }
// A task's runs: the note, the way to a report, an unchanged look.
shoot("42-schedule-runs-reports", Phone.Scroll) { ScheduleContent(Fakes.scheduleWithReports) }
shoot("42-schedule-runs-reports", Phone.SmallScroll, fontScale = 1.5f) { ScheduleContent(Fakes.scheduleWithReports) }
}
@Test
fun scheduleRun() {
@@ -298,6 +335,16 @@ class ScreenShots {
shoot("20-assistant-answered", content = over(Fakes.assistAnswered, false))
shoot("21-assistant-writing", content = over(Fakes.assistWriting, false))
shoot("22-assistant-locked", content = over(Fakes.assistOpened, true))
// Over the lock screen after the wake word: listening, then the question waiting for the
// unlock; and a conversation that was up when the phone locked is not shown.
shoot("22-assistant-locked-listening", content = over(Fakes.assistListening, true))
val waiting = Fakes.assistOpened.copy(waiting = "How far is it to the next town?")
shoot("22-assistant-locked-waiting", content = over(waiting, true))
shoot("22-assistant-locked-waiting", Phone.Small, fontScale = 1.5f, content = over(waiting, true))
shoot("22-assistant-locked-answered", content = over(Fakes.assistAnswered, true))
// Heard where the instance writes speech down: it waits as a recording, with no words.
shoot("22-assistant-locked-recording", content = over(Fakes.assistOpened.copy(waitingRecording = true), true))
shoot("22-assistant-locked-recording", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistOpened.copy(waitingRecording = true), true))
shoot("23-assistant-offline", Phone.Small, content = over(Fakes.assistOffline, false))
shoot("24-assistant-conversation", content = over(Fakes.assistConversation, false))
shoot("24-assistant-conversation", Phone.Small, fontScale = 1.5f, content = over(Fakes.assistConversation, false))
+9 -1
View File
@@ -24,5 +24,13 @@
"cap": 32
},
"created_at": "2026-01-02T03:04:05+00:00",
"updated_at": "2026-01-02T03:04:05+00:00"
"updated_at": "2026-01-02T03:04:05+00:00",
"controls": [
"rename",
"delete",
"archive",
"pin",
"folder"
],
"report": null
}
+9 -1
View File
@@ -27,5 +27,13 @@
"cap": 32
},
"created_at": "2026-01-02T03:04:05+00:00",
"updated_at": "2026-01-02T03:04:05+00:00"
"updated_at": "2026-01-02T03:04:05+00:00",
"controls": [
"rename",
"delete",
"archive",
"pin",
"folder"
],
"report": null
}
+4
View File
@@ -0,0 +1,4 @@
{
"offered": true,
"on": false
}
+32
View File
@@ -0,0 +1,32 @@
{
"id": "chat9",
"kind": "report",
"title": "Two cakes are unwrapped",
"model": "qwen",
"folder_id": null,
"pinned": false,
"archived": false,
"temporary": false,
"unread": true,
"running": false,
"mode": "",
"effort": "low",
"device": null,
"device_session_id": null,
"parent_chat_id": null,
"agents": {
"min": 1,
"max": 4
},
"subagents": null,
"created_at": "2026-01-02T03:04:05+00:00",
"updated_at": "2026-01-02T03:04:05+00:00",
"controls": [
"rename",
"delete"
],
"report": {
"id": "rep1",
"title": "Two cakes are unwrapped"
}
}
+9 -1
View File
@@ -22,7 +22,15 @@
},
"subagents": null,
"created_at": "2026-01-02T03:04:05+00:00",
"updated_at": "2026-01-02T03:04:05+00:00"
"updated_at": "2026-01-02T03:04:05+00:00",
"controls": [
"rename",
"delete",
"archive",
"pin",
"folder"
],
"report": null
}
],
"more": false
+17
View File
@@ -0,0 +1,17 @@
{
"unread": 1,
"newest": {
"id": "rep1",
"title": "Two cakes are unwrapped",
"summary": "Two of the twelve cakes have lost their leaves.",
"importance": "high",
"schedule": {
"id": "sched1",
"title": "Waybread check"
},
"schedule_title": "Waybread check",
"created": "2026-01-02T03:04:05+00:00",
"unread": true
},
"latest_created": "2026-01-02T03:04:05+00:00"
}
+15 -11
View File
@@ -1,5 +1,5 @@
{
"version": "8bee85746004dc19",
"version": "d55e588277f6c90b",
"schedules": [
{
"id": "sched1",
@@ -32,7 +32,10 @@
],
"target": "chat",
"mode": "fresh",
"notify": "matters",
"notify": "when",
"notify_when": "",
"notify_default": "something needs my attention",
"save_file": false,
"catch_up": "one",
"grace_minutes": null,
"model": "qwen",
@@ -81,25 +84,26 @@
"chat_id": "chat1",
"message_id": "msg2",
"report_path": null,
"report": "rep1",
"note": "Filed a report: two cakes are unwrapped.",
"preview": "All the waybread is wrapped.",
"error": null,
"notified": true,
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "Waybread check",
"body": "Finished"
"title": "New report",
"body": ""
},
"actions": [
"open",
"run_again"
"open"
],
"labels": {
"open": "Open",
"run_again": "Run again"
"open": "Open"
},
"ask": ""
"ask": "",
"importance": "high"
},
"watch": null
},
+3 -3
View File
@@ -1,5 +1,5 @@
{
"ref": "v2.0.0-beta.11",
"commit": "cd9795363195e30232c70409d1cb21e100f94edc",
"sha256": "da264d17c7c4a11ef5774482df5e1eaab9c608078b8c2a151ab026d3d14a7298"
"ref": "v2.0.0-beta.13",
"commit": "3191ecf5fabb7583dd73826f54f7b37f6dae338c",
"sha256": "fcdfaca53bec6edefc22ae0d600bf284c3fe3c8880ed959ae9db8d539fed5c31"
}
+6 -3
View File
@@ -22,7 +22,8 @@
"subagents": {
"offered": true,
"named_only": false
}
},
"html_pages": false
},
{
"id": "gpt-oss",
@@ -49,7 +50,8 @@
"subagents": {
"offered": true,
"named_only": true
}
},
"html_pages": false
},
{
"id": "vision-small",
@@ -70,7 +72,8 @@
"subagents": {
"offered": false,
"named_only": false
}
},
"html_pages": false
}
],
"subagents_cap": 32
+6 -3
View File
@@ -22,7 +22,8 @@
"subagents": {
"offered": true,
"named_only": false
}
},
"html_pages": false
},
{
"id": "gpt-oss",
@@ -49,7 +50,8 @@
"subagents": {
"offered": true,
"named_only": false
}
},
"html_pages": false
},
{
"id": "vision-small",
@@ -70,7 +72,8 @@
"subagents": {
"offered": true,
"named_only": false
}
},
"html_pages": false
}
],
"subagents_cap": 32,
+6
View File
@@ -0,0 +1,6 @@
{
"title": "Cakes",
"digest": "526b3a6b58f09769d9f81f628942cc7f",
"html": "<!doctype html>\n<meta charset=\"utf-8\"><title>Cakes</title><style>:root{--page-bg:#101418;--page-ink:#E2E8EC;color-scheme:light dark}html{background:var(--page-bg,Canvas);color:var(--page-ink,CanvasText);font-family:system-ui,sans-serif}</style>\n<p>10 wrapped, 2 not</p>",
"policy": "sandbox; default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src 'none'; connect-src 'none'; worker-src 'none'; child-src 'none'; frame-src 'none'; object-src 'none'; manifest-src 'none'; form-action 'none'; base-uri 'none'; webrtc 'block'; frame-ancestors 'self'"
}
+29
View File
@@ -0,0 +1,29 @@
{
"report_id": "rep1",
"schedule_id": "sched1",
"run_id": "run1",
"visibility": "private",
"actions": [
"open"
],
"notification": {
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "New report",
"body": ""
},
"actions": [
"open"
],
"labels": {
"open": "Open"
},
"ask": "",
"importance": "high"
},
"title": "LLeMbas",
"body": "New report",
"url": "/reports/rep1",
"kind": "report"
}
-34
View File
@@ -1,34 +0,0 @@
{
"schedule_id": "sched1",
"run_id": "run1",
"chat_id": "chat1",
"status": "ok",
"visibility": "private",
"actions": [
"open",
"run_again"
],
"ask": "",
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"public": {
"title": "Waybread check",
"body": "Finished"
},
"actions": [
"open",
"run_again"
],
"labels": {
"open": "Open",
"run_again": "Run again"
},
"ask": ""
},
"pause_label": "Pause",
"title": "LLeMbas",
"body": "A scheduled task has finished.",
"url": "/scheduled/sched1?run=run1",
"kind": "schedule"
}
+25
View File
@@ -0,0 +1,25 @@
{
"report": {
"id": "rep1",
"title": "Two cakes are unwrapped",
"summary": "Two of the twelve cakes have lost their leaves.",
"importance": "high",
"schedule": {
"id": "sched1",
"title": "Waybread check"
},
"schedule_title": "Waybread check",
"created": "2026-01-02T03:04:05+00:00",
"unread": true,
"body": "## What\n\nTwo of the twelve cakes have lost their leaves.\n\n```html-view Cakes\n<p>10 wrapped, 2 not</p>\n```\n",
"text": "## What\n\nTwo of the twelve cakes have lost their leaves.\n\n[page: Cakes]\n",
"pages": [
{
"title": "Cakes",
"digest": "526b3a6b58f09769d9f81f628942cc7f"
}
],
"model": "gpt-oss",
"chat": "chat9"
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"report": {
"id": "rep1",
"title": "Two cakes are unwrapped",
"summary": "Two of the twelve cakes have lost their leaves.",
"importance": "high",
"schedule": null,
"schedule_title": "Waybread check",
"created": "2026-01-02T03:04:05+00:00",
"unread": true,
"body": "## What\n\nTwo of the twelve cakes have lost their leaves.\n\n```html-view Cakes\n<p>10 wrapped, 2 not</p>\n```\n",
"text": "## What\n\nTwo of the twelve cakes have lost their leaves.\n\n[page: Cakes]\n",
"pages": [
{
"title": "Cakes",
"digest": "526b3a6b58f09769d9f81f628942cc7f"
}
],
"model": "gpt-oss",
"chat": "chat9"
}
}
+3
View File
@@ -0,0 +1,3 @@
{
"chat": "chat9"
}
+18
View File
@@ -0,0 +1,18 @@
{
"reports": [
{
"id": "rep1",
"title": "Two cakes are unwrapped",
"summary": "Two of the twelve cakes have lost their leaves.",
"importance": "high",
"schedule": {
"id": "sched1",
"title": "Waybread check"
},
"schedule_title": "Waybread check",
"created": "2026-01-02T03:04:05+00:00",
"unread": true
}
],
"unread": 1
}
+14 -10
View File
@@ -30,7 +30,10 @@
],
"target": "chat",
"mode": "fresh",
"notify": "matters",
"notify": "when",
"notify_when": "",
"notify_default": "something needs my attention",
"save_file": false,
"catch_up": "one",
"grace_minutes": null,
"model": "qwen",
@@ -79,25 +82,26 @@
"chat_id": "chat1",
"message_id": "msg2",
"report_path": null,
"report": "rep1",
"note": "Filed a report: two cakes are unwrapped.",
"preview": "All the waybread is wrapped.",
"error": null,
"notified": true,
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "Waybread check",
"body": "Finished"
"title": "New report",
"body": ""
},
"actions": [
"open",
"run_again"
"open"
],
"labels": {
"open": "Open",
"run_again": "Run again"
"open": "Open"
},
"ask": ""
"ask": "",
"importance": "high"
},
"watch": null
},
+2
View File
@@ -26,6 +26,7 @@
"offered": false,
"named_only": false
},
"html_pages": false,
"free": false,
"busy": "it is answering someone",
"chosen": true
@@ -53,6 +54,7 @@
"offered": false,
"named_only": false
},
"html_pages": false,
"free": true,
"busy": null,
"chosen": false
+6 -1
View File
@@ -16,7 +16,10 @@
"next_runs": [],
"target": "chat",
"mode": "fresh",
"notify": "matters",
"notify": "when",
"notify_when": "",
"notify_default": "something needs my attention",
"save_file": false,
"catch_up": "one",
"grace_minutes": null,
"model": null,
@@ -83,6 +86,8 @@
"chat_id": null,
"message_id": null,
"report_path": null,
"report": null,
"note": "",
"preview": "",
"error": {
"class": "device_away",
+10 -9
View File
@@ -26,25 +26,26 @@
"chat_id": "chat1",
"message_id": "msg2",
"report_path": null,
"report": "rep1",
"note": "Filed a report: two cakes are unwrapped.",
"preview": "All the waybread is wrapped.",
"error": null,
"notified": true,
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "Waybread check",
"body": "Finished"
"title": "New report",
"body": ""
},
"actions": [
"open",
"run_again"
"open"
],
"labels": {
"open": "Open",
"run_again": "Run again"
"open": "Open"
},
"ask": ""
"ask": "",
"importance": "high"
},
"watch": null
},
+12 -9
View File
@@ -32,6 +32,8 @@
"chat_id": null,
"message_id": null,
"report_path": null,
"report": null,
"note": "",
"preview": "",
"error": {
"class": "no_model",
@@ -68,25 +70,26 @@
"chat_id": "chat1",
"message_id": "msg2",
"report_path": null,
"report": "rep1",
"note": "Filed a report: two cakes are unwrapped.",
"preview": "All the waybread is wrapped.",
"error": null,
"notified": true,
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "Waybread check",
"body": "Finished"
"title": "New report",
"body": ""
},
"actions": [
"open",
"run_again"
"open"
],
"labels": {
"open": "Open",
"run_again": "Run again"
"open": "Open"
},
"ask": ""
"ask": "",
"importance": "high"
},
"watch": null
}
+6 -1
View File
@@ -16,7 +16,10 @@
"next_runs": [],
"target": "chat",
"mode": "fresh",
"notify": "matters",
"notify": "when",
"notify_when": "",
"notify_default": "something needs my attention",
"save_file": false,
"catch_up": "one",
"grace_minutes": null,
"model": null,
@@ -70,6 +73,8 @@
"chat_id": null,
"message_id": null,
"report_path": null,
"report": null,
"note": "",
"preview": "",
"error": null,
"notified": false,
+14 -10
View File
@@ -31,7 +31,10 @@
],
"target": "chat",
"mode": "fresh",
"notify": "matters",
"notify": "when",
"notify_when": "",
"notify_default": "something needs my attention",
"save_file": false,
"catch_up": "one",
"grace_minutes": null,
"model": "qwen",
@@ -80,25 +83,26 @@
"chat_id": "chat1",
"message_id": "msg2",
"report_path": null,
"report": "rep1",
"note": "Filed a report: two cakes are unwrapped.",
"preview": "All the waybread is wrapped.",
"error": null,
"notified": true,
"notification": {
"title": "Waybread check",
"body": "All the waybread is wrapped.",
"title": "Two cakes are unwrapped",
"body": "Two of the twelve cakes have lost their leaves.",
"public": {
"title": "Waybread check",
"body": "Finished"
"title": "New report",
"body": ""
},
"actions": [
"open",
"run_again"
"open"
],
"labels": {
"open": "Open",
"run_again": "Run again"
"open": "Open"
},
"ask": ""
"ask": "",
"importance": "high"
},
"watch": null
},
+13
View File
@@ -0,0 +1,13 @@
{
"index": 2,
"kind": "text",
"open": false,
"markdown": "Two are unwrapped.\n\n```html-view Cakes\n<p>10 wrapped, 2 not</p>\n```\n",
"pages": [
{
"title": "Cakes",
"digest": "526b3a6b58f09769d9f81f628942cc7f"
}
],
"text": "Two are unwrapped.\n\n[page: Cakes]\n"
}
+64
View File
@@ -261,6 +261,35 @@ STRINGS: dict[str, str] = {
"channel_scheduled_failures": "Scheduled failures",
"scheduled_result_public": "A scheduled task has a result.",
"scheduled_failed_public": "A scheduled task failed.",
"page_note": "This answer has a page: %1$s",
"page_where": "Open it on the web or in LLeMbas Desktop to see it.",
"page_untitled": "Page",
"reports": "Reports",
"report": "Report",
"reports_none": "No reports yet. A scheduled task files one when it has something to tell you.",
"reports_unsupported": "This instance runs a LLeMbas that has no Reports yet.",
"report_untitled": "Untitled report",
"report_delete_title": "Delete this report?",
"report_delete_line": "“%1$s” is deleted for good, and the conversation about it with it.",
"report_mark_read": "Mark read",
"report_important": "Important",
"report_share": "Share",
"report_reply": "Reply",
"report_chat_title": "Report: %1$s",
"notify_when": "Notify when",
"notify_every_run": "Every run",
"notify_every_run_line": "The model writes a report every time, also when nothing was found.",
"notify_when_option": "When…",
"notify_when_line": "The model writes a report only when this holds.",
"notify_when_label": "When what?",
"notify_when_default": "something needs my attention",
"notify_never_option": "Never",
"notify_never_line": "No reports: runs are kept in the task's history only.",
"notify_when_words": "Tells you when: %1$s",
"run_open_report": "Open its report",
"channel_reports": "Reports",
"channel_reports_high": "Important reports",
"report_new_public": "New report",
"schedule_run_again": "Run again",
# Cards
"card_approval": "Allow this?",
@@ -369,6 +398,9 @@ STRINGS: dict[str, str] = {
"settings_assistant": "Assistant",
"assistant_explained": "Make LLeMbas the phone's digital assistant: choose it under Default apps › Digital assistant app. Then holding the power button, the assist gesture or the lock screen's shortcut opens it over whatever is on screen.",
"assistant_open_settings": "Open the assistant settings",
"assistant_model": "Assistant model",
"assistant_model_default": "Instance default",
"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.",
"assistant_samsung": "On Samsung phones: Settings › Advanced features › Side button › Press and hold › Digital assistant.",
"assistant_temporary": "Assistant chats are temporary",
"assistant_read_aloud": "Read the answer aloud when asked by voice",
@@ -419,12 +451,19 @@ STRINGS: dict[str, str] = {
"assist_say_it": "Say it, then pause",
"assist_type": "Type instead",
"assist_writing_down": "Writing down what you said…",
"assist_unlock_to_send": "Unlock to send",
"assist_question_heard": "Question heard",
"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.",
"assist_locked_line": "The phone is locked. Nothing is sent, and no answer is shown, until you unlock it.",
"assist_conversation": "In conversation",
"assist_conversation_line": "I listen again after each answer. Say “stop” to end.",
"assist_conversation_end": "End",
"assist_stop_words": "stop|that's all|that is all|that's it|goodbye|bye|enough|end|thank you that's all|cancel",
"assistant_conversation": "Keep a spoken conversation going",
"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.",
"experimental": "Experimental",
"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.",
"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.",
"assist_wake_word_hint": "No wake word unless you want one: Settings › Assistant › Wake word turns on LLeMbas's own, on this phone.",
"channel_wake": "Wake word",
"wake_word": "Wake word",
@@ -475,6 +514,31 @@ STRINGS: dict[str, str] = {
"wake_heard_line": "LLeMbas can open by itself over other apps only as the phone's digital assistant app.",
"wake_not_assistant": "LLeMbas is not the digital assistant app",
"wake_not_assistant_line": "So the wake word cannot open the assistant over other apps: you get a notification to tap. To open by voice anywhere, tap here and choose LLeMbas as the digital assistant app.",
"wake_last": "Last wake",
"wake_last_none": "It has not heard the phrase yet.",
"wake_out_opened": "Opened the assistant.",
"wake_out_no_sheet": "Asked Android to open the assistant; it did not refuse, but no sheet came.",
"wake_out_not_connected": "Android had not connected LLeMbas as the assistant, so it could not open the sheet.",
"wake_out_refused": "Android refused to open the assistant: %1$s",
"wake_out_activity": "Opened it as a screen of the app instead.",
"wake_out_notification": "Posted a notification to tap instead.",
"wake_out_tested": "Heard in a test: nothing was to open.",
"wake_role_held": "LLeMbas was the digital assistant app.",
"wake_role_not_held": "LLeMbas was not the digital assistant app.",
"wake_link_never": "Android had not connected the assistant since the app started.",
"wake_link_ready": "Android had connected the assistant at %1$s.",
"wake_link_shutdown": "Android had disconnected it at %1$s.",
"wake_link_later": "Android connected it again at %1$s.",
"wake_sheet_ms": "The sheet was up after %1$s ms.",
"wake_no_recognizers": "This phone has no voice recognisers, so Android runs no voice assistant service on it.",
"wake_not_active": "LLeMbas was chosen as the digital assistant app, but Android was not using it as its voice assistant.",
"wake_waited": "Waited a moment for Android to connect it.",
"wake_show_failed": "Android said it could not show the assistant's sheet.",
"wake_assistant_inactive": "Android is not using LLeMbas as its voice assistant right now",
"wake_assistant_inactive_line": "Choose LLeMbas as the digital assistant app again: tap here, pick another app, then LLeMbas. Until then the long press opens it as an ordinary screen, and the wake word can only send a notification.",
"wake_assistant_unbound": "LLeMbas is the assistant, but Android has not connected it right now",
"wake_assistant_unbound_line": "Until it does, the wake word cannot open the sheet by itself. Tap for the system's assistant setting: choosing another app and then LLeMbas again connects it.",
"wake_heard_could_not": "Could not open by itself — tap to ask",
"wake_resume": "Listen for the wake word again",
"wake_resume_line": "The phone restarted. Tap to start listening again.",
"assist_notifications": "Summarise my notifications",
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -1,9 +1,9 @@
{
"tag": "v2.0.0-beta.11",
"commit": "cd9795363195e30232c70409d1cb21e100f94edc",
"sha256": "12e78f4f7051a9f7cd5a75800aa896b445f2385d11cc8d81f5631939e1ad2e11",
"tag": "v2.0.0-beta.13",
"commit": "3191ecf5fabb7583dd73826f54f7b37f6dae338c",
"sha256": "75803136d7e5c2b2173639c6e219b2427c3314c0520bdb70c26f6b85dacaf9ba",
"res": {
"values": "a33a4ac9ec2704127dc7af60c7051b563037299ac46a37f06a458e91fdb0a134",
"values-night": "ef6fa755a06ee9e36af479ba262afea489693918df65c2a854abbfd7ee7b2a1e"
"values": "abbab21cbfec763d7f4dc40ef111ade8c6bff88aa59d0c1405ad0c2eb5c74076",
"values-night": "91d16df6047a101e0526f6ee96e19a16b2ed80fe7ef3e2fd177b6f1e955434c1"
}
}