Compare commits

..
Author SHA1 Message Date
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
HomerandClaude Fable 5.2 118b2aa764 LLeMbas for Android 1.0.0-beta.8: pinned to LLeMbas 2.0.0-beta.11
Release / release (push) Canceled after 0s
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:56:05 +00:00
HomerandClaude Fable 5.2 694e7f46d7 Contract at server dev 9ab0818: spec 3.7.0 from the server -- end, ms, always, the builds
CI / check (push) Canceled after 0s
- Pinned: 75 files, with the spec's display.json (DisplayTest runs its
  duration and end cases) and progress.json's budget stop.
- Not additive: a call's chips no longer carry "exit 0", and an edit's are
  one "+N -M" (the app draws chips only, so nothing is said twice);
  block.title follows the spec's key order.
- A message's `end {phase, reason, text}` is what a stopped or failed reply
  is drawn from, so a reloaded one says "Stopped: by you" too; the app
  writes the line in its own language from the phase and the reason.
- A call's time is block.duration (the server's), else made from `ms`;
  its state is block.state; a call without a title shows block.label.
- "Always allow" only when every item of the approval has `always`.
- The notifications build's updater takes its file from latest.json, else
  from GET /apps' `notifications {url, sha256}` of the same version.
- ApiClient.mentions and attachFrom with their models and fixtures; the
  composer does not use them yet.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 12:33:47 +00:00
HomerandClaude Fable 5.2 d30b74e1a4 Wake word: Stop's start id counts too, so the service still ends after it
CI / check (push) Canceled after 0s
The service stops itself by the newest start id it was given; without
Stop's own id that call would have been ignored after a tap on Stop.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:40:22 +00:00
HomerandClaude Fable 5.2 5fcc158763 Wake word, from the review: a heard word always shows, holds end, stop and retry
CI / check (push) Canceled after 0s
1. Heard, but not the assistant and not on screen: Android blocks the
   activity start silently and runCatching called it a success, so nothing
   opened and nothing was posted. The opening is decided from what Android
   allows (wakeOpening: session, activity while an activity of the app is
   started, else a notification); "Heard you. Tap to ask." goes on a channel
   of its own (high importance, fixed words, times out after a minute) and
   the sheet cancels it. Settings says that only the digital assistant app
   opens by voice over other apps, with a row to that system setting.
2. The hold after the word is apart from the sheets' count and ends on a
   process scope in a finally; a starting service clears it.
3. A tap on the state in Settings retries now (WakeStatus.retryNow ->
   WakeListener.retryNow) and restarts the back-off; thirty seconds of
   samples taken in also resets the count of failures.
4. State writes carry the instance's token (WakeStatus.begin): an older
   instance's last "off" no longer overwrites a newer one. Engine.create is
   synchronized and writes the keywords to a file of its own.
5. numTrailingBlanks = 1 means more than one blank frame after the phrase
   (about 80 ms): the comment is corrected, and Settings and the test row
   say to pause after the phrase.
6. Stop no longer calls stopService or stopSelf() under a possible pending
   foreground start: the setting goes off and the loop ends the service with
   stopSelf(lastStartId); a start that arrives after the loop ended begins
   it again.
7. The "tap to listen again" notification is cancelled when the service
   starts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:39:34 +00:00
HomerandClaude Fable 5.2 649cb526de Assistant: a new chat's name is fetched after the answer, for a bounded while
The sheet follows the reply's stream to done only, so it never saw the
title frame. When done says the name is pending, the chat's name is asked
for every 4 s for at most 20 s in the background (never delaying speech,
never holding the stream open) and kept as the name the sheet offers the
chat under next time.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:38:47 +00:00
HomerandClaude Fable 5.2 3e15900521 A call's duration that rounds to sixty seconds is "1m 00s", never "60.0s"
Tenths, rounded half up, decide the form (59.96 s is a minute).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:38:47 +00:00
HomerandClaude Fable 5.2 0437f802a4 Screenshots: the wake word's group and notification summaries on their own
CI / check (push) Canceled after 0s
The settings page is longer than a shot, so its wake-word rows were cut off.
The two groups are drawn alone: listening, failed with its reason, and a
test that heard the phrase in a standard build.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:15:15 +00:00
HomerandClaude Fable 5.2 e35bf3004c Contract at server dev 5044168: done is the end of a reply, the chat's name follows
CI / check (push) Canceled after 0s
The server now sends `done` as soon as the reply is saved and names a new
chat afterwards: `done.chat.title_pending`, then one `title` frame before
`close` (up to the naming's time limit).

- The chat screen finishes the reply at `done` (the row replaced, nothing
  live, a queued prompt's reply followed at once) and keeps the stream only
  for the `title` frame, which renames the chat. It used to wait for
  `close`, which with this server would have left a first reply undrawn for
  the seconds the naming takes.
- The assistant's sheet follows the stream to `done` only, so a spoken
  answer is read aloud without waiting for the name.
- Fixtures: event_done (title_pending), event_done_title_pending,
  event_title. Tokens and strings are unchanged at this ref.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:06:37 +00:00
HomerandClaude Fable 5.2 a30075c8f3 Display per harness spec 3.7.0: the end line, durations, locale numbers, the cards' actions
CI / check (push) Canceled after 0s
- A reply that was stopped or failed keeps the progress text at its end
  (display.md section 4): "Stopped: by you", "Failed: ...". message.stopped
  was never drawn, and a failure showed the raw error. The reason comes from
  the stream's last status frame and stays with the finished row; a stored
  row gives "Stopped" or "Failed: <first line of its error>".
- A finished tool call shows its duration (0.4s, 1m 05s, 2h 03m) from the
  call's `ms`, where the server sends it; none while running or when denied.
- Counts in the progress line are in the phone's locale format (Locale.ROOT
  is the spec's plain format, which the conformance cases use); a cut `what`
  ends in an ellipsis, counted in code points; the clock is joined with the
  shared progress_line separator.
- Approval card: Allow once / Always allow / Deny / Deny, and say why. Plan
  card: Approve, continue in Edit / in Manual, and Revise.
- fetch-contract.py pins the spec's display.json as harness_display.json
  once the server's copy of the spec has it; DisplayTest then runs its
  duration and end cases.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:03:04 +00:00
HomerandClaude Fable 5.2 f2a2acf996 Three APKs: the notification listener leaves the standard builds; releases drop x86_64
CI / check (push) Canceled after 0s
Google Play Protect blocked installing beta.7, most likely for the
notification listener (notification summaries).

- A second flavour dimension, `reading`: `standard` declares no listener and
  no permission of it; `notifications` is the full build plus the listener,
  with the same application id and key. Variants: fullStandard,
  fullNotifications, fdroidStandard (no F-Droid build with the listener).
  The listener class and its manifest entry live in src/notifications only.
- Settings in a standard build says where notification summaries went and
  why. The self-updater installs only its own kind: a notifications build
  takes latest.json's optional `notifications {url, sha256}` or nothing.
- Release builds carry arm64-v8a and armeabi-v7a only; debug keeps x86_64
  for the emulator. The engine's unused C and C++ API libraries are left out.
- scripts/check-apk.sh checks the built files (listener only where it may
  be, model stored, no x86 in a release); CI runs it on the three debug APKs
  and on an unsigned release build, release.yml on what it publishes.
- release.yml publishes llembas-android-<version>.apk, -notifications.apk
  and -fdroid.apk with SHA256SUMS.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:58:07 +00:00
HomerandClaude Fable 5.2 6a05f56e7c Tests: the wake-word service as Android starts it
CI / check (push) Canceled after 0s
A start never posts a phrase it is not listening for (the default phrase on
every app open was the bug), and without the microphone permission the
service is not started and the state says why. With the earlier commits'
tests this covers state -> notification text (Robolectric), the engine
missing or failing, the microphone failing, the saved-phrase migration and
the generated table against tokens.txt.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:53:01 +00:00
HomerandClaude Fable 5.2 e1d99f3f0a Settings: "Test the wake word" -- ten seconds of live state and "Heard it"
CI / check (push) Canceled after 0s
A heard phrase during the test is counted instead of opening the assistant.
The test is a deadline in WakeStatus, not a switch, so one that nobody ends
cannot leave the wake word deaf. Screenshot tests: the wake word's rows
(listening, failed with its reason, tested) and the greeting, name and
sensitivity sheets.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:52:03 +00:00
HomerandClaude Fable 5.2 3046ad154a Wake phrases the model can hear: greeting x name, generated pieces, sensitivity
CI / check (push) Canceled after 0s
"Hey Lembas" could not work well: Lembas is not a word the model knows.

- The phrase is a greeting (Hey, OK, Hello) and a name (Assistant, Computer,
  Google, and ten ordinary names); the default is Hey Assistant and an old
  saved id reads as it.
- Token pieces are generated, not hand-written: fetch-wakeword.py also takes
  the model's bpe.model from the same pinned archive, gen-wake-phrases.py
  encodes every word with it into wake/WakeWords.kt, CI checks the committed
  table against the tokenizer, and WakeWordsTest checks every piece against
  tokens.txt. "OK" is spelled as the model's speech wrote it, OKAY.
  Elizabeth and Benjamin are dropped (four or more single-letter pieces).
- Each keyword line carries a boosting score and a trigger threshold
  (sherpa-onnx's ":boost #threshold"), chosen by a Sensitivity setting:
  Low 1.0/0.35, Normal 1.5/0.25, High 2.0/0.15; short phrases 0.05 stricter.
  numTrailingBlanks is the engine's own 1.
- Settings says the phrase is English whatever the app's language is, and
  that a Google device nearby answers to Google too.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:49:47 +00:00
HomerandClaude Fable 5.2 374574b9ce Wake word: the engine loads, and its state is one truth that is shown
CI / check (push) Canceled after 0s
The model was read from the APK with AssetManager.openFd, which throws for a
compressed asset; the assets were compressed, runCatching swallowed it, and
the engine never loaded on any phone.

- The model is copied out by stream, keyed by a version file the fetch
  script writes (a hash of the pinned model); onnx assets are stored.
- WakeState (Off, Starting, Listening, Paused, Failed) in one StateFlow that
  the service, its notification and Settings read. onStartCommand no longer
  posts the default phrase; the notification is written from the state only.
- WakeListener holds the loop apart from Android: an engine that does not
  load and a microphone that does not start or stops are Failed states with
  a reason, logged, retried with back-off; a new phrase cancels and joins the
  old loop before the engine is released.
- A keywords line is checked against tokens.txt before the engine sees it
  (the engine exits the process on an unknown piece).
- The service is not started without the microphone permission, and the app
  looks again each time it comes to the screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:44:49 +00:00
HomerandClaude Opus 5.5 2d38ccd321 LLeMbas for Android 1.0.0-beta.7: pinned to LLeMbas 2.0.0-beta.10
CI / check (push) Canceled after 0s
Release / release (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 17:47:11 +00:00
HomerandClaude Opus 5.5 f816919071 Phone actions: the confirm card and the capability (harness spec 3.6.0, server e463621)
CI / check (push) Canceled after 0s
- Contract and strings pinned at server dev e463621 (event_ask_phone.json); tokens unchanged.
- Every message declares client ["phone_actions"] (POST /chats and /chats/{id}/messages).
- CardItem.phone; a phone_action card (chat card sheet, and inline in the assistant's sheet):
  the model's summary, how it will be done, its facts, the map app to use when Settings leaves
  it open, Google Maps' limits said; Cancel answers declined, Do it runs ActionRunner and
  answers {result: {status, message}} -- done or failed with why. Locked: "unlock first".
- Executor on the spec's fields: alarm time HH:MM/days/label, timer, calendar_event
  (start/end local, notes), sms_draft (numbers only; names left to the person), email_draft
  with cc, dial, open_app by name, open_url, media command, torch on, settings_panel,
  automation_intent (Tasker's ACTION_TASK by name with values as local variables, else
  LLeMbas's own AUTOMATION broadcast), navigate (replace_route -> OsmAnd force), add_stop,
  search_nearby (near), stop_navigation. Tool-result reasons in English, for the model.
- Tests: PhoneActionsTest reads the fixture; shots 35-38 phone cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:51:32 +00:00
HomerandClaude Opus 5.5 9906554d09 Phone actions, groundwork: the executor and its settings, before the server's phone_action
CI / check (push) Canceled after 0s
- actions/PhoneActions: standard intents for alarm, timer, calendar insert, SMS and email
  drafts, dial (the dialler, never a call), open URL (http/https only), open app (package or
  launcher label), settings panels, automation broadcasts (never android.* / com.android.*);
  torch via CameraManager; media keys via AudioManager.
- actions/Navigation: Google Maps (google.navigation:, the dir URL with waypoints, geo:0,0?q=;
  no adding to a running route, no stop) and OsmAnd through its intent API only
  (osmand.api:// navigate, navigate_gpx with route points as GPX data, navigate_search,
  stop_navigation; no OsmAnd code, which is GPLv3). add_stop re-plans here -> stop -> destination.
- Optional OsmAnd get_info (Settings switch, after allowing LLeMbas inside OsmAnd): position and
  the running route's destination, through a see-through ResultActivity.
- Settings › Navigation app: whichever is installed (both: ask), Google Maps, OsmAnd, ask.
- Not wired yet: the confirm card and the capability wait for the server's spec 3.6.0 fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:39:11 +00:00
HomerandClaude Opus 5.5 9ca27cee01 Notification summaries on request: NotificationListenerService, off by default
CI / check (push) Canceled after 0s
- LembasNotificationListener keeps nothing; NotificationReader.read takes the notifications up
  now (not ours, not ongoing, not group summaries; newest 40, 600 chars each, 12k in all) and
  returns nothing while the phone is locked.
- The assistant sends them with one question: its "Summarise my notifications" chip, or a
  question naming them (assist_notifications_phrases, per language).
- Settings › Assistant › Notification summaries: the app's switch (off) and, when on, Android's
  notification-access page with whether it is given; a privacy paragraph.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:29:14 +00:00
HomerandClaude Opus 5.5 dc642c62b9 Opt-in wake word: on-device keyword spotting in a microphone foreground service
CI / check (push) Canceled after 0s
- Engine: sherpa-onnx 2.0.1 keyword spotter (Apache-2.0) with the English
  zipformer-gigaspeech-3.3M KWS model (Apache-2.0, int8), fetched hash-pinned by
  scripts/fetch-wakeword.py into app/libs and src/full/assets (gitignored); CI and release run it.
  `full` flavour only (abiFilters arm64-v8a, armeabi-v7a, x86_64); `fdroid` has a stub engine
  and Settings says why. ProGuard keeps com.k2fsa.sherpa.onnx (JNI reads fields by name).
- WakeWordService (foregroundServiceType microphone): persistent notification with Stop; audio
  only to the engine in memory; pauses while the sheet is up (AssistPresence), in battery saver,
  and with the screen off unless Settings says otherwise. On the word: the sheet opens listening
  through LembasAssistService.showSession when LLeMbas is the assistant, else the activity,
  else a "tap to ask" notification.
- No microphone service at boot: WakeBootReceiver posts "tap to listen again"; MainActivity
  restarts a service the phone stopped.
- Settings › Assistant › Wake word: switch (off), four built-in English phrases (BPE-tokenized
  with the model's bpe.model), screen-on only, battery-optimisation page; privacy and cost text.
- The sheet's "no wake word" line now points at the setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:27:51 +00:00
HomerandClaude Opus 5.5 2080f0b67e Share sheet: the last chat is known to the Send row too
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:19:33 +00:00
HomerandClaude Opus 5.5 9592fbeeb4 Syntax highlighting in the file viewer and in a reply's code blocks
CI / check (push) Canceled after 0s
A small scanner of the app's own (ui/Highlight.kt) rather than Prism4j (annotation processor,
unmaintained since 2019): comments, strings, numbers, keywords, types, markup tags/attributes,
YAML/TOML keys and shell/PHP variables for the server's `show` languages plus common fence
aliases. Colours are theme tokens only (accent, success, warning, leaf, ink-faint). The viewer
highlights off the main thread (plain until ready; at once in previews); over 400k chars stays
plain. HighlightTest; shots 33-viewer-{kotlin,python,yaml,typescript}, 34-code-block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:17:39 +00:00
HomerandClaude Opus 5.5 9976186599 Spoken conversation mode: listen again after each spoken answer until stopped
CI / check (push) Canceled after 0s
- A spoken question answered aloud opens a conversation (Settings › Assistant, on by default,
  needs voice replies); after the answer is heard to the end, the sheet listens again.
- Ends on a stop phrase (assist_stop_words, per language; isStopPhrase), End, typing, a stopped
  voice, a card waiting, or nothing said (the existing silence timeout).
- "In conversation" banner with End in the sheet's foot; shot 24-assistant-conversation.
- HeadsetRoute: a Bluetooth headset made the communication device (Android 12+) and its
  microphone preferred by the recorder, so the conversation can stay in the ear.
- Speaker.playToEnd tells a voice heard to the end from one stopped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:16:15 +00:00
HomerandClaude Opus 5.5 d46e7aa548 Widget layout: no double hyphen inside an XML comment (aapt refuses it)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:16:15 +00:00
HomerandClaude Opus 5.5 77e1539e8f Assistant entry points: share sheet (new or last chat), widget, shortcuts, headset button
CI / check (push) Canceled after 0s
- Share: a sheet over the sharing app shows what came in, takes an optional request, and sends
  to a new chat or the last assistant chat; files uploaded first; a new chat becomes the last.
- Home-screen widget (RemoteViews, nothing from the account): Ask, Speak, last chat.
- Launcher shortcuts published from code (the debug build's package differs): Ask, Speak, Last.
- ACTION_VOICE_COMMAND / VOICE_SEARCH_HANDS_FREE open the sheet listening; locked: unlock first.
- Quick Settings tile: STATE_INACTIVE (never greyed out), TOGGLEABLE_TILE false.
- fetch-tokens.py also writes values{,-night}/tokens.xml for what Compose cannot draw.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 16:05:11 +00:00
162 changed files with 14097 additions and 474 deletions

No files matched your search

+38 -7
View File
@@ -37,26 +37,57 @@ jobs:
echo "369ad2b789f95a011f807e1fcb690ccef80bd7cd014fd139e73ae82dcc0baeab ktlint.jar" | sha256sum -c
java -jar ktlint.jar "app/src/**/*.kt" "*.kts" "app/*.kts"
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
- name: Wake-word engine (hash-pinned)
run: python3 scripts/fetch-wakeword.py
# The wake phrases' token pieces are generated from the model's own tokenizer (bpe.model,
# fetched above); the committed table must be what it gives.
- name: Wake phrases match the model's tokenizer
run: |
python3 -m venv "$RUNNER_TEMP/wake"
"$RUNNER_TEMP/wake/bin/pip" install --quiet --require-hashes --only-binary :all: -r scripts/wake-requirements.txt
"$RUNNER_TEMP/wake/bin/python" scripts/gen-wake-phrases.py --check
- uses: gradle/actions/wrapper-validation@v4
- uses: gradle/actions/setup-gradle@v4
- name: Unit tests and both builds
run: ./gradlew --no-daemon testFullDebugUnitTest assembleFullDebug assembleFdroidDebug
- name: Unit tests and the three builds
run: >
./gradlew --no-daemon testFullStandardDebugUnitTest
assembleFullStandardDebug assembleFullNotificationsDebug assembleFdroidStandardDebug
# The files themselves: only the notifications build declares a notification listener, the
# wake-word model is stored uncompressed, the F-Droid build has no engine.
- name: What the APKs declare
run: |
scripts/check-apk.sh app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk standard
scripts/check-apk.sh app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk notifications
scripts/check-apk.sh app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk fdroid
# A release as the release workflow builds it, unsigned: shrunk by R8, and without the
# emulator's x86_64 libraries. Found here rather than at a tag.
- name: The release build's shape
run: |
./gradlew --no-daemon assembleFullStandardRelease
scripts/check-apk.sh "$(ls app/build/outputs/apk/fullStandard/release/*.apk)" standard release
- name: Android lint (report only, for now)
run: ./gradlew --no-daemon lintFullDebug
run: ./gradlew --no-daemon lintFullStandardDebug
continue-on-error: true
# The test build a tester installs (Actions › this run › Artifacts): debug-signed with the
# repository's public test key, so each one installs over the last. `full` is the one to
# use; `fdroid` is the same app without the updater.
# repository's public test key, so each one installs over the last. The plain one is the
# one to use; `-notifications` is the same app with the notification listener (it installs
# over the plain one and back); `-fdroid` is the app without the updater and the wake word.
- name: Name the test builds
run: |
mkdir test-builds
short="${GITHUB_SHA::7}"
cp app/build/outputs/apk/full/debug/app-full-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
cp app/build/outputs/apk/fdroid/debug/app-fdroid-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
cp app/build/outputs/apk/fullStandard/debug/app-full-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short.apk"
cp app/build/outputs/apk/fullNotifications/debug/app-full-notifications-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-notifications.apk"
cp app/build/outputs/apk/fdroidStandard/debug/app-fdroid-standard-debug.apk "test-builds/llembas-android-debug-$GITHUB_RUN_NUMBER-$short-fdroid.apk"
(cd test-builds && sha256sum *.apk > SHA256SUMS)
- uses: actions/upload-artifact@v4
+16 -5
View File
@@ -1,7 +1,8 @@
name: Release
# A signed tag `vX.Y.Z` builds both flavours, signed with the release key from the secrets,
# and publishes them with SHA256SUMS as the GitHub Release. The release notes are the tag's
# A signed tag `vX.Y.Z` builds the three APKs, signed with the release key from the secrets,
# and publishes them with SHA256SUMS as the GitHub Release: the standard one, `-notifications`
# (the same app, id and key, plus the notification listener) and `-fdroid`. The release notes are the tag's
# message. The key never touches the repository: it is written to a temporary file here and
# deleted with the runner.
on:
@@ -43,6 +44,10 @@ jobs:
distribution: temurin
java-version: 17
# The wake-word engine and model for the full build, hash-pinned (never in the repository).
- name: Wake-word engine (hash-pinned)
run: python3 scripts/fetch-wakeword.py
- uses: gradle/actions/wrapper-validation@v4
- uses: gradle/actions/setup-gradle@v4
@@ -57,14 +62,20 @@ jobs:
[ -n "$KEYSTORE_B64" ] || { echo "no release key in the secrets" >&2; exit 1; }
export LEMBAS_KEYSTORE="$RUNNER_TEMP/release.jks"
echo "$KEYSTORE_B64" | base64 -d > "$LEMBAS_KEYSTORE"
./gradlew --no-daemon testFullReleaseUnitTest assembleFullRelease assembleFdroidRelease
./gradlew --no-daemon testFullStandardReleaseUnitTest assembleFullStandardRelease assembleFullNotificationsRelease assembleFdroidStandardRelease
rm -f "$LEMBAS_KEYSTORE"
- name: Name the files and sum them
run: |
mkdir dist
cp app/build/outputs/apk/full/release/app-full-release.apk "dist/llembas-android-$VERSION.apk"
cp app/build/outputs/apk/fdroid/release/app-fdroid-release.apk "dist/llembas-android-$VERSION-fdroid.apk"
cp app/build/outputs/apk/fullStandard/release/app-full-standard-release.apk "dist/llembas-android-$VERSION.apk"
cp app/build/outputs/apk/fullNotifications/release/app-full-notifications-release.apk "dist/llembas-android-$VERSION-notifications.apk"
cp app/build/outputs/apk/fdroidStandard/release/app-fdroid-standard-release.apk "dist/llembas-android-$VERSION-fdroid.apk"
# What is about to be published, checked on the files: the listener only in
# -notifications, the model stored, no x86_64 library.
scripts/check-apk.sh "dist/llembas-android-$VERSION.apk" standard release
scripts/check-apk.sh "dist/llembas-android-$VERSION-notifications.apk" notifications release
scripts/check-apk.sh "dist/llembas-android-$VERSION-fdroid.apk" fdroid release
{ echo "# llembas-android $VERSION"; (cd dist && sha256sum *.apk); } > SHA256SUMS
mv SHA256SUMS dist/
+3
View File
@@ -16,3 +16,6 @@ local.properties
.kotlin/
# Python
__pycache__/
# The wake-word engine and model: fetched by scripts/fetch-wakeword.py, never committed
/app/libs/
/app/src/full/assets/wakeword/
+218
View File
@@ -3,6 +3,224 @@
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`.
## [1.0.0-beta.9] — 2026-11-13
For LLeMbas server 2.0.0-beta.12 or later.
For LLeMbas server 2.0.0-beta.12 (harness spec 3.8.0); an older instance works as before.
### Added
- **Reports.** A scheduled task no longer answers into a chat: it files a report when it has
something to tell you, or leaves a line in its history. *Reports* is in the drawer, with a
count of the unread. The list has the unread first -- title, the task it came from, when, and
a mark where the model called it important; pull to read it again, swipe a row one way to mark
it read and the other to delete it (which asks once). A report reads as a page and is marked
read when opened; **Share** hands its text to another app; **Reply** continues it as a
conversation that stays with the report -- its bar says *Report: …*, Back returns to the
report, and it is not among your chats.
- **Notify when** on a scheduled task's form: *Every run* (the model writes a report every
time, also when nothing was found), *When…* (only when your own words hold; "something needs
my attention" to start from) or *Never* (runs are kept in the task's history only). Offered
where the instance has Reports.
- A task's runs show the run's own note -- what it found, or why it filed no report -- and a way
to its report when it filed one. The run's working chat can still be opened from the run.
- **Last wake** in Settings › Wake word: when the phrase was last heard, what the app tried
(the assistant's sheet, the sheet as a screen of the app, a notification) and exactly how it
went -- opened, and after how long; Android had not connected LLeMbas as the assistant;
Android refused, in its own words; or it did not refuse and still no sheet came -- with what
Android itself said at that moment: whether LLeMbas was the digital assistant app, whether
Android was really using it as its voice assistant, and when it had connected or dropped it.
A tap shows the last five. Nothing from your account is in it.
### Fixed
- **The wake word heard you and only a notification came, though LLeMbas is the assistant.**
The app can open the sheet from the background only through a connection Android keeps to
the assistant app, and it threw away the reason when that was missing or refused. It now
keeps it (*Last wake*), says in Settings when LLeMbas is the assistant but Android has not
connected it right now -- with the way to the system's setting -- and checks that the sheet
really came up before it counts the wake as opened; when it did not, the notification follows
and says *Could not open by itself — tap to ask*. What makes a phone drop that connection is
not fixed by this: the record is there to find out.
- Settings says so when LLeMbas is chosen as the digital assistant app but Android is not using
it as its voice assistant (which Android can undo at a restart): the long press then opens
it as an ordinary screen, and the wake word can only send a notification until LLeMbas is
chosen again.
- The wake word stayed paused "while the assistant is open" after the sheet was left with the
Home button, or after the assistant was asked for twice in a row.
- A report's conversation showed the line the server opens it with as if you had written it;
such lines are a quiet note now, and that first one is left out.
- The screen is turned on when the wake word opens the sheet (with *Only while the screen is
on* switched off, the phrase can come while it is dark).
### Changed
- **Notifications come from a report, not from a run**, on a *Reports* channel of their own:
unlocked, the report's title and summary; on the lock screen only "New report". A tap opens
the report; *Mark read* asks for the phone to be unlocked. A run that filed no report notifies
nothing; a failed run still says that it failed. An instance on 2.0.0-beta.11 keeps sending
its runs' notifications, and they work as before.
- A report the model called important arrives on a channel of its own, *Important reports*,
which may come up over what is on screen. A report read or deleted in the app takes its
notification away. *Reports* is in the drawer only where the instance has reports. An empty
*When…* means the instance's own default, which the field shows as a placeholder.
- **A page in an answer is not drawn on the phone** (LLeMbas 2.0.0-beta.12 can let a model add
HTML pages to an answer; the web and LLeMbas Desktop show them). The phone shows one quiet
card -- *This answer has a page: …*, and where to open it -- in a chat and in a report, never
the page's source. What you copy or share says `[page: …]` in its place. The phone's chat
settings do not offer the switch.
## [1.0.0-beta.8] — 2026-11-12
For LLeMbas server 2.0.0-beta.11 or later. Three files now: the standard app, `-notifications` (the same app with notification summaries) and `-fdroid`.
### Added
- **Test the wake word** (Settings › Wake word): for ten seconds the row shows what the wake word
is doing and says *Heard it* when your phrase lands, without opening the assistant -- so a
phrase, a sensitivity and a place in the room can be tried before relying on them.
### Fixed
- **The wake word never started, on any phone.** The engine read its model out of the APK in a
way that only works for files stored uncompressed, and they were not; the failure was swallowed,
so the notification went on saying it listened. The model is now copied out by stream (once per
model version, so an update that brings a new model replaces the old one) and stored
uncompressed as well.
- **The wake word's notification told the default phrase, not yours**, each time the app was
opened. It is now written from one place, from what the wake word is really doing.
- **Hearing the word when LLeMbas is not the phone's assistant and not on screen did nothing at
all**: Android blocks an activity started from the background without saying so, and the app
took the silence for success. It now posts *Heard you. Tap to ask.* on a channel of its own that
comes up over what is on screen, and Settings › Wake word says plainly that only the phone's
digital assistant app can open by voice over other apps, with a row that opens that setting.
- The wake word could stay "paused while the assistant is open" for good if its service ended in
the three seconds after the word. The hold now ends by itself, whatever happens to the service.
- Turning the wake word off and on again quickly could leave "not listening" showing over a wake
word that listened, or close the app (the service was stopped under a start still on its way).
Stop is now the setting going off, and the service ends itself.
- A change of phrase could release the engine while the old listening loop was still using it.
The old loop is now stopped and waited for first.
- A microphone that failed to start, or stopped giving sound, was not noticed (and one kind of
failure kept a processor core busy for nothing). Both are failures that are shown now.
- Opening the app with the wake word on but the microphone permission taken away could close the
app. The service is no longer started without the permission; the state says what is missing.
### Changed
- **One display with the web, Desktop and the CLI** (harness spec 3.7.0, `display.md`):
- A reply that was stopped or failed keeps the spec's line at its end -- *Stopped: by you*,
*Stopped: step limit*, *Stopped: budget*, *Failed: …* -- an error in the error colour, a stop
muted. A stopped reply said nothing at all before, and a failed one showed the raw error.
- A finished tool call says how long it took (`0.4s`, `1m 05s`, `2h 03m`) where the instance
sends the call's time; a running or a denied call shows none.
- Counts in the progress line are in the phone's own number format (`12,480`, `12 480`,
`12.480`); a tool call's title that had to be cut ends in `…`; the clock is joined by the
shared separator instead of a copy of it.
- The approval card offers the spec's four actions: *Allow once*, *Always allow*, *Deny*, and
*Deny, and say why*. The plan card approves together with the mode to continue in --
*Approve, continue in Edit* or *Approve, continue in Manual* -- and *Revise*.
- With LLeMbas 2.0.0-beta.11: a reply that was stopped or failed says so with its reason after a
reload too (the instance stores how it ended); *Always allow* is offered only where the request
offers it; a tool call's time is the instance's own; a call without a title is named as the
instance names its tool. The notifications build can take its own file from the instance's
recommendation of the same release when the website's manifest names none.
- **A reply ends when it is saved, and the chat's name follows** (with a server that sends `done`
first: LLeMbas 2.0.0-beta.11). The app treats `done` as the end -- the transcript, a spoken
answer and a queued prompt no longer wait for a model to name a new chat -- and takes the name
from the `title` frame when it comes.
- **Wake phrases the engine can hear.** "Hey Lembas" is gone: Lembas is not a word the engine's
model was ever trained on, so it had to be repeated until it happened to land. The phrase is now
a greeting and a name, each chosen in Settings › Wake word: **Hey**, **OK** or **Hello**, then
**Assistant**, **Computer**, **Google** (Settings says a Google device nearby will answer too),
or an ordinary name -- Victoria, Samantha, Jessica, Amanda, Olivia, Oliver, Sebastian, Jonathan,
Alexander, Christopher. The default is "Hey Assistant", and a phrase saved by an earlier beta
becomes it. The phrases are English whatever language the app is in, and Settings says so: the
model knows English speech only.
- **Sensitivity** (Low, Normal, High) in Settings › Wake word: how easily the phrase is taken as
heard, against how often it starts by mistake. Each phrase now goes to the engine with a
boosting score and a trigger threshold (1.0 / 0.35, 1.5 / 0.25, 2.0 / 0.15; a short phrase such
as "OK Computer" is held 0.05 stricter). These are starting values from the engine's
documentation, not yet tuned on phones.
- The phrases' spelling in the model's token pieces is generated from the model's own tokenizer
(`scripts/gen-wake-phrases.py`) and checked against its token table in CI, instead of written by
hand. Elizabeth and Benjamin are left out: the tokenizer can only spell them letter by letter.
- **Notification summaries moved to a build of their own**, `llembas-android-<version>-notifications.apk`:
the same app with the same signature, plus the notification listener. Google Play Protect
blocked installing beta.7, most likely because an app from outside the Play Store that can read
notifications is what it looks for; the standard and F-Droid APKs now declare no notification
listener at all, and Settings says where notification summaries went and why. The
notifications build installs over the standard one as an ordinary update, and back; it updates
itself only to its own kind.
- **A smaller download.** Release APKs no longer carry the emulator's x86_64 libraries (about
36 MB of beta.7's 98 MB) nor two libraries of the wake-word engine the app never calls.
- **The wake word says what it is doing**, in its notification and under its switch in Settings:
*Starting*, *Listening for "…"*, paused and why (screen off, battery saver, assistant open, no
microphone permission, or the microphone gives no sound because another app has it or it is
switched off), or not working and why (its model could not be unpacked, the engine did not
start, the microphone did not start) -- with the technical reason under it in Settings. A
failure is tried again by itself, after 2 s, 5 s, 15 s, a minute, then every five minutes.
- A tap on a failure in Settings tries again at once; trouble after half a minute of listening
well starts the waits over instead of counting on from old failures. Say the phrase and then
leave a short pause: the engine takes it as heard once something else follows (Settings and the
test row say so).
- A microphone permission given or taken in the system's settings is noticed when the app comes
back to the screen.
## [1.0.0-beta.7] — 2026-11-10
For LLeMbas server 2.0 (2.0.0-beta.10 or later for phone actions).
### Added
- **Share to LLeMbas, with a say in it.** *Ask LLeMbas* in any app's share menu now opens a
sheet over that app: what came in (the text or link, the files by name), a line for what to do
with it (optional), and where it goes -- a **new chat** or the **last assistant chat**. Files
are uploaded and go with the message; the chat then opens in the app.
- **A home-screen widget**: *Ask anything* opens the assistant, the microphone opens it
listening, and the clock opens the last assistant chat. It shows nothing from your account.
- **Spoken conversations with the assistant.** Ask by voice and, once the answer has been read
aloud, the assistant listens again -- until you say "stop" (or "that's all"), tap **End**, or
say nothing for a few seconds. The sheet says *In conversation* while it lasts. With a
Bluetooth headset connected, its microphone is used, so the conversation can stay in your ear.
Settings › Assistant › *Keep a spoken conversation going* (on; it needs voice replies).
- **A wake word, if you want one** (off by default). Settings › Assistant › *Wake word*: say
"Hey Lembas" (or one of three other English phrases) and the assistant opens, listening, over
whatever is on screen. It listens on the phone with an open-source engine (sherpa-onnx) and a
small on-device model; nothing leaves the phone before the word, and a notification is up the
whole time it listens. It pauses in battery saver, while the assistant is open, and -- unless
you change it -- with the screen off. Settings explains what it costs in battery and how to
keep a phone's battery optimisation from stopping it. Not in the F-Droid build, which builds
every library from source.
- **"Summarise my notifications"**, if you allow it (off by default). Settings › Assistant ›
*Notification summaries*, plus Android's own notification-access switch, which Settings opens
for you. Then ask the assistant about "my notifications", or tap its chip, and the
notifications on the phone right now go with that one question -- never before you ask, never
while the phone is locked, and the app keeps none of them.
- **Phone actions** (with LLeMbas server 2.0 and harness spec 3.6.0): a model may offer to do
something on this phone -- set an alarm or a timer, add a calendar event, draft a text or an
email, open the dialler with a number, start a route (with stops), add a stop, search nearby,
end the route, open an app or a web page, play/pause/skip, switch the torch, open a settings
panel, or run a Tasker task. A card says what will happen; nothing happens until you tap
**Do it**, never while the phone is locked, and drafts and calls are left for you to send and
place. The chat (and the assistant's sheet) tells the model whether it was done, declined or
failed. Navigation goes to Google Maps or **OsmAnd** (Settings › Navigation app: whichever is
installed, or ask); OsmAnd can also be asked where you are and where the running route goes,
once you allow LLeMbas inside OsmAnd.
- **Code in colour.** The file viewer highlights a source file by its language (as the server
names it), and a reply's code blocks by their fence's language: comments, strings, numbers,
keywords, type names, and markup's tags and attributes, in the theme's own colours in Shire
and Moria. Still read-only; a language it does not know is shown plain.
- **Launcher shortcuts** (long-press the icon): Ask LLeMbas, Speak, Last chat.
- **A headset's voice button** opens the assistant listening, when LLeMbas answers it; over the
lock screen it asks to unlock first.
### Changed
- The Quick Settings tile always shows as ready, never greyed out.
## [1.0.0-beta.6] — 2026-11-10
For LLeMbas server 2.0 (2.0.0-beta.9 or later for schedules on a computer, the update check through the instance, pinning, folders, memory and search).
+18 -4
View File
@@ -40,13 +40,27 @@ certificate). The app trusts CAs you installed, as the browser does.
digital assistant app. On Samsung phones also set Settings › Advanced features › Side button ›
Press and hold › Digital assistant.
There is no wake word. Android reserves always-on hotword detection for the system's own
preinstalled assistant; no app from outside can use it.
A wake word is there if you want one, off by default: Settings › Assistant › Wake word, a
greeting and a name in English ("Hey Assistant"). Android reserves its low-power, always-on
hotword detection for the system's own preinstalled assistant, so LLeMbas listens with an
on-device engine in a microphone service, with a notification up the whole time; nothing leaves
the phone before the word. Not in the F-Droid build.
## Build
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is the usual
`./gradlew assembleFullDebug` with JDK 17 and the Android SDK.
Builds run on GitHub Actions (`.github/workflows/ci.yml`); locally it is
`scripts/fetch-wakeword.py` (the wake-word engine and model, hash-pinned, never committed) and
then the usual `./gradlew assembleFullStandardDebug` with JDK 17 and the Android SDK.
A release is three APKs of one app, signed with one key:
| File | Build | What it is |
|---|---|---|
| `llembas-android-<version>.apk` | `fullStandard` | The app: updates itself, has the wake word. The one to install. |
| `llembas-android-<version>-notifications.apk` | `fullNotifications` | The same, plus a notification listener for *notification summaries*. Separate because Google Play Protect blocks installing an app from outside the Play Store that can read notifications; it installs over the standard one, and back. |
| `llembas-android-<version>-fdroid.apk` | `fdroidStandard` | No updater and no wake-word engine: only what F-Droid can build from source. |
`scripts/check-apk.sh` checks each built file for what it must and must not declare.
Three things are generated from the server at one ref; the first two are pinned with a lock
file CI checks, and CI checks the strings against the code:
+49 -3
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.6"
versionName = "1.0.0-beta.9"
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
@@ -67,17 +67,31 @@ android {
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
signingConfig = signingConfigs.findByName("release")
// The wake-word engine's native code, for phones only: a release carries no x86_64
// library (36 MB that only an emulator would load).
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") }
}
debug {
applicationIdSuffix = ".debug"
// CI's run number, so a tester can tell two test builds apart in Settings › About.
versionNameSuffix = "-debug" + (System.getenv("GITHUB_RUN_NUMBER")?.let { ".$it" } ?: "")
signingConfig = signingConfigs.getByName("debug")
// A test build also runs on the 64-bit emulator (not 32-bit x86).
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") }
}
}
// `full` updates itself from llembas.eu; `fdroid` has no updater, because F-Droid updates it.
flavorDimensions += "distribution"
// Two questions, three APKs.
//
// `distribution`: `full` updates itself from llembas.eu and has the wake-word engine; `fdroid`
// has neither, because F-Droid updates it and builds every library from source.
//
// `reading`: whether the app declares a notification listener (notification summaries).
// `standard` does not -- no listener, no permission, nothing of it in the manifest -- because
// Google Play Protect blocks installing an app from outside the Play Store that can read
// notifications. `notifications` is the full build plus the listener: the same application
// id and the same key, so it installs over the standard one as an ordinary update.
flavorDimensions += listOf("distribution", "reading")
productFlavors {
create("full") {
dimension = "distribution"
@@ -87,6 +101,26 @@ android {
dimension = "distribution"
buildConfigField("boolean", "SELF_UPDATE", "false")
}
create("standard") {
dimension = "reading"
}
create("notifications") {
dimension = "reading"
}
}
androidResources {
// The wake-word model is read as files the engine opens itself: stored as it is, never
// deflated a second time (it does not shrink, and nothing has to inflate it on the phone).
noCompress += "onnx"
}
packaging {
jniLibs {
// The engine is called through its JNI library alone, which needs only onnxruntime;
// the C and C++ API libraries its AAR also carries are for other kinds of caller.
excludes += listOf("**/libsherpa-onnx-c-api.so", "**/libsherpa-onnx-cxx-api.so")
}
}
buildFeatures {
@@ -130,6 +164,14 @@ android {
}
}
// fullStandard, fullNotifications and fdroidStandard: there is no F-Droid build with the listener.
androidComponents {
beforeVariants { variant ->
val flavors = variant.productFlavors.toMap()
if (flavors["distribution"] == "fdroid" && flavors["reading"] == "notifications") variant.enable = false
}
}
kotlin {
jvmToolchain(17)
}
@@ -156,6 +198,10 @@ dependencies {
implementation(libs.markwon.tables)
implementation(libs.markwon.strikethrough)
implementation(libs.unifiedpush.connector)
// The wake-word engine, sherpa-onnx (Apache-2.0), in the `full` build only: its prebuilt Android
// library, fetched hash-pinned by scripts/fetch-wakeword.py (never committed). The `fdroid`
// build, which F-Droid builds from source, has no engine (src/fdroid/.../wake/Engine.kt).
add("fullImplementation", files("libs/sherpa-onnx-2.0.1.aar"))
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
+3
View File
@@ -17,3 +17,6 @@
-dontwarn org.conscrypt.**
-dontwarn org.bouncycastle.**
-dontwarn org.openjsse.**
# The wake-word engine's JNI reads its config classes' fields by name.
-keep class com.k2fsa.sherpa.onnx.** { *; }
@@ -0,0 +1,14 @@
package eu.llembas.android.wake
import android.content.Context
/**
* The F-Droid build has no wake-word engine: F-Droid builds every library from source, and the
* engine (sherpa-onnx, Apache-2.0) comes to the other build as its project's prebuilt Android
* library. Settings says so; everything else about the wake word is the same code in both.
*/
object WakeEngine {
const val AVAILABLE = false
fun create(context: Context, keywords: String): WakeDetector = throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
}
@@ -0,0 +1,99 @@
package eu.llembas.android.wake
import android.content.Context
import com.k2fsa.sherpa.onnx.FeatureConfig
import com.k2fsa.sherpa.onnx.KeywordSpotter
import com.k2fsa.sherpa.onnx.KeywordSpotterConfig
import com.k2fsa.sherpa.onnx.OnlineModelConfig
import com.k2fsa.sherpa.onnx.OnlineStream
import com.k2fsa.sherpa.onnx.OnlineTransducerModelConfig
import java.io.File
/**
* The wake-word engine: sherpa-onnx's keyword spotter (Apache-2.0) with its small English model
* (a 3.3M-parameter zipformer, int8, Apache-2.0), both fetched hash-pinned at build time by
* `scripts/fetch-wakeword.py`. It runs on the phone's CPU, one thread, on the 16 kHz samples the
* service hands it; nothing leaves the phone.
*
* The model's files are copied out of the APK's assets into the app's no-backup files
* ([unpackWakeModel]: by stream, keyed by the model's version), so the engine reads them as files
* beside a keywords file written for the chosen phrase.
*/
object WakeEngine {
const val AVAILABLE = true
private val FILES = listOf("encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt")
/**
* The engine for [keywords] (the keywords file's text). Throws a [WakeError] that says which
* half failed -- the model's files or the engine -- and never returns nothing.
*
* One at a time: two service instances may overlap for a moment (the wake word turned off and
* on again), and the unpacking and the keywords file are shared. The keywords go into a file
* of this call's own, which the engine reads as it is made and which is gone afterwards.
*/
@Synchronized
fun create(context: Context, keywords: String): WakeDetector {
val dir = File(context.noBackupFilesDir, "wakeword")
try {
unpackWakeModel({ context.assets.open("wakeword/$it") }, dir, FILES)
} catch (e: Exception) {
throw WakeError(WakeFailure.Model, e)
}
checkKeywords(keywords, File(dir, "tokens.txt").readText())
var file: File? = null
try {
val written = File.createTempFile("keywords", ".txt", dir)
file = written
written.writeText(keywords)
val config = KeywordSpotterConfig(
featConfig = FeatureConfig(sampleRate = RATE, featureDim = 80),
modelConfig = OnlineModelConfig(
transducer = OnlineTransducerModelConfig(
encoder = File(dir, "encoder.int8.onnx").path,
decoder = File(dir, "decoder.int8.onnx").path,
joiner = File(dir, "joiner.int8.onnx").path,
),
tokens = File(dir, "tokens.txt").path,
modelType = "zipformer2",
numThreads = 1,
),
keywordsFile = written.path,
// The engine's own default (the Kotlin wrapper's is 2). The phrase counts once
// MORE than this many blank frames follow it -- two frames, about 80 ms of
// anything that is not the phrase going on. So: say it, then a short pause; a
// question run straight into the name can be missed.
numTrailingBlanks = 1,
)
return SherpaDetector(KeywordSpotter(null, config))
} catch (e: Throwable) {
// UnsatisfiedLinkError included: a phone whose processor the library was not built for.
throw WakeError(WakeFailure.Engine, e)
} finally {
file?.delete()
}
}
private const val RATE = 16_000
private class SherpaDetector(private val spotter: KeywordSpotter) : WakeDetector {
private val stream: OnlineStream = spotter.createStream()
override fun accept(samples: FloatArray): Boolean {
stream.acceptWaveform(samples, RATE)
while (spotter.isReady(stream)) {
spotter.decode(stream)
if (spotter.getResult(stream).keyword.isNotBlank()) {
spotter.reset(stream)
return true
}
}
return false
}
override fun release() {
stream.release()
spotter.release()
}
}
}
+77 -4
View File
@@ -5,6 +5,17 @@
<!-- Dictation and the assistant's voice. Asked for the first time either is used. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- A spoken conversation through a Bluetooth headset: its microphone made the route. -->
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<!-- The wake word (opt-in): a microphone foreground service, and "tap to listen again"
after a restart. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- Phone actions: an alarm or a timer, set through the clock app once the person confirms. -->
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<!-- Phone actions: run a Tasker task by its name (Tasker asks the person to allow it). -->
<uses-permission android:name="net.dinglisch.android.tasker.PERMISSION_RUN_TASKS" />
<queries>
<!-- UnifiedPush distributors (ntfy and others) are found by this action. -->
@@ -15,6 +26,16 @@
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
<!-- Phone actions: "open an app" by its name, and the navigation apps a route goes to. -->
<intent>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent>
<package android:name="com.google.android.apps.maps" />
<package android:name="net.osmand.plus" />
<package android:name="net.osmand" />
<package android:name="net.osmand.dev" />
<package android:name="net.dinglisch.android.taskerm" />
</queries>
<application
@@ -38,11 +59,11 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
</activity>
<!-- The assistant's sheet as an activity: the tile, the shortcut, ACTION_ASSIST, and
the lock-screen path (it asks to unlock before sending anything). -->
<!-- The assistant's sheet as an activity: the tile, the widget, the shortcuts,
ACTION_ASSIST, a headset's voice button, and the lock-screen path (it asks to
unlock before sending anything). -->
<activity
android:name=".assist.AssistActivity"
android:exported="true"
@@ -55,6 +76,15 @@
<action android:name="android.intent.action.ASSIST" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- A headset's voice button: the sheet opens listening. -->
<intent-filter>
<action android:name="android.intent.action.VOICE_COMMAND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.speech.action.VOICE_SEARCH_HANDS_FREE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
@@ -62,7 +92,9 @@
android:exported="true"
android:excludeFromRecents="true"
android:label="@string/share_label"
android:taskAffinity="">
android:taskAffinity=""
android:theme="@style/Theme.Lembas.Sheet"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
@@ -78,6 +110,25 @@
</intent-filter>
</activity>
<!-- Phone actions: asks another app for a result (OsmAnd's get_info) and goes. -->
<activity
android:name=".actions.ActionRunner$ResultActivity"
android:excludeFromRecents="true"
android:exported="false"
android:taskAffinity=""
android:theme="@style/Theme.Lembas.Sheet" />
<!-- The home-screen widget: Ask, the microphone, the last assistant chat. -->
<receiver
android:name=".widget.AskWidget"
android:exported="true"
android:label="@string/tile_ask">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_ask" />
</receiver>
<!-- The digital assistant: Settings › Default apps › Digital assistant app. -->
<service
android:name=".assist.LembasAssistService"
@@ -112,6 +163,8 @@
android:icon="@drawable/ic_notification"
android:label="@string/tile_ask"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<!-- A button, not a switch. -->
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="false" />
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
@@ -125,10 +178,30 @@
</intent-filter>
</service>
<!-- The wake word: listens only while its notification is up (wake/WakeWordService.kt). -->
<service
android:name=".wake.WakeWordService"
android:exported="false"
android:foregroundServiceType="microphone" />
<receiver
android:name=".wake.WakeBootReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<receiver
android:name=".push.CardActionReceiver"
android:exported="false" />
<!-- A report's Mark read, from its notification. -->
<receiver
android:name=".push.ReportActionReceiver"
android:exported="false" />
<!-- A scheduled task's Pause, from its notification. -->
<receiver
android:name=".push.ScheduleActionReceiver"
@@ -1,9 +1,12 @@
package eu.llembas.android
import android.app.Activity
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Bundle
import eu.llembas.android.auth.InstanceStore
import eu.llembas.android.wake.AppVisibility
/** The process: one store of instances, and the notification channels, made once. */
class LembasApp : Application() {
@@ -13,6 +16,25 @@ class LembasApp : Application() {
override fun onCreate() {
super.onCreate()
instances = InstanceStore(this)
// Whether the app is on screen: the wake word may open the assistant's sheet as an
// activity only then (Android blocks one started from the background, silently).
registerActivityLifecycleCallbacks(
object : ActivityLifecycleCallbacks {
override fun onActivityStarted(activity: Activity) = AppVisibility.activityStarted()
override fun onActivityStopped(activity: Activity) = AppVisibility.activityStopped()
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
},
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannels(
listOf(
@@ -20,13 +42,17 @@ 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)
}
companion object {
@@ -34,6 +60,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
@@ -54,6 +58,9 @@ import eu.llembas.android.ui.settings.SettingsScreen
import eu.llembas.android.ui.signin.SignInScreen
import eu.llembas.android.ui.theme.LembasTheme
import eu.llembas.android.update.ReleaseCheck
import eu.llembas.android.wake.WakeBootReceiver
import eu.llembas.android.wake.WakeEngine
import eu.llembas.android.wake.WakeWordService
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
@@ -62,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. */
@@ -90,6 +97,18 @@ class MainActivity : ComponentActivity() {
}
}
/**
* A wake word that is on, but whose service the phone stopped, listens again -- each time the
* app comes to the screen, which is also when a microphone permission given or taken in the
* system's settings is noticed ([WakeWordService.start] says which it is).
*/
override fun onStart() {
super.onStart()
lifecycleScope.launch {
if (WakeEngine.AVAILABLE && lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity)
}
}
/**
* Keep the app in the language Settings › Language says: the account's by default. A
* language chosen for the app in the system's own settings (Android 13+) since the app last
@@ -115,12 +134,20 @@ class MainActivity : ComponentActivity() {
}
private fun take(intent: Intent?) {
val chat = intent?.getStringExtra(Notifications.EXTRA_CHAT)
val schedule = intent?.getStringExtra(Notifications.EXTRA_SCHEDULE)
val run = intent?.getStringExtra(Notifications.EXTRA_RUN)
// "Tap to listen again" after a restart: the app is on screen now, so the microphone
// service may start.
if (intent?.getBooleanExtra(WakeBootReceiver.EXTRA_RESUME, false) == true) {
lifecycleScope.launch { if (lembas.instances.prefs.first().wakeWord) WakeWordService.start(this@MainActivity) }
}
// Extras are whatever the sender put there (this activity can be started from outside):
// only ids that look like ids go on to become routes.
val chat = safeId(intent?.getStringExtra(Notifications.EXTRA_CHAT))
val schedule = safeId(intent?.getStringExtra(Notifications.EXTRA_SCHEDULE))
val run = safeId(intent?.getStringExtra(Notifications.EXTRA_RUN))
val instance = intent?.getStringExtra(Notifications.EXTRA_INSTANCE)
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) {
@@ -188,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") }
@@ -222,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")
@@ -235,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,
@@ -279,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() },
@@ -297,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 ->
@@ -305,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") {
@@ -0,0 +1,146 @@
package eu.llembas.android.actions
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
/**
* Carries out a phone action the person confirmed: [run] picks the way -- one intent, the torch, a
* media key, or a navigation app -- and answers with done, failed (and why), never silence.
*/
object ActionRunner {
// The reasons go back to the model as the tool's result, so they are written for it, in English.
private const val NOT_POSSIBLE = "the phone cannot do this action with these arguments"
private const val NO_NAV_APP = "no navigation app chosen or installed (Google Maps or OsmAnd)"
private const val NO_DESTINATION =
"a stop can only be added with the route's destination: name it (destination), or the person lets LLeMbas ask OsmAnd for it"
private const val GOOGLE_CANNOT_STOP = "Google Maps cannot be told to stop navigating; the person stops it there"
private const val OSMAND_NEEDS_COORDINATES = "OsmAnd takes a route through stops only with every point's lat and lon"
/**
* [askOsmAnd]: Settings › Phone actions says the person allowed LLeMbas inside OsmAnd, so its
* position and the running route's destination may be asked for (`get_info`).
*/
suspend fun run(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean = false): ActionOutcome {
when (action) {
"torch" -> return PhoneActions.torch(context, args.bool("on"))
"media" -> return PhoneActions.media(context, args.str("command").ifBlank { "toggle" })
"navigate", "add_stop", "search_nearby", "stop_navigation" -> return navigate(context, action, args, nav, askOsmAnd)
}
val intent = PhoneActions.intentFor(context, action, args)
?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
return PhoneActions.launch(context, intent, broadcast = action == "automation_intent")
}
private suspend fun navigate(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean): ActionOutcome {
val app = nav ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
val pkg = app.installed(context) ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
val travel = Travel.of(args.str("mode").ifBlank { null })
// OsmAnd's own position and destination, if the person allowed LLeMbas to ask it.
val info = if (app == NavApp.OsmAnd && askOsmAnd && action != "stop_navigation") osmandInfo(context, pkg) else null
val step = when (action) {
"navigate" -> args.place("destination")?.let {
NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info, replace = args.bool("replace_route") == true)
}
"add_stop" -> args.place("stop")?.let {
NavIntents.addStop(app, pkg, it, args.place("destination"), travel, info, NO_DESTINATION)
}
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let {
NavIntents.searchNearby(
app,
pkg,
it,
info,
alongRoute =
args.str("near") == "route",
)
}
else -> NavIntents.stop(app, pkg, GOOGLE_CANNOT_STOP)
} ?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
return when (step) {
is NavStep.Unsupported -> ActionOutcome(ActionStatus.Failed, step.reason.ifBlank { OSMAND_NEEDS_COORDINATES })
// The map app comes to the front and stays: it answers nothing more until the person
// leaves it, so its having taken the intent is "done".
is NavStep.Launch -> PhoneActions.launch(context, step.intent)
}
}
/** OsmAnd's `get_info`, when the person allowed it inside OsmAnd; null otherwise, quietly. */
private suspend fun osmandInfo(context: Context, pkg: String): OsmAndInfo? {
val (code, extras) = forResult(context, NavIntents.osmandInfo(pkg), timeoutMs = 4_000) ?: return null
return if (code == Activity.RESULT_OK) OsmAndInfo.of(extras) else null
}
private val waiting = ConcurrentHashMap<Int, CompletableDeferred<Pair<Int, Bundle?>>>()
private val ids = AtomicInteger()
/**
* Start [intent] for its result through [ResultActivity] -- a see-through activity of the
* app's own, so this works from the assistant's sheet (a voice-interaction session) as well.
*/
suspend fun forResult(context: Context, intent: Intent, timeoutMs: Long = 60_000): Pair<Int, Bundle?>? {
val id = ids.incrementAndGet()
val answer = CompletableDeferred<Pair<Int, Bundle?>>()
waiting[id] = answer
return try {
context.startActivity(
Intent(context, ResultActivity::class.java)
.putExtra(ResultActivity.EXTRA_ID, id)
.putExtra(ResultActivity.EXTRA_INTENT, intent)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
withTimeoutOrNull(timeoutMs) { answer.await() }
} finally {
waiting.remove(id)
}
}
internal fun answered(id: Int, code: Int, extras: Bundle?) {
waiting[id]?.complete(code to extras)
}
/** Asks another app for a result on [ActionRunner]'s behalf, then goes. Shows nothing of its own. */
class ResultActivity : ComponentActivity() {
private var id = 0
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
answered(id, result.resultCode, result.data?.extras)
finish()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
id = intent.getIntExtra(EXTRA_ID, 0)
if (savedInstanceState != null) return
@Suppress("DEPRECATION")
val target = intent.getParcelableExtra<Intent>(EXTRA_INTENT)
if (target == null) {
answered(id, Activity.RESULT_CANCELED, null)
finish()
return
}
try {
launcher.launch(target)
} catch (e: ActivityNotFoundException) {
answered(id, Activity.RESULT_FIRST_USER, null)
finish()
}
}
companion object {
const val EXTRA_ID = "eu.llembas.android.RESULT_ID"
const val EXTRA_INTENT = "eu.llembas.android.RESULT_INTENT"
}
}
}
@@ -0,0 +1,218 @@
package eu.llembas.android.actions
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
/** A place for a navigation app: coordinates when the model knows them, else words to search for. */
data class Place(val name: String = "", val lat: Double? = null, val lon: Double? = null, val query: String = "") {
val hasCoordinates: Boolean get() = lat != null && lon != null
val label: String get() = name.ifBlank { query.ifBlank { if (hasCoordinates) "$lat, $lon" else "" } }
/** What a map app searches for: the words, else the name. */
val searchText: String get() = query.ifBlank { name }
}
/** The navigation apps the phone actions drive. */
enum class NavApp(val id: String, val packages: List<String>) {
GoogleMaps("google", listOf("com.google.android.apps.maps")),
// OsmAnd: `net.osmand.plus` is OsmAnd+ and the F-Droid build (OsmAnd~); `net.osmand` the free one.
OsmAnd("osmand", listOf("net.osmand.plus", "net.osmand", "net.osmand.dev")),
;
/** The package of this app on the phone, if it is installed. */
fun installed(context: Context): String? = packages.firstOrNull { isInstalled(context, it) }
companion object {
/**
* Settings' choice among [installed]: the one named; by default whichever is installed, and
* with both installed (or "ask"), null -- the card then offers each.
*/
fun chosen(pref: String, installed: List<NavApp>): NavApp? = when (pref) {
PREF_ASK -> null
"" -> installed.singleOrNull()
else -> installed.firstOrNull { it.id == pref } ?: installed.singleOrNull()
}
fun installedApps(context: Context): List<NavApp> = entries.filter { it.installed(context) != null }
const val PREF_ASK = "ask"
private fun isInstalled(context: Context, pkg: String): Boolean = runCatching {
if (Build.VERSION.SDK_INT >= 33) {
context.packageManager.getPackageInfo(pkg, PackageManager.PackageInfoFlags.of(0))
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(pkg, 0)
}
}.isSuccess
}
}
/** How a person travels, as the action names it. */
enum class Travel(val id: String, val google: String, val googleNav: String, val osmand: String) {
Drive("drive", "driving", "d", "car"),
Walk("walk", "walking", "w", "pedestrian"),
Bike("bike", "bicycling", "b", "bicycle"),
Transit("transit", "transit", "d", "public_transport"),
;
companion object {
fun of(id: String?): Travel = entries.firstOrNull { it.id == id } ?: Drive
}
}
/** One request to a navigation app: an [Intent], or why it cannot be done in that app. */
sealed interface NavStep {
data class Launch(val intent: Intent) : NavStep
data class Unsupported(val reason: String) : NavStep
}
/**
* What OsmAnd itself says about the route, when the person allowed LLeMbas to ask
* (OsmAnd › Plugins › … › the app's "Location" access for its API): the phone's position and the
* route's destination. Null when not allowed -- the actions then use what the model gave.
*/
data class OsmAndInfo(val lat: Double?, val lon: Double?, val destination: Place?) {
companion object {
fun of(extras: Bundle?): OsmAndInfo? {
extras ?: return null
fun d(key: String) = if (extras.containsKey(key)) extras.getDouble(key) else null
val dLat = d("destination_lat")
val dLon = d("destination_lon")
return OsmAndInfo(d("lat"), d("lon"), if (dLat != null && dLon != null) Place(lat = dLat, lon = dLon) else null)
}
}
}
/**
* The intents, per app. Google Maps: a route to a place with up to a few stops (its `dir` URL),
* a search near here (`geo:0,0?q=`); it cannot take a stop into a route already running, nor be
* told to stop -- adding a stop there starts the route again through the stop. OsmAnd: its intent
* API (`osmand.api://`, a URI protocol; no OsmAnd code in this app): navigate, a route through
* stops as a GPX passed as data, a search near a position, stop navigation.
*/
object NavIntents {
private const val GOOGLE_STOPS = 9
/** [replace]: a route already running is replaced without the map app asking first (OsmAnd asks otherwise). */
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, replace: Boolean = false): NavStep =
when (app) {
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info, if (replace) "true" else "false")
}
/** A stop on the way to the route's destination ([destination] from the model, else OsmAnd's own). */
fun addStop(app: NavApp, pkg: String, stop: Place, destination: Place?, travel: Travel, info: OsmAndInfo?, noDestination: String): NavStep {
val to = destination?.takeIf { it.hasCoordinates || it.searchText.isNotBlank() } ?: info?.destination ?: return NavStep.Unsupported(noDestination)
// Planned again from here: the route being replaced is the one the person asked to change.
return navigate(app, pkg, to, listOf(stop), travel, info, replace = true)
}
/**
* [alongRoute] searches near the running route; OsmAnd is given the phone's position for both
* (its search ranks along the route itself while one runs), Google Maps searches near here.
*/
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?, alongRoute: Boolean = false): NavStep = when {
app == NavApp.OsmAnd && info?.lat != null && info.lon != null -> NavStep.Launch(
osmandUri(
pkg,
"navigate_search",
"dest_search_query" to query,
"search_lat" to info.lat.toString(),
"search_lon" to info.lon.toString(),
"show_search_results" to "true",
"force" to "true",
),
)
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))).setPackage(pkg))
}
fun stop(app: NavApp, pkg: String, unsupported: String): NavStep = when (app) {
NavApp.OsmAnd -> NavStep.Launch(osmandUri(pkg, "stop_navigation"))
NavApp.GoogleMaps -> NavStep.Unsupported(unsupported)
}
/** OsmAnd's own account of the route (needs the person's grant inside OsmAnd). */
fun osmandInfo(pkg: String): Intent = osmandUri(pkg, "get_info")
private fun google(pkg: String, destination: Place, stops: List<Place>, travel: Travel): NavStep {
if (stops.isEmpty()) {
val q = if (destination.hasCoordinates) "${destination.lat},${destination.lon}" else destination.searchText
return NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${Uri.encode(q)}&mode=${travel.googleNav}")).setPackage(pkg))
}
val url = Uri.parse("https://www.google.com/maps/dir/").buildUpon()
.appendQueryParameter("api", "1")
.appendQueryParameter("destination", googlePlace(destination))
.appendQueryParameter("waypoints", stops.take(GOOGLE_STOPS).joinToString("|") { googlePlace(it) })
.appendQueryParameter("travelmode", travel.google)
.appendQueryParameter("dir_action", "navigate")
.build()
return NavStep.Launch(Intent(Intent.ACTION_VIEW, url).setPackage(pkg))
}
private fun googlePlace(p: Place) = if (p.hasCoordinates) "${p.lat},${p.lon}" else p.searchText
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?, force: String): NavStep {
val route = stops + destination
return when {
// Through stops: OsmAnd follows a route given as GPX, which needs every point's coordinates.
stops.isNotEmpty() && route.all { it.hasCoordinates } -> NavStep.Launch(
osmandUri(pkg, "navigate_gpx", "force" to force).putExtra("data", gpx(route)),
)
stops.isNotEmpty() -> NavStep.Unsupported("")
destination.hasCoordinates -> NavStep.Launch(
osmandUri(
pkg,
"navigate",
"dest_lat" to destination.lat.toString(),
"dest_lon" to destination.lon.toString(),
"dest_name" to destination.label,
"profile" to travel.osmand,
"force" to force,
),
)
// Words only: OsmAnd searches them near the phone when it says where the phone is,
// else its own search opens with them (geo:0,0?q=).
info?.lat != null && info.lon != null -> NavStep.Launch(
osmandUri(
pkg,
"navigate_search",
"dest_search_query" to destination.searchText,
"search_lat" to info.lat.toString(),
"search_lon" to info.lon.toString(),
"profile" to travel.osmand,
"force" to force,
),
)
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(destination.searchText))).setPackage(pkg))
}
}
private fun osmandUri(pkg: String, command: String, vararg params: Pair<String, String>): Intent {
val uri = Uri.Builder().scheme("osmand.api").authority(command).apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }.build()
return Intent(Intent.ACTION_VIEW, uri).setPackage(pkg)
}
/** A route as GPX 1.1: its points in order, named. */
fun gpx(points: List<Place>): String = buildString {
append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
append("<gpx version=\"1.1\" creator=\"LLeMbas\" xmlns=\"http://www.topografix.com/GPX/1/1\"><rte>")
for (p in points) {
append("<rtept lat=\"${p.lat}\" lon=\"${p.lon}\"><name>")
append(p.label.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
append("</name></rtept>")
}
append("</rte></gpx>\n")
}
}
@@ -0,0 +1,285 @@
package eu.llembas.android.actions
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.media.AudioManager
import android.net.Uri
import android.provider.AlarmClock
import android.provider.CalendarContract
import android.provider.Settings
import android.view.KeyEvent
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.ZoneId
/** How a phone action ended, as the tool's result says it. */
enum class ActionStatus(val wire: String) { Done("done"), Declined("declined"), Failed("failed") }
data class ActionOutcome(val status: ActionStatus, val message: String = "")
/** The arguments of an action, read leniently: a model writes numbers as strings now and then. */
class Args(val json: JsonObject) {
private val o get() = json
fun str(key: String): String = (o[key] as? JsonPrimitive)?.takeIf { it.isString || it.booleanOrNull == null }?.content.orEmpty()
fun int(key: String): Int? = (o[key] as? JsonPrimitive)?.let { it.intOrNull ?: it.content.toIntOrNull() }
fun long(key: String): Long? = (o[key] as? JsonPrimitive)?.let { it.longOrNull ?: it.content.toLongOrNull() }
fun bool(key: String): Boolean? = (o[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.toBooleanStrictOrNull() }
fun obj(key: String): Args? = (o[key] as? JsonObject)?.let(::Args)
fun list(key: String): List<JsonElement> = (o[key] as? JsonArray).orEmpty()
/** A list of strings (or one string, which a model sometimes writes for a list of one). */
fun strings(key: String): List<String> = when (val v = o[key]) {
is JsonArray -> v.mapNotNull { (it as? JsonPrimitive)?.content?.trim()?.takeIf(String::isNotEmpty) }
is JsonPrimitive -> listOfNotNull(v.content.trim().takeIf { it.isNotEmpty() })
else -> emptyList()
}
fun place(key: String): Place? = when (val v = o[key]) {
is JsonObject -> placeOf(v)
is JsonPrimitive -> v.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
else -> null
}
fun places(key: String): List<Place> = list(key).mapNotNull { e ->
when (e) {
is JsonObject -> placeOf(e)
is JsonPrimitive -> e.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
else -> null
}
}
private fun placeOf(v: JsonObject): Place {
fun d(k: String) = (v[k] as? JsonPrimitive)?.let { it.doubleOrNull ?: it.content.toDoubleOrNull() }
return Place(
name = (v["name"] as? JsonPrimitive)?.content.orEmpty(),
lat = d("lat"),
lon = d("lon"),
query = (v["query"] as? JsonPrimitive)?.content.orEmpty(),
)
}
/** A time the model wrote: `YYYY-MM-DDTHH:MM` in the phone's zone, `YYYY-MM-DD`, or with an offset. */
fun time(key: String): Long? {
val raw = str(key).ifBlank { return null }
val zone = ZoneId.systemDefault()
return runCatching { LocalDateTime.parse(raw).atZone(zone).toInstant().toEpochMilli() }.getOrNull()
?: runCatching { LocalDate.parse(raw).atStartOfDay(zone).toInstant().toEpochMilli() }.getOrNull()
?: runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
}
}
/**
* The phone actions a model may propose (`phone_action`), carried out with Android's standard
* intents once the person tapped Do it on the card. Each one either opens the app that does it,
* with everything filled in (an alarm, an event, a draft -- the person sends a message or saves
* an event there themselves), or does a small thing at once (the torch, play/pause).
*
* Nothing here runs without the card's Do it, and none of it from the lock screen. A model's
* words are data: a URL opens only for http and https, a broadcast never names a system action,
* a phone number goes to the dialler and is never called.
*/
object PhoneActions {
/** Media keys, by the action's `command`. */
private val MEDIA = mapOf(
"toggle" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
"play" to KeyEvent.KEYCODE_MEDIA_PLAY,
"pause" to KeyEvent.KEYCODE_MEDIA_PAUSE,
"next" to KeyEvent.KEYCODE_MEDIA_NEXT,
"previous" to KeyEvent.KEYCODE_MEDIA_PREVIOUS,
)
/** Settings panels, by the action's `panel`. Panels (Android 10+) float over the app; the rest are pages. */
private val PANELS = mapOf(
"wifi" to Settings.Panel.ACTION_WIFI,
"internet" to Settings.Panel.ACTION_INTERNET_CONNECTIVITY,
"nfc" to Settings.Panel.ACTION_NFC,
"volume" to Settings.Panel.ACTION_VOLUME,
"bluetooth" to Settings.ACTION_BLUETOOTH_SETTINGS,
"location" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
"do_not_disturb" to Settings.ACTION_ZEN_MODE_PRIORITY_SETTINGS,
)
/** Tasker's public intent for running a task by its name (its TaskerIntent protocol). */
const val TASKER_PACKAGE = "net.dinglisch.android.taskerm"
private const val TASKER_ACTION = "net.dinglisch.android.tasker.ACTION_TASK"
/** The broadcast any other automation app (Automate, MacroDroid, …) can listen for. */
const val AUTOMATION_ACTION = "eu.llembas.android.action.AUTOMATION"
/** A URL the phone may open for a model: web pages only. */
fun urlAllowed(url: String): Boolean = url.trim().lowercase().let {
(it.startsWith("http://") || it.startsWith("https://")) &&
it.substringAfter("://").isNotBlank()
}
/** `HH:MM` as hour and minute, or null. */
fun clock(time: String): Pair<Int, Int>? {
val m = Regex("^(\\d{1,2}):(\\d{2})$").matchEntire(time.trim()) ?: return null
val (h, min) = m.destructured
return (h.toInt() to min.toInt()).takeIf { it.first in 0..23 && it.second in 0..59 }
}
/** SMS recipients: the numbers among [to]; a name the messaging app has to find is left to the person. */
fun smsNumbers(to: List<String>): List<String> = to.map { it.trim() }.filter { Regex("^[+0-9 ()./#*-]{3,}$").matches(it) && it.count(Char::isDigit) >= 3 }
/**
* The intent for an action that is one intent (everything but navigation, the torch and media
* keys), or null when [action] is not one of these or its arguments do not make one.
*/
fun intentFor(context: Context, action: String, a: Args): Intent? = when (action) {
"alarm" -> clock(a.str("time"))?.let { (hour, minute) ->
Intent(AlarmClock.ACTION_SET_ALARM)
.putExtra(AlarmClock.EXTRA_HOUR, hour)
.putExtra(AlarmClock.EXTRA_MINUTES, minute)
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
.apply {
val days = a.strings("days").mapNotNull(::calendarDay)
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
}
}
"timer" -> a.int("seconds")?.let { seconds ->
Intent(AlarmClock.ACTION_SET_TIMER)
.putExtra(AlarmClock.EXTRA_LENGTH, seconds.coerceIn(1, 86_400))
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
}
// The calendar's new-event screen, filled in: the person saves it.
"calendar_event" -> Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.Events.TITLE, a.str("title"))
.apply {
a.time("start")?.let { putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, it) }
a.time("end")?.let { putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it) }
if (a.bool("all_day") == true) putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
a.str("location").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.EVENT_LOCATION, it) }
a.str("notes").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
}
// A draft: the messaging app opens with it, and the person sends.
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + smsNumbers(a.strings("to")).joinToString(";") { Uri.encode(it) }))
.putExtra("sms_body", a.str("body"))
"email_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
.putExtra(Intent.EXTRA_EMAIL, a.strings("to").toTypedArray())
.putExtra(Intent.EXTRA_CC, a.strings("cc").toTypedArray())
.putExtra(Intent.EXTRA_SUBJECT, a.str("subject"))
.putExtra(Intent.EXTRA_TEXT, a.str("body"))
// The dialler with the number in it: the person places the call.
"dial" -> Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(a.str("number"))))
"open_url" -> a.str("url").trim().takeIf(::urlAllowed)?.let { Intent(Intent.ACTION_VIEW, Uri.parse(it)) }
"open_app" -> appIntent(context, "", a.str("app"))
"settings_panel" -> PANELS[a.str("panel")]?.let { Intent(it) }
// Tasker (by default) runs the task by its name, the values as its local variables; any
// other automation app gets LLeMbas's own broadcast, with the task's name and the values.
"automation_intent" -> {
val task = a.str("task")
val app = a.str("app").trim()
val values = a.obj("values")?.json.orEmpty().mapNotNull { (k, v) -> (v as? JsonPrimitive)?.let { k to it.content } }
if (app.isBlank() || app.equals("tasker", ignoreCase = true)) {
Intent(TASKER_ACTION)
.setPackage(TASKER_PACKAGE)
.putExtra("version_number", "1.1")
.putExtra("task_name", task)
.putExtra("task_priority", 5)
.putStringArrayListExtra("varNames", ArrayList(values.map { "%" + it.first.lowercase() }))
.putStringArrayListExtra("varValues", ArrayList(values.map { it.second }))
} else {
Intent(AUTOMATION_ACTION)
.putExtra("task", task)
.putExtra("app", app)
.apply { values.forEach { (k, v) -> putExtra(k, v) } }
}
}
else -> null
}
/** An app by its package, else by the name the launcher shows (the first app whose label matches). */
fun appIntent(context: Context, pkg: String, name: String): Intent? {
val pm = context.packageManager
pkg.takeIf { it.isNotBlank() }?.let { p -> pm.getLaunchIntentForPackage(p)?.let { return it } }
if (name.isBlank()) return null
val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
val apps = runCatching { pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL) }.getOrDefault(emptyList())
val wanted = name.trim().lowercase()
val found = apps.firstOrNull { it.loadLabel(pm).toString().lowercase() == wanted }
?: apps.firstOrNull { it.loadLabel(pm).toString().lowercase().contains(wanted) }
?: return null
return pm.getLaunchIntentForPackage(found.activityInfo.packageName)
}
/** The torch on or off (or the other way round), through the camera service; no permission needed. */
fun torch(context: Context, on: Boolean?): ActionOutcome {
val cameras = context.getSystemService(CameraManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no camera")
val id = cameras.cameraIdList.firstOrNull { cameras.getCameraCharacteristics(it).get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true }
?: return ActionOutcome(ActionStatus.Failed, "this phone has no torch")
val target = on ?: !torchOn
return runCatching {
cameras.setTorchMode(id, target)
torchOn = target
ActionOutcome(ActionStatus.Done, if (target) "torch on" else "torch off")
}.getOrElse { ActionOutcome(ActionStatus.Failed, it.message.orEmpty()) }
}
@Volatile
private var torchOn = false
/** A media key to whatever is playing. */
fun media(context: Context, key: String): ActionOutcome {
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media command: $key")
val audio = context.getSystemService(AudioManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no audio")
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
return ActionOutcome(ActionStatus.Done, key)
}
/** Start [intent] as a new task; whether an app took it. */
fun launch(context: Context, intent: Intent, broadcast: Boolean = false): ActionOutcome = try {
if (broadcast) {
context.sendBroadcast(intent)
} else {
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
ActionOutcome(ActionStatus.Done)
} catch (e: ActivityNotFoundException) {
ActionOutcome(ActionStatus.Failed, "no app on this phone does that")
} catch (e: SecurityException) {
ActionOutcome(ActionStatus.Failed, e.message.orEmpty())
}
private fun calendarDay(day: String): Int? = when (day.lowercase().take(3)) {
"sun" -> java.util.Calendar.SUNDAY
"mon" -> java.util.Calendar.MONDAY
"tue" -> java.util.Calendar.TUESDAY
"wed" -> java.util.Calendar.WEDNESDAY
"thu" -> java.util.Calendar.THURSDAY
"fri" -> java.util.Calendar.FRIDAY
"sat" -> java.util.Calendar.SATURDAY
else -> null
}
}
@@ -174,6 +174,27 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
/** The app releases this server recommends; 404 from a server older than the route. */
suspend fun apps(): AppsInfo = get("/apps")
/** What `@` offers from the server for [q]: the chat's earlier attachments, files of the tree, a web address. */
suspend fun mentions(q: String, chatId: String? = null): Mentions = get("/mentions?q=${segment(q)}" + (chatId?.let { "&chat=${segment(it)}" } ?: ""))
/**
* Attach without uploading: a copy of an earlier attachment, a file of the tree as it is now,
* or a web page's text -- whichever [mention] is. 404 for what cannot be reached, 400 for a
* page that cannot be fetched.
*/
suspend fun attachFrom(mention: Mention, chatId: String? = null): Attachment = send<AttachmentEnvelope>(
"POST",
"/attachments/from",
buildJsonObject {
when (mention.kind) {
"attachment" -> put("attachment", mention.id)
"url" -> put("url", mention.url)
else -> put("path", mention.path)
}
chatId?.let { put("chat", it) }
},
).attachment
/** The web's search in JSON: chats by their words (and meaning, where indexed), files, memories. */
suspend fun search(q: String, within: String = "all", limit: Int = 20): SearchResults = get("/search?q=${segment(q)}&in=${segment(within)}&limit=$limit")
@@ -239,6 +260,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
agents?.let { put("agents", agentsJson(it)) }
put("temporary", temporary)
forceTool?.let { put("force_tool", it) }
put("client", CAPABILITIES)
// An agent chat runs on a linked device; an empty directory is the device's first
// allowed one. A device that is no longer linked makes it an ordinary chat on the
// server, rather than losing the message.
@@ -258,6 +280,7 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
put("text", text)
put("attachments", JsonArray(attachments.map { JsonPrimitive(it) }))
forceTool?.let { put("force_tool", it) }
put("client", CAPABILITIES)
},
)
@@ -348,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
@@ -363,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
@@ -513,6 +566,12 @@ class ApiClient(val base: String, private val token: String, val http: OkHttpCli
authed("$v2/chats/$chatId/messages/$messageId/stream").header("Accept", "text/event-stream").build()
companion object {
/**
* What this app can do, sent with every message (spec 3.6.0): the phone carries out
* `phone_action` calls the person confirms here, so the chat is offered the tool.
*/
private val CAPABILITIES = JsonArray(listOf(JsonPrimitive("phone_actions")))
/** 1 MB, the server's own limit on a shown file, with room for a little more. */
const val SHOWN_MAX_BYTES = 1_100_000L
@@ -0,0 +1,146 @@
package eu.llembas.android.api
import java.text.NumberFormat
import java.util.Locale
/*
* One display in every client (harness spec 3.7.0, `display.md`): what this app says about a tool
* call, the end of a reply and a number -- the same things, from the same data, as the web UI,
* Desktop and the CLI.
*/
/** The states that end a turn without finishing it; their line stays on the reply (`display.end`). */
val END_PHASES = setOf("stopped", "failed")
/**
* A call's short title as a line may show it (`display.md` §1, step 4): trimmed, its first line
* only, and cut to [max] code points -- one fewer and `…` -- so a cut title says it was cut.
* Null when nothing is left.
*/
fun shortTitle(text: String?, max: Int = TITLE_MAX): String? {
val line = text?.trim()?.lineSequence()?.firstOrNull()?.trim().orEmpty()
if (line.isEmpty()) return null
if (line.codePointCount(0, line.length) <= max) return line
return line.substring(0, line.offsetByCodePoints(0, max - 1)) + "…"
}
/** `loop.json` `progress.what_max`. */
const val TITLE_MAX = 80
/**
* The state a drawn call is in (`display.md` §2): `running`, `done`, `failed` or `denied`, from
* what `/api/v2` says of it.
*/
fun ToolCall.state(): String = when {
// The server's own word, from spec 3.7.0; an older one leaves it to what the call carries.
block.state in CALL_STATES -> block.state
status == "denied" -> "denied"
status == "error" || !error.isNullOrEmpty() -> "failed"
status == "running" || status == "pending" -> "running"
else -> "done"
}
private val CALL_STATES = setOf("running", "done", "failed", "denied")
/**
* What is written after a call's title for its time: the server's own [ToolBlock.duration] where
* it sends one (it measured the call), else made from the call's `ms`; nothing for a call that is
* running or was denied.
*/
fun ToolCall.took(): String? {
val state = state()
if (state == "running" || state == "denied") return null
return block.duration.ifBlank { null } ?: callDuration(state, ms)
}
/**
* How long a finished call took (`display.md` §2): tenths under a minute (`0.4s`), then
* `1m 05s`, then `2h 03m`. None for a call that is running or was denied, or whose time was not
* kept. Not a locale number: written with `.` everywhere.
*/
fun callDuration(state: String, ms: Long?): String? {
if (ms == null || state == "running" || state == "denied") return null
// Tenths, rounded half up, decide the form: 59.96 s is not "60.0s" but a minute.
val tenths = (ms.coerceAtLeast(0) + 50) / 100
if (tenths < 600) return "${tenths / 10}.${tenths % 10}s"
val seconds = (ms / 1000).coerceAtLeast(60)
val minutes = seconds / 60
return if (minutes < 60) {
String.format(Locale.ROOT, "%dm %02ds", minutes, seconds % 60)
} else {
String.format(Locale.ROOT, "%dh %02dm", minutes / 60, minutes % 60)
}
}
/**
* How a reply ended, when it did not finish (`display.md` §4): the `stopped` or `failed` progress
* whose line stays on it. From the row's own `end` (spec 3.7.0: the phase and the reason, stored
* with the reply); from an older server, the end the stream said (kept on the message as its
* `progress`), else what the row knows -- that it was stopped, or its error, of which the first
* line is the reason. Null for a reply that
* finished, a user's message, or one still queued.
*/
fun Message.ending(): Progress? = when {
role != "assistant" -> null
// What the server stored with the reply (spec 3.7.0): it stays true after a reload.
end?.phase in END_PHASES -> Progress(phase = end?.phase.orEmpty(), reason = end?.reason?.ifBlank { null })
progress?.phase in END_PHASES -> progress
!error.isNullOrBlank() -> Progress(phase = "failed", reason = error.lineSequence().firstOrNull { it.isNotBlank() }?.trim())
stopped -> Progress(phase = "stopped")
else -> null
}
/**
* A count a person reads, in [locale]'s own format -- its grouping and its decimal mark
* (`display.md` §6): `12,480`, `12 480`, `12.480`. [Locale.ROOT] is the spec's plain format, no
* grouping and `.`, which is what its conformance texts are written in.
*/
fun localeNumber(n: Long, locale: Locale): String = if (locale == Locale.ROOT) n.toString() else NumberFormat.getIntegerInstance(locale).format(n)
/** A measure with [decimals] places, in [locale]'s format; plain for [Locale.ROOT]. */
fun localeNumber(n: Double, decimals: Int, locale: Locale): String {
if (locale == Locale.ROOT) return String.format(Locale.ROOT, "%.${decimals}f", n)
val format = NumberFormat.getNumberInstance(locale)
format.minimumFractionDigits = decimals
format.maximumFractionDigits = decimals
format.roundingMode = java.math.RoundingMode.HALF_UP
return format.format(n)
}
/** How a message is drawn in the transcript. */
enum class Drawn {
/** The person's own words: their bubble. */
Person,
/** The model's reply. */
Reply,
/** A line the server wrote in the person's place (`machine`): a quiet note, never their bubble. */
Note,
/** Not drawn at all. */
Hidden,
}
/**
* How [message] is drawn. A `user` row the server wrote itself (`machine`: a schedule's
* instruction, the line that opens a report's conversation) is not something the person said,
* so it is never their bubble: a quiet note -- and in a report's conversation ([reportChat]) the
* [first] such line, which only tells the model what the conversation continues, is left out,
* since the report itself is one tap back.
*/
fun drawn(message: Message, first: Boolean, reportChat: Boolean): Drawn = when {
!message.isUser -> Drawn.Reply
!message.machine -> Drawn.Person
reportChat && first -> Drawn.Hidden
else -> Drawn.Note
}
@@ -17,15 +17,23 @@ data class LiveReply(
val status: String = "",
/** The structured progress beside [status] (spec 3.4.0); null from an older server, or idle. */
val progress: Progress? = null,
/** How the turn ended when it did not finish: the last `stopped` or `failed` progress, with its reason. */
val end: Progress? = null,
val cards: List<Card> = emptyList(),
val jobs: List<Job> = emptyList(),
/** The subagent tree (spec 3.4.0), from the `tree` frame; null until there is one. */
val tree: SubagentTree? = null,
val metrics: Metrics? = null,
val steered: Set<String> = emptySet(),
/** Set by `done`: the finished row, which replaces this in the transcript. */
/**
* Set by `done`: the finished row, which replaces this in the transcript. `done` is the end
* of the reply -- the stream may stay open after it for one `title` frame, which nobody
* waits for.
*/
val finished: Message? = null,
val title: String? = null,
/** From `done`: a model is still naming the chat, so [title] is the one made from the prompt. */
val titlePending: Boolean = false,
/** A queued prompt the server started when this reply ended: the next stream to follow. */
val next: String? = null,
val closed: Boolean = false,
@@ -49,7 +57,9 @@ data class LiveReply(
"plan" -> copy(plan = decodePlan(data))
"status" -> decode(StatusFrame.serializer(), data)?.let { copy(status = it.text, progress = it.progress) } ?: this
"status" -> decode(StatusFrame.serializer(), data)?.let { frame ->
copy(status = frame.text, progress = frame.progress, end = frame.progress?.takeIf { it.phase in END_PHASES })
} ?: this
"ask" -> decode(AskFrame.serializer(), data)?.let { copy(cards = it.cards) } ?: this
@@ -59,10 +69,26 @@ data class LiveReply(
"metrics" -> decode(Metrics.serializer(), data)?.let { copy(metrics = it) } ?: this
"done" -> decode(DoneFrame.serializer(), data)?.let {
copy(finished = it.message, title = it.chat.title.ifEmpty { null }, next = it.next, cards = emptyList(), status = "", progress = null)
"done" -> decode(DoneFrame.serializer(), data)?.let { done ->
// The finished row says that it was stopped or failed; the stream said why (by you,
// the step limit, the budget). The reason goes with the row, where its line stays
// (display.md §4).
val row = done.message
val ended = row.stopped || !row.error.isNullOrBlank()
copy(
finished = if (ended && row.progress == null && end != null) row.copy(progress = end) else row,
title = done.chat.title.ifEmpty { null },
titlePending = done.chat.titlePending,
next = done.next,
cards = emptyList(),
status = "",
progress = null,
)
} ?: this
// After `done`, when a model has named the chat: the name, and nothing else changes.
"title" -> decode(TitleFrame.serializer(), data)?.let { named -> copy(title = named.chat.title.ifEmpty { title }, titlePending = false) } ?: this
"close" -> copy(closed = true)
else -> this
@@ -222,7 +222,26 @@ data class SearchResults(
/** One app release the server recommends (`GET /api/v2/apps`), with the page its files are on. */
@Serializable
data class AppRelease(val version: String = "", val tag: String = "", val channel: String = "", val page: String = "")
data class AppRelease(
val version: String = "",
val tag: String = "",
val channel: String = "",
val page: String = "",
/** The release's other builds, for an updater that installs its own kind: `{url, sha256}` each, where the server knows them. */
val notifications: AppBuild? = null,
val fdroid: AppBuild? = null,
)
/** One APK of a release: where it is and its SHA-256. */
@Serializable
data class AppBuild(val url: String = "", val sha256: String = "")
/** What `@` offers from the server (`GET /api/v2/mentions`): an earlier `attachment` by [id], a `file` of the tree by [path], or a `url`. */
@Serializable
data class Mention(val kind: String = "", val id: String = "", val path: String = "", val url: String = "", val name: String = "", val detail: String = "")
@Serializable
data class Mentions(val items: List<Mention> = emptyList())
@Serializable
data class ServerChannel(val version: String = "", val channel: String = "")
@@ -295,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,
@@ -302,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) {
@@ -355,8 +384,23 @@ data class Metrics(
@SerialName("tok_s") val tokPerSecond: Double = 0.0,
)
/**
* How a call is drawn (`display.md`): its [kind], the one short [title], the facts after it as
* [chips] (an edit's `+N −M`, a non-zero `exit N`, the hits), and from spec 3.7.0 its [state]
* (running, done, failed, denied), the [duration] of a finished call as the spec writes it, and
* the tool's name as a person reads it ([label]). The last three are empty from an older server.
*/
@Serializable
data class ToolBlock(val kind: String = "tool", val title: String = "", val chips: List<String> = emptyList(), val added: Int = 0, val removed: Int = 0)
data class ToolBlock(
val kind: String = "tool",
val title: String = "",
val chips: List<String> = emptyList(),
val added: Int = 0,
val removed: Int = 0,
val state: String = "",
val duration: String = "",
val label: String = "",
)
/** One tool call. What the tool wrote varies by tool, so the free-form parts stay JSON. */
@Serializable
@@ -376,6 +420,8 @@ data class ToolCall(
val diff: String? = null,
val exit: Int? = null,
val hits: Int? = null,
/** How long the call took, in milliseconds (spec 3.7.0: `tool_end`'s `ms`); null where it was not kept. */
val ms: Long? = null,
val path: String? = null,
val truncated: Boolean = false,
val job: JsonElement? = null,
@@ -476,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,
@@ -485,10 +531,32 @@ data class Step(
val text: String? = null,
val label: String? = null,
val markdown: String? = null,
/** A `page` step's title (spec 3.8.0): the page itself is not sent to a client that does not draw it. */
val title: String? = null,
/** A `text` step's pages (spec 3.8.0): where it has any, [text] is its markdown with each page as the one line `[page: Title]`. */
val pages: List<StepPage> = emptyList(),
val calls: List<ToolCall> = emptyList(),
val messages: List<SteerNote> = emptyList(),
)
/**
* A reply's end when it did not finish: `stopped` with `person`, `steps`, `budget` or no reason,
* or `failed` with the error's first line. [text] is the line in the account's language; the app
* writes its own from [phase] and [reason], in the app's language.
*/
@Serializable
data class MessageEnd(val phase: String = "", val reason: String = "", val text: String = "")
/** A page in a reply's text: its title (the page itself is fetched by its digest, by a client that draws pages). */
@Serializable
data class StepPage(val title: String = "", val digest: String = "")
/**
* What a client that draws no pages shows of a `text` step: the server's own text where the step
* has pages (each page its one line), else the markdown as it is.
*/
val Step.shownMarkdown: String get() = text?.takeIf { pages.isNotEmpty() && it.isNotBlank() } ?: markdown.orEmpty()
@Serializable
data class Message(
val id: String,
@@ -497,6 +565,8 @@ data class Message(
val complete: Boolean = true,
val stopped: Boolean = false,
val error: String? = null,
/** How a reply that did not finish ended (spec 3.7.0); null for one that finished, or from an older server. */
val end: MessageEnd? = null,
val queued: Boolean = false,
val machine: Boolean = false,
val origin: String = "",
@@ -538,12 +608,19 @@ data class CardItem(
val options: List<Option> = emptyList(),
val multiple: Boolean = false,
@SerialName("free_text") val freeText: Boolean = true,
/** An approval: whether "Always allow" is offered beside "Allow once" (spec 3.7.0). An older server says nothing, and offered it always. */
val always: Boolean = true,
val editable: Boolean = false,
val plan: JsonObject? = null,
@SerialName("mode_choice") val modeChoice: Boolean = false,
val job: String = "",
/** The tree subagent asking (spec 3.4.0), for a call nobody in the tree may allow; null otherwise. */
val subagent: CardSubagent? = null,
/**
* A `phone_action` card's action (spec 3.6.0, `phone.md` §2): `action`, `summary` and the
* action's own fields, as the server checked them. Carried out by `actions/ActionRunner`.
*/
val phone: JsonObject? = null,
)
@Serializable
@@ -582,6 +659,8 @@ data class Job(
/** The answer to a card, as the page's form says it (see `api/v2/chats.py:answer`). */
@Serializable
data class CardAnswer(
/** A phone card's answer: what the phone did once the person confirmed or declined. */
val result: PhoneResult? = null,
val verdict: String = "",
val reason: String = "",
val choices: Map<String, List<String>> = emptyMap(),
@@ -589,6 +668,9 @@ data class CardAnswer(
val asks: Map<String, String> = emptyMap(),
)
@Serializable
data class PhoneResult(val status: String, val message: String = "")
@Serializable
data class PushKey(val key: String = "", val registered: Boolean = false)
@@ -625,10 +707,19 @@ data class JobsFrame(val jobs: List<Job> = emptyList())
@Serializable
data class DoneFrame(val message: Message, val chat: DoneChat = DoneChat(), val next: String? = null) {
/**
* [titlePending]: a model is still naming the chat, so [title] is the one made from the
* prompt and a `title` frame may follow before `close`. `done` is the end of the reply all
* the same.
*/
@Serializable
data class DoneChat(val id: String = "", val title: String = "")
data class DoneChat(val id: String = "", val title: String = "", @SerialName("title_pending") val titlePending: Boolean = false)
}
/** The `title` frame: the name a model gave the chat, after `done`. */
@Serializable
data class TitleFrame(val chat: DoneFrame.DoneChat = DoneFrame.DoneChat())
/** The push payload the server sends (services/push.py), as the app reads it. */
@Serializable
data class PushPayload(
@@ -648,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(),
@@ -36,7 +36,7 @@ data class Progress(
) {
companion object {
/** `loop.json` `progress.no_elapsed`: drawn as their text alone. */
val NO_ELAPSED = setOf("stopped", "failed")
val NO_ELAPSED = END_PHASES
}
}
@@ -51,14 +51,16 @@ fun interface ProgressWords {
}
/**
* The phase's text, its fields filled (`progress.md` §2): numbers as integers, a rate with one
* decimal in [locale]'s format, `retrying`'s `in` counted down to [now]. Null for a phase this
* app does not know -- a newer server's -- so the caller falls back to the `status` text.
* The phase's text, its fields filled (`progress.md` §2): every count and measure in [locale]'s
* own number format (`display.md` §6: the phone's grouping and decimal mark; [Locale.ROOT] is the
* spec's plain format), a title that had to be cut ending in `…`, `retrying`'s `in` counted down
* to [now]. Null for a phase this app does not know -- a newer server's -- so the caller falls
* back to the `status` text.
*/
fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Locale = Locale.getDefault()): String? {
val p = progress
return when (p.phase) {
"queued" -> if (p.ahead != null) words.text("queued_ahead", "${p.ahead}") else words.text("queued")
"queued" -> if (p.ahead != null) words.text("queued_ahead", localeNumber(p.ahead.toLong(), locale)) else words.text("queued")
"waiting_for_model" -> {
val model = p.model ?: return null
@@ -72,7 +74,8 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
val done = p.done
val total = p.total
if (done != null && total != null && total > 0) {
words.text("reading_prompt", "$done", "$total", "${done.toLong() * 100 / total}")
val percent = localeNumber(done.toLong() * 100 / total, locale)
words.text("reading_prompt", localeNumber(done.toLong(), locale), localeNumber(total.toLong(), locale), percent)
} else {
words.text("reading_prompt_bare")
}
@@ -80,11 +83,13 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
"thinking" -> words.text("thinking")
"writing" -> p.rate?.let { words.text("writing", String.format(locale, "%.1f", it)) } ?: words.text("writing_bare")
"writing" -> p.rate?.let { words.text("writing", localeNumber(it, 1, locale)) } ?: words.text("writing_bare")
"running_tool" -> {
val tool = p.tool ?: return null
if (!p.what.isNullOrBlank()) words.text("running_tool", tool, p.what.take(80)) else words.text("running_tool_bare", tool)
// The call's short title (display.md §1): one line, and `…` where it had to be cut.
val what = shortTitle(p.what)
if (what != null) words.text("running_tool", tool, what) else words.text("running_tool_bare", tool)
}
"waiting_for_person" -> {
@@ -96,7 +101,7 @@ fun progressText(progress: Progress, words: ProgressWords, now: Long, locale: Lo
words.text("waiting_for_person", what)
}
"waiting_for_subagents" -> words.text("waiting_for_subagents", "${p.running ?: 0}")
"waiting_for_subagents" -> words.text("waiting_for_subagents", localeNumber((p.running ?: 0).toLong(), locale))
"compacting" -> words.text("compacting")
@@ -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,17 +3,36 @@ package eu.llembas.android.assist
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import eu.llembas.android.R
/** A Quick Settings tile that opens the assistant's sheet: one more way in besides the power button. */
/**
* A Quick Settings tile that opens the assistant's sheet: one more way in besides the power
* button. It is a button, not a switch -- always shown as ready (`STATE_INACTIVE`), never as
* "on", and the system's default (`STATE_UNAVAILABLE` on some phones until the first update)
* would grey it out. Over the lock screen the sheet opens there and asks to unlock before it
* sends anything, as from any other way in.
*/
class AskTileService : TileService() {
override fun onStartListening() {
super.onStartListening()
qsTile?.apply {
state = Tile.STATE_INACTIVE
label = getString(R.string.tile_ask)
updateTile()
}
}
@android.annotation.SuppressLint("StartActivityAndCollapseDeprecated")
override fun onClick() {
super.onClick()
val intent = Intent(this, AssistActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= 34) {
// Android 14 refuses the Intent overload; the PendingIntent one is the way now.
startActivityAndCollapse(PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE))
startActivityAndCollapse(
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT),
)
} else {
@Suppress("DEPRECATION")
startActivityAndCollapse(intent)
@@ -2,8 +2,11 @@ package eu.llembas.android.assist
import android.Manifest
import android.app.KeyguardManager
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.SystemClock
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
@@ -16,6 +19,37 @@ 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 java.lang.ref.WeakReference
/** What a way into the sheet asks for. */
enum class Opening {
Sheet,
Listen,
Continue,
;
companion object {
/**
* A headset's voice button sends `VOICE_COMMAND` (or, locked, `VOICE_SEARCH_HANDS_FREE`):
* the person means to speak, so the sheet opens listening whatever Settings says.
*/
fun of(intent: Intent): Opening = when {
intent.getBooleanExtra(AssistActivity.EXTRA_LISTEN, false) -> Listen
intent.action == AssistActivity.ACTION_CONTINUE -> Continue
intent.action in LISTENING -> Listen
else -> Sheet
}
private val LISTENING = setOf(
AssistActivity.ACTION_LISTEN,
Intent.ACTION_VOICE_COMMAND,
"android.speech.action.VOICE_SEARCH_HANDS_FREE",
)
}
}
/**
* The assistant as an activity: what the Quick Settings tile, the "Ask" shortcut and a plain
@@ -27,6 +61,9 @@ import eu.llembas.android.ui.theme.LembasTheme
*/
class AssistActivity : ComponentActivity() {
private lateinit var controller: AssistController
private lateinit var keyguard: KeyguardManager
private var started = false
private var byWake = false
/** Whether the phone is locked: the sheet shows nothing from the account until it is not. */
private val locked = mutableStateOf(false)
@@ -41,31 +78,12 @@ class AssistActivity : ComponentActivity() {
super.onCreate(savedInstanceState)
setShowWhenLocked(true)
controller = AssistController(this, lifecycleScope)
val keyguard = getSystemService(KeyguardManager::class.java)
keyguard = getSystemService(KeyguardManager::class.java)
locked.value = keyguard.isKeyguardLocked
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
val wantsMic = intent.getBooleanExtra(EXTRA_LISTEN, false)
if (keyguard.isKeyguardLocked) {
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
if (waiting.isNotBlank()) controller.ask(waiting) else controller.opened(locked = false)
}
override fun onDismissCancelled() = finish()
override fun onDismissError() = finish()
},
)
} else if (waiting.isNotBlank()) {
controller.ask(waiting)
} else if (wantsMic && !controller.micAllowed()) {
mic.launch(Manifest.permission.RECORD_AUDIO)
} else {
controller.opened(locked = false)
}
// Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch,
// so nothing else has woken the phone).
woken(intent)
take(intent)
setContent {
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
LembasTheme(prefs.theme) {
@@ -94,6 +112,85 @@ class AssistActivity : ComponentActivity() {
}
}
/** Opened again while it is up -- the headset's button pressed twice, the tile again, the wake word. */
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
woken(intent)
// The same sheet answers again: it is up, and whoever asked for it is told so.
if (started) AssistLink.sheetShown(SystemClock.elapsedRealtime())
take(intent)
}
/**
* Opened by the wake word: the screen comes on with it (a spoken phrase is not a touch, so
* nothing else has woken the phone), and the sheet is remembered as the wake word's, so that
* the assistant's own sheet can take its place if that one comes after all.
*/
private fun woken(intent: Intent?) {
byWake = 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
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, 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.
*/
private fun take(intent: Intent) {
val opening = Opening.of(intent)
val waiting = intent.getStringExtra(EXTRA_QUESTION).orEmpty()
val go = {
when {
waiting.isNotBlank() -> controller.ask(waiting)
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)
}
}
if (keyguard.isKeyguardLocked) {
keyguard.requestDismissKeyguard(
this,
object : KeyguardManager.KeyguardDismissCallback() {
override fun onDismissSucceeded() {
locked.value = false
go()
}
override fun onDismissCancelled() = finish()
override fun onDismissError() = finish()
},
)
} else {
go()
}
}
override fun onDestroy() {
controller.close()
super.onDestroy()
@@ -104,5 +201,32 @@ class AssistActivity : ComponentActivity() {
/** Handed over by the session: ask for the microphone, then listen. */
const val EXTRA_LISTEN = "eu.llembas.android.LISTEN"
/** Open listening: the widget's microphone and the Speak shortcut. */
const val ACTION_LISTEN = "eu.llembas.android.action.LISTEN"
/** Open at the last chat the assistant made: the widget and the shortcut. */
const val ACTION_CONTINUE = "eu.llembas.android.action.CONTINUE"
/** The sheet, listening. */
fun listening(context: Context): Intent = 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)
}
}
@@ -9,12 +9,17 @@ import android.speech.SpeechRecognizer
import androidx.core.content.ContextCompat
import eu.llembas.android.MainActivity
import eu.llembas.android.R
import eu.llembas.android.api.ApiClient
import eu.llembas.android.api.ApiException
import eu.llembas.android.api.Card
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.ModelInfo
import eu.llembas.android.api.Step
import eu.llembas.android.api.StreamClient
import eu.llembas.android.lembas
import eu.llembas.android.notify.NotificationAccess
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import kotlinx.coroutines.CoroutineScope
@@ -24,10 +29,12 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.transformWhile
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import java.io.ByteArrayOutputStream
@@ -71,6 +78,13 @@ data class AssistUiState(
val speaking: Boolean = false,
/** Whether anything can turn speech into words: the instance's speech-to-text, or the phone's. */
val canListen: Boolean = true,
/**
* A spoken conversation: after each spoken answer is read aloud, the sheet listens again --
* until the person says stop, taps End, types, or says nothing.
*/
val conversation: Boolean = false,
/** Whether the person let the assistant read the notifications when asked (Settings and Android both). */
val canReadNotifications: Boolean = false,
) {
val screenAvailable: Boolean get() = screenText || screenshot != null
val modelInfo: ModelInfo? get() = models.firstOrNull { it.id == modelId }
@@ -94,6 +108,9 @@ interface AssistActions {
fun voiceReply(on: Boolean) {}
fun readAloud() {}
fun stopReading() {}
fun endConversation() {}
fun summariseNotifications() {}
fun answerCard(card: Card, answer: CardAnswer) {}
}
/**
@@ -116,6 +133,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
private val recorder = Recorder(scope)
private val phone = PhoneRecognizer(context)
private val speaker = Speaker(context)
private val route = HeadsetRoute(context)
private var following: Job? = null
private var hearing: Job? = null
private var usingPhone = false
@@ -138,6 +156,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
signedIn = instance != null,
instanceName = instance?.name?.ifBlank { instance.base }.orEmpty(),
voiceReply = prefs.readAloudSpoken,
canReadNotifications = prefs.notificationSummaries && NotificationAccess.granted(context),
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
)
@@ -168,14 +187,25 @@ 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).
* 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.
*/
fun opened(locked: Boolean) {
fun opened(locked: Boolean, listen: Boolean = false) {
scope.launch {
ready.join()
val prefs = context.lembas.instances.prefs.first()
val s = _state.value
if (s.signedIn && !locked && prefs.assistantListens && s.canListen && s.empty && !s.listening && micAllowed()) listen()
if (s.signedIn && !locked && (listen || prefs.assistantListens) && s.canListen && !s.listening && micAllowed()) {
if (listen || s.empty) listen()
}
}
}
/** 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)
}
}
@@ -204,13 +234,15 @@ class AssistController(private val context: Context, private val scope: Coroutin
_state.update { it.copy(listening = true, heard = "", level = 0f, error = null) }
hearing = scope.launch {
usingPhone = phoneEngine()
// A headset's microphone when one is there: the conversation can go on in the ear.
val headset = route.microphone()
if (usingPhone) {
phone.start(
onPartial = { words -> _state.update { it.copy(heard = words) } },
onLevel = { l -> _state.update { it.copy(level = l) } },
onResult = { words ->
_state.update { it.copy(listening = false, level = 0f, heard = "") }
if (words.isNotBlank()) ask(words, spoken = true)
if (words.isNotBlank()) askOrStop(words) else endConversation()
},
onFail = { code ->
val quiet = code == SpeechRecognizer.ERROR_NO_MATCH || code == SpeechRecognizer.ERROR_SPEECH_TIMEOUT
@@ -218,12 +250,14 @@ class AssistController(private val context: Context, private val scope: Coroutin
it.copy(
listening = false,
level = 0f,
conversation = false,
error = if (quiet) null else context.getString(R.string.assist_recogniser_failed),
)
}
},
)
} else {
recorder.preferred = headset
recorder.start()
launch { recorder.level.collect { l -> _state.update { it.copy(level = l) } } }
launch { writeDownAsSaid() }
@@ -306,20 +340,33 @@ class AssistController(private val context: Context, private val scope: Coroutin
_state.update { it.copy(busy = true) }
val text = context.lembas.instances.client()?.transcribe(wav).orEmpty()
_state.update { it.copy(busy = false, heard = "") }
if (text.isNotBlank()) ask(text, spoken = true)
if (text.isNotBlank()) askOrStop(text) else endConversation()
} catch (e: Exception) {
_state.update { it.copy(busy = false, heard = "", error = context.explain(e)) }
}
}
}
/** Stop listening and keep nothing: the person would rather type. */
/**
* Stop listening and keep nothing: the person would rather type -- or said nothing at all.
* Either ends a spoken conversation.
*/
override fun type() {
hearing?.cancel()
hearing = null
phone.stop()
scope.launch { recorder.stop() }
_state.update { it.copy(listening = false, heard = "", level = 0f) }
_state.update { it.copy(listening = false, heard = "", level = 0f, conversation = false) }
}
/** What was said: in a conversation, "stop" (or the like) ends it; anything else is asked. */
private fun askOrStop(words: String) {
val phrases = context.getString(R.string.assist_stop_words).split("|")
if (_state.value.conversation && isStopPhrase(words, phrases)) endConversation() else ask(words, spoken = true)
}
override fun endConversation() {
_state.update { it.copy(conversation = false) }
}
// --- Asking ------------------------------------------------------------------------------
@@ -331,13 +378,20 @@ class AssistController(private val context: Context, private val scope: Coroutin
ask(prompt, spoken = false)
}
fun ask(question: String, spoken: Boolean) {
/** 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)
fun ask(question: String, spoken: Boolean, notifications: Boolean = false) {
if (question.isBlank()) return
if (_state.value.listening) type()
following?.cancel()
following = scope.launch {
val turn = AssistTurn(question)
_state.update { it.copy(busy = true, turns = it.turns + turn, error = null) }
// A spoken question, answered aloud, opens a conversation (Settings › Assistant).
val talking = spoken && context.lembas.instances.prefs.first().assistantConversation &&
_state.value.voiceReply && _state.value.canSpeak
_state.update { it.copy(conversation = talking) }
try {
val store = context.lembas.instances
val api = store.client() ?: throw ApiException(401, "Not signed in.")
@@ -347,7 +401,19 @@ class AssistController(private val context: Context, private val scope: Coroutin
val attachments = buildList {
if (withScreen) now.screenshot?.let { shot -> add(api.upload("screen.png", "image/png", png(shot), now.chatId).id) }
}
val text = if (withScreen && screenText != null) "$question\n\n---\nOn my screen:\n\n$screenText" else question
// The notifications, when asked for by the chip or by name ("my notifications") --
// read now, only while unlocked (NotificationAccess.read), and for this question only.
val phrases = context.getString(R.string.assist_notifications_phrases).split("|")
val notices = if (now.canReadNotifications && (notifications || NotificationReader.asksAbout(question, phrases))) {
NotificationReader.asText(NotificationAccess.read(context)).ifBlank { NO_NOTIFICATIONS }
} else {
null
}
val text = buildString {
append(question)
if (withScreen && screenText != null) append("\n\n---\nOn my screen:\n\n$screenText")
if (notices != null) append("\n\n---\nMy notifications:\n\n$notices")
}
// The screen goes with one question, not every one after it.
_state.update { it.copy(includeScreen = false) }
val chatId = now.chatId
@@ -369,19 +435,55 @@ class AssistController(private val context: Context, private val scope: Coroutin
}
}
var live = LiveReply(replyId)
StreamClient(api).follow(inChat, replyId).collect { frame ->
// To `done`, which is the end of the reply: the stream may stay open after it for
// the chat's name, and a spoken answer must not wait for that.
StreamClient(api).follow(inChat, replyId).transformWhile { frame ->
emit(frame)
frame.event != "done"
}.collect { frame ->
live = live.apply(frame.event, frame.data)
_state.update { s -> s.copy(turns = s.turns.dropLast(1) + turn.copy(reply = live), busy = live.finished == null) }
}
if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null) speak(spokenWords(live.finished?.steps.orEmpty()))
// A new chat is named by a model after `done`. The name the sheet offers the chat
// under next time is fetched in the background, for a bounded while -- never by
// holding the reply's stream open, and never before the answer is spoken.
if (live.titlePending && !prefs.assistantTemporary) nameLater(api, inChat, live.title.orEmpty())
val heardAll = if (spoken && _state.value.voiceReply && _state.value.canSpeak && live.finished != null && live.cards.isEmpty()) {
speak(spokenWords(live.finished?.steps.orEmpty()))
} else {
false
}
// The answer was heard to the end: listen for the next thing said. Stopped, a
// card waiting, or nothing to read: the conversation ends there.
if (_state.value.conversation && heardAll && micAllowed()) listen() else endConversation()
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
_state.update { it.copy(error = context.explain(e), conversation = false) }
} finally {
_state.update { it.copy(busy = false) }
}
}
}
/**
* The chat's name once a model has given it: asked for a few times over [TITLE_WAIT_MS], then
* left -- the name made from the prompt stands, and the app's list has the real one anyway.
*/
private fun nameLater(api: ApiClient, chatId: String, provisional: String) {
scope.launch {
withTimeoutOrNull(TITLE_WAIT_MS) {
while (true) {
delay(TITLE_ASK_MS)
val title = runCatching { api.chat(chatId).chat.title }.getOrNull().orEmpty()
if (title.isNotBlank() && title != provisional) {
context.lembas.instances.savePrefs { if (it.lastAssistChat == chatId) it.copy(lastAssistTitle = title.take(120)) else it }
_state.update { s -> s.copy(last = s.last?.let { l -> if (l.chatId == chatId) l.copy(title = title.take(120)) else l }) }
break
}
}
}
}
}
/** Carry on the last chat the assistant made: its last exchange shown, the next question sent to it. */
override fun continueLast() {
val last = _state.value.last ?: return
@@ -408,10 +510,25 @@ class AssistController(private val context: Context, private val scope: Coroutin
}
}
/** A phone action's card, answered in the sheet: what the phone did (spec 3.6.0). */
override fun answerCard(card: Card, answer: CardAnswer) {
val chat = _state.value.chatId ?: return
scope.launch {
try {
context.lembas.instances.client()?.answer(chat, card.id, answer)
} catch (e: ApiException) {
// First answer wins: a 409 is somebody answering elsewhere already.
if (e.status != 409) _state.update { it.copy(error = context.explain(e)) }
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
}
}
}
override fun newChat() {
following?.cancel()
speaker.stop()
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false) }
_state.update { it.copy(chatId = null, turns = emptyList(), error = null, busy = false, conversation = false) }
}
/** The model: for the chat this sheet is in, changed at once; for a new one, kept for next time. */
@@ -438,15 +555,18 @@ class AssistController(private val context: Context, private val scope: Coroutin
scope.launch { speak(spokenWords(steps)) }
}
/** Stop the voice -- and, in a conversation, the listening that would follow it. */
override fun stopReading() = speaker.stop()
private suspend fun speak(words: String) {
if (words.isBlank()) return
try {
val api = context.lembas.instances.client() ?: return
speaker.play(api.speech(words))
/** Read [words] aloud; true when they were heard to the end. */
private suspend fun speak(words: String): Boolean {
if (words.isBlank()) return false
return try {
val api = context.lembas.instances.client() ?: return false
speaker.playToEnd(api.speech(words))
} catch (e: Exception) {
_state.update { it.copy(error = context.explain(e)) }
false
}
}
@@ -461,6 +581,7 @@ class AssistController(private val context: Context, private val scope: Coroutin
hearing?.cancel()
speaker.stop()
phone.stop()
route.release()
scope.launch { recorder.stop() }
}
@@ -473,6 +594,11 @@ class AssistController(private val context: Context, private val scope: Coroutin
companion object {
const val MAX_SCREEN_CHARS = 8_000
private const val NO_NOTIFICATIONS = "(none)"
/** How long, and how often, a new chat's name is asked for after its first reply. */
private const val TITLE_WAIT_MS = 20_000L
private const val TITLE_ASK_MS = 4_000L
// Listening, 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,
@@ -2,14 +2,18 @@ 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,11 +31,15 @@ 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.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
/**
@@ -41,7 +49,79 @@ import kotlinx.coroutines.runBlocking
* there is no hotword here -- Android keeps always-on hotword detection for the system's own
* preinstalled assistant (`CAPTURE_AUDIO_HOTWORD` is a privileged permission).
*/
class LembasAssistService : VoiceInteractionService()
class LembasAssistService : VoiceInteractionService() {
override fun onCreate() {
super.onCreate()
AssistLink.created(System.currentTimeMillis())
}
override fun onReady() {
super.onReady()
current = this
// When Android connected it is kept: the wake word's record says whether it was, and an
// attempt that found it not connected is told that it came later.
val now = System.currentTimeMillis()
AssistLink.ready(now)
Log.i(TAG, "assistant service connected by Android")
background.launch { runCatching { lembas.instances.savePrefs { it.copy(wakeLog = wakeLogConnected(it.wakeLog, now)) } } }
}
override fun onShutdown() {
// Only the instance that is the current one disconnects it: an old one going away late
// must not say "not connected" over a new one.
if (current === this) {
current = null
AssistLink.shutdown(System.currentTimeMillis())
}
Log.i(TAG, "assistant service disconnected by Android")
super.onShutdown()
}
override fun onDestroy() {
AssistLink.destroyed(System.currentTimeMillis())
super.onDestroy()
}
/** Android 14+: Android is about to show a session it was asked for -- or, below, could not. Kept for the wake word's record. */
override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
AssistLink.prepared(SystemClock.elapsedRealtime())
super.onPrepareToShowSession(args, showFlags)
}
override fun onShowSessionFailed(args: Bundle) {
AssistLink.showFailed(SystemClock.elapsedRealtime())
Log.w(TAG, "Android could not show the assistant's session")
super.onShowSessionFailed(args)
}
companion object {
/**
* The service while the system has it bound -- while LLeMbas is the phone's assistant. The
* wake word opens the sheet through it ([showSession]), which Android allows from the
* background, as it does for the power button.
*/
@Volatile
var current: LembasAssistService? = null
private set
private const val TAG = "LLeMbasWake"
private val background = CoroutineScope(SupervisorJob() + Dispatchers.Default)
/**
* Whether Android itself uses this service as its voice-interaction service right now.
* Holding the assistant role is not the same: Android keeps the service only while a
* speech recogniser is set that it accepts, and resets it at start-up otherwise -- the
* long press then opens the assistant as an ordinary screen, and nothing is connected
* that could open it from the background.
*/
fun isActive(context: Context): Boolean =
runCatching { VoiceInteractionService.isActiveService(context, ComponentName(context, LembasAssistService::class.java)) }.getOrDefault(false)
/** Whether Android says LLeMbas holds the assistant role (Settings › Default apps › Digital assistant app). */
fun holdsRole(context: Context): Boolean =
runCatching { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_ASSISTANT) }.getOrNull() ?: false
}
}
class LembasAssistSessionService : VoiceInteractionSessionService() {
override fun onNewSession(args: Bundle?): VoiceInteractionSession = LembasAssistSession(this)
@@ -61,6 +141,9 @@ 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
override val lifecycle: Lifecycle get() = registry
override val savedStateRegistry: SavedStateRegistry get() = saved.savedStateRegistry
@@ -109,7 +192,18 @@ class LembasAssistSession(context: Context) :
override fun onShow(args: Bundle?, showFlags: Int) {
super.onShow(args, showFlags)
registry.currentState = Lifecycle.State.RESUMED
controller.opened(locked())
// 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.
controller.opened(locked(), listen = args?.getBoolean(AssistActivity.EXTRA_LISTEN) == true)
}
/**
@@ -119,6 +213,10 @@ class LembasAssistSession(context: Context) :
*/
override fun onHide() {
super.onHide()
if (up) {
up = false
AssistPresence.hidden()
}
controller.close()
scope.cancel()
scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
@@ -42,10 +42,12 @@ import androidx.compose.material.icons.automirrored.filled.VolumeOff
import androidx.compose.material.icons.automirrored.filled.VolumeUp
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.EditNote
import androidx.compose.material.icons.filled.Forum
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Keyboard
import androidx.compose.material.icons.filled.Lightbulb
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.ScreenshotMonitor
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Summarize
@@ -89,6 +91,7 @@ import androidx.compose.ui.unit.dp
import eu.llembas.android.R
import eu.llembas.android.ui.ModelAvatar
import eu.llembas.android.ui.ProgressStatus
import eu.llembas.android.ui.chat.PhoneCard
import eu.llembas.android.ui.chat.Steps
import eu.llembas.android.ui.progressLineOf
import eu.llembas.android.ui.theme.LocalPalette
@@ -276,6 +279,7 @@ fun ColumnScope.AssistSheetContent(
// The foot.
Column(Modifier.fillMaxWidth().padding(start = 12.dp, end = 12.dp, top = 4.dp, bottom = 12.dp)) {
if (state.conversation && !locked) Conversation(actions)
if (state.screenAvailable && !locked) ScreenToggle(state, actions)
if (state.listening) {
Listening(state, onDone = actions::heard, onType = actions::type)
@@ -441,9 +445,13 @@ private fun Starting(state: AssistUiState, actions: AssistActions, locked: Boole
QuickAction(Icons.Filled.Lightbulb, stringResource(R.string.assist_quick_explain)) { actions.quick(explain) }
}
}
// The notifications, read only now that it is asked, and never over the lock screen.
if (state.canReadNotifications && !locked) {
QuickAction(Icons.Filled.Notifications, stringResource(R.string.assist_notifications)) { actions.summariseNotifications() }
}
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(stringResource(R.string.assist_help), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
Text(stringResource(R.string.assist_no_wake_word), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
Text(stringResource(R.string.assist_wake_word_hint), style = MaterialTheme.typography.bodySmall, color = palette.inkFaint)
}
}
@@ -474,6 +482,11 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
val reply = turn.reply
val drawsProgress = reply != null && (progressLineOf(reply.progress) != null || reply.status.isNotBlank())
when {
// A phone action is confirmed here, where the phone is; any other card in the app.
reply != null && reply.cards.any { it.kind == "phone_action" } -> reply.cards.first { it.kind == "phone_action" }.let { card ->
PhoneCard(card) { answer -> actions.answerCard(card, answer) }
}
reply != null && reply.cards.isNotEmpty() -> TextButton(onClick = onOpenApp) { Text(stringResource(R.string.assist_answer_in_app)) }
turn.writing && drawsProgress -> ProgressStatus(reply?.progress, reply?.status.orEmpty(), MaterialTheme.typography.labelSmall, palette.inkFaint)
@@ -498,6 +511,28 @@ private fun Turn(turn: AssistTurn, last: Boolean, state: AssistUiState, actions:
}
}
/**
* A spoken conversation is on: the sheet will listen again after the answer is read. Says so,
* and how it ends -- End here, "stop" said, or silence. The words give; End keeps its size.
*/
@Composable
private fun Conversation(actions: AssistActions) {
val palette = LocalPalette.current
Surface(shape = RoundedCornerShape(16.dp), color = palette.accentSoft, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
Row(Modifier.padding(start = 14.dp, end = 4.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.Forum, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
Spacer(Modifier.width(12.dp))
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.assist_conversation), style = MaterialTheme.typography.labelLarge, color = palette.accent)
Text(stringResource(R.string.assist_conversation_line), style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
}
TextButton(onClick = actions::endConversation, modifier = Modifier.heightIn(min = 48.dp)) {
Text(stringResource(R.string.assist_conversation_end))
}
}
}
}
/** Use screen: off every time the sheet opens; on, the screen goes with the next question only. */
@Composable
private fun ScreenToggle(state: AssistUiState, actions: AssistActions) {
@@ -5,7 +5,9 @@ import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioDeviceInfo
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.MediaPlayer
import android.media.MediaRecorder
@@ -17,6 +19,7 @@ import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.annotation.RequiresPermission
import eu.llembas.android.auth.Prefs
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
@@ -56,6 +59,9 @@ class Recorder(private val scope: CoroutineScope) {
/** How many seconds have been recorded. */
val seconds: Float get() = pcm.size() / (RATE * 2f)
/** The microphone to prefer -- a headset's, while one is the route ([HeadsetRoute]). */
var preferred: AudioDeviceInfo? = null
@RequiresPermission(Manifest.permission.RECORD_AUDIO)
fun start() {
if (record != null) return
@@ -69,6 +75,7 @@ class Recorder(private val scope: CoroutineScope) {
maxOf(min, RATE),
)
record = audio
preferred?.let { audio.setPreferredDevice(it) }
audio.startRecording()
job = scope.launch(Dispatchers.IO) {
val buffer = ByteArray(maxOf(min, 4096))
@@ -143,11 +150,15 @@ class Speaker(private val context: Context) {
private val _playing = MutableStateFlow(false)
val playing: StateFlow<Boolean> = _playing.asStateFlow()
private var ended: CompletableDeferred<Boolean>? = null
suspend fun play(mp3: ByteArray) {
stop()
val file = withContext(Dispatchers.IO) {
File.createTempFile("reply", ".mp3", context.cacheDir).apply { writeBytes(mp3) }
}
val done = CompletableDeferred<Boolean>()
ended = done
player = MediaPlayer().apply {
setAudioAttributes(
AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_ASSISTANT)
@@ -159,6 +170,7 @@ class Speaker(private val context: Context) {
file.delete()
player = null
_playing.value = false
done.complete(true)
}
prepare()
start()
@@ -166,6 +178,12 @@ class Speaker(private val context: Context) {
_playing.value = true
}
/** Play [mp3] and wait: true when it was heard to the end, false when it was stopped. */
suspend fun playToEnd(mp3: ByteArray): Boolean {
play(mp3)
return ended?.await() ?: false
}
fun stop() {
player?.runCatching {
stop()
@@ -173,9 +191,58 @@ class Speaker(private val context: Context) {
}
player = null
_playing.value = false
ended?.complete(false)
ended = null
}
}
/**
* A headset's microphone for the assistant, while one is connected: a Bluetooth headset is
* made the communication device (Android 12+), so the sheet hears the headset and answers into
* it, as a call would; a wired headset's microphone is the default anyway. [release] gives the
* route back. Nothing happens without a headset.
*/
class HeadsetRoute(context: Context) {
private val audio = context.getSystemService(AudioManager::class.java)
private var engaged = false
/** The headset's microphone, if there is one -- made the route first where that is needed. */
fun microphone(): AudioDeviceInfo? {
val inputs = audio?.getDevices(AudioManager.GET_DEVICES_INPUTS).orEmpty()
val wired = inputs.firstOrNull { it.type == AudioDeviceInfo.TYPE_WIRED_HEADSET || it.type == AudioDeviceInfo.TYPE_USB_HEADSET }
if (wired != null) return wired
if (Build.VERSION.SDK_INT < 31 || audio == null) return null
val headset = audio.availableCommunicationDevices.firstOrNull {
it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO || it.type == AudioDeviceInfo.TYPE_BLE_HEADSET
} ?: return null
if (!engaged) engaged = runCatching { audio.setCommunicationDevice(headset) }.getOrDefault(false)
return inputs.firstOrNull { it.type == headset.type } ?: headset
}
fun release() {
if (engaged && Build.VERSION.SDK_INT >= 31) runCatching { audio?.clearCommunicationDevice() }
engaged = false
}
}
/**
* Whether [heard] is the person ending a spoken conversation: one of [phrases] ("stop", "that's
* all", in the app's language), alone or with a word or two around it ("stop please", "ok
* that's all"). A longer sentence that happens to hold "stop" is a question, not an ending.
*/
fun isStopPhrase(heard: String, phrases: List<String>): Boolean {
val said = words(heard)
if (said.isEmpty()) return false
return phrases.map(::words).filter { it.isNotEmpty() }.any { phrase ->
said.size <= phrase.size + 2 && said.windowed(phrase.size).any { it == phrase }
}
}
private fun words(text: String): List<String> = text.lowercase()
.replace(Regex("[\\u2019']"), "")
.split(Regex("[^\\p{L}\\p{N}]+"))
.filter { it.isNotBlank() }
/**
* Speech in through the phone's own recogniser, for Settings › Voice input › Phone: words as
* they are said ([start]'s `onPartial`), and the end of speech found by the recogniser.
@@ -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
@@ -85,6 +86,24 @@ data class Prefs(
val accountLanguage: String = "",
val voiceInput: String = VOICE_LEMBAS,
val assistantListens: Boolean = true,
/** After a spoken answer is read aloud, listen again: a spoken conversation. */
val assistantConversation: Boolean = true,
/** Listen for a wake word on the phone (WakeWordService). Off until the person turns it on. */
val wakeWord: Boolean = false,
/** Which of WakePhrases.all, as `greeting_name`; an id that is no phrase any more reads as the default. */
val wakePhrase: String = "hey_assistant",
/** WakeSensitivity's id: low, normal or high. */
val wakeSensitivity: String = "normal",
/** What happened the last times the wake word was heard (WakeLog): shown in Settings, nothing of the account in it. */
val wakeLog: List<WakeAttempt> = emptyList(),
/** Listen only while the screen is on. */
val wakeScreenOnly: Boolean = true,
/** The assistant may read the notifications when asked (with Android's notification access). */
val notificationSummaries: Boolean = false,
/** Phone actions' navigation app: "" whichever is installed, "google", "osmand", or "ask". */
val navApp: String = "",
/** Ask OsmAnd for the phone's position and the route's destination (allowed inside OsmAnd first). */
val osmandInfo: Boolean = false,
val assistantModel: String = "",
val lastAssistChat: String = "",
val lastAssistTitle: String = "",
@@ -0,0 +1,29 @@
package eu.llembas.android.notify
/** One notification, as the question carries it. */
data class Notice(val app: String, val title: String, val text: String, val at: Long)
/**
* Notification summaries, the half every build has: how the notifications are written into a
* question, and when a question asks for them. Reading them is [NotificationAccess]'s, which only
* the `notifications` build can do.
*/
object NotificationReader {
/** The notifications as the question's attachment of text: one block per notification. */
fun asText(notices: List<Notice>, now: Long = System.currentTimeMillis()): String = notices.joinToString("\n\n") { n ->
val minutes = ((now - n.at) / 60_000).coerceAtLeast(0)
val ago = if (minutes < 60) "${minutes}m ago" else "${minutes / 60}h ago"
listOf("[${n.app} · $ago] ${n.title}".trim(), n.text).filter { it.isNotBlank() }.joinToString("\n")
}.take(MAX_CHARS)
/**
* Whether a question asks about the notifications: one of [phrases] (in the app's language,
* "my notifications" and the like) is in it.
*/
fun asksAbout(question: String, phrases: List<String>): Boolean {
val q = question.lowercase()
return phrases.map { it.trim().lowercase() }.any { it.isNotEmpty() && it in q }
}
private const val MAX_CHARS = 12_000
}
+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
@@ -7,108 +7,131 @@ import android.os.Bundle
import android.provider.OpenableColumns
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.core.content.IntentCompat
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.AppLanguage
import eu.llembas.android.MainActivity
import eu.llembas.android.R
import eu.llembas.android.api.ApiException
import eu.llembas.android.assist.AssistSheetFrame
import eu.llembas.android.assist.LastAssist
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.push.Notifications
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.theme.LembasTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* "Share to LLeMbas": text, a link, a picture or a file from any app starts a new chat with it.
* Files are uploaded first and bound to the first message, as the composer's are.
* "Ask LLeMbas" in any app's share menu: text, a link, a picture or files. A sheet over the app
* it came from says what came in, takes a line of what to do with it, and sends it to a new chat
* or to the last chat the assistant made; files are uploaded first and bound to that message, as
* the composer's are. The chat then opens in the app. A new chat made here becomes the
* assistant's last chat, so the next share can follow it.
*/
class ShareActivity : ComponentActivity() {
private val failure = mutableStateOf<String?>(null)
class ShareActivity :
ComponentActivity(),
ShareActions {
private val state = MutableStateFlow(ShareState())
private var uris: List<Uri> = emptyList()
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
uris = when (intent.action) {
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
Intent.ACTION_SEND_MULTIPLE -> IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
else -> emptyList()
}
val text = listOfNotNull(intent.getStringExtra(Intent.EXTRA_SUBJECT), intent.getCharSequenceExtra(Intent.EXTRA_TEXT)?.toString())
.filter { it.isNotBlank() }
.distinct()
.joinToString("\n\n")
.trim()
state.update { it.copy(text = text, files = uris.map { uri -> SharedFile(nameOf(uri), (contentResolver.getType(uri) ?: "").startsWith("image/")) }) }
lifecycleScope.launch {
val store = lembas.instances
val prefs = store.prefs.first()
state.update {
it.copy(
signedIn = store.current() != null,
last = prefs.lastAssistChat.takeIf { id -> id.isNotBlank() && !prefs.assistantTemporary }
?.let { id -> LastAssist(id, prefs.lastAssistTitle, prefs.lastAssistAt) },
)
}
}
setContent {
LembasTheme {
Surface(Modifier.fillMaxSize()) {
Column(
Modifier.fillMaxSize().padding(24.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally,
) {
val error = failure.value
if (error == null) {
CircularProgressIndicator()
Text(stringResource(R.string.share_sending))
} else {
Text(error, color = MaterialTheme.colorScheme.error)
TextButton(onClick = { finish() }) { Text(stringResource(R.string.close)) }
}
val prefs by lembas.instances.prefs.collectAsState(initial = Prefs())
val shown by state.collectAsState()
LembasTheme(prefs.theme) {
AssistSheetFrame(onDismiss = ::cancel) { handle, _ -> ShareSheetContent(shown, this@ShareActivity, handle) }
}
}
}
override fun cancel() = finish()
override fun send(ask: String, toLast: Boolean) {
if (state.value.sending) return
state.update { it.copy(sending = true, error = null) }
lifecycleScope.launch {
try {
val store = lembas.instances
val api = store.client() ?: run {
startActivity(Intent(this@ShareActivity, MainActivity::class.java))
finish()
return@launch
}
val now = state.value
val into = if (toLast) now.last?.chatId else null
val files = uris.map { uri ->
val bytes = withContext(Dispatchers.IO) { contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0) }
api.upload(nameOf(uri), contentResolver.getType(uri) ?: "application/octet-stream", bytes, into).id
}
val message = shareMessage(ask, now.text, getString(R.string.share_default_prompt))
val chatId = if (into != null) {
api.sendMessage(into, message, files)
into
} else {
val prefs = store.prefs.first()
val made = api.createChat(message, files, model = prefs.assistantModel.ifBlank { null })
store.savePrefs {
it.copy(
lastAssistChat = made.chat.id,
lastAssistTitle = ask.ifBlank { now.text.ifBlank { now.files.firstOrNull()?.name.orEmpty() } }.take(120),
lastAssistAt = System.currentTimeMillis(),
)
}
made.chat.id
}
startActivity(
Intent(this@ShareActivity, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(Notifications.EXTRA_CHAT, chatId),
)
finish()
} catch (e: Exception) {
// The last chat deleted since: it is not offered again.
if (e is ApiException && e.status == 404 && toLast) {
lembas.instances.savePrefs { it.copy(lastAssistChat = "", lastAssistTitle = "", lastAssistAt = 0) }
state.update { it.copy(last = null) }
}
state.update { it.copy(sending = false, error = explain(e)) }
}
}
lifecycleScope.launch { share(intent) }
}
private suspend fun share(intent: Intent) {
try {
val api = lembas.instances.client() ?: run {
startActivity(Intent(this, MainActivity::class.java))
finish()
return
}
val text = listOfNotNull(
intent.getStringExtra(Intent.EXTRA_SUBJECT),
intent.getStringExtra(Intent.EXTRA_TEXT),
).joinToString("\n\n").trim()
val uris = when (intent.action) {
Intent.ACTION_SEND -> listOfNotNull(IntentCompat.getParcelableExtra(intent, Intent.EXTRA_STREAM, Uri::class.java))
Intent.ACTION_SEND_MULTIPLE ->
IntentCompat.getParcelableArrayListExtra(intent, Intent.EXTRA_STREAM, Uri::class.java).orEmpty()
else -> emptyList()
}
val files = uris.map { uri ->
val (name, bytes) = withContext(Dispatchers.IO) {
val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
} ?: "shared"
name to (contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: ByteArray(0))
}
api.upload(name, contentResolver.getType(uri) ?: "application/octet-stream", bytes).id
}
if (text.isBlank() && files.isEmpty()) {
finish()
return
}
val made = api.createChat(text.ifBlank { getString(R.string.share_default_prompt) }, files)
startActivity(
Intent(this, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra(Notifications.EXTRA_CHAT, made.chat.id),
)
finish()
} catch (e: Exception) {
failure.value = explain(e)
}
}
private fun nameOf(uri: Uri): String = runCatching {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
}.getOrNull() ?: uri.lastPathSegment ?: "shared"
}
@@ -0,0 +1,230 @@
package eu.llembas.android.share
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.filled.EditNote
import androidx.compose.material.icons.filled.History
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.llembas.android.R
import eu.llembas.android.assist.LastAssist
import eu.llembas.android.ui.theme.LocalPalette
/** One shared file, as the sheet names it. */
data class SharedFile(val name: String, val image: Boolean)
/** What was shared, where it may go, and how sending it went. */
data class ShareState(
val signedIn: Boolean = true,
val text: String = "",
val files: List<SharedFile> = emptyList(),
/** The last chat the assistant made, offered as the other place to send it. */
val last: LastAssist? = null,
val sending: Boolean = false,
val error: String? = null,
)
/** What the share sheet can do; nothing by default, for the screenshot tests. */
interface ShareActions {
/** Send it with [ask] (empty: the default request) to a new chat, or [toLast] to the last assistant chat. */
fun send(ask: String, toLast: Boolean) {}
fun cancel() {}
}
/**
* The share sheet's contents, from [state] alone: what came in (the text, the files by name),
* what to do with it (a line of the person's own, optional), where it goes -- a new chat, or the
* last chat the assistant made -- and Send. Rows of unknown height stack; the two choices are
* whole-row tap targets of at least 56 dp.
*/
@Composable
fun ColumnScope.ShareSheetContent(state: ShareState, actions: ShareActions, handle: Modifier = Modifier) {
val palette = LocalPalette.current
var ask by remember { mutableStateOf("") }
var toLast by remember { mutableStateOf(false) }
val last = state.last
Column(handle.fillMaxWidth()) {
Box(Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 6.dp), contentAlignment = Alignment.Center) {
Box(Modifier.size(width = 36.dp, height = 4.dp).background(palette.inkFaint, RoundedCornerShape(2.dp)))
}
Text(
stringResource(R.string.share_label),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
)
if (state.sending) {
val bar = Modifier.fillMaxWidth().padding(horizontal = 16.dp).height(2.dp)
if (LocalInspectionMode.current) LinearProgressIndicator(progress = { 0.4f }, modifier = bar) else LinearProgressIndicator(bar)
}
}
if (!state.signedIn) {
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.Center) {
Text(stringResource(R.string.assist_signed_out), style = MaterialTheme.typography.bodyLarge)
}
return
}
Column(
Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
// What came in.
if (state.text.isNotBlank()) {
Surface(
shape = RoundedCornerShape(16.dp),
color = palette.surfaceRaised,
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.fillMaxWidth(),
) {
Text(
state.text,
style = MaterialTheme.typography.bodyMedium,
color = palette.inkMuted,
maxLines = 6,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
)
}
}
state.files.forEach { file ->
Row(Modifier.fillMaxWidth().heightIn(min = 40.dp), verticalAlignment = Alignment.CenterVertically) {
Icon(
if (file.image) Icons.Filled.Image else Icons.AutoMirrored.Filled.InsertDriveFile,
contentDescription = null,
tint = palette.accent,
modifier = Modifier.size(24.dp),
)
Spacer(Modifier.width(12.dp))
Text(file.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
}
}
// What to do with it.
TextField(
value = ask,
onValueChange = { ask = it },
placeholder = { Text(stringResource(R.string.share_ask_hint)) },
shape = RoundedCornerShape(20.dp),
colors = TextFieldDefaults.colors(
focusedContainerColor = palette.surfaceRaised,
unfocusedContainerColor = palette.surfaceRaised,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
),
maxLines = 4,
enabled = !state.sending,
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
)
// Where it goes.
if (last != null) {
Surface(
shape = RoundedCornerShape(20.dp),
color = palette.surfaceRaised,
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.fillMaxWidth(),
) {
Column {
Destination(Icons.Filled.EditNote, stringResource(R.string.new_chat), null, selected = !toLast, enabled = !state.sending) { toLast = false }
Destination(Icons.Filled.History, stringResource(R.string.assist_continue), last.title, selected = toLast, enabled = !state.sending) {
toLast =
true
}
}
}
}
state.error?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.danger) }
}
Row(
Modifier.fillMaxWidth().padding(start = 12.dp, end = 16.dp, top = 4.dp, bottom = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.End,
) {
TextButton(onClick = actions::cancel, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
Spacer(Modifier.width(8.dp))
Button(
onClick = { actions.send(ask, toLast && last != null) },
enabled = !state.sending && (state.text.isNotBlank() || state.files.isNotEmpty()),
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
modifier = Modifier.heightIn(min = 48.dp),
) { Text(stringResource(if (state.sending) R.string.share_sending else R.string.send)) }
}
}
@Composable
private fun Destination(icon: ImageVector, title: String, detail: String?, selected: Boolean, enabled: Boolean, onClick: () -> Unit) {
val palette = LocalPalette.current
Row(
Modifier
.fillMaxWidth()
.selectable(selected = selected, enabled = enabled, role = Role.RadioButton, onClick = onClick)
.heightIn(min = 56.dp)
.padding(horizontal = 16.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(icon, contentDescription = null, tint = palette.inkMuted, modifier = Modifier.size(24.dp))
Spacer(Modifier.width(16.dp))
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.bodyLarge)
detail?.takeIf { it.isNotBlank() }?.let {
Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
RadioButton(selected = selected, onClick = null, enabled = enabled)
}
}
/**
* The message a share sends: the person's own words (or the default request) first, then what was
* shared, so the model reads the request before the material.
*/
fun shareMessage(ask: String, shared: String, fallback: String): String {
val request = ask.trim().ifBlank { fallback }
return if (shared.isBlank()) request else "$request\n\n---\n\n${shared.trim()}"
}
@@ -0,0 +1,415 @@
package eu.llembas.android.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import eu.llembas.android.ui.theme.Palette
/**
* Syntax highlighting for code that is only read: the file viewer and a reply's code blocks.
*
* A small scanner of the app's own, not a library: what it has to tell apart is few -- comments,
* strings, numbers, keywords, type names, and a markup language's tags -- and a highlighter that
* is a parser of its own (Prism4j, which needs an annotation processor and has not moved since
* 2019; or a WebView, which the app does not have) would be more to trust than the result is worth.
* It never runs anything and never fails: a language it does not know, or text it does not
* follow, is simply drawn plain. The colours are the theme's tokens, so it follows Shire and
* Moria like everything else.
*
* The languages are the server's (`show`'s `language`, from the file's extension) and a fence's
* info string in a reply (```kotlin), with the usual short names.
*/
enum class TokenKind { Comment, Text, Number, Keyword, Type, Tag, Attribute }
data class Token(val start: Int, val end: Int, val kind: TokenKind)
/** How one language is read: the scanner's few settings. */
private data class Spec(
val keywords: Set<String> = emptySet(),
val lineComments: List<String> = emptyList(),
val blockComments: List<Pair<String, String>> = emptyList(),
/** String delimiters, longest first (""" before "). */
val strings: List<String> = listOf("\"", "'"),
val ignoreCase: Boolean = false,
/** A capitalised identifier is a type (Kotlin, Java, Swift, Rust...). */
val capitalisedTypes: Boolean = false,
/** `<tag attr="...">`: markup (XML, HTML, Vue and Svelte templates). */
val markup: Boolean = false,
/** `key:` / `key =` at a line's start is the key (YAML, TOML). */
val keys: Boolean = false,
/** `$name` / `${...}` variables (shells, PHP). */
val dollarVariables: Boolean = false,
)
private fun words(text: String): Set<String> = text.split(' ').filter { it.isNotBlank() }.toSet()
private val C_FAMILY = words(
"if else for while do switch case default break continue return goto sizeof typedef struct union enum " +
"static const extern volatile register inline void char short int long float double signed unsigned " +
"auto true false NULL nullptr",
)
private val CPP = C_FAMILY + words(
"class namespace template typename public private protected virtual override final new delete this " +
"using operator friend explicit constexpr noexcept try catch throw bool std",
)
private val JAVA = words(
"abstract assert boolean break byte case catch char class const continue default do double else enum " +
"extends final finally float for goto if implements import instanceof int interface long native new " +
"package private protected public return short static strictfp super switch synchronized this throw " +
"throws transient try void volatile while true false null var record sealed permits yield",
)
private val KOTLIN = words(
"as break class continue do else false for fun if in interface is null object package return super this " +
"throw true try typealias typeof val var when while by catch constructor delegate dynamic field file " +
"finally get import init param property receiver set setparam where actual abstract annotation " +
"companion const crossinline data enum expect external final infix inline inner internal lateinit " +
"noinline open operator out override private protected public reified sealed suspend tailrec vararg value",
)
private val JS = words(
"break case catch class const continue debugger default delete do else export extends finally for " +
"function if import in instanceof new return super switch this throw try typeof var void while with " +
"yield let static async await of true false null undefined from as get set",
)
private val TS = JS + words(
"interface type enum implements declare namespace module public private protected readonly abstract " +
"keyof infer is never unknown any string number boolean symbol bigint object satisfies",
)
private val PYTHON = words(
"False None True and as assert async await break class continue def del elif else except finally for " +
"from global if import in is lambda nonlocal not or pass raise return try while with yield match case self",
)
private val RUST = words(
"as async await break const continue crate dyn else enum extern false fn for if impl in let loop match " +
"mod move mut pub ref return self Self static struct super trait true type unsafe use where while",
)
private val GO = words(
"break case chan const continue default defer else fallthrough for func go goto if import interface map " +
"package range return select struct switch type var true false nil iota",
)
private val RUBY = words(
"BEGIN END alias and begin break case class def defined do else elsif end ensure false for if in module " +
"next nil not or redo rescue retry return self super then true undef unless until when while yield require",
)
private val PHP = words(
"abstract and array as break callable case catch class clone const continue declare default do echo else " +
"elseif empty enddeclare endfor endforeach endif endswitch endwhile extends final finally fn for foreach " +
"function global goto if implements include instanceof insteadof interface isset list match namespace new " +
"or print private protected public readonly require return static switch throw trait try unset use var " +
"while yield true false null",
)
private val SWIFT = words(
"associatedtype class deinit enum extension fileprivate func import init inout internal let open operator " +
"private protocol public rethrows static struct subscript typealias var break case continue default defer " +
"do else fallthrough for guard if in repeat return switch where while as catch false is nil super self Self " +
"throw throws true try async await some any",
)
private val CSHARP = words(
"abstract as base bool break byte case catch char checked class const continue decimal default delegate do " +
"double else enum event explicit extern false finally fixed float for foreach goto if implicit in int " +
"interface internal is lock long namespace new null object operator out override params private protected " +
"public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true " +
"try typeof uint ulong unchecked unsafe ushort using virtual void volatile while var async await record",
)
private val DART = words(
"abstract as assert async await break case catch class const continue covariant default deferred do dynamic " +
"else enum export extends extension external factory false final finally for get if implements import in " +
"interface is late library mixin new null on operator part required rethrow return set show static super " +
"switch sync this throw true try typedef var void while with yield",
)
private val ZIG = words(
"addrspace align allowzero and anyframe anytype asm async await break callconv catch comptime const continue " +
"defer else enum errdefer error export extern fn for if inline noalias nosuspend noinline opaque or orelse " +
"packed pub resume return linksection struct suspend switch test threadlocal try union unreachable usingnamespace " +
"var volatile while true false null undefined",
)
private val SHELL = words(
"if then else elif fi case esac for select while until do done in function return exit local export " +
"readonly declare set unset shift source echo cd test true false",
)
private val SQL = words(
"select from where and or not insert into values update set delete create table drop alter add index view " +
"join left right inner outer full on as group by order having limit offset union all distinct case when then " +
"else end null is in like between exists primary key foreign references default unique check begin commit " +
"rollback transaction with returning asc desc count sum avg min max integer text real blob varchar",
)
private val LUA = words(
"and break do else elseif end false for function goto if in local nil not or repeat return then true until while",
)
private val CSS = words("important inherit initial unset none auto")
private val LITERALS = words("true false null yes no on off")
private val DOCKER = words(
"FROM RUN CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS",
)
private val C_LIKE = Spec(lineComments = listOf("//"), blockComments = listOf("/*" to "*/"))
private val SPECS: Map<String, Spec> = buildMap {
val js = C_LIKE.copy(keywords = JS, strings = listOf("\"", "'", "`"))
val ts = C_LIKE.copy(keywords = TS, strings = listOf("\"", "'", "`"), capitalisedTypes = true)
put("javascript", js)
put("jsx", js)
put("typescript", ts)
put("tsx", ts)
put("json", Spec(keywords = LITERALS, strings = listOf("\"")))
put("python", Spec(keywords = PYTHON, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
put("rust", C_LIKE.copy(keywords = RUST, strings = listOf("\""), capitalisedTypes = true))
put("go", C_LIKE.copy(keywords = GO, strings = listOf("\"", "`", "'")))
put("ruby", Spec(keywords = RUBY, lineComments = listOf("#"), strings = listOf("\"", "'"), capitalisedTypes = true))
put("php", C_LIKE.copy(keywords = PHP, lineComments = listOf("//", "#"), dollarVariables = true, ignoreCase = true))
put("java", C_LIKE.copy(keywords = JAVA, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
put("kotlin", C_LIKE.copy(keywords = KOTLIN, strings = listOf("\"\"\"", "\"", "'"), capitalisedTypes = true))
put("swift", C_LIKE.copy(keywords = SWIFT, strings = listOf("\"\"\"", "\""), capitalisedTypes = true))
put("c", C_LIKE.copy(keywords = C_FAMILY))
put("cpp", C_LIKE.copy(keywords = CPP, capitalisedTypes = true))
put("csharp", C_LIKE.copy(keywords = CSHARP, capitalisedTypes = true))
put("dart", C_LIKE.copy(keywords = DART, strings = listOf("\"\"\"", "'''", "\"", "'"), capitalisedTypes = true))
put("zig", C_LIKE.copy(keywords = ZIG, strings = listOf("\"", "'")))
val shell = Spec(keywords = SHELL, lineComments = listOf("#"), dollarVariables = true)
put("bash", shell)
put("fish", shell)
put("css", C_LIKE.copy(keywords = CSS, lineComments = emptyList()))
put("scss", C_LIKE.copy(keywords = CSS, dollarVariables = true))
put("sql", Spec(keywords = SQL, lineComments = listOf("--"), blockComments = listOf("/*" to "*/"), strings = listOf("'", "\""), ignoreCase = true))
put("yaml", Spec(keywords = LITERALS, lineComments = listOf("#"), keys = true))
put("toml", Spec(keywords = LITERALS, lineComments = listOf("#"), strings = listOf("\"\"\"", "'''", "\"", "'"), keys = true))
// Text between tags is prose: an apostrophe in it is not a string. Attribute values are read by markup().
val markup = Spec(blockComments = listOf("<!--" to "-->"), strings = emptyList(), markup = true)
put("xml", markup)
put("html", markup)
put("vue", markup)
put("svelte", markup)
put("lua", Spec(keywords = LUA, lineComments = listOf("--"), blockComments = listOf("--[[" to "]]"), strings = listOf("\"", "'")))
put("dockerfile", Spec(keywords = DOCKER, lineComments = listOf("#")))
put("makefile", Spec(lineComments = listOf("#"), dollarVariables = true, keys = true))
}
/** A fence's short names for the server's language names. */
private val ALIASES = mapOf(
"js" to "javascript", "mjs" to "javascript", "cjs" to "javascript", "ts" to "typescript", "py" to "python",
"python3" to "python", "rs" to "rust", "golang" to "go", "rb" to "ruby", "kt" to "kotlin", "kts" to "kotlin",
"c++" to "cpp", "cc" to "cpp", "hpp" to "cpp", "h" to "c", "cs" to "csharp", "c#" to "csharp", "sh" to "bash",
"shell" to "bash", "zsh" to "bash", "console" to "bash", "yml" to "yaml", "svg" to "xml", "htm" to "html",
"docker" to "dockerfile", "make" to "makefile", "jsonc" to "json", "json5" to "json", "postgres" to "sql",
"postgresql" to "sql", "sqlite" to "sql", "mysql" to "sql",
)
/** Whether [language] is one this highlighter reads. */
fun highlights(language: String): Boolean = specOf(language) != null
private fun specOf(language: String): Spec? {
val name = language.trim().lowercase()
return SPECS[name] ?: ALIASES[name]?.let { SPECS[it] }
}
/** Larger than this is drawn plain: a megabyte of spans costs more than it helps. */
const val HIGHLIGHT_MAX_CHARS = 400_000
/** The tokens of [text] read as [language]: empty for a language not known, or a text too large. */
fun tokenize(text: String, language: String): List<Token> {
val spec = specOf(language) ?: return emptyList()
if (text.length > HIGHLIGHT_MAX_CHARS) return emptyList()
return Scanner(text, spec).run()
}
private class Scanner(private val s: String, private val spec: Spec) {
private val out = mutableListOf<Token>()
private var i = 0
private var lineStart = true
fun run(): List<Token> {
while (i < s.length) {
val c = s[i]
if (c == '\n') {
lineStart = true
i++
continue
}
if (c == ' ' || c == '\t') {
i++
continue
}
val atLineStart = lineStart
lineStart = false
if (block() || line() || (spec.markup && markup()) || string() || (spec.keys && atLineStart && key()) ||
(spec.dollarVariables && variable()) || number() || word()
) {
continue
}
i++
}
return out
}
private fun add(start: Int, end: Int, kind: TokenKind) {
if (end > start) out += Token(start, end, kind)
}
private fun block(): Boolean {
for ((open, close) in spec.blockComments) {
if (s.startsWith(open, i)) {
val end = s.indexOf(close, i + open.length).let { if (it < 0) s.length else it + close.length }
add(i, end, TokenKind.Comment)
i = end
return true
}
}
return false
}
private fun line(): Boolean {
for (mark in spec.lineComments) {
// `#` in a shell word ("a#b") or `$#` is not a comment; one after a space or at a line's start is.
if (s.startsWith(mark, i) && (mark != "#" || i == 0 || s[i - 1].isWhitespace())) {
val end = s.indexOf('\n', i).let { if (it < 0) s.length else it }
add(i, end, TokenKind.Comment)
i = end
return true
}
}
return false
}
private fun string(): Boolean {
for (quote in spec.strings) {
if (!s.startsWith(quote, i)) continue
// A single-character quote ends at the line's end if it is not closed: a stray
// apostrophe ("don't" in a comment-less shell line) colours one line, not the file.
var j = i + quote.length
while (j < s.length) {
if (s[j] == '\\' && quote.length == 1) {
j += 2
continue
}
if (s.startsWith(quote, j)) {
j += quote.length
break
}
if (s[j] == '\n' && quote.length == 1 && quote != "`") break
j++
}
val end = j.coerceAtMost(s.length)
add(i, end, TokenKind.Text)
i = end
return true
}
return false
}
private fun number(): Boolean {
val c = s[i]
if (!c.isDigit() && !(c == '.' && i + 1 < s.length && s[i + 1].isDigit())) return false
if (i > 0 && (s[i - 1].isLetterOrDigit() || s[i - 1] == '_')) return false
var j = i
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '.' || s[j] == '_')) j++
add(i, j, TokenKind.Number)
i = j
return true
}
private fun word(): Boolean {
val c = s[i]
if (!c.isLetter() && c != '_' && c != '@') return false
var j = i + 1
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
val word = s.substring(i, j)
val bare = word.removePrefix("@")
when {
word.startsWith("@") && word.length > 1 -> add(i, j, TokenKind.Attribute)
(if (spec.ignoreCase) bare.lowercase() in spec.keywords || bare in spec.keywords else bare in spec.keywords) ->
add(i, j, TokenKind.Keyword)
spec.capitalisedTypes && bare.first().isUpperCase() && bare.any { it.isLowerCase() } -> add(i, j, TokenKind.Type)
}
i = j
return true
}
private fun variable(): Boolean {
if (s[i] != '$' || i + 1 >= s.length) return false
var j = i + 1
if (s[j] == '{') {
j = s.indexOf('}', j).let { if (it < 0) s.length else it + 1 }
} else {
while (j < s.length && (s[j].isLetterOrDigit() || s[j] == '_')) j++
}
if (j == i + 1) return false
add(i, j, TokenKind.Attribute)
i = j
return true
}
/** `key:` (YAML) or `key =` (TOML, Make) as a line's first word. */
private fun key(): Boolean {
var j = i
if (s[j] == '-' && j + 1 < s.length && s[j + 1] == ' ') return false
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "_-.[]\"'")) j++
if (j == i) return false
var k = j
while (k < s.length && s[k] == ' ') k++
if (k < s.length && (s[k] == ':' || s[k] == '=') && (k + 1 >= s.length || s[k + 1] != '=')) {
add(i, j, TokenKind.Type)
i = j
return true
}
return false
}
/** `<tag attr="value">` and `</tag>`: the tag's name, its attributes' names, the values as strings. */
private fun markup(): Boolean {
if (s[i] != '<' || i + 1 >= s.length) return false
var j = i + 1
if (s[j] == '/' || s[j] == '?' || s[j] == '!') j++
val nameStart = j
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:.")) j++
if (j == nameStart) return false
add(nameStart, j, TokenKind.Tag)
while (j < s.length && s[j] != '>') {
when {
s[j] == '"' || s[j] == '\'' -> {
val q = s[j]
val end = s.indexOf(q, j + 1).let { if (it < 0) s.length else it + 1 }
add(j, end, TokenKind.Text)
j = end
}
s[j].isLetter() -> {
val a = j
while (j < s.length && (s[j].isLetterOrDigit() || s[j] in "-_:@.")) j++
add(a, j, TokenKind.Attribute)
}
s[j] == '\n' -> {
j++
}
else -> j++
}
}
i = (j + 1).coerceAtMost(s.length)
return true
}
}
/** The theme's colour for each kind of token. */
fun tokenStyle(kind: TokenKind, palette: Palette): SpanStyle = when (kind) {
TokenKind.Comment -> SpanStyle(color = palette.inkFaint, fontStyle = FontStyle.Italic)
TokenKind.Text -> SpanStyle(color = palette.success)
TokenKind.Number -> SpanStyle(color = palette.warning)
TokenKind.Keyword -> SpanStyle(color = palette.accent)
TokenKind.Type -> SpanStyle(color = palette.leaf)
TokenKind.Tag -> SpanStyle(color = palette.accent)
TokenKind.Attribute -> SpanStyle(color = palette.warning)
}
/** [text] with its [tokens] in the theme's colours; the rest in [plain]. */
fun highlighted(text: String, tokens: List<Token>, palette: Palette, plain: Color = palette.ink): AnnotatedString = buildAnnotatedString {
append(text)
addStyle(SpanStyle(color = plain), 0, text.length)
for (token in tokens) addStyle(tokenStyle(token.kind, palette), token.start, token.end.coerceAtMost(text.length))
}
/** [text] as [language], highlighted -- or plain, when the language is not one it reads. */
fun highlight(text: String, language: String, palette: Palette): AnnotatedString = highlighted(text, tokenize(text, language), palette)
@@ -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
@@ -63,6 +63,9 @@ fun progressWords(resources: Resources): ProgressWords = ProgressWords { key, ar
PROGRESS_STRINGS[key]?.let { id -> if (args.isEmpty()) resources.getString(id) else resources.getString(id, *args) }
}
/** The end of a progress line: the shared `progress.line` separator and [clock], without the text before it. */
fun progressClock(resources: Resources, clock: String): String = resources.getString(R.string.progress_line, "", clock)
/** The clock a progress line ticks by: now, again on every whole second. */
@Composable
fun rememberTick(): Long {
@@ -115,7 +118,8 @@ fun ProgressStatus(progress: Progress?, status: String, style: TextStyle, color:
}
Row(modifier, verticalAlignment = Alignment.Top) {
Text(text, style = style, color = color, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
// The spec's separator, `progress.line`'s " · ", before the clock.
if (clock != null) Text(" · $clock", style = style, color = color, maxLines = 1, softWrap = false)
// The clock after the shared separator: `progress.line` (`{{text}} · {{elapsed}}`) with
// the text left out, so the separator is the spec's and not a copy of it.
if (clock != null) Text(progressClock(LocalContext.current.resources, clock), style = style, color = color, maxLines = 1, softWrap = false)
}
}
@@ -51,6 +51,7 @@ import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.took
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.theme.LocalPalette
@@ -97,7 +98,8 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
Icon(iconFor(call.block.kind), contentDescription = null, modifier = Modifier.size(16.dp), tint = palette.inkMuted)
Spacer(Modifier.width(6.dp))
Text(
call.block.title.ifBlank { call.name },
// The one short title; a call without one is named as a person reads the tool.
call.block.title.ifBlank { call.block.label.ifBlank { call.name } },
fontFamily = if (call.block.kind == "shell") FontFamily.Monospace else null,
style = MaterialTheme.typography.bodySmall,
maxLines = if (open) 6 else 1,
@@ -107,6 +109,10 @@ fun ToolCallBlock(call: ToolCall, depth: Int = 0, onShow: ((ShowCard) -> Unit)?
call.block.chips.forEach { chip ->
Text(chip, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, modifier = Modifier.padding(start = 6.dp))
}
// How long a finished call took (display.md §2); a running or a denied one shows none.
call.took()?.let { took ->
Text(took, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint, maxLines = 1, modifier = Modifier.padding(start = 6.dp))
}
}
call.purpose?.takeIf { it.isNotBlank() }?.let {
Text(it, style = MaterialTheme.typography.labelSmall, color = palette.inkFaint)
@@ -58,6 +58,7 @@ fun CardSheet(card: Card, onAnswer: (CardAnswer) -> Unit) {
}
when (card.kind) {
"approval" -> Approval(card, onAnswer)
"phone_action" -> PhoneCard(card, onAnswer)
"plan" -> PlanCard(card, onAnswer)
else -> Questions(card, onAnswer)
}
@@ -120,10 +121,15 @@ private fun Approval(card: Card, onAnswer: (CardAnswer) -> Unit) {
} else {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { onAnswer(CardAnswer(verdict = "allow", texts = texts)) }) { Text(stringResource(R.string.card_allow_once)) }
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
Text(stringResource(R.string.card_allow_always))
// Only where the request offers it: a call that may only ever be allowed once has none.
if (offersAlways(card)) {
OutlinedButton(onClick = { onAnswer(CardAnswer(verdict = "allow_always", texts = texts)) }) {
Text(stringResource(R.string.card_allow_always))
}
}
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny)) }
// The spec's four actions (display.md §5): Deny at once, or with the person's words to the model.
TextButton(onClick = { onAnswer(CardAnswer(verdict = "deny")) }) { Text(stringResource(R.string.card_deny)) }
TextButton(onClick = { refusing = true }) { Text(stringResource(R.string.card_deny_reason)) }
}
}
}
@@ -203,20 +209,11 @@ private fun toggle(item: CardItem, now: Set<String>?, label: String): Set<String
@Composable
private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
val item = card.items.firstOrNull() ?: return
var mode by remember { mutableStateOf("edit") }
var revising by remember { mutableStateOf(false) }
var feedback by remember { mutableStateOf("") }
val plan = item.plan?.let { runCatching { LembasJson.decodeFromJsonElement(Plan.serializer(), it) }.getOrNull() }
Text(plan?.title?.ifBlank { null } ?: item.title, style = MaterialTheme.typography.titleMedium)
plan?.let { PlanBody(it) }
if (item.modeChoice) {
Row(verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected = mode == "edit", onClick = { mode = "edit" })
Text(stringResource(R.string.mode_edit))
RadioButton(selected = mode == "manual", onClick = { mode = "manual" })
Text(stringResource(R.string.mode_manual))
}
}
if (revising) {
OutlinedTextField(
value = feedback,
@@ -226,15 +223,27 @@ private fun PlanCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
)
Button(onClick = { onAnswer(CardAnswer(verdict = "deny", reason = feedback)) }) { Text(stringResource(R.string.card_send)) }
} else {
// Approve together with the mode the work continues in (display.md §5), where the
// session may choose one; otherwise Approve alone. And Revise.
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = {
onAnswer(CardAnswer(verdict = "allow", choices = if (item.modeChoice) mapOf(item.key to listOf(mode)) else emptyMap()))
}) { Text(stringResource(R.string.plan_approve)) }
OutlinedButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
if (item.modeChoice) {
Button(onClick = { onAnswer(planApproval(item, "edit")) }) { Text(stringResource(R.string.plan_approve_edit)) }
OutlinedButton(onClick = { onAnswer(planApproval(item, "manual")) }) { Text(stringResource(R.string.plan_approve_manual)) }
} else {
Button(onClick = { onAnswer(planApproval(item, null)) }) { Text(stringResource(R.string.plan_approve)) }
}
TextButton(onClick = { revising = true }) { Text(stringResource(R.string.plan_revise)) }
}
}
}
/** Whether an approval card offers "Always allow": only when every call on it may be remembered (`always`). */
internal fun offersAlways(card: Card): Boolean = card.items.isNotEmpty() && card.items.all { it.always }
/** A plan's approval as the server reads it: allow, and the mode to continue in where one was chosen. */
internal fun planApproval(item: CardItem, mode: String?): CardAnswer =
CardAnswer(verdict = "allow", choices = if (item.modeChoice && mode != null) mapOf(item.key to listOf(mode)) else emptyMap())
/** A plan's phases and tasks, ticked as the reply works through them. */
@Composable
fun PlanBody(plan: Plan) {
@@ -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,
)
}
}
}
}
@@ -279,17 +279,47 @@ class ChatViewModel(app: Application) :
following?.cancel()
following = viewModelScope.launch {
_state.update { it.copy(live = LiveReply(messageId)) }
// Set at `done`, which is the end of the reply: from then on the stream is followed
// only for the name a model may still give the chat (the `title` frame).
var ended: LiveReply? = null
try {
StreamClient(api()).follow(chat.id, messageId).collect { frame ->
_state.update { s ->
val live = (s.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
val before = ended
if (before != null) {
val named = before.apply(frame.event, frame.data)
ended = named
if (named.title != before.title) _state.update { s -> s.copy(chat = s.chat?.let { c -> named.title?.let { c.copy(title = it) } ?: c }) }
return@collect
}
val live = (_state.value.live ?: LiveReply(messageId)).apply(frame.event, frame.data)
val finished = live.finished
if (finished == null) {
// The tree outlives the reply: kept for the activity sheet once it ends.
s.copy(live = live, tree = live.tree ?: s.tree)
_state.update { s -> s.copy(live = live, tree = live.tree ?: s.tree) }
return@collect
}
ended = live
_state.update { s ->
s.copy(
live = null,
tree = live.tree ?: s.tree,
messages = s.messages.map { if (it.id == finished.id) finished else it },
chat = s.chat?.let { c -> live.title?.let { c.copy(title = it) } ?: c },
)
}
// The queue handed a waiting prompt to a fresh reply: the transcript has moved
// on the server, so it is read again rather than patched -- and that reply is
// followed instead of this stream's tail.
live.next?.let { next ->
refresh()
follow(next)
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
// After `done` only the name was still to come: nothing to say, nothing to redo.
if (ended != null) return@launch
fail(e)
// The reply goes on on the server; what it has written so far is read back
// rather than left half-drawn.
@@ -297,21 +327,8 @@ class ChatViewModel(app: Application) :
refresh()
return@launch
}
val ended = _state.value.live
_state.update { s ->
val finished = ended?.finished
s.copy(
live = null,
messages = if (finished != null) s.messages.map { if (it.id == finished.id) finished else it } else s.messages,
chat = s.chat?.let { c -> ended?.title?.let { c.copy(title = it) } ?: c },
)
}
// The queue handed a waiting prompt to a fresh reply: the transcript has moved on
// the server, so it is read again rather than patched.
ended?.next?.let { next ->
refresh()
follow(next)
}
// The stream closed without a `done` (an older reply already gone): nothing is live.
if (ended == null) _state.update { it.copy(live = null) }
}
}
@@ -0,0 +1,250 @@
package eu.llembas.android.ui.chat
import android.app.KeyguardManager
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import eu.llembas.android.R
import eu.llembas.android.actions.ActionRunner
import eu.llembas.android.actions.Args
import eu.llembas.android.actions.NavApp
import eu.llembas.android.api.Card
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.PhoneResult
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
/** The actions a map app carries out. */
val NAV_ACTIONS = setOf("navigate", "add_stop", "search_nearby", "stop_navigation")
/** What the card shows of a phone card while it is being carried out. */
data class PhoneCardState(val running: Boolean = false, val locked: Boolean = false, val error: String? = null)
/**
* A `phone_action` card (spec 3.6.0) with the phone behind it: Do it carries the action out
* ([ActionRunner]) and answers what happened -- done, or failed and why; Cancel answers declined.
* Never while the phone is locked: Do it says to unlock first. Used by the chat's card sheet and
* by the assistant's sheet alike.
*/
@Composable
fun PhoneCard(card: Card, onAnswer: (CardAnswer) -> Unit) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val prefs by context.lembas.instances.prefs.collectAsState(initial = Prefs())
val installed = remember { NavApp.installedApps(context) }
var state by remember(card.id) { mutableStateOf(PhoneCardState()) }
val item = card.items.firstOrNull() ?: return
val phone = item.phone ?: JsonObject(emptyMap())
PhoneCardContent(
phone = phone,
navApps = installed,
chosen = NavApp.chosen(prefs.navApp, installed),
state = state,
onDo = { app ->
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) {
state = state.copy(locked = true)
return@PhoneCardContent
}
state = PhoneCardState(running = true)
scope.launch {
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
val outcome = ActionRunner.run(context, action, Args(phone), app, askOsmAnd = prefs.osmandInfo)
state = PhoneCardState(error = outcome.message.takeIf { outcome.status.wire == "failed" })
onAnswer(CardAnswer(result = PhoneResult(outcome.status.wire, outcome.message)))
}
},
onDecline = { onAnswer(CardAnswer(result = PhoneResult("declined"))) },
)
}
/**
* The card from its state alone (what the screenshot tests draw): the phone's icon and "Do this
* on your phone?", the model's one line ([phone]'s `summary`), how it will be done and its facts,
* the map app to use when Settings leaves it open ([chosen] null, more than one installed), and
* Cancel / Do it -- each at least 48 dp, the line above them free to wrap.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun PhoneCardContent(
phone: JsonObject,
navApps: List<NavApp>,
chosen: NavApp?,
state: PhoneCardState,
onDo: (NavApp?) -> Unit = {},
onDecline: () -> Unit = {},
) {
val palette = LocalPalette.current
val action = (phone["action"] as? JsonPrimitive)?.content.orEmpty()
val summary = (phone["summary"] as? JsonPrimitive)?.content.orEmpty().ifBlank { action }
val nav = action in NAV_ACTIONS
var picked by remember(chosen) { mutableStateOf(chosen ?: navApps.singleOrNull()) }
Surface(
shape = RoundedCornerShape(20.dp),
color = palette.surfaceRaised,
border = BorderStroke(1.dp, palette.border),
modifier = Modifier.fillMaxWidth(),
) {
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(Icons.Filled.PhoneAndroid, contentDescription = null, tint = palette.accent, modifier = Modifier.size(20.dp))
Spacer(Modifier.width(10.dp))
Text(stringResource(R.string.action_card_title), style = MaterialTheme.typography.labelLarge, color = palette.accent)
}
Text(summary, style = MaterialTheme.typography.titleMedium)
Text(howLine(action, picked), style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted)
phoneFacts(phone).takeIf { it.isNotBlank() }?.let {
Text(it, style = MaterialTheme.typography.bodySmall, color = palette.inkMuted)
}
if (nav && chosen == null && navApps.size > 1) {
Text(stringResource(R.string.nav_app_pick), style = MaterialTheme.typography.labelMedium, color = palette.inkMuted)
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
navApps.forEach { app ->
FilterChip(
selected = picked == app,
onClick = { picked = app },
label = { Text(stringResource(if (app == NavApp.OsmAnd) R.string.nav_app_osmand else R.string.nav_app_google)) },
colors = FilterChipDefaults.filterChipColors(selectedContainerColor = palette.accentSoft),
modifier = Modifier.heightIn(min = 40.dp),
)
}
}
}
if (nav && picked == NavApp.GoogleMaps && action in setOf("add_stop", "stop_navigation")) {
Text(
stringResource(if (action == "add_stop") R.string.action_google_add_stop else R.string.action_google_no_stop),
style = MaterialTheme.typography.bodySmall,
color = palette.warning,
)
}
when {
state.locked -> Text(stringResource(R.string.action_unlock), style = MaterialTheme.typography.bodyMedium, color = palette.warning)
state.error != null -> Text(
stringResource(R.string.action_failed, state.error),
style = MaterialTheme.typography.bodyMedium,
color = palette.danger,
)
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
TextButton(onClick = onDecline, enabled = !state.running, modifier = Modifier.heightIn(min = 48.dp)) { Text(stringResource(R.string.cancel)) }
Spacer(Modifier.width(8.dp))
Button(
onClick = { onDo(picked) },
enabled = !state.running && (!nav || picked != null),
colors = ButtonDefaults.buttonColors(containerColor = palette.accent, contentColor = palette.accentInk),
modifier = Modifier.heightIn(min = 48.dp),
) { Text(stringResource(if (state.running) R.string.action_running else R.string.action_do)) }
}
}
}
}
/** How the action will be done, in a sentence: which kind of app, and what is left to the person. */
@Composable
private fun howLine(action: String, app: NavApp?): String = when (action) {
"alarm", "timer" -> stringResource(R.string.action_line_clock)
"calendar_event" -> stringResource(R.string.action_line_calendar)
"sms_draft", "email_draft" -> stringResource(R.string.action_line_draft)
"dial" -> stringResource(R.string.action_line_dial)
"navigate", "add_stop", "search_nearby", "stop_navigation" ->
stringResource(
R.string.action_line_map,
stringResource(
if (app ==
NavApp.OsmAnd
) {
R.string.nav_app_osmand
} else if (app == NavApp.GoogleMaps) {
R.string.nav_app_google
} else {
R.string.nav_app
},
),
)
"media", "torch" -> stringResource(R.string.action_line_now)
"settings_panel" -> stringResource(R.string.action_line_settings)
"automation_intent" -> stringResource(R.string.action_line_automation)
else -> stringResource(R.string.action_line_open)
}
/**
* The action's facts as one line, values only, in the order the spec lists the fields: what the
* person checks before Do it ("07:00 · mon tue wed thu fri · Work"). A place is its name and,
* when it has one, what the map app will search, or its coordinates.
*/
fun phoneFacts(phone: JsonObject): String {
fun place(e: JsonElement?): String? {
val o = e as? JsonObject ?: return (e as? JsonPrimitive)?.content
val name = (o["name"] as? JsonPrimitive)?.content.orEmpty()
val query = (o["query"] as? JsonPrimitive)?.content.orEmpty()
val lat = (o["lat"] as? JsonPrimitive)?.content
val lon = (o["lon"] as? JsonPrimitive)?.content
val where = query.ifBlank { if (lat != null && lon != null) "$lat, $lon" else "" }
return listOf(name, where).filter { it.isNotBlank() }.distinct().let {
if (it.size == 2) "${it[0]} (${it[1]})" else it.firstOrNull()
}
}
fun value(key: String, e: JsonElement?): String? = when {
e == null -> null
key in setOf("destination", "stop") -> place(e)
key == "stops" -> (e as? JsonArray)?.mapNotNull { place(it) }?.joinToString(" → ")?.ifBlank { null }
e is JsonArray -> e.mapNotNull { (it as? JsonPrimitive)?.content }.joinToString(" ").ifBlank { null }
e is JsonObject -> e.entries.joinToString(", ") { (k, v) -> "$k=${(v as? JsonPrimitive)?.content.orEmpty()}" }.ifBlank { null }
e is JsonPrimitive -> e.content.takeIf { it.isNotBlank() && it != "false" && it != "true" }
else -> null
}
return FACT_ORDER.mapNotNull { key -> value(key, phone[key]) }.joinToString(" · ")
}
private val FACT_ORDER = listOf(
"time", "days", "seconds", "label", "title", "start", "end", "location", "to", "cc", "subject", "number",
"stops", "stop", "destination", "mode", "query", "near", "app", "url", "command", "panel", "task", "values",
)
@@ -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
@@ -85,9 +86,13 @@ import eu.llembas.android.api.Message
import eu.llembas.android.api.ShowCard
import eu.llembas.android.api.Step
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.ending
import eu.llembas.android.api.shownMarkdown
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.Segment
import eu.llembas.android.ui.highlight
import eu.llembas.android.ui.pageProjection
import eu.llembas.android.ui.progressLineOf
import eu.llembas.android.ui.splitFences
import eu.llembas.android.ui.theme.LocalPalette
@@ -166,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
@@ -223,8 +247,16 @@ fun AssistantMessage(
if (writing) {
Writing(Modifier.padding(top = if (steps.isEmpty()) 0.dp else 8.dp), withLine = steps.isEmpty())
} else {
message.error?.let {
Text(it, color = palette.danger, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 8.dp))
// How a reply that did not finish ended (display.md §4): the progress text alone --
// "Stopped: by you", "Failed: …" -- staying at the end of the reply; an error in
// the error colour, a stop muted. Nothing else says it a second time.
message.ending()?.let { end ->
Text(
progressLineOf(end, withElapsed = false) ?: message.error.orEmpty(),
color = if (end.phase == "failed") palette.danger else palette.inkMuted,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(top = 8.dp),
)
}
// The actions and the foot share one row: the icons keep their 48 dp, the foot gives.
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {
@@ -286,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? {
@@ -344,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) }
}
}
@@ -354,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) {
@@ -391,8 +470,10 @@ fun CodeBlock(language: String, code: String, modifier: Modifier = Modifier) {
}
}
HorizontalDivider(color = palette.codeBorder)
// The fence's language in the theme's colours (ui/Highlight.kt); plain when it names none it reads.
val shown = remember(code, language, palette) { highlight(code, language, palette) }
Text(
code,
shown,
fontFamily = FontFamily.Monospace,
fontSize = 13.sp,
lineHeight = 19.sp,
@@ -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) {
@@ -2,9 +2,14 @@
package eu.llembas.android.ui.settings
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemClock
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
@@ -26,20 +31,31 @@ import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Assistant
import androidx.compose.material.icons.filled.BatteryAlert
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.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
import androidx.compose.material.icons.filled.Navigation
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material.icons.filled.PhoneAndroid
import androidx.compose.material.icons.filled.RecordVoiceOver
import androidx.compose.material.icons.filled.Science
import androidx.compose.material.icons.filled.ScreenLockPortrait
import androidx.compose.material.icons.filled.Security
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.filled.Timer
import androidx.compose.material.icons.filled.Translate
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
@@ -55,6 +71,7 @@ import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -71,13 +88,17 @@ 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.core.content.ContextCompat
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.assist.LembasAssistService
import eu.llembas.android.assist.PhoneRecognizer
import eu.llembas.android.auth.Instance
import eu.llembas.android.auth.Prefs
import eu.llembas.android.lembas
import eu.llembas.android.notify.NotificationAccess
import eu.llembas.android.push.Push
import eu.llembas.android.ui.theme.LocalPalette
import eu.llembas.android.update.AppVersion
@@ -87,6 +108,21 @@ 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
import eu.llembas.android.wake.WakePhrase
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.WakeWordService
import eu.llembas.android.wake.WakeWords
import eu.llembas.android.wake.wakeAttemptWords
import eu.llembas.android.wake.wakeTitle
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/** What the settings page does; every action has a do-nothing default for the screenshots. */
@@ -102,6 +138,18 @@ interface SettingsActions {
fun assistantTemporary(on: Boolean) {}
fun voiceInput(value: String) {}
fun assistantListens(on: Boolean) {}
fun assistantConversation(on: Boolean) {}
fun wakeWord(on: Boolean) {}
fun wakePhrase(id: String) {}
fun wakeSensitivity(id: String) {}
fun wakeTest() {}
fun wakeRetry() {}
fun wakeScreenOnly(on: Boolean) {}
fun batterySettings() {}
fun notificationSummaries(on: Boolean) {}
fun notificationAccess() {}
fun navApp(id: String) {}
fun osmandInfo(on: Boolean) {}
fun readAloud(on: Boolean) {}
fun checkUpdate() {}
fun openRelease() {}
@@ -110,6 +158,9 @@ interface SettingsActions {
fun updateBetas(on: Boolean) {}
}
/** "Test the wake word" as the row shows it: not started, [running], or [done] -- with how often it was [heard]. */
data class WakeTestShown(val running: Boolean = false, val done: Boolean = false, val heard: Int = 0)
/** What the settings page shows. */
data class SettingsState(
val instances: List<Instance> = emptyList(),
@@ -126,6 +177,24 @@ data class SettingsState(
val beta: Boolean = false,
/** Whether the phone has a speech recogniser of its own (Settings › Voice input › Phone). */
val phoneRecognizer: Boolean = false,
/** Whether this build has a wake-word engine (the F-Droid build has none). */
val wakeAvailable: Boolean = false,
/** What the wake word is doing right now (WakeStatus), said under its switch while it is on. */
val wakeState: WakeState = WakeState.Off,
/** "Test the wake word": whether its ten seconds are running, and how often the phrase landed. */
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(),
)
@Composable
@@ -136,11 +205,33 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
val instances by store.instances.collectAsState(initial = emptyList())
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()) }
var tested by remember { mutableStateOf(false) }
LaunchedEffect(trial.until) {
while (SystemClock.elapsedRealtime() < trial.until) {
clock = SystemClock.elapsedRealtime()
delay(200)
}
clock = SystemClock.elapsedRealtime()
}
var pushNote by remember { mutableStateOf<String?>(null) }
var updateNote by remember { mutableStateOf<String?>(null) }
var updateFound by remember { mutableStateOf<UpdateOffer?>(null) }
val beta = remember { AppVersion.parse(BuildConfig.VERSION_NAME)?.isBeta ?: false }
val distributors = remember { Push.distributors(context) }
// The wake word needs the microphone before it can be turned on.
val micForWake = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) {
scope.launch {
store.savePrefs { it.copy(wakeWord = true) }
WakeWordService.start(context)
}
}
}
val actions = remember {
object : SettingsActions {
override fun use(instance: Instance) {
@@ -196,6 +287,74 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
scope.launch { store.savePrefs { it.copy(assistantListens = on) } }
}
override fun assistantConversation(on: Boolean) {
scope.launch { store.savePrefs { it.copy(assistantConversation = on) } }
}
override fun wakeWord(on: Boolean) {
val mic = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
when {
on && !mic -> micForWake.launch(Manifest.permission.RECORD_AUDIO)
on -> scope.launch {
store.savePrefs { it.copy(wakeWord = true) }
WakeWordService.start(context)
}
else -> scope.launch {
store.savePrefs { it.copy(wakeWord = false) }
WakeWordService.stop()
}
}
}
override fun wakePhrase(id: String) {
scope.launch { store.savePrefs { it.copy(wakePhrase = id) } }
}
override fun wakeSensitivity(id: String) {
scope.launch { store.savePrefs { it.copy(wakeSensitivity = id) } }
}
// A tap on the wake word's state: start it if the phone stopped it (asking for the
// microphone where that is missing), and if it is waiting to try again, try now.
override fun wakeRetry() {
WakeStatus.retryNow()
wakeWord(true)
}
override fun wakeTest() {
tested = true
WakeStatus.startTrial(SystemClock.elapsedRealtime())
}
override fun wakeScreenOnly(on: Boolean) {
scope.launch { store.savePrefs { it.copy(wakeScreenOnly = on) } }
}
// The list of apps the phone's battery optimisation leaves alone; no permission needed to open it.
override fun batterySettings() {
runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
// On: Android's own switch is the person's to flip, so its page opens if it is off.
override fun notificationSummaries(on: Boolean) {
scope.launch { store.savePrefs { it.copy(notificationSummaries = on) } }
if (on && !NotificationAccess.granted(context)) notificationAccess()
}
override fun notificationAccess() {
NotificationAccess.settingsIntent(context)?.let { page -> runCatching { context.startActivity(page) } }
}
override fun navApp(id: String) {
scope.launch { store.savePrefs { it.copy(navApp = id) } }
}
override fun osmandInfo(on: Boolean) {
scope.launch { store.savePrefs { it.copy(osmandInfo = on) } }
}
override fun readAloud(on: Boolean) {
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
}
@@ -250,6 +409,17 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
selfUpdate = BuildConfig.SELF_UPDATE,
beta = beta,
phoneRecognizer = remember { PhoneRecognizer.available(context) },
wakeAvailable = WakeEngine.AVAILABLE,
wakeState = wakeState,
// Read again each time Settings is composed: the person comes back from the system's page.
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 } },
),
actions,
onBack,
@@ -265,6 +435,15 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -> Unit = {}) {
val palette = LocalPalette.current
var choosingLanguage by remember { mutableStateOf(false) }
var choosingWake by remember { mutableStateOf<WakeChoice?>(null) }
choosingWake?.let { which ->
ModalBottomSheet(onDismissRequest = { choosingWake = null }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
WakeChoices(which, state.prefs, onPick = { pick ->
choosingWake = null
pick(actions)
})
}
}
if (choosingLanguage) {
ModalBottomSheet(onDismissRequest = { choosingLanguage = false }, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)) {
LanguageChoices(state.prefs, onPick = {
@@ -408,14 +587,32 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
onClick = { actions.readAloud(!state.prefs.readAloudSpoken) },
trailing = { Switch(checked = state.prefs.readAloudSpoken, onCheckedChange = actions::readAloud) },
)
Rule()
SettingRow(
Icons.Filled.Forum,
stringResource(R.string.assistant_conversation),
subtitle = stringResource(R.string.assistant_conversation_line),
enabled = state.prefs.readAloudSpoken,
onClick = { actions.assistantConversation(!state.prefs.assistantConversation) },
trailing = {
Switch(
checked = state.prefs.assistantConversation && state.prefs.readAloudSpoken,
enabled = state.prefs.readAloudSpoken,
onCheckedChange = actions::assistantConversation,
)
},
)
}
Text(
stringResource(R.string.assistant_samsung) + "\n\n" + stringResource(R.string.assist_no_wake_word),
stringResource(R.string.assistant_samsung),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
item { WakeWordGroup(state, actions, onChoose = { choosingWake = it }) }
item { NotificationSummaryGroup(state, actions) }
item { PhoneActionsGroup(state, actions) }
item {
// Which recogniser turns speech into words: the instance's or the phone's -- what
// each one is, and where the recording goes, said in the row itself.
@@ -497,6 +694,236 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
}
}
/** The three things about the wake word that are chosen from a list, each in a sheet. */
enum class WakeChoice { Greeting, Name, Sensitivity }
/**
* The wake word: off until turned on; the phrase as a greeting and a name (English, words the
* engine's model knows); how easily it is taken as heard; only while the screen is on; and what
* it costs and why a phone may stop it, said before it is turned on.
*/
@Composable
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)) {
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),
enabled = state.wakeAvailable,
onClick = { actions.wakeWord(!on) },
trailing = { Switch(checked = on, enabled = state.wakeAvailable, onCheckedChange = actions::wakeWord) },
)
if (on) {
// The truth, not the setting: listening, paused and why, or failed and why. A tap
// tries again (and asks for the microphone when that is what is missing).
val wake = state.wakeState
val trouble = wake is WakeState.Failed || wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone)
Rule()
SettingRow(
if (trouble) Icons.Filled.ErrorOutline else Icons.Filled.GraphicEq,
wakeTitle(LocalContext.current, wake),
subtitle = when {
wake is WakeState.Failed && wake.why != WakeFailure.NoEngine ->
listOf(stringResource(R.string.wake_failed_line), wake.detail).filter { it.isNotBlank() }.joinToString("\n")
wake == WakeState.Off || wake == WakeState.Paused(WakePause.NoMicrophone) -> stringResource(R.string.wake_tap_to_start)
else -> null
},
tint = if (trouble) palette.warning else null,
onClick = actions::wakeRetry,
)
if (!state.isAssistant) {
// Said plainly: Android lets only the phone's assistant open over other apps.
Rule()
SettingRow(
Icons.Filled.Assistant,
stringResource(R.string.wake_not_assistant),
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) {
val phrase = WakePhrases.byId(state.prefs.wakePhrase)
Rule()
SettingRow(
Icons.Filled.RecordVoiceOver,
"“${phrase.words}”",
subtitle = stringResource(R.string.wake_phrase_line),
onClick = { onChoose(WakeChoice.Name) },
)
Rule()
SettingRow(
Icons.Filled.RecordVoiceOver,
stringResource(R.string.wake_greeting),
subtitle = phrase.greeting.words,
showIcon = false,
onClick = { onChoose(WakeChoice.Greeting) },
)
Rule()
SettingRow(
Icons.Filled.RecordVoiceOver,
stringResource(R.string.wake_name),
subtitle = if (phrase.name.id == GOOGLE) phrase.name.words + " · " + stringResource(R.string.wake_name_google_line) else phrase.name.words,
showIcon = false,
onClick = { onChoose(WakeChoice.Name) },
)
Rule()
SettingRow(
Icons.Filled.Tune,
stringResource(R.string.wake_sensitivity),
subtitle = stringResource(sensitivityLabel(WakeSensitivity.byId(state.prefs.wakeSensitivity))),
onClick = { onChoose(WakeChoice.Sensitivity) },
)
Rule()
WakeTestRow(state, on, phrase.words, actions)
Rule()
WakeLogRow(state.prefs.wakeLog)
Rule()
SettingRow(
Icons.Filled.ScreenLockPortrait,
stringResource(R.string.wake_screen_only),
subtitle = stringResource(R.string.wake_screen_only_line),
onClick = { actions.wakeScreenOnly(!state.prefs.wakeScreenOnly) },
trailing = { Switch(checked = state.prefs.wakeScreenOnly, onCheckedChange = actions::wakeScreenOnly) },
)
Rule()
SettingRow(
Icons.Filled.BatteryAlert,
stringResource(R.string.wake_battery),
subtitle = stringResource(R.string.wake_battery_line),
onClick = actions::batterySettings,
)
}
}
Text(
stringResource(R.string.wake_word_privacy) + "\n\n" + stringResource(R.string.wake_word_cost),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
/**
* Phone actions: which navigation app a route goes to (whichever is installed by default; with
* both, the card asks), and whether OsmAnd may be asked where the phone is and where the running
* route goes -- which the person allows inside OsmAnd first.
*/
@Composable
private fun PhoneActionsGroup(state: SettingsState, actions: SettingsActions) {
val palette = LocalPalette.current
val choices = listOf(
"" to stringResource(R.string.nav_app_auto),
NavApp.GoogleMaps.id to stringResource(R.string.nav_app_google),
NavApp.OsmAnd.id to stringResource(R.string.nav_app_osmand),
NavApp.PREF_ASK to stringResource(R.string.nav_app_ask),
)
Group(stringResource(R.string.nav_app)) {
choices.forEachIndexed { i, (id, label) ->
if (i > 0) Rule()
val installed = id == "" || id == NavApp.PREF_ASK || id in state.navApps
SettingRow(
Icons.Filled.Navigation,
label,
subtitle = if (installed) null else stringResource(R.string.nav_app_not_installed),
showIcon = i == 0,
enabled = installed,
onClick = { actions.navApp(id) },
trailing = { RadioButton(selected = state.prefs.navApp == id, enabled = installed, onClick = { actions.navApp(id) }) },
)
}
if (NavApp.OsmAnd.id in state.navApps) {
Rule()
SettingRow(
Icons.Filled.MyLocation,
stringResource(R.string.osmand_info),
subtitle = stringResource(R.string.osmand_info_line),
onClick = { actions.osmandInfo(!state.prefs.osmandInfo) },
trailing = { Switch(checked = state.prefs.osmandInfo, onCheckedChange = actions::osmandInfo) },
)
}
}
Text(
stringResource(R.string.phone_actions_line),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
/**
* Notification summaries: off by default; on needs Android's notification access too, which this
* explains. In a build without the listener the group says which build has it, and why.
*/
@Composable
internal fun NotificationSummaryGroup(state: SettingsState, actions: SettingsActions) {
val palette = LocalPalette.current
val on = state.prefs.notificationSummaries
Group(stringResource(R.string.notification_summaries)) {
if (!state.notificationsBuild) {
SettingRow(
Icons.Filled.Notifications,
stringResource(R.string.notification_summaries_switch),
subtitle = stringResource(R.string.notification_summaries_unavailable),
enabled = false,
onClick = {},
)
} else {
SettingRow(
Icons.Filled.Notifications,
stringResource(R.string.notification_summaries_switch),
subtitle = stringResource(R.string.notification_summaries_line),
onClick = { actions.notificationSummaries(!on) },
trailing = { Switch(checked = on, onCheckedChange = actions::notificationSummaries) },
)
if (on) {
Rule()
SettingRow(
Icons.Filled.Security,
stringResource(R.string.notification_access),
subtitle = stringResource(if (state.notificationAccess) R.string.notification_access_on else R.string.notification_access_off),
tint = if (state.notificationAccess) null else palette.warning,
onClick = actions::notificationAccess,
)
}
}
}
if (state.notificationsBuild) {
Text(
stringResource(R.string.notification_summaries_privacy),
style = MaterialTheme.typography.bodySmall,
color = palette.inkFaint,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
)
}
}
@Composable
private fun Group(title: String, content: @Composable () -> Unit) {
val palette = LocalPalette.current
@@ -581,6 +1008,139 @@ private fun languageLabel(prefs: Prefs): String = when (prefs.language) {
else -> AppLanguage.name(prefs.language) ?: stringResource(R.string.language_account)
}
/**
* "Test the wake word": for ten seconds the row says what the wake word is doing and whether the
* phrase landed ("Heard it"), while the assistant stays shut -- so the phrase, the sensitivity and
* the place can be tried without a sheet opening each time.
*/
@Composable
private fun WakeTestRow(state: SettingsState, on: Boolean, phrase: String, actions: SettingsActions) {
val palette = LocalPalette.current
val test = state.wakeTest
val heard = stringResource(R.string.wake_test_heard) + if (test.heard > 1) " ×${test.heard}" else ""
val say = stringResource(R.string.wake_test_say, phrase)
SettingRow(
if (test.heard > 0) Icons.Filled.CheckCircle else Icons.Filled.Mic,
stringResource(R.string.wake_test),
subtitle = when {
!on -> stringResource(R.string.wake_test_off)
test.running && test.heard > 0 -> heard + "\n" + say
test.running -> say + "\n" + wakeTitle(LocalContext.current, state.wakeState)
test.done && test.heard > 0 -> heard
test.done -> stringResource(R.string.wake_test_missed)
else -> stringResource(R.string.wake_test_line)
},
tint = when {
!on -> null
test.heard > 0 -> palette.accent
test.done -> palette.warning
else -> null
},
enabled = on,
onClick = actions::wakeTest,
)
}
/**
* "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) {
WakeSensitivity.Low -> R.string.wake_sensitivity_low
WakeSensitivity.Normal -> R.string.wake_sensitivity_normal
WakeSensitivity.High -> R.string.wake_sensitivity_high
}
/**
* One of the wake word's lists, as a sheet: the greetings, the names (Google's says that a Google
* device nearby answers to it too), or the sensitivity with what each step trades. A pick is
* handed back as what to do with the actions.
*/
@Composable
fun WakeChoices(which: WakeChoice, prefs: Prefs, onPick: ((SettingsActions) -> Unit) -> Unit) {
val phrase = WakePhrases.byId(prefs.wakePhrase)
val google = stringResource(R.string.wake_name_google_line)
val title = stringResource(
when (which) {
WakeChoice.Greeting -> R.string.wake_greeting
WakeChoice.Name -> R.string.wake_name
WakeChoice.Sensitivity -> R.string.wake_sensitivity
},
)
// id, words, a line under them, whether it is the one chosen.
val choices: List<Choice> = when (which) {
WakeChoice.Greeting -> WakeWords.greetings.map { Choice(WakePhrase(it, phrase.name).id, it.words, null, it.id == phrase.greeting.id) }
WakeChoice.Name -> WakeWords.names.map {
Choice(WakePhrase(phrase.greeting, it).id, it.words, if (it.id == GOOGLE) google else null, it.id == phrase.name.id)
}
WakeChoice.Sensitivity -> WakeSensitivity.entries.map {
val line = when (it) {
WakeSensitivity.Low -> R.string.wake_sensitivity_low_line
WakeSensitivity.Normal -> R.string.wake_sensitivity_normal_line
WakeSensitivity.High -> R.string.wake_sensitivity_high_line
}
Choice(it.id, stringResource(sensitivityLabel(it)), stringResource(line), it.id == WakeSensitivity.byId(prefs.wakeSensitivity).id)
}
}
ChoiceList(title, choices) { id ->
onPick { actions -> if (which == WakeChoice.Sensitivity) actions.wakeSensitivity(id) else actions.wakePhrase(id) }
}
}
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. */
@Composable
private fun ChoiceList(title: String, choices: List<Choice>, onPick: (String) -> Unit) {
val palette = LocalPalette.current
LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 24.dp)) {
item {
Text(title, style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(start = 24.dp, end = 24.dp, bottom = 8.dp))
}
choices.forEach { choice ->
item(key = choice.id) {
Row(
Modifier
.fillMaxWidth()
.clickable { onPick(choice.id) }
.heightIn(min = 56.dp)
.padding(horizontal = 24.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
Text(choice.title, style = MaterialTheme.typography.bodyLarge)
choice.subtitle?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = palette.inkMuted) }
}
Spacer(Modifier.width(12.dp))
RadioButton(selected = choice.chosen, onClick = { onPick(choice.id) })
}
}
}
}
}
/**
* Settings › Language, as a sheet: the account's language (the default), the phone's, then every
* language the app has, each named in itself so a person who cannot read the current one still
@@ -1,4 +1,4 @@
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.9. Do not edit.
// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12. Do not edit.
package eu.llembas.android.ui.theme
import androidx.compose.ui.graphics.Color
@@ -38,13 +38,16 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.rememberTextMeasurer
@@ -61,7 +64,11 @@ import eu.llembas.android.api.ShowCard
import eu.llembas.android.lembas
import eu.llembas.android.ui.MarkdownText
import eu.llembas.android.ui.explain
import eu.llembas.android.ui.highlight
import eu.llembas.android.ui.highlights
import eu.llembas.android.ui.theme.LocalPalette
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
/**
@@ -74,15 +81,15 @@ private const val MARKDOWN_MAX_CHARS = 200_000
private sealed interface Loaded {
data object Loading : Loaded
/** [kind]: what the server said the file is, when it is only known once it came. */
data class Text(val text: String, val kind: String? = null) : Loaded
/** [kind], [language]: what the server said the file is, when it is only known once it came. */
data class Text(val text: String, val kind: String? = null, val language: String? = null) : Loaded
/** [unavailable]: this server has no door for the app to read the file through. */
data class Failed(val message: String, val unavailable: Boolean = false) : Loaded
}
/** What the viewer's title and body need to know before the text comes. */
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String)
private data class Viewed(val name: String, val path: String, val line: Int, val kind: String, val language: String = "")
/**
* What a `show` card opens: the file, full screen, read-only, as the chat sees it now.
@@ -97,7 +104,7 @@ private data class Viewed(val name: String, val path: String, val line: Int, val
@Composable
fun FileViewer(chatId: String, show: ShowCard, onClose: () -> Unit) {
Viewer(
file = Viewed(show.name, show.path, show.line, show.viewKind),
file = Viewed(show.name, show.path, show.line, show.viewKind, show.language),
key = chatId to show,
webUrl = { it.webViewer(chatId, show) },
load = { api, _ -> Loaded.Text(api.shownText(chatId, show)) },
@@ -120,7 +127,7 @@ fun TreeFileViewer(path: String, onClose: () -> Unit) {
val file = api.fileContent(path)
val withheld = file.withheld
when {
withheld == null -> Loaded.Text(file.text, file.viewKind)
withheld == null -> Loaded.Text(file.text, file.viewKind, file.language)
withheld.message.isNotBlank() -> Loaded.Failed(withheld.message)
withheld.reason == "too_large" -> Loaded.Failed(context.getString(R.string.viewer_too_large))
else -> Loaded.Failed(context.getString(R.string.viewer_not_text))
@@ -217,15 +224,20 @@ private fun Viewer(file: Viewed, key: Any, webUrl: (ApiClient) -> String?, load:
}
}
is Loaded.Text -> Body(now.kind ?: file.kind, file.line, now.text)
is Loaded.Text -> FileBody(now.kind ?: file.kind, now.language ?: file.language, file.line, now.text)
}
}
}
}
}
/**
* A file's text as the viewer draws it, from these alone (what the screenshot tests draw):
* Markdown rendered, anything else as numbered lines -- code in the theme's colours when its
* [language] is one [highlight] reads. Read-only either way.
*/
@Composable
private fun Body(kind: String, line: Int, text: String) {
fun FileBody(kind: String, language: String, line: Int, text: String) {
val palette = LocalPalette.current
if (kind == "markdown" && text.length <= MARKDOWN_MAX_CHARS) {
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp)) {
@@ -247,7 +259,7 @@ private fun Body(kind: String, line: Int, text: String) {
modifier = Modifier.fillMaxWidth().background(palette.bgSunken).padding(horizontal = 16.dp, vertical = 10.dp),
)
}
Lines(text, line)
Lines(text, line, language)
}
}
@@ -258,12 +270,14 @@ private fun Body(kind: String, line: Int, text: String) {
* text rather than under the numbers.
*/
@Composable
private fun Lines(text: String, line: Int) {
private fun Lines(text: String, line: Int, language: String) {
val palette = LocalPalette.current
val rows = remember(text) {
val split = text.split('\n')
if (split.size > 1 && split.last().isEmpty()) split.dropLast(1) else split
val plain = remember(text) { linesOf(AnnotatedString(text)) }
// Highlighted off the main thread: a long file shows plain for a moment, then in colour.
val coloured by produceState<List<AnnotatedString>?>(null, text, language, palette) {
if (highlights(language)) value = withContext(Dispatchers.Default) { linesOf(highlight(text, language, palette)) }
}
val rows = coloured ?: if (LocalInspectionMode.current && highlights(language)) linesOf(highlight(text, language, palette)) else plain
val style = TextStyle(fontFamily = FontFamily.Monospace, fontSize = 13.sp, lineHeight = 18.sp, color = palette.ink)
val measurer = rememberTextMeasurer()
val density = LocalDensity.current
@@ -286,12 +300,27 @@ private fun Lines(text: String, line: Int) {
) {
Text((i + 1).toString(), style = style.copy(color = palette.inkFaint), textAlign = TextAlign.End, modifier = Modifier.width(gutter))
Spacer(Modifier.width(12.dp))
Text(row.ifEmpty { " " }, style = style, modifier = Modifier.weight(1f))
Text(if (row.isEmpty()) AnnotatedString(" ") else row, style = style, modifier = Modifier.weight(1f))
}
}
}
}
/** [text]'s lines, each with its own spans; a final newline makes no empty last line. */
private fun linesOf(text: AnnotatedString): List<AnnotatedString> {
val out = mutableListOf<AnnotatedString>()
var start = 0
while (true) {
val end = text.text.indexOf('\n', start)
if (end < 0) {
if (start < text.length || out.isEmpty()) out += text.subSequence(start, text.length)
return out
}
out += text.subSequence(start, end)
start = end + 1
}
}
private fun copy(context: Context, label: String, text: String) {
context.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText(label, text))
}
@@ -10,9 +10,12 @@ import android.net.Uri
import android.provider.Settings
import eu.llembas.android.BuildConfig
import eu.llembas.android.R
import eu.llembas.android.api.AppRelease
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.SharedHttp
import eu.llembas.android.api.await
import eu.llembas.android.lembas
import eu.llembas.android.notify.NotificationAccess
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
@@ -20,9 +23,34 @@ import okhttp3.Request
import java.io.File
import java.security.MessageDigest
/** What llembas.eu says the newest release is (`site/android/latest.json`, written at release). */
/** One APK of a release: where it is and its SHA-256. */
@Serializable
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "")
data class LatestFile(val url: String, val sha256: String)
/**
* What llembas.eu says the newest release is (`site/android/latest.json`, written at release):
* the standard APK as [url] and [sha256], and the `notifications` build's (the same app with the
* notification listener) as [notifications] when the release has one.
*/
@Serializable
data class Latest(val version: String, val url: String, val sha256: String, val notes: String = "", val notifications: LatestFile? = null) {
/**
* The file this build updates itself to: its own kind, never the other. A `notifications`
* build that installed the standard APK would lose its listener without a word (same id,
* same key: Android takes it), so without its own file it installs nothing.
*/
fun fileFor(notificationsBuild: Boolean): LatestFile? = if (notificationsBuild) notifications else LatestFile(url, sha256)
/**
* The same, with what the instance says of the release it recommends (`GET /api/v2/apps`,
* its entry's `notifications` build) for a manifest that names no notifications file -- but
* only when both speak of the same version, and the address is https.
*/
fun fileFor(notificationsBuild: Boolean, recommended: AppRelease?): LatestFile? = fileFor(notificationsBuild)
?: recommended?.takeIf { notificationsBuild && it.version == version }?.notifications
?.takeIf { it.url.startsWith("https://") && it.sha256.isNotBlank() }
?.let { LatestFile(it.url, it.sha256) }
}
/**
* The `full` build updates itself, as LLeMbas Desktop does: the manifest on the website names
@@ -47,12 +75,20 @@ class Updater(private val context: Context) {
)
return@withContext context.getString(R.string.update_allow_installs)
}
// Its own kind: from the manifest, else from the instance's recommendation of the same release.
val recommended = if (NotificationAccess.AVAILABLE && latest.notifications == null) {
runCatching { context.lembas.instances.client()?.apps()?.android }.getOrNull()
} else {
null
}
val file = latest.fileFor(NotificationAccess.AVAILABLE, recommended)
?: return@withContext context.getString(R.string.update_notifications_manual)
val apk = File(context.cacheDir, "update.apk")
SharedHttp.newCall(Request.Builder().url(latest.url).build()).await().use { response ->
SharedHttp.newCall(Request.Builder().url(file.url).build()).await().use { response ->
if (!response.isSuccessful) return@withContext context.getString(R.string.update_unreachable)
apk.outputStream().use { out -> response.body!!.byteStream().copyTo(out) }
}
if (sha256(apk) != latest.sha256.lowercase()) {
if (sha256(apk) != file.sha256.lowercase()) {
apk.delete()
return@withContext context.getString(R.string.update_bad_file)
}
@@ -0,0 +1,433 @@
package eu.llembas.android.wake
import android.content.Context
import eu.llembas.android.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
/** One word of a wake phrase: its [id], how it is written for the person, and its spelling in the model's [pieces]. */
data class WakeWord(val id: String, val words: String, val pieces: String)
/**
* A wake phrase: a greeting and a name ("Hey Assistant"). What the person says ([words]), the
* engine's spelling of it ([tokens], the model's BPE pieces -- generated with its `bpe.model` by
* `scripts/gen-wake-phrases.py`, since the phone has no tokenizer), and the [id] Settings keeps.
*
* Only words from [WakeWords] can be chosen: an open-vocabulary spotter hears any phrase it can
* spell, but one it was never trained to hear (a made-up name) has to be repeated until it lands,
* and a free text box would invite one that fires on every other sentence. English only: the
* model is trained on English speech.
*/
data class WakePhrase(val greeting: WakeWord, val name: WakeWord) {
val id: String get() = "${greeting.id}_${name.id}"
val words: String get() = "${greeting.words} ${name.words}"
val tokens: String get() = "${greeting.pieces} ${name.pieces}"
}
object WakePhrases {
/** "Hey Assistant". */
val default: WakePhrase = WakePhrase(WakeWords.greetings.first { it.id == "hey" }, WakeWords.names.first { it.id == "assistant" })
val all: List<WakePhrase> = WakeWords.greetings.flatMap { greeting -> WakeWords.names.map { WakePhrase(greeting, it) } }
/**
* The phrase Settings saved as [id] (`greeting_name`). An id that is no longer a phrase --
* the "Lembas" ones of the first wake word, which the model could not hear -- is the default.
*/
fun byId(id: String): WakePhrase = all.firstOrNull { it.id == id } ?: default
}
/**
* How easily the phrase is taken as heard: Settings › Wake word › Sensitivity.
*
* The engine has two numbers per keyword (sherpa-onnx's keyword-spotting documentation): a
* boosting score that keeps the phrase's path alive in the search ([boost], larger is easier),
* and a trigger threshold, the least probability the heard pieces must reach ([threshold], 0 to
* 1, lower is easier). Normal is the engine's own default threshold with the boost its
* documentation uses for a two-word phrase; Low takes that documentation's stricter example
* (0.35), High goes as far below the default as Low goes above it. Starting values: nobody has
* measured them on a phone yet.
*/
enum class WakeSensitivity(val id: String, val boost: Float, val threshold: Float) {
Low("low", 1.0f, 0.35f),
Normal("normal", 1.5f, 0.25f),
High("high", 2.0f, 0.15f),
;
companion object {
fun byId(id: String): WakeSensitivity = entries.firstOrNull { it.id == id } ?: Normal
}
}
/**
* The engine, as the service sees it: 16 kHz mono samples in, the phrase out when it was heard.
* Everything happens on the phone; [accept] neither records nor sends anything.
*/
interface WakeDetector {
/** Feed [samples] (-1..1); true when the wake word ended in them. */
fun accept(samples: FloatArray): Boolean
fun release()
}
/** The microphone, as the listener sees it: 16 kHz mono samples, already recording when it is made. */
interface WakeMicrophone {
/** Fill [into]; how many samples were read, or a negative number when the microphone failed. */
fun read(into: ShortArray): Int
fun close()
}
/**
* Whether the assistant's sheet is up -- the wake-word service lets go of the microphone while
* it is, and takes it back once the sheet is gone. Counted, since the session and the activity
* can overlap for a moment when one hands over to the other.
*
* The wake word's own hold is apart from the count: when the word is heard the microphone is
* the sheet's for a few seconds ([holdFor]), whether or not a sheet then says it is up. It ends
* by itself on a scope that outlives the service, so a service that is destroyed in those
* seconds cannot leave the wake word "paused while the assistant is open" for good.
*/
object AssistPresence {
private val sheets = MutableStateFlow(0)
private val held = MutableStateFlow(0L)
private val holds = AtomicLong(0)
private val _open = MutableStateFlow(0)
val open: StateFlow<Int> = _open.asStateFlow()
private val process = CoroutineScope(SupervisorJob() + Dispatchers.Default)
private fun count() {
_open.value = sheets.value + if (held.value != 0L) 1 else 0
}
fun shown() {
sheets.update { it + 1 }
count()
}
fun hidden() {
sheets.update { (it - 1).coerceAtLeast(0) }
count()
}
/** The word was heard: the microphone is the sheet's for [millis], then the hold lets go by itself. */
fun holdFor(millis: Long, scope: CoroutineScope = process) {
// Each hold has a number of its own, never used twice, so an old one cannot end a newer one.
val mine = holds.incrementAndGet()
held.value = mine
count()
scope.launch {
try {
delay(millis)
} finally {
// Only the newest hold lets go; an older one that ends later changes nothing.
if (held.compareAndSet(mine, 0L)) count()
}
}
}
/** No hold is left standing: the wake-word service starts from what the sheets say alone. */
fun release() {
held.value = 0L
count()
}
}
/** Whether the app has an activity on screen: counted from every activity's start and stop (LembasApp). */
object AppVisibility {
private val started = AtomicInteger(0)
val visible: Boolean get() = started.get() > 0
fun activityStarted() {
started.incrementAndGet()
}
fun activityStopped() {
started.updateAndGet { (it - 1).coerceAtLeast(0) }
}
}
/**
* Why listening for the wake word is paused, or [None]: what the notification and Settings say.
* [Silent] is the one the listener finds out itself: the microphone is open but gives no sound at
* all, which is what Android hands a background app while a call or another recorder has it, or
* while the phone's microphone switch is off.
*/
enum class WakePause { None, ScreenOff, BatterySaver, Assistant, NoMicrophone, Silent }
/**
* When the service listens, from what the phone is doing: never while the sheet is up (it has the
* microphone), never in battery saver (the person asked the phone to spare power), and -- when
* Settings says so, the default -- only while the screen is on.
*/
fun wakePause(screenOn: Boolean, screenOnly: Boolean, batterySaver: Boolean, sheetOpen: Boolean, micAllowed: Boolean): WakePause = when {
!micAllowed -> WakePause.NoMicrophone
sheetOpen -> WakePause.Assistant
batterySaver -> WakePause.BatterySaver
screenOnly && !screenOn -> WakePause.ScreenOff
else -> WakePause.None
}
/** What went wrong: this build has no engine, the model's files, the engine itself, or the microphone. */
enum class WakeFailure { NoEngine, Model, Engine, Microphone }
/** A failure with its kind, so the notification and Settings can say it in plain words. */
class WakeError(val why: WakeFailure, cause: Throwable? = null, message: String? = cause?.message) : Exception(message, cause) {
/** The technical half, for Settings and the log: the exception's name and what it said. */
val detail: String
get() = listOfNotNull(cause?.javaClass?.simpleName, message?.takeIf { it.isNotBlank() }).joinToString(": ").take(DETAIL_MAX)
private companion object {
const val DETAIL_MAX = 200
}
}
/**
* What the wake word is doing, the one truth the service, its notification and Settings all read
* ([WakeStatus.state]). [Failed] carries the plain reason and the technical [Failed.detail];
* nothing here is ever a guess from the settings alone.
*/
sealed interface WakeState {
/** Not running: turned off, or the phone stopped the service. */
data object Off : WakeState
/** Running, loading the engine. */
data object Starting : WakeState
/** The microphone is open and the engine hears it, for these words. */
data class Listening(val phrase: String) : WakeState
data class Paused(val why: WakePause) : WakeState
data class Failed(val why: WakeFailure, val detail: String = "") : WakeState
}
/**
* "Test the wake word" (Settings): until [until] (the phone's elapsed time, in ms) a heard phrase
* is counted in [heard] instead of opening the assistant. A deadline, not a switch, so a test
* nobody ends cannot leave the wake word deaf.
*/
data class WakeTrial(val until: Long = 0, val heard: Int = 0)
/**
* The wake word's state for the whole process: written by the service, read by everything else.
*
* A service instance writes with the token [begin] gave it, and only the newest token's writes
* count: an old instance on its way out (its loop ending after Settings turned the wake word off
* and on again) cannot write its "off" over the new one's state.
*/
object WakeStatus {
private val _state = MutableStateFlow<WakeState>(WakeState.Off)
val state: StateFlow<WakeState> = _state.asStateFlow()
private val _trial = MutableStateFlow(WakeTrial())
val trial: StateFlow<WakeTrial> = _trial.asStateFlow()
private val _retries = MutableStateFlow(0)
/** Counts up each time somebody asks for a retry now ([retryNow]). */
val retries: StateFlow<Int> = _retries.asStateFlow()
private val generation = AtomicInteger(0)
/** A new writer takes over: its token, which makes every older one's writes count for nothing. */
fun begin(): Int = generation.incrementAndGet()
/** [now], if [token] is still the newest writer's. */
fun set(token: Int, now: WakeState) {
synchronized(generation) {
if (token == generation.get()) _state.value = now
}
}
/** [now], said by the app itself, outside any service instance: not started and why, turned off. */
fun set(now: WakeState) {
synchronized(generation) { _state.value = now }
}
/** Try again now, instead of when the back-off says: the person tapped the failure. */
fun retryNow() = _retries.update { it + 1 }
/** Start a test at [now]: the next [TRIAL_MS] of heard phrases are counted, not acted on. */
fun startTrial(now: Long) {
_trial.value = WakeTrial(until = now + TRIAL_MS)
}
/** The phrase was heard at [now]: true when a test took it, so the assistant stays shut. */
fun heardInTrial(now: Long): Boolean {
var taken = false
_trial.update { trial ->
taken = now < trial.until
if (taken) trial.copy(heard = trial.heard + 1) else trial
}
return taken
}
const val TRIAL_MS = 10_000L
}
/**
* One [attempt] in plain words, a line each: when and for which phrase; what was tried and how it
* went (Android's own words where it refused); what was done instead; and, where the assistant
* could not be used, what Android had said of it -- whether LLeMbas held the role, and when the
* service was connected and disconnected in this run of the app.
*/
fun wakeAttemptWords(context: Context, attempt: WakeAttempt, zone: ZoneId = ZoneId.systemDefault(), locale: Locale = Locale.getDefault()): List<String> {
fun time(at: Long): String = DateTimeFormatter.ofPattern("EEE d MMM, HH:mm:ss", locale).format(Instant.ofEpochMilli(at).atZone(zone))
val lines = mutableListOf("${time(attempt.at)} · “${attempt.phrase}”")
lines += when (attempt.outcome) {
WakeAttempt.OUT_OPENED -> context.getString(R.string.wake_out_opened)
WakeAttempt.OUT_TESTED -> context.getString(R.string.wake_out_tested)
WakeAttempt.OUT_NO_SHEET -> context.getString(R.string.wake_out_no_sheet)
WakeAttempt.OUT_REFUSED -> context.getString(R.string.wake_out_refused, attempt.detail)
else -> context.getString(R.string.wake_out_not_connected)
}
when (attempt.fallback) {
WakeWay.Activity.id -> lines += context.getString(R.string.wake_out_activity)
WakeWay.Notification.id -> lines += context.getString(R.string.wake_out_notification)
}
if (attempt.outcome == WakeAttempt.OUT_TESTED) return lines
if (attempt.sheetMs >= 0) lines += context.getString(R.string.wake_sheet_ms, attempt.sheetMs.toString())
if (attempt.outcome == WakeAttempt.OUT_OPENED) return lines
// Why the assistant's own way was not there, from what Android itself said at that moment.
lines += when {
!attempt.assistant -> context.getString(R.string.wake_role_not_held)
!attempt.recognizers -> context.getString(R.string.wake_no_recognizers)
!attempt.active -> context.getString(R.string.wake_not_active)
else -> context.getString(R.string.wake_role_held)
}
if (attempt.waited) lines += context.getString(R.string.wake_waited)
if (attempt.showFailed) lines += context.getString(R.string.wake_show_failed)
lines += if (attempt.readyAt == 0L) context.getString(R.string.wake_link_never) else context.getString(R.string.wake_link_ready, time(attempt.readyAt))
if (attempt.shutdownAt != 0L) lines += context.getString(R.string.wake_link_shutdown, time(attempt.shutdownAt))
if (attempt.connectedLater != 0L) lines += context.getString(R.string.wake_link_later, time(attempt.connectedLater))
// The rest as it was noted, for whoever looks for the cause: names and values, not a sentence.
lines += listOf(
"screen=${if (attempt.screenOn) "on" else "off"}",
"locked=${attempt.locked}",
"visible=${attempt.visible}",
"created=${if (attempt.createdAt == 0L) "-" else time(attempt.createdAt)}",
"destroyed=${if (attempt.destroyedAt == 0L) "-" else time(attempt.destroyedAt)}",
"prepared=${attempt.prepared}",
).joinToString(" ")
return lines
}
/**
* What the service's notification says the moment Android starts it (again): what is true --
* [current], while its loop is [running]; "starting" for a service that has only just begun.
* Never a phrase by default.
*/
fun wakeStateAtStart(running: Boolean, current: WakeState): WakeState = if (running && current != WakeState.Off) current else WakeState.Starting
/**
* [state] in plain words: the notification's title and Settings' line. A failure names what
* failed and that it is tried again; it never claims to listen while it does not.
*/
fun wakeTitle(context: Context, state: WakeState): String = when (state) {
WakeState.Off -> context.getString(R.string.wake_off)
WakeState.Starting -> context.getString(R.string.wake_starting)
is WakeState.Listening -> context.getString(R.string.wake_listening_for, state.phrase)
is WakeState.Paused -> context.getString(
when (state.why) {
WakePause.None -> R.string.wake_starting
WakePause.ScreenOff -> R.string.wake_paused_screen
WakePause.BatterySaver -> R.string.wake_paused_battery
WakePause.Assistant -> R.string.wake_paused_assistant
WakePause.NoMicrophone -> R.string.wake_paused_microphone
WakePause.Silent -> R.string.wake_paused_silent
},
)
is WakeState.Failed -> context.getString(
when (state.why) {
WakeFailure.NoEngine -> R.string.wake_failed_no_engine
WakeFailure.Model -> R.string.wake_failed_model
WakeFailure.Engine -> R.string.wake_failed_engine
WakeFailure.Microphone -> R.string.wake_failed_microphone
},
)
}
/** The notification's second line: the promise while it listens, else nothing more to say. */
fun wakeLine(context: Context, state: WakeState): String? = when (state) {
is WakeState.Listening -> context.getString(R.string.wake_notification_line)
is WakeState.Failed -> if (state.why == WakeFailure.NoEngine) null else context.getString(R.string.wake_failed_line)
else -> null
}
/**
* The engine's keywords file for [phrase]: its pieces, `:` the boosting score, `#` the trigger
* threshold, then `@` and the id the engine answers with (sherpa-onnx's syntax; no space after
* `:` or `#`). A phrase of fewer than five pieces is short enough to turn up inside other speech,
* so it has to be a little surer ([SHORT_PHRASE_STRICTER]).
*/
fun wakeKeywords(phrase: WakePhrase, sensitivity: WakeSensitivity = WakeSensitivity.Normal): String {
val short = phrase.tokens.split(' ').size < SHORT_PHRASE_PIECES
val threshold = sensitivity.threshold + if (short) SHORT_PHRASE_STRICTER else 0f
// Locale.ROOT: a decimal comma would not be a number to the engine.
return String.format(Locale.ROOT, "%s :%.1f #%.2f @%s\n", phrase.tokens, sensitivity.boost, threshold, phrase.id)
}
private const val SHORT_PHRASE_PIECES = 5
private const val SHORT_PHRASE_STRICTER = 0.05f
/**
* Every piece of [keywords] must be in the model's token table ([tokens], `tokens.txt`: a piece
* and its number per line): the engine ends the whole app on a piece it does not know, so it is
* never handed one.
*/
fun checkKeywords(keywords: String, tokens: String) {
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
for (line in keywords.lineSequence().filter { it.isNotBlank() }) {
val unknown = line.split(' ').filter { it.isNotEmpty() && it[0] !in ":#@" }.firstOrNull { it !in known }
if (unknown != null) throw WakeError(WakeFailure.Engine, message = "the model has no piece \"$unknown\"")
}
}
/**
* The model's files, out of the APK's assets into [dir], where the engine reads them as files.
* Copied by stream ([open] is `AssetManager.open`), so it works however the APK stores them, and
* keyed by the assets' `version` (a hash of the pinned model, written by
* `scripts/fetch-wakeword.py`): a new model replaces the old one, and a copy that was cut short
* has no marker and is made again.
*/
fun unpackWakeModel(open: (String) -> InputStream, dir: File, files: List<String>) {
val version = open("version").use { it.readBytes().decodeToString().trim() }
val marker = File(dir, "version")
if (marker.isFile && marker.readText() == version && files.all { File(dir, it).length() > 0 }) return
if (!dir.isDirectory && !dir.mkdirs()) throw IOException("cannot make ${dir.name}")
marker.delete()
for (name in files) {
val part = File(dir, "$name.part")
open(name).use { input -> part.outputStream().use { input.copyTo(it) } }
if (part.length() == 0L) throw IOException("$name is empty")
val target = File(dir, name)
target.delete()
if (!part.renameTo(target)) throw IOException("cannot write $name")
}
marker.writeText(version)
}
/** How long to wait before the next try after the [attempt]-th failure in a row: 2 s, 5 s, 15 s, 1 min, then every 5 min. */
fun wakeBackoff(attempt: Int): Long = listOf(2_000L, 5_000L, 15_000L, 60_000L).getOrElse(attempt) { 300_000L }
@@ -0,0 +1,207 @@
package eu.llembas.android.wake
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/** What the service wants right now: this phrase, spelled for the engine as [keywords], unless [pause]d. */
data class WakePlan(val phrase: WakePhrase, val keywords: String, val pause: WakePause)
/**
* The listening itself, apart from Android so it can be tested: follows the plans, keeps one
* engine and one microphone, and says every change of state through [say].
*
* Nothing fails silently. An engine that does not load, a microphone that does not start or
* stops giving samples: each is a [WakeState.Failed] with its reason, logged, and tried again
* after [backoff]. And the engine is never released while a loop may still be feeding it: a new
* plan first cancels the old loop and waits for it to end ([cancelAndJoin]), then the engine is
* swapped, on the one coroutine that owns it.
*/
class WakeListener(
private val say: (WakeState) -> Unit,
private val engine: (keywords: String) -> WakeDetector,
private val microphone: () -> WakeMicrophone,
private val heard: suspend (WakePhrase) -> Unit,
private val work: CoroutineDispatcher = Dispatchers.IO,
private val backoff: (attempt: Int) -> Long = ::wakeBackoff,
private val log: (String, Throwable) -> Unit = { _, _ -> },
) {
@Volatile private var detector: WakeDetector? = null
@Volatile private var detectorFor: String? = null
/** Listen as [plans] say, until the flow ends or this is cancelled; the engine is released on the way out. */
suspend fun follow(plans: Flow<WakePlan>) = coroutineScope {
// Where a heard word is answered: beside the listening, so a pause does not cancel the answer.
val answers = this
var hearing: Job? = null
try {
plans.distinctUntilChanged().collect { plan ->
hearing?.cancelAndJoin()
hearing = null
if (plan.pause != WakePause.None) {
say(WakeState.Paused(plan.pause))
} else {
hearing = launch { hear(plan) { phrase -> answers.launch { heard(phrase) } } }
}
}
} finally {
withContext(NonCancellable) {
hearing?.cancelAndJoin()
release()
}
}
}
private fun release() {
runCatching { detector?.release() }
detector = null
detectorFor = null
}
private val nudges = MutableStateFlow(0)
/** How many samples the last stretch of listening heard before it ended. */
@Volatile private var listened = 0L
/** Try again now rather than when the back-off says: somebody asked. The count of failures starts over. */
fun retryNow() = nudges.update { it + 1 }
/** Listen for [plan]'s phrase until cancelled: after the word, again; after a failure, again later. */
private suspend fun hear(plan: WakePlan, heardIt: (WakePhrase) -> Unit) {
var failures = 0
while (true) {
try {
listened = 0
listen(plan)
failures = 0
// Handed to the caller's scope, not run here: answering the word usually pauses
// the listening (the sheet takes the microphone), which cancels this very loop --
// and must not cancel the answer with it.
heardIt(plan.phrase)
// The sheet takes the microphone now (a new plan cancels this); otherwise listen again.
delay(HEARD_REST_MS)
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
log("wake word: ${e.why}: ${e.detail}", e)
say(WakeState.Failed(e.why, e.detail))
// A build without an engine does not grow one: nothing to try again.
if (e.why == WakeFailure.NoEngine) return
// It had been listening well for a while: this is a new trouble, not the old one again.
if (listened >= STEADY_SAMPLES) failures = 0
val seen = nudges.value
val asked = withTimeoutOrNull(backoff(failures++)) { nudges.first { it != seen } } != null
if (asked) failures = 0
}
}
}
/** One stretch of listening: returns when the word was heard, throws a [WakeError] when something failed. */
private suspend fun listen(plan: WakePlan) {
val spotter = engineFor(plan)
try {
withContext(work) {
// Opened and closed on this one thread, so a cancellation cannot leave it open.
val mic = try {
microphone()
} catch (e: Exception) {
throw WakeError(WakeFailure.Microphone, e)
}
try {
say(WakeState.Listening(plan.phrase.words))
val chunk = ShortArray(CHUNK)
var empty = 0
var silent = 0
while (true) {
ensureActive()
val read = mic.read(chunk)
if (read < 0) throw WakeError(WakeFailure.Microphone, message = "the microphone stopped (error $read)")
if (read == 0) {
if (++empty > EMPTY_READS) throw WakeError(WakeFailure.Microphone, message = "the microphone gives no samples")
continue
}
empty = 0
listened += read
val samples = FloatArray(read)
var sound = false
for (i in 0 until read) {
if (chunk[i] != 0.toShort()) sound = true
samples[i] = chunk[i] / 32768f
}
// Exact silence for seconds is not a quiet room: Android gives a background
// app zeros while another app has the microphone or its switch is off.
if (sound) {
if (silent >= SILENT_SAMPLES) say(WakeState.Listening(plan.phrase.words))
silent = 0
} else if (silent < SILENT_SAMPLES) {
silent += read
if (silent >= SILENT_SAMPLES) say(WakeState.Paused(WakePause.Silent))
}
if (spotter.accept(samples)) break
}
} finally {
runCatching { mic.close() }
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// The engine threw while hearing: it is not trusted again, a new one is made.
release()
throw WakeError(WakeFailure.Engine, e)
}
}
/** The engine for [plan]'s keywords: the one there is, or a new one once the old is released. */
private suspend fun engineFor(plan: WakePlan): WakeDetector {
detector?.takeIf { detectorFor == plan.keywords }?.let { return it }
release()
say(WakeState.Starting)
return try {
// Kept the moment it exists, so a cancellation while it loads cannot lose it unreleased.
withContext(work) {
engine(plan.keywords).also {
detector = it
detectorFor = plan.keywords
}
}
} catch (e: CancellationException) {
throw e
} catch (e: WakeError) {
throw e
} catch (e: Throwable) {
// A missing native library is an Error, not an Exception: it is a failure to show all the same.
throw WakeError(WakeFailure.Engine, e)
}
}
companion object {
const val RATE = 16_000
/** A tenth of a second at a time. */
private const val CHUNK = RATE / 10
private const val EMPTY_READS = 50
private const val SILENT_SAMPLES = RATE * 5
private const val HEARD_REST_MS = 1_500L
/** Half a minute of sound taken in: the microphone and the engine work. */
private const val STEADY_SAMPLES = RATE * 30L
}
}
@@ -0,0 +1,303 @@
package eu.llembas.android.wake
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.serialization.Serializable
/**
* What happened the last times the wake word was heard: kept (the last [WAKE_LOG_SIZE], in the
* phone's settings) and shown in Settings › Wake word, because "it heard me and nothing opened"
* cannot be put right without knowing which step said no. Nothing of the account is in it: the
* phrase, clock times, and Android's own words where it refused.
*/
@Serializable
data class WakeAttempt(
/** When the phrase was heard (wall clock, ms). */
val at: Long = 0,
val phrase: String = "",
/** What was tried first: a [WakeWay]'s id. */
val way: String = "",
/** How that went: one of the `OUT_…` words. */
val outcome: String = "",
/** Android's own words when it refused: the exception's class and message. */
val detail: String = "",
/** What was done instead, when the first way did not open the sheet: `activity`, `notification` or nothing. */
val fallback: String = "",
/** Whether Android said LLeMbas holds the assistant role at that moment. */
val assistant: Boolean = false,
/** When Android last connected the assistant service in this run of the app, and last disconnected it; 0: never. */
val readyAt: Long = 0,
val shutdownAt: Long = 0,
/** Set afterwards, when the service was not connected and Android connected it later. */
val connectedLater: Long = 0,
/**
* Whether Android itself said LLeMbas's service is its active voice-interaction service
* (`VoiceInteractionService.isActiveService`). The role can be held without it: Android then
* opens the assistant as an ordinary screen on a long press, and keeps no connection that
* could open it from the background.
*/
val active: Boolean = false,
/** Whether the phone has voice recognisers at all (`FEATURE_VOICE_RECOGNIZERS`): without it Android runs no voice-interaction service. */
val recognizers: Boolean = true,
val screenOn: Boolean = true,
val locked: Boolean = false,
/** Whether one of the app's own screens was showing. */
val visible: Boolean = false,
/** How long the sheet took to say it was up, in ms; -1 when none came. */
val sheetMs: Long = -1,
/** When the assistant service was last made and destroyed in this run of the app; 0: never. */
val createdAt: Long = 0,
val destroyedAt: Long = 0,
/** Whether the wake waited for Android to connect the service (it was active but not connected yet). */
val waited: Boolean = false,
/** What Android told the service about this show (API 34+): it prepared one, or it failed. */
val prepared: Boolean = false,
val showFailed: Boolean = false,
) {
companion object {
/** The sheet came up. */
const val OUT_OPENED = "opened"
/** Android was asked and did not refuse, but no sheet came up in time. */
const val OUT_NO_SHEET = "no_sheet"
/** The assistant service was not connected (`LembasAssistService.current` was null). */
const val OUT_NOT_CONNECTED = "not_connected"
/** Android refused, with [detail]. */
const val OUT_REFUSED = "refused"
/** A test in Settings took the word: nothing was to open. */
const val OUT_TESTED = "tested"
}
}
const val WAKE_LOG_SIZE = 5
/** [log] with [attempt] put first, cut to the last [WAKE_LOG_SIZE]. */
fun wakeLogAdd(log: List<WakeAttempt>, attempt: WakeAttempt): List<WakeAttempt> = (listOf(attempt) + log).take(WAKE_LOG_SIZE)
/**
* Android connected the assistant service at [now]: the newest attempt that found it not
* connected, and has not been answered yet, is told so. Anything else is left as it is.
*/
fun wakeLogConnected(log: List<WakeAttempt>, now: Long): List<WakeAttempt> {
val newest = log.firstOrNull() ?: return log
if (newest.outcome != WakeAttempt.OUT_NOT_CONNECTED || newest.connectedLater != 0L || now < newest.at) return log
return listOf(newest.copy(connectedLater = now)) + log.drop(1)
}
/** The ways the assistant may be opened when the word was heard, in the order they are worth trying. */
enum class WakeWay(val id: String) {
/** The assistant service is connected and the screen is on: it shows its sheet, from anywhere. */
Session("session"),
/**
* The assistant service is connected and the screen is off: a session's window turns no
* screen on, so the sheet's activity is started through the service instead (Android lets an
* app whose service the system has bound start one), and the activity turns the screen on.
*/
AssistantActivity("assistant_activity"),
/** No connected assistant service, but the app is on screen: the sheet's activity may start. */
Activity("activity"),
/**
* Neither: Android blocks an activity started from the background, and says nothing when it
* does -- so it is not relied on, and a notification to tap is posted.
*/
Notification("notification"),
// A further way (answering by voice without a sheet) would be one more entry here, chosen in
// [wakeWay] and carried out where the others are.
}
/** The first way to try, from what is true at that moment. */
fun wakeWay(connected: Boolean, screenOn: Boolean, appVisible: Boolean): WakeWay = when {
connected && screenOn -> WakeWay.Session
connected -> WakeWay.AssistantActivity
appVisible -> WakeWay.Activity
else -> WakeWay.Notification
}
/**
* The assistant service's life in this run of the app, as Android told it: when it was made,
* connected (`onReady`), disconnected (`onShutdown`) and destroyed, what Android said of the last
* show it was asked for, and when a sheet last came up. Written by the assistant service, the
* session and the sheet's activity; read when the word is heard.
*/
object AssistLink {
@Volatile var createdAt = 0L
private set
@Volatile var destroyedAt = 0L
private set
@Volatile var readyAt = 0L
private set
@Volatile var shutdownAt = 0L
private set
/** On the phone's elapsed clock: when Android last said it prepares to show a session, and when one failed to show. */
@Volatile var preparedAt = 0L
private set
@Volatile var showFailedAt = 0L
private set
private val _shown = MutableStateFlow(0L)
/** When a sheet last came up, on the phone's elapsed clock (ms); 0: not yet. */
val shown: StateFlow<Long> = _shown.asStateFlow()
private val _connected = MutableStateFlow(false)
/** Whether Android has the assistant service connected right now. */
val connected: StateFlow<Boolean> = _connected.asStateFlow()
fun created(now: Long) {
createdAt = now
}
fun destroyed(now: Long) {
destroyedAt = now
}
fun ready(now: Long) {
readyAt = now
_connected.value = true
}
fun shutdown(now: Long) {
shutdownAt = now
_connected.value = false
}
fun prepared(elapsed: Long) {
preparedAt = elapsed
}
fun showFailed(elapsed: Long) {
showFailedAt = elapsed
}
fun sheetShown(elapsed: Long) {
_shown.value = elapsed
}
}
/** What is true of the phone and the assistant at the moment the phrase is heard. */
data class WakeFacts(
/** The assistant service is connected (`LembasAssistService.current` is there). */
val connected: Boolean,
/** Android says the service is its active voice-interaction service. */
val active: Boolean,
/** LLeMbas holds the assistant role. */
val role: Boolean,
val recognizers: Boolean = true,
val screenOn: Boolean = true,
val locked: Boolean = false,
val visible: Boolean = false,
)
/**
* Opening the assistant when the phrase was heard, apart from Android so that the order of what
* is tried -- and what is written down about it -- can be tested.
*
* 1. The assistant's own way, where its service is connected ([wakeWay]). When Android says the
* service is active but has not connected it yet, a moment is waited for the connection.
* 2. "Opened" only once a sheet says it is up ([sheetCame]).
* 3. Otherwise the sheet's activity -- relied on only where Android will start it: the service is
* connected (a bound service lets the whole app start activities) or the app is on screen. A
* session that was only slow is given a second wait first, so there are never two sheets.
* 4. Otherwise a notification to tap.
*
* [open] returns what happened, for the record.
*/
class WakeOpener(
private val facts: () -> WakeFacts,
/** Wait up to the given ms for Android to connect the service; whether it did. */
private val awaitConnected: suspend (Long) -> Boolean,
/** Ask the connected service to show its sheet; throws what Android throws. */
private val showSession: () -> Unit,
/** Start the sheet's activity; throws what Android throws. */
private val startActivity: () -> Unit,
/** Wait up to the given ms for a sheet to say it is up; how long it took, or null. */
private val sheetCame: suspend (Long) -> Long?,
private val notify: (WakeAttempt) -> Unit,
/** What Android said of the show since it was asked: prepared, failed. */
private val showSignals: () -> Pair<Boolean, Boolean> = { false to false },
private val now: () -> Long = System::currentTimeMillis,
) {
suspend fun open(phrase: String, link: WakeAttempt = WakeAttempt()): WakeAttempt {
var seen = facts()
var waited = false
if (!seen.connected && seen.active) {
// Android's own assistant, only not connected at this instant: it may be on its way.
waited = true
if (awaitConnected(CONNECT_WAIT_MS)) seen = facts().copy(connected = true)
}
val way = wakeWay(seen.connected, seen.screenOn, seen.visible)
var attempt = link.copy(
at = now(),
phrase = phrase,
way = way.id,
assistant = seen.role,
active = seen.active,
recognizers = seen.recognizers,
screenOn = seen.screenOn,
locked = seen.locked,
visible = seen.visible,
waited = waited,
)
if (way == WakeWay.Session || way == WakeWay.AssistantActivity) {
val refused = runCatching { if (way == WakeWay.Session) showSession() else startActivity() }.exceptionOrNull()
val took = if (refused == null) sheetCame(SHEET_WAIT_MS) else null
val (prepared, failed) = showSignals()
attempt = attempt.copy(prepared = prepared, showFailed = failed)
if (took != null) return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = took)
attempt = if (refused != null) {
attempt.copy(outcome = WakeAttempt.OUT_REFUSED, detail = describe(refused))
} else {
attempt.copy(outcome = WakeAttempt.OUT_NO_SHEET)
}
// The activity was the way that just did not come up: starting it a second time is no fallback.
if (way == WakeWay.AssistantActivity && refused == null) return notified(attempt)
// A session Android did not refuse may only be slow: a second wait, before anything
// else is put on screen beside it.
if (refused == null) {
sheetCame(SHEET_WAIT_MS)?.let { late -> return attempt.copy(outcome = WakeAttempt.OUT_OPENED, sheetMs = SHEET_WAIT_MS + late) }
}
} else {
attempt = attempt.copy(outcome = WakeAttempt.OUT_NOT_CONNECTED)
}
// The sheet's activity. Android blocks one started from the background without a word,
// so it counts only where it may start -- and only once it says it is up.
val started = runCatching { startActivity() }.isSuccess
if (started && (seen.connected || seen.visible)) {
sheetCame(SHEET_WAIT_MS)?.let { took -> return attempt.copy(fallback = WakeWay.Activity.id, sheetMs = took) }
}
return notified(attempt)
}
private fun notified(attempt: WakeAttempt): WakeAttempt {
val told = attempt.copy(fallback = WakeWay.Notification.id)
notify(told)
return told
}
private fun describe(e: Throwable): String = listOfNotNull(e.javaClass.simpleName, e.message?.takeIf { it.isNotBlank() }).joinToString(": ").take(200)
companion object {
/** How long a sheet has to say it is up before the way that was tried counts as not having opened it. */
const val SHEET_WAIT_MS = 2_500L
/** How long Android is given to connect a service it says is active. */
const val CONNECT_WAIT_MS = 1_000L
/** The longest an attempt can take: the connection, three waits for a sheet, and a margin. The microphone is held that long. */
const val ATTEMPT_MAX_MS = CONNECT_WAIT_MS + 3 * SHEET_WAIT_MS + 1_500L
}
}
@@ -0,0 +1,470 @@
package eu.llembas.android.wake
import android.Manifest
import android.app.KeyguardManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.PowerManager
import android.os.SystemClock
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import eu.llembas.android.MainActivity
import eu.llembas.android.R
import eu.llembas.android.assist.AssistActivity
import eu.llembas.android.assist.LembasAssistService
import eu.llembas.android.lembas
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/**
* Listening for the wake word: opt-in (Settings › Assistant › Wake word), off by default.
*
* A `microphone` foreground service with its notification up the whole time it runs -- Android
* lets an app hear the microphone in the background only that way, and only once the person has
* started it from the app. The audio goes to the on-device engine ([WakeEngine]) in memory and
* nowhere else; it is not kept, and nothing is sent anywhere until the word is heard. Then the
* microphone is let go and the assistant opens, listening, as the power button would open it.
*
* It pauses itself (the notification says why) while the assistant's sheet is up, in battery
* saver, and -- unless Settings says otherwise -- while the screen is off; it goes on once the
* reason is gone. It cannot start itself at boot (Android forbids a microphone service there):
* [WakeBootReceiver] posts "tap to listen again" instead.
*/
class WakeWordService : LifecycleService() {
private val screenOn = MutableStateFlow(true)
private val batterySaver = MutableStateFlow(false)
private val mayRecord = MutableStateFlow(true)
private var following: Job? = null
private var watching: Job? = null
/** This instance's right to write the state (WakeStatus.begin). */
private var token = 0
/** The newest start Android has delivered: what the service stops itself by, so a start still on its way is not stopped. */
private var lastStart = 0
/** Set when the service could not even start: the state then says why, and is not wiped on the way out. */
private var keepState = false
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_SCREEN_ON -> {
screenOn.value = true
mayRecord.value = micAllowed(this@WakeWordService)
}
Intent.ACTION_SCREEN_OFF -> screenOn.value = false
PowerManager.ACTION_POWER_SAVE_MODE_CHANGED -> batterySaver.value = power().isPowerSaveMode
}
}
}
override fun onCreate() {
super.onCreate()
channel(this)
screenOn.value = power().isInteractive
batterySaver.value = power().isPowerSaveMode
ContextCompat.registerReceiver(
this,
receiver,
IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED)
},
ContextCompat.RECEIVER_NOT_EXPORTED,
)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
// Every start counts, Stop's too: the service stops itself by the newest one it was given.
lastStart = startId
if (intent?.action == ACTION_STOP) {
// Stop is the setting going off; the loop sees it and ends the service on the path
// that has shown its notification first (follow). The service is stopped from here
// only when nothing is running in it, and only if no newer start is on its way
// (stopSelf(startId)): stopping under a pending foreground start closes the app.
lifecycleScope.launch {
lembas.instances.savePrefs { it.copy(wakeWord = false) }
if (following?.isActive != true) stopSelf(startId)
}
return START_NOT_STICKY
}
mayRecord.value = micAllowed(this)
val running = following?.isActive == true
// The notification first: Android stops a foreground service that is slow to show one.
// It says what is true now -- "starting" for a service that just began, and on every
// later start (the app opens) whatever the state already is; never a phrase by default.
val now = wakeStateAtStart(running, WakeStatus.state.value)
try {
ServiceCompat.startForeground(this, NOTIFICATION_ID, wakeNotification(this, now), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
} catch (e: Exception) {
// Android refuses a microphone service without the permission, or from the background.
Log.w(TAG, "wake word: the service could not start", e)
keepState = true
WakeStatus.set(
if (mayRecord.value) {
WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail)
} else {
WakeState.Paused(WakePause.NoMicrophone)
},
)
stopSelf()
return START_NOT_STICKY
}
val manager = getSystemService(NotificationManager::class.java)
// It is listening again: "tap to listen again" (after a restart) has nothing left to say.
manager.cancel(WakeBootReceiver.RESUME_ID)
if (!running) {
keepState = false
// This instance writes the state from here; an older one's last words count for nothing.
token = WakeStatus.begin()
// And it starts from what the sheets say: no hold of an earlier instance is left standing.
AssistPresence.release()
WakeStatus.set(token, now)
following = lifecycleScope.launch { follow() }
}
if (watching == null) {
// The one place the notification is written: from the state, whenever it changes.
watching = lifecycleScope.launch {
WakeStatus.state.collect { state ->
if (state != WakeState.Off) manager.notify(NOTIFICATION_ID, wakeNotification(this@WakeWordService, state))
}
}
// A tap on the failure in Settings: try now, not when the back-off says.
lifecycleScope.launch { WakeStatus.retries.drop(1).collect { listener.retryNow() } }
}
return START_NOT_STICKY
}
private val listener by lazy {
WakeListener(
say = { WakeStatus.set(token, it) },
engine = { keywords -> WakeEngine.create(this, keywords) },
microphone = { PhoneMicrophone() },
// A test in Settings takes the word; otherwise the assistant opens.
heard = { phrase ->
if (WakeStatus.heardInTrial(SystemClock.elapsedRealtime())) {
val tested = WakeAttempt(at = System.currentTimeMillis(), phrase = phrase.words, outcome = WakeAttempt.OUT_TESTED)
wakeScope.launch { record(this@WakeWordService, tested) }
} else {
wake(phrase)
}
},
log = { message, cause -> Log.w(TAG, message, cause) },
)
}
/** Listen, or pause, as the phone and Settings change; stop when Settings turns it off. */
private suspend fun follow() {
val mine = token
val plans = combine(lembas.instances.prefs, screenOn, batterySaver, AssistPresence.open, mayRecord) { prefs, on, saver, open, mic ->
if (!prefs.wakeWord) {
null
} else {
val phrase = WakePhrases.byId(prefs.wakePhrase)
WakePlan(phrase, wakeKeywords(phrase, WakeSensitivity.byId(prefs.wakeSensitivity)), wakePause(on, prefs.wakeScreenOnly, saver, open > 0, mic))
}
}
try {
listener.follow(plans.takeWhile { it != null }.filterNotNull())
} finally {
// After the loop has ended, so nothing it said on its way out is left standing --
// and only if no newer writer has taken over meanwhile.
if (!keepState) WakeStatus.set(mine, WakeState.Off)
}
// Not if a newer start is already on its way: that one finds the loop ended and begins it again.
stopSelf(lastStart)
}
/**
* The word was heard: the assistant opens listening ([WakeOpener] decides how and checks that
* it did), and what was tried and how it went is written down ([WakeAttempt], kept in the
* settings and shown in Settings › Wake word), because a silent "no" here looks to the
* person like a wake word that does not work.
*
* It runs on the app's own scope, never inside the listening loop: the hold below pauses
* the listener, which cancels the loop that heard the word -- and a wake that ran in that
* loop was cancelled by its own first step. One at a time: a word heard while the last one
* is still being answered is let go.
*/
private fun wake(phrase: WakePhrase) {
if (waking?.isActive == true) return
// The microphone is the sheet's from here, for as long as the attempt can take; once it
// is over, for a moment more, and then for as long as a sheet says it is up.
AssistPresence.holdFor(WakeOpener.ATTEMPT_MAX_MS)
waking = wakeScope.launch {
try {
val asked = SystemClock.elapsedRealtime()
val opener = WakeOpener(
facts = { wakeFacts(this@WakeWordService) },
awaitConnected = { ms -> withTimeoutOrNull(ms) { AssistLink.connected.first { it } } != null },
showSession = {
val assistant = LembasAssistService.current ?: error("the assistant service is not connected")
assistant.showSession(Bundle().apply { putBoolean(AssistActivity.EXTRA_LISTEN, true) }, 0)
},
// Through the assistant service where it is connected (the same permission either way: Android lets
// the whole app start activities while it holds the service bound).
startActivity = { (LembasAssistService.current ?: this@WakeWordService).startActivity(AssistActivity.woken(this@WakeWordService)) },
sheetCame = { ms ->
withTimeoutOrNull(ms) { AssistLink.shown.first { it >= asked } }?.let { (it - asked).coerceAtLeast(0) }
},
notify = { attempt ->
getSystemService(NotificationManager::class.java).notify(HEARD_ID, wakeHeardNotification(this@WakeWordService, attempt.assistant))
},
showSignals = { (AssistLink.preparedAt >= asked) to (AssistLink.showFailedAt >= asked) },
)
val link = WakeAttempt(
createdAt = AssistLink.createdAt,
destroyedAt = AssistLink.destroyedAt,
readyAt = AssistLink.readyAt,
shutdownAt = AssistLink.shutdownAt,
)
record(this@WakeWordService, opener.open(phrase.words, link))
} finally {
AssistPresence.holdFor(SHEET_GRACE_MS)
}
}
}
private var waking: Job? = null
private fun power() = getSystemService(PowerManager::class.java)
override fun onDestroy() {
runCatching { unregisterReceiver(receiver) }
// The scope ends with the service: the listener's loop is joined and its engine released
// on the way out (WakeListener.follow), not here under a loop that may still run.
if (!keepState) WakeStatus.set(token, WakeState.Off)
super.onDestroy()
}
companion object {
const val CHANNEL = "wake_word"
const val CHANNEL_HEARD = "wake_heard"
private const val NOTIFICATION_ID = 7001
const val HEARD_ID = 7002
private const val SHEET_GRACE_MS = 3_000L
/** `PackageManager.FEATURE_VOICE_RECOGNIZERS`, which the SDK does not name for apps: without it Android runs no voice-interaction service. */
private const val FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers"
/** The app's own scope: a wake and its record outlive the listening loop, and the service too. */
private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
/** What is true at this moment, for the opener and the record. */
fun wakeFacts(context: Context): WakeFacts = WakeFacts(
connected = LembasAssistService.current != null,
active = LembasAssistService.isActive(context),
role = LembasAssistService.holdsRole(context),
recognizers = context.packageManager.hasSystemFeature(FEATURE_VOICE_RECOGNIZERS),
screenOn = context.getSystemService(PowerManager::class.java).isInteractive,
locked = context.getSystemService(KeyguardManager::class.java).isKeyguardLocked,
visible = AppVisibility.visible,
)
/**
* Write [attempt] down: in the log under a fixed tag, and first among the last few in the
* settings. Not cancellable: what happened is kept whatever ends meanwhile.
*/
suspend fun record(context: Context, attempt: WakeAttempt) = withContext(NonCancellable) {
Log.i(TAG, "wake word heard: $attempt")
runCatching { context.lembas.instances.savePrefs { it.copy(wakeLog = wakeLogAdd(it.wakeLog, attempt)) } }
Unit
}
private const val TAG = "LLeMbasWake"
const val ACTION_STOP = "eu.llembas.android.action.WAKE_STOP"
/**
* Start listening, or say why not. Only from the app on screen: Android allows a
* microphone service from there, and only with the microphone permission -- without it
* the service is not started at all, and the state says so.
*/
fun start(context: Context) {
if (!WakeEngine.AVAILABLE) return WakeStatus.set(WakeState.Failed(WakeFailure.NoEngine))
if (!micAllowed(context)) return WakeStatus.set(WakeState.Paused(WakePause.NoMicrophone))
try {
ContextCompat.startForegroundService(context, Intent(context, WakeWordService::class.java))
} catch (e: Exception) {
Log.w(TAG, "wake word: the service could not be started", e)
WakeStatus.set(WakeState.Failed(WakeFailure.Microphone, WakeError(WakeFailure.Microphone, e).detail))
}
}
/**
* The wake word was turned off. The service is not stopped from outside: it ends itself
* when it sees the setting, after it has shown its notification -- stopping it under a
* foreground start that is still on its way closes the app. The state is "off" at once.
*/
fun stop() {
WakeStatus.set(WakeState.Off)
}
fun micAllowed(context: Context) = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
fun channel(context: Context) {
context.getSystemService(NotificationManager::class.java).createNotificationChannels(
listOf(
NotificationChannel(CHANNEL, context.getString(R.string.channel_wake), NotificationManager.IMPORTANCE_LOW),
// "Heard you. Tap to ask.": it must come up over what is on screen, or the word was for nothing.
NotificationChannel(CHANNEL_HEARD, context.getString(R.string.channel_wake_heard), NotificationManager.IMPORTANCE_HIGH),
),
)
}
}
}
/**
* "Heard you. Tap to ask.": what the wake word posts when it cannot open the assistant itself.
* A fixed sentence, nothing from the account; the tap opens the assistant listening.
*/
fun wakeHeardNotification(context: Context, assistant: Boolean = false): Notification {
val ask = PendingIntent.getActivity(context, 1, AssistActivity.listening(context), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
return NotificationCompat.Builder(context, WakeWordService.CHANNEL_HEARD)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.wake_heard))
// Why it is a notification and not the sheet, in fixed words: LLeMbas is not the phone's
// assistant -- or it is, and could not open by itself this time (Settings says which step said no).
.setContentText(context.getString(if (assistant) R.string.wake_heard_could_not else R.string.wake_heard_line))
.setContentIntent(ask)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setTimeoutAfter(HEARD_TIMEOUT_MS)
.build()
}
/** A minute: a "tap to ask" nobody tapped is no longer an answer to anything. */
private const val HEARD_TIMEOUT_MS = 60_000L
/**
* The persistent notification, from [state] alone: what the wake word is doing in plain words
* (the phrase it listens for, why it is paused, what failed). Nothing from the account.
*/
fun wakeNotification(context: Context, state: WakeState): Notification {
val stop = PendingIntent.getService(
context,
2,
Intent(context, WakeWordService::class.java).setAction(WakeWordService.ACTION_STOP),
PendingIntent.FLAG_IMMUTABLE,
)
val open = PendingIntent.getActivity(context, 3, Intent(context, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE)
return NotificationCompat.Builder(context, WakeWordService.CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(wakeTitle(context, state))
.setContentText(wakeLine(context, state))
.setOngoing(true)
.setSilent(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(open)
.addAction(0, context.getString(R.string.wake_stop), stop)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.build()
}
/**
* The phone's microphone at 16 kHz, recording from the moment it is made -- or an exception that
* says what did not work. Android reports none of this by throwing: a recorder that could not be
* opened is merely "uninitialized", and one that did not start merely "stopped".
*/
@android.annotation.SuppressLint("MissingPermission")
private class PhoneMicrophone : WakeMicrophone {
private val audio: AudioRecord
init {
val rate = WakeListener.RATE
val min = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
check(min > 0) { "the phone cannot record at 16 kHz" }
audio = AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(min, rate))
try {
check(audio.state == AudioRecord.STATE_INITIALIZED) { "the microphone could not be opened" }
audio.startRecording()
check(audio.recordingState == AudioRecord.RECORDSTATE_RECORDING) { "recording did not start; another app may have the microphone" }
} catch (e: Exception) {
audio.release()
throw e
}
}
override fun read(into: ShortArray): Int = audio.read(into, 0, into.size)
override fun close() {
runCatching { audio.stop() }
audio.release()
}
}
/**
* After a restart: Android does not let a microphone service start at boot, so a wake word that
* was on says "tap to listen again" -- the tap opens the app, which starts it.
*/
class WakeBootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return
val pending = goAsync()
CoroutineScope(Dispatchers.Default).launch {
try {
val prefs = context.lembas.instances.prefs.first()
if (!prefs.wakeWord || !WakeEngine.AVAILABLE) return@launch
if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) return@launch
WakeWordService.channel(context)
val open = PendingIntent.getActivity(
context,
4,
Intent(context, MainActivity::class.java).putExtra(EXTRA_RESUME, true).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
context.getSystemService(NotificationManager::class.java).notify(
RESUME_ID,
NotificationCompat.Builder(context, WakeWordService.CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.wake_resume))
.setContentText(context.getString(R.string.wake_resume_line))
.setContentIntent(open)
.setAutoCancel(true)
.build(),
)
} finally {
pending.finish()
}
}
}
companion object {
/** On MainActivity's intent: start listening for the wake word again. */
const val EXTRA_RESUME = "eu.llembas.android.WAKE_RESUME"
const val RESUME_ID = 7003
}
}
@@ -0,0 +1,35 @@
// Generated by scripts/gen-wake-phrases.py from the model's bpe.model. Do not edit: edit the lists there.
package eu.llembas.android.wake
/**
* The words a wake phrase is made of -- a greeting and a name -- each with its spelling in the
* model's BPE pieces (`sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01`). English, as the
* model is.
*
* Left out, because the tokenizer can only spell them out letter by letter:
* Elizabeth (▁E LI Z A B E TH)
* Benjamin (▁BE N J A M IN)
*/
object WakeWords {
val greetings = listOf(
WakeWord("hey", "Hey", "▁HE Y"),
WakeWord("ok", "OK", "▁OKAY"),
WakeWord("hello", "Hello", "▁HE LL O"),
)
val names = listOf(
WakeWord("assistant", "Assistant", "▁AS S IST ANT"),
WakeWord("computer", "Computer", "▁COMP U TER"),
WakeWord("google", "Google", "▁GO O G LE"),
WakeWord("victoria", "Victoria", "▁VI C T OR IA"),
WakeWord("samantha", "Samantha", "▁SA MAN TH A"),
WakeWord("jessica", "Jessica", "▁JE S S IC A"),
WakeWord("amanda", "Amanda", "▁A MAN D A"),
WakeWord("olivia", "Olivia", "▁O LI VI A"),
WakeWord("oliver", "Oliver", "▁O LI VER"),
WakeWord("sebastian", "Sebastian", "▁SE B AS T IAN"),
WakeWord("jonathan", "Jonathan", "▁JO N A TH AN"),
WakeWord("alexander", "Alexander", "▁A LE X AN DER"),
WakeWord("christopher", "Christopher", "▁ CH R IST O PH ER"),
)
}
@@ -0,0 +1,73 @@
package eu.llembas.android.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.widget.RemoteViews
import eu.llembas.android.R
import eu.llembas.android.assist.AssistActivity
/**
* The home-screen widget: a bar that opens the assistant's sheet (Ask), the sheet listening (the
* microphone), or the sheet at the last chat the assistant made. Nothing on it comes from the
* account, so it never needs updating and shows nothing private wherever it is placed.
*/
class AskWidget : AppWidgetProvider() {
override fun onUpdate(context: Context, manager: AppWidgetManager, ids: IntArray) {
val views = RemoteViews(context.packageName, R.layout.widget_ask).apply {
setOnClickPendingIntent(R.id.widget_ask, open(context, REQUEST_ASK, Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST)))
setOnClickPendingIntent(R.id.widget_mic, open(context, REQUEST_LISTEN, AssistActivity.listening(context)))
setOnClickPendingIntent(R.id.widget_last, open(context, REQUEST_CONTINUE, AssistActivity.continuing(context)))
}
ids.forEach { manager.updateAppWidget(it, views) }
}
private fun open(context: Context, request: Int, intent: Intent): PendingIntent = PendingIntent.getActivity(
context,
request,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
private companion object {
const val REQUEST_ASK = 1
const val REQUEST_LISTEN = 2
const val REQUEST_CONTINUE = 3
}
}
/**
* The launcher icon's long-press shortcuts: Ask, Speak and the last assistant chat. Published from
* code rather than `shortcuts.xml`, because a static shortcut names the package, and the test
* build's is `….debug`; and so their labels follow the app's language.
*/
object Shortcuts {
fun publish(context: Context) {
val manager = context.getSystemService(ShortcutManager::class.java) ?: return
val shortcuts = listOf(
shortcut(
context,
"ask",
R.string.tile_ask,
R.string.tile_ask,
R.drawable.ic_shortcut_ask,
Intent(context, AssistActivity::class.java).setAction(Intent.ACTION_ASSIST),
),
shortcut(context, "speak", R.string.widget_speak, R.string.widget_speak, R.drawable.ic_shortcut_mic, AssistActivity.listening(context)),
shortcut(context, "continue", R.string.shortcut_last, R.string.assist_continue, R.drawable.ic_shortcut_history, AssistActivity.continuing(context)),
)
runCatching { manager.dynamicShortcuts = shortcuts }
}
private fun shortcut(context: Context, id: String, short: Int, long: Int, icon: Int, intent: Intent): ShortcutInfo = ShortcutInfo.Builder(context, id)
.setShortLabel(context.getString(short))
.setLongLabel(context.getString(long))
.setIcon(Icon.createWithResource(context, icon))
.setIntent(intent)
.build()
}
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp"
android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
<group android:translateX="12" android:translateY="12">
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
</group>
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp"
android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
<group android:translateX="12" android:translateY="12">
<path android:fillColor="@color/token_accent" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
</group>
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A launcher shortcut's icon: a Material icon (Apache-2.0) on a disc, in the theme's colours. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp"
android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="@color/token_surface_raised" android:pathData="M24,0a24,24 0,1 1,0 48a24,24 0,1 1,0 -48z" />
<group android:translateX="12" android:translateY="12">
<path android:fillColor="@color/token_accent" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
</group>
</vector>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp"
android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="@color/token_accent" android:pathData="M20,2L4,2c-1.1,0 -1.99,0.9 -1.99,2L2,22l4,-4h14c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2z" />
</vector>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp"
android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="@color/token_ink_muted" android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
</vector>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A Material icon (Apache-2.0) in the theme's colour (values*/tokens.xml). -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp"
android:viewportWidth="24" android:viewportHeight="24">
<path android:fillColor="@color/token_accent_ink" android:pathData="M12,14c1.66,0 2.99,-1.34 2.99,-3L15,5c0,-1.66 -1.34,-3 -3,-3S9,3.34 9,5v6c0,1.66 1.34,3 3,3zM17.3,11c0,3 -2.54,5.1 -5.3,5.1S6.7,14 6.7,11L5,11c0,3.41 2.72,6.23 6,6.72L11,21h2v-3.28c3.28,-0.48 6,-3.3 6,-6.72h-1.7z" />
</vector>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The widget's bar, in the theme's colours (values*/tokens.xml). -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/token_surface" />
<stroke android:width="1dp" android:color="@color/token_border" />
<corners android:radius="28dp" />
</shape>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="@color/token_accent" />
</shape>
+59
View File
@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The home-screen widget: Ask (the sheet), the microphone (the sheet, listening) and the last
assistant chat. It shows nothing from the account (no chat title, no model), so nothing
of it is private wherever the launcher shows it. Every part keeps a fixed size except the
Ask label, which gives. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/widget_background"
android:gravity="center_vertical"
android:minHeight="56dp"
android:orientation="horizontal"
android:paddingStart="16dp"
android:paddingEnd="4dp">
<LinearLayout
android:id="@+id/widget_ask"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:importantForAccessibility="no"
android:src="@drawable/ic_widget_ask" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:ellipsize="end"
android:maxLines="1"
android:text="@string/widget_hint"
android:textColor="@color/token_ink_muted"
android:textSize="16sp" />
</LinearLayout>
<ImageView
android:id="@+id/widget_last"
android:layout_width="48dp"
android:layout_height="48dp"
android:contentDescription="@string/assist_continue"
android:padding="12dp"
android:src="@drawable/ic_widget_history" />
<ImageView
android:id="@+id/widget_mic"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="2dp"
android:background="@drawable/widget_mic_background"
android:contentDescription="@string/widget_speak"
android:padding="12dp"
android:src="@drawable/ic_widget_mic" />
</LinearLayout>
+159 -2
View File
@@ -244,11 +244,43 @@
<string name="channel_scheduled_failures">Selhání naplánovaných úloh</string>
<string name="scheduled_result_public">Naplánovaná úloha má výsledek.</string>
<string name="scheduled_failed_public">Naplánovaná úloha selhala.</string>
<string name="page_note">Tato odpověď obsahuje stránku: %1$s</string>
<string name="page_where">Zobrazíte ji na webu nebo v aplikaci LLeMbas Desktop.</string>
<string name="page_untitled">Stránka</string>
<string name="reports">Zprávy</string>
<string name="report">Zpráva</string>
<string name="reports_none">Zatím žádné zprávy. Naplánovaná úloha ji napíše, když vám má co říct.</string>
<string name="reports_unsupported">Na této instanci běží LLeMbas, který Zprávy ještě nemá.</string>
<string name="report_untitled">Zpráva bez názvu</string>
<string name="report_delete_title">Smazat tuto zprávu?</string>
<string name="report_delete_line">Zpráva „%1$s“ se smaže natrvalo, i s rozhovorem o ní.</string>
<string name="report_mark_read">Označit jako přečtené</string>
<string name="report_important">Důležité</string>
<string name="report_share">Sdílet</string>
<string name="report_reply">Odpovědět</string>
<string name="report_chat_title">Zpráva: %1$s</string>
<string name="notify_when">Kdy dát vědět</string>
<string name="notify_every_run">Při každém běhu</string>
<string name="notify_every_run_line">Model napíše zprávu pokaždé, i když nic nenašel.</string>
<string name="notify_when_option">Když…</string>
<string name="notify_when_line">Model napíše zprávu jen tehdy, když platí tohle.</string>
<string name="notify_when_label">Když co?</string>
<string name="notify_when_default">něco vyžaduje moji pozornost</string>
<string name="notify_never_option">Nikdy</string>
<string name="notify_never_line">Žádné zprávy: běhy zůstanou jen v historii úlohy.</string>
<string name="notify_when_words">Dá vědět, když: %1$s</string>
<string name="run_open_report">Otevřít její zprávu</string>
<string name="channel_reports">Zprávy</string>
<string name="channel_reports_high">Důležité zprávy</string>
<string name="report_new_public">Nová zpráva</string>
<string name="schedule_run_again">Spustit znovu</string>
<string name="card_approval">Povolit to?</string>
<string name="card_allow_once">Povolit jednou</string>
<string name="card_allow_always">Toto vždy povolit</string>
<string name="card_allow_always">Vždy povolit</string>
<string name="card_deny">Zamítnout</string>
<string name="card_deny_reason">Zamítnout a říct proč</string>
<string name="plan_approve_edit">Schválit, pokračovat v režimu Upravit</string>
<string name="plan_approve_manual">Schválit, pokračovat v režimu Ručně</string>
<string name="card_reason">Proč ne? (nepovinné)</string>
<string name="card_recommended">doporučeno</string>
<string name="card_answer">Vaše odpověď</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Vysvětli, co je na mé obrazovce.</string>
<string name="assist_continue">Pokračovat v poslední konverzaci</string>
<string name="assist_help">Podržením tlačítka napájení otevřete asistenta nad libovolnou aplikací; nebo použijte dlaždici v Rychlém nastavení.</string>
<string name="assist_no_wake_word">Budicí slovo není: na běžném Androidu je naslouchání budicímu slovu vyhrazeno asistentovi zabudovanému v telefonu.</string>
<string name="assist_connecting">Připojování…</string>
<string name="assist_offline">%1$s není dostupná</string>
<string name="assist_no_model">Žádný model</string>
@@ -390,6 +421,127 @@
<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_conversation">Rozhovor</string>
<string name="assist_conversation_line">Po každé odpovědi znovu poslouchám. Řekněte „stop“ a skončíme.</string>
<string name="assist_conversation_end">Ukončit</string>
<string name="assist_stop_words">stop|dost|to je vše|to je všechno|konec|nashledanou|díky to je vše|zrušit|stop stop</string>
<string name="assistant_conversation">Pokračovat v mluveném rozhovoru</string>
<string name="assistant_conversation_line">Po přečtení mluvené odpovědi asistent znovu poslouchá — dokud neřeknete „stop“, neklepnete na Ukončit nebo pár sekund nic neřeknete. Funguje i se sluchátky.</string>
<string name="assist_wake_word_hint">Budicí slovo jen pokud chcete: Nastavení › Asistent › Budicí slovo zapne vlastní slovo LLeMbas, přímo v tomto telefonu.</string>
<string name="channel_wake">Budicí slovo</string>
<string name="wake_word">Budicí slovo</string>
<string name="wake_word_listen">Naslouchat budicímu slovu</string>
<string name="wake_word_line">Ve výchozím stavu vypnuto. Řekněte frázi a asistent se otevře a poslouchá, nad jakoukoli aplikací na obrazovce.</string>
<string name="wake_word_unavailable">V tomto sestavení není. Sestavení pro F-Droid nemá modul pro budicí slovo, protože F-Droid sestavuje každou knihovnu ze zdrojů; sestavení z llembas.eu ho má.</string>
<string name="wake_phrase_line">Tohle říkáte, potom krátká pauza: platí, až když zmlknete. Anglicky, ať je aplikace v jakémkoli jazyce: modul zná jen anglickou řeč.</string>
<string name="wake_greeting">Oslovení</string>
<string name="wake_name">Jméno</string>
<string name="wake_name_google_line">Ozve se i telefon nebo reproduktor Google poblíž.</string>
<string name="wake_sensitivity">Citlivost</string>
<string name="wake_sensitivity_low">Nízká</string>
<string name="wake_sensitivity_low_line">Omylem se spustí nejméně často. Frázi možná budete muset říct zřetelněji nebo dvakrát.</string>
<string name="wake_sensitivity_normal">Normální</string>
<string name="wake_sensitivity_normal_line">Vlastní nastavení modulu.</string>
<string name="wake_sensitivity_high">Vysoká</string>
<string name="wake_sensitivity_high_line">Slyší vás nejsnáze, i z větší dálky. Omylem se spustí častěji.</string>
<string name="wake_test">Vyzkoušet budicí slovo</string>
<string name="wake_test_line">Deset sekund ukazuje, zda je vaši frázi slyšet, bez otevření asistenta.</string>
<string name="wake_test_say">Teď řekněte „%1$s“ a udělejte pauzu…</string>
<string name="wake_test_heard">Slyšel jsem ji</string>
<string name="wake_test_missed">Za deset sekund jsem ji neslyšel. Zkuste to blíž k telefonu, ve chvíli většího ticha nebo s vyšší citlivostí.</string>
<string name="wake_test_off">Nejdřív zapněte budicí slovo.</string>
<string name="wake_screen_only">Jen při zapnuté obrazovce</string>
<string name="wake_screen_only_line">Vypnuto: poslouchá i při zhasnuté obrazovce, za cenu vyšší spotřeby baterie.</string>
<string name="wake_battery">Nechat běžet na pozadí</string>
<string name="wake_battery_line">Některé telefony (Samsung, Xiaomi, Huawei, OnePlus a další) kvůli baterii zastavují aplikace na pozadí, a s nimi i budicí slovo. Zde vyjměte LLeMbas z optimalizace baterie; dontkillmyapp.com vysvětluje nastavení vašeho telefonu.</string>
<string name="wake_word_privacy">Před vyslovením slova nic neopustí telefon. Zvuk z mikrofonu jde jen do modulu pro budicí slovo v telefonu a neukládá se; po celou dobu naslouchání je vidět oznámení. Fráze jsou anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to baterii: mikrofon zůstává zapnutý a procesor telefonu kontroluje každý okamžik zvuku, bez úsporného čipu, který používá vestavěný asistent. Pozastaví se v úsporném režimu, když je asistent otevřený, a pokud to nezměníte, i při zhasnuté obrazovce. Po restartu ho znovu spustíte klepnutím na oznámení.</string>
<string name="wake_listening_for">Naslouchám frázi „%1$s“</string>
<string name="wake_off">Budicí slovo neposlouchá</string>
<string name="wake_tap_to_start">Klepnutím ho znovu spustíte. Pokud se Android zeptá, povolte mikrofon.</string>
<string name="wake_starting">Budicí slovo se spouští…</string>
<string name="wake_paused_silent">Budicí slovo nic neslyší: mikrofon používá jiná aplikace, nebo je v telefonu vypnutý</string>
<string name="wake_failed_no_engine">Budicí slovo nefunguje: toto sestavení nemá modul</string>
<string name="wake_failed_model">Budicí slovo nefunguje: jeho model se v tomto telefonu nepodařilo rozbalit</string>
<string name="wake_failed_engine">Budicí slovo nefunguje: modul se nespustil</string>
<string name="wake_failed_microphone">Budicí slovo nefunguje: mikrofon se nespustil</string>
<string name="wake_failed_line">Neposlouchá. Zkusí to znovu samo.</string>
<string name="wake_notification_line">Dokud ji neřeknete, nic neopustí telefon.</string>
<string name="wake_paused_screen">Budicí slovo pozastaveno: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budicí slovo pozastaveno: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budicí slovo je pozastaveno, dokud je asistent otevřený</string>
<string name="wake_paused_microphone">Budicí slovo pozastaveno: LLeMbas nemá povolený mikrofon</string>
<string name="wake_stop">Přestat naslouchat</string>
<string name="wake_heard">Slyšel jsem vás. Klepněte a ptejte se.</string>
<string name="channel_wake_heard">Budicí slovo zaznělo</string>
<string name="wake_heard_line">LLeMbas se umí sám otevřít nad jinými aplikacemi jen jako aplikace digitálního asistenta v telefonu.</string>
<string name="wake_not_assistant">LLeMbas není aplikací digitálního asistenta</string>
<string name="wake_not_assistant_line">Budicí slovo proto nemůže otevřít asistenta nad jinými aplikacemi: dostanete oznámení, na které klepnete. Chcete-li otevírat hlasem kdekoli, klepněte sem a vyberte LLeMbas jako aplikaci digitálního asistenta.</string>
<string name="wake_last">Poslední probuzení</string>
<string name="wake_last_none">Frázi zatím neslyšel.</string>
<string name="wake_out_opened">Otevřel asistenta.</string>
<string name="wake_out_no_sheet">Požádal Android o otevření asistenta; neodmítl, ale panel se neobjevil.</string>
<string name="wake_out_not_connected">Android neměl LLeMbas připojený jako asistenta, proto panel nemohl otevřít.</string>
<string name="wake_out_refused">Android odmítl otevřít asistenta: %1$s</string>
<string name="wake_out_activity">Místo toho ho otevřel jako obrazovku aplikace.</string>
<string name="wake_out_notification">Místo toho poslal oznámení, na které je třeba klepnout.</string>
<string name="wake_out_tested">Slyšeno při zkoušce: nebylo co otevírat.</string>
<string name="wake_role_held">LLeMbas byl aplikací digitálního asistenta.</string>
<string name="wake_role_not_held">LLeMbas nebyl aplikací digitálního asistenta.</string>
<string name="wake_link_never">Android od spuštění aplikace asistenta nepřipojil.</string>
<string name="wake_link_ready">Android připojil asistenta v %1$s.</string>
<string name="wake_link_shutdown">Android ho odpojil v %1$s.</string>
<string name="wake_link_later">Android ho znovu připojil v %1$s.</string>
<string name="wake_sheet_ms">Panel se zobrazil po %1$s ms.</string>
<string name="wake_no_recognizers">Tento telefon nemá rozpoznávače hlasu, proto na něm Android nespouští službu hlasového asistenta.</string>
<string name="wake_not_active">LLeMbas byl vybrán jako aplikace digitálního asistenta, ale Android ho nepoužíval jako hlasového asistenta.</string>
<string name="wake_waited">Chvíli čekal, až ho Android připojí.</string>
<string name="wake_show_failed">Android oznámil, že panel asistenta nedokázal zobrazit.</string>
<string name="wake_assistant_inactive">Android právě nepoužívá LLeMbas jako hlasového asistenta</string>
<string name="wake_assistant_inactive_line">Vyberte LLeMbas jako aplikaci digitálního asistenta znovu: klepněte sem, zvolte jinou aplikaci a potom LLeMbas. Do té doby ho dlouhé stisknutí otevírá jako běžnou obrazovku a budicí slovo může poslat jen oznámení.</string>
<string name="wake_assistant_unbound">LLeMbas je asistent, ale Android ho právě nemá připojeného</string>
<string name="wake_assistant_unbound_line">Dokud ho nepřipojí, budicí slovo nemůže panel otevřít samo. Klepnutím otevřete systémové nastavení asistenta: vyberte jinou aplikaci a potom znovu LLeMbas, tím se připojí.</string>
<string name="wake_heard_could_not">Nepodařilo se otevřít samo — klepněte a ptejte se</string>
<string name="wake_resume">Znovu naslouchat budicímu slovu</string>
<string name="wake_resume_line">Telefon se restartoval. Klepnutím znovu spustíte naslouchání.</string>
<string name="assist_notifications">Shrnout má oznámení</string>
<string name="assist_notifications_prompt">Shrň moje oznámení: co potřebuje mou pozornost?</string>
<string name="assist_notifications_phrases">moje oznámení|má oznámení|mých oznámení|moje notifikace</string>
<string name="notification_summaries">Shrnutí oznámení</string>
<string name="notification_summaries_switch">Dovolit asistentovi číst má oznámení, když o to požádám</string>
<string name="notification_summaries_line">Řekněte „shrň moje oznámení“, nebo klepněte na tlačítko v asistentovi.</string>
<string name="notification_summaries_unavailable">V tomto sestavení není. Čtení oznámení vyžaduje sestavení LLeMbas „notifications“, protože Google Play Protect blokuje instalaci aplikace mimo Obchod Play, která je umí číst. Je to stejná aplikace se stejným podpisem: na stránce vydání se soubor končící na -notifications.apk nainstaluje přes tuto.</string>
<string name="update_notifications_manual">Toto je sestavení „notifications“: aktualizaci nainstalujte ze stránky vydání, soubor končící na -notifications.apk.</string>
<string name="notification_access">Přístup k oznámením</string>
<string name="notification_access_on">Uděleno. Přepínač Androidu je v systémovém nastavení.</string>
<string name="notification_access_off">Zatím neuděleno. Klepnutím otevřete přepínač Androidu pro LLeMbas.</string>
<string name="notification_summaries_privacy">Ve výchozím stavu vypnuto. Když požádáte, text oznámení, která jsou v telefonu právě teď (aplikace, název, text), půjde s touto jedinou otázkou na vaši instanci a její model. Dřív se nic nečte, aplikace si nic neponechá a při zamčeném telefonu se nečte nic. Přístup k oznámením v Androidu dovolí aplikaci vidět každé oznámení, proto je na vás, zda ho dáte a zase vezmete.</string>
<string name="nav_app">Navigační aplikace</string>
<string name="nav_app_auto">Ta, která je nainstalovaná</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Pokaždé se zeptat</string>
<string name="nav_app_not_installed">Není nainstalovaná</string>
<string name="osmand_info">Ptát se OsmAnd na trasu</string>
<string name="osmand_info_line">Umožní „přidat zastávku“ a hledání v okolí i u trasy nastavené přímo v OsmAnd: LLeMbas se OsmAnd zeptá, kde jste a kam trasa vede. Nejdřív LLeMbas povolte v OsmAnd (připojené aplikace, s polohou); OsmAnd dá vědět, pokud povoleno není.</string>
<string name="phone_actions_line">Model může nabídnout, že v telefonu něco udělá — nastaví budík, přidá událost, připraví zprávu, spustí trasu. Nic se nestane, dokud neklepnete na Provést na jeho kartě, a nikdy při zamčeném telefonu. Mapy Google spustí trasu s několika zastávkami, ale do běžící trasy zastávku nepřidají ani je nelze zastavit; OsmAnd to umí.</string>
<string name="action_card_title">Udělat to v telefonu?</string>
<string name="action_do">Provést</string>
<string name="action_running">Provádím…</string>
<string name="action_unlock">Nejdřív odemkněte telefon, pak klepněte na Provést.</string>
<string name="action_failed">Nepovedlo se: %1$s</string>
<string name="nav_app_pick">Ve které mapové aplikaci?</string>
<string name="action_google_add_stop">Mapy Google nepřidají zastávku do běžící trasy: spustí trasu znovu, přes zastávku.</string>
<string name="action_google_no_stop">Mapy Google nelze zastavit zvenčí: trasu ukončete v nich.</string>
<string name="action_line_clock">Nastaví to aplikace Hodiny.</string>
<string name="action_line_calendar">Otevře se kalendář s vyplněnou událostí; uložíte ji vy.</string>
<string name="action_line_draft">Otevře koncept; odešlete ho sami.</string>
<string name="action_line_dial">Otevře se vytáčení s číslem; hovor zahájíte vy.</string>
<string name="action_line_map">Trasu převezme %1$s.</string>
<string name="action_line_now">Stane se hned.</string>
<string name="action_line_settings">Otevře nastavení; změníte ho vy.</string>
<string name="action_line_automation">Spustí vaši automatizaci (Tasker, pokud není uvedena jiná aplikace).</string>
<string name="action_line_open">Otevře to.</string>
<string name="assist_recogniser_failed">Rozpoznávání řeči v telefonu se zastavilo. Zkuste to znovu nebo zvolte LLeMbas v Nastavení › Hlasový vstup.</string>
<string name="assistant_listens">Začít poslouchat, když se asistent otevře</string>
<string name="voice_input">Hlasový vstup</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Používá ho asistent i mikrofon v konverzaci. S LLeMbas asistent ukazuje slova s malým zpožděním a pauza je odešle, konverzace je zapíše, když přestanete; s rozpoznáváním v telefonu se objevují, jak mluvíte.</string>
<string name="share_sending">Odesílá se do LLeMbas…</string>
<string name="share_default_prompt">Podívejte se na tohle.</string>
<string name="share_ask_hint">Co s tím má LLeMbas udělat? (nepovinné)</string>
<string name="widget_hint">Zeptejte se na cokoli</string>
<string name="widget_speak">Mluvit</string>
<string name="widget_description">Ptejte se hlasem nebo textem, nebo pokračujte v poslední konverzaci s asistentem. Neukazuje nic z vašeho účtu.</string>
<string name="shortcut_last">Poslední chat</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<string name="channel_scheduled_failures">Geplante Fehler</string>
<string name="scheduled_result_public">Eine geplante Aufgabe hat ein Ergebnis.</string>
<string name="scheduled_failed_public">Eine geplante Aufgabe ist fehlgeschlagen.</string>
<string name="page_note">Diese Antwort hat eine Seite: %1$s</string>
<string name="page_where">Öffne sie im Web oder in LLeMbas Desktop, um sie zu sehen.</string>
<string name="page_untitled">Seite</string>
<string name="reports">Berichte</string>
<string name="report">Bericht</string>
<string name="reports_none">Noch keine Berichte. Eine geplante Aufgabe schreibt einen, wenn sie dir etwas zu sagen hat.</string>
<string name="reports_unsupported">Auf dieser Instanz läuft ein LLeMbas, das noch keine Berichte hat.</string>
<string name="report_untitled">Bericht ohne Titel</string>
<string name="report_delete_title">Diesen Bericht löschen?</string>
<string name="report_delete_line">„%1$s“ wird endgültig gelöscht, samt der Unterhaltung darüber.</string>
<string name="report_mark_read">Als gelesen markieren</string>
<string name="report_important">Wichtig</string>
<string name="report_share">Teilen</string>
<string name="report_reply">Antworten</string>
<string name="report_chat_title">Bericht: %1$s</string>
<string name="notify_when">Benachrichtigen, wenn</string>
<string name="notify_every_run">Bei jedem Lauf</string>
<string name="notify_every_run_line">Das Modell schreibt jedes Mal einen Bericht, auch wenn nichts gefunden wurde.</string>
<string name="notify_when_option">Wenn…</string>
<string name="notify_when_line">Das Modell schreibt nur dann einen Bericht, wenn das zutrifft.</string>
<string name="notify_when_label">Wenn was?</string>
<string name="notify_when_default">etwas braucht meine Aufmerksamkeit</string>
<string name="notify_never_option">Nie</string>
<string name="notify_never_line">Keine Berichte: Läufe bleiben nur im Verlauf der Aufgabe.</string>
<string name="notify_when_words">Meldet sich, wenn: %1$s</string>
<string name="run_open_report">Zugehörigen Bericht öffnen</string>
<string name="channel_reports">Berichte</string>
<string name="channel_reports_high">Wichtige Berichte</string>
<string name="report_new_public">Neuer Bericht</string>
<string name="schedule_run_again">Erneut ausführen</string>
<string name="card_approval">Das erlauben?</string>
<string name="card_allow_once">Einmal erlauben</string>
<string name="card_allow_always">Dies immer erlauben</string>
<string name="card_allow_always">Immer erlauben</string>
<string name="card_deny">Ablehnen</string>
<string name="card_deny_reason">Ablehnen und begründen</string>
<string name="plan_approve_edit">Bestätigen, weiter im Modus Bearbeiten</string>
<string name="plan_approve_manual">Bestätigen, weiter im Modus Manuell</string>
<string name="card_reason">Warum nicht? (optional)</string>
<string name="card_recommended">empfohlen</string>
<string name="card_answer">Ihre Antwort</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Erkläre, was auf meinem Bildschirm ist.</string>
<string name="assist_continue">Letzten Chat fortsetzen</string>
<string name="assist_help">Halten Sie die Ein-/Aus-Taste, um den Assistenten über jeder App zu öffnen, oder nutzen Sie die Kachel in den Schnelleinstellungen.</string>
<string name="assist_no_wake_word">Es gibt kein Aktivierungswort: Auf normalem Android ist das Lauschen darauf dem im Telefon eingebauten Assistenten vorbehalten.</string>
<string name="assist_connecting">Verbinden…</string>
<string name="assist_offline">%1$s ist nicht erreichbar</string>
<string name="assist_no_model">Kein Modell</string>
@@ -390,6 +421,127 @@
<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_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="assist_wake_word_hint">Kein Aktivierungswort, außer du willst eines: Einstellungen › Assistent › Aktivierungswort schaltet das eigene von LLeMbas ein, auf diesem Telefon.</string>
<string name="channel_wake">Aktivierungswort</string>
<string name="wake_word">Aktivierungswort</string>
<string name="wake_word_listen">Auf ein Aktivierungswort hören</string>
<string name="wake_word_line">Standardmäßig aus. Sag den Satz, und der Assistent öffnet sich zuhörend über der App auf dem Bildschirm.</string>
<string name="wake_word_unavailable">Nicht in diesem Build. Der F-Droid-Build hat keine Aktivierungswort-Engine, weil F-Droid jede Bibliothek aus dem Quellcode baut; der Build von llembas.eu hat eine.</string>
<string name="wake_phrase_line">Das sagst du, dann eine kurze Pause: Es zählt, sobald du aufhörst. Auf Englisch, egal in welcher Sprache die App ist: Die Engine kennt nur englische Sprache.</string>
<string name="wake_greeting">Anrede</string>
<string name="wake_name">Name</string>
<string name="wake_name_google_line">Ein Google-Telefon oder -Lautsprecher in der Nähe antwortet ebenfalls.</string>
<string name="wake_sensitivity">Empfindlichkeit</string>
<string name="wake_sensitivity_low">Niedrig</string>
<string name="wake_sensitivity_low_line">Startet am seltensten versehentlich. Du musst den Satz vielleicht deutlicher oder zweimal sagen.</string>
<string name="wake_sensitivity_normal">Normal</string>
<string name="wake_sensitivity_normal_line">Die eigene Einstellung der Engine.</string>
<string name="wake_sensitivity_high">Hoch</string>
<string name="wake_sensitivity_high_line">Hört dich am leichtesten, auch aus größerer Entfernung. Startet öfter versehentlich.</string>
<string name="wake_test">Aktivierungswort testen</string>
<string name="wake_test_line">Zeigt zehn Sekunden lang, ob dein Satz gehört wird, ohne den Assistenten zu öffnen.</string>
<string name="wake_test_say">Sag jetzt „%1$s“, dann eine Pause…</string>
<string name="wake_test_heard">Gehört</string>
<string name="wake_test_missed">In zehn Sekunden nicht gehört. Versuch es näher am Telefon, in einem ruhigeren Moment oder mit höherer Empfindlichkeit.</string>
<string name="wake_test_off">Schalte zuerst das Aktivierungswort ein.</string>
<string name="wake_screen_only">Nur bei eingeschaltetem Bildschirm</string>
<string name="wake_screen_only_line">Aus: Es hört auch bei ausgeschaltetem Bildschirm zu, was mehr Akku kostet.</string>
<string name="wake_battery">Im Hintergrund laufen lassen</string>
<string name="wake_battery_line">Manche Telefone (Samsung, Xiaomi, Huawei, OnePlus und andere) beenden Hintergrund-Apps, um Akku zu sparen, und damit auch das Aktivierungswort. Nimm LLeMbas hier von der Akku-Optimierung aus; dontkillmyapp.com erklärt die Einstellungen deines Telefons.</string>
<string name="wake_word_privacy">Vor dem Wort verlässt nichts das Telefon. Der Ton des Mikrofons geht nur an die Aktivierungswort-Engine auf dem Telefon und wird nicht gespeichert; die Benachrichtigung bleibt sichtbar, solange es zuhört. Die Sätze sind englisch; die Engine ist sherpa-onnx (Open Source).</string>
<string name="wake_word_cost">Es kostet Akku: Das Mikrofon bleibt an, und der Prozessor des Telefons prüft jeden Moment Ton, ohne den Stromspar-Chip, den der eingebaute Assistent nutzt. Es pausiert im Energiesparmodus, während der Assistent offen ist und, wenn du es nicht änderst, bei ausgeschaltetem Bildschirm. Nach einem Neustart tippe auf seine Benachrichtigung, um es wieder zu starten.</string>
<string name="wake_listening_for">Hört auf „%1$s“</string>
<string name="wake_off">Das Aktivierungswort hört nicht zu</string>
<string name="wake_tap_to_start">Tippe, um es wieder zu starten. Wenn Android fragt, erlaube das Mikrofon.</string>
<string name="wake_starting">Aktivierungswort wird gestartet…</string>
<string name="wake_paused_silent">Aktivierungswort hört nichts: Eine andere App hat das Mikrofon, oder das Mikrofon des Telefons ist ausgeschaltet</string>
<string name="wake_failed_no_engine">Aktivierungswort funktioniert nicht: Dieser Build hat keine Engine</string>
<string name="wake_failed_model">Aktivierungswort funktioniert nicht: Sein Modell konnte auf diesem Telefon nicht entpackt werden</string>
<string name="wake_failed_engine">Aktivierungswort funktioniert nicht: Die Engine ist nicht gestartet</string>
<string name="wake_failed_microphone">Aktivierungswort funktioniert nicht: Das Mikrofon ist nicht gestartet</string>
<string name="wake_failed_line">Es hört nicht zu. Es versucht es von selbst erneut.</string>
<string name="wake_notification_line">Bis du es sagst, verlässt nichts das Telefon.</string>
<string name="wake_paused_screen">Aktivierungswort pausiert: Bildschirm aus</string>
<string name="wake_paused_battery">Aktivierungswort pausiert: Energiesparmodus ist an</string>
<string name="wake_paused_assistant">Aktivierungswort pausiert, solange der Assistent offen ist</string>
<string name="wake_paused_microphone">Aktivierungswort pausiert: LLeMbas darf das Mikrofon nicht verwenden</string>
<string name="wake_stop">Nicht mehr zuhören</string>
<string name="wake_heard">Gehört. Tippe, um zu fragen.</string>
<string name="channel_wake_heard">Aktivierungswort gehört</string>
<string name="wake_heard_line">LLeMbas kann sich nur als App für den digitalen Assistenten des Telefons selbst über anderen Apps öffnen.</string>
<string name="wake_not_assistant">LLeMbas ist nicht die App für den digitalen Assistenten</string>
<string name="wake_not_assistant_line">Deshalb kann das Aktivierungswort den Assistenten nicht über anderen Apps öffnen: Du bekommst eine Benachrichtigung zum Antippen. Um überall per Stimme zu öffnen, tippe hier und wähle LLeMbas als App für den digitalen Assistenten.</string>
<string name="wake_last">Letztes Aufwecken</string>
<string name="wake_last_none">Der Satz wurde noch nicht gehört.</string>
<string name="wake_out_opened">Assistent geöffnet.</string>
<string name="wake_out_no_sheet">Android wurde gebeten, den Assistenten zu öffnen; es hat nicht abgelehnt, aber es kam kein Blatt.</string>
<string name="wake_out_not_connected">Android hatte LLeMbas nicht als Assistenten verbunden, daher ließ sich das Blatt nicht öffnen.</string>
<string name="wake_out_refused">Android hat das Öffnen des Assistenten abgelehnt: %1$s</string>
<string name="wake_out_activity">Stattdessen als Bildschirm der App geöffnet.</string>
<string name="wake_out_notification">Stattdessen eine Benachrichtigung zum Antippen gesendet.</string>
<string name="wake_out_tested">In einem Test gehört: Es war nichts zu öffnen.</string>
<string name="wake_role_held">LLeMbas war die App für den digitalen Assistenten.</string>
<string name="wake_role_not_held">LLeMbas war nicht die App für den digitalen Assistenten.</string>
<string name="wake_link_never">Android hatte den Assistenten seit dem Start der App nicht verbunden.</string>
<string name="wake_link_ready">Android hatte den Assistenten um %1$s verbunden.</string>
<string name="wake_link_shutdown">Android hatte ihn um %1$s getrennt.</string>
<string name="wake_link_later">Android hat ihn um %1$s wieder verbunden.</string>
<string name="wake_sheet_ms">Das Blatt war nach %1$s ms da.</string>
<string name="wake_no_recognizers">Dieses Telefon hat keine Spracherkenner, daher führt Android darauf keinen Sprachassistenten-Dienst aus.</string>
<string name="wake_not_active">LLeMbas war als App für den digitalen Assistenten gewählt, aber Android nutzte es nicht als Sprachassistenten.</string>
<string name="wake_waited">Kurz gewartet, bis Android ihn verbindet.</string>
<string name="wake_show_failed">Android meldete, dass es das Blatt des Assistenten nicht anzeigen konnte.</string>
<string name="wake_assistant_inactive">Android nutzt LLeMbas gerade nicht als Sprachassistenten</string>
<string name="wake_assistant_inactive_line">Wähle LLeMbas erneut als App für den digitalen Assistenten: Tippe hier, wähle eine andere App und dann LLeMbas. Bis dahin öffnet langes Drücken es als gewöhnlichen Bildschirm, und das Aktivierungswort kann nur eine Benachrichtigung senden.</string>
<string name="wake_assistant_unbound">LLeMbas ist der Assistent, aber Android hat ihn gerade nicht verbunden</string>
<string name="wake_assistant_unbound_line">Solange das so ist, kann das Aktivierungswort das Blatt nicht selbst öffnen. Tippe für die Assistenten-Einstellung des Systems: Eine andere App und dann wieder LLeMbas zu wählen verbindet ihn.</string>
<string name="wake_heard_could_not">Ließ sich nicht selbst öffnen — tippe, um zu fragen</string>
<string name="wake_resume">Wieder auf das Aktivierungswort hören</string>
<string name="wake_resume_line">Das Telefon wurde neu gestartet. Tippe, um wieder zuzuhören.</string>
<string name="assist_notifications">Meine Benachrichtigungen zusammenfassen</string>
<string name="assist_notifications_prompt">Fasse meine Benachrichtigungen zusammen: Was braucht meine Aufmerksamkeit?</string>
<string name="assist_notifications_phrases">meine benachrichtigungen|meinen benachrichtigungen|meiner benachrichtigungen</string>
<string name="notification_summaries">Zusammenfassungen der Benachrichtigungen</string>
<string name="notification_summaries_switch">Den Assistenten meine Benachrichtigungen lesen lassen, wenn ich frage</string>
<string name="notification_summaries_line">Sag „fasse meine Benachrichtigungen zusammen“ oder tippe auf den Chip im Assistenten.</string>
<string name="notification_summaries_unavailable">Nicht in diesem Build. Das Lesen von Benachrichtigungen braucht den „notifications“-Build von LLeMbas, weil Google Play Protect die Installation einer App von außerhalb des Play Store blockiert, die sie lesen kann. Es ist dieselbe App mit derselben Signatur: Auf der Release-Seite lässt sich die Datei, die auf -notifications.apk endet, über diese installieren.</string>
<string name="update_notifications_manual">Dies ist der „notifications“-Build: Installiere das Update von der Release-Seite, die Datei, die auf -notifications.apk endet.</string>
<string name="notification_access">Zugriff auf Benachrichtigungen</string>
<string name="notification_access_on">Erteilt. Der Schalter dafür ist in den Android-Einstellungen.</string>
<string name="notification_access_off">Noch nicht erteilt. Tippe, um den Android-Schalter für LLeMbas zu öffnen.</string>
<string name="notification_summaries_privacy">Standardmäßig aus. Wenn du fragst, geht der Text der Benachrichtigungen, die gerade auf deinem Telefon sind (App, Titel, Text), mit dieser einen Frage an deine Instanz und ihr Modell. Vorher wird nichts gelesen, die App behält nichts davon, und bei gesperrtem Telefon wird nichts gelesen. Der Benachrichtigungszugriff von Android lässt eine App jede Benachrichtigung sehen; ihn zu erteilen und zu entziehen liegt bei dir.</string>
<string name="nav_app">Navigations-App</string>
<string name="nav_app_auto">Die installierte</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Jedes Mal fragen</string>
<string name="nav_app_not_installed">Nicht installiert</string>
<string name="osmand_info">OsmAnd nach der Route fragen</string>
<string name="osmand_info_line">Damit „Zwischenstopp hinzufügen“ und die Suche in der Nähe auch mit einer in OsmAnd geplanten Route gehen: LLeMbas fragt OsmAnd, wo du bist und wohin die Route führt. Erlaube LLeMbas zuerst in OsmAnd (verbundene Apps, mit Standort); OsmAnd sagt Bescheid, wenn es nicht erlaubt ist.</string>
<string name="phone_actions_line">Ein Modell kann anbieten, etwas auf diesem Telefon zu tun — einen Wecker stellen, einen Termin eintragen, eine Nachricht entwerfen, eine Route starten. Nichts passiert, bevor du auf seiner Karte auf Ausführen tippst, und nie bei gesperrtem Telefon. Google Maps startet eine Route mit ein paar Stopps, kann aber keinen in eine laufende Route einfügen und nicht angehalten werden; OsmAnd kann das.</string>
<string name="action_card_title">Das auf deinem Telefon tun?</string>
<string name="action_do">Ausführen</string>
<string name="action_running">Wird ausgeführt…</string>
<string name="action_unlock">Entsperre zuerst das Telefon und tippe dann auf Ausführen.</string>
<string name="action_failed">Hat nicht geklappt: %1$s</string>
<string name="nav_app_pick">Mit welcher Karten-App?</string>
<string name="action_google_add_stop">Google Maps kann keinen Stopp in eine laufende Route einfügen: Es startet die Route neu, über den Stopp.</string>
<string name="action_google_no_stop">Google Maps lässt sich nicht von außen anhalten: Beende die Route dort.</string>
<string name="action_line_clock">Die Uhr-App stellt es ein.</string>
<string name="action_line_calendar">Der Kalender öffnet sich mit dem ausgefüllten Termin; du speicherst ihn.</string>
<string name="action_line_draft">Öffnet einen Entwurf; du sendest ihn selbst.</string>
<string name="action_line_dial">Die Telefon-App öffnet sich mit der Nummer; du rufst an.</string>
<string name="action_line_map">%1$s übernimmt die Route.</string>
<string name="action_line_now">Passiert sofort.</string>
<string name="action_line_settings">Öffnet die Einstellung; du änderst sie.</string>
<string name="action_line_automation">Startet deine Automatisierung (Tasker, wenn keine andere App genannt ist).</string>
<string name="action_line_open">Öffnet es.</string>
<string name="assist_recogniser_failed">Die Spracherkennung des Telefons hat angehalten. Versuchen Sie es erneut oder wählen Sie LLeMbas unter Einstellungen › Spracheingabe.</string>
<string name="assistant_listens">Beim Öffnen des Assistenten zuhören</string>
<string name="voice_input">Spracheingabe</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Wird vom Assistenten und vom Mikrofon im Chat genutzt. Mit LLeMbas zeigt der Assistent die Wörter einen Moment später, und eine Pause sendet sie, ein Chat schreibt sie auf, wenn Sie aufhören; mit der Erkennung des Telefons erscheinen sie beim Sprechen.</string>
<string name="share_sending">Wird an LLeMbas gesendet…</string>
<string name="share_default_prompt">Schauen Sie sich das an.</string>
<string name="share_ask_hint">Was soll LLeMbas damit tun? (optional)</string>
<string name="widget_hint">Frag mich alles</string>
<string name="widget_speak">Sprechen</string>
<string name="widget_description">Per Sprache oder Text fragen oder den letzten Assistenten-Chat fortsetzen. Zeigt nichts aus Ihrem Konto.</string>
<string name="shortcut_last">Letzter Chat</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<string name="channel_scheduled_failures">Fallos programados</string>
<string name="scheduled_result_public">Una tarea programada tiene un resultado.</string>
<string name="scheduled_failed_public">Una tarea programada falló.</string>
<string name="page_note">Esta respuesta tiene una página: %1$s</string>
<string name="page_where">Ábrela en la web o en LLeMbas Desktop para verla.</string>
<string name="page_untitled">Página</string>
<string name="reports">Informes</string>
<string name="report">Informe</string>
<string name="reports_none">Aún no hay informes. Una tarea programada escribe uno cuando tiene algo que decirte.</string>
<string name="reports_unsupported">Esta instancia ejecuta un LLeMbas que todavía no tiene Informes.</string>
<string name="report_untitled">Informe sin título</string>
<string name="report_delete_title">¿Eliminar este informe?</string>
<string name="report_delete_line">«%1$s» se elimina para siempre, junto con la conversación sobre él.</string>
<string name="report_mark_read">Marcar como leído</string>
<string name="report_important">Importante</string>
<string name="report_share">Compartir</string>
<string name="report_reply">Responder</string>
<string name="report_chat_title">Informe: %1$s</string>
<string name="notify_when">Avisar cuando</string>
<string name="notify_every_run">En cada ejecución</string>
<string name="notify_every_run_line">El modelo escribe un informe cada vez, también cuando no ha encontrado nada.</string>
<string name="notify_when_option">Cuando…</string>
<string name="notify_when_line">El modelo escribe un informe solo cuando esto se cumple.</string>
<string name="notify_when_label">¿Cuando qué?</string>
<string name="notify_when_default">algo necesita mi atención</string>
<string name="notify_never_option">Nunca</string>
<string name="notify_never_line">Sin informes: las ejecuciones quedan solo en el historial de la tarea.</string>
<string name="notify_when_words">Avisa cuando: %1$s</string>
<string name="run_open_report">Abrir su informe</string>
<string name="channel_reports">Informes</string>
<string name="channel_reports_high">Informes importantes</string>
<string name="report_new_public">Informe nuevo</string>
<string name="schedule_run_again">Ejecutar de nuevo</string>
<string name="card_approval">¿Permitir esto?</string>
<string name="card_allow_once">Permitir una vez</string>
<string name="card_allow_always">Permitir siempre esto</string>
<string name="card_allow_always">Permitir siempre</string>
<string name="card_deny">Denegar</string>
<string name="card_deny_reason">Denegar y decir por qué</string>
<string name="plan_approve_edit">Aprobar y continuar en Editar</string>
<string name="plan_approve_manual">Aprobar y continuar en Manual</string>
<string name="card_reason">¿Por qué no? (opcional)</string>
<string name="card_recommended">recomendado</string>
<string name="card_answer">Su respuesta</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Explica lo que hay en mi pantalla.</string>
<string name="assist_continue">Continuar el último chat</string>
<string name="assist_help">Mantenga pulsado el botón de encendido para abrir el asistente sobre cualquier app, o use el mosaico de Ajustes rápidos.</string>
<string name="assist_no_wake_word">No hay palabra de activación: en Android estándar, escucharla está reservado al asistente integrado en el teléfono.</string>
<string name="assist_connecting">Conectando…</string>
<string name="assist_offline">No se puede contactar con %1$s</string>
<string name="assist_no_model">Sin modelo</string>
@@ -390,6 +421,127 @@
<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_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="assist_wake_word_hint">Sin palabra de activación salvo que quieras una: Ajustes › Asistente › Palabra de activación activa la propia de LLeMbas, en este teléfono.</string>
<string name="channel_wake">Palabra de activación</string>
<string name="wake_word">Palabra de activación</string>
<string name="wake_word_listen">Escuchar una palabra de activación</string>
<string name="wake_word_line">Desactivado por defecto. Di la frase y el asistente se abre escuchando, sobre la app que esté en pantalla.</string>
<string name="wake_word_unavailable">No en esta versión. La versión de F-Droid no tiene motor de palabra de activación, porque F-Droid compila cada biblioteca desde el código fuente; la de llembas.eu sí lo tiene.</string>
<string name="wake_phrase_line">Lo que dices, y después una pausa breve: cuenta cuando te callas. En inglés, sea cual sea el idioma de la app: el motor solo conoce el habla inglesa.</string>
<string name="wake_greeting">Saludo</string>
<string name="wake_name">Nombre</string>
<string name="wake_name_google_line">Un teléfono o altavoz de Google cercano también responderá.</string>
<string name="wake_sensitivity">Sensibilidad</string>
<string name="wake_sensitivity_low">Baja</string>
<string name="wake_sensitivity_low_line">Es la que menos se activa por error. Puede que tengas que decir la frase con más claridad, o dos veces.</string>
<string name="wake_sensitivity_normal">Normal</string>
<string name="wake_sensitivity_normal_line">El ajuste propio del motor.</string>
<string name="wake_sensitivity_high">Alta</string>
<string name="wake_sensitivity_high_line">Te oye con más facilidad, también desde más lejos. Se activa por error más a menudo.</string>
<string name="wake_test">Probar la palabra de activación</string>
<string name="wake_test_line">Durante diez segundos muestra si se oye tu frase, sin abrir el asistente.</string>
<string name="wake_test_say">Di «%1$s» ahora y haz una pausa…</string>
<string name="wake_test_heard">Oída</string>
<string name="wake_test_missed">No se ha oído en diez segundos. Prueba más cerca del teléfono, en un momento más tranquilo o con más sensibilidad.</string>
<string name="wake_test_off">Activa primero la palabra de activación.</string>
<string name="wake_screen_only">Solo con la pantalla encendida</string>
<string name="wake_screen_only_line">Desactivado: también escucha con la pantalla apagada, con más gasto de batería.</string>
<string name="wake_battery">Dejar que funcione en segundo plano</string>
<string name="wake_battery_line">Algunos teléfonos (Samsung, Xiaomi, Huawei, OnePlus y otros) detienen las apps en segundo plano para ahorrar batería, y con ellas la palabra de activación. Excluye aquí a LLeMbas de la optimización de batería; dontkillmyapp.com explica los ajustes de tu teléfono.</string>
<string name="wake_word_privacy">Nada sale del teléfono antes de la palabra. El sonido del micrófono va solo al motor de palabra de activación del teléfono y no se guarda; la notificación se mantiene mientras escucha. Las frases están en inglés; el motor es sherpa-onnx (código abierto).</string>
<string name="wake_word_cost">Gasta batería: el micrófono sigue encendido y el procesador del teléfono revisa cada instante de sonido, sin el chip de bajo consumo que usa el asistente integrado. Se pausa en ahorro de batería, mientras el asistente está abierto y, salvo que lo cambies, con la pantalla apagada. Tras reiniciar, toca su notificación para volver a iniciarlo.</string>
<string name="wake_listening_for">Escuchando «%1$s»</string>
<string name="wake_off">La palabra de activación no está escuchando</string>
<string name="wake_tap_to_start">Toca para iniciarla de nuevo. Si Android pregunta, permite el micrófono.</string>
<string name="wake_starting">Iniciando la palabra de activación…</string>
<string name="wake_paused_silent">La palabra de activación no oye nada: otra app tiene el micrófono, o el micrófono del teléfono está apagado</string>
<string name="wake_failed_no_engine">La palabra de activación no funciona: esta versión no tiene motor</string>
<string name="wake_failed_model">La palabra de activación no funciona: no se pudo desempaquetar su modelo en este teléfono</string>
<string name="wake_failed_engine">La palabra de activación no funciona: el motor no se inició</string>
<string name="wake_failed_microphone">La palabra de activación no funciona: el micrófono no se inició</string>
<string name="wake_failed_line">No está escuchando. Lo intenta de nuevo por sí sola.</string>
<string name="wake_notification_line">Nada sale del teléfono hasta que lo digas.</string>
<string name="wake_paused_screen">Palabra de activación en pausa: la pantalla está apagada</string>
<string name="wake_paused_battery">Palabra de activación en pausa: ahorro de batería activado</string>
<string name="wake_paused_assistant">Palabra de activación en pausa mientras el asistente está abierto</string>
<string name="wake_paused_microphone">Palabra de activación en pausa: LLeMbas no tiene permiso para usar el micrófono</string>
<string name="wake_stop">Dejar de escuchar</string>
<string name="wake_heard">Te he oído. Toca para preguntar.</string>
<string name="channel_wake_heard">Palabra de activación oída</string>
<string name="wake_heard_line">LLeMbas solo puede abrirse por sí mismo sobre otras apps si es la app de asistente digital del teléfono.</string>
<string name="wake_not_assistant">LLeMbas no es la app de asistente digital</string>
<string name="wake_not_assistant_line">Por eso la palabra de activación no puede abrir el asistente sobre otras apps: recibes una notificación que tocar. Para abrir con la voz en cualquier parte, toca aquí y elige LLeMbas como app de asistente digital.</string>
<string name="wake_last">Última activación</string>
<string name="wake_last_none">Todavía no ha oído la frase.</string>
<string name="wake_out_opened">Abrió el asistente.</string>
<string name="wake_out_no_sheet">Pidió a Android que abriera el asistente; no se negó, pero no apareció el panel.</string>
<string name="wake_out_not_connected">Android no tenía LLeMbas conectado como asistente, así que no pudo abrir el panel.</string>
<string name="wake_out_refused">Android se negó a abrir el asistente: %1$s</string>
<string name="wake_out_activity">En su lugar lo abrió como una pantalla de la app.</string>
<string name="wake_out_notification">En su lugar envió una notificación para tocar.</string>
<string name="wake_out_tested">Oída en una prueba: no había nada que abrir.</string>
<string name="wake_role_held">LLeMbas era la app de asistente digital.</string>
<string name="wake_role_not_held">LLeMbas no era la app de asistente digital.</string>
<string name="wake_link_never">Android no había conectado el asistente desde que se inició la app.</string>
<string name="wake_link_ready">Android había conectado el asistente a las %1$s.</string>
<string name="wake_link_shutdown">Android lo había desconectado a las %1$s.</string>
<string name="wake_link_later">Android volvió a conectarlo a las %1$s.</string>
<string name="wake_sheet_ms">El panel apareció tras %1$s ms.</string>
<string name="wake_no_recognizers">Este teléfono no tiene reconocedores de voz, así que Android no ejecuta en él ningún servicio de asistente de voz.</string>
<string name="wake_not_active">LLeMbas estaba elegido como app de asistente digital, pero Android no lo usaba como asistente de voz.</string>
<string name="wake_waited">Esperó un momento a que Android lo conectara.</string>
<string name="wake_show_failed">Android dijo que no pudo mostrar el panel del asistente.</string>
<string name="wake_assistant_inactive">Android no está usando LLeMbas como asistente de voz ahora mismo</string>
<string name="wake_assistant_inactive_line">Elige de nuevo LLeMbas como app de asistente digital: toca aquí, elige otra app y luego LLeMbas. Hasta entonces la pulsación larga lo abre como una pantalla normal y la palabra de activación solo puede enviar una notificación.</string>
<string name="wake_assistant_unbound">LLeMbas es el asistente, pero Android no lo tiene conectado ahora mismo</string>
<string name="wake_assistant_unbound_line">Hasta que lo conecte, la palabra de activación no puede abrir el panel por sí sola. Toca para ir al ajuste del asistente del sistema: elegir otra app y luego LLeMbas de nuevo lo conecta.</string>
<string name="wake_heard_could_not">No pudo abrirse por sí solo: toca para preguntar</string>
<string name="wake_resume">Volver a escuchar la palabra de activación</string>
<string name="wake_resume_line">El teléfono se reinició. Toca para volver a escuchar.</string>
<string name="assist_notifications">Resumir mis notificaciones</string>
<string name="assist_notifications_prompt">Resume mis notificaciones: ¿qué necesita mi atención?</string>
<string name="assist_notifications_phrases">mis notificaciones</string>
<string name="notification_summaries">Resúmenes de notificaciones</string>
<string name="notification_summaries_switch">Dejar que el asistente lea mis notificaciones cuando lo pida</string>
<string name="notification_summaries_line">Pide «resume mis notificaciones» o toca el botón en el asistente.</string>
<string name="notification_summaries_unavailable">No en esta versión. Leer notificaciones requiere la versión «notifications» de LLeMbas, porque Google Play Protect bloquea la instalación de una app de fuera de Play Store que pueda leerlas. Es la misma app con la misma firma: en la página de la versión, el archivo que termina en -notifications.apk se instala sobre esta.</string>
<string name="update_notifications_manual">Esta es la versión «notifications»: instala la actualización desde su página, el archivo que termina en -notifications.apk.</string>
<string name="notification_access">Acceso a notificaciones</string>
<string name="notification_access_on">Concedido. El interruptor de Android está en los ajustes del sistema.</string>
<string name="notification_access_off">Aún no concedido. Toca para abrir el interruptor de Android para LLeMbas.</string>
<string name="notification_summaries_privacy">Desactivado por defecto. Cuando lo pides, el texto de las notificaciones que hay ahora en tu teléfono (app, título, texto) va con esa única pregunta a tu instancia y su modelo. No se lee nada antes, la app no guarda nada y no se lee nada con el teléfono bloqueado. El acceso a notificaciones de Android permite a una app ver todas las notificaciones; darlo y retirarlo es cosa tuya.</string>
<string name="nav_app">App de navegación</string>
<string name="nav_app_auto">La que esté instalada</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Preguntar cada vez</string>
<string name="nav_app_not_installed">No instalada</string>
<string name="osmand_info">Preguntar a OsmAnd por la ruta</string>
<string name="osmand_info_line">Permite «añadir una parada» y buscar cerca de ti con una ruta creada en el propio OsmAnd: LLeMbas pregunta a OsmAnd dónde estás y adónde va la ruta. Primero permite LLeMbas en OsmAnd (apps conectadas, con ubicación); OsmAnd te avisa si no está permitido.</string>
<string name="phone_actions_line">Un modelo puede ofrecer hacer cosas en este teléfono: poner una alarma, añadir un evento, redactar un mensaje, iniciar una ruta. No pasa nada hasta que tocas Hacerlo en su tarjeta, y nunca con el teléfono bloqueado. Google Maps inicia una ruta con unas pocas paradas, pero no puede añadir una a una ruta en curso ni detenerse a petición; OsmAnd sí.</string>
<string name="action_card_title">¿Hacer esto en tu teléfono?</string>
<string name="action_do">Hacerlo</string>
<string name="action_running">Haciéndolo…</string>
<string name="action_unlock">Desbloquea primero el teléfono y luego toca Hacerlo.</string>
<string name="action_failed">No funcionó: %1$s</string>
<string name="nav_app_pick">¿Con qué app de mapas?</string>
<string name="action_google_add_stop">Google Maps no puede añadir una parada a una ruta en curso: vuelve a iniciar la ruta, pasando por la parada.</string>
<string name="action_google_no_stop">A Google Maps no se le puede pedir que pare: termina la ruta allí.</string>
<string name="action_line_clock">La app de reloj lo programa.</string>
<string name="action_line_calendar">El calendario se abre con el evento rellenado; tú lo guardas.</string>
<string name="action_line_draft">Abre un borrador; lo envías tú.</string>
<string name="action_line_dial">El marcador se abre con el número; tú haces la llamada.</string>
<string name="action_line_map">%1$s se encarga de la ruta.</string>
<string name="action_line_now">Ocurre al instante.</string>
<string name="action_line_settings">Abre el ajuste; tú lo cambias.</string>
<string name="action_line_automation">Ejecuta tu automatización (Tasker salvo que se indique otra app).</string>
<string name="action_line_open">Lo abre.</string>
<string name="assist_recogniser_failed">El reconocimiento de voz del teléfono se detuvo. Inténtelo de nuevo o elija LLeMbas en Ajustes › Entrada de voz.</string>
<string name="assistant_listens">Empezar a escuchar al abrir el asistente</string>
<string name="voice_input">Entrada de voz</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">La usan el asistente y el micrófono de un chat. Con LLeMbas el asistente muestra las palabras un momento después y una pausa las envía, y un chat las escribe cuando usted para; con el reconocimiento del teléfono aparecen mientras habla.</string>
<string name="share_sending">Enviando a LLeMbas…</string>
<string name="share_default_prompt">Échele un vistazo a esto.</string>
<string name="share_ask_hint">¿Qué debe hacer LLeMbas con esto? (opcional)</string>
<string name="widget_hint">Pregunta lo que quieras</string>
<string name="widget_speak">Hablar</string>
<string name="widget_description">Pregunta por voz o por texto, o continúa el último chat del asistente. No muestra nada de tu cuenta.</string>
<string name="shortcut_last">Último chat</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<string name="channel_scheduled_failures">Échecs planifiés</string>
<string name="scheduled_result_public">Une tâche planifiée a un résultat.</string>
<string name="scheduled_failed_public">Une tâche planifiée a échoué.</string>
<string name="page_note">Cette réponse contient une page : %1$s</string>
<string name="page_where">Ouvrez-la sur le web ou dans LLeMbas Desktop pour la voir.</string>
<string name="page_untitled">Page</string>
<string name="reports">Rapports</string>
<string name="report">Rapport</string>
<string name="reports_none">Pas encore de rapport. Une tâche planifiée en rédige un quand elle a quelque chose à vous dire.</string>
<string name="reports_unsupported">Cette instance utilise un LLeMbas qui n’a pas encore les Rapports.</string>
<string name="report_untitled">Rapport sans titre</string>
<string name="report_delete_title">Supprimer ce rapport ?</string>
<string name="report_delete_line">« %1$s » est supprimé définitivement, avec la conversation à son sujet.</string>
<string name="report_mark_read">Marquer comme lu</string>
<string name="report_important">Important</string>
<string name="report_share">Partager</string>
<string name="report_reply">Répondre</string>
<string name="report_chat_title">Rapport : %1$s</string>
<string name="notify_when">Prévenir quand</string>
<string name="notify_every_run">À chaque exécution</string>
<string name="notify_every_run_line">Le modèle rédige un rapport à chaque fois, même quand rien n’a été trouvé.</string>
<string name="notify_when_option">Quand…</string>
<string name="notify_when_line">Le modèle ne rédige un rapport que si ceci est vrai.</string>
<string name="notify_when_label">Quand quoi ?</string>
<string name="notify_when_default">quelque chose demande mon attention</string>
<string name="notify_never_option">Jamais</string>
<string name="notify_never_line">Aucun rapport : les exécutions restent seulement dans l’historique de la tâche.</string>
<string name="notify_when_words">Prévient quand : %1$s</string>
<string name="run_open_report">Ouvrir son rapport</string>
<string name="channel_reports">Rapports</string>
<string name="channel_reports_high">Rapports importants</string>
<string name="report_new_public">Nouveau rapport</string>
<string name="schedule_run_again">Relancer</string>
<string name="card_approval">Autoriser ceci ?</string>
<string name="card_allow_once">Autoriser une fois</string>
<string name="card_allow_always">Toujours autoriser ceci</string>
<string name="card_allow_always">Toujours autoriser</string>
<string name="card_deny">Refuser</string>
<string name="card_deny_reason">Refuser, et dire pourquoi</string>
<string name="plan_approve_edit">Approuver, continuer en mode Modifier</string>
<string name="plan_approve_manual">Approuver, continuer en mode Manuel</string>
<string name="card_reason">Pourquoi pas ? (facultatif)</string>
<string name="card_recommended">recommandé</string>
<string name="card_answer">Votre réponse</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Explique ce qui est sur mon écran.</string>
<string name="assist_continue">Reprendre la dernière conversation</string>
<string name="assist_help">Maintenez le bouton marche/arrêt pour ouvrir l’assistant par-dessus n’importe quelle app, ou utilisez la tuile des Réglages rapides.</string>
<string name="assist_no_wake_word">Pas de mot d’activation : sur Android standard, l’écoute d’un tel mot est réservée à l’assistant intégré au téléphone.</string>
<string name="assist_connecting">Connexion…</string>
<string name="assist_offline">%1$s est injoignable</string>
<string name="assist_no_model">Aucun modèle</string>
@@ -390,6 +421,127 @@
<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_conversation">En conversation</string>
<string name="assist_conversation_line">J’écoute à nouveau après chaque réponse. Dites « stop » pour arrêter.</string>
<string name="assist_conversation_end">Terminer</string>
<string name="assist_stop_words">stop|arrête|c\'est tout|ça suffit|au revoir|fin|terminé|merci c\'est tout|annuler</string>
<string name="assistant_conversation">Poursuivre une conversation orale</string>
<string name="assistant_conversation_line">Après la lecture d’une réponse orale, l’assistant écoute à nouveau — jusqu’à ce que vous disiez « stop », touchiez Terminer ou ne disiez rien pendant quelques secondes. Fonctionne avec un casque.</string>
<string name="assist_wake_word_hint">Pas de mot d’activation sauf si vous en voulez un : Paramètres › Assistant › Mot d’activation active celui de LLeMbas, sur ce téléphone.</string>
<string name="channel_wake">Mot d’activation</string>
<string name="wake_word">Mot d’activation</string>
<string name="wake_word_listen">Écouter un mot d’activation</string>
<string name="wake_word_line">Désactivé par défaut. Dites la phrase et l’assistant s’ouvre en écoute, par-dessus l’app à l’écran.</string>
<string name="wake_word_unavailable">Pas dans cette version. La version F-Droid n’a pas de moteur de mot d’activation, car F-Droid compile chaque bibliothèque depuis les sources ; celle de llembas.eu en a un.</string>
<string name="wake_phrase_line">Ce que vous dites, puis une courte pause : cela compte dès que vous vous taisez. En anglais, quelle que soit la langue de l’app : le moteur ne connaît que la parole anglaise.</string>
<string name="wake_greeting">Salutation</string>
<string name="wake_name">Nom</string>
<string name="wake_name_google_line">Un téléphone ou une enceinte Google à proximité répondra aussi.</string>
<string name="wake_sensitivity">Sensibilité</string>
<string name="wake_sensitivity_low">Faible</string>
<string name="wake_sensitivity_low_line">Se déclenche le moins souvent par erreur. Vous devrez peut-être dire la phrase plus distinctement, ou deux fois.</string>
<string name="wake_sensitivity_normal">Normale</string>
<string name="wake_sensitivity_normal_line">Le réglage propre au moteur.</string>
<string name="wake_sensitivity_high">Élevée</string>
<string name="wake_sensitivity_high_line">Vous entend le plus facilement, même de plus loin. Se déclenche plus souvent par erreur.</string>
<string name="wake_test">Tester le mot d’activation</string>
<string name="wake_test_line">Pendant dix secondes, indique si votre phrase est entendue, sans ouvrir l’assistant.</string>
<string name="wake_test_say">Dites « %1$s » maintenant, puis faites une pause…</string>
<string name="wake_test_heard">Entendu</string>
<string name="wake_test_missed">Pas entendu en dix secondes. Essayez plus près du téléphone, dans un moment plus calme ou avec une sensibilité plus élevée.</string>
<string name="wake_test_off">Activez d’abord le mot d’activation.</string>
<string name="wake_screen_only">Seulement écran allumé</string>
<string name="wake_screen_only_line">Désactivé : il écoute aussi écran éteint, au prix de plus de batterie.</string>
<string name="wake_battery">Le laisser tourner en arrière-plan</string>
<string name="wake_battery_line">Certains téléphones (Samsung, Xiaomi, Huawei, OnePlus et d’autres) arrêtent les apps en arrière-plan pour économiser la batterie, et le mot d’activation avec. Exemptez ici LLeMbas de l’optimisation de la batterie ; dontkillmyapp.com explique les réglages de votre téléphone.</string>
<string name="wake_word_privacy">Rien ne quitte le téléphone avant le mot. Le son du micro ne va qu’au moteur de mot d’activation du téléphone et n’est pas conservé ; la notification reste affichée tant qu’il écoute. Les phrases sont en anglais ; le moteur est sherpa-onnx (open source).</string>
<string name="wake_word_cost">Cela consomme de la batterie : le micro reste allumé et le processeur du téléphone examine chaque instant de son, sans la puce basse consommation de l’assistant intégré. Il se met en pause en économie de batterie, quand l’assistant est ouvert et, sauf si vous le changez, écran éteint. Après un redémarrage, touchez sa notification pour le relancer.</string>
<string name="wake_listening_for">À l’écoute de « %1$s »</string>
<string name="wake_off">Le mot d’activation n’écoute pas</string>
<string name="wake_tap_to_start">Touchez pour le relancer. Si Android le demande, autorisez le micro.</string>
<string name="wake_starting">Démarrage du mot d’activation…</string>
<string name="wake_paused_silent">Le mot d’activation n’entend rien : une autre app utilise le micro, ou le micro du téléphone est coupé</string>
<string name="wake_failed_no_engine">Le mot d’activation ne fonctionne pas : cette version n’a pas de moteur</string>
<string name="wake_failed_model">Le mot d’activation ne fonctionne pas : son modèle n’a pas pu être décompressé sur ce téléphone</string>
<string name="wake_failed_engine">Le mot d’activation ne fonctionne pas : le moteur n’a pas démarré</string>
<string name="wake_failed_microphone">Le mot d’activation ne fonctionne pas : le micro n’a pas démarré</string>
<string name="wake_failed_line">Il n’écoute pas. Il réessaie de lui-même.</string>
<string name="wake_notification_line">Rien ne quitte le téléphone avant que vous le disiez.</string>
<string name="wake_paused_screen">Mot d’activation en pause : écran éteint</string>
<string name="wake_paused_battery">Mot d’activation en pause : économiseur de batterie activé</string>
<string name="wake_paused_assistant">Mot d’activation en pause pendant que l’assistant est ouvert</string>
<string name="wake_paused_microphone">Mot d’activation en pause : LLeMbas n’est pas autorisé à utiliser le micro</string>
<string name="wake_stop">Arrêter l’écoute</string>
<string name="wake_heard">Entendu. Touchez pour demander.</string>
<string name="channel_wake_heard">Mot d’activation entendu</string>
<string name="wake_heard_line">LLeMbas ne peut s’ouvrir de lui-même par-dessus d’autres apps que s’il est l’assistant numérique du téléphone.</string>
<string name="wake_not_assistant">LLeMbas n’est pas l’application d’assistant numérique</string>
<string name="wake_not_assistant_line">Le mot d’activation ne peut donc pas ouvrir l’assistant par-dessus d’autres apps : vous recevez une notification à toucher. Pour ouvrir à la voix partout, touchez ici et choisissez LLeMbas comme application d’assistant numérique.</string>
<string name="wake_last">Dernier réveil</string>
<string name="wake_last_none">Il n’a pas encore entendu la phrase.</string>
<string name="wake_out_opened">A ouvert l’assistant.</string>
<string name="wake_out_no_sheet">A demandé à Android d’ouvrir l’assistant ; il n’a pas refusé, mais aucun panneau n’est apparu.</string>
<string name="wake_out_not_connected">Android n’avait pas connecté LLeMbas comme assistant, le panneau n’a donc pas pu s’ouvrir.</string>
<string name="wake_out_refused">Android a refusé d’ouvrir l’assistant : %1$s</string>
<string name="wake_out_activity">L’a ouvert à la place comme un écran de l’app.</string>
<string name="wake_out_notification">A envoyé à la place une notification à toucher.</string>
<string name="wake_out_tested">Entendu pendant un test : il n’y avait rien à ouvrir.</string>
<string name="wake_role_held">LLeMbas était l’application d’assistant numérique.</string>
<string name="wake_role_not_held">LLeMbas n’était pas l’application d’assistant numérique.</string>
<string name="wake_link_never">Android n’avait pas connecté l’assistant depuis le démarrage de l’app.</string>
<string name="wake_link_ready">Android avait connecté l’assistant à %1$s.</string>
<string name="wake_link_shutdown">Android l’avait déconnecté à %1$s.</string>
<string name="wake_link_later">Android l’a reconnecté à %1$s.</string>
<string name="wake_sheet_ms">Le panneau était affiché après %1$s ms.</string>
<string name="wake_no_recognizers">Ce téléphone n’a pas de reconnaissance vocale, Android n’y exécute donc aucun service d’assistant vocal.</string>
<string name="wake_not_active">LLeMbas était choisi comme application d’assistant numérique, mais Android ne l’utilisait pas comme assistant vocal.</string>
<string name="wake_waited">A attendu un instant qu’Android le connecte.</string>
<string name="wake_show_failed">Android a indiqué qu’il n’avait pas pu afficher le panneau de l’assistant.</string>
<string name="wake_assistant_inactive">Android n’utilise pas LLeMbas comme assistant vocal pour l’instant</string>
<string name="wake_assistant_inactive_line">Choisissez de nouveau LLeMbas comme application d’assistant numérique : touchez ici, prenez une autre app, puis LLeMbas. D’ici là, l’appui long l’ouvre comme un écran ordinaire et le mot d’activation ne peut qu’envoyer une notification.</string>
<string name="wake_assistant_unbound">LLeMbas est l’assistant, mais Android ne l’a pas connecté pour l’instant</string>
<string name="wake_assistant_unbound_line">Tant que ce n’est pas fait, le mot d’activation ne peut pas ouvrir le panneau de lui-même. Touchez pour le réglage de l’assistant du système : choisir une autre app puis de nouveau LLeMbas le reconnecte.</string>
<string name="wake_heard_could_not">N’a pas pu s’ouvrir de lui-même — touchez pour demander</string>
<string name="wake_resume">Écouter à nouveau le mot d’activation</string>
<string name="wake_resume_line">Le téléphone a redémarré. Touchez pour reprendre l’écoute.</string>
<string name="assist_notifications">Résumer mes notifications</string>
<string name="assist_notifications_prompt">Résume mes notifications : qu’est-ce qui demande mon attention ?</string>
<string name="assist_notifications_phrases">mes notifications</string>
<string name="notification_summaries">Résumés des notifications</string>
<string name="notification_summaries_switch">Laisser l’assistant lire mes notifications quand je le demande</string>
<string name="notification_summaries_line">Demandez « résume mes notifications », ou touchez la puce dans l’assistant.</string>
<string name="notification_summaries_unavailable">Pas dans cette version. Lire les notifications demande la version « notifications » de LLeMbas, car Google Play Protect bloque l’installation d’une app hors du Play Store capable de les lire. C’est la même app avec la même signature : sur la page de la version, le fichier se terminant par -notifications.apk s’installe par-dessus celle-ci.</string>
<string name="update_notifications_manual">Ceci est la version « notifications » : installez la mise à jour depuis sa page, le fichier se terminant par -notifications.apk.</string>
<string name="notification_access">Accès aux notifications</string>
<string name="notification_access_on">Accordé. L’interrupteur d’Android est dans les paramètres du système.</string>
<string name="notification_access_off">Pas encore accordé. Touchez pour ouvrir l’interrupteur d’Android pour LLeMbas.</string>
<string name="notification_summaries_privacy">Désactivé par défaut. Quand vous le demandez, le texte des notifications présentes sur votre téléphone (app, titre, texte) part avec cette seule question vers votre instance et son modèle. Rien n’est lu avant, l’app n’en garde rien, et rien n’est lu téléphone verrouillé. L’accès aux notifications d’Android permet à une app de voir toutes les notifications : c’est à vous de l’accorder et de le retirer.</string>
<string name="nav_app">App de navigation</string>
<string name="nav_app_auto">Celle qui est installée</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Demander à chaque fois</string>
<string name="nav_app_not_installed">Non installée</string>
<string name="osmand_info">Demander l’itinéraire à OsmAnd</string>
<string name="osmand_info_line">Permet « ajouter un arrêt » et la recherche à proximité avec un itinéraire créé dans OsmAnd même : LLeMbas demande à OsmAnd où vous êtes et où va l’itinéraire. Autorisez d’abord LLeMbas dans OsmAnd (apps connectées, avec la position) ; OsmAnd vous prévient sinon.</string>
<string name="phone_actions_line">Un modèle peut proposer de faire des choses sur ce téléphone : régler une alarme, ajouter un événement, rédiger un message, lancer un itinéraire. Rien ne se passe tant que vous ne touchez pas Le faire sur sa carte, et jamais téléphone verrouillé. Google Maps lance un itinéraire avec quelques arrêts mais ne peut ni en ajouter à un itinéraire en cours ni être arrêté ; OsmAnd le peut.</string>
<string name="action_card_title">Faire ceci sur votre téléphone ?</string>
<string name="action_do">Le faire</string>
<string name="action_running">En cours…</string>
<string name="action_unlock">Déverrouillez d’abord le téléphone, puis touchez Le faire.</string>
<string name="action_failed">Cela n’a pas marché : %1$s</string>
<string name="nav_app_pick">Avec quelle app de cartes ?</string>
<string name="action_google_add_stop">Google Maps ne peut pas ajouter d’arrêt à un itinéraire en cours : il relance l’itinéraire, par l’arrêt.</string>
<string name="action_google_no_stop">On ne peut pas dire à Google Maps d’arrêter : terminez l’itinéraire dans l’app.</string>
<string name="action_line_clock">L’app Horloge le règle.</string>
<string name="action_line_calendar">Le calendrier s’ouvre avec l’événement rempli ; vous l’enregistrez.</string>
<string name="action_line_draft">Ouvre un brouillon ; vous l’envoyez vous-même.</string>
<string name="action_line_dial">Le clavier s’ouvre avec le numéro ; vous lancez l’appel.</string>
<string name="action_line_map">%1$s prend l’itinéraire.</string>
<string name="action_line_now">Se fait aussitôt.</string>
<string name="action_line_settings">Ouvre le réglage ; vous le changez.</string>
<string name="action_line_automation">Lance votre automatisation (Tasker sauf si une autre app est nommée).</string>
<string name="action_line_open">L’ouvre.</string>
<string name="assist_recogniser_failed">La reconnaissance vocale du téléphone s’est arrêtée. Réessayez, ou choisissez LLeMbas dans Réglages › Saisie vocale.</string>
<string name="assistant_listens">Écouter dès l’ouverture de l’assistant</string>
<string name="voice_input">Saisie vocale</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Utilisée par l’assistant et par le micro d’une conversation. Avec LLeMbas, l’assistant affiche les mots avec un léger décalage et une pause les envoie, et une conversation les écrit quand vous vous arrêtez ; avec la reconnaissance du téléphone, ils apparaissent pendant que vous parlez.</string>
<string name="share_sending">Envoi à LLeMbas…</string>
<string name="share_default_prompt">Jetez un œil à ceci.</string>
<string name="share_ask_hint">Que doit en faire LLeMbas ? (facultatif)</string>
<string name="widget_hint">Posez une question</string>
<string name="widget_speak">Parler</string>
<string name="widget_description">Demandez à la voix ou par écrit, ou reprenez la dernière discussion de l’assistant. N’affiche rien de votre compte.</string>
<string name="shortcut_last">Dernière discussion</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<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>
<string name="card_allow_always">Ennek mindig engedélyezése</string>
<string name="card_allow_always">Engedélyezés mindig</string>
<string name="card_deny">Elutasítás</string>
<string name="card_deny_reason">Elutasítás indoklással</string>
<string name="plan_approve_edit">Jóváhagyás, folytatás Szerkesztés módban</string>
<string name="plan_approve_manual">Jóváhagyás, folytatás Kézi módban</string>
<string name="card_reason">Miért nem? (opcionális)</string>
<string name="card_recommended">ajánlott</string>
<string name="card_answer">Az Ön válasza</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Magyarázd el, mi van a képernyőmön.</string>
<string name="assist_continue">Az utolsó csevegés folytatása</string>
<string name="assist_help">Tartsa lenyomva a bekapcsológombot, hogy bármely alkalmazás fölött megnyissa az asszisztenst, vagy használja a Gyorsbeállítások csempét.</string>
<string name="assist_no_wake_word">Ébresztőszó nincs: a gyári Androidon az ébresztőszó figyelése a telefonba épített asszisztensé.</string>
<string name="assist_connecting">Csatlakozás…</string>
<string name="assist_offline">%1$s nem érhető el</string>
<string name="assist_no_model">Nincs modell</string>
@@ -390,6 +421,127 @@
<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_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="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>
<string name="wake_word_listen">Ébresztőszó figyelése</string>
<string name="wake_word_line">Alapból ki van kapcsolva. Mondd ki a kifejezést, és az asszisztens figyelve megnyílik a képernyőn lévő alkalmazás fölött.</string>
<string name="wake_word_unavailable">Ebben a változatban nincs. Az F-Droid-változatban nincs ébresztőszó-motor, mert az F-Droid minden könyvtárat forrásból fordít; a llembas.eu-s változatban van.</string>
<string name="wake_phrase_line">Ezt mondod, utána rövid szünet: akkor számít, amikor elhallgatsz. Angolul, bármilyen nyelvű is az alkalmazás: a motor csak az angol beszédet ismeri.</string>
<string name="wake_greeting">Megszólítás</string>
<string name="wake_name">Név</string>
<string name="wake_name_google_line">A közelben lévő Google-telefon vagy -hangszóró is válaszolni fog.</string>
<string name="wake_sensitivity">Érzékenység</string>
<string name="wake_sensitivity_low">Alacsony</string>
<string name="wake_sensitivity_low_line">A legritkábban indul el tévedésből. Lehet, hogy tisztábban vagy kétszer kell kimondanod a kifejezést.</string>
<string name="wake_sensitivity_normal">Normál</string>
<string name="wake_sensitivity_normal_line">A motor saját beállítása.</string>
<string name="wake_sensitivity_high">Magas</string>
<string name="wake_sensitivity_high_line">A legkönnyebben hall meg, távolabbról is. Gyakrabban indul el tévedésből.</string>
<string name="wake_test">Ébresztőszó kipróbálása</string>
<string name="wake_test_line">Tíz másodpercig mutatja, hogy hallja-e a kifejezésedet, az asszisztens megnyitása nélkül.</string>
<string name="wake_test_say">Most mondd: „%1$s”, aztán tarts szünetet…</string>
<string name="wake_test_heard">Hallottam</string>
<string name="wake_test_missed">Tíz másodperc alatt nem hallottam. Próbáld közelebb a telefonhoz, csendesebb pillanatban vagy nagyobb érzékenységgel.</string>
<string name="wake_test_off">Előbb kapcsold be az ébresztőszót.</string>
<string name="wake_screen_only">Csak bekapcsolt képernyőnél</string>
<string name="wake_screen_only_line">Kikapcsolva kikapcsolt képernyőnél is figyel, ami több akkumulátort fogyaszt.</string>
<string name="wake_battery">Futhasson a háttérben</string>
<string name="wake_battery_line">Egyes telefonok (Samsung, Xiaomi, Huawei, OnePlus és mások) az akkumulátor kímélése miatt leállítják a háttéralkalmazásokat, és velük az ébresztőszót is. Itt vedd ki a LLeMbast az akkumulátor-optimalizálásból; a dontkillmyapp.com elmagyarázza a telefonod beállításait.</string>
<string name="wake_word_privacy">A szó előtt semmi nem hagyja el a telefont. A mikrofon hangja csak a telefonon futó ébresztőszó-motorhoz jut, és nem tárolódik; amíg figyel, az értesítés végig látható. A kifejezések angolok; a motor a sherpa-onnx (nyílt forráskódú).</string>
<string name="wake_word_cost">Akkumulátorba kerül: a mikrofon bekapcsolva marad, és a telefon processzora minden hangpillanatot ellenőriz, a beépített asszisztens energiatakarékos chipje nélkül. Energiatakarékos módban, nyitott asszisztensnél és — ha nem változtatod meg — kikapcsolt képernyőnél szünetel. Újraindítás után koppints az értesítésére az újraindításhoz.</string>
<string name="wake_listening_for">Figyeli: „%1$s”</string>
<string name="wake_off">Az ébresztőszó nem figyel</string>
<string name="wake_tap_to_start">Koppints az újraindításához. Ha az Android rákérdez, engedélyezd a mikrofont.</string>
<string name="wake_starting">Az ébresztőszó indul…</string>
<string name="wake_paused_silent">Az ébresztőszó semmit nem hall: másik alkalmazás használja a mikrofont, vagy a telefon mikrofonja ki van kapcsolva</string>
<string name="wake_failed_no_engine">Az ébresztőszó nem működik: ebben a változatban nincs motor</string>
<string name="wake_failed_model">Az ébresztőszó nem működik: a modelljét nem sikerült kicsomagolni ezen a telefonon</string>
<string name="wake_failed_engine">Az ébresztőszó nem működik: a motor nem indult el</string>
<string name="wake_failed_microphone">Az ébresztőszó nem működik: a mikrofon nem indult el</string>
<string name="wake_failed_line">Nem figyel. Magától újrapróbálja.</string>
<string name="wake_notification_line">Amíg ki nem mondod, semmi nem hagyja el a telefont.</string>
<string name="wake_paused_screen">Ébresztőszó szünetel: a képernyő ki van kapcsolva</string>
<string name="wake_paused_battery">Ébresztőszó szünetel: be van kapcsolva az energiatakarékos mód</string>
<string name="wake_paused_assistant">Az ébresztőszó szünetel, amíg az asszisztens nyitva van</string>
<string name="wake_paused_microphone">Ébresztőszó szünetel: a LLeMbas nem használhatja a mikrofont</string>
<string name="wake_stop">Figyelés leállítása</string>
<string name="wake_heard">Hallottalak. Koppints a kérdezéshez.</string>
<string name="channel_wake_heard">Ébresztőszó elhangzott</string>
<string name="wake_heard_line">A LLeMbas csak a telefon digitális asszisztens alkalmazásaként tud magától megnyílni más alkalmazások fölött.</string>
<string name="wake_not_assistant">A LLeMbas nem a digitális asszisztens alkalmazás</string>
<string name="wake_not_assistant_line">Ezért az ébresztőszó nem tudja megnyitni az asszisztenst más alkalmazások fölött: értesítést kapsz, amelyre koppinthatsz. Ha bárhol hanggal szeretnéd megnyitni, koppints ide, és válaszd a LLeMbast digitális asszisztens alkalmazásnak.</string>
<string name="wake_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>
<string name="assist_notifications_prompt">Foglald össze az értesítéseimet: mi igényli a figyelmemet?</string>
<string name="assist_notifications_phrases">értesítéseim|értesítéseimet|az értesítéseimről</string>
<string name="notification_summaries">Értesítések összefoglalása</string>
<string name="notification_summaries_switch">Az asszisztens kérésemre elolvashatja az értesítéseimet</string>
<string name="notification_summaries_line">Kérd, hogy „foglald össze az értesítéseimet”, vagy koppints a gombra az asszisztensben.</string>
<string name="notification_summaries_unavailable">Ebben a változatban nincs. Az értesítések olvasásához a LLeMbas „notifications” változata kell, mert a Google Play Protect letiltja az olyan, Play Áruházon kívüli alkalmazás telepítését, amely olvasni tudja őket. Ugyanaz az alkalmazás ugyanazzal az aláírással: a kiadás oldalán a -notifications.apk végű fájl erre telepíthető rá.</string>
<string name="update_notifications_manual">Ez a „notifications” változat: a frissítést a kiadás oldaláról telepítsd, a -notifications.apk végű fájlt.</string>
<string name="notification_access">Hozzáférés az értesítésekhez</string>
<string name="notification_access_on">Megadva. Az Android kapcsolója a rendszerbeállításokban van.</string>
<string name="notification_access_off">Még nincs megadva. Koppints az Android LLeMbas-kapcsolójának megnyitásához.</string>
<string name="notification_summaries_privacy">Alapból ki van kapcsolva. Ha kéred, a telefonon éppen látható értesítések szövege (alkalmazás, cím, szöveg) ezzel az egy kérdéssel együtt a példányodhoz és a modelljéhez kerül. Előtte semmit nem olvas, az alkalmazás semmit nem tart meg, és zárolt telefonnál semmit nem olvas. Az Android értesítés-hozzáférése minden értesítést láthatóvá tesz egy alkalmazásnak, ezért rajtad múlik, megadod-e, és visszavonod-e.</string>
<string name="nav_app">Navigációs alkalmazás</string>
<string name="nav_app_auto">Amelyik telepítve van</string>
<string name="nav_app_google">Google Térkép</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Mindig kérdezzen</string>
<string name="nav_app_not_installed">Nincs telepítve</string>
<string name="osmand_info">Útvonal lekérdezése az OsmAndtól</string>
<string name="osmand_info_line">Így a „megálló hozzáadása” és a közeli keresés az OsmAndban beállított útvonallal is működik: a LLeMbas megkérdezi az OsmAndot, hol vagy és hová tart az útvonal. Előbb engedélyezd a LLeMbast az OsmAndban (csatlakoztatott alkalmazások, helyadattal); az OsmAnd szól, ha nincs engedélyezve.</string>
<string name="phone_actions_line">Egy modell felajánlhatja, hogy tesz valamit ezen a telefonon — ébresztőt állít, eseményt vesz fel, üzenetet fogalmaz, útvonalat indít. Semmi sem történik, amíg a kártyáján nem koppintasz a Mehet gombra, és zárolt telefonnál soha. A Google Térkép néhány megállós útvonalat indít, de futó útvonalhoz nem ad megállót és nem állítható le; az OsmAnd igen.</string>
<string name="action_card_title">Megtegyem ezt a telefonodon?</string>
<string name="action_do">Mehet</string>
<string name="action_running">Folyamatban…</string>
<string name="action_unlock">Előbb oldd fel a telefont, aztán koppints a Mehet gombra.</string>
<string name="action_failed">Nem sikerült: %1$s</string>
<string name="nav_app_pick">Melyik térképalkalmazással?</string>
<string name="action_google_add_stop">A Google Térkép nem tud megállót adni egy futó útvonalhoz: újraindítja az útvonalat a megállón át.</string>
<string name="action_google_no_stop">A Google Térképet nem lehet kívülről leállítani: ott fejezd be az útvonalat.</string>
<string name="action_line_clock">Az Óra alkalmazás beállítja.</string>
<string name="action_line_calendar">Megnyílik a naptár a kitöltött eseménnyel; te mented el.</string>
<string name="action_line_draft">Megnyit egy piszkozatot; te küldöd el.</string>
<string name="action_line_dial">Megnyílik a tárcsázó a számmal; te indítod a hívást.</string>
<string name="action_line_map">Az útvonalat a(z) %1$s kapja.</string>
<string name="action_line_now">Azonnal megtörténik.</string>
<string name="action_line_settings">Megnyitja a beállítást; te módosítod.</string>
<string name="action_line_automation">Lefuttatja az automatizálásodat (Tasker, ha nincs más alkalmazás megadva).</string>
<string name="action_line_open">Megnyitja.</string>
<string name="assist_recogniser_failed">A telefon beszédfelismerője leállt. Próbálja újra, vagy válassza a LLeMbast a Beállítások › Hangbevitel alatt.</string>
<string name="assistant_listens">Hallgatás indítása az asszisztens megnyitásakor</string>
<string name="voice_input">Hangbevitel</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Az asszisztens és a csevegés mikrofonja használja. LLeMbasszal az asszisztens kis késéssel mutatja a szavakat, és egy szünet elküldi őket, a csevegés pedig akkor írja le őket, amikor abbahagyja; a telefon felismerőjével beszéd közben jelennek meg.</string>
<string name="share_sending">Küldés az LLeMbas-nak…</string>
<string name="share_default_prompt">Nézze meg ezt.</string>
<string name="share_ask_hint">Mit kezdjen vele a LLeMbas? (nem kötelező)</string>
<string name="widget_hint">Kérdezz bármit</string>
<string name="widget_speak">Beszéd</string>
<string name="widget_description">Kérdezz hanggal vagy szöveggel, vagy folytasd az asszisztens legutóbbi csevegését. A fiókodból semmit sem mutat.</string>
<string name="shortcut_last">Utolsó csevegés</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<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>
<string name="card_allow_always">Consenti sempre questo</string>
<string name="card_allow_always">Consenti sempre</string>
<string name="card_deny">Nega</string>
<string name="card_deny_reason">Nega e spiega perché</string>
<string name="plan_approve_edit">Approva, continua in Modifica</string>
<string name="plan_approve_manual">Approva, continua in Manuale</string>
<string name="card_reason">Perché no? (facoltativo)</string>
<string name="card_recommended">consigliato</string>
<string name="card_answer">La tua risposta</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Spiega cosa c’è sul mio schermo.</string>
<string name="assist_continue">Continua l’ultima chat</string>
<string name="assist_help">Tenga premuto il tasto di accensione per aprire l’assistente sopra qualsiasi app, oppure usi il riquadro delle Impostazioni rapide.</string>
<string name="assist_no_wake_word">Non c’è una parola di attivazione: su Android standard, l’ascolto di una tale parola è riservato all’assistente integrato nel telefono.</string>
<string name="assist_connecting">Connessione…</string>
<string name="assist_offline">%1$s non è raggiungibile</string>
<string name="assist_no_model">Nessun modello</string>
@@ -390,6 +421,127 @@
<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_conversation">In conversazione</string>
<string name="assist_conversation_line">Ascolto di nuovo dopo ogni risposta. Di’ «basta» per finire.</string>
<string name="assist_conversation_end">Termina</string>
<string name="assist_stop_words">basta|stop|è tutto|fine|ciao|arrivederci|grazie è tutto|annulla|smetti</string>
<string name="assistant_conversation">Continuare una conversazione a voce</string>
<string name="assistant_conversation_line">Dopo aver letto ad alta voce una risposta a voce, l’assistente ascolta di nuovo, finché non dici «basta», tocchi Termina o non dici nulla per qualche secondo. Funziona con le cuffie.</string>
<string name="assist_wake_word_hint">Nessuna parola di attivazione, a meno che tu non la voglia: Impostazioni › Assistente › Parola di attivazione attiva quella di LLeMbas, su questo telefono.</string>
<string name="channel_wake">Parola di attivazione</string>
<string name="wake_word">Parola di attivazione</string>
<string name="wake_word_listen">Ascolta una parola di attivazione</string>
<string name="wake_word_line">Disattivata per impostazione predefinita. Di’ la frase e l’assistente si apre in ascolto, sopra l’app sullo schermo.</string>
<string name="wake_word_unavailable">Non in questa build. La build F-Droid non ha un motore per la parola di attivazione, perché F-Droid compila ogni libreria dal sorgente; la build di llembas.eu ce l’ha.</string>
<string name="wake_phrase_line">Quello che dici, poi una breve pausa: conta quando smetti di parlare. In inglese, qualunque sia la lingua dell’app: il motore conosce solo il parlato inglese.</string>
<string name="wake_greeting">Saluto</string>
<string name="wake_name">Nome</string>
<string name="wake_name_google_line">Risponderà anche un telefono o un altoparlante Google nelle vicinanze.</string>
<string name="wake_sensitivity">Sensibilità</string>
<string name="wake_sensitivity_low">Bassa</string>
<string name="wake_sensitivity_low_line">È quella che si attiva per errore meno spesso. Potresti dover dire la frase più chiaramente, o due volte.</string>
<string name="wake_sensitivity_normal">Normale</string>
<string name="wake_sensitivity_normal_line">L’impostazione propria del motore.</string>
<string name="wake_sensitivity_high">Alta</string>
<string name="wake_sensitivity_high_line">Ti sente più facilmente, anche da più lontano. Si attiva per errore più spesso.</string>
<string name="wake_test">Prova la parola di attivazione</string>
<string name="wake_test_line">Per dieci secondi mostra se la tua frase viene sentita, senza aprire l’assistente.</string>
<string name="wake_test_say">Di’ «%1$s» adesso, poi fai una pausa…</string>
<string name="wake_test_heard">Sentita</string>
<string name="wake_test_missed">Non sentita in dieci secondi. Prova più vicino al telefono, in un momento più silenzioso o con una sensibilità più alta.</string>
<string name="wake_test_off">Attiva prima la parola di attivazione.</string>
<string name="wake_screen_only">Solo a schermo acceso</string>
<string name="wake_screen_only_line">Disattivato: ascolta anche a schermo spento, con più consumo di batteria.</string>
<string name="wake_battery">Lascialo funzionare in background</string>
<string name="wake_battery_line">Alcuni telefoni (Samsung, Xiaomi, Huawei, OnePlus e altri) fermano le app in background per risparmiare batteria, e con loro la parola di attivazione. Escludi qui LLeMbas dall’ottimizzazione della batteria; dontkillmyapp.com spiega le impostazioni del tuo telefono.</string>
<string name="wake_word_privacy">Niente lascia il telefono prima della parola. Il suono del microfono va solo al motore della parola di attivazione sul telefono e non viene conservato; la notifica resta visibile finché ascolta. Le frasi sono in inglese; il motore è sherpa-onnx (open source).</string>
<string name="wake_word_cost">Consuma batteria: il microfono resta acceso e il processore del telefono esamina ogni istante di suono, senza il chip a basso consumo usato dall’assistente integrato. Si mette in pausa con il risparmio energetico, mentre l’assistente è aperto e, se non lo cambi, a schermo spento. Dopo un riavvio, tocca la sua notifica per riavviarlo.</string>
<string name="wake_listening_for">In ascolto di «%1$s»</string>
<string name="wake_off">La parola di attivazione non è in ascolto</string>
<string name="wake_tap_to_start">Tocca per riavviarla. Se Android lo chiede, consenti il microfono.</string>
<string name="wake_starting">Avvio della parola di attivazione…</string>
<string name="wake_paused_silent">La parola di attivazione non sente nulla: un’altra app sta usando il microfono, o il microfono del telefono è disattivato</string>
<string name="wake_failed_no_engine">La parola di attivazione non funziona: questa build non ha un motore</string>
<string name="wake_failed_model">La parola di attivazione non funziona: non è stato possibile estrarre il suo modello su questo telefono</string>
<string name="wake_failed_engine">La parola di attivazione non funziona: il motore non si è avviato</string>
<string name="wake_failed_microphone">La parola di attivazione non funziona: il microfono non si è avviato</string>
<string name="wake_failed_line">Non è in ascolto. Riprova da sola.</string>
<string name="wake_notification_line">Niente lascia il telefono finché non lo dici.</string>
<string name="wake_paused_screen">Parola di attivazione in pausa: schermo spento</string>
<string name="wake_paused_battery">Parola di attivazione in pausa: risparmio energetico attivo</string>
<string name="wake_paused_assistant">Parola di attivazione in pausa mentre l’assistente è aperto</string>
<string name="wake_paused_microphone">Parola di attivazione in pausa: LLeMbas non ha il permesso di usare il microfono</string>
<string name="wake_stop">Smetti di ascoltare</string>
<string name="wake_heard">Ti ho sentito. Tocca per chiedere.</string>
<string name="channel_wake_heard">Parola di attivazione sentita</string>
<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>
<string name="assist_notifications_prompt">Riassumi le mie notifiche: cosa richiede la mia attenzione?</string>
<string name="assist_notifications_phrases">le mie notifiche|mie notifiche</string>
<string name="notification_summaries">Riepiloghi delle notifiche</string>
<string name="notification_summaries_switch">Lascia che l’assistente legga le mie notifiche quando lo chiedo</string>
<string name="notification_summaries_line">Chiedi «riassumi le mie notifiche» o tocca il pulsante nell’assistente.</string>
<string name="notification_summaries_unavailable">Non in questa build. Leggere le notifiche richiede la build «notifications» di LLeMbas, perché Google Play Protect blocca l’installazione di un’app esterna al Play Store in grado di leggerle. È la stessa app con la stessa firma: nella pagina della release, il file che termina in -notifications.apk si installa sopra questa.</string>
<string name="update_notifications_manual">Questa è la build «notifications»: installa l’aggiornamento dalla pagina della release, il file che termina in -notifications.apk.</string>
<string name="notification_access">Accesso alle notifiche</string>
<string name="notification_access_on">Concesso. L’interruttore di Android è nelle impostazioni di sistema.</string>
<string name="notification_access_off">Non ancora concesso. Tocca per aprire l’interruttore di Android per LLeMbas.</string>
<string name="notification_summaries_privacy">Disattivato per impostazione predefinita. Quando lo chiedi, il testo delle notifiche presenti ora sul telefono (app, titolo, testo) va con quella sola domanda alla tua istanza e al suo modello. Prima non si legge nulla, l’app non conserva nulla e a telefono bloccato non si legge nulla. L’accesso alle notifiche di Android permette a un’app di vedere ogni notifica: concederlo e revocarlo spetta a te.</string>
<string name="nav_app">App di navigazione</string>
<string name="nav_app_auto">Quella installata</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Chiedi ogni volta</string>
<string name="nav_app_not_installed">Non installata</string>
<string name="osmand_info">Chiedi il percorso a OsmAnd</string>
<string name="osmand_info_line">Permette «aggiungi una tappa» e la ricerca nelle vicinanze anche con un percorso impostato in OsmAnd: LLeMbas chiede a OsmAnd dove sei e dove va il percorso. Prima consenti LLeMbas in OsmAnd (app collegate, con posizione); OsmAnd ti avvisa se non è consentito.</string>
<string name="phone_actions_line">Un modello può offrirsi di fare cose su questo telefono: impostare una sveglia, aggiungere un evento, preparare un messaggio, avviare un percorso. Non succede nulla finché non tocchi Fallo sulla sua scheda, e mai a telefono bloccato. Google Maps avvia un percorso con alcune tappe ma non può aggiungerne a un percorso in corso né essere fermato; OsmAnd sì.</string>
<string name="action_card_title">Farlo sul tuo telefono?</string>
<string name="action_do">Fallo</string>
<string name="action_running">In corso…</string>
<string name="action_unlock">Sblocca prima il telefono, poi tocca Fallo.</string>
<string name="action_failed">Non ha funzionato: %1$s</string>
<string name="nav_app_pick">Con quale app di mappe?</string>
<string name="action_google_add_stop">Google Maps non può aggiungere una tappa a un percorso in corso: riavvia il percorso passando per la tappa.</string>
<string name="action_google_no_stop">Non si può dire a Google Maps di fermarsi: termina il percorso lì.</string>
<string name="action_line_clock">Lo imposta l’app Orologio.</string>
<string name="action_line_calendar">Il calendario si apre con l’evento compilato; lo salvi tu.</string>
<string name="action_line_draft">Apre una bozza; la invii tu.</string>
<string name="action_line_dial">Il tastierino si apre con il numero; la chiamata la fai tu.</string>
<string name="action_line_map">Il percorso va a %1$s.</string>
<string name="action_line_now">Avviene subito.</string>
<string name="action_line_settings">Apre l’impostazione; la cambi tu.</string>
<string name="action_line_automation">Esegue la tua automazione (Tasker se non è indicata un’altra app).</string>
<string name="action_line_open">Lo apre.</string>
<string name="assist_recogniser_failed">Il riconoscimento vocale del telefono si è fermato. Riprovi, oppure scelga LLeMbas in Impostazioni › Input vocale.</string>
<string name="assistant_listens">Inizia ad ascoltare all’apertura dell’assistente</string>
<string name="voice_input">Input vocale</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">La usano l’assistente e il microfono di una chat. Con LLeMbas l’assistente mostra le parole con un attimo di ritardo e una pausa le invia, e una chat le scrive quando si ferma; con il riconoscimento del telefono appaiono mentre parla.</string>
<string name="share_sending">Invio a LLeMbas…</string>
<string name="share_default_prompt">Dai un\'occhiata a questo.</string>
<string name="share_ask_hint">Cosa deve farne LLeMbas? (facoltativo)</string>
<string name="widget_hint">Chiedi qualsiasi cosa</string>
<string name="widget_speak">Parla</string>
<string name="widget_description">Chiedi a voce o per iscritto, o continua l’ultima chat dell’assistente. Non mostra nulla del tuo account.</string>
<string name="shortcut_last">Ultima chat</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12 (moria). Do not edit. -->
<resources>
<color name="token_bg">#FF0B0D10</color>
<color name="token_surface">#FF11151A</color>
<color name="token_surface_raised">#FF171C22</color>
<color name="token_border">#FF26303A</color>
<color name="token_ink">#FFE2E8EC</color>
<color name="token_ink_muted">#FFA6B2BC</color>
<color name="token_accent">#FF8FD8E8</color>
<color name="token_accent_ink">#FF061418</color>
<color name="token_accent_soft">#1F8FD8E8</color>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<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>
<string name="card_allow_always">Zawsze na to zezwalaj</string>
<string name="card_allow_always">Zawsze zezwalaj</string>
<string name="card_deny">Odrzuć</string>
<string name="card_deny_reason">Odrzuć i powiedz dlaczego</string>
<string name="plan_approve_edit">Zatwierdź, kontynuuj w trybie Edytuj</string>
<string name="plan_approve_manual">Zatwierdź, kontynuuj w trybie Ręcznie</string>
<string name="card_reason">Czemu nie? (opcjonalnie)</string>
<string name="card_recommended">zalecane</string>
<string name="card_answer">Twoja odpowiedź</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Wyjaśnij, co jest na moim ekranie.</string>
<string name="assist_continue">Kontynuuj ostatni czat</string>
<string name="assist_help">Przytrzymaj przycisk zasilania, aby otworzyć asystenta nad dowolną aplikacją, albo użyj kafelka w Szybkich ustawieniach.</string>
<string name="assist_no_wake_word">Nie ma słowa wybudzającego: w zwykłym Androidzie nasłuchiwanie go jest zarezerwowane dla asystenta wbudowanego w telefon.</string>
<string name="assist_connecting">Łączenie…</string>
<string name="assist_offline">%1$s jest nieosiągalna</string>
<string name="assist_no_model">Brak modelu</string>
@@ -390,6 +421,127 @@
<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_conversation">Rozmowa</string>
<string name="assist_conversation_line">Po każdej odpowiedzi słucham znowu. Powiedz „stop”, aby zakończyć.</string>
<string name="assist_conversation_end">Zakończ</string>
<string name="assist_stop_words">stop|wystarczy|to wszystko|koniec|do widzenia|dzięki to wszystko|anuluj|przestań</string>
<string name="assistant_conversation">Prowadź rozmowę głosową</string>
<string name="assistant_conversation_line">Po odczytaniu odpowiedzi na głos asystent znów słucha — dopóki nie powiesz „stop”, nie dotkniesz Zakończ albo nie będziesz milczeć przez kilka sekund. Działa ze słuchawkami.</string>
<string name="assist_wake_word_hint">Bez słowa aktywującego, chyba że chcesz: Ustawienia › Asystent › Słowo aktywujące włącza własne słowo LLeMbas, na tym telefonie.</string>
<string name="channel_wake">Słowo aktywujące</string>
<string name="wake_word">Słowo aktywujące</string>
<string name="wake_word_listen">Nasłuchuj słowa aktywującego</string>
<string name="wake_word_line">Domyślnie wyłączone. Powiedz frazę, a asystent otworzy się i zacznie słuchać, nad aplikacją na ekranie.</string>
<string name="wake_word_unavailable">Nie w tej wersji. Wersja z F-Droid nie ma silnika słowa aktywującego, bo F-Droid buduje każdą bibliotekę ze źródeł; wersja z llembas.eu go ma.</string>
<string name="wake_phrase_line">To, co mówisz, a potem krótka pauza: liczy się, gdy zamilkniesz. Po angielsku, niezależnie od języka aplikacji: silnik zna tylko mowę angielską.</string>
<string name="wake_greeting">Powitanie</string>
<string name="wake_name">Imię</string>
<string name="wake_name_google_line">Odpowie też telefon lub głośnik Google w pobliżu.</string>
<string name="wake_sensitivity">Czułość</string>
<string name="wake_sensitivity_low">Niska</string>
<string name="wake_sensitivity_low_line">Najrzadziej uruchamia się przez pomyłkę. Być może trzeba będzie powiedzieć frazę wyraźniej albo dwa razy.</string>
<string name="wake_sensitivity_normal">Normalna</string>
<string name="wake_sensitivity_normal_line">Własne ustawienie silnika.</string>
<string name="wake_sensitivity_high">Wysoka</string>
<string name="wake_sensitivity_high_line">Słyszy Cię najłatwiej, także z większej odległości. Częściej uruchamia się przez pomyłkę.</string>
<string name="wake_test">Wypróbuj słowo aktywujące</string>
<string name="wake_test_line">Przez dziesięć sekund pokazuje, czy Twoja fraza jest słyszana, bez otwierania asystenta.</string>
<string name="wake_test_say">Powiedz teraz „%1$s” i zrób pauzę…</string>
<string name="wake_test_heard">Usłyszano</string>
<string name="wake_test_missed">Nie usłyszano w ciągu dziesięciu sekund. Spróbuj bliżej telefonu, w cichszej chwili albo z wyższą czułością.</string>
<string name="wake_test_off">Najpierw włącz słowo aktywujące.</string>
<string name="wake_screen_only">Tylko przy włączonym ekranie</string>
<string name="wake_screen_only_line">Wyłączone: słucha także przy wyłączonym ekranie, kosztem baterii.</string>
<string name="wake_battery">Pozwól działać w tle</string>
<string name="wake_battery_line">Niektóre telefony (Samsung, Xiaomi, Huawei, OnePlus i inne) zatrzymują aplikacje w tle, by oszczędzać baterię, a z nimi słowo aktywujące. Wyłącz tu LLeMbas z optymalizacji baterii; dontkillmyapp.com wyjaśnia ustawienia Twojego telefonu.</string>
<string name="wake_word_privacy">Nic nie opuszcza telefonu przed słowem. Dźwięk z mikrofonu trafia tylko do silnika słowa aktywującego w telefonie i nie jest zapisywany; powiadomienie jest widoczne przez cały czas nasłuchiwania. Frazy są po angielsku; silnik to sherpa-onnx (open source).</string>
<string name="wake_word_cost">Zużywa baterię: mikrofon pozostaje włączony, a procesor telefonu sprawdza każdą chwilę dźwięku, bez energooszczędnego układu, którego używa wbudowany asystent. Wstrzymuje się w trybie oszczędzania baterii, gdy asystent jest otwarty, i — jeśli tego nie zmienisz — przy wyłączonym ekranie. Po ponownym uruchomieniu dotknij jego powiadomienia, by znów zaczął.</string>
<string name="wake_listening_for">Nasłuchuje „%1$s”</string>
<string name="wake_off">Słowo aktywujące nie nasłuchuje</string>
<string name="wake_tap_to_start">Dotknij, aby uruchomić je ponownie. Jeśli Android zapyta, zezwól na mikrofon.</string>
<string name="wake_starting">Uruchamianie słowa aktywującego…</string>
<string name="wake_paused_silent">Słowo aktywujące nic nie słyszy: inna aplikacja używa mikrofonu albo mikrofon telefonu jest wyłączony</string>
<string name="wake_failed_no_engine">Słowo aktywujące nie działa: ta wersja nie ma silnika</string>
<string name="wake_failed_model">Słowo aktywujące nie działa: nie udało się rozpakować jego modelu na tym telefonie</string>
<string name="wake_failed_engine">Słowo aktywujące nie działa: silnik się nie uruchomił</string>
<string name="wake_failed_microphone">Słowo aktywujące nie działa: mikrofon się nie uruchomił</string>
<string name="wake_failed_line">Nie nasłuchuje. Spróbuje ponownie samo.</string>
<string name="wake_notification_line">Nic nie opuszcza telefonu, dopóki tego nie powiesz.</string>
<string name="wake_paused_screen">Słowo aktywujące wstrzymane: ekran jest wyłączony</string>
<string name="wake_paused_battery">Słowo aktywujące wstrzymane: oszczędzanie baterii jest włączone</string>
<string name="wake_paused_assistant">Słowo aktywujące wstrzymane, gdy asystent jest otwarty</string>
<string name="wake_paused_microphone">Słowo aktywujące wstrzymane: LLeMbas nie ma zgody na używanie mikrofonu</string>
<string name="wake_stop">Przestań słuchać</string>
<string name="wake_heard">Słyszę. Dotknij, aby zapytać.</string>
<string name="channel_wake_heard">Usłyszano słowo aktywujące</string>
<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>
<string name="assist_notifications_prompt">Podsumuj moje powiadomienia: co wymaga mojej uwagi?</string>
<string name="assist_notifications_phrases">moje powiadomienia|moich powiadomień|moje notyfikacje</string>
<string name="notification_summaries">Podsumowania powiadomień</string>
<string name="notification_summaries_switch">Pozwól asystentowi czytać moje powiadomienia, gdy poproszę</string>
<string name="notification_summaries_line">Poproś „podsumuj moje powiadomienia” albo dotknij przycisku w asystencie.</string>
<string name="notification_summaries_unavailable">Nie w tej wersji. Czytanie powiadomień wymaga wersji „notifications” LLeMbas, bo Google Play Protect blokuje instalację aplikacji spoza Sklepu Play, która potrafi je czytać. To ta sama aplikacja z tym samym podpisem: na stronie wydania plik kończący się na -notifications.apk instaluje się na tę.</string>
<string name="update_notifications_manual">To jest wersja „notifications”: zainstaluj aktualizację ze strony wydania, plik kończący się na -notifications.apk.</string>
<string name="notification_access">Dostęp do powiadomień</string>
<string name="notification_access_on">Przyznany. Przełącznik Androida jest w ustawieniach systemu.</string>
<string name="notification_access_off">Jeszcze nie przyznany. Dotknij, aby otworzyć przełącznik Androida dla LLeMbas.</string>
<string name="notification_summaries_privacy">Domyślnie wyłączone. Gdy poprosisz, tekst powiadomień, które są teraz na telefonie (aplikacja, tytuł, treść), trafi z tym jednym pytaniem do Twojej instancji i jej modelu. Wcześniej nic nie jest czytane, aplikacja niczego nie zachowuje i nic nie jest czytane przy zablokowanym telefonie. Dostęp do powiadomień w Androidzie pozwala aplikacji widzieć każde powiadomienie, więc to Ty decydujesz, czy go dać i odebrać.</string>
<string name="nav_app">Aplikacja nawigacyjna</string>
<string name="nav_app_auto">Ta, która jest zainstalowana</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Pytaj za każdym razem</string>
<string name="nav_app_not_installed">Nie zainstalowano</string>
<string name="osmand_info">Pytaj OsmAnd o trasę</string>
<string name="osmand_info_line">Pozwala „dodać przystanek” i szukać w pobliżu także przy trasie ustawionej w samym OsmAnd: LLeMbas pyta OsmAnd, gdzie jesteś i dokąd prowadzi trasa. Najpierw zezwól LLeMbas w OsmAnd (połączone aplikacje, z lokalizacją); OsmAnd poinformuje, jeśli nie ma zgody.</string>
<string name="phone_actions_line">Model może zaproponować zrobienie czegoś na tym telefonie — ustawienie budzika, dodanie wydarzenia, szkic wiadomości, start trasy. Nic się nie dzieje, dopóki nie dotkniesz Zrób to na jego karcie, i nigdy przy zablokowanym telefonie. Mapy Google uruchomią trasę z kilkoma przystankami, ale nie dodadzą przystanku do trwającej trasy ani nie dadzą się zatrzymać; OsmAnd potrafi.</string>
<string name="action_card_title">Zrobić to na telefonie?</string>
<string name="action_do">Zrób to</string>
<string name="action_running">Robię to…</string>
<string name="action_unlock">Najpierw odblokuj telefon, potem dotknij Zrób to.</string>
<string name="action_failed">Nie udało się: %1$s</string>
<string name="nav_app_pick">W której aplikacji map?</string>
<string name="action_google_add_stop">Mapy Google nie dodadzą przystanku do trwającej trasy: uruchomią trasę od nowa, przez przystanek.</string>
<string name="action_google_no_stop">Map Google nie da się zatrzymać z zewnątrz: zakończ trasę w nich.</string>
<string name="action_line_clock">Ustawi to aplikacja Zegar.</string>
<string name="action_line_calendar">Kalendarz otworzy się z wypełnionym wydarzeniem; Ty je zapiszesz.</string>
<string name="action_line_draft">Otwiera szkic; wysyłasz go sam.</string>
<string name="action_line_dial">Otworzy się wybieranie z numerem; połączenie rozpoczniesz Ty.</string>
<string name="action_line_map">Trasę przejmie %1$s.</string>
<string name="action_line_now">Dzieje się od razu.</string>
<string name="action_line_settings">Otwiera ustawienie; Ty je zmieniasz.</string>
<string name="action_line_automation">Uruchamia Twoją automatyzację (Tasker, chyba że podano inną aplikację).</string>
<string name="action_line_open">Otwiera to.</string>
<string name="assist_recogniser_failed">Rozpoznawanie mowy w telefonie przestało działać. Spróbuj ponownie albo wybierz LLeMbas w Ustawienia › Wprowadzanie głosowe.</string>
<string name="assistant_listens">Zacznij słuchać po otwarciu asystenta</string>
<string name="voice_input">Wprowadzanie głosowe</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Używa go asystent i mikrofon w czacie. Z LLeMbas asystent pokazuje słowa z lekkim opóźnieniem, a pauza je wysyła, czat zapisuje je, gdy przestaniesz; z rozpoznawaniem telefonu pojawiają się w trakcie mówienia.</string>
<string name="share_sending">Wysyłanie do LLeMbas…</string>
<string name="share_default_prompt">Zobacz to.</string>
<string name="share_ask_hint">Co LLeMbas ma z tym zrobić? (opcjonalnie)</string>
<string name="widget_hint">Zapytaj o cokolwiek</string>
<string name="widget_speak">Mów</string>
<string name="widget_description">Pytaj głosem lub tekstem albo kontynuuj ostatni czat asystenta. Nie pokazuje niczego z Twojego konta.</string>
<string name="shortcut_last">Ostatni czat</string>
</resources>
+159 -2
View File
@@ -244,11 +244,43 @@
<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>
<string name="card_allow_always">Toto vždy povoliť</string>
<string name="card_allow_always">Vždy povoliť</string>
<string name="card_deny">Odmietnuť</string>
<string name="card_deny_reason">Odmietnuť a povedať prečo</string>
<string name="plan_approve_edit">Schváliť, pokračovať v režime Upraviť</string>
<string name="plan_approve_manual">Schváliť, pokračovať v režime Ručne</string>
<string name="card_reason">Prečo nie? (nepovinné)</string>
<string name="card_recommended">odporúčané</string>
<string name="card_answer">Vaša odpoveď</string>
@@ -377,7 +409,6 @@
<string name="assist_quick_explain_prompt">Vysvetli, čo je na mojej obrazovke.</string>
<string name="assist_continue">Pokračovať v poslednej konverzácii</string>
<string name="assist_help">Podržaním tlačidla napájania otvoríte asistenta nad ľubovoľnou aplikáciou; alebo použite dlaždicu v Rýchlych nastaveniach.</string>
<string name="assist_no_wake_word">Budiace slovo nie je: na bežnom Androide je počúvanie budiaceho slova vyhradené asistentovi zabudovanému v telefóne.</string>
<string name="assist_connecting">Pripája sa…</string>
<string name="assist_offline">%1$s je nedostupná</string>
<string name="assist_no_model">Žiadny model</string>
@@ -390,6 +421,127 @@
<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_conversation">Rozhovor</string>
<string name="assist_conversation_line">Po každej odpovedi znova počúvam. Povedzte „stop“ a skončíme.</string>
<string name="assist_conversation_end">Ukončiť</string>
<string name="assist_stop_words">stop|dosť|to je všetko|koniec|dovidenia|ďakujem to je všetko|zrušiť|prestaň</string>
<string name="assistant_conversation">Pokračovať v hovorenom rozhovore</string>
<string name="assistant_conversation_line">Po prečítaní hovorenej odpovede asistent znova počúva — kým nepoviete „stop“, neťuknete na Ukončiť alebo pár sekúnd nič nepoviete. Funguje aj so slúchadlami.</string>
<string name="assist_wake_word_hint">Budiace slovo len ak chcete: Nastavenia › Asistent › Budiace slovo zapne vlastné slovo LLeMbas, priamo v tomto telefóne.</string>
<string name="channel_wake">Budiace slovo</string>
<string name="wake_word">Budiace slovo</string>
<string name="wake_word_listen">Počúvať budiace slovo</string>
<string name="wake_word_line">Predvolene vypnuté. Povedzte frázu a asistent sa otvorí a počúva, nad akoukoľvek aplikáciou na obrazovke.</string>
<string name="wake_word_unavailable">V tomto zostavení nie je. Zostavenie pre F-Droid nemá modul pre budiace slovo, pretože F-Droid zostavuje každú knižnicu zo zdrojov; zostavenie z llembas.eu ho má.</string>
<string name="wake_phrase_line">Toto hovoríte, potom krátka pauza: platí, až keď zmĺknete. Po anglicky, nech je aplikácia v akomkoľvek jazyku: modul pozná len anglickú reč.</string>
<string name="wake_greeting">Oslovenie</string>
<string name="wake_name">Meno</string>
<string name="wake_name_google_line">Ozve sa aj telefón alebo reproduktor Google nablízku.</string>
<string name="wake_sensitivity">Citlivosť</string>
<string name="wake_sensitivity_low">Nízka</string>
<string name="wake_sensitivity_low_line">Omylom sa spustí najmenej často. Frázu možno budete musieť povedať zreteľnejšie alebo dvakrát.</string>
<string name="wake_sensitivity_normal">Normálna</string>
<string name="wake_sensitivity_normal_line">Vlastné nastavenie modulu.</string>
<string name="wake_sensitivity_high">Vysoká</string>
<string name="wake_sensitivity_high_line">Počuje vás najľahšie, aj z väčšej diaľky. Omylom sa spustí častejšie.</string>
<string name="wake_test">Vyskúšať budiace slovo</string>
<string name="wake_test_line">Desať sekúnd ukazuje, či vašu frázu počuť, bez otvorenia asistenta.</string>
<string name="wake_test_say">Teraz povedzte „%1$s“ a urobte pauzu…</string>
<string name="wake_test_heard">Počul som ju</string>
<string name="wake_test_missed">Za desať sekúnd som ju nepočul. Skúste to bližšie k telefónu, v tichšej chvíli alebo s vyššou citlivosťou.</string>
<string name="wake_test_off">Najprv zapnite budiace slovo.</string>
<string name="wake_screen_only">Len pri zapnutej obrazovke</string>
<string name="wake_screen_only_line">Vypnuté: počúva aj pri zhasnutej obrazovke, za cenu vyššej spotreby batérie.</string>
<string name="wake_battery">Nechať bežať na pozadí</string>
<string name="wake_battery_line">Niektoré telefóny (Samsung, Xiaomi, Huawei, OnePlus a ďalšie) kvôli batérii zastavujú aplikácie na pozadí, a s nimi aj budiace slovo. Tu vyjmite LLeMbas z optimalizácie batérie; dontkillmyapp.com vysvetľuje nastavenia vášho telefónu.</string>
<string name="wake_word_privacy">Pred vyslovením slova nič neopustí telefón. Zvuk z mikrofónu ide len do modulu pre budiace slovo v telefóne a neukladá sa; počas celého počúvania je viditeľné oznámenie. Frázy sú anglické; modul je sherpa-onnx (open source).</string>
<string name="wake_word_cost">Stojí to batériu: mikrofón zostáva zapnutý a procesor telefónu kontroluje každý okamih zvuku, bez úsporného čipu, ktorý používa vstavaný asistent. Pozastaví sa v úspornom režime, keď je asistent otvorený, a ak to nezmeníte, aj pri zhasnutej obrazovke. Po reštarte ho znova spustíte ťuknutím na oznámenie.</string>
<string name="wake_listening_for">Počúvam frázu „%1$s“</string>
<string name="wake_off">Budiace slovo nepočúva</string>
<string name="wake_tap_to_start">Ťuknutím ho znova spustíte. Ak sa Android opýta, povoľte mikrofón.</string>
<string name="wake_starting">Budiace slovo sa spúšťa…</string>
<string name="wake_paused_silent">Budiace slovo nič nepočuje: mikrofón používa iná aplikácia alebo je v telefóne vypnutý</string>
<string name="wake_failed_no_engine">Budiace slovo nefunguje: toto zostavenie nemá modul</string>
<string name="wake_failed_model">Budiace slovo nefunguje: jeho model sa v tomto telefóne nepodarilo rozbaliť</string>
<string name="wake_failed_engine">Budiace slovo nefunguje: modul sa nespustil</string>
<string name="wake_failed_microphone">Budiace slovo nefunguje: mikrofón sa nespustil</string>
<string name="wake_failed_line">Nepočúva. Skúsi to znova samo.</string>
<string name="wake_notification_line">Kým ju nepoviete, nič neopustí telefón.</string>
<string name="wake_paused_screen">Budiace slovo pozastavené: obrazovka je zhasnutá</string>
<string name="wake_paused_battery">Budiace slovo pozastavené: je zapnutý úsporný režim</string>
<string name="wake_paused_assistant">Budiace slovo je pozastavené, kým je asistent otvorený</string>
<string name="wake_paused_microphone">Budiace slovo pozastavené: LLeMbas nemá povolený mikrofón</string>
<string name="wake_stop">Prestať počúvať</string>
<string name="wake_heard">Počul som vás. Ťuknite a pýtajte sa.</string>
<string name="channel_wake_heard">Budiace slovo zaznelo</string>
<string name="wake_heard_line">LLeMbas sa dokáže sám otvoriť nad inými aplikáciami len ako aplikácia digitálneho asistenta v telefóne.</string>
<string name="wake_not_assistant">LLeMbas nie je aplikáciou digitálneho asistenta</string>
<string name="wake_not_assistant_line">Budiace slovo preto nemôže otvoriť asistenta nad inými aplikáciami: dostanete oznámenie, na ktoré ťuknete. Ak chcete otvárať hlasom kdekoľvek, ťuknite sem a vyberte LLeMbas ako aplikáciu digitálneho asistenta.</string>
<string name="wake_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>
<string name="assist_notifications_prompt">Zhrň moje oznámenia: čo potrebuje moju pozornosť?</string>
<string name="assist_notifications_phrases">moje oznámenia|mojich oznámení|moje notifikácie</string>
<string name="notification_summaries">Zhrnutia oznámení</string>
<string name="notification_summaries_switch">Dovoliť asistentovi čítať moje oznámenia, keď o to požiadam</string>
<string name="notification_summaries_line">Povedzte „zhrň moje oznámenia“, alebo ťuknite na tlačidlo v asistentovi.</string>
<string name="notification_summaries_unavailable">V tomto zostavení nie je. Čítanie oznámení vyžaduje zostavenie LLeMbas „notifications“, pretože Google Play Protect blokuje inštaláciu aplikácie mimo Obchodu Play, ktorá ich dokáže čítať. Je to tá istá aplikácia s tým istým podpisom: na stránke vydania sa súbor končiaci na -notifications.apk nainštaluje cez túto.</string>
<string name="update_notifications_manual">Toto je zostavenie „notifications“: aktualizáciu nainštalujte zo stránky vydania, súbor končiaci na -notifications.apk.</string>
<string name="notification_access">Prístup k oznámeniam</string>
<string name="notification_access_on">Udelený. Prepínač Androidu je v systémových nastaveniach.</string>
<string name="notification_access_off">Zatiaľ neudelený. Ťuknutím otvoríte prepínač Androidu pre LLeMbas.</string>
<string name="notification_summaries_privacy">Predvolene vypnuté. Keď požiadate, text oznámení, ktoré sú v telefóne práve teraz (aplikácia, názov, text), pôjde s touto jedinou otázkou na vašu inštanciu a jej model. Predtým sa nič nečíta, aplikácia si nič neponechá a pri zamknutom telefóne sa nečíta nič. Prístup k oznámeniam v Androide dovolí aplikácii vidieť každé oznámenie, preto je na vás, či ho dáte a znova vezmete.</string>
<string name="nav_app">Navigačná aplikácia</string>
<string name="nav_app_auto">Tá, ktorá je nainštalovaná</string>
<string name="nav_app_google">Mapy Google</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Zakaždým sa opýtať</string>
<string name="nav_app_not_installed">Nie je nainštalovaná</string>
<string name="osmand_info">Pýtať sa OsmAnd na trasu</string>
<string name="osmand_info_line">Umožní „pridať zastávku“ a hľadanie v okolí aj pri trase nastavenej priamo v OsmAnd: LLeMbas sa OsmAnd opýta, kde ste a kam trasa vedie. Najprv LLeMbas povoľte v OsmAnd (pripojené aplikácie, s polohou); OsmAnd dá vedieť, ak povolené nie je.</string>
<string name="phone_actions_line">Model môže ponúknuť, že v telefóne niečo urobí — nastaví budík, pridá udalosť, pripraví správu, spustí trasu. Nič sa nestane, kým neťuknete na Urobiť na jeho karte, a nikdy pri zamknutom telefóne. Mapy Google spustia trasu s niekoľkými zastávkami, ale do bežiacej trasy zastávku nepridajú ani sa nedajú zastaviť; OsmAnd to vie.</string>
<string name="action_card_title">Urobiť to v telefóne?</string>
<string name="action_do">Urobiť</string>
<string name="action_running">Robím to…</string>
<string name="action_unlock">Najprv odomknite telefón, potom ťuknite na Urobiť.</string>
<string name="action_failed">Nepodarilo sa: %1$s</string>
<string name="nav_app_pick">V ktorej mapovej aplikácii?</string>
<string name="action_google_add_stop">Mapy Google nepridajú zastávku do bežiacej trasy: spustia trasu znova, cez zastávku.</string>
<string name="action_google_no_stop">Mapy Google sa nedajú zastaviť zvonka: trasu ukončite v nich.</string>
<string name="action_line_clock">Nastaví to aplikácia Hodiny.</string>
<string name="action_line_calendar">Otvorí sa kalendár s vyplnenou udalosťou; uložíte ju vy.</string>
<string name="action_line_draft">Otvorí koncept; odošlete ho sami.</string>
<string name="action_line_dial">Otvorí sa vytáčanie s číslom; hovor začnete vy.</string>
<string name="action_line_map">Trasu prevezme %1$s.</string>
<string name="action_line_now">Stane sa hneď.</string>
<string name="action_line_settings">Otvorí nastavenie; zmeníte ho vy.</string>
<string name="action_line_automation">Spustí vašu automatizáciu (Tasker, ak nie je uvedená iná aplikácia).</string>
<string name="action_line_open">Otvorí to.</string>
<string name="assist_recogniser_failed">Rozpoznávanie reči v telefóne sa zastavilo. Skúste to znova alebo zvoľte LLeMbas v Nastaveniach › Hlasový vstup.</string>
<string name="assistant_listens">Začať počúvať, keď sa asistent otvorí</string>
<string name="voice_input">Hlasový vstup</string>
@@ -401,4 +553,9 @@
<string name="voice_input_hint">Používa ho asistent aj mikrofón v konverzácii. S LLeMbas asistent ukazuje slová s malým oneskorením a pauza ich odošle, konverzácia ich zapíše, keď prestanete; s rozpoznávaním v telefóne sa objavujú, ako hovoríte.</string>
<string name="share_sending">Odosiela sa do LLeMbas…</string>
<string name="share_default_prompt">Pozrite sa na toto.</string>
<string name="share_ask_hint">Čo s tým má LLeMbas urobiť? (nepovinné)</string>
<string name="widget_hint">Opýtajte sa na čokoľvek</string>
<string name="widget_speak">Hovoriť</string>
<string name="widget_description">Pýtajte sa hlasom alebo textom, alebo pokračujte v poslednej konverzácii s asistentom. Neukazuje nič z vášho účtu.</string>
<string name="shortcut_last">Posledný chat</string>
</resources>
+159 -2
View File
@@ -245,11 +245,43 @@
<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>
<string name="card_allow_always">Always allow this</string>
<string name="card_allow_always">Always allow</string>
<string name="card_deny">Deny</string>
<string name="card_deny_reason">Deny, and say why</string>
<string name="plan_approve_edit">Approve, continue in Edit</string>
<string name="plan_approve_manual">Approve, continue in Manual</string>
<string name="card_reason">Why not? (optional)</string>
<string name="card_recommended">recommended</string>
<string name="card_answer">Your answer</string>
@@ -379,7 +411,6 @@
<string name="assist_quick_explain_prompt">Explain what is on my screen.</string>
<string name="assist_continue">Continue the last chat</string>
<string name="assist_help">Hold the power button to open the assistant over any app, or use the Quick Settings tile.</string>
<string name="assist_no_wake_word">There is no wake word: on stock Android, listening for one is kept for the assistant built into the phone.</string>
<string name="assist_connecting">Connecting…</string>
<string name="assist_offline">%1$s cannot be reached</string>
<string name="assist_no_model">No model</string>
@@ -392,6 +423,127 @@
<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_conversation">In conversation</string>
<string name="assist_conversation_line">I listen again after each answer. Say “stop” to end.</string>
<string name="assist_conversation_end">End</string>
<string name="assist_stop_words">stop|that\'s all|that is all|that\'s it|goodbye|bye|enough|end|thank you that\'s all|cancel</string>
<string name="assistant_conversation">Keep a spoken conversation going</string>
<string name="assistant_conversation_line">After a spoken answer is read aloud, the assistant listens again — until you say “stop”, tap End, or say nothing for a few seconds. Works with a headset.</string>
<string name="assist_wake_word_hint">No wake word unless you want one: Settings › Assistant › Wake word turns on LLeMbas\'s own, on this phone.</string>
<string name="channel_wake">Wake word</string>
<string name="wake_word">Wake word</string>
<string name="wake_word_listen">Listen for a wake word</string>
<string name="wake_word_line">Off by default. Say the phrase and the assistant opens, listening, over whatever app is on screen.</string>
<string name="wake_word_unavailable">Not in this build. The F-Droid build has no wake-word engine, because F-Droid builds every library from source; the build from llembas.eu has one.</string>
<string name="wake_phrase_line">What you say, then a short pause: it counts once you stop. In English, whatever language the app is in: the engine only knows English speech.</string>
<string name="wake_greeting">Greeting</string>
<string name="wake_name">Name</string>
<string name="wake_name_google_line">A Google phone or speaker nearby will answer too.</string>
<string name="wake_sensitivity">Sensitivity</string>
<string name="wake_sensitivity_low">Low</string>
<string name="wake_sensitivity_low_line">Starts by mistake least often. You may have to say the phrase more clearly, or twice.</string>
<string name="wake_sensitivity_normal">Normal</string>
<string name="wake_sensitivity_normal_line">The engine\'s own setting.</string>
<string name="wake_sensitivity_high">High</string>
<string name="wake_sensitivity_high_line">Hears you most easily, also from further away. Starts by mistake more often.</string>
<string name="wake_test">Test the wake word</string>
<string name="wake_test_line">For ten seconds, shows whether your phrase is heard, without opening the assistant.</string>
<string name="wake_test_say">Say “%1$s” now, then pause…</string>
<string name="wake_test_heard">Heard it</string>
<string name="wake_test_missed">Not heard in ten seconds. Try closer to the phone, in a quieter moment, or a higher sensitivity.</string>
<string name="wake_test_off">Turn the wake word on first.</string>
<string name="wake_screen_only">Only while the screen is on</string>
<string name="wake_screen_only_line">Off: it listens with the screen off too, at more cost to the battery.</string>
<string name="wake_battery">Let it run in the background</string>
<string name="wake_battery_line">Some phones (Samsung, Xiaomi, Huawei, OnePlus and others) stop background apps to save battery, and the wake word with them. Exempt LLeMbas from battery optimisation here; dontkillmyapp.com explains your phone\'s own settings.</string>
<string name="wake_word_privacy">Nothing leaves the phone before the word. The microphone\'s sound goes only to the wake-word engine on the phone and is not kept, and the notification stays up the whole time it listens. The phrases are English; the engine is sherpa-onnx (open source).</string>
<string name="wake_word_cost">It costs battery: the microphone stays on and the phone\'s processor checks every moment of sound, without the low-power chip the built-in assistant uses. It pauses in battery saver, while the assistant is open and, unless you change it, with the screen off. After a restart, tap its notification to start it again.</string>
<string name="wake_listening_for">Listening for “%1$s”</string>
<string name="wake_off">The wake word is not listening</string>
<string name="wake_tap_to_start">Tap to start it again. If Android asks, allow the microphone.</string>
<string name="wake_starting">Starting the wake word…</string>
<string name="wake_paused_silent">Wake word hears nothing: another app has the microphone, or the phone\'s microphone is switched off</string>
<string name="wake_failed_no_engine">Wake word is not working: this build has no engine</string>
<string name="wake_failed_model">Wake word is not working: its model could not be unpacked on this phone</string>
<string name="wake_failed_engine">Wake word is not working: the engine did not start</string>
<string name="wake_failed_microphone">Wake word is not working: the microphone did not start</string>
<string name="wake_failed_line">It is not listening. It tries again by itself.</string>
<string name="wake_notification_line">Nothing leaves the phone until you say it.</string>
<string name="wake_paused_screen">Wake word paused: the screen is off</string>
<string name="wake_paused_battery">Wake word paused: battery saver is on</string>
<string name="wake_paused_assistant">Wake word paused while the assistant is open</string>
<string name="wake_paused_microphone">Wake word paused: LLeMbas is not allowed to use the microphone</string>
<string name="wake_stop">Stop listening</string>
<string name="wake_heard">Heard you. Tap to ask.</string>
<string name="channel_wake_heard">Wake word heard</string>
<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>
<string name="assist_notifications_prompt">Summarise my notifications: what needs my attention?</string>
<string name="assist_notifications_phrases">my notifications|notifications on my phone</string>
<string name="notification_summaries">Notification summaries</string>
<string name="notification_summaries_switch">Let the assistant read my notifications when I ask</string>
<string name="notification_summaries_line">Ask “summarise my notifications”, or tap the chip in the assistant.</string>
<string name="notification_summaries_unavailable">Not in this build. Reading notifications needs the “notifications” build of LLeMbas, because Google Play Protect blocks installing an app from outside the Play Store that can read them. It is the same app with the same signature: on the release page, the file ending in -notifications.apk installs over this one.</string>
<string name="update_notifications_manual">This is the “notifications” build: install the update from its release page, the file ending in -notifications.apk.</string>
<string name="notification_access">Notification access</string>
<string name="notification_access_on">Given. Android\'s switch for it is in the system\'s settings.</string>
<string name="notification_access_off">Not given yet. Tap to open Android\'s switch for LLeMbas.</string>
<string name="notification_summaries_privacy">Off by default. When you ask, the text of the notifications on your phone right now (app, title, text) goes with that one question to your instance and its model. Nothing is read before you ask, the app keeps none of it, and none is read while the phone is locked. Android\'s notification access lets an app see every notification, so it is yours to give and to take back.</string>
<string name="nav_app">Navigation app</string>
<string name="nav_app_auto">Whichever is installed</string>
<string name="nav_app_google">Google Maps</string>
<string name="nav_app_osmand">OsmAnd</string>
<string name="nav_app_ask">Ask each time</string>
<string name="nav_app_not_installed">Not installed</string>
<string name="osmand_info">Ask OsmAnd about the route</string>
<string name="osmand_info_line">Lets “add a stop” and searches near you work with a route you set up in OsmAnd itself: LLeMbas asks OsmAnd where you are and where the route goes. Allow LLeMbas in OsmAnd first (its connected apps, with Location); OsmAnd tells you if it is not allowed.</string>
<string name="phone_actions_line">A model may offer to do things on this phone — set an alarm, add an event, draft a message, start a route. Nothing happens until you tap Do it on its card, and never while the phone is locked. Google Maps starts a route with a few stops but cannot add one to a route already running or be told to stop; OsmAnd can.</string>
<string name="action_card_title">Do this on your phone?</string>
<string name="action_do">Do it</string>
<string name="action_running">Doing it…</string>
<string name="action_unlock">Unlock the phone first, then tap Do it.</string>
<string name="action_failed">It did not work: %1$s</string>
<string name="nav_app_pick">With which map app?</string>
<string name="action_google_add_stop">Google Maps cannot add a stop to a running route: it starts the route again, through the stop.</string>
<string name="action_google_no_stop">Google Maps cannot be told to stop: end the route there.</string>
<string name="action_line_clock">The clock app sets it.</string>
<string name="action_line_calendar">The calendar opens with the event filled in; you save it.</string>
<string name="action_line_draft">Opens a draft; you send it yourself.</string>
<string name="action_line_dial">The dialler opens with the number; you place the call.</string>
<string name="action_line_map">%1$s takes the route.</string>
<string name="action_line_now">Happens at once.</string>
<string name="action_line_settings">Opens the setting; you change it.</string>
<string name="action_line_automation">Runs your automation (Tasker unless another app is named).</string>
<string name="action_line_open">Opens it.</string>
<string name="assist_recogniser_failed">The phone\'s speech recogniser stopped. Try again, or choose LLeMbas under Settings › Voice input.</string>
<string name="assistant_listens">Start listening when the assistant opens</string>
<string name="voice_input">Voice input</string>
@@ -403,4 +555,9 @@
<string name="voice_input_hint">Used by the assistant and by the microphone in a chat. With LLeMbas the assistant shows the words a moment behind you and a pause sends them, and a chat writes them down when you stop; with the phone\'s recogniser they appear as you speak.</string>
<string name="share_sending">Sending to LLeMbas…</string>
<string name="share_default_prompt">Have a look at this.</string>
<string name="share_ask_hint">What should LLeMbas do with it? (optional)</string>
<string name="widget_hint">Ask anything</string>
<string name="widget_speak">Speak</string>
<string name="widget_description">Ask by voice or text, or carry on the last assistant chat. Shows nothing from your account.</string>
<string name="shortcut_last">Last chat</string>
</resources>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at v2.0.0-beta.12 (shire). Do not edit. -->
<resources>
<color name="token_bg">#FFF1EAD6</color>
<color name="token_surface">#FFF8F3E5</color>
<color name="token_surface_raised">#FFFCF9F0</color>
<color name="token_border">#FFCBBF9D</color>
<color name="token_ink">#FF1F2418</color>
<color name="token_ink_muted">#FF474D3B</color>
<color name="token_accent">#FF285F3C</color>
<color name="token_accent_ink">#FFF8F3E5</color>
<color name="token_accent_soft">#1A285F3C</color>
</resources>
-13
View File
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:shortcutId="ask"
android:enabled="true"
android:icon="@mipmap/ic_launcher"
android:shortcutShortLabel="@string/tile_ask">
<intent
android:action="android.intent.action.ASSIST"
android:targetPackage="eu.llembas.android"
android:targetClass="eu.llembas.android.assist.AssistActivity" />
</shortcut>
</shortcuts>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/widget_description"
android:initialLayout="@layout/widget_ask"
android:minWidth="250dp"
android:minHeight="40dp"
android:minResizeWidth="180dp"
android:previewLayout="@layout/widget_ask"
android:resizeMode="horizontal"
android:targetCellWidth="4"
android:targetCellHeight="1"
android:updatePeriodMillis="0"
android:widgetCategory="home_screen" />
+18
View File
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- The `notifications` build: the full build plus the notification listener (notification
summaries, opt-in). Only this build declares it; the standard builds do not, because
Google Play Protect blocks installing an app from outside the Play Store that does. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Read only when a question asks for them (notify/NotificationAccess.kt). -->
<service
android:name="eu.llembas.android.notify.LembasNotificationListener"
android:exported="true"
android:label="@string/notification_summaries"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
@@ -0,0 +1,88 @@
package eu.llembas.android.notify
import android.app.KeyguardManager
import android.app.Notification
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.Settings
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.core.app.NotificationManagerCompat
/**
* Notification summaries on request: the assistant reads the notifications on the phone only when
* the person asks it to ("summarise my notifications", or the sheet's chip), and sends their text
* with that one question. Off by default, twice over: Android's own notification-access switch
* (which only the person can turn on, in the system's settings) and Settings › Assistant's.
*
* The listener keeps nothing: it is how Android lets an app read the notifications that are up
* right now ([activeNotifications]), and nothing is read until a question asks for it. Never over
* the lock screen ([NotificationAccess.read] returns nothing while the phone is locked).
*
* Only the `notifications` build has this class and declares the service; the standard builds
* have a [NotificationAccess] that can do nothing.
*/
class LembasNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
super.onListenerConnected()
current = this
}
override fun onListenerDisconnected() {
if (current === this) current = null
super.onListenerDisconnected()
}
companion object {
@Volatile
var current: LembasNotificationListener? = null
private set
}
}
/** Reading the phone's notifications, in the build that can. */
object NotificationAccess {
const val AVAILABLE = true
/** Whether the person gave LLeMbas notification access in the system's settings. */
fun granted(context: Context): Boolean = context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
/** The system's page for this app's notification access (the detail page where Android has one). */
fun settingsIntent(context: Context): Intent? = if (Build.VERSION.SDK_INT >= 30) {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS)
.putExtra(Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME, ComponentName(context, LembasNotificationListener::class.java).flattenToString())
} else {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** The notifications up now, newest first -- or none, when locked or not allowed. */
fun read(context: Context): List<Notice> {
if (context.getSystemService(KeyguardManager::class.java).isKeyguardLocked) return emptyList()
val listener = LembasNotificationListener.current ?: return emptyList()
val shown = runCatching { listener.activeNotifications }.getOrNull().orEmpty()
return shown
.filter { it.packageName != context.packageName && !it.isOngoing && it.notification.flags and Notification.FLAG_GROUP_SUMMARY == 0 }
.sortedByDescending { it.postTime }
.mapNotNull { notice(context, it) }
.take(MAX_NOTICES)
}
private fun notice(context: Context, sbn: StatusBarNotification): Notice? {
val extras = sbn.notification.extras
val title = extras.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val lines = extras.getCharSequenceArray(Notification.EXTRA_TEXT_LINES)?.joinToString("\n").orEmpty()
val text = (extras.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras.getCharSequence(Notification.EXTRA_TEXT))?.toString()
?.ifBlank { null } ?: lines
if (title.isBlank() && text.isBlank()) return null
val app = runCatching {
val pm = context.packageManager
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
}.getOrDefault(sbn.packageName)
return Notice(app, title, text.take(MAX_TEXT), sbn.postTime)
}
private const val MAX_NOTICES = 40
private const val MAX_TEXT = 600
}
@@ -0,0 +1,21 @@
package eu.llembas.android.notify
import android.content.Context
import android.content.Intent
/**
* The standard builds cannot read the phone's notifications: they declare no notification
* listener at all, because Google Play Protect blocks installing an app from outside the Play
* Store that does. Notification summaries are in the `notifications` build -- the same app, the
* same signature, with the listener -- and Settings says so. Everything else about them is the
* same code in both, which here simply never has anything to read.
*/
object NotificationAccess {
const val AVAILABLE = false
fun granted(context: Context): Boolean = false
fun settingsIntent(context: Context): Intent? = null
fun read(context: Context): List<Notice> = emptyList()
}
@@ -7,9 +7,13 @@ import eu.llembas.android.assist.AssistController
import eu.llembas.android.assist.AssistTurn
import eu.llembas.android.assist.Recorder
import eu.llembas.android.assist.SheetStop
import eu.llembas.android.assist.isStopPhrase
import eu.llembas.android.assist.settle
import eu.llembas.android.assist.usePhoneRecognizer
import eu.llembas.android.auth.Prefs
import eu.llembas.android.notify.Notice
import eu.llembas.android.notify.NotificationReader
import eu.llembas.android.share.shareMessage
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -87,4 +91,39 @@ class AssistTest {
assertFalse(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = true))
assertTrue(usePhoneRecognizer(Prefs.VOICE_LEMBAS, phoneHas = true, instanceStt = false))
}
@Test
fun aShareSendsTheRequestBeforeWhatWasShared() {
assertEquals("Summarise it.\n\n---\n\nhttps://example.org", shareMessage(" Summarise it. ", "https://example.org\n", "Have a look."))
assertEquals("Have a look.\n\n---\n\nSome text", shareMessage("", "Some text", "Have a look."))
// Files only: the request alone, the files go as attachments.
assertEquals("Have a look.", shareMessage(" ", "", "Have a look."))
}
@Test
fun stopEndsAConversationButAQuestionAboutStoppingDoesNot() {
val phrases = "stop|that's all|goodbye".split("|")
assertTrue(isStopPhrase("Stop.", phrases))
assertTrue(isStopPhrase("OK, that’s all, thanks", phrases))
assertTrue(isStopPhrase("stop please", phrases))
assertFalse(isStopPhrase("How do I stop the kettle from whistling in the morning?", phrases))
assertFalse(isStopPhrase("", phrases))
assertTrue(isStopPhrase("Ďakujem, to je všetko", listOf("ďakujem to je všetko")))
}
@Test
fun notificationsGoAsShortBlocksAndOnlyWhenAskedFor() {
val now = 10 * 3_600_000L
val text = NotificationReader.asText(
listOf(
Notice("Mail", "Bilbo", "The party is on Thursday.", now - 5 * 60_000),
Notice("Weather", "Rain", "", now - 3 * 3_600_000),
),
now,
)
assertEquals("[Mail · 5m ago] Bilbo\nThe party is on Thursday.\n\n[Weather · 3h ago] Rain", text)
val phrases = listOf("my notifications")
assertTrue(NotificationReader.asksAbout("Anything urgent in My Notifications?", phrases))
assertFalse(NotificationReader.asksAbout("How do notifications work on Android?", phrases))
}
}
@@ -3,6 +3,8 @@ package eu.llembas.android
import eu.llembas.android.api.APP_API
import eu.llembas.android.api.AgentSubagents
import eu.llembas.android.api.AskFrame
import eu.llembas.android.api.AttachmentEnvelope
import eu.llembas.android.api.CardItem
import eu.llembas.android.api.CardSubagent
import eu.llembas.android.api.Chat
import eu.llembas.android.api.ChatPage
@@ -17,21 +19,30 @@ import eu.llembas.android.api.LiveReply
import eu.llembas.android.api.Me
import eu.llembas.android.api.MemoryEnvelope
import eu.llembas.android.api.MemoryList
import eu.llembas.android.api.Mentions
import eu.llembas.android.api.Message
import eu.llembas.android.api.Metrics
import eu.llembas.android.api.ModelList
import eu.llembas.android.api.Plan
import eu.llembas.android.api.ProgressWords
import eu.llembas.android.api.SearchResults
import eu.llembas.android.api.StatusFrame
import eu.llembas.android.api.SteeredFrame
import eu.llembas.android.api.StepsFrame
import eu.llembas.android.api.SubagentTranscript
import eu.llembas.android.api.Tail
import eu.llembas.android.api.TitleFrame
import eu.llembas.android.api.ToolCall
import eu.llembas.android.api.TreeFrame
import eu.llembas.android.api.TreeView
import eu.llembas.android.api.callDuration
import eu.llembas.android.api.ending
import eu.llembas.android.api.progressText
import eu.llembas.android.api.state
import eu.llembas.android.api.took
import eu.llembas.android.ui.chat.ChatState
import eu.llembas.android.ui.chat.approvalTexts
import eu.llembas.android.ui.chat.offersAlways
import eu.llembas.android.ui.chat.offersTeam
import kotlinx.serialization.KSerializer
import kotlinx.serialization.builtins.ListSerializer
@@ -42,6 +53,7 @@ import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Locale
/**
* The server's contract, as pinned in `contract/` by `scripts/fetch-contract.py`: every shape
@@ -189,7 +201,18 @@ class ContractTest {
val call = reply.steps[2].calls.single()
assertEquals("shell", call.block.kind)
assertEquals("bake --slow", call.block.title)
assertEquals(listOf("exit 0"), call.block.chips)
// Spec 3.7.0: an exit code is a fact only when it is not 0; the call says its state, how
// long it took and what its tool is called.
assertTrue(call.block.chips.isEmpty())
assertEquals("done", call.block.state)
assertEquals("done", call.state())
assertEquals(2412L, call.ms)
assertEquals("2.4s", call.block.duration)
assertEquals("2.4s", call.took())
assertEquals("2.4s", callDuration("done", call.ms))
assertEquals("Bash", call.block.label)
assertNull(reply.end)
assertNull(reply.ending())
assertEquals("and add honey", reply.steps[3].messages.single().text)
assertEquals(40, reply.metrics!!.completionTokens)
}
@@ -315,6 +338,67 @@ class ContractTest {
assertEquals("Waybread", read("event_done", DoneFrame.serializer()).chat.title)
}
@Test
fun aStoredReplySaysHowItEnded() {
val words = ProgressWords { key, args ->
mapOf("stopped_reason" to "Stopped: %s", "stopped_reason_person" to "by you", "failed" to "Failed: %s")[key]?.format(*args)
}
val stopped = read("message_stopped", Message.serializer())
assertEquals("person", stopped.end!!.reason)
// The app's own words, from the phase and the reason, say what the server's line says.
assertEquals(stopped.end!!.text, progressText(stopped.ending()!!, words, 0, Locale.ROOT))
val failed = read("message_failed", Message.serializer())
assertEquals("failed", failed.ending()!!.phase)
assertEquals(failed.end!!.text, progressText(failed.ending()!!, words, 0, Locale.ROOT))
}
@Test
fun alwaysAllowIsOfferedOnlyWhereTheRequestOffersIt() {
val cards = read("event_ask", AskFrame.serializer()).cards
val approvals = cards.filter { it.kind == "approval" }
assertEquals(listOf(true, true), approvals.map { offersAlways(it) })
val once = approvals[0].copy(items = approvals[0].items.map { it.copy(always = false) })
assertFalse(offersAlways(once))
// An older server says nothing of it, and offered it always.
assertTrue(LembasJson.decodeFromString(CardItem.serializer(), """{"key":"0","kind":"approval"}""").always)
}
@Test
fun whatAtOffersAndWhatAttachingItGives() {
val items = read("mentions", Mentions.serializer()).items
assertEquals(listOf("file", "attachment"), items.map { it.kind })
assertEquals("/home/frodo/bread.md", items[0].path)
assertEquals("att1", items[1].id)
assertEquals("https://example.org/waybread", read("mentions_url", Mentions.serializer()).items.single().url)
assertEquals("bread.md", read("attachment_from", AttachmentEnvelope.serializer()).attachment.name)
}
@Test
fun aRunningCallComesWithTheTail() {
// The tail's `calls` are not drawn yet (the steps are); the frame must still parse.
assertEquals("Done. *Wrap", read("event_tail", Tail.serializer()).text)
}
@Test
fun doneIsTheEndAndTheChatsNameMayFollow() {
// A new chat's first reply: saved and done at once, under the name made from the prompt.
val pending = read("event_done_title_pending", DoneFrame.serializer())
assertTrue(pending.chat.titlePending)
assertEquals("How is lembas made?", pending.chat.title)
assertFalse(read("event_done", DoneFrame.serializer()).chat.titlePending)
var live = LiveReply("msg2").apply("done", text("event_done_title_pending"))
assertNotNull(live.finished)
assertEquals("How is lembas made?", live.title)
assertFalse(live.closed)
// Then, if a model names it before the stream closes, one `title` frame: only the name changes.
val finished = live.finished
live = live.apply("title", text("event_title"))
assertEquals("Waybread", live.title)
assertEquals(finished, live.finished)
assertEquals("chat1", read("event_title", TitleFrame.serializer()).chat.id)
assertTrue(live.apply("close", text("event_close")).closed)
}
@Test
fun aWholeStreamBuildsAReply() {
var live = LiveReply("msg2")
@@ -0,0 +1,202 @@
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
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
import eu.llembas.android.api.progressText
import eu.llembas.android.api.shortTitle
import eu.llembas.android.api.state
import eu.llembas.android.ui.chat.planApproval
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.util.Locale
/**
* One display in every client (harness spec 3.7.0, `display.md`), as far as the phone draws it:
* a finished call's duration, the line that stays on a reply that was stopped or failed, a title
* that was cut, and numbers in the phone's format. The values are the spec's own examples; once
* the server's copy of the spec carries `conformance/display.json` it is pinned as
* `contract/harness_display.json` and its `duration` and `end` cases run here too.
*/
class DisplayTest {
private val english: ProgressWords by lazy {
val xml = File("src/main/res/values/strings.xml").readText()
val strings = Regex("""<string name="progress_([a-z_]+)"[^>]*>(.*?)</string>""").findAll(xml)
.associate { it.groupValues[1] to it.groupValues[2].replace("\\'", "'").replace("&amp;", "&") }
val keys = mapOf("stopped_reason_person" to "stopped_person", "stopped_reason_steps" to "stopped_steps", "stopped_reason_budget" to "stopped_budget")
ProgressWords { key, args -> strings[keys[key] ?: key]?.let { String.format(Locale.ROOT, it, *args) } }
}
@Test
fun aFinishedCallSaysHowLongItTook() {
assertEquals("0.4s", callDuration("done", 412))
assertEquals("8.4s", callDuration("done", 8_449))
assertEquals("59.9s", callDuration("failed", 59_940))
// What would round to sixty seconds is a minute, never "60.0s".
assertEquals("1m 00s", callDuration("done", 59_960))
assertEquals("1m 00s", callDuration("done", 60_000))
assertEquals("1m 05s", callDuration("done", 65_000))
assertEquals("2h 03m", callDuration("done", 7_380_000))
assertEquals("1.2s", callDuration("failed", 1_200))
// Never a running call, never a denied one, and none where the time was not kept.
assertNull(callDuration("denied", 3))
assertNull(callDuration("running", 5_000))
assertNull(callDuration("done", null))
// A duration is not a locale number: a decimal point on every phone.
val phone = Locale.getDefault()
try {
Locale.setDefault(Locale.forLanguageTag("sk-SK"))
assertEquals("8.4s", callDuration("done", 8_449))
} finally {
Locale.setDefault(phone)
}
}
@Test
fun aCallIsInOneOfFourStates() {
assertEquals("done", ToolCall(name = "bash", status = "ok").state())
assertEquals("running", ToolCall(name = "bash", status = "running").state())
assertEquals("failed", ToolCall(name = "bash", status = "error").state())
assertEquals("failed", ToolCall(name = "bash", status = "ok", error = "exit 2").state())
assertEquals("denied", ToolCall(name = "bash", status = "denied").state())
// The call's time comes with the call (the link's `ms`), and an older server sends none.
assertEquals(8_449L, LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"bash","status":"ok","ms":8449}""").ms)
assertNull(LembasJson.decodeFromString(ToolCall.serializer(), """{"name":"bash","status":"ok"}""").ms)
}
private fun reply(stopped: Boolean = false, error: String? = null, progress: Progress? = null) =
Message(id = "m", role = "assistant", stopped = stopped, error = error, progress = progress)
private fun line(message: Message): String? = message.ending()?.let { progressText(it, english, 0, Locale.ROOT) }
@Test
fun aReplyThatDidNotFinishKeepsItsLine() {
assertEquals("Stopped: by you", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "person"))))
assertEquals("Stopped: step limit", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "steps"))))
assertEquals("Stopped: budget", line(reply(stopped = true, progress = Progress(phase = "stopped", reason = "budget"))))
// A stored row knows that it was stopped, not why: the line without a reason.
assertEquals("Stopped", line(reply(stopped = true)))
// An error: its first line is the reason, and the line is the spec's, not the raw text.
assertEquals("Failed: 502 Bad Gateway", line(reply(error = "502 Bad Gateway\n at upstream")))
// A reply that finished shows nothing; nor does a user's message, or one that is only queued.
assertNull(reply().ending())
assertNull(Message(id = "u", role = "user", stopped = true).ending())
assertNull(reply(progress = Progress(phase = "queued", ahead = 1)).ending())
}
@Test
fun theStreamsReasonStaysWithTheFinishedReply() {
val stopped = """{"text": "", "progress": {"phase": "stopped", "since": 1767323045000, "reason": "person"}}"""
val done = LembasJson.parseToJsonElement(File("../contract/event_done.json").readText()).jsonObject
fun doneWith(change: (MutableMap<String, kotlinx.serialization.json.JsonElement>) -> Unit): String {
val message = done.getValue("message").jsonObject.toMutableMap().also(change)
return JsonObject(done + ("message" to JsonObject(message))).toString()
}
// Stopped by the person: the stream said why, the row only that it was stopped.
val live = LiveReply("msg2").apply("status", stopped)
val ended = live.apply("done", doneWith { it["stopped"] = kotlinx.serialization.json.JsonPrimitive(true) })
assertNull(ended.progress)
assertEquals("Stopped: by you", line(ended.finished!!))
// A reply that finished after all keeps nothing of an earlier stop.
assertNull(live.apply("done", doneWith { }).finished!!.ending())
// The phase moved on before the end (a retry that then worked): no end is remembered.
val moved = live.apply("status", """{"text": "Writing", "progress": {"phase": "writing", "since": 1}}""")
assertNull(moved.end)
assertTrue(done.getValue("message").jsonObject["error"] is JsonNull)
}
@Test
fun aTitleThatWasCutSaysSo() {
assertEquals("bake --slow", shortTitle(" bake --slow\n--and more "))
assertNull(shortTitle(" "))
assertNull(shortTitle(null))
val long = "x".repeat(81)
assertEquals("x".repeat(79) + "…", shortTitle(long))
assertEquals("x".repeat(80), shortTitle("x".repeat(80)))
// Counted in code points: a character outside the basic plane is one, and is never split.
val leaves = "\uD83C\uDF43".repeat(81)
assertEquals("\uD83C\uDF43".repeat(79) + "…", shortTitle(leaves))
val running = Progress(phase = "running_tool", since = 0, tool = "bash", what = long)
assertEquals("Running bash: ${"x".repeat(79)}… · 0s", progressLine(running, english, 0, Locale.ROOT))
}
@Test
fun numbersAreInThePhonesFormat() {
val reading = Progress(phase = "reading_prompt", since = 0, done = 12_480, total = 32_000)
assertEquals("Reading the prompt: 12480 / 32000 tokens (39%)", progressText(reading, english, 0, Locale.ROOT))
assertEquals("Reading the prompt: 12,480 / 32,000 tokens (39%)", progressText(reading, english, 0, Locale.US))
assertEquals("Reading the prompt: 12.480 / 32.000 tokens (39%)", progressText(reading, english, 0, Locale.GERMANY))
assertEquals("Writing: 1.234,5 tok/s", progressText(Progress(phase = "writing", since = 0, rate = 1234.46), english, 0, Locale.GERMANY))
assertEquals("Queued: 1,200 ahead", progressText(Progress(phase = "queued", since = 0, ahead = 1200), english, 0, Locale.US))
assertEquals("12480", localeNumber(12_480, Locale.ROOT))
assertEquals("12.5", localeNumber(12.46, 1, Locale.ROOT))
}
@Test
fun aPlanIsApprovedWithTheModeToContinueIn() {
val choose = CardItem(key = "p0", kind = "plan", modeChoice = true)
assertEquals(mapOf("p0" to listOf("edit")), planApproval(choose, "edit").choices)
assertEquals(mapOf("p0" to listOf("manual")), planApproval(choose, "manual").choices)
assertEquals("allow", planApproval(choose, "manual").verdict)
// A session that may not choose a mode approves the plan alone.
assertTrue(planApproval(CardItem(key = "p0", kind = "plan", modeChoice = false), null).choices.isEmpty())
}
@Test
fun theSpecsOwnCasesOnceTheyArePinned() {
val file = javaClass.classLoader!!.getResource("harness_display.json") ?: return
val cases = LembasJson.parseToJsonElement(file.readText()).jsonObject.getValue("cases").jsonArray.map { it.jsonObject }
for (case in cases) {
val about = case["about"]?.jsonPrimitive?.content
val expect = case.getValue("expect").jsonObject
when (case.getValue("show").jsonPrimitive.content) {
"duration" -> {
val want = expect.getValue("duration").let { if (it is JsonNull) null else it.jsonPrimitive.content }
assertEquals(about, want, callDuration(case.getValue("state").jsonPrimitive.content, case["ms"]?.jsonPrimitive?.long))
}
"end" -> {
val progress = case.getValue("progress").let { if (it is JsonNull) null else LembasJson.decodeFromJsonElement(Progress.serializer(), it) }
val want = expect.getValue("line").let { if (it is JsonNull) null else it.jsonPrimitive.content }
val message = Message(id = "m", role = "assistant", progress = progress)
assertEquals(about, want, message.ending()?.let { progressLine(it, english, case.getValue("now").jsonPrimitive.long, Locale.ROOT) })
}
}
}
}
@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,85 @@
package eu.llembas.android
import eu.llembas.android.ui.TokenKind
import eu.llembas.android.ui.highlights
import eu.llembas.android.ui.tokenize
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class HighlightTest {
/** Each token as its text and kind, for reading a test at a glance. */
private fun read(text: String, language: String): List<Pair<String, TokenKind>> =
tokenize(text, language).map { text.substring(it.start, it.end) to it.kind }
@Test
fun kotlinKeywordsStringsCommentsNumbersAndTypes() {
val got = read("val x: Int = 42 // the answer\nfun f() = \"a \\\" b\"", "kotlin")
assertTrue("val" to TokenKind.Keyword in got)
assertTrue("Int" to TokenKind.Type in got)
assertTrue("42" to TokenKind.Number in got)
assertTrue("// the answer" to TokenKind.Comment in got)
assertTrue("fun" to TokenKind.Keyword in got)
// An escaped quote does not end the string.
assertTrue("\"a \\\" b\"" to TokenKind.Text in got)
}
@Test
fun aBlockCommentRunsAcrossLines() {
val text = "/* one\n two */ int x;"
val got = read(text, "c")
assertEquals("/* one\n two */" to TokenKind.Comment, got.first())
assertTrue("int" to TokenKind.Keyword in got)
}
@Test
fun pythonTripleQuotesAndHashComments() {
val got = read("def f():\n \"\"\"Doc\n string\"\"\"\n return None # nothing", "py")
assertTrue("def" to TokenKind.Keyword in got)
assertTrue("\"\"\"Doc\n string\"\"\"" to TokenKind.Text in got)
assertTrue("None" to TokenKind.Keyword in got)
assertTrue("# nothing" to TokenKind.Comment in got)
}
@Test
fun anUnclosedQuoteColoursOneLineNotTheFile() {
val got = read("echo don't\nls -la", "bash")
val string = got.first { it.second == TokenKind.Text }
assertFalse(string.first.contains('\n'))
}
@Test
fun sqlIgnoresCaseAndShellHasVariables() {
assertTrue("SELECT" to TokenKind.Keyword in read("SELECT * FROM t -- all", "sql"))
assertTrue("-- all" to TokenKind.Comment in read("SELECT * FROM t -- all", "sql"))
assertTrue("\$HOME" to TokenKind.Attribute in read("cd \$HOME", "sh"))
}
@Test
fun markupTagsAttributesAndValues() {
val got = read("<!-- note -->\n<a href=\"x\">don't</a>", "xml")
assertEquals("<!-- note -->" to TokenKind.Comment, got.first())
assertTrue("a" to TokenKind.Tag in got)
assertTrue("href" to TokenKind.Attribute in got)
assertTrue("\"x\"" to TokenKind.Text in got)
// Prose between tags is not a string.
assertFalse(got.any { it.first.startsWith("'") })
}
@Test
fun yamlKeys() {
val got = read("name: lembas\ncount: 3\n# end", "yaml")
assertTrue("name" to TokenKind.Type in got)
assertTrue("3" to TokenKind.Number in got)
assertTrue("# end" to TokenKind.Comment in got)
}
@Test
fun anUnknownLanguageIsPlain() {
assertFalse(highlights("brainfuck"))
assertTrue(tokenize("anything at all", "").isEmpty())
assertTrue(highlights("TypeScript"))
assertTrue(highlights("c++"))
}
}
@@ -0,0 +1,78 @@
package eu.llembas.android
import eu.llembas.android.actions.Args
import eu.llembas.android.actions.NavApp
import eu.llembas.android.actions.NavIntents
import eu.llembas.android.actions.PhoneActions
import eu.llembas.android.actions.Place
import eu.llembas.android.api.AskFrame
import eu.llembas.android.api.CardAnswer
import eu.llembas.android.api.LembasJson
import eu.llembas.android.api.PhoneResult
import eu.llembas.android.ui.chat.phoneFacts
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
class PhoneActionsTest {
private fun args(json: String) = Args(LembasJson.parseToJsonElement(json).jsonObject)
@Test
fun placesAreReadLeniently() {
val a = args("""{"destination": {"name": "Rivendell", "lat": "47.1", "lon": 8.5}, "stops": ["Bree", {"query": "inn"}], "hour": "7"}""")
assertEquals(Place("Rivendell", 47.1, 8.5), a.place("destination"))
assertEquals(listOf(Place(query = "Bree"), Place(query = "inn")), a.places("stops"))
assertEquals(7, a.int("hour"))
assertNull(a.place("missing"))
}
@Test
fun theNavigationAppIsTheOneInstalledOrAsked() {
val both = listOf(NavApp.GoogleMaps, NavApp.OsmAnd)
assertEquals(NavApp.OsmAnd, NavApp.chosen("", listOf(NavApp.OsmAnd)))
// Both installed and nothing chosen: the card asks.
assertNull(NavApp.chosen("", both))
assertEquals(NavApp.GoogleMaps, NavApp.chosen("google", both))
assertNull(NavApp.chosen(NavApp.PREF_ASK, both))
// Chosen but since uninstalled: the one there is.
assertEquals(NavApp.GoogleMaps, NavApp.chosen("osmand", listOf(NavApp.GoogleMaps)))
}
@Test
fun aRouteForOsmAndIsGpxWithItsPointsInOrder() {
val gpx = NavIntents.gpx(listOf(Place("Bree & Co", 1.0, 2.0), Place("Rivendell", 3.0, 4.0)))
assertTrue(gpx.contains("<rtept lat=\"1.0\" lon=\"2.0\"><name>Bree &amp; Co</name></rtept><rtept lat=\"3.0\" lon=\"4.0\">"))
}
@Test
fun clockTimesAndNumbersAreCheckedAgain() {
assertEquals(7 to 5, PhoneActions.clock("07:05"))
assertNull(PhoneActions.clock("24:00"))
assertNull(PhoneActions.clock("7 am"))
// A name the messaging app would have to find is left out: the person picks the contact.
assertEquals(listOf("+421 900 123 456"), PhoneActions.smsNumbers(listOf("+421 900 123 456", "Sam")))
assertTrue(PhoneActions.urlAllowed("HTTPS://example.org"))
assertFalse(PhoneActions.urlAllowed("javascript:alert(1)"))
assertFalse(PhoneActions.urlAllowed("https://"))
}
@Test
fun theCardSaysWhatWillHappenFromTheContract() {
val frame = requireNotNull(javaClass.classLoader!!.getResource("event_ask_phone.json")).readText()
val cards = LembasJson.decodeFromString(AskFrame.serializer(), frame).cards
assertEquals(listOf("phone_action"), cards.map { it.kind }.distinct())
val phones = cards.map { requireNotNull(it.items.single().phone) }
assertEquals("07:00 · mon tue wed thu fri · Work", phoneFacts(phones[0]))
assertEquals("Bakery (48.894, 18.044) · Home (1 Bagshot Row, Hobbiton) · drive", phoneFacts(phones[1]))
assertEquals("Bakery (Bakery, Bywater) · Home (1 Bagshot Row, Hobbiton)", phoneFacts(phones[2]))
assertEquals("", phoneFacts(phones[3]))
// The answer the server reads: {"result": {"status", "message"}}, nothing else.
assertEquals(
"""{"result":{"status":"done","message":"ok"}}""",
LembasJson.encodeToString(CardAnswer.serializer(), CardAnswer(result = PhoneResult("done", "ok"))),
)
}
}
@@ -46,7 +46,7 @@ class ProgressTest {
@Test
fun everyConformanceCase() {
assertEquals(25, cases.size)
assertEquals(26, cases.size)
for (case in cases) {
val progress = LembasJson.decodeFromJsonElement(Progress.serializer(), case.getValue("progress"))
val now = case.getValue("now").jsonPrimitive.long
@@ -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
@@ -1,10 +1,17 @@
package eu.llembas.android
import eu.llembas.android.api.AppBuild
import eu.llembas.android.api.AppRelease
import eu.llembas.android.api.AppsInfo
import eu.llembas.android.api.LembasJson
import eu.llembas.android.assist.AssistController
import eu.llembas.android.assist.Recorder
import eu.llembas.android.update.Latest
import eu.llembas.android.update.LatestFile
import eu.llembas.android.update.Updater
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -17,6 +24,40 @@ class SmallThingsTest {
assertFalse(Updater.newer("0.1.0", "0.2.0"))
}
@Test
fun aBuildUpdatesItselfToItsOwnKindOnly() {
val plain = LembasJson.decodeFromString(Latest.serializer(), """{"version":"1.0.0","url":"https://example.org/a.apk","sha256":"aa"}""")
assertEquals(LatestFile("https://example.org/a.apk", "aa"), plain.fileFor(notificationsBuild = false))
// A release that names no notifications APK: that build installs nothing, rather than lose its listener.
assertNull(plain.fileFor(notificationsBuild = true))
val both = LembasJson.decodeFromString(
Latest.serializer(),
"""{"version":"1.0.0","url":"https://example.org/a.apk","sha256":"aa","notifications":{"url":"https://example.org/a-notifications.apk","sha256":"bb"}}""",
)
assertEquals(LatestFile("https://example.org/a-notifications.apk", "bb"), both.fileFor(notificationsBuild = true))
assertEquals(LatestFile("https://example.org/a.apk", "aa"), both.fileFor(notificationsBuild = false))
}
@Test
fun theInstanceMayNameTheNotificationsBuildOfTheSameRelease() {
val plain = Latest(version = "1.0.0", url = "https://example.org/a.apk", sha256 = "aa")
val build = AppBuild("https://example.org/a-notifications.apk", "bb")
val same = AppRelease(version = "1.0.0", notifications = build)
assertEquals(LatestFile(build.url, build.sha256), plain.fileFor(notificationsBuild = true, recommended = same))
// Another version, no address worth trusting, or nothing known: it installs nothing itself.
assertNull(plain.fileFor(notificationsBuild = true, recommended = same.copy(version = "1.0.1")))
assertNull(plain.fileFor(notificationsBuild = true, recommended = same.copy(notifications = build.copy(url = "http://example.org/a.apk"))))
assertNull(plain.fileFor(notificationsBuild = true, recommended = null))
// The standard build never takes it.
assertEquals(LatestFile("https://example.org/a.apk", "aa"), plain.fileFor(notificationsBuild = false, recommended = same))
val apps = LembasJson.decodeFromString(
AppsInfo.serializer(),
"""{"apps":{"android":{"version":"1.0.0","notifications":{"url":"https://example.org/n.apk","sha256":"cc"},"fdroid":{"url":"https://example.org/f.apk","sha256":"dd"}}}}""",
)
assertEquals("cc", apps.android!!.notifications!!.sha256)
assertEquals("dd", apps.android!!.fdroid!!.sha256)
}
@Test
fun aVoiceReadsNoMarkup() {
val said = AssistController.plain("**Bake** it.\n\n```sh\nbake\n```\nSee [the recipe](https://example.org).")
@@ -0,0 +1,287 @@
package eu.llembas.android
import eu.llembas.android.wake.WakeDetector
import eu.llembas.android.wake.WakeError
import eu.llembas.android.wake.WakeFailure
import eu.llembas.android.wake.WakeListener
import eu.llembas.android.wake.WakeMicrophone
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakePlan
import eu.llembas.android.wake.WakeState
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
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Collections
/**
* The listening loop without a phone: an engine that does not load, a microphone that does not
* start or stops, silence, a pause and a change of phrase -- each must end in a state somebody
* can read, and the engine must never be released under a loop that still feeds it.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class WakeListenerTest {
/** Gives [script] one chunk at a time (true: sound, false: exact silence), then [after]: more sound, or an error code. */
private class Mic(private val script: List<Boolean> = emptyList(), private val after: Int = 0, private val pauseMs: Long = 0) : WakeMicrophone {
@Volatile var closed = false
private var reads = 0
override fun read(into: ShortArray): Int {
if (pauseMs > 0) Thread.sleep(pauseMs)
val sound = script.getOrNull(reads++) ?: if (after < 0) return after else true
into.fill(if (sound) 100 else 0)
return into.size
}
override fun close() {
closed = true
}
}
/** Hears the word on its [hearOn]-th chunk; notes a release that came while it was at work, or work after a release. */
private class Detector(private val hearOn: Int = Int.MAX_VALUE, private val workMs: Long = 0) : WakeDetector {
@Volatile var released = false
@Volatile var misused = false
@Volatile private var busy = false
private var accepts = 0
override fun accept(samples: FloatArray): Boolean {
if (released) misused = true
busy = true
if (workMs > 0) Thread.sleep(workMs)
busy = false
return ++accepts % hearOn == 0
}
override fun release() {
if (busy) misused = true
released = true
}
}
private val assistant = WakePhrases.byId("hey_assistant")
private val plan = WakePlan(assistant, wakeKeywords(assistant), WakePause.None)
private val states: MutableList<WakeState> = Collections.synchronizedList(mutableListOf())
private fun TestScope.listener(engine: (String) -> WakeDetector, microphone: () -> WakeMicrophone, heard: () -> Unit = {}) = WakeListener(
say = { states += it },
engine = engine,
microphone = microphone,
heard = { heard() },
work = StandardTestDispatcher(testScheduler),
)
@Test
fun anEngineThatDoesNotLoadIsShownAndTriedAgain() = runTest {
var tries = 0
var heard = 0
val detector = Detector(hearOn = 3)
val listener = listener(
engine = { if (++tries < 3) error("no such file") else detector },
microphone = { Mic() },
heard = { heard++ },
)
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(listOf(WakeState.Starting, WakeState.Failed(WakeFailure.Engine, "IllegalStateException: no such file")), states.toList())
advanceTimeBy(2_001) // the first wait
assertEquals(2, tries)
advanceTimeBy(5_001) // the second, longer
assertEquals(3, tries)
assertEquals(WakeState.Listening("Hey Assistant"), states.last())
assertEquals(1, heard)
job.cancelAndJoin()
assertTrue(detector.released)
}
@Test
fun aBuildWithoutAnEngineSaysSoOnce() = runTest {
var tries = 0
val listener = listener(engine = {
tries++
throw WakeError(WakeFailure.NoEngine, message = "this build has no wake-word engine")
}, microphone = { Mic() })
val job = launch { listener.follow(MutableStateFlow(plan)) }
advanceTimeBy(3_600_000)
assertEquals(1, tries)
assertEquals(WakeState.Failed(WakeFailure.NoEngine, "this build has no wake-word engine"), states.last())
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatDoesNotStartIsAFailureNotASilentReturn() = runTest {
var opens = 0
val listener = listener(engine = { Detector() }, microphone = {
opens++
throw IllegalStateException("recording did not start")
})
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "IllegalStateException: recording did not start"), states.last())
advanceTimeBy(2_001)
assertEquals(2, opens)
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
val listener = listener(engine = { Detector() }, microphone = {
opens++
throw IllegalStateException("recording did not start")
})
val job = launch { listener.follow(MutableStateFlow(plan)) }
advanceTimeBy(2_001 + 5_001) // two waits gone by: the third would be fifteen seconds
assertEquals(3, opens)
listener.retryNow()
runCurrent()
assertEquals(4, opens)
// And the count of failures starts over: two seconds again, not a minute.
advanceTimeBy(2_001)
assertEquals(5, opens)
job.cancelAndJoin()
}
@Test
fun troubleAfterListeningWellIsNewTroubleNotTheOldOneAgain() = runTest {
var opens = 0
// Each microphone works for forty seconds (a tenth of a second a chunk), then stops.
val listener = listener(engine = { Detector() }, microphone = {
opens++
Mic(script = List(400) { true }, after = -3)
})
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(1, opens)
// Every wait is the first, two seconds, however many times it has happened.
repeat(4) {
advanceTimeBy(2_001)
assertEquals(it + 2, opens)
}
job.cancelAndJoin()
}
@Test
fun aMicrophoneThatStopsIsAFailureAndIsClosed() = runTest {
val mic = Mic(script = listOf(true, true), after = -3)
val listener = listener(engine = { Detector() }, microphone = { mic })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
assertEquals(WakeState.Failed(WakeFailure.Microphone, "the microphone stopped (error -3)"), states.last())
assertTrue(mic.closed)
job.cancelAndJoin()
}
@Test
fun exactSilenceForSecondsIsSaidAndSoIsSoundComingBack() = runTest {
// Six seconds of zeros (a tenth of a second a chunk), then sound; the word on the 70th chunk.
val listener = listener(engine = { Detector(hearOn = 70) }, microphone = { Mic(script = List(60) { false }) })
val job = launch { listener.follow(MutableStateFlow(plan)) }
runCurrent()
val listening = WakeState.Listening("Hey Assistant")
assertEquals(listOf(WakeState.Starting, listening, WakeState.Paused(WakePause.Silent), listening), states.toList())
job.cancelAndJoin()
}
/** With real threads: wait until the listener has said [state]. */
private suspend fun said(now: MutableStateFlow<WakeState>, state: WakeState) = withTimeout(10_000) { now.first { it == state } }
@Test
fun aPauseLetsGoOfTheMicrophoneAndKeepsTheEngine() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val mics = Collections.synchronizedList(mutableListOf<Mic>())
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
engine = { Detector().also { detectors += it } },
microphone = { Mic(pauseMs = 2).also { mics += it } },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
said(now, WakeState.Listening("Hey Assistant"))
plans.value = plan.copy(pause = WakePause.ScreenOff)
said(now, WakeState.Paused(WakePause.ScreenOff))
assertTrue(mics.single().closed)
assertFalse(detectors.single().released)
plans.value = plan
said(now, WakeState.Listening("Hey Assistant"))
assertEquals(1, detectors.size)
assertEquals(2, mics.size)
job.cancelAndJoin()
assertTrue(detectors.single().released)
assertTrue(mics.all { it.closed })
assertFalse(detectors.single().misused)
}
@Test
fun aNewPhraseWaitsForTheOldLoopBeforeItsEngineIsReleased() = runBlocking {
val now = MutableStateFlow<WakeState>(WakeState.Off)
val detectors = Collections.synchronizedList(mutableListOf<Detector>())
val listener = WakeListener(
say = { now.value = it },
// Slow at its work, so a release that did not wait would land in the middle of it.
engine = { Detector(workMs = 30).also { detectors += it } },
microphone = { Mic() },
heard = {},
)
val plans = MutableStateFlow(plan)
val job = launch(Dispatchers.Default) { listener.follow(plans) }
val other = WakePhrases.byId("ok_computer")
repeat(5) { round ->
val phrase = if (round % 2 == 0) other else assistant
said(now, WakeState.Listening(if (round % 2 == 0) assistant.words else other.words))
plans.value = WakePlan(phrase, wakeKeywords(phrase), WakePause.None)
}
said(now, WakeState.Listening(other.words))
job.cancelAndJoin()
assertEquals(6, detectors.size)
assertTrue(detectors.all { it.released })
assertFalse(detectors.any { it.misused })
}
}
@@ -0,0 +1,180 @@
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
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
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
* listens for it, a pause with its reason, a failure with what failed -- and nothing else, ever.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35], qualifiers = "en")
class WakeNotificationTest {
private val app: Application get() = RuntimeEnvironment.getApplication()
private fun title(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TITLE).toString()
private fun line(state: WakeState) = wakeNotification(app, state).extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()
@Test
fun itNamesThePhraseOnlyWhileItListensForIt() {
assertEquals("Listening for “Hey Assistant”", title(WakeState.Listening("Hey Assistant")))
assertEquals("Nothing leaves the phone until you say it.", line(WakeState.Listening("Hey Assistant")))
// A service that has just started knows no phrase yet, and names none.
assertEquals("Starting the wake word…", title(WakeState.Starting))
assertNull(line(WakeState.Starting))
}
@Test
fun aPauseSaysWhy() {
assertEquals("Wake word paused: the screen is off", title(WakeState.Paused(WakePause.ScreenOff)))
assertEquals("Wake word paused: battery saver is on", title(WakeState.Paused(WakePause.BatterySaver)))
assertEquals("Wake word paused while the assistant is open", title(WakeState.Paused(WakePause.Assistant)))
assertEquals("Wake word paused: LLeMbas is not allowed to use the microphone", title(WakeState.Paused(WakePause.NoMicrophone)))
assertEquals(
"Wake word hears nothing: another app has the microphone, or the phone's microphone is switched off",
title(WakeState.Paused(WakePause.Silent)),
)
}
@Test
fun aFailureSaysWhatFailedAndNeverThatItListens() {
val failures = mapOf(
WakeFailure.Engine to "Wake word is not working: the engine did not start",
WakeFailure.Model to "Wake word is not working: its model could not be unpacked on this phone",
WakeFailure.Microphone to "Wake word is not working: the microphone did not start",
)
for ((why, words) in failures) {
val state = WakeState.Failed(why, "IOException: no space left")
assertEquals(words, title(state))
assertEquals("It is not listening. It tries again by itself.", line(state))
assertFalse(title(state).contains("Listening"))
}
assertEquals("Wake word is not working: this build has no engine", title(WakeState.Failed(WakeFailure.NoEngine)))
assertNull(line(WakeState.Failed(WakeFailure.NoEngine)))
assertEquals("The wake word is not listening", wakeTitle(app, WakeState.Off))
}
@Test
fun itShowsNothingOfTheAccountAndCannotBeSwipedAway() {
val notification = wakeNotification(app, WakeState.Listening("Hey Assistant"))
assertEquals(Notification.VISIBILITY_PUBLIC, notification.visibility)
assertEquals(Notification.FLAG_ONGOING_EVENT, notification.flags and Notification.FLAG_ONGOING_EVENT)
assertEquals(1, notification.actions.size)
}
@Test
fun heardButUnableToOpenIsANotificationThatComesUp() {
val heard = wakeHeardNotification(app)
assertEquals("Heard you. Tap to ask.", heard.extras.getCharSequence(Notification.EXTRA_TITLE).toString())
// Its own channel, which may come up over what is on screen; the listening one is quiet.
assertEquals(WakeWordService.CHANNEL_HEARD, heard.channelId)
WakeWordService.channel(app)
val manager = app.getSystemService(NotificationManager::class.java)
assertEquals(NotificationManager.IMPORTANCE_HIGH, manager.getNotificationChannel(WakeWordService.CHANNEL_HEARD).importance)
assertEquals(NotificationManager.IMPORTANCE_LOW, manager.getNotificationChannel(WakeWordService.CHANNEL).importance)
// Fixed words, nothing from the account: it may show on the lock screen. The tap asks.
assertEquals(Notification.VISIBILITY_PUBLIC, heard.visibility)
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)
}
}
@@ -0,0 +1,91 @@
package eu.llembas.android
import android.Manifest
import android.app.Application
import android.app.Notification
import android.app.NotificationManager
import androidx.core.app.NotificationCompat
import eu.llembas.android.wake.AssistPresence
import eu.llembas.android.wake.WakeBootReceiver
import eu.llembas.android.wake.WakePause
import eu.llembas.android.wake.WakeState
import eu.llembas.android.wake.WakeStatus
import eu.llembas.android.wake.WakeWordService
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
/**
* The wake-word service as Android starts it. What a phone showed before: every time the app was
* opened the service was started again and posted "Listening for" the default phrase, whatever
* was chosen and whether or not anything listened.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35], qualifiers = "en")
class WakeServiceTest {
private val app: Application get() = RuntimeEnvironment.getApplication()
private fun title(notification: Notification) = notification.extras.getCharSequence(Notification.EXTRA_TITLE).toString()
@After
fun off() = WakeStatus.set(WakeState.Off)
@Test
fun aStartNeverPostsAPhraseItIsNotListeningFor() {
shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)
val service = Robolectric.buildService(WakeWordService::class.java).create()
// The first start: nothing is known yet, so it says it is starting -- no phrase.
service.startCommand(0, 1)
assertEquals("Starting the wake word…", title(shadowOf(service.get()).lastForegroundNotification))
service.destroy()
}
@Test
fun aStartClearsWhatAnEarlierInstanceLeftBehind() {
shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)
val manager = app.getSystemService(NotificationManager::class.java)
WakeWordService.channel(app)
// "Tap to listen again" from a restart, and a hold of the microphone nobody ended.
manager.notify(WakeBootReceiver.RESUME_ID, NotificationCompat.Builder(app, WakeWordService.CHANNEL).setSmallIcon(R.drawable.ic_notification).build())
AssistPresence.release()
val before = AssistPresence.open.value
AssistPresence.holdFor(600_000)
assertEquals(before + 1, AssistPresence.open.value)
val service = Robolectric.buildService(WakeWordService::class.java).create()
service.startCommand(0, 1)
assertNull(shadowOf(manager).getNotification(WakeBootReceiver.RESUME_ID))
assertEquals(before, AssistPresence.open.value)
service.destroy()
}
@Test
fun stopIsTheSettingGoingOffNotTheServiceStoppedUnderAStart() {
shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)
WakeStatus.set(WakeState.Listening("Hey Assistant"))
while (shadowOf(app).nextStoppedService != null) Unit
WakeWordService.stop()
// Nobody calls stopService: the service ends itself once it has shown its notification.
assertNull(shadowOf(app).nextStoppedService)
assertEquals(WakeState.Off, WakeStatus.state.value)
}
@Test
fun withoutTheMicrophonePermissionItIsNotStartedAndSaysWhy() {
shadowOf(app).denyPermissions(Manifest.permission.RECORD_AUDIO)
while (shadowOf(app).nextStartedService != null) Unit
WakeWordService.start(app)
assertEquals(WakeState.Paused(WakePause.NoMicrophone), WakeStatus.state.value)
assertNull(shadowOf(app).nextStartedService)
// Given back (in the system's settings), the next time the app comes to the screen starts it.
shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)
WakeWordService.start(app)
assertEquals(WakeWordService::class.java.name, shadowOf(app).nextStartedService.component?.className)
}
}
@@ -0,0 +1,307 @@
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.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.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
import kotlinx.coroutines.cancel
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.FileNotFoundException
import java.io.InputStream
import java.util.Locale
@OptIn(ExperimentalCoroutinesApi::class)
class WakeTest {
@get:Rule
val folder = TemporaryFolder()
private val files = listOf("encoder.int8.onnx", "tokens.txt")
/** The APK's assets as [unpackWakeModel] opens them: by stream, counted. */
private class Assets(private val content: Map<String, String>) : (String) -> InputStream {
var opened = 0
override fun invoke(name: String): InputStream {
if (name != "version") opened++
return content[name]?.byteInputStream() ?: throw FileNotFoundException(name)
}
}
@Test
fun theModelIsCopiedOncePerVersion() {
val dir = File(folder.root, "wakeword")
val first = Assets(mapOf("version" to "aaaa\n", "encoder.int8.onnx" to "model one", "tokens.txt" to "A 1"))
unpackWakeModel(first, dir, files)
assertEquals("model one", File(dir, "encoder.int8.onnx").readText())
assertEquals(2, first.opened)
// The same version again: nothing is copied.
unpackWakeModel(first, dir, files)
assertEquals(2, first.opened)
// An update brings another model: it replaces the old one, though the file names are the same.
val second = Assets(mapOf("version" to "bbbb\n", "encoder.int8.onnx" to "model two, longer", "tokens.txt" to "A 1"))
unpackWakeModel(second, dir, files)
assertEquals("model two, longer", File(dir, "encoder.int8.onnx").readText())
assertFalse(File(dir, "encoder.int8.onnx.part").exists())
}
@Test
fun aCopyThatWasCutShortIsMadeAgain() {
val dir = File(folder.root, "wakeword")
// The second file is not in the APK: the copy fails, loudly, and leaves no marker.
val broken = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model"))
assertThrows(FileNotFoundException::class.java) { unpackWakeModel(broken, dir, files) }
assertFalse(File(dir, "version").exists())
val whole = Assets(mapOf("version" to "aaaa", "encoder.int8.onnx" to "model", "tokens.txt" to "A 1"))
unpackWakeModel(whole, dir, files)
assertEquals(2, whole.opened)
// A file that went missing afterwards (storage cleared in part) is noticed too.
File(dir, "tokens.txt").delete()
unpackWakeModel(whole, dir, files)
assertEquals(4, whole.opened)
}
@Test
fun aPieceTheModelDoesNotKnowNeverReachesTheEngine() {
val tokens = "<blk> 0\n▁HE 5\nY 6\n▁AS 7\nS 3\nIST 8\nANT 9\n"
checkKeywords("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", tokens)
val refused = assertThrows(WakeError::class.java) { checkKeywords("▁HE Y ▁LE M B AS @hey_lembas\n", tokens) }
assertEquals(WakeFailure.Engine, refused.why)
assertTrue(refused.detail.contains("▁LE"))
}
@Test
fun theKeywordsFileCarriesBoostAndThresholdInTheEnginesSyntax() {
val assistant = WakePhrases.byId("hey_assistant")
assertEquals("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", wakeKeywords(assistant))
assertEquals("▁HE Y ▁AS S IST ANT :1.0 #0.35 @hey_assistant\n", wakeKeywords(assistant, WakeSensitivity.Low))
assertEquals("▁HE Y ▁AS S IST ANT :2.0 #0.15 @hey_assistant\n", wakeKeywords(assistant, WakeSensitivity.High))
// Four pieces: short enough to turn up inside other speech, so it must be a little surer.
assertEquals("▁OKAY ▁COMP U TER :1.5 #0.30 @ok_computer\n", wakeKeywords(WakePhrases.byId("ok_computer")))
// A phone set to a language with a decimal comma still writes numbers the engine reads.
val phone = Locale.getDefault()
try {
Locale.setDefault(Locale.forLanguageTag("sk-SK"))
assertEquals("▁HE Y ▁AS S IST ANT :1.5 #0.25 @hey_assistant\n", wakeKeywords(assistant))
} finally {
Locale.setDefault(phone)
}
assertEquals(WakeSensitivity.Normal, WakeSensitivity.byId("nonsense"))
}
@Test
fun aPhraseIsAGreetingAndAName() {
assertEquals("Hey Assistant", WakePhrases.default.words)
assertEquals(WakeWords.greetings.size * WakeWords.names.size, WakePhrases.all.size)
assertEquals(WakePhrases.all.size, WakePhrases.all.map { it.id }.toSet().size)
assertEquals("OK Google", WakePhrases.byId("ok_google").words)
assertEquals("Hello Samantha", WakePhrases.byId("hello_samantha").words)
// Nothing the model cannot hear is offered.
assertFalse(WakePhrases.all.any { "lembas" in it.id })
}
@Test
fun aSavedPhraseThatIsGoneBecomesHeyAssistant() {
for (old in listOf("hey_lembas", "ok_lembas", "hello_lembas", "nonsense", "")) assertEquals("hey_assistant", WakePhrases.byId(old).id)
assertEquals("hey_assistant", WakePhrases.byId("hey_assistant").id)
// Settings as beta.7 saved them: the old phrase id, no sensitivity yet.
val saved = LembasJson.decodeFromString(Prefs.serializer(), """{"wakeWord":true,"wakePhrase":"hey_lembas","wakeScreenOnly":false}""")
assertTrue(saved.wakeWord)
assertFalse(saved.wakeScreenOnly)
assertEquals("Hey Assistant", WakePhrases.byId(saved.wakePhrase).words)
assertEquals(WakeSensitivity.Normal, WakeSensitivity.byId(saved.wakeSensitivity))
// And a phone that never had the wake word starts on the same phrase.
assertEquals("hey_assistant", Prefs().wakePhrase)
}
@Test
fun aTestTakesTheWordForTenSecondsAndNoLonger() {
WakeStatus.startTrial(now = 1_000)
assertEquals(0, WakeStatus.trial.value.heard)
// Heard during the test: counted, and the assistant stays shut.
assertTrue(WakeStatus.heardInTrial(now = 4_000))
assertTrue(WakeStatus.heardInTrial(now = 10_999))
assertEquals(2, WakeStatus.trial.value.heard)
// The test is over by itself, whether or not anybody ended it: the word opens the assistant again.
assertFalse(WakeStatus.heardInTrial(now = 11_000))
assertEquals(2, WakeStatus.trial.value.heard)
// A new test starts its count again.
WakeStatus.startTrial(now = 20_000)
assertEquals(0, WakeStatus.trial.value.heard)
}
@Test
fun theAssistantIsOpenedOnlyTheWayAndroidAllows() {
// 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()
AppVisibility.activityStarted()
AppVisibility.activityStopped()
assertTrue(AppVisibility.visible)
AppVisibility.activityStopped()
assertFalse(AppVisibility.visible)
}
@Test
fun theHoldAfterTheWordEndsEvenIfWhoeverStartedItIsGone() = runTest {
AssistPresence.release()
val before = AssistPresence.open.value
// The service that heard the word is destroyed before its three seconds are up.
val service = CoroutineScope(coroutineContext + Job())
AssistPresence.holdFor(3_000, service)
assertEquals(before + 1, AssistPresence.open.value)
runCurrent()
service.cancel()
runCurrent()
assertEquals(before, AssistPresence.open.value)
// Left to itself it ends after its time; a second word meanwhile holds on from then.
AssistPresence.holdFor(3_000, this)
advanceTimeBy(2_000)
AssistPresence.holdFor(3_000, this)
advanceTimeBy(2_000)
assertEquals(before + 1, AssistPresence.open.value)
advanceTimeBy(1_001)
assertEquals(before, AssistPresence.open.value)
// A sheet that is up is counted apart, and a starting service clears only the hold.
AssistPresence.shown()
AssistPresence.holdFor(60_000, this)
AssistPresence.release()
assertEquals(before + 1, AssistPresence.open.value)
AssistPresence.hidden()
assertEquals(before, AssistPresence.open.value)
}
@Test
fun aStartSaysWhatIsTrueAndNeverAPhraseByDefault() {
// A service that has only just begun knows no phrase.
assertEquals(WakeState.Starting, wakeStateAtStart(running = false, current = WakeState.Off))
// Whatever an earlier instance left behind is not this one's to repeat.
assertEquals(WakeState.Starting, wakeStateAtStart(running = false, current = WakeState.Listening("Hey Assistant")))
// The app is opened again while it runs: the start says the same as before.
val listening = WakeState.Listening("OK Google")
assertEquals(listening, wakeStateAtStart(running = true, current = listening))
val paused = WakeState.Paused(WakePause.BatterySaver)
assertEquals(paused, wakeStateAtStart(running = true, current = paused))
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()
WakeStatus.set(old, WakeState.Listening("Hey Assistant"))
assertEquals(WakeState.Listening("Hey Assistant"), WakeStatus.state.value)
// Turned off and on again: a new instance takes over while the old one is still ending.
val new = WakeStatus.begin()
WakeStatus.set(new, WakeState.Starting)
WakeStatus.set(old, WakeState.Off)
assertEquals(WakeState.Starting, WakeStatus.state.value)
WakeStatus.set(new, WakeState.Off)
assertEquals(WakeState.Off, WakeStatus.state.value)
}
@Test
fun retriesBackOff() {
assertEquals(listOf(2_000L, 5_000L, 15_000L, 60_000L, 300_000L, 300_000L), (0..5).map(::wakeBackoff))
}
@Test
fun itListensOnlyWhenNothingStandsInTheWay() {
assertEquals(WakePause.None, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))
assertEquals(WakePause.ScreenOff, wakePause(screenOn = false, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = true))
// Told to listen with the screen off too.
assertEquals(WakePause.None, wakePause(screenOn = false, screenOnly = false, batterySaver = false, sheetOpen = false, micAllowed = true))
assertEquals(WakePause.BatterySaver, wakePause(screenOn = true, screenOnly = true, batterySaver = true, sheetOpen = false, micAllowed = true))
// The sheet has the microphone.
assertEquals(WakePause.Assistant, wakePause(screenOn = true, screenOnly = true, batterySaver = true, sheetOpen = true, micAllowed = true))
assertEquals(WakePause.NoMicrophone, wakePause(screenOn = true, screenOnly = true, batterySaver = false, sheetOpen = false, micAllowed = false))
}
@Test
fun phrasesAreSpelledInTheModelsPieces() {
// Every piece of the spelling starts a word with ▁ or continues one; no spaces inside a word.
for (phrase in WakePhrases.all) {
assertTrue(phrase.tokens.startsWith("▁"))
assertEquals(phrase.words.split(' ').size, phrase.tokens.split(' ').count { it.startsWith("▁") })
}
}
}
@@ -0,0 +1,53 @@
package eu.llembas.android
import eu.llembas.android.wake.WakePhrases
import eu.llembas.android.wake.WakeSensitivity
import eu.llembas.android.wake.WakeWords
import eu.llembas.android.wake.checkKeywords
import eu.llembas.android.wake.wakeKeywords
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
/**
* The generated table (`wake/WakeWords.kt`, by `scripts/gen-wake-phrases.py`) against the model
* that will hear it: every piece of every phrase must be in the model's `tokens.txt` -- the
* engine ends the app on one that is not. The table is the model's, so the test reads the very
* file the build puts into the APK (`scripts/fetch-wakeword.py` fetches it before Gradle).
*/
class WakeWordsTest {
private val tokens: String by lazy {
val file = File("src/full/assets/wakeword/tokens.txt")
check(file.isFile) { "no ${file.path}: run scripts/fetch-wakeword.py before the tests" }
file.readText()
}
@Test
fun everyPieceOfEveryPhraseIsInTheModel() {
val known = tokens.lineSequence().map { it.substringBeforeLast(' ') }.toSet()
assertTrue(known.size > 400)
for (word in WakeWords.greetings + WakeWords.names) {
for (piece in word.pieces.split(' ')) assertTrue("${word.words}: the model has no piece \"$piece\"", piece in known)
}
// And as the engine gets them: the whole keywords line of every phrase, at every sensitivity.
for (phrase in WakePhrases.all) {
for (sensitivity in WakeSensitivity.entries) checkKeywords(wakeKeywords(phrase, sensitivity), tokens)
}
}
@Test
fun theTableIsWhatTheSettingsOffer() {
assertEquals(listOf("Hey", "OK", "Hello"), WakeWords.greetings.map { it.words })
assertEquals(listOf("Assistant", "Computer", "Google"), WakeWords.names.take(3).map { it.words })
// Ids are what Settings saves: lower case, one word, unique.
val ids = (WakeWords.greetings + WakeWords.names).map { it.id }
assertEquals(ids.size, ids.toSet().size)
assertTrue(ids.all { id -> id.isNotEmpty() && id.all { it in 'a'..'z' } })
// Written as the model's speech was: capitals only, each word starting with the word mark.
for (word in WakeWords.greetings + WakeWords.names) {
assertTrue(word.pieces.startsWith("▁"))
assertTrue(word.pieces.all { it == '▁' || it == ' ' || it in 'A'..'Z' })
}
}
}
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more