Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cec05ceec2 | ||
|
|
0e30699fff | ||
|
|
d4041e4528 | ||
|
|
c5ae402cd7 | ||
|
|
56eb213bbf | ||
|
|
3165ebb8ce | ||
|
|
a2457a39d4 | ||
|
|
c2799082b0 | ||
|
|
2a467bc03f | ||
|
|
a30d3dc6ed | ||
|
|
44293030c9 | ||
|
|
42ac8c5589 | ||
|
|
b481f1f337 | ||
|
|
62c4017eeb | ||
|
|
7b61ed4758 | ||
|
|
21259230b2 | ||
|
|
7ef1e93544 | ||
|
|
61a50dc968 | ||
|
|
18b9ed005b | ||
|
|
c597187fa3 | ||
|
|
c97f3a3359 | ||
|
|
2d9ccd4712 | ||
|
|
93643be844 | ||
|
|
b82ee95b8f | ||
|
|
1132fdf576 | ||
|
|
04c69cd15f | ||
|
|
b4edcad1e7 | ||
|
|
bef9579917 | ||
|
|
c84e037b77 | ||
|
|
3ad33691cb | ||
|
|
bb0a810798 | ||
|
|
b675c1498c | ||
|
|
6da1ad1a99 | ||
|
|
380b9e918d | ||
|
|
d531b4d377 | ||
|
|
8cba61d2d8 | ||
|
|
4106fd4b78 | ||
|
|
47426db290 | ||
|
|
b7945b072f | ||
|
|
3aead772a0 | ||
|
|
ccf94e1d9d | ||
|
|
6b6edc1322 | ||
|
|
2644b94fa9 | ||
|
|
440e3d5bb9 | ||
|
|
97158bc861 | ||
|
|
d5a313ab5d | ||
|
|
3033e331b0 | ||
|
|
07bbb16671 |
@@ -11,6 +11,34 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
||||
- **Issue area labels require maintainer review.** The unreliable keyword-based auto-labeling workflow no longer assigns ownership from ambiguous issue text.
|
||||
- **Windows-trusted certificates work in the desktop CLI.** The packaged Windows binary and newer Node runtimes add the Windows certificate store without dropping bundled or operator-supplied roots, while TLS verification and Relay certificate pinning remain enforced.
|
||||
|
||||
## [Android 1.8.1] - 2026-08-09
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android preserves complete long-session transcripts.** API-server and profile-scoped Dashboard history reads now use explicit bounded pagination, retain compatibility with older unpaginated responses, and keep edit, retry, sharing, and recovery anchors stable beyond Hermes' latest-500 default window.
|
||||
- **Android follows authoritative Gateway turn contracts.** Submit rejections retain the server's message without silently falling through to SSE, event envelopes reconcile consistently, and edit-and-regenerate requests send the required truncation confirmation.
|
||||
|
||||
## [Android 1.8.0] - 2026-08-09
|
||||
|
||||
### Added
|
||||
|
||||
- **Android chat keeps work in context and makes live turns easier to read.** Draft text, edits, quotes, and attachments stay with their connection, profile, and session; conversation search and prompt-turn navigation jump by stable message identity; message actions reveal smoothly on tap; quoted replies use linked previews without placing markup in the composer; assistant replies retain their compact high-contrast bubbles; and pending attachments support preview, removal, and accessible reordering.
|
||||
- **Android reasoning and tool activity use a quieter transcript.** Live thinking opens as an inline disclosure and settles to a collapsed Thought row, while consecutive routine reads, searches, commands, browser actions, and device actions share one live activity ticker or concise completed summary. Approvals, failures, generated media, file changes, output risks, and delegated work keep their own visible lifecycle surfaces even when ordinary tool progress is hidden.
|
||||
- **Android Profile Shelf makes agent switching immediate without mixing conversations.** The Chat header expands a compact, accessible shelf with ordered profile avatars, a subtle Server-default home badge on the resolved identity, last-session restoration, display hiding, lock controls, and one full switcher shared with Agent Passport.
|
||||
- **Android accepts shared text as a new Chat draft.** Hermes Relay now appears in the system sharesheet for text, opens the active profile in a fresh conversation, and fills the composer for review without sending automatically.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Android appearance controls are more expressive and easier to preview.** Theme presets, accent and shape customization, imported Sphere skins, and custom pet creation share one live-preview workflow while preserving separate agent, background, and companion identities.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Android restores complete Gateway activity and makes settled replies speakable.** Successful Gateway turns reconcile structured persisted tool calls even when an upstream server omits live tool lifecycle events, and a configured voice can read a completed assistant reply from its message actions without requiring Voice Mode. While that narration is active, the same message actions expose Stop without cancelling an unrelated chat turn.
|
||||
- **Android chat matches standard keyboard, scrolling, and photo behavior.** Sentence capitalization is enabled, physical Enter can send or insert a newline according to a device-level setting, Ctrl/Command+Enter always submits, directional keys stay with the text caret, expanded thinking and tool content retains bottom-follow until the user scrolls away, and portrait attachments honor their EXIF orientation in previews and message viewers.
|
||||
- **Android distinguishes live-turn corrections from queued follow-ups.** The composer names its current action with visible text and accessible state, successful gateway redirects show a correction lifecycle marker, and attachment-bearing follow-ups always enter the session-owned queue because the upstream redirect operation is text-only.
|
||||
- **Android visibly explains quiet startup work without an empty chat bubble.** The full-size thinking animation now sits directly in the conversation lane with a stable reviewable status until the first answer text arrives, while recovery keeps its explicit reconnecting state.
|
||||
- **Android keeps pets and screen chrome inside safe interaction bounds.** Floating companions avoid agent identity rows and controls during scrolling, remain touchable for their menu, and settings headers respect edge-to-edge system insets.
|
||||
|
||||
## [Android 1.7.1] - 2026-08-08
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -1,5 +1,135 @@
|
||||
# Hermes-Relay — Dev Log
|
||||
|
||||
## 2026-08-09 — Gateway activity recovery and chat speech
|
||||
|
||||
Successful Android Gateway turns now reconcile against their profile-owned,
|
||||
structured session history. This recovers persisted tool calls when an upstream
|
||||
Gateway completes a turn without emitting live tool lifecycle events; assistant
|
||||
prose is never inspected for inferred activity, and the recovered calls continue
|
||||
through the existing Off, Compact, and Detailed display policy.
|
||||
|
||||
The Speak message action now follows configured voice readiness and idle output
|
||||
state instead of active Voice Mode or presentation style. A settled assistant
|
||||
reply can therefore be read aloud directly from chat, while live or provider
|
||||
playback still prevents overlapping output. One-shot message narration owns its
|
||||
completion state outside Voice Mode and replaces Speak with Stop while active;
|
||||
stopping drains only that narration pipeline and does not cancel a chat turn
|
||||
started while the response was playing.
|
||||
|
||||
## 2026-08-09 — Quiet reasoning and grouped tool activity
|
||||
|
||||
Android Chat now treats reasoning and routine tools as transcript scaffolding.
|
||||
Visible live reasoning opens automatically without a tinted card, then collapses
|
||||
to a quiet Thought disclosure when it settles unless the reader has explicitly
|
||||
chosen its state. Empty reasoning remains absent and the existing first-token
|
||||
status continues to own the waiting state.
|
||||
|
||||
Top-level routine calls retain their source order but render as consecutive
|
||||
activity runs. A live run keeps one summary and one latest-activity ticker in a
|
||||
stable footprint; a settled run becomes one collapsed summary that can disclose
|
||||
the original identity-preserving tool rows. File edits, approval/question tools,
|
||||
generated media, failures, output-risk findings, and delegated work split runs
|
||||
and retain independent surfaces. Off hides only ordinary activity runs, Compact
|
||||
uses compact disclosed rows, and Detailed preserves the full per-tool detail
|
||||
surface on demand. Expansion still yields bottom-follow ownership, and each run
|
||||
registers its measured bounds as Chat pet terrain.
|
||||
|
||||
## 2026-08-09 — Android chat experience and attachment polish
|
||||
|
||||
The Android composer now declares sentence capitalization and a Send IME
|
||||
action. A device-level setting chooses whether unmodified physical Enter sends
|
||||
or inserts a newline; Shift+Enter remains a newline and Ctrl/Command+Enter
|
||||
always submits. Every submit route converges on the existing live-turn owner,
|
||||
so the current gateway state still decides whether content steers the active
|
||||
turn or queues behind it. Directional focus traversal is cancelled while the
|
||||
editor owns focus so hardware arrow keys continue to move the caret and
|
||||
selection.
|
||||
|
||||
Conversation bottom-follow now remains owned when thinking or tool details
|
||||
expand. Only an actual drag ending above the bottom yields that ownership, and
|
||||
a chat first measured while the IME is already visible now captures the same
|
||||
resize-follow state as a keyboard opened after composition.
|
||||
|
||||
Bitmap-backed attachment surfaces now apply EXIF rotation and reflection before
|
||||
display. Attachment reads and Base64 conversion also leave the UI thread, so
|
||||
selecting a larger photo no longer performs the full ingestion path inside the
|
||||
activity-result callback.
|
||||
|
||||
Composer drafts now belong to the stable connection, profile, and session
|
||||
identity. Text, edit context, and pending attachments restore when returning to
|
||||
a chat without persisting attachment bytes. Pending attachments expose bounded,
|
||||
orientation-aware previews plus explicit remove and reorder controls.
|
||||
|
||||
Conversation overflow now opens transcript search with previous/next matches
|
||||
and a prompt-turn rail, both keyed to the same stable UI identity as the message
|
||||
list. Assistant prose retains the compact bubble and subtle edge treatment that
|
||||
keeps it legible above the animated chat background. Tapping a message reveals
|
||||
the existing copy, quote, speak, and edit actions with reduced-motion-aware
|
||||
expansion and accessible targets.
|
||||
|
||||
Quotes are composer-owned structured references instead of raw blockquote text.
|
||||
The composer and sent message render a linked, highlighted author preview; the
|
||||
transport remains ordinary Markdown so unmodified Desktop and TUI clients show
|
||||
a readable quoted reply. Thinking and top-level tools continue to use their
|
||||
independent compact thought bubbles and configured compact or full tool cards,
|
||||
without an aggregate completion card. The composer also names Correction and
|
||||
Queue states with visible labels. Gateway redirects remain text-only:
|
||||
follow-ups with attachments are forced through the existing destination-owned
|
||||
queue so files cannot be left behind by a correction request.
|
||||
|
||||
## 2026-08-08 — Standalone Android thinking status
|
||||
|
||||
Blank streaming assistant rows now present the full-size working animation
|
||||
directly in the conversation lane above the visible `Still working…` label,
|
||||
without painting an empty assistant bubble around the status. The first answer
|
||||
token replaces that standalone state with the normal response bubble, while
|
||||
recovery retains the distinct `Reconnecting to your answer…` wording. The
|
||||
status owns one stable TalkBack description and suppresses animated child
|
||||
nodes, avoiding repeated announcements without claiming measurable progress.
|
||||
|
||||
## 2026-08-08 — Android text-share draft handoff
|
||||
|
||||
The shared Android manifest now advertises a `text/*` `ACTION_SEND` target for
|
||||
both app flavors. `MainActivity` accepts only non-blank single-item text shares
|
||||
and places them in a process-local, identity-fenced handoff that survives cold
|
||||
Compose initialization. Once the configured chat context settles, the app root
|
||||
navigates to Chat and delegates draft creation and composer prefill to
|
||||
`ChatViewModel`.
|
||||
|
||||
The ViewModel reuses the existing new-chat lifecycle, preserving Gateway
|
||||
background-turn reconciliation and the active connection/profile/transport
|
||||
namespace. Composer prefills use a one-consumer conflated channel so an intent
|
||||
received before Chat composition is delivered once. Shared text is never
|
||||
routed through message sending; the user must review and submit it explicitly.
|
||||
|
||||
## 2026-08-08 — Android Profile Shelf and profile-context identity
|
||||
|
||||
Chat profile selection now lives in a collapsible shelf directly below the top
|
||||
app bar. The header toggles the shelf, the active capsule opens Agent Passport,
|
||||
inactive 48 dp avatars switch context, and a pinned overflow opens the same full
|
||||
switcher used by Passport. Saved ordering and hidden state drive both surfaces;
|
||||
the selected hidden profile remains disclosed, while a one-identity shelf stays
|
||||
out of the layout. Long-press actions expose inspection, Passport, profile lock,
|
||||
and hiding without adding activity or presence claims.
|
||||
|
||||
The shelf uses the chat surface instead of a second elevated toolbar. A neutral
|
||||
active capsule, 36 dp avatar artwork inside 48 dp targets, compact spacing, and
|
||||
a contained overflow affordance keep the row visually subordinate to Chat. When
|
||||
Server default resolves to a concrete profile, that profile's avatar remains
|
||||
the identity and a small home badge discloses its default routing role.
|
||||
Local avatar lookup remains keyed to the Server-default presentation identity,
|
||||
so an image customized while that row is selected appears consistently in both
|
||||
the Chat header and shelf rather than being re-keyed to whichever explicit
|
||||
profile is currently active.
|
||||
|
||||
The Server-default sentinel is now distinct from a profile literally named
|
||||
`default`. Profile selection restores the last compatible connection/profile/
|
||||
transport session, otherwise leaves a fresh draft. Gateway turns detach and
|
||||
reconcile in their original session, live SSE turns keep switching disabled,
|
||||
and every profile transition clears session-scoped model, provider, personality,
|
||||
reasoning, approval, Fast, and YOLO state before the destination session seeds
|
||||
its own values. Server sticky-default state is never written.
|
||||
|
||||
## 2026-08-08 — Streaming reply tail follow
|
||||
|
||||
Android's conversation-bottom follower now reads the current immutable message
|
||||
|
||||
@@ -138,7 +138,7 @@ Full server setup, TLS, and systemd details: [docs/relay-server.md](docs/relay-s
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/01_startup.png" alt="Cold start" width="100%"><br><sub><b>Cold start</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/01_voice_conversation.png" alt="Voice controls in chat" width="100%"><br><sub><b>Voice in chat</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/02_chat.png" alt="Streaming chat" width="100%"><br><sub><b>Streaming chat</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/03_voice.png" alt="Hands-free voice" width="100%"><br><sub><b>Hands-free voice</b></sub></td>
|
||||
<td align="center" width="25%"><img src="assets/screenshots/04_sessions.png" alt="Session history" width="100%"><br><sub><b>Session history</b></sub></td>
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Hermes-Relay-Android v1.7.1
|
||||
# Hermes-Relay-Android v1.8.1
|
||||
|
||||
**Release Date:** August 8, 2026
|
||||
**Release Date:** August 9, 2026
|
||||
|
||||
## Download
|
||||
|
||||
> Installing on your phone? Download `hermes-relay-1.7.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
> Installing on your phone? Download `hermes-relay-1.8.1-sideload-release.apk` and tap it for the full feature set, or install the conservative build from [Google Play](https://play.google.com/store/apps/details?id=com.axiomlabs.hermesrelay).
|
||||
|
||||
The `.aab` file is a Play Console upload bundle and cannot be installed by tapping it on a phone.
|
||||
|
||||
@@ -12,32 +12,22 @@ Verify the download against `SHA256SUMS.txt`. See the [sideload guide](https://h
|
||||
|
||||
## Summary
|
||||
|
||||
This patch tightens Android chat ownership, interaction safety, session
|
||||
durability, and hosted-Hermes onboarding after the 1.7.0 release.
|
||||
This patch keeps long Hermes conversations complete and aligns Android's
|
||||
Gateway behavior with current upstream turn contracts.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Growing streamed replies stay visible while bottom-follow is owned, and
|
||||
intentional scrollback still releases that ownership.
|
||||
- Completed replies transition immediately from stable live text to rendered
|
||||
Markdown without reopening the session.
|
||||
- Queued follow-ups retain their originating connection, profile, session,
|
||||
route, attachments, and voice context through concurrent session switches.
|
||||
- Approval cards remain pending until an explicit labeled response or an
|
||||
authoritative upstream expiry; scrolling, navigation, and later activity
|
||||
cannot silently decide them.
|
||||
- Session pins and archives persist through the owning Hermes profile, with
|
||||
rollback when an update fails.
|
||||
- Live tool cards retain stable identity and details while a run is active, and
|
||||
duplicate model inventory rows are reconciled before rendering.
|
||||
- Hosted Hermes addresses complete through the official Dashboard system-browser
|
||||
sign-in flow and resume the verified connection after callback.
|
||||
- Agent Passport safety controls use accessible full-width choices and a
|
||||
reliable close or downward-swipe path.
|
||||
- Complete transcript reads page explicitly across both API-server and
|
||||
profile-scoped Dashboard routes, so sessions beyond Hermes' latest-500
|
||||
default retain stable history, sharing, retry, edit, and recovery anchors.
|
||||
- Gateway submit rejections preserve the authoritative server message without
|
||||
silently falling through to SSE.
|
||||
- Gateway event envelopes reconcile consistently, and edit-and-regenerate
|
||||
requests send the required truncation confirmation.
|
||||
|
||||
## Install / Verify
|
||||
|
||||
- App version: **1.7.1** (versionCode **40**).
|
||||
- App version: **1.8.1** (versionCode **42**).
|
||||
- Standard Chat, sessions, Manage, and Vanilla Hermes voice continue to work
|
||||
against unmodified upstream Hermes.
|
||||
- The optional Relay plugin is not required for standard Android chat or hosted
|
||||
|
||||
@@ -1274,7 +1274,7 @@ Follow-ups:
|
||||
profile/skill-aware empty-state chips and the ~40-flow recomposition hotspot at
|
||||
the top of `ChatScreen`.
|
||||
- **Pet hot-load + in-app add/remove (shipped 2026-06-20).** Pets now live-refresh: an `avatarsRefreshTick` keys the avatar `produceState` in `RelayApp`, and Appearance re-scans `pets/` on open and after in-app import/delete — no app restart. Appearance gained "Add a pet" (SAF `.zip` import via `PetImporter`, zip-slip/zip-bomb guarded + validated through `toAvatar`) and an "Installed pets" list with per-pet remove (`PetLoader.deletePet`, confirm dialog, Sphere fallback). Remaining:
|
||||
- **Sphere-skin parity.** Skins are still process-scoped + `adb push` only — the live tick and the importer cover pets, not skins. Extend the tick to `loadUserSkins` and add a `.json` skin import if hot-loading/adding skins in-app is wanted.
|
||||
- **Sphere-skin parity (shipped 2026-08-09).** Appearance now imports a bounded, validated declarative `.json` skin through the system picker, hot-refreshes the shared sphere registry, and selects the imported skin without an app restart.
|
||||
- `**adb push` into `Android/data` hangs on Samsung scoped storage.** Confirmed: pushing a pet pack to `/sdcard/Android/data/<pkg>/files/pets/` stalls (no bytes written) although `adb shell ls` of the dir works. In-app `.zip` import is the supported path; `/sdcard/Download` pushes fine. Consider softening `docs/pet-spec.md` + user-docs to lead with in-app import over adb.
|
||||
- **On-device import/delete smoke.** Import `/sdcard/Download/lucy.zip` via Add a pet → confirm Lucy appears, selects, and animates all states; then remove it and confirm the avatar falls back to the Sphere.
|
||||
- **Pet behavior model — richer state association (spec'd 2026-06-19, `docs/pet-spec.md` "Agent states & pet behavior").** Shipped: the honesty clamp (declared reactivity ∩ `PET_RENDERER_CAPABILITIES`), the friendly `writing` alias, the `**working`/tool-use overlay** (pet-local sub-state from `toolCallBurst`; opt-in `working` clip drives both the swap and the Tools badge), the **one-shot reaction layer** (`greet`/`wake` on appear, `done`/`celebrate` on turn-finish — opt-in, play-once-then-revert, transition-derived; `ONE_SHOT_MAX_MS` backstop), and `**intensity` modulation** (opt-in `reactive.intensity` → live playback speedup ≤1.6× via `rememberUpdatedState`; un-clamps the Activity badge). Voice · Tools · Activity reactivity is now complete. Remaining:
|
||||
|
||||
@@ -320,6 +320,7 @@ dependencies {
|
||||
// Coil 3 — async image loading for generated images in chat
|
||||
implementation(libs.coil.compose)
|
||||
implementation(libs.coil.network.okhttp)
|
||||
implementation(libs.exifinterface)
|
||||
|
||||
// QR Code scanning (ML Kit + CameraX)
|
||||
implementation(libs.mlkit.barcode)
|
||||
|
||||
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 176 KiB |
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 186 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 132 KiB |
|
Before Width: | Height: | Size: 134 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 129 KiB After Width: | Height: | Size: 232 KiB |
|
Before Width: | Height: | Size: 222 KiB After Width: | Height: | Size: 203 KiB |
|
Before Width: | Height: | Size: 110 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 166 KiB After Width: | Height: | Size: 180 KiB |
@@ -1 +1 @@
|
||||
Growing replies now stay visible without overriding intentional scrollback, completed Markdown renders immediately, and queued follow-ups remain with their originating chat. Session pins and archives persist, approval cards require an explicit decision, Agent Passport controls are easier to use, and hosted Hermes setup completes through the official Dashboard sign-in flow.
|
||||
Long sessions now retain complete history beyond Hermes' latest-500 default, keeping edit, retry, sharing, and recovery anchors stable. Gateway submit rejections preserve the server's message without unintended SSE fallback, while event envelopes and edit-and-regenerate requests follow current upstream contracts.
|
||||
|
||||
@@ -48,6 +48,13 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- User-mediated text handoff. The app opens a fresh Chat draft
|
||||
and fills the composer; it never sends from an external intent. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/*" />
|
||||
</intent-filter>
|
||||
<!-- The loopback native-PKCE result page uses this fixed, tokenless
|
||||
link only to bring the installed flavor back to the foreground.
|
||||
MainActivity intentionally does not interpret the URI as an auth
|
||||
|
||||
@@ -1,5 +1,61 @@
|
||||
{
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.8.1",
|
||||
"title": "Complete, reliable transcripts",
|
||||
"date": "2026-08-09",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Keep long sessions complete",
|
||||
"bullets": [
|
||||
"Android pages explicitly through complete API-server and profile-scoped Dashboard history instead of silently stopping at Hermes' latest-500 default.",
|
||||
"Sharing, retry, edit, and recovery retain stable transcript anchors while bounded safety limits keep unusually large reads controlled."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Follow Gateway truth",
|
||||
"bullets": [
|
||||
"Authoritative submit rejections preserve the server's message without an unintended SSE fallback.",
|
||||
"Gateway event envelopes and edit-and-regenerate truncation confirmation now follow current upstream contracts."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.8.0",
|
||||
"title": "Conversations with more context",
|
||||
"date": "2026-08-09",
|
||||
"sections": [
|
||||
{
|
||||
"header": "Keep the whole turn together",
|
||||
"bullets": [
|
||||
"Quote, edit, search, and attach or reorder files without losing the active connection, profile, or session.",
|
||||
"Share text from another Android app into a fresh Chat draft for review before sending."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "See the work without the clutter",
|
||||
"bullets": [
|
||||
"Live thinking settles into a compact Thought disclosure, while routine tool activity groups into concise runs.",
|
||||
"Approvals, failures, generated media, file changes, risks, and delegated work remain clearly distinct."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Switch agents, not identities",
|
||||
"bullets": [
|
||||
"The Profile Shelf switches agents from Chat while restoring each profile's last session.",
|
||||
"Agent Passport model and reasoning controls remain scoped to the active session instead of rewriting server defaults."
|
||||
]
|
||||
},
|
||||
{
|
||||
"header": "Make it yours",
|
||||
"bullets": [
|
||||
"Preview theme accents and shapes, Sphere skins, and pets in one Appearance workflow.",
|
||||
"Message speech controls, pet touch targets, scrolling terrain, image rotation, and edge-to-edge settings layout are more reliable."
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "1.7.1",
|
||||
"title": "Safer, steadier conversations",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
v1.7.1 - Safer, steadier conversations
|
||||
v1.8.1 - Complete, reliable transcripts
|
||||
|
||||
* Follow growing replies without overriding intentional scrollback.
|
||||
* Render completed Markdown immediately and keep live tool details expandable.
|
||||
* Keep queued follow-ups with their originating chat and persist session pins and archives.
|
||||
* Require explicit approval decisions and improve Agent Passport controls.
|
||||
* Complete hosted Hermes setup through the official Dashboard sign-in flow.
|
||||
* Keep complete history in long sessions beyond Hermes' latest-500 default.
|
||||
* Preserve stable edit, retry, sharing, and recovery anchors while paging history.
|
||||
* Show authoritative Gateway rejection messages without an unintended fallback.
|
||||
* Reconcile Gateway events and edit-and-regenerate requests with current upstream contracts.
|
||||
|
||||
@@ -25,6 +25,8 @@ import com.hermesandroid.relay.notifications.TurnCompleteNotifier
|
||||
import com.hermesandroid.relay.notifications.InteractionRequestNotifier
|
||||
import com.hermesandroid.relay.ui.RelayApp
|
||||
import com.hermesandroid.relay.util.NavRouteRequest
|
||||
import com.hermesandroid.relay.util.SharedTextRequest
|
||||
import com.hermesandroid.relay.util.extractSharedText
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.collect
|
||||
@@ -127,6 +129,7 @@ class MainActivity : AppCompatActivity() {
|
||||
// in RelayApp's NavRouteRequest collector — we just pump the request
|
||||
// into the SharedFlow here.
|
||||
consumeNavRouteIntent(intent)
|
||||
consumeSharedTextIntent(intent)
|
||||
val consumedAssistantActivation =
|
||||
com.hermesandroid.relay.assistant.AssistantSessionProtocol.consumeActivation(
|
||||
this,
|
||||
@@ -153,6 +156,7 @@ class MainActivity : AppCompatActivity() {
|
||||
// instead of onCreate. RelayApp's collector handles both cases.
|
||||
setIntent(intent)
|
||||
consumeNavRouteIntent(intent)
|
||||
consumeSharedTextIntent(intent)
|
||||
com.hermesandroid.relay.assistant.AssistantSessionProtocol.consumeActivation(this, intent)
|
||||
// === END PHASE3-safety-rails-followup ===
|
||||
}
|
||||
@@ -163,6 +167,15 @@ class MainActivity : AppCompatActivity() {
|
||||
NavRouteRequest.tryRequest(route)
|
||||
}
|
||||
|
||||
private fun consumeSharedTextIntent(intent: Intent?) {
|
||||
val sharedText = extractSharedText(
|
||||
action = intent?.action,
|
||||
mimeType = intent?.type,
|
||||
text = intent?.getCharSequenceExtra(Intent.EXTRA_TEXT),
|
||||
) ?: return
|
||||
SharedTextRequest.tryRequest(sharedText)
|
||||
}
|
||||
|
||||
private fun configureAssistantWindow(intent: Intent?) {
|
||||
if (
|
||||
intent?.getBooleanExtra(
|
||||
|
||||
@@ -3,10 +3,10 @@ package com.hermesandroid.relay.data
|
||||
/**
|
||||
* Shared profile/personality display and request identity helpers.
|
||||
*
|
||||
* A null profile name is the app's explicit "Server default" state. The
|
||||
* relay also advertises the root Hermes config as a synthetic profile named
|
||||
* "default"; for request/session identity that row is an alias of server
|
||||
* default so it does not split chat, voice, or session scope.
|
||||
* A null profile name is the app's explicit "Server default" state. It is
|
||||
* intentionally distinct from a real profile whose name is literally
|
||||
* `default`: the former follows the server's sticky default, while the latter
|
||||
* explicitly addresses the root profile.
|
||||
*/
|
||||
object AgentDisplay {
|
||||
const val SERVER_DEFAULT_PROFILE_KEY: String = "__server_default__"
|
||||
@@ -16,17 +16,16 @@ object AgentDisplay {
|
||||
"hermes agent",
|
||||
)
|
||||
|
||||
// Only an EXPLICIT pick drives request/session identity. The advertised
|
||||
// "default" profile is an alias for server default, so falling back to it
|
||||
// here would split chat, voice, or session scope.
|
||||
// Only an explicit pick drives request identity. Server default is the null
|
||||
// selection; a named `default` profile is an ordinary explicit pick.
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
fun effectiveProfile(
|
||||
selectedProfile: Profile?,
|
||||
profiles: List<Profile>,
|
||||
): Profile? = selectedProfile
|
||||
|
||||
// Display can use the synthetic default profile's metadata without making
|
||||
// it a request/session override. Verbose SOUL summaries are filtered by
|
||||
// Display can use the root default profile's metadata without making it a
|
||||
// request/session override. Verbose SOUL summaries are filtered by
|
||||
// profileDisplayName below, so this is safe for headers/cards.
|
||||
fun effectiveDisplayProfile(
|
||||
selectedProfile: Profile?,
|
||||
@@ -39,7 +38,7 @@ object AgentDisplay {
|
||||
?.let { activeName ->
|
||||
profiles.firstOrNull { it.name.equals(activeName, ignoreCase = true) }
|
||||
}
|
||||
?: profiles.firstOrNull { isServerDefaultAlias(it.name) }
|
||||
?: profiles.firstOrNull { it.name.equals("default", ignoreCase = true) }
|
||||
}
|
||||
|
||||
// The NAME goes in the name slot. Non-default profiles use their profile
|
||||
@@ -48,7 +47,7 @@ object AgentDisplay {
|
||||
// verbose SOUL summary.
|
||||
fun profileDisplayName(profile: Profile?): String? {
|
||||
if (profile == null) return null
|
||||
if (isServerDefaultAlias(profile.name)) {
|
||||
if (profile.name.equals("default", ignoreCase = true)) {
|
||||
return defaultProfileDisplayName(profile)
|
||||
}
|
||||
return when {
|
||||
@@ -135,22 +134,18 @@ object AgentDisplay {
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?.takeUnless { it.lowercase() in GENERIC_MODEL_ALIASES }
|
||||
|
||||
fun isServerDefaultAlias(profileName: String?): Boolean =
|
||||
profileName?.trim()?.equals("default", ignoreCase = true) == true
|
||||
|
||||
fun normalizeSelection(profile: Profile?): Profile? =
|
||||
if (isServerDefaultAlias(profile?.name)) null else profile
|
||||
fun normalizeSelection(profile: Profile?): Profile? = profile
|
||||
|
||||
fun profileRequestName(profileName: String?): String? =
|
||||
profileName
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() && !isServerDefaultAlias(it) }
|
||||
?.takeIf { it.isNotEmpty() && it != SERVER_DEFAULT_PROFILE_KEY }
|
||||
|
||||
/**
|
||||
* The profile name that owns chat sessions for the current UI selection.
|
||||
*
|
||||
* [selectedProfileName] is null (or the synthetic `default` alias) for the
|
||||
* "Server default" row. That UI sentinel must remain distinct from the
|
||||
* [selectedProfileName] is null for the "Server default" row. That UI
|
||||
* sentinel must remain distinct from the
|
||||
* server's sticky active profile: a dashboard launched under the root home
|
||||
* may still report `active=victor`, in which case upstream Gateway and
|
||||
* dashboard session calls must explicitly target `victor`. The resolved
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/**
|
||||
* Immutable owner of one composer draft.
|
||||
*
|
||||
* Callers must supply stable ids rather than display labels. [sessionId] may be
|
||||
* a server id or a stable client-generated id for a not-yet-created session.
|
||||
* [draftId] separates the primary composer from any future named draft slot.
|
||||
*/
|
||||
data class ChatComposerDraftKey(
|
||||
val connectionId: String,
|
||||
val profileId: String,
|
||||
val sessionId: String,
|
||||
val draftId: String = PRIMARY_DRAFT_ID,
|
||||
) {
|
||||
init {
|
||||
require(connectionId.isNotBlank()) { "connectionId must not be blank" }
|
||||
require(profileId.isNotBlank()) { "profileId must not be blank" }
|
||||
require(sessionId.isNotBlank()) { "sessionId must not be blank" }
|
||||
require(draftId.isNotBlank()) { "draftId must not be blank" }
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val PRIMARY_DRAFT_ID = "primary"
|
||||
const val DEFAULT_PROFILE_ID = "default"
|
||||
}
|
||||
}
|
||||
|
||||
/** Message references associated with composer content. */
|
||||
data class ChatComposerDraftContext(
|
||||
val quotedMessageId: String? = null,
|
||||
val editingMessageId: String? = null,
|
||||
) {
|
||||
internal fun normalized(): ChatComposerDraftContext = copy(
|
||||
quotedMessageId = quotedMessageId?.takeIf(String::isNotBlank),
|
||||
editingMessageId = editingMessageId?.takeIf(String::isNotBlank),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete restorable state for one composer.
|
||||
*
|
||||
* Selection offsets use the same start-inclusive/end-exclusive convention as
|
||||
* Compose text fields. The store clamps them whenever the text changes so a
|
||||
* restored selection can never address outside the restored string.
|
||||
*/
|
||||
data class ChatComposerDraft(
|
||||
val text: String = "",
|
||||
val selectionStart: Int = text.length,
|
||||
val selectionEnd: Int = selectionStart,
|
||||
val context: ChatComposerDraftContext = ChatComposerDraftContext(),
|
||||
val attachments: List<Attachment> = emptyList(),
|
||||
) {
|
||||
val isEmpty: Boolean
|
||||
get() = text.isEmpty() &&
|
||||
context.quotedMessageId == null &&
|
||||
context.editingMessageId == null &&
|
||||
attachments.isEmpty()
|
||||
|
||||
internal fun normalized(): ChatComposerDraft {
|
||||
val normalizedStart = selectionStart.coerceIn(0, text.length)
|
||||
val normalizedEnd = selectionEnd.coerceIn(0, text.length)
|
||||
return copy(
|
||||
selectionStart = minOf(normalizedStart, normalizedEnd),
|
||||
selectionEnd = maxOf(normalizedStart, normalizedEnd),
|
||||
context = context.normalized(),
|
||||
attachments = attachments.toList(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session-owned composer state.
|
||||
*
|
||||
* This store is deliberately memory-only: outbound [Attachment.content] can
|
||||
* contain large Base64 payloads and must not enter Preferences DataStore. Keep
|
||||
* one instance in the chat owner (normally its ViewModel) so drafts survive
|
||||
* navigation and Activity recreation. Process death starts with empty drafts;
|
||||
* a future durable implementation should persist URI grants, not attachment
|
||||
* bytes.
|
||||
*/
|
||||
interface ChatComposerDraftStore {
|
||||
fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft>
|
||||
fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft
|
||||
fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft)
|
||||
fun update(
|
||||
key: ChatComposerDraftKey,
|
||||
transform: (ChatComposerDraft) -> ChatComposerDraft,
|
||||
)
|
||||
fun remove(key: ChatComposerDraftKey)
|
||||
fun removeSession(connectionId: String, profileId: String, sessionId: String)
|
||||
fun clear()
|
||||
}
|
||||
|
||||
class InMemoryChatComposerDraftStore : ChatComposerDraftStore {
|
||||
private val drafts = MutableStateFlow<Map<ChatComposerDraftKey, ChatComposerDraft>>(emptyMap())
|
||||
|
||||
override fun observe(key: ChatComposerDraftKey): Flow<ChatComposerDraft> =
|
||||
drafts
|
||||
.map { it[key] ?: ChatComposerDraft() }
|
||||
.distinctUntilChanged()
|
||||
|
||||
override fun snapshot(key: ChatComposerDraftKey): ChatComposerDraft =
|
||||
drafts.value[key] ?: ChatComposerDraft()
|
||||
|
||||
@Synchronized
|
||||
override fun save(key: ChatComposerDraftKey, draft: ChatComposerDraft) {
|
||||
val normalized = draft.normalized()
|
||||
drafts.value = if (normalized.isEmpty) {
|
||||
drafts.value - key
|
||||
} else {
|
||||
drafts.value + (key to normalized)
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun update(
|
||||
key: ChatComposerDraftKey,
|
||||
transform: (ChatComposerDraft) -> ChatComposerDraft,
|
||||
) {
|
||||
save(key, transform(snapshot(key)))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun remove(key: ChatComposerDraftKey) {
|
||||
drafts.value = drafts.value - key
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun removeSession(connectionId: String, profileId: String, sessionId: String) {
|
||||
drafts.value = drafts.value.filterKeys { key ->
|
||||
key.connectionId != connectionId ||
|
||||
key.profileId != profileId ||
|
||||
key.sessionId != sessionId
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun clear() {
|
||||
drafts.value = emptyMap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
/** Phone-local behavior for a physical keyboard's unmodified Enter key. */
|
||||
enum class PhysicalKeyboardEnterBehavior(val storedValue: String) {
|
||||
SendMessage("send_message"),
|
||||
InsertNewline("insert_newline"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun fromStoredValue(value: String?): PhysicalKeyboardEnterBehavior =
|
||||
entries.firstOrNull { it.storedValue == value } ?: SendMessage
|
||||
}
|
||||
}
|
||||
|
||||
/** Device-level chat input preferences shared by every Hermes profile. */
|
||||
class ChatInputPreferencesRepository(
|
||||
private val dataStore: DataStore<Preferences>,
|
||||
) {
|
||||
constructor(context: Context) : this(context.relayDataStore)
|
||||
|
||||
companion object {
|
||||
internal val KEY_PHYSICAL_KEYBOARD_ENTER =
|
||||
stringPreferencesKey("physical_keyboard_enter_behavior")
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: Flow<PhysicalKeyboardEnterBehavior> = dataStore.data
|
||||
.map { preferences ->
|
||||
PhysicalKeyboardEnterBehavior.fromStoredValue(
|
||||
preferences[KEY_PHYSICAL_KEYBOARD_ENTER],
|
||||
)
|
||||
}
|
||||
.distinctUntilChanged()
|
||||
|
||||
suspend fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
|
||||
dataStore.edit { preferences ->
|
||||
preferences[KEY_PHYSICAL_KEYBOARD_ENTER] = behavior.storedValue
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,12 +112,11 @@ data class ChatMessage(
|
||||
*/
|
||||
val clientOnly: Boolean = false,
|
||||
/**
|
||||
* Delivery state for a message the user sends into an agent **Thread** over
|
||||
* the relay proactive channel ([com.hermesandroid.relay.viewmodel.ChatViewModel]
|
||||
* routes `source=phone` sessions here instead of the normal chat send).
|
||||
* `SENDING` until the relay acks (`proactive.reply.ack`) → `DELIVERED`;
|
||||
* `FAILED` on a send error. Null for ordinary chat messages — those render
|
||||
* no status affix.
|
||||
* Delivery state for a user-authored message. Agent **Thread** replies use
|
||||
* `SENDING` until the relay acks (`proactive.reply.ack`) → `DELIVERED`,
|
||||
* with `FAILED` on a send error. Ordinary chat may additionally use
|
||||
* `QUEUED` and `STEERED` to make active-turn routing visible. Null keeps the
|
||||
* legacy behavior of rendering no status affix.
|
||||
*/
|
||||
val deliveryStatus: MessageDeliveryStatus? = null,
|
||||
/**
|
||||
@@ -388,15 +387,17 @@ enum class MessageRole {
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery state of a user reply sent into an agent Thread over the relay
|
||||
* proactive channel. Only set on Thread replies; ordinary chat messages leave
|
||||
* it null and show no status affix.
|
||||
* Delivery state of a user-authored message. Thread replies use the relay ack
|
||||
* lifecycle; ordinary chat can additionally expose queue and steer outcomes.
|
||||
* Null preserves the legacy behavior of rendering no status affix.
|
||||
*
|
||||
* - [SENDING] handed to the relay; awaiting the per-reply ack.
|
||||
* - [QUEUED] held client-side until the active turn completes.
|
||||
* - [STEERED] accepted as a correction to the active turn.
|
||||
* - [DELIVERED] the relay acked (`proactive.reply.ack`) — buffered for the agent.
|
||||
* - [FAILED] the send errored (e.g. relay disconnected).
|
||||
*/
|
||||
enum class MessageDeliveryStatus { SENDING, DELIVERED, FAILED }
|
||||
enum class MessageDeliveryStatus { SENDING, QUEUED, STEERED, DELIVERED, FAILED }
|
||||
|
||||
data class ChatSession(
|
||||
val sessionId: String,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.Base64
|
||||
|
||||
/** Structured identity and preview for a quoted chat message. */
|
||||
data class ChatQuoteReference(
|
||||
val messageId: String,
|
||||
val authorLabel: String,
|
||||
val excerpt: String,
|
||||
)
|
||||
|
||||
/** Parsed transport envelope: Android renders [reference] separately from [body]. */
|
||||
data class ChatQuoteEnvelope(
|
||||
val reference: ChatQuoteReference,
|
||||
val body: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Serialize a structured quote as ordinary Markdown for unmodified Hermes clients.
|
||||
* Android parses the same envelope back into a quote chip, while Desktop/TUI see
|
||||
* a readable linked attribution instead of an Android-only marker.
|
||||
*/
|
||||
fun buildChatQuotedPrompt(body: String, reference: ChatQuoteReference?): String {
|
||||
if (reference == null) return body
|
||||
val encodedId = Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
reference.messageId.toByteArray(StandardCharsets.UTF_8),
|
||||
)
|
||||
val author = reference.authorLabel.normalizedQuoteText(MAX_AUTHOR_CHARS)
|
||||
val excerpt = reference.excerpt.normalizedQuoteText(MAX_EXCERPT_CHARS)
|
||||
if (encodedId.isBlank() || author.isBlank() || excerpt.isBlank()) return body
|
||||
return "> **Replying to [@$author](hermes-message://$encodedId):** $excerpt\n\n$body"
|
||||
}
|
||||
|
||||
/** Parse only the exact bounded envelope emitted by [buildChatQuotedPrompt]. */
|
||||
fun parseChatQuotedPrompt(content: String): ChatQuoteEnvelope? {
|
||||
val match = QUOTE_ENVELOPE.matchEntire(content) ?: return null
|
||||
val author = match.groupValues[1]
|
||||
val encodedId = match.groupValues[2]
|
||||
val excerpt = match.groupValues[3]
|
||||
val body = match.groupValues[4]
|
||||
val messageId = runCatching {
|
||||
String(Base64.getUrlDecoder().decode(encodedId), StandardCharsets.UTF_8)
|
||||
}.getOrNull()?.takeIf { it.isNotBlank() && it.length <= MAX_MESSAGE_ID_CHARS } ?: return null
|
||||
return ChatQuoteEnvelope(
|
||||
reference = ChatQuoteReference(messageId, author, excerpt),
|
||||
body = body,
|
||||
)
|
||||
}
|
||||
|
||||
private fun String.normalizedQuoteText(maxChars: Int): String =
|
||||
replace(Regex("[\\p{Cc}\\s]+"), " ")
|
||||
.replace("\\", "")
|
||||
.replace("]", "")
|
||||
.trim()
|
||||
.take(maxChars)
|
||||
|
||||
private val QUOTE_ENVELOPE = Regex(
|
||||
pattern = "^> \\*\\*Replying to \\[@([^]\\r\\n]{1,$MAX_AUTHOR_CHARS})]" +
|
||||
"\\(hermes-message://([A-Za-z0-9_-]{1,512})\\):\\*\\* " +
|
||||
"([^\\r\\n]{1,$MAX_EXCERPT_CHARS})\\n\\n([\\s\\S]*)$",
|
||||
)
|
||||
|
||||
private const val MAX_AUTHOR_CHARS = 40
|
||||
private const val MAX_EXCERPT_CHARS = 240
|
||||
private const val MAX_MESSAGE_ID_CHARS = 512
|
||||
@@ -26,7 +26,6 @@ object ProfilePresentationPolicy {
|
||||
fun availableKeys(profiles: List<Profile>): List<String> = buildList {
|
||||
add(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY)
|
||||
profiles.asSequence()
|
||||
.filterNot { AgentDisplay.isServerDefaultAlias(it.name) }
|
||||
.map(Profile::name)
|
||||
.distinct()
|
||||
.forEach(::add)
|
||||
@@ -49,6 +48,12 @@ object ProfilePresentationPolicy {
|
||||
): List<String> = orderedKeys(profiles, presentation).filter { key ->
|
||||
key == selectedKey || key !in presentation.hidden
|
||||
}
|
||||
|
||||
fun shouldShowShelf(
|
||||
profiles: List<Profile>,
|
||||
presentation: ProfilePresentation,
|
||||
selectedKey: String,
|
||||
): Boolean = visibleKeys(profiles, presentation, selectedKey).size > 1
|
||||
}
|
||||
|
||||
class ProfilePresentationStore(
|
||||
|
||||
@@ -1909,6 +1909,37 @@ class ChatHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when structured session history contains tool lifecycle
|
||||
* state that the live transcript did not receive. This is a read-only
|
||||
* preflight for Gateway completion reconciliation: healthy live turns keep
|
||||
* their current StateFlow list and UI identity, while omitted upstream
|
||||
* tool events opt into [loadMessageHistory]. Assistant prose is never
|
||||
* inspected or interpreted here.
|
||||
*/
|
||||
fun hasMissingPersistedToolActivity(items: List<MessageItem>): Boolean {
|
||||
val toolResults = items.filter { it.role == "tool" }
|
||||
.associateBy { it.toolCallId }
|
||||
val persistedCalls = coalesceRenderedHistoryItems(items)
|
||||
.asSequence()
|
||||
.filter { it.role == "assistant" }
|
||||
.flatMap { parseToolCallsFromHistory(it.toolCalls, toolResults).asSequence() }
|
||||
.toList()
|
||||
if (persistedCalls.isEmpty()) return false
|
||||
|
||||
val localCalls = _messages.value.flatMap { it.toolCalls }
|
||||
return persistedCalls.any { persisted ->
|
||||
val local = persisted.id?.let { id -> localCalls.firstOrNull { it.id == id } }
|
||||
?: localCalls.firstOrNull {
|
||||
it.id == null && it.name == persisted.name && it.args == persisted.args
|
||||
}
|
||||
local == null ||
|
||||
(persisted.isComplete && !local.isComplete) ||
|
||||
(persisted.result != null && persisted.result != local.result) ||
|
||||
(persisted.success != null && persisted.success != local.success)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Session management ---
|
||||
|
||||
fun setSessionId(sessionId: String?) {
|
||||
|
||||
@@ -763,12 +763,24 @@ class DashboardApiClient(
|
||||
suspend fun getSessionMessages(
|
||||
sessionId: String,
|
||||
profile: String? = null,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): Result<List<MessageItem>> = withContext(Dispatchers.IO) {
|
||||
val name = profile?.trim().orEmpty()
|
||||
val query = if (name.isNotBlank()) "?profile=${pathSegment(name)}" else ""
|
||||
getJson("/api/sessions/${pathSegment(sessionId)}/messages$query").mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(MessageListResponse.serializer(), root)
|
||||
parsed.messages ?: parsed.data ?: parsed.items ?: emptyList()
|
||||
loadSessionMessages(mode) { page ->
|
||||
val query = buildList {
|
||||
add("limit=${page.limit}")
|
||||
add("offset=${page.offset}")
|
||||
add("order=${page.order}")
|
||||
if (name.isNotBlank()) add("profile=${pathSegment(name)}")
|
||||
}.joinToString(prefix = "?", separator = "&")
|
||||
getJson("/api/sessions/${pathSegment(sessionId)}/messages$query").mapCatching { root ->
|
||||
val parsed = json.decodeFromJsonElement(MessageListResponse.serializer(), root)
|
||||
SessionMessagePage(
|
||||
messages = parsed.messages ?: parsed.data ?: parsed.items ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = root.toString().length,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -562,7 +562,11 @@ class GatewayChatClient(
|
||||
buildJsonObject {
|
||||
put("session_id", liveSessionId ?: error("no live session"))
|
||||
put("text", text)
|
||||
truncateBeforeUserOrdinal?.let { put("truncate_before_user_ordinal", it) }
|
||||
truncateBeforeUserOrdinal?.let { ordinal ->
|
||||
put("truncate_before_user_ordinal", ordinal)
|
||||
put("confirm_truncate", true)
|
||||
if (ordinal == 0) put("confirm_empty_truncate", true)
|
||||
}
|
||||
if (queuedFollowUp) put("queued", true)
|
||||
},
|
||||
// Long-running RPC, not a generic 15s ack — see the
|
||||
@@ -588,7 +592,7 @@ class GatewayChatClient(
|
||||
if (activeTurn === turn) activeTurn = null
|
||||
turn.disarmWatchdog()
|
||||
val submitError = submitted.exceptionOrNull()
|
||||
if ((submitError as? GatewayRpcException)?.code == ACTIVE_SESSION_CAP_REJECTION) {
|
||||
if (submitError.isAuthoritativePromptSubmitRejection()) {
|
||||
// Authoritative policy rejection: the gateway received
|
||||
// the prompt and deliberately refused to create the
|
||||
// first turn. Falling back to SSE would bypass the cap
|
||||
@@ -597,7 +601,7 @@ class GatewayChatClient(
|
||||
// through the normal failed-turn callback instead.
|
||||
turn.tracer.done("submit-rejected")
|
||||
turn.callbacks.onError(
|
||||
submitError.message ?: "Hermes rejected the new session",
|
||||
submitError?.message ?: "Hermes rejected the new session",
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
@@ -3084,7 +3088,13 @@ internal class GatewayConnectAttemptException(message: String) : Exception(messa
|
||||
internal class GatewayRpcException(message: String, val code: Int? = null) : Exception(message)
|
||||
|
||||
private const val JSONRPC_METHOD_NOT_FOUND = -32601
|
||||
private const val ACTIVE_SESSION_CAP_REJECTION = 4090
|
||||
private val AUTHORITATIVE_PROMPT_SUBMIT_REJECTIONS = setOf(
|
||||
4028, // first-turn truncate requires explicit empty-history confirmation
|
||||
4029, // every destructive truncate requires explicit confirmation
|
||||
4090, // active-session capacity policy
|
||||
5070, // initial session persistence failed: storage full
|
||||
5071, // other authoritative initial session persistence failure
|
||||
)
|
||||
private const val MAX_RECOVERED_CORRECTIONS = 32
|
||||
private const val MAX_RECOVERED_CORRECTION_CHARS = 32_768
|
||||
private const val PET_THUMB_DATA_PREFIX = "data:image/png;base64,"
|
||||
@@ -3140,6 +3150,9 @@ private fun Throwable?.isMethodNotFound(): Boolean {
|
||||
msg.contains("unknown method", ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun Throwable?.isAuthoritativePromptSubmitRejection(): Boolean =
|
||||
(this as? GatewayRpcException)?.code in AUTHORITATIVE_PROMPT_SUBMIT_REJECTIONS
|
||||
|
||||
private fun Throwable?.isApprovalModeUnsupported(): Boolean {
|
||||
val rpcError = this as? GatewayRpcException ?: return false
|
||||
val message = rpcError.message.orEmpty()
|
||||
|
||||
@@ -503,6 +503,21 @@ internal fun isCurrentModelOptionsResponse(
|
||||
): Boolean =
|
||||
requestGeneration == currentGeneration && requestProfileKey == currentProfileKey
|
||||
|
||||
/**
|
||||
* Selects the identity a model-options response may publish into chat UI state.
|
||||
* Catalog-only requests populate picker choices without changing session identity.
|
||||
*/
|
||||
internal fun modelOptionsIdentityToPublish(
|
||||
catalogOnly: Boolean,
|
||||
hasLiveSession: Boolean,
|
||||
sessionIdentity: GatewayModelIdentity?,
|
||||
options: GatewayModelOptions,
|
||||
): GatewayModelIdentity? = when {
|
||||
catalogOnly -> null
|
||||
hasLiveSession && sessionIdentity != null -> sessionIdentity
|
||||
else -> GatewayModelIdentity(options.currentModel, options.currentProvider)
|
||||
}
|
||||
|
||||
/**
|
||||
* The explicit in-chat overrides to bind onto a gateway `session.create` as the
|
||||
* new session's PER-SESSION overrides. Matches the upstream desktop client,
|
||||
|
||||
@@ -19,6 +19,7 @@ import com.hermesandroid.relay.network.upstream.models.SkillListResponse
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
import com.hermesandroid.relay.util.TurnLatencyTracer
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.encodeToString
|
||||
import kotlinx.serialization.Serializable
|
||||
@@ -713,19 +714,34 @@ class HermesApiClient(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun getMessages(sessionId: String): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val request = authRequest("$baseUrl/api/sessions/$sessionId/messages")
|
||||
.get()
|
||||
.build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) return@withContext emptyList()
|
||||
val body = response.body?.string() ?: return@withContext emptyList()
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
parsed.data ?: parsed.items ?: parsed.messages ?: emptyList()
|
||||
suspend fun getMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> = withContext(Dispatchers.IO) {
|
||||
loadSessionMessages(mode) { page ->
|
||||
runCatching {
|
||||
val url = "$baseUrl/api/sessions/$sessionId/messages".toHttpUrlOrNull()
|
||||
?.newBuilder()
|
||||
?.addQueryParameter("limit", page.limit.toString())
|
||||
?.addQueryParameter("offset", page.offset.toString())
|
||||
?.addQueryParameter("order", page.order)
|
||||
?.build()
|
||||
?: error("invalid session messages URL")
|
||||
val request = authRequest(url.toString()).get().build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) error("HTTP ${response.code}")
|
||||
val body = response.body?.string() ?: error("empty response body")
|
||||
val parsed = json.decodeFromString<MessageListResponse>(body)
|
||||
SessionMessagePage(
|
||||
messages = parsed.data ?: parsed.items ?: parsed.messages ?: emptyList(),
|
||||
pagination = parsed.pagination,
|
||||
payloadChars = body.length,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Failed to get messages: ${e.message}")
|
||||
}.getOrElse { error ->
|
||||
if (error is CancellationException) throw error
|
||||
Log.w(TAG, "Failed to get messages: ${error.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessagePagination
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/** Explicit transcript read intent for Hermes' bounded messages endpoint. */
|
||||
enum class SessionMessageLoadMode {
|
||||
/** One bounded newest-first window, returned in chronological order. */
|
||||
LATEST,
|
||||
|
||||
/** Every page, oldest first, subject to Android memory safety bounds. */
|
||||
COMPLETE,
|
||||
}
|
||||
|
||||
internal const val SESSION_MESSAGE_PAGE_SIZE = 500
|
||||
private const val MAX_COMPLETE_TRANSCRIPT_MESSAGES = 50_000
|
||||
private const val MAX_COMPLETE_TRANSCRIPT_PAYLOAD_CHARS = 32_000_000
|
||||
|
||||
internal data class SessionMessagePageRequest(
|
||||
val limit: Int = SESSION_MESSAGE_PAGE_SIZE,
|
||||
val offset: Int = 0,
|
||||
val order: String,
|
||||
)
|
||||
|
||||
internal data class SessionMessagePage(
|
||||
val messages: List<MessageItem>,
|
||||
val pagination: MessagePagination?,
|
||||
val payloadChars: Int,
|
||||
)
|
||||
|
||||
internal class SessionTranscriptTooLargeException(message: String) : IllegalStateException(message)
|
||||
|
||||
/** Shared API-server/dashboard pagination contract. Legacy unpaginated envelopes remain valid. */
|
||||
internal suspend fun loadSessionMessages(
|
||||
mode: SessionMessageLoadMode,
|
||||
fetchPage: suspend (SessionMessagePageRequest) -> Result<SessionMessagePage>,
|
||||
): Result<List<MessageItem>> {
|
||||
return try {
|
||||
val order = if (mode == SessionMessageLoadMode.LATEST) "latest" else "oldest"
|
||||
val collected = ArrayList<MessageItem>()
|
||||
var offset = 0
|
||||
var payloadChars = 0L
|
||||
|
||||
while (true) {
|
||||
val request = SessionMessagePageRequest(offset = offset, order = order)
|
||||
val page = fetchPage(request).getOrThrow()
|
||||
payloadChars += page.payloadChars
|
||||
if (payloadChars > MAX_COMPLETE_TRANSCRIPT_PAYLOAD_CHARS) {
|
||||
throw SessionTranscriptTooLargeException(
|
||||
"Session transcript exceeds Android's 32 MB safe-load limit",
|
||||
)
|
||||
}
|
||||
if (collected.size + page.messages.size > MAX_COMPLETE_TRANSCRIPT_MESSAGES) {
|
||||
throw SessionTranscriptTooLargeException(
|
||||
"Session transcript exceeds Android's 50,000-message safe-load limit",
|
||||
)
|
||||
}
|
||||
collected += page.messages
|
||||
|
||||
if (mode == SessionMessageLoadMode.LATEST) break
|
||||
// Older Hermes returned one unpaginated complete envelope. Never issue
|
||||
// a speculative second request against that contract.
|
||||
val pagination = page.pagination ?: break
|
||||
val returned = pagination.returned ?: page.messages.size
|
||||
if (page.messages.isEmpty() || returned < request.limit || page.messages.size < request.limit) break
|
||||
|
||||
val nextOffset = offset + page.messages.size
|
||||
if (nextOffset <= offset) break
|
||||
offset = nextOffset
|
||||
}
|
||||
Result.success(collected)
|
||||
} catch (error: CancellationException) {
|
||||
throw error
|
||||
} catch (error: Throwable) {
|
||||
Result.failure(error)
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,16 @@ data class MessageListResponse(
|
||||
val items: List<MessageItem>? = null,
|
||||
val messages: List<MessageItem>? = null, // alternate key
|
||||
val data: List<MessageItem>? = null, // upstream /api/sessions/{id}/messages list envelope
|
||||
val total: Int? = null
|
||||
val total: Int? = null,
|
||||
val pagination: MessagePagination? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class MessagePagination(
|
||||
val limit: Int? = null,
|
||||
val offset: Int? = null,
|
||||
val order: String? = null,
|
||||
val returned: Int? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
|
||||
@@ -176,7 +176,7 @@ internal class HermesRuntimeBinder(
|
||||
chat.setDisplayProfileProvider { connection.effectiveDisplayProfile.value }
|
||||
chat.setDisplayAliasProvider { connection.profileDisplayAlias.value }
|
||||
chat.setProfileSessionLister { connection.listProfileScopedSessions() }
|
||||
chat.setProfileMessageLoader(connection::loadProfileScopedMessages)
|
||||
chat.setProfileMessageLoaderWithMode(connection::loadProfileScopedMessages)
|
||||
chat.setDashboardConfigLoader { connection.loadActiveDashboardConfig() }
|
||||
chat.profileSessionDeleter = connection::deleteProfileScopedSession
|
||||
chat.profileSessionRenamer = connection::renameProfileScopedSession
|
||||
|
||||
@@ -59,6 +59,7 @@ import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalWindowInfo
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -96,13 +97,16 @@ import com.hermesandroid.relay.ui.components.avatar.LocalPetPlaybackSpeed
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalPetStabilize
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetLoader
|
||||
import com.hermesandroid.relay.ui.components.avatar.SphereAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.resolveBackgroundAvatar
|
||||
import com.hermesandroid.relay.ui.components.FloatingPetCompanion
|
||||
import com.hermesandroid.relay.ui.components.shouldCompactFloatingPet
|
||||
import com.hermesandroid.relay.ui.components.pet.LocalPetCompanionCoordinator
|
||||
import com.hermesandroid.relay.ui.components.pet.LocalPetSafeAreaRegistry
|
||||
import com.hermesandroid.relay.ui.components.pet.PetCompanionCoordinator
|
||||
import com.hermesandroid.relay.ui.components.pet.PetInteractionLayer
|
||||
import com.hermesandroid.relay.ui.components.pet.PetSafeAreaRegistry
|
||||
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
|
||||
import com.hermesandroid.relay.ui.components.pet.platformModalOwnsPetLayer
|
||||
import com.hermesandroid.relay.ui.components.ConnectionSwitcherSheet
|
||||
import com.hermesandroid.relay.ui.components.ChatTransportStatusBadge
|
||||
import com.hermesandroid.relay.ui.components.ChatTransportTier
|
||||
@@ -135,6 +139,7 @@ import com.hermesandroid.relay.ui.onboarding.OnboardingScreen
|
||||
import com.hermesandroid.relay.ui.screens.AboutScreen
|
||||
import com.hermesandroid.relay.ui.screens.AnalyticsScreen
|
||||
import com.hermesandroid.relay.ui.screens.AppearanceSettingsScreen
|
||||
import com.hermesandroid.relay.ui.screens.CustomPetGuideScreen
|
||||
import com.hermesandroid.relay.ui.screens.PetdexBrowseScreen
|
||||
import com.hermesandroid.relay.ui.screens.BridgeCoreScreen
|
||||
import com.hermesandroid.relay.ui.screens.DiagnosticsScreen
|
||||
@@ -465,6 +470,7 @@ sealed class Screen(
|
||||
data object MediaSettings : Screen("settings/media", "Media", Icons.Filled.Settings)
|
||||
data object AppearanceSettings : Screen("settings/appearance", "Appearance", Icons.Filled.Settings)
|
||||
data object PetdexBrowse : Screen("settings/appearance/petdex", "Petdex", Icons.Filled.Settings)
|
||||
data object CustomPetGuide : Screen("settings/appearance/custom-pet", "Create a pet", Icons.Filled.Settings)
|
||||
data object Analytics : Screen("settings/analytics", "Analytics", Icons.Filled.Settings)
|
||||
data object Diagnostics : Screen("settings/diagnostics", "Diagnostics", Icons.Filled.Settings)
|
||||
data object DeveloperSettings : Screen("settings/developer", "Developer", Icons.Filled.Settings)
|
||||
@@ -698,16 +704,20 @@ fun RelayApp() {
|
||||
val appThemeId by connectionViewModel.appTheme.collectAsState()
|
||||
val fontScale by connectionViewModel.fontScale.collectAsState()
|
||||
val appFontId by connectionViewModel.appFont.collectAsState()
|
||||
val appearanceAccent by connectionViewModel.appearanceAccent.collectAsState()
|
||||
val appearanceShape by connectionViewModel.appearanceShape.collectAsState()
|
||||
|
||||
// Resolve the active sphere skin (built-in / adaptive / user-loaded) and
|
||||
// publish it + the full available set so every MorphingSphere picks it up
|
||||
// via LocalSphereSkin without per-call-site threading. Adaptive skins read
|
||||
// the brand lazily inside MorphingSphere, so this can sit outside the theme.
|
||||
val sphereSkinId by connectionViewModel.sphereSkin.collectAsState()
|
||||
val appearanceAssetsRefreshTick by connectionViewModel.avatarsRefreshTick.collectAsState()
|
||||
val sphereContext = androidx.compose.ui.platform.LocalContext.current
|
||||
val availableSphereSkins by produceState(
|
||||
initialValue = SphereRegistry.builtIns,
|
||||
key1 = sphereContext,
|
||||
key2 = appearanceAssetsRefreshTick,
|
||||
) {
|
||||
value = SphereRegistry.builtIns +
|
||||
withContext(Dispatchers.IO) { SphereSkinLoader.loadUserSkins(sphereContext) }
|
||||
@@ -720,14 +730,14 @@ fun RelayApp() {
|
||||
)
|
||||
}
|
||||
|
||||
// Ambient visualization and pet companionship are independent. Existing
|
||||
// LocalAgentAvatar call sites keep rendering the sphere; a selected pet is
|
||||
// published separately for the floating companion surface.
|
||||
// Central/background visualization and pet companionship are independent.
|
||||
// LocalAgentAvatar owns the central surfaces; LocalFloatingPet owns roaming.
|
||||
val floatingPetId by connectionViewModel.floatingPet.collectAsState()
|
||||
val backgroundAvatarId by connectionViewModel.backgroundAvatar.collectAsState()
|
||||
// Re-scans the pets/ dir whenever the tick bumps (in-app import/delete, or the
|
||||
// Appearance screen opening), so newly added/removed pets appear everywhere
|
||||
// without an app restart.
|
||||
val avatarsRefreshTick by connectionViewModel.avatarsRefreshTick.collectAsState()
|
||||
val avatarsRefreshTick = appearanceAssetsRefreshTick
|
||||
val availablePets by produceState(
|
||||
initialValue = emptyList<AgentAvatar>(),
|
||||
key1 = sphereContext,
|
||||
@@ -738,6 +748,10 @@ fun RelayApp() {
|
||||
val activeFloatingPet = remember(floatingPetId, availablePets) {
|
||||
availablePets.firstOrNull { it.id == floatingPetId }
|
||||
}
|
||||
var floatingPetMenuExpanded by remember(activeFloatingPet?.id) { mutableStateOf(false) }
|
||||
val activeBackgroundAvatar = remember(backgroundAvatarId, availablePets) {
|
||||
resolveBackgroundAvatar(backgroundAvatarId, availablePets)
|
||||
}
|
||||
val petSpeed by connectionViewModel.petSpeed.collectAsState()
|
||||
val petStabilize by connectionViewModel.petStabilize.collectAsState()
|
||||
val petRoamingEnabled by connectionViewModel.petRoamingEnabled.collectAsState()
|
||||
@@ -818,7 +832,7 @@ fun RelayApp() {
|
||||
CompositionLocalProvider(
|
||||
LocalSphereSkin provides activeSphereSkin,
|
||||
LocalAvailableSphereSkins provides availableSphereSkins,
|
||||
LocalAgentAvatar provides SphereAvatar,
|
||||
LocalAgentAvatar provides activeBackgroundAvatar,
|
||||
// Compatibility list for the existing Appearance picker during the
|
||||
// transition; new companion UI consumes LocalAvailablePets.
|
||||
LocalAvailableAvatars provides listOf(SphereAvatar) + availablePets,
|
||||
@@ -831,11 +845,23 @@ fun RelayApp() {
|
||||
LocalPetSafeAreaRegistry provides petSafeAreaRegistry,
|
||||
LocalAgentIconPath provides agentIconPath,
|
||||
) {
|
||||
// Dialogs and modal sheets use their own focused window. Treat that
|
||||
// focus handoff as an app-wide interaction layer so a dock-only pet on
|
||||
// any route cannot remain visible beneath modal chrome.
|
||||
PetInteractionLayer(
|
||||
owner = "platform-modal-window",
|
||||
active = platformModalOwnsPetLayer(
|
||||
windowFocused = LocalWindowInfo.current.isWindowFocused,
|
||||
petMenuExpanded = floatingPetMenuExpanded,
|
||||
),
|
||||
)
|
||||
HermesRelayTheme(
|
||||
appThemeId = appThemeId,
|
||||
themePreference = themePreference,
|
||||
fontScale = fontScale,
|
||||
appFontId = appFontId,
|
||||
accentHex = appearanceAccent,
|
||||
shapeId = appearanceShape,
|
||||
) {
|
||||
// Surface a crash report from a previous session, if any. Renders a
|
||||
// platform Dialog (own window) so tree position is z-order-agnostic;
|
||||
@@ -1051,6 +1077,22 @@ fun RelayApp() {
|
||||
val gatewayCurrentModel by chatViewModel.gatewayCurrentModel.collectAsState()
|
||||
val appReady by connectionViewModel.isReady.collectAsState()
|
||||
val initialChatSettled by chatViewModel.initialChatSettled.collectAsState()
|
||||
// Android sharesheet handoff: wait until the configured chat context is
|
||||
// settled, then ask ChatViewModel to own the new draft and composer
|
||||
// prefill. Navigation is presentation-only; no composable writes chat
|
||||
// stores or sends the shared text.
|
||||
LaunchedEffect(navController, onboardingCompleted, initialChatSettled) {
|
||||
if (!onboardingCompleted || !initialChatSettled) return@LaunchedEffect
|
||||
com.hermesandroid.relay.util.SharedTextRequest.pending.collect { request ->
|
||||
request ?: return@collect
|
||||
if (chatViewModel.openSharedTextDraft(request.text)) {
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
launchSingleTop = true
|
||||
}
|
||||
com.hermesandroid.relay.util.SharedTextRequest.consume(request.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The SAME readiness signal ChatScreen renders its "Connect Standard
|
||||
// Hermes" CTA from (chat client exists + reachable verdict). The gate
|
||||
// must release on this — releasing on the resolver's earlier
|
||||
@@ -1657,9 +1699,9 @@ fun RelayApp() {
|
||||
) { backStackEntry ->
|
||||
// Responsive bubble width based on screen width. The "Blend"
|
||||
// chat look favors wider bubbles: on compact phones the cap is
|
||||
// raised so long turns fill most of the row (binding on the
|
||||
// available width minus the assistant avatar gutter) instead
|
||||
// of wrapping early in a narrow column.
|
||||
// raised so long turns fill most of the row instead of
|
||||
// wrapping early in a narrow column. Assistant identity
|
||||
// stays in the group header and does not reduce this cap.
|
||||
val configuration = LocalConfiguration.current
|
||||
val screenWidthDp = configuration.screenWidthDp.dp
|
||||
val maxBubbleWidth = when {
|
||||
@@ -2475,6 +2517,7 @@ fun RelayApp() {
|
||||
connectionViewModel = connectionViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
onBrowsePetdex = { navController.navigate(Screen.PetdexBrowse.route) },
|
||||
onCreatePet = { navController.navigate(Screen.CustomPetGuide.route) },
|
||||
)
|
||||
}
|
||||
composable(Screen.PetdexBrowse.route) {
|
||||
@@ -2483,6 +2526,20 @@ fun RelayApp() {
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
composable(Screen.CustomPetGuide.route) {
|
||||
CustomPetGuideScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
onStartNewChat = { prompt ->
|
||||
chatViewModel.createNewChat()
|
||||
chatViewModel.stageComposerDraft(prompt)
|
||||
navController.navigate(Screen.Chat.route(openAgentSheet = false)) {
|
||||
popUpTo(Screen.Chat.route) { inclusive = false }
|
||||
launchSingleTop = true
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
composable(Screen.Analytics.route) {
|
||||
AnalyticsScreen(
|
||||
connectionViewModel = connectionViewModel,
|
||||
@@ -2670,6 +2727,7 @@ fun RelayApp() {
|
||||
onOpenAppearance = {
|
||||
navController.navigate(Screen.AppearanceSettings.route) { launchSingleTop = true }
|
||||
},
|
||||
onMenuExpandedChanged = { floatingPetMenuExpanded = it },
|
||||
onExitTerrainDebug = {
|
||||
petTerrainOverlayScope.launch {
|
||||
FeatureFlags.setPetTerrainOverlayEnabled(sphereContext, false)
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil3.compose.AsyncImage
|
||||
import com.hermesandroid.relay.R
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
@@ -28,6 +33,15 @@ fun AgentAvatarFace(name: String, letterStyle: TextStyle, modifier: Modifier = M
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
)
|
||||
} else if (name.equals("Hermes", ignoreCase = true)) {
|
||||
Image(
|
||||
painter = painterResource(R.drawable.splash_icon),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(2.dp),
|
||||
)
|
||||
} else {
|
||||
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
|
||||
@@ -332,7 +332,7 @@ private fun decodeGalleryBitmap(bytes: ByteArray): android.graphics.Bitmap? {
|
||||
sample *= 2
|
||||
}
|
||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
return decodeOrientedBitmap(bytes, options)
|
||||
}
|
||||
|
||||
private const val GALLERY_COLUMNS = 2
|
||||
|
||||
@@ -4,7 +4,6 @@ package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.audiofx.Visualizer
|
||||
import android.net.Uri
|
||||
@@ -697,7 +696,7 @@ private fun ImageBody(
|
||||
val decoded = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val bytes = attachmentBytes(context, attachment)
|
||||
bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }
|
||||
bytes?.let { decodeOrientedBitmap(it)?.asImageBitmap() }
|
||||
}.getOrNull()
|
||||
}
|
||||
if (decoded != null) bitmap = decoded else failed = true
|
||||
|
||||
@@ -304,10 +304,8 @@ private fun DataUrlChatImage(image: ChatInlineImage, maxWidth: Dp) {
|
||||
BitmapFactory.decodeByteArray(decoded.bytes, 0, decoded.bytes.size, bounds)
|
||||
val sample = inlineImageSampleSize(bounds.outWidth, bounds.outHeight)
|
||||
?: return@withInlineImageDecodeLock DataUrlImagePhase.Rejected
|
||||
val bitmap = BitmapFactory.decodeByteArray(
|
||||
val bitmap = decodeOrientedBitmap(
|
||||
decoded.bytes,
|
||||
0,
|
||||
decoded.bytes.size,
|
||||
BitmapFactory.Options().apply {
|
||||
inSampleSize = sample
|
||||
inPreferredConfig = android.graphics.Bitmap.Config.ARGB_8888
|
||||
@@ -482,7 +480,7 @@ private fun RelayServerImage(
|
||||
is ServerImageResult.Success -> {
|
||||
val bytes = result.bytes
|
||||
val bmp = runCatching {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
decodeOrientedBitmap(bytes)
|
||||
}.getOrNull()?.asImageBitmap()
|
||||
if (bmp != null) {
|
||||
putInlineImage(image.src, bmp, result.sensitive)
|
||||
|
||||
@@ -29,6 +29,8 @@ import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
@@ -58,8 +60,18 @@ 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.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusProperties
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
@@ -84,6 +96,7 @@ enum class ChatInputTrailing { SEND, VOICE, STOP, STEER, QUEUE }
|
||||
|
||||
private val ChatComposerShape = RoundedCornerShape(18.dp)
|
||||
private val ChatInputChipShape = RoundedCornerShape(12.dp)
|
||||
internal const val CHAT_INPUT_FIELD_TEST_TAG = "chat-input-field"
|
||||
|
||||
data class ChatInputPickerOption(
|
||||
val label: String,
|
||||
@@ -174,7 +187,14 @@ fun ChatInputBar(
|
||||
modifier: Modifier = Modifier,
|
||||
surfaceModifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
physicalEnterSends: Boolean = true,
|
||||
) {
|
||||
val canSubmit = enabled && trailing in setOf(
|
||||
ChatInputTrailing.SEND,
|
||||
ChatInputTrailing.STEER,
|
||||
ChatInputTrailing.QUEUE,
|
||||
)
|
||||
|
||||
// Keep the last caption around so the AnimatedVisibility exit doesn't
|
||||
// flash an empty line while collapsing.
|
||||
var lastCaption by remember { mutableStateOf<String?>(null) }
|
||||
@@ -203,18 +223,57 @@ fun ChatInputBar(
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
// Caption row — correct/queue hinting, single line, no buttons.
|
||||
// Correction and queueing are materially different actions. Keep the
|
||||
// explanation, but lead with a visible state pill so the distinction
|
||||
// does not depend on the trailing icon or accent color alone.
|
||||
AnimatedVisibility(visible = caption != null) {
|
||||
Text(
|
||||
text = caption ?: lastCaption.orEmpty(),
|
||||
style = relayMetadataStyle(),
|
||||
color = if (trailing == ChatInputTrailing.STEER) {
|
||||
MaterialTheme.colorScheme.tertiary.copy(alpha = 0.9f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
modifier = Modifier.padding(horizontal = 20.dp, vertical = 2.dp),
|
||||
)
|
||||
val detail = caption ?: lastCaption.orEmpty()
|
||||
val actionLabel = when (trailing) {
|
||||
ChatInputTrailing.STEER -> stringResource(R.string.chat_input_steer_response)
|
||||
ChatInputTrailing.QUEUE -> stringResource(R.string.chat_input_queue_message)
|
||||
else -> null
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp, vertical = 2.dp)
|
||||
.semantics {
|
||||
liveRegion = LiveRegionMode.Polite
|
||||
contentDescription = listOfNotNull(actionLabel, detail)
|
||||
.joinToString(separator = ". ")
|
||||
},
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (actionLabel != null) {
|
||||
Text(
|
||||
text = actionLabel,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (trailing == ChatInputTrailing.STEER) {
|
||||
MaterialTheme.colorScheme.onTertiaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSecondaryContainer
|
||||
},
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(999.dp))
|
||||
.background(
|
||||
if (trailing == ChatInputTrailing.STEER) {
|
||||
MaterialTheme.colorScheme.tertiaryContainer
|
||||
} else {
|
||||
MaterialTheme.colorScheme.secondaryContainer
|
||||
},
|
||||
)
|
||||
.padding(horizontal = 8.dp, vertical = 3.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = detail,
|
||||
style = relayMetadataStyle(),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Voice hint pill — floats above the trailing button.
|
||||
@@ -290,9 +349,44 @@ fun ChatInputBar(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 34.dp)
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp),
|
||||
.padding(horizontal = 8.dp, vertical = 4.dp)
|
||||
// Keep directional keys inside the editor. Compose's
|
||||
// BasicTextField owns normal caret/selection movement;
|
||||
// cancelling focus traversal prevents a boundary arrow
|
||||
// from jumping to a neighboring composer control.
|
||||
.focusProperties {
|
||||
left = FocusRequester.Cancel
|
||||
right = FocusRequester.Cancel
|
||||
up = FocusRequester.Cancel
|
||||
down = FocusRequester.Cancel
|
||||
}
|
||||
.onPreviewKeyEvent { event ->
|
||||
val native = event.nativeKeyEvent
|
||||
val isEnter = native.keyCode == android.view.KeyEvent.KEYCODE_ENTER ||
|
||||
native.keyCode == android.view.KeyEvent.KEYCODE_NUMPAD_ENTER
|
||||
val isSubmitShortcut = native.isCtrlPressed || native.isMetaPressed
|
||||
if (native.action != android.view.KeyEvent.ACTION_DOWN || !isEnter) {
|
||||
false
|
||||
} else if (isSubmitShortcut || (physicalEnterSends && !native.isShiftPressed)) {
|
||||
if (canSubmit) onSend()
|
||||
true
|
||||
} else {
|
||||
// Shift+Enter always inserts a newline. When
|
||||
// Enter is configured for newlines, the plain
|
||||
// key also stays owned by BasicTextField.
|
||||
false
|
||||
}
|
||||
}
|
||||
.testTag(CHAT_INPUT_FIELD_TEST_TAG),
|
||||
maxLines = 5,
|
||||
enabled = enabled,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
capitalization = KeyboardCapitalization.Sentences,
|
||||
imeAction = ImeAction.Send,
|
||||
),
|
||||
keyboardActions = KeyboardActions(
|
||||
onSend = { if (canSubmit) onSend() },
|
||||
),
|
||||
textStyle = MaterialTheme.typography.bodyLarge.copy(
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
@@ -314,7 +408,7 @@ fun ChatInputBar(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 40.dp),
|
||||
.heightIn(min = 48.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
@@ -324,7 +418,7 @@ fun ChatInputBar(
|
||||
Box {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(38.dp)
|
||||
.size(48.dp)
|
||||
.clip(CircleShape)
|
||||
.combinedClickable(
|
||||
onClick = { attachMenuExpanded = true },
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
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.Close
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ColorScheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ChatQuoteReference
|
||||
|
||||
internal data class ChatQuoteReferenceColors(
|
||||
val background: Color,
|
||||
val author: Color,
|
||||
val excerpt: Color,
|
||||
val accent: Color,
|
||||
)
|
||||
|
||||
internal fun chatQuoteReferenceColors(colorScheme: ColorScheme) = ChatQuoteReferenceColors(
|
||||
background = colorScheme.surfaceContainerHigh,
|
||||
author = colorScheme.onSurface,
|
||||
excerpt = colorScheme.onSurfaceVariant,
|
||||
accent = colorScheme.primary,
|
||||
)
|
||||
|
||||
/** Attachment-like quote reference used in both the composer and sent bubbles. */
|
||||
@Composable
|
||||
fun ChatQuoteReferenceChip(
|
||||
reference: ChatQuoteReference,
|
||||
modifier: Modifier = Modifier,
|
||||
onOpenOriginal: (() -> Unit)? = null,
|
||||
onRemove: (() -> Unit)? = null,
|
||||
) {
|
||||
val openDescription = stringResource(R.string.chat_quote_open, reference.authorLabel)
|
||||
val colors = chatQuoteReferenceColors(MaterialTheme.colorScheme)
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
color = colors.background,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.then(
|
||||
onOpenOriginal?.let { open ->
|
||||
Modifier.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = openDescription,
|
||||
onClick = open,
|
||||
)
|
||||
} ?: Modifier,
|
||||
)
|
||||
.semantics { contentDescription = "$openDescription. ${reference.excerpt}" }
|
||||
.padding(start = 7.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.width(3.dp)
|
||||
.height(32.dp)
|
||||
.clip(RoundedCornerShape(99.dp))
|
||||
.background(colors.accent),
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.padding(horizontal = 8.dp, vertical = 5.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "@${reference.authorLabel}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.author,
|
||||
)
|
||||
Text(
|
||||
text = reference.excerpt,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = colors.excerpt,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (onRemove != null) {
|
||||
IconButton(
|
||||
onClick = onRemove,
|
||||
modifier = Modifier.size(48.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.chat_quote_remove),
|
||||
tint = colors.excerpt,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -684,7 +684,6 @@ fun RelayInfoSheet(
|
||||
// the Profile section footer spells out the override.
|
||||
|
||||
private enum class AgentPassportPicker {
|
||||
Profile,
|
||||
Personality,
|
||||
Model,
|
||||
Reasoning,
|
||||
@@ -762,6 +761,7 @@ fun AgentInfoSheet(
|
||||
|
||||
var selectedTab by remember { mutableStateOf(0) }
|
||||
var activePicker by remember { mutableStateOf<AgentPassportPicker?>(null) }
|
||||
var showProfileSwitcher by remember { mutableStateOf(false) }
|
||||
var showIdentityEditor by remember { mutableStateOf(false) }
|
||||
var showProfileManager by remember { mutableStateOf(false) }
|
||||
|
||||
@@ -771,6 +771,20 @@ fun AgentInfoSheet(
|
||||
val currentSession = remember(sessions, currentSessionId) {
|
||||
sessions.firstOrNull { it.sessionId == currentSessionId }
|
||||
}
|
||||
val sessionModelState = resolveSessionModelUiState(
|
||||
hasSession = currentSessionId != null,
|
||||
pendingModel = selectedModel,
|
||||
pendingProvider = selectedProvider,
|
||||
gatewayModel = gatewayModel,
|
||||
gatewayProvider = gatewayProvider,
|
||||
persistedSessionModel = currentSession?.model,
|
||||
profileDefaultModel = resolvedProfile?.model,
|
||||
serverDefaultModel = serverModel,
|
||||
)
|
||||
val sessionPickerProvider = sessionModelState.pickerProvider
|
||||
?: sessionModelState.pickerModel?.let { model ->
|
||||
modelProviders.singleOrNull { model in it.models }?.slug
|
||||
}
|
||||
val agentName = AgentDisplay.agentName(
|
||||
profile = resolvedProfile,
|
||||
selectedPersonality = selectedPersonality,
|
||||
@@ -782,25 +796,22 @@ fun AgentInfoSheet(
|
||||
AgentDisplay.profileDisplayName(it) ?: it.name
|
||||
} ?: stringResource(R.string.conn_info_server_default)
|
||||
val serverDefaultLabel = stringResource(R.string.conn_info_server_default)
|
||||
val modelLabel = AgentDisplay.displayModelName(selectedModel ?: gatewayModel)
|
||||
?: AgentDisplay.displayModelName(resolvedProfile?.model)
|
||||
?: AgentDisplay.displayModelName(serverModel)
|
||||
val modelLabel = AgentDisplay.displayModelName(sessionModelState.model)
|
||||
?: serverDefaultLabel
|
||||
val serverDefaultModelLabel = AgentDisplay.displayModelName(serverModel)
|
||||
?: AgentDisplay.displayModelName(resolvedProfile?.model)
|
||||
val providerLabel = modelProviders
|
||||
.firstOrNull { it.slug.equals(gatewayProvider, ignoreCase = true) }
|
||||
.firstOrNull { it.slug.equals(sessionModelState.provider, ignoreCase = true) }
|
||||
?.name
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: gatewayProvider.takeIf { it.isNotBlank() }
|
||||
val sessionModelLabel = AgentDisplay.displayModelName(currentSession?.model)
|
||||
?: modelLabel
|
||||
val sessionProviderLabel = currentSession?.model
|
||||
?: sessionModelState.provider
|
||||
val sessionModelLabel = modelLabel
|
||||
val sessionProviderLabel = sessionModelState.model
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?.let { sessionModel ->
|
||||
modelProviders.firstOrNull { sessionModel in it.models }?.name
|
||||
}
|
||||
?: providerLabel.takeIf { currentSession?.model.isNullOrBlank() }
|
||||
?: providerLabel
|
||||
val connected = chatReady
|
||||
val resolvedPresence = resolvedProfile?.let {
|
||||
ProfilePresenceResolver.resolve(it, connected)
|
||||
@@ -851,6 +862,8 @@ fun AgentInfoSheet(
|
||||
agentProfiles,
|
||||
selectedModel,
|
||||
selectedProvider,
|
||||
sessionModelState,
|
||||
sessionPickerProvider,
|
||||
modelLabel,
|
||||
unavailableModelLabel,
|
||||
modelNeedsSetupLabel,
|
||||
@@ -871,7 +884,7 @@ fun AgentInfoSheet(
|
||||
label = serverDefaultLabel,
|
||||
value = null,
|
||||
secondary = serverDefaultModelLabel,
|
||||
selected = selectedModel == null,
|
||||
selected = sessionModelState.inheritsProfileDefault,
|
||||
),
|
||||
)
|
||||
modelProviders
|
||||
@@ -891,8 +904,8 @@ fun AgentInfoSheet(
|
||||
provider.warning ?: modelNeedsSetupLabel
|
||||
else -> null
|
||||
},
|
||||
selected = selectedModel == model &&
|
||||
selectedProvider.equals(provider.slug, ignoreCase = true),
|
||||
selected = sessionModelState.pickerModel == model &&
|
||||
sessionPickerProvider.equals(provider.slug, ignoreCase = true),
|
||||
enabled = !unavailable,
|
||||
),
|
||||
)
|
||||
@@ -908,7 +921,7 @@ fun AgentInfoSheet(
|
||||
value = model.id,
|
||||
group = "Routes",
|
||||
secondary = model.routeDetail,
|
||||
selected = selectedModel == model.id,
|
||||
selected = sessionModelState.pickerModel == model.id,
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -916,10 +929,10 @@ fun AgentInfoSheet(
|
||||
}
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
chatViewModel.refreshModelOptions()
|
||||
chatViewModel.refreshModelOptions(catalogOnly = true)
|
||||
chatViewModel.refreshApprovalMode()
|
||||
chatViewModel.refreshPersonalities()
|
||||
chatViewModel.refreshModels()
|
||||
chatViewModel.refreshModels(catalogOnly = true)
|
||||
connectionViewModel.refreshDashboardProfiles()
|
||||
}
|
||||
|
||||
@@ -945,10 +958,7 @@ fun AgentInfoSheet(
|
||||
presence = resolvedPresence,
|
||||
hasSoul = resolvedProfile?.hasSoul == true,
|
||||
skillCount = resolvedProfile?.skillCount ?: 0,
|
||||
transportLabel = transportFriendlyName(sessionTransport.type),
|
||||
sessionLabel = currentSessionId?.take(8) ?: "—",
|
||||
contextLabel = contextLabel,
|
||||
onProfileClick = { activePicker = AgentPassportPicker.Profile },
|
||||
onProfileClick = { showProfileSwitcher = true },
|
||||
)
|
||||
|
||||
if (showIdentityEditor) {
|
||||
@@ -982,7 +992,7 @@ fun AgentInfoSheet(
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
text = stringResource(R.string.conn_info_active_configuration),
|
||||
text = stringResource(R.string.conn_info_session_title),
|
||||
modifier = Modifier.padding(
|
||||
start = 18.dp,
|
||||
top = 17.dp,
|
||||
@@ -992,25 +1002,13 @@ fun AgentInfoSheet(
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
PassportConfigRow(
|
||||
icon = Icons.Filled.Person,
|
||||
title = stringResource(R.string.conn_info_personality_title),
|
||||
value = AgentDisplay.personalityLabel(
|
||||
selectedPersonality,
|
||||
defaultPersonality,
|
||||
),
|
||||
expanded = false,
|
||||
enabled = !isStreaming,
|
||||
onClick = { activePicker = AgentPassportPicker.Personality },
|
||||
)
|
||||
PassportDivider()
|
||||
PassportConfigRow(
|
||||
icon = Icons.Filled.ViewInAr,
|
||||
title = stringResource(R.string.conn_info_model_title),
|
||||
value = selectedModel ?: if (modelLabel == serverDefaultLabel) {
|
||||
serverDefaultLabel
|
||||
} else {
|
||||
value = if (sessionModelState.inheritsProfileDefault) {
|
||||
stringResource(R.string.conn_info_server_default_model, modelLabel)
|
||||
} else {
|
||||
modelLabel
|
||||
},
|
||||
expanded = false,
|
||||
enabled = !isStreaming,
|
||||
@@ -1034,6 +1032,44 @@ fun AgentInfoSheet(
|
||||
}
|
||||
}
|
||||
|
||||
// Upstream personality changes persist to the active profile
|
||||
// while also applying to the live session. Keep that control
|
||||
// visibly separate from the session-only model/effort card so
|
||||
// it cannot be mistaken for an ephemeral override.
|
||||
Surface(
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
border = androidx.compose.foundation.BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f),
|
||||
),
|
||||
) {
|
||||
Column {
|
||||
Text(
|
||||
text = stringResource(R.string.conn_info_profile),
|
||||
modifier = Modifier.padding(
|
||||
start = 18.dp,
|
||||
top = 17.dp,
|
||||
end = 18.dp,
|
||||
bottom = 4.dp,
|
||||
),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
PassportConfigRow(
|
||||
icon = Icons.Filled.Person,
|
||||
title = stringResource(R.string.conn_info_personality_title),
|
||||
value = AgentDisplay.personalityLabel(
|
||||
selectedPersonality,
|
||||
defaultPersonality,
|
||||
),
|
||||
expanded = false,
|
||||
enabled = !isStreaming,
|
||||
onClick = { activePicker = AgentPassportPicker.Personality },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
AgentPassportSafetyCard(
|
||||
approvalMode = approvalMode,
|
||||
approvalCapability = approvalCapability,
|
||||
@@ -1155,49 +1191,6 @@ fun AgentInfoSheet(
|
||||
}
|
||||
|
||||
when (activePicker) {
|
||||
AgentPassportPicker.Profile -> {
|
||||
val selectedProfileKey = AgentDisplay.profileSessionKey(selectedProfile?.name)
|
||||
val visibleProfileKeys = ProfilePresentationPolicy.visibleKeys(
|
||||
profiles = agentProfiles,
|
||||
presentation = profilePresentation,
|
||||
selectedKey = selectedProfileKey,
|
||||
)
|
||||
val options = visibleProfileKeys.mapNotNull { profileKey ->
|
||||
if (profileKey == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY) {
|
||||
ChatInputPickerOption(
|
||||
label = serverDefaultLabel,
|
||||
value = null,
|
||||
secondary = AgentDisplay.profileDisplayName(resolvedProfile),
|
||||
selected = selectedProfile == null,
|
||||
enabled = !isProfileLocked && profileSwitchEnabled,
|
||||
)
|
||||
} else {
|
||||
agentProfiles.firstOrNull { it.name == profileKey }?.let { profile ->
|
||||
ChatInputPickerOption(
|
||||
label = AgentDisplay.profileDisplayName(profile)
|
||||
?: profile.name.replaceFirstChar { it.uppercase() },
|
||||
value = profile.name,
|
||||
secondary = profile.model.takeIf { it.isNotBlank() },
|
||||
selected = selectedProfile?.name == profile.name,
|
||||
enabled = !isProfileLocked && profileSwitchEnabled,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
OptionPickerSheet(
|
||||
title = stringResource(R.string.conn_info_profile),
|
||||
options = options,
|
||||
onSelect = { option ->
|
||||
val profile = option.value?.let { name ->
|
||||
agentProfiles.firstOrNull { it.name == name }
|
||||
}
|
||||
connectionViewModel.selectProfile(profile)
|
||||
chatViewModel.activateGatewayProfile(profile)
|
||||
activePicker = null
|
||||
},
|
||||
onDismiss = { activePicker = null },
|
||||
)
|
||||
}
|
||||
AgentPassportPicker.Personality -> OptionPickerSheet(
|
||||
title = stringResource(R.string.conn_info_personality_title),
|
||||
options = buildList {
|
||||
@@ -1228,7 +1221,9 @@ fun AgentInfoSheet(
|
||||
AgentPassportPicker.Model -> ModelPickerSheet(
|
||||
options = passportModelOptions,
|
||||
refreshing = modelOptionsRefreshing,
|
||||
onRefresh = { chatViewModel.refreshModelOptions(refresh = true) },
|
||||
onRefresh = {
|
||||
chatViewModel.refreshModelOptions(refresh = true, catalogOnly = true)
|
||||
},
|
||||
onSelect = { option ->
|
||||
activePicker = null
|
||||
if (option.provider == null && apiModelOptions.any { it.id == option.value }) {
|
||||
@@ -1274,6 +1269,31 @@ fun AgentInfoSheet(
|
||||
null -> Unit
|
||||
}
|
||||
|
||||
if (showProfileSwitcher) {
|
||||
ProfileSwitcherSheet(
|
||||
connectionViewModel = connectionViewModel,
|
||||
profiles = agentProfiles,
|
||||
selectedProfile = selectedProfile,
|
||||
resolvedProfile = resolvedProfile,
|
||||
presentation = profilePresentation,
|
||||
isProfileLocked = isProfileLocked,
|
||||
switchEnabled = profileSwitchEnabled,
|
||||
onSelect = { profile ->
|
||||
if (AgentDisplay.profileSessionKey(profile?.name) !=
|
||||
AgentDisplay.profileSessionKey(selectedProfile?.name)
|
||||
) {
|
||||
connectionViewModel.selectProfile(profile)
|
||||
chatViewModel.activateGatewayProfile(profile)
|
||||
}
|
||||
},
|
||||
onManageDisplay = {
|
||||
showProfileSwitcher = false
|
||||
showProfileManager = true
|
||||
},
|
||||
onDismiss = { showProfileSwitcher = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (showProfileManager) {
|
||||
ProfileDisplayManagerDialog(
|
||||
profiles = agentProfiles,
|
||||
@@ -1303,11 +1323,11 @@ internal fun AgentPassportSheetHost(
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = onDismiss,
|
||||
sheetState = sheetState,
|
||||
// Use Material's gesture owner instead of custom pointer input. The
|
||||
// verticalScroll child consumes downward movement until its top
|
||||
// boundary, then hands the remainder to the sheet; Material also
|
||||
// follows the platform animator scale for reduced-motion users.
|
||||
sheetGesturesEnabled = true,
|
||||
// A full-height sheet and its long verticalScroll child otherwise
|
||||
// compete for the same drag at the content boundaries. On some devices
|
||||
// that repeatedly settles/re-expands the sheet and produces a visible
|
||||
// vibration at the bottom. Close and system Back remain explicit.
|
||||
sheetGesturesEnabled = false,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -1441,9 +1461,6 @@ private fun AgentPassportHeader(
|
||||
presence: ProfilePresence?,
|
||||
hasSoul: Boolean,
|
||||
skillCount: Int,
|
||||
transportLabel: String,
|
||||
sessionLabel: String,
|
||||
contextLabel: String,
|
||||
onProfileClick: () -> Unit,
|
||||
) {
|
||||
val brand = LocalBrand.current
|
||||
@@ -1461,18 +1478,9 @@ private fun AgentPassportHeader(
|
||||
}
|
||||
}
|
||||
val identityMetadata = listOfNotNull(
|
||||
providerLabel,
|
||||
stringResource(R.string.conn_info_soul).takeIf { hasSoul },
|
||||
stringResource(R.string.conn_info_skills_count, skillCount).takeIf { skillCount > 0 },
|
||||
).joinToString(" · ")
|
||||
val connectionValue = listOf(
|
||||
transportLabel,
|
||||
if (connected) {
|
||||
stringResource(R.string.conn_info_connected)
|
||||
} else {
|
||||
stringResource(R.string.conn_info_disconnected)
|
||||
},
|
||||
).joinToString(" · ")
|
||||
Surface(
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainer,
|
||||
@@ -1565,7 +1573,7 @@ private fun AgentPassportHeader(
|
||||
) {
|
||||
Column(modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.conn_info_active_profile).uppercase(),
|
||||
text = stringResource(R.string.profile_shelf_switch_agent).uppercase(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
@@ -1607,40 +1615,17 @@ private fun AgentPassportHeader(
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_model_title),
|
||||
value = modelLabel,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PassportTechnicalDivider(height = 44.dp)
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_connection),
|
||||
value = connectionValue,
|
||||
valueColor = if (connected) brand.green else MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
Row(modifier = Modifier.fillMaxWidth()) {
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_session_title),
|
||||
value = sessionLabel,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PassportTechnicalDivider(height = 42.dp)
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_context),
|
||||
value = contextLabel,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PassportTechnicalDivider(height = 42.dp)
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_transport),
|
||||
value = transportLabel,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.voice_test_label_provider),
|
||||
value = providerLabel ?: "—",
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
PassportTechnicalField(
|
||||
label = stringResource(R.string.conn_info_model_title),
|
||||
value = modelLabel,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1651,6 +1636,7 @@ private fun PassportTechnicalField(
|
||||
value: String,
|
||||
modifier: Modifier = Modifier,
|
||||
valueColor: Color = MaterialTheme.colorScheme.onSurface,
|
||||
maxLines: Int = 1,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.padding(horizontal = 8.dp),
|
||||
@@ -1666,22 +1652,12 @@ private fun PassportTechnicalField(
|
||||
text = value,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = valueColor,
|
||||
maxLines = 1,
|
||||
maxLines = maxLines,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PassportTechnicalDivider(height: Dp) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.height(height)
|
||||
.widthIn(min = 1.dp, max = 1.dp)
|
||||
.background(MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AgentPassportTabs(
|
||||
selected: Int,
|
||||
@@ -2290,7 +2266,7 @@ private fun LegacyAgentInfoSheet(
|
||||
|
||||
// Pull the gateway's curated provider/model list (model.options) when the
|
||||
// sheet opens — the real switchable models, grouped by provider.
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshModelOptions() }
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshModelOptions(catalogOnly = true) }
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshApprovalMode() }
|
||||
// Re-pull server-supplied personalities (list + default + active) on open so
|
||||
// a server-side change shows without an app reload.
|
||||
@@ -2298,7 +2274,7 @@ private fun LegacyAgentInfoSheet(
|
||||
// Re-pull the SSE-fallback model list + skill catalog on open so server-side
|
||||
// changes surface without an app reload (gateway model groups are covered by
|
||||
// refreshModelOptions above; skills feed the command palette).
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshModels() }
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshModels(catalogOnly = true) }
|
||||
LaunchedEffect(Unit) { chatViewModel.refreshSkills() }
|
||||
// Pull the host's agent profiles from the dashboard so they appear in the
|
||||
// Profile picker even on a dashboard-only (non-relay) connection.
|
||||
@@ -2503,7 +2479,7 @@ private fun LegacyAgentInfoSheet(
|
||||
// "default" so "Server default" vs "default" would be
|
||||
// otherwise indistinguishable.
|
||||
val serverDefaultProfile = agentProfiles
|
||||
.firstOrNull { AgentDisplay.isServerDefaultAlias(it.name) }
|
||||
.firstOrNull { it.name.equals("default", ignoreCase = true) }
|
||||
val selectedKey = AgentDisplay.profileSessionKey(selectedProfile?.name)
|
||||
val visibleProfileKeys = ProfilePresentationPolicy
|
||||
.visibleKeys(agentProfiles, profilePresentation, selectedKey)
|
||||
@@ -2526,8 +2502,7 @@ private fun LegacyAgentInfoSheet(
|
||||
val lockedDisplayName = when {
|
||||
lockedProfileName == null ->
|
||||
stringResource(R.string.conn_info_server_default)
|
||||
AgentDisplay.isServerDefaultAlias(lockedProfileName) ||
|
||||
lockedProfileName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY ->
|
||||
lockedProfileName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY ->
|
||||
stringResource(R.string.conn_info_server_default)
|
||||
else ->
|
||||
agentProfiles
|
||||
@@ -3615,7 +3590,7 @@ private fun LegacyAgentInfoSheet(
|
||||
// --- AgentInfoSheet helpers ----------------------------------------------
|
||||
|
||||
@Composable
|
||||
private fun ProfileDisplayManagerDialog(
|
||||
internal fun ProfileDisplayManagerDialog(
|
||||
profiles: List<Profile>,
|
||||
presentation: ProfilePresentation,
|
||||
selectedProfileName: String?,
|
||||
|
||||
@@ -19,6 +19,7 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
@@ -319,6 +320,31 @@ internal fun shouldDockFloatingPet(
|
||||
roamingAllowed: Boolean,
|
||||
): Boolean = !roamingEnabled || !roamingAllowed
|
||||
|
||||
/**
|
||||
* Chat gives a deliberately paused companion one stable home: the live
|
||||
* composer rail. Other routes retain the user's saved free-form edge home, and
|
||||
* active roaming keeps its richer settled-chat habitat hierarchy.
|
||||
*/
|
||||
internal fun floatingPetHomePoint(
|
||||
route: String?,
|
||||
roamingEnabled: Boolean,
|
||||
roamingAllowed: Boolean,
|
||||
manualHomePoint: PetPoint,
|
||||
roamingHomePoint: PetPoint?,
|
||||
pausedChatDockPoint: PetPoint?,
|
||||
): PetPoint = when {
|
||||
route == "chat" && roamingAllowed && !roamingEnabled && pausedChatDockPoint != null -> {
|
||||
pausedChatDockPoint
|
||||
}
|
||||
roamingEnabled && roamingAllowed -> roamingHomePoint ?: manualHomePoint
|
||||
else -> manualHomePoint
|
||||
}
|
||||
|
||||
internal fun floatingPetAllowsVerticalMoveActions(
|
||||
route: String?,
|
||||
roamingEnabled: Boolean,
|
||||
): Boolean = route != "chat" || roamingEnabled
|
||||
|
||||
internal fun petRailSupportingPoint(
|
||||
rails: Iterable<PetRoamingRail>,
|
||||
point: PetPoint,
|
||||
@@ -465,10 +491,19 @@ fun FloatingPetCompanion(
|
||||
onResetPlacement: () -> Unit,
|
||||
onHide: () -> Unit,
|
||||
onOpenAppearance: () -> Unit,
|
||||
onMenuExpandedChanged: (Boolean) -> Unit = {},
|
||||
onExitTerrainDebug: () -> Unit = {},
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var menuExpanded by remember(pet.id) { mutableStateOf(false) }
|
||||
val latestOnMenuExpandedChanged by rememberUpdatedState(onMenuExpandedChanged)
|
||||
fun setMenuExpanded(expanded: Boolean) {
|
||||
menuExpanded = expanded
|
||||
onMenuExpandedChanged(expanded)
|
||||
}
|
||||
DisposableEffect(pet.id) {
|
||||
onDispose { latestOnMenuExpandedChanged(false) }
|
||||
}
|
||||
var dragging by remember(pet.id) { mutableStateOf(false) }
|
||||
var draggedPoint by remember(pet.id) { mutableStateOf<PetPoint?>(null) }
|
||||
var pendingDrop by remember(pet.id) { mutableStateOf<PendingPetDrop?>(null) }
|
||||
@@ -834,30 +869,47 @@ fun FloatingPetCompanion(
|
||||
val requested = placement.sanitized().resolve(safeBounds, petLayoutDirection)
|
||||
projectIntoSafeBounds(requested, safeBounds, registeredObstacles) ?: requested
|
||||
}
|
||||
val homeRail = remember(roamingRails, manualHomePoint, settledHabitat) {
|
||||
val composerHomeRail = remember(composerRails, manualHomePoint) {
|
||||
val distanceToHome: (PetRoamingRail) -> Float = { rail ->
|
||||
rail.bounds.clamp(manualHomePoint).distanceSquaredTo(manualHomePoint)
|
||||
}
|
||||
composerRails.minByOrNull(distanceToHome)
|
||||
}
|
||||
val homeRail = remember(roamingRails, manualHomePoint, settledHabitat, composerHomeRail) {
|
||||
val distanceToHome: (PetRoamingRail) -> Float = { rail ->
|
||||
rail.bounds.clamp(manualHomePoint).distanceSquaredTo(manualHomePoint)
|
||||
}
|
||||
settledHabitat?.rail
|
||||
?: roamingRails.filter { it.perchKey == CHAT_PET_WALK_REGION }.minByOrNull(distanceToHome)
|
||||
?: composerHomeRail
|
||||
?: roamingRails.minByOrNull(distanceToHome)
|
||||
}
|
||||
fun pointAtPlacementEdge(rail: PetSafeBounds): PetPoint {
|
||||
val xAtEdge = if (
|
||||
(placement.edge == PetLogicalEdge.Start) == (petLayoutDirection == PetLayoutDirection.Ltr)
|
||||
) rail.left else rail.right
|
||||
return PetPoint(xAtEdge, rail.top)
|
||||
}
|
||||
val roamingHomePoint = remember(placement.edge, homeRail, petLayoutDirection) {
|
||||
homeRail?.bounds?.let { rail ->
|
||||
homeRail?.bounds?.let(::pointAtPlacementEdge)
|
||||
}
|
||||
val pausedChatDockPoint = remember(placement.edge, composerHomeRail, petLayoutDirection) {
|
||||
composerHomeRail?.bounds?.let { rail ->
|
||||
val xAtEdge = if (
|
||||
(placement.edge == PetLogicalEdge.Start) == (petLayoutDirection == PetLayoutDirection.Ltr)
|
||||
) rail.left else rail.right
|
||||
PetPoint(xAtEdge, rail.top)
|
||||
}
|
||||
}
|
||||
// Enabling roaming explicitly docks onto the screen-owned safe rail. A
|
||||
// manual drag or vertical accessibility action pauses roaming first, so the
|
||||
// persisted free-form placement remains visible and authoritative.
|
||||
val homePoint = if (roamingEnabled && roamingAllowed) {
|
||||
roamingHomePoint ?: manualHomePoint
|
||||
} else {
|
||||
manualHomePoint
|
||||
}
|
||||
// Active roaming uses screen-owned terrain. Paused Chat deliberately uses
|
||||
// the composer rail; other routes retain the persisted free-form edge home.
|
||||
val homePoint = floatingPetHomePoint(
|
||||
route = route,
|
||||
roamingEnabled = roamingEnabled,
|
||||
roamingAllowed = roamingAllowed,
|
||||
manualHomePoint = manualHomePoint,
|
||||
roamingHomePoint = roamingHomePoint,
|
||||
pausedChatDockPoint = pausedChatDockPoint,
|
||||
)
|
||||
|
||||
val heldProgress by animateFloatAsState(
|
||||
targetValue = if (dragging) 1f else 0f,
|
||||
@@ -1606,7 +1658,7 @@ fun FloatingPetCompanion(
|
||||
// Chat roaming owns a measured composer rail. Publishing before that rail
|
||||
// exists lets initialization race route registration and can strand the
|
||||
// pet on transient fallback geometry until direct manipulation.
|
||||
val initialTerrainReady = route != "chat" || !roamingEnabled || !roamingAllowed ||
|
||||
val initialTerrainReady = route != "chat" || !roamingAllowed ||
|
||||
composerRails.isNotEmpty()
|
||||
LaunchedEffect(
|
||||
pet.id,
|
||||
@@ -2350,31 +2402,43 @@ fun FloatingPetCompanion(
|
||||
enabled = floatingPetAcceptsPointerInput(positioned, surfaceScrolling),
|
||||
) {
|
||||
tapReactionNonce += 1
|
||||
menuExpanded = true
|
||||
setMenuExpanded(true)
|
||||
}
|
||||
.semantics(mergeDescendants = true) {
|
||||
role = Role.Button
|
||||
contentDescription = companionDescription
|
||||
stateDescription = stateLabel
|
||||
customActions = listOf(
|
||||
CustomAccessibilityAction(moveStartLabel) {
|
||||
customActions = buildList {
|
||||
add(CustomAccessibilityAction(moveStartLabel) {
|
||||
onPlacementChanged(placement.copy(edge = PetLogicalEdge.Start)); true
|
||||
},
|
||||
CustomAccessibilityAction(moveEndLabel) {
|
||||
})
|
||||
add(CustomAccessibilityAction(moveEndLabel) {
|
||||
onPlacementChanged(placement.copy(edge = PetLogicalEdge.End)); true
|
||||
},
|
||||
CustomAccessibilityAction(moveUpLabel) {
|
||||
if (roamingEnabled) onRoamingEnabledChanged(false)
|
||||
onPlacementChanged(placement.copy(verticalFraction = placement.verticalFraction - 0.15f)); true
|
||||
},
|
||||
CustomAccessibilityAction(moveDownLabel) {
|
||||
if (roamingEnabled) onRoamingEnabledChanged(false)
|
||||
onPlacementChanged(placement.copy(verticalFraction = placement.verticalFraction + 0.15f)); true
|
||||
},
|
||||
CustomAccessibilityAction(resetLabel) { onResetPlacement(); true },
|
||||
CustomAccessibilityAction(appearanceLabel) { onOpenAppearance(); true },
|
||||
CustomAccessibilityAction(hideLabel) { onHide(); true },
|
||||
)
|
||||
})
|
||||
// A paused Chat pet has no meaningful vertical free-form
|
||||
// coordinate: it is deliberately attached to the composer.
|
||||
// Do not expose TalkBack actions that would appear to do
|
||||
// nothing; start/end still choose the dock corner.
|
||||
if (floatingPetAllowsVerticalMoveActions(route, roamingEnabled)) {
|
||||
add(CustomAccessibilityAction(moveUpLabel) {
|
||||
if (roamingEnabled) onRoamingEnabledChanged(false)
|
||||
onPlacementChanged(
|
||||
placement.copy(verticalFraction = placement.verticalFraction - 0.15f),
|
||||
)
|
||||
true
|
||||
})
|
||||
add(CustomAccessibilityAction(moveDownLabel) {
|
||||
if (roamingEnabled) onRoamingEnabledChanged(false)
|
||||
onPlacementChanged(
|
||||
placement.copy(verticalFraction = placement.verticalFraction + 0.15f),
|
||||
)
|
||||
true
|
||||
})
|
||||
}
|
||||
add(CustomAccessibilityAction(resetLabel) { onResetPlacement(); true })
|
||||
add(CustomAccessibilityAction(appearanceLabel) { onOpenAppearance(); true })
|
||||
add(CustomAccessibilityAction(hideLabel) { onHide(); true })
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
@@ -2419,7 +2483,7 @@ fun FloatingPetCompanion(
|
||||
|
||||
DropdownMenu(
|
||||
expanded = menuExpanded,
|
||||
onDismissRequest = { menuExpanded = false },
|
||||
onDismissRequest = { setMenuExpanded(false) },
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("${pet.label} · $stateLabel", color = MaterialTheme.colorScheme.onSurfaceVariant) },
|
||||
@@ -2436,28 +2500,28 @@ fun FloatingPetCompanion(
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
menuExpanded = false
|
||||
setMenuExpanded(false)
|
||||
onRoamingEnabledChanged(!roamingEnabled)
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(resetLabel) },
|
||||
onClick = {
|
||||
menuExpanded = false
|
||||
setMenuExpanded(false)
|
||||
onResetPlacement()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(appearanceLabel) },
|
||||
onClick = {
|
||||
menuExpanded = false
|
||||
setMenuExpanded(false)
|
||||
onOpenAppearance()
|
||||
},
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text(hideLabel) },
|
||||
onClick = {
|
||||
menuExpanded = false
|
||||
setMenuExpanded(false)
|
||||
onHide()
|
||||
},
|
||||
)
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.media.MediaMetadataRetriever
|
||||
import android.net.Uri
|
||||
@@ -290,7 +289,7 @@ private fun ImageRender(
|
||||
android.util.Base64.decode(attachment.content, android.util.Base64.DEFAULT)
|
||||
else -> null
|
||||
}
|
||||
bytes?.let { BitmapFactory.decodeByteArray(it, 0, it.size)?.asImageBitmap() }
|
||||
bytes?.let { decodeOrientedBitmap(it)?.asImageBitmap() }
|
||||
}.getOrNull()
|
||||
}
|
||||
if (decoded != null) bitmap = decoded else decodeFailed = true
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
@@ -32,7 +37,12 @@ import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.text.selection.DisableSelection
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.VolumeUp
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Edit
|
||||
import androidx.compose.material.icons.filled.FormatQuote
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
@@ -40,7 +50,6 @@ import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
@@ -71,13 +80,16 @@ import com.hermesandroid.relay.data.HermesCardAction
|
||||
import com.hermesandroid.relay.data.MediaSettingsRepository
|
||||
import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.parseChatQuotedPrompt
|
||||
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
|
||||
import com.hermesandroid.relay.ui.components.pet.petPerchSurface
|
||||
import com.hermesandroid.relay.ui.components.pet.petVisitTargetSurface
|
||||
import com.hermesandroid.relay.ui.theme.leftEdgeGlow
|
||||
import kotlinx.coroutines.delay
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
|
||||
internal const val CHAT_PET_IDENTITY_OBSTACLE_PREFIX = "chat-message-identity:"
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun MessageBubble(
|
||||
@@ -96,16 +108,19 @@ fun MessageBubble(
|
||||
retainStreamingLayout: Boolean = false,
|
||||
onCopyMessage: (String) -> Unit = {},
|
||||
/**
|
||||
* Quote this message into the input field. Null hides the Quote entry in
|
||||
* the long-press menu, so legacy call sites keep the copy-only behavior.
|
||||
* Select this message as a structured composer quote. Null hides Quote.
|
||||
*/
|
||||
onQuoteMessage: ((String) -> Unit)? = null,
|
||||
onQuoteMessage: ((ChatMessage) -> Unit)? = null,
|
||||
/** Navigate a rendered quote chip to its original message id. */
|
||||
onNavigateToMessage: ((String) -> Unit)? = null,
|
||||
/**
|
||||
* Reads a completed assistant response through the active voice renderer.
|
||||
* Null hides the entry; the owning screen uses that to limit the action to
|
||||
* idle Conversation voice sessions.
|
||||
*/
|
||||
onSpeakMessage: ((String) -> Unit)? = null,
|
||||
/** Stops a message-context narration currently owned by the voice pipeline. */
|
||||
onStopSpeaking: (() -> Unit)? = null,
|
||||
/**
|
||||
* Invoked when the user taps a FAILED inbound attachment card.
|
||||
* `attachmentIndex` is the position in [ChatMessage.attachments] so the
|
||||
@@ -151,6 +166,7 @@ fun MessageBubble(
|
||||
imageGenerationRotationIndex: Int = 0,
|
||||
petVisitTargetKey: String? = null,
|
||||
petPerchKey: String? = null,
|
||||
animationEnabled: Boolean = true,
|
||||
) {
|
||||
val isUser = message.role == MessageRole.USER
|
||||
val isSystem = message.role == MessageRole.SYSTEM
|
||||
@@ -204,18 +220,19 @@ fun MessageBubble(
|
||||
val alignment = if (isUser) Alignment.End else Alignment.Start
|
||||
val locale = LocalLocale.current.platformLocale
|
||||
val timeFormat = remember(locale) { SimpleDateFormat("h:mm a", locale) }
|
||||
val a11yDescription = "${message.role.name.lowercase()} message: ${message.content.take(100)}"
|
||||
val quoteEnvelope = remember(message.content) { parseChatQuotedPrompt(message.content) }
|
||||
val visibleMessageContent = quoteEnvelope?.body ?: message.content
|
||||
val isDarkTheme = LocalBrand.current.isDark
|
||||
|
||||
// Pull generated/inline image links (``) out of assistant
|
||||
// content so they render as real images (remote URLs via Coil) or a
|
||||
// graceful inline notice — not the blank element the markdown renderer
|
||||
// emits for an image link. User/system bubbles keep their raw content.
|
||||
val (markdownBody, inlineImages) = remember(message.content, isUser, isSystem) {
|
||||
val (markdownBody, inlineImages) = remember(visibleMessageContent, isUser, isSystem) {
|
||||
if (isUser || isSystem) {
|
||||
message.content to emptyList()
|
||||
visibleMessageContent to emptyList()
|
||||
} else {
|
||||
extractChatInlineImages(message.content)
|
||||
extractChatInlineImages(visibleMessageContent)
|
||||
}
|
||||
}
|
||||
val showImageGeneration = shouldShowImageGenerationPlaceholder(
|
||||
@@ -223,6 +240,26 @@ fun MessageBubble(
|
||||
isStreaming = message.isStreaming,
|
||||
hasMediaResult = message.attachments.isNotEmpty() || inlineImages.isNotEmpty(),
|
||||
)
|
||||
val streamingStatusLabel = if (
|
||||
!isUser &&
|
||||
!isSystem &&
|
||||
message.isStreaming &&
|
||||
message.content.isBlank() &&
|
||||
!showImageGeneration
|
||||
) {
|
||||
if (recoveringAnswer) {
|
||||
stringResource(R.string.msg_bubble_reconnecting)
|
||||
} else {
|
||||
stringResource(R.string.msg_bubble_still_working)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val a11yDescription = buildString {
|
||||
append(message.role.name.lowercase())
|
||||
append(" message: ")
|
||||
append(streamingStatusLabel ?: visibleMessageContent.take(100))
|
||||
}
|
||||
val hasImageGenerationCall = remember(message.toolCalls) {
|
||||
message.toolCalls.any {
|
||||
it.name.trim().lowercase() == "image_generate"
|
||||
@@ -251,52 +288,36 @@ fun MessageBubble(
|
||||
val blurMode by blurRepo.blurMode.collectAsState(initial = BlurMode.FLAGGED)
|
||||
|
||||
CompositionLocalProvider(LocalMediaBlurMode provides blurMode) {
|
||||
// The active profile image is sender identity, distinct from both the
|
||||
// floating pet companion and the ambient Sphere. Reserve one stable gutter
|
||||
// for an assistant run and render the identity only on its first message.
|
||||
Row(
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalAlignment = Alignment.Top,
|
||||
horizontalAlignment = alignment,
|
||||
) {
|
||||
if (!isUser && !isSystem) {
|
||||
Box(
|
||||
modifier = Modifier.width(40.dp),
|
||||
contentAlignment = Alignment.TopCenter,
|
||||
) {
|
||||
if (shouldShowMessageGroupAvatar(
|
||||
isUser = isUser,
|
||||
isSystem = isSystem,
|
||||
isFirstInGroup = isFirstInGroup,
|
||||
agentName = message.agentName,
|
||||
)
|
||||
// Keep sender identity in the first-message label rather than a
|
||||
// persistent leading column. Long responses and every follow-up in the
|
||||
// group therefore retain the full bubble-width allowance.
|
||||
if (!isUser && !isSystem && isFirstInGroup && !message.agentName.isNullOrBlank()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier
|
||||
.padding(bottom = 3.dp, start = 4.dp)
|
||||
.petObstacleSurface(
|
||||
key = "$CHAT_PET_IDENTITY_OBSTACLE_PREFIX${message.uiKey}",
|
||||
routes = setOf("chat"),
|
||||
),
|
||||
) {
|
||||
Surface(
|
||||
// Decorative: the adjacent visible agent name already owns
|
||||
// the identity announcement, avoiding duplicate TalkBack copy.
|
||||
modifier = Modifier.size(32.dp),
|
||||
modifier = Modifier.size(24.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
) {
|
||||
AgentAvatarFace(
|
||||
name = message.agentName.orEmpty(),
|
||||
letterStyle = MaterialTheme.typography.labelMedium,
|
||||
letterStyle = MaterialTheme.typography.labelSmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
horizontalAlignment = alignment
|
||||
) {
|
||||
// Agent name label sits beside the first group identity avatar. Pet
|
||||
// companions never enter this row.
|
||||
if (!isUser && !isSystem && isFirstInGroup && !message.agentName.isNullOrBlank()) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.padding(bottom = 2.dp, start = 4.dp),
|
||||
) {
|
||||
Text(
|
||||
text = localizeAgentName(message.agentName),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
@@ -331,7 +352,7 @@ fun MessageBubble(
|
||||
}
|
||||
|
||||
// Thinking block (above the bubble, only for assistant messages)
|
||||
if (!isUser && showThinking && message.thinkingContent.isNotEmpty()) {
|
||||
if (!isUser && showThinking && message.thinkingContent.isNotBlank()) {
|
||||
ThinkingBlock(
|
||||
thinkingContent = message.thinkingContent,
|
||||
isStreaming = message.isThinkingStreaming,
|
||||
@@ -380,12 +401,22 @@ fun MessageBubble(
|
||||
// carries only thinking and/or tool calls (both rendered OUTSIDE
|
||||
// this Surface — the ThinkingBlock above, the tool pills as separate
|
||||
// rows) would otherwise paint a bare timestamp-only chip between the
|
||||
// Thought-process block and the tool pill. Keep the bubble while
|
||||
// streaming (StreamingDots is the live "working" indicator) and
|
||||
// whenever there are cards/attachments to render inside it.
|
||||
// Thought-process block and the tool pill. The first-token working state
|
||||
// is rendered directly in the conversation
|
||||
// lane below, without an opaque bubble. Cards and attachments still own
|
||||
// a normal bubble even when response prose has not arrived yet.
|
||||
streamingStatusLabel?.let { streamingStatus ->
|
||||
StandaloneStreamingStatus(
|
||||
status = streamingStatus,
|
||||
accessibilityDescription = a11yDescription,
|
||||
textColor = textColor,
|
||||
modifier = Modifier.padding(start = 12.dp, top = 4.dp, bottom = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
val showBubble = isUser || isSystem ||
|
||||
message.content.isNotBlank() ||
|
||||
message.isStreaming ||
|
||||
visibleMessageContent.isNotBlank() ||
|
||||
quoteEnvelope != null ||
|
||||
showImageGeneration ||
|
||||
message.cards.isNotEmpty() ||
|
||||
message.attachments.isNotEmpty() ||
|
||||
@@ -400,19 +431,25 @@ fun MessageBubble(
|
||||
modifier = Modifier
|
||||
.padding(top = 8.dp, bottom = 8.dp, end = 6.dp)
|
||||
.width(3.dp)
|
||||
.height(if (message.content.isBlank()) 14.dp else 24.dp)
|
||||
.height(if (visibleMessageContent.isBlank()) 14.dp else 24.dp)
|
||||
.clip(CircleShape)
|
||||
.background(MaterialTheme.colorScheme.tertiary.copy(alpha = 0.85f))
|
||||
)
|
||||
}
|
||||
// Long-press opens a compact action menu when a quote handler is
|
||||
// wired; with copy as the only action it stays a direct copy so the
|
||||
// one-action case doesn't pay a menu tap.
|
||||
Column(horizontalAlignment = alignment) {
|
||||
// A normal tap reveals the compact action strip. Long-press preserves
|
||||
// the existing overflow menu (or direct-copy shortcut when Copy is the
|
||||
// only available action).
|
||||
var showMessageActions by remember { mutableStateOf(false) }
|
||||
var showInlineActions by remember(message.uiKey) { mutableStateOf(false) }
|
||||
val haptic = LocalHapticFeedback.current
|
||||
val accessibleMotion = rememberAccessibleMotionState()
|
||||
val animateInlineActions = animationEnabled && accessibleMotion.osAnimations &&
|
||||
!accessibleMotion.touchExploration
|
||||
val showEditAction = onEditMessage != null && isUser
|
||||
val showSpeakAction = shouldShowSpeakResponseAction(message, onSpeakMessage != null)
|
||||
if (onQuoteMessage != null || showEditAction || showSpeakAction) {
|
||||
val showStopSpeakingAction = shouldShowStopSpeakingAction(message, onStopSpeaking != null)
|
||||
if (onQuoteMessage != null || showEditAction || showSpeakAction || showStopSpeakingAction) {
|
||||
DropdownMenu(
|
||||
expanded = showMessageActions,
|
||||
onDismissRequest = { showMessageActions = false },
|
||||
@@ -421,7 +458,7 @@ fun MessageBubble(
|
||||
text = { Text(stringResource(R.string.msg_bubble_copy)) },
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onCopyMessage(message.content)
|
||||
onCopyMessage(visibleMessageContent)
|
||||
},
|
||||
)
|
||||
if (onQuoteMessage != null) {
|
||||
@@ -429,7 +466,7 @@ fun MessageBubble(
|
||||
text = { Text(stringResource(R.string.msg_bubble_quote)) },
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onQuoteMessage(message.content)
|
||||
onQuoteMessage(message.copy(content = visibleMessageContent))
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -444,7 +481,22 @@ fun MessageBubble(
|
||||
},
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onSpeakMessage?.invoke(message.content)
|
||||
onSpeakMessage?.invoke(visibleMessageContent)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (showStopSpeakingAction) {
|
||||
DropdownMenuItem(
|
||||
text = { Text(stringResource(R.string.msg_bubble_stop_speaking)) },
|
||||
leadingIcon = {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Stop,
|
||||
contentDescription = null,
|
||||
)
|
||||
},
|
||||
onClick = {
|
||||
showMessageActions = false
|
||||
onStopSpeaking?.invoke()
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -493,16 +545,19 @@ fun MessageBubble(
|
||||
} else Modifier
|
||||
)
|
||||
.combinedClickable(
|
||||
onClick = {},
|
||||
onClick = { showInlineActions = !showInlineActions },
|
||||
onLongClick = {
|
||||
// Buzz the instant the long-press registers — opening the
|
||||
// action menu is the discoverability moment, so it gets the
|
||||
// same tactile confirm every chat app fires.
|
||||
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
|
||||
if (onQuoteMessage != null || showEditAction || showSpeakAction) {
|
||||
if (
|
||||
onQuoteMessage != null || showEditAction || showSpeakAction ||
|
||||
showStopSpeakingAction
|
||||
) {
|
||||
showMessageActions = true
|
||||
} else {
|
||||
onCopyMessage(message.content)
|
||||
onCopyMessage(visibleMessageContent)
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -528,12 +583,23 @@ fun MessageBubble(
|
||||
}
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp)) {
|
||||
Column(
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 9.dp),
|
||||
) {
|
||||
quoteEnvelope?.let { envelope ->
|
||||
ChatQuoteReferenceChip(
|
||||
reference = envelope.reference,
|
||||
onOpenOriginal = onNavigateToMessage?.let { navigate ->
|
||||
{ navigate(envelope.reference.messageId) }
|
||||
},
|
||||
modifier = Modifier.padding(bottom = 7.dp),
|
||||
)
|
||||
}
|
||||
val messageTextContent: @Composable () -> Unit = {
|
||||
if (isUser || isSystem) {
|
||||
// Plain text for user and system messages
|
||||
Text(
|
||||
text = message.content,
|
||||
text = visibleMessageContent,
|
||||
style = MaterialTheme.typography.bodyMedium.copy(
|
||||
fontSize = 15.sp,
|
||||
lineHeight = 21.sp,
|
||||
@@ -559,7 +625,7 @@ fun MessageBubble(
|
||||
// a live Text node becomes a Markdown tree, or settled
|
||||
// Markdown content changes its node topology, so a handle
|
||||
// cannot keep pointing at a removed selectable.
|
||||
if (showSpeakAction) {
|
||||
if (showSpeakAction || showStopSpeakingAction) {
|
||||
DisableSelection { messageTextContent() }
|
||||
} else {
|
||||
key(
|
||||
@@ -687,64 +753,6 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
|
||||
// Streaming indicator — only while awaiting the first token. Once
|
||||
// text starts flowing, the growing reply is itself the progress
|
||||
// signal, so the pulsing dots stop (Messenger/Telegram drop the
|
||||
// typing bubble the moment content appears) instead of throbbing
|
||||
// under the text for the whole turn.
|
||||
if (
|
||||
message.isStreaming &&
|
||||
message.content.isBlank() &&
|
||||
!showImageGeneration
|
||||
) {
|
||||
// After a few seconds with no content yet, escalate the bare
|
||||
// dots to a labeled "Still working…" so a slow first token
|
||||
// never reads as a hang on the SSE / sessions paths.
|
||||
val awaitingFirstToken = message.content.isBlank()
|
||||
var showStillWorking by remember(message.id) { mutableStateOf(false) }
|
||||
LaunchedEffect(message.id, awaitingFirstToken) {
|
||||
showStillWorking = false
|
||||
if (awaitingFirstToken) {
|
||||
delay(4_000)
|
||||
showStillWorking = true
|
||||
}
|
||||
}
|
||||
val thinkingIndicator = LocalThinkingIndicator.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
when (thinkingIndicator.style) {
|
||||
ThinkingIndicatorStyle.Matrix -> DotMatrixIndicator(
|
||||
// Auto follows the bubble text color; accents
|
||||
// come from the brand palette. The grid modulates
|
||||
// its own alpha (idle dots ≈0.18, lit dots 1.0).
|
||||
color = thinkingIndicator.color.toColor(autoColor = textColor),
|
||||
pattern = thinkingIndicator.pattern,
|
||||
animated = thinkingIndicator.animated,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
ThinkingIndicatorStyle.Dots -> StreamingDots(
|
||||
color = textColor.copy(alpha = 0.6f),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
// During dropped-stream answer recovery the label shows
|
||||
// immediately (the 4s escalation is for a slow first
|
||||
// token; a recovery is already known to be slow).
|
||||
if ((showStillWorking || recoveringAnswer) && awaitingFirstToken) {
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(
|
||||
text = if (recoveringAnswer) {
|
||||
stringResource(R.string.msg_bubble_reconnecting)
|
||||
} else {
|
||||
stringResource(R.string.msg_bubble_still_working)
|
||||
},
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = textColor.copy(alpha = 0.6f),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Timestamp — only on the LAST bubble of a same-author run so a
|
||||
// burst of fragments doesn't stack three near-touching time labels.
|
||||
// Grouping breaks on a >5min gap (ChatScreen), so every pause still
|
||||
@@ -771,23 +779,17 @@ fun MessageBubble(
|
||||
// message routed over the relay proactive channel). Null on every
|
||||
// ordinary chat message, which render nothing here.
|
||||
message.deliveryStatus?.takeIf { isUser }?.let { status ->
|
||||
val label = stringResource(
|
||||
when (status) {
|
||||
MessageDeliveryStatus.SENDING -> R.string.msg_bubble_sending
|
||||
MessageDeliveryStatus.DELIVERED -> R.string.msg_bubble_delivered
|
||||
MessageDeliveryStatus.FAILED -> R.string.msg_bubble_not_sent
|
||||
}
|
||||
)
|
||||
val alpha = when (status) {
|
||||
MessageDeliveryStatus.SENDING -> 0.5f
|
||||
MessageDeliveryStatus.DELIVERED -> 0.5f
|
||||
MessageDeliveryStatus.FAILED -> 0.7f
|
||||
}
|
||||
Spacer(modifier = Modifier.height(2.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = textColor.copy(alpha = alpha),
|
||||
MessageDeliveryIndicator(
|
||||
status = status,
|
||||
text = MessageDeliveryIndicatorText(
|
||||
sending = stringResource(R.string.msg_bubble_sending),
|
||||
queued = stringResource(R.string.msg_bubble_queued),
|
||||
steered = stringResource(R.string.msg_bubble_steered),
|
||||
delivered = stringResource(R.string.msg_bubble_delivered),
|
||||
failed = stringResource(R.string.msg_bubble_not_sent),
|
||||
tapToRetry = stringResource(R.string.chat_retry),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -801,13 +803,127 @@ fun MessageBubble(
|
||||
}
|
||||
}
|
||||
}
|
||||
val inlineActions: @Composable () -> Unit = {
|
||||
MessageInlineActions(
|
||||
showQuote = onQuoteMessage != null,
|
||||
showSpeak = showSpeakAction,
|
||||
showStopSpeaking = showStopSpeakingAction,
|
||||
showEdit = showEditAction,
|
||||
onCopy = {
|
||||
showInlineActions = false
|
||||
onCopyMessage(visibleMessageContent)
|
||||
},
|
||||
onQuote = {
|
||||
showInlineActions = false
|
||||
onQuoteMessage?.invoke(message.copy(content = visibleMessageContent))
|
||||
},
|
||||
onSpeak = {
|
||||
showInlineActions = false
|
||||
onSpeakMessage?.invoke(visibleMessageContent)
|
||||
},
|
||||
onStopSpeaking = {
|
||||
showInlineActions = false
|
||||
onStopSpeaking?.invoke()
|
||||
},
|
||||
onEdit = {
|
||||
showInlineActions = false
|
||||
onEditMessage?.invoke(message)
|
||||
},
|
||||
)
|
||||
}
|
||||
if (animateInlineActions) {
|
||||
AnimatedVisibility(
|
||||
visible = showInlineActions,
|
||||
enter = fadeIn(tween(120)) + expandVertically(
|
||||
animationSpec = tween(180, easing = LinearOutSlowInEasing),
|
||||
expandFrom = Alignment.Top,
|
||||
),
|
||||
exit = fadeOut(tween(90)) + shrinkVertically(
|
||||
animationSpec = tween(140),
|
||||
shrinkTowards = Alignment.Top,
|
||||
),
|
||||
) {
|
||||
inlineActions()
|
||||
}
|
||||
} else if (showInlineActions) {
|
||||
inlineActions()
|
||||
}
|
||||
} // end Column (bubble + revealed actions)
|
||||
} // end Row (bubble + optional leading accent bar)
|
||||
} // end if (showBubble)
|
||||
} // end content Column
|
||||
} // end Row (avatar gutter + content)
|
||||
} // end CompositionLocalProvider(LocalMediaBlurMode)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun MessageInlineActions(
|
||||
showQuote: Boolean,
|
||||
showSpeak: Boolean,
|
||||
showStopSpeaking: Boolean,
|
||||
showEdit: Boolean,
|
||||
onCopy: () -> Unit,
|
||||
onQuote: () -> Unit,
|
||||
onSpeak: () -> Unit,
|
||||
onStopSpeaking: () -> Unit,
|
||||
onEdit: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHigh,
|
||||
tonalElevation = 2.dp,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(horizontal = 2.dp),
|
||||
) {
|
||||
IconButton(onClick = onCopy, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ContentCopy,
|
||||
contentDescription = stringResource(R.string.msg_bubble_copy),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
if (showQuote) {
|
||||
IconButton(onClick = onQuote, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.FormatQuote,
|
||||
contentDescription = stringResource(R.string.msg_bubble_quote),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showSpeak) {
|
||||
IconButton(onClick = onSpeak, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.VolumeUp,
|
||||
contentDescription = stringResource(R.string.msg_bubble_speak_response),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showStopSpeaking) {
|
||||
IconButton(onClick = onStopSpeaking, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Stop,
|
||||
contentDescription = stringResource(R.string.msg_bubble_stop_speaking),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showEdit) {
|
||||
IconButton(onClick = onEdit, modifier = Modifier.size(48.dp)) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Edit,
|
||||
contentDescription = stringResource(R.string.msg_bubble_edit),
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal data class MessageSelectionTopologyKey(
|
||||
val renderer: String,
|
||||
val markdownBody: String?,
|
||||
@@ -881,6 +997,15 @@ internal fun shouldShowSpeakResponseAction(
|
||||
!message.isStreaming &&
|
||||
message.content.isNotBlank()
|
||||
|
||||
internal fun shouldShowStopSpeakingAction(
|
||||
message: ChatMessage,
|
||||
handlerAvailable: Boolean,
|
||||
): Boolean =
|
||||
handlerAvailable &&
|
||||
message.role == MessageRole.ASSISTANT &&
|
||||
!message.isStreaming &&
|
||||
message.content.isNotBlank()
|
||||
|
||||
internal fun shouldShowMessageGroupAvatar(
|
||||
isUser: Boolean,
|
||||
isSystem: Boolean,
|
||||
@@ -918,6 +1043,42 @@ private fun MessagePathBadge(text: String, leadingIcon: ImageVector? = null) {
|
||||
}
|
||||
}
|
||||
|
||||
/** First-token progress rendered in the conversation lane, not inside a message bubble. */
|
||||
@Composable
|
||||
private fun StandaloneStreamingStatus(
|
||||
status: String,
|
||||
accessibilityDescription: String,
|
||||
textColor: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val thinkingIndicator = LocalThinkingIndicator.current
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = modifier.clearAndSetSemantics {
|
||||
contentDescription = accessibilityDescription
|
||||
},
|
||||
) {
|
||||
when (thinkingIndicator.style) {
|
||||
ThinkingIndicatorStyle.Matrix -> DotMatrixIndicator(
|
||||
color = thinkingIndicator.color.toColor(autoColor = textColor),
|
||||
pattern = thinkingIndicator.pattern,
|
||||
animated = thinkingIndicator.animated,
|
||||
)
|
||||
ThinkingIndicatorStyle.Dots -> StreamingDots(
|
||||
color = textColor.copy(alpha = 0.6f),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = status,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = textColor.copy(alpha = 0.68f),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Three dots that animate opacity in sequence to indicate streaming is in progress.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.Send
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.ErrorOutline
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.minimumInteractiveComponentSize
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.semantics.LiveRegionMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.liveRegion
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.ui.theme.relayMetadataStyle
|
||||
|
||||
/**
|
||||
* Localized copy for [MessageDeliveryIndicator]. Keeping copy at the call site
|
||||
* lets MessageBubble use Android string resources without coupling this small
|
||||
* presentation component to a particular resource catalog.
|
||||
*/
|
||||
data class MessageDeliveryIndicatorText(
|
||||
val sending: String,
|
||||
val queued: String,
|
||||
val steered: String,
|
||||
val delivered: String,
|
||||
val failed: String,
|
||||
val tapToRetry: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Compact, accessible lifecycle feedback for a user-authored chat message.
|
||||
*
|
||||
* Every state has both a distinct icon and a visible text label, so meaning is
|
||||
* never carried by color alone. A failed state becomes a button only when
|
||||
* [onRetry] is supplied; its entire 48dp row is then the retry target.
|
||||
*/
|
||||
@Composable
|
||||
fun MessageDeliveryIndicator(
|
||||
status: MessageDeliveryStatus,
|
||||
text: MessageDeliveryIndicatorText,
|
||||
modifier: Modifier = Modifier,
|
||||
failureMessage: String? = null,
|
||||
onRetry: (() -> Unit)? = null,
|
||||
) {
|
||||
val retryAction = onRetry.takeIf { status == MessageDeliveryStatus.FAILED }
|
||||
val retryable = retryAction != null
|
||||
val line = messageDeliveryStatusLine(
|
||||
status = status,
|
||||
text = text,
|
||||
failureMessage = failureMessage,
|
||||
retryable = retryable,
|
||||
)
|
||||
val presentation = messageDeliveryPresentation(status)
|
||||
val tint = when (presentation.colorRole) {
|
||||
DeliveryColorRole.NEUTRAL -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
DeliveryColorRole.ACCENT -> MaterialTheme.colorScheme.primary
|
||||
DeliveryColorRole.QUEUED -> MaterialTheme.colorScheme.tertiary
|
||||
DeliveryColorRole.ERROR -> MaterialTheme.colorScheme.error
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.then(
|
||||
if (retryable) {
|
||||
Modifier
|
||||
.minimumInteractiveComponentSize()
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = text.tapToRetry,
|
||||
onClick = retryAction,
|
||||
)
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
)
|
||||
.semantics(mergeDescendants = true) {
|
||||
contentDescription = line
|
||||
liveRegion = LiveRegionMode.Polite
|
||||
}
|
||||
.padding(horizontal = 2.dp, vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = presentation.icon,
|
||||
contentDescription = null,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(14.dp),
|
||||
)
|
||||
Text(
|
||||
text = line,
|
||||
style = relayMetadataStyle(),
|
||||
color = tint,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun messageDeliveryStatusLine(
|
||||
status: MessageDeliveryStatus,
|
||||
text: MessageDeliveryIndicatorText,
|
||||
failureMessage: String? = null,
|
||||
retryable: Boolean = false,
|
||||
): String {
|
||||
val label = when (status) {
|
||||
MessageDeliveryStatus.SENDING -> text.sending
|
||||
MessageDeliveryStatus.QUEUED -> text.queued
|
||||
MessageDeliveryStatus.STEERED -> text.steered
|
||||
MessageDeliveryStatus.DELIVERED -> text.delivered
|
||||
MessageDeliveryStatus.FAILED -> text.failed
|
||||
}
|
||||
if (status != MessageDeliveryStatus.FAILED) return label
|
||||
|
||||
return buildList {
|
||||
add(label)
|
||||
failureMessage?.trim()?.takeIf(String::isNotEmpty)?.let(::add)
|
||||
if (retryable) add(text.tapToRetry)
|
||||
}.joinToString(" · ")
|
||||
}
|
||||
|
||||
private data class DeliveryPresentation(
|
||||
val icon: ImageVector,
|
||||
val colorRole: DeliveryColorRole,
|
||||
)
|
||||
|
||||
private enum class DeliveryColorRole { NEUTRAL, ACCENT, QUEUED, ERROR }
|
||||
|
||||
private fun messageDeliveryPresentation(status: MessageDeliveryStatus): DeliveryPresentation =
|
||||
when (status) {
|
||||
MessageDeliveryStatus.SENDING -> DeliveryPresentation(
|
||||
icon = Icons.AutoMirrored.Filled.Send,
|
||||
colorRole = DeliveryColorRole.NEUTRAL,
|
||||
)
|
||||
MessageDeliveryStatus.QUEUED -> DeliveryPresentation(
|
||||
icon = Icons.Filled.Schedule,
|
||||
colorRole = DeliveryColorRole.QUEUED,
|
||||
)
|
||||
MessageDeliveryStatus.STEERED -> DeliveryPresentation(
|
||||
icon = Icons.Filled.Bolt,
|
||||
colorRole = DeliveryColorRole.ACCENT,
|
||||
)
|
||||
MessageDeliveryStatus.DELIVERED -> DeliveryPresentation(
|
||||
icon = Icons.Filled.CheckCircle,
|
||||
colorRole = DeliveryColorRole.ACCENT,
|
||||
)
|
||||
MessageDeliveryStatus.FAILED -> DeliveryPresentation(
|
||||
icon = Icons.Filled.ErrorOutline,
|
||||
colorRole = DeliveryColorRole.ERROR,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Matrix
|
||||
import androidx.exifinterface.media.ExifInterface
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
internal data class ImageOrientationTransform(
|
||||
val rotationDegrees: Float = 0f,
|
||||
val flipHorizontal: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun imageOrientationTransform(orientation: Int): ImageOrientationTransform = when (orientation) {
|
||||
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> ImageOrientationTransform(flipHorizontal = true)
|
||||
ExifInterface.ORIENTATION_ROTATE_180 -> ImageOrientationTransform(rotationDegrees = 180f)
|
||||
ExifInterface.ORIENTATION_FLIP_VERTICAL ->
|
||||
ImageOrientationTransform(rotationDegrees = 180f, flipHorizontal = true)
|
||||
ExifInterface.ORIENTATION_TRANSPOSE ->
|
||||
ImageOrientationTransform(rotationDegrees = 90f, flipHorizontal = true)
|
||||
ExifInterface.ORIENTATION_ROTATE_90 -> ImageOrientationTransform(rotationDegrees = 90f)
|
||||
ExifInterface.ORIENTATION_TRANSVERSE ->
|
||||
ImageOrientationTransform(rotationDegrees = -90f, flipHorizontal = true)
|
||||
ExifInterface.ORIENTATION_ROTATE_270 -> ImageOrientationTransform(rotationDegrees = -90f)
|
||||
else -> ImageOrientationTransform()
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode image bytes for display and apply their EXIF orientation. BitmapFactory
|
||||
* returns the stored pixel layout and otherwise leaves portrait phone photos
|
||||
* sideways when the camera encoded rotation as metadata.
|
||||
*/
|
||||
internal fun decodeOrientedBitmap(
|
||||
bytes: ByteArray,
|
||||
options: BitmapFactory.Options? = null,
|
||||
): Bitmap? {
|
||||
if (bytes.isEmpty()) return null
|
||||
val decoded = if (options == null) {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
} else {
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||
} ?: return null
|
||||
|
||||
val orientation = runCatching {
|
||||
ByteArrayInputStream(bytes).use { stream ->
|
||||
ExifInterface(stream).getAttributeInt(
|
||||
ExifInterface.TAG_ORIENTATION,
|
||||
ExifInterface.ORIENTATION_NORMAL,
|
||||
)
|
||||
}
|
||||
}.getOrDefault(ExifInterface.ORIENTATION_NORMAL)
|
||||
val transform = imageOrientationTransform(orientation)
|
||||
if (transform.rotationDegrees == 0f && !transform.flipHorizontal) return decoded
|
||||
|
||||
val matrix = Matrix().apply {
|
||||
if (transform.rotationDegrees != 0f) postRotate(transform.rotationDegrees)
|
||||
if (transform.flipHorizontal) postScale(-1f, 1f)
|
||||
}
|
||||
return runCatching {
|
||||
Bitmap.createBitmap(decoded, 0, 0, decoded.width, decoded.height, matrix, true)
|
||||
}.getOrNull()?.also { oriented ->
|
||||
if (oriented !== decoded) decoded.recycle()
|
||||
} ?: decoded
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.util.Base64
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.AttachFile
|
||||
import androidx.compose.material.icons.filled.BrokenImage
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.Attachment
|
||||
import com.hermesandroid.relay.data.AttachmentRenderMode
|
||||
import com.hermesandroid.relay.data.AttachmentState
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Pending files shown immediately above the chat composer.
|
||||
*
|
||||
* The owner keeps attachment state and handles the four stable integration
|
||||
* callbacks. [onMove] receives the current and requested indices, allowing a
|
||||
* ViewModel or session-owned draft store to perform one atomic reorder.
|
||||
*/
|
||||
@Composable
|
||||
fun PendingAttachmentComposer(
|
||||
attachments: List<Attachment>,
|
||||
onPreview: (attachment: Attachment, index: Int) -> Unit,
|
||||
onRemove: (index: Int) -> Unit,
|
||||
onMove: (fromIndex: Int, toIndex: Int) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
imageDecoder: suspend (Attachment) -> ImageBitmap? = ::decodePendingAttachmentImage,
|
||||
) {
|
||||
if (attachments.isEmpty()) return
|
||||
val attachmentLabel = stringResource(R.string.attachment_title)
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.semantics {
|
||||
contentDescription = "${attachments.size} $attachmentLabel"
|
||||
}
|
||||
.testTag("pending-attachment-composer"),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
attachments.forEachIndexed { index, attachment ->
|
||||
PendingAttachmentItem(
|
||||
attachment = attachment,
|
||||
index = index,
|
||||
count = attachments.size,
|
||||
onPreview = { onPreview(attachment, index) },
|
||||
onRemove = { onRemove(index) },
|
||||
onMoveLeft = { onMove(index, index - 1) },
|
||||
onMoveRight = { onMove(index, index + 1) },
|
||||
imageDecoder = imageDecoder,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PendingAttachmentItem(
|
||||
attachment: Attachment,
|
||||
index: Int,
|
||||
count: Int,
|
||||
onPreview: () -> Unit,
|
||||
onRemove: () -> Unit,
|
||||
onMoveLeft: () -> Unit,
|
||||
onMoveRight: () -> Unit,
|
||||
imageDecoder: suspend (Attachment) -> ImageBitmap?,
|
||||
) {
|
||||
var previewState by remember(attachment.content, attachment.cachedUri, attachment.state) {
|
||||
mutableStateOf(initialPreviewState(attachment))
|
||||
}
|
||||
LaunchedEffect(attachment.content, attachment.cachedUri, attachment.state) {
|
||||
if (attachment.isImage && attachment.state == AttachmentState.LOADED) {
|
||||
previewState = PendingPreviewState.Loading
|
||||
previewState = imageDecoder(attachment)?.let(PendingPreviewState::Ready)
|
||||
?: PendingPreviewState.Failed
|
||||
}
|
||||
}
|
||||
|
||||
val name = attachment.fileName?.takeIf(String::isNotBlank)
|
||||
?: stringResource(R.string.attachment_title)
|
||||
val type = attachmentTypeLabel(attachment.renderMode)
|
||||
val size = attachment.fileSize?.let { formatAttachmentSize(it) }
|
||||
val status = when (previewState) {
|
||||
PendingPreviewState.Loading -> stringResource(R.string.pending_attachment_status_loading)
|
||||
is PendingPreviewState.Ready -> stringResource(R.string.pending_attachment_status_ready)
|
||||
PendingPreviewState.Failed -> attachment.errorMessage?.takeIf(String::isNotBlank)
|
||||
?: stringResource(R.string.pending_attachment_status_failed)
|
||||
}
|
||||
val summary = listOfNotNull(name, type, size, status).joinToString(", ")
|
||||
val previewEnabled = previewState is PendingPreviewState.Ready
|
||||
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.width(216.dp)
|
||||
.semantics { contentDescription = summary }
|
||||
.clip(RoundedCornerShape(14.dp))
|
||||
.clickable(
|
||||
enabled = previewEnabled,
|
||||
onClickLabel = stringResource(R.string.pending_attachment_preview_named, name),
|
||||
role = Role.Button,
|
||||
onClick = onPreview,
|
||||
)
|
||||
.testTag("pending-attachment-$index"),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
PendingAttachmentThumbnail(previewState)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = name,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = listOfNotNull(type, size).joinToString(" · "),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = status,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (previewState == PendingPreviewState.Failed) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
IconButton(
|
||||
onClick = onMoveLeft,
|
||||
enabled = index > 0,
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.testTag("pending-attachment-move-left-$index"),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowBack,
|
||||
contentDescription = stringResource(R.string.pending_attachment_move_left, name),
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = onMoveRight,
|
||||
enabled = index < count - 1,
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.testTag("pending-attachment-move-right-$index"),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.ArrowForward,
|
||||
contentDescription = stringResource(R.string.pending_attachment_move_right, name),
|
||||
)
|
||||
}
|
||||
IconButton(
|
||||
onClick = onRemove,
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.testTag("pending-attachment-remove-$index"),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.pending_attachment_remove, name),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PendingAttachmentThumbnail(state: PendingPreviewState) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(64.dp)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(MaterialTheme.colorScheme.surface),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
when (state) {
|
||||
PendingPreviewState.Loading -> CircularProgressIndicator(
|
||||
modifier = Modifier.size(24.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
is PendingPreviewState.Ready -> if (state.bitmap != null) {
|
||||
Image(
|
||||
bitmap = state.bitmap,
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.size(64.dp),
|
||||
)
|
||||
} else {
|
||||
Icon(Icons.Filled.AttachFile, contentDescription = null)
|
||||
}
|
||||
PendingPreviewState.Failed -> Icon(
|
||||
Icons.Filled.BrokenImage,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun attachmentTypeLabel(mode: AttachmentRenderMode): String = stringResource(
|
||||
when (mode) {
|
||||
AttachmentRenderMode.IMAGE -> R.string.attachment_type_image
|
||||
AttachmentRenderMode.VIDEO -> R.string.attachment_type_video
|
||||
AttachmentRenderMode.AUDIO -> R.string.attachment_type_audio
|
||||
AttachmentRenderMode.PDF -> R.string.attachment_type_pdf
|
||||
AttachmentRenderMode.TEXT -> R.string.attachment_type_text
|
||||
AttachmentRenderMode.GENERIC -> R.string.attachment_type_file
|
||||
},
|
||||
)
|
||||
|
||||
private fun initialPreviewState(attachment: Attachment): PendingPreviewState = when {
|
||||
attachment.state == AttachmentState.FAILED -> PendingPreviewState.Failed
|
||||
attachment.state == AttachmentState.LOADING -> PendingPreviewState.Loading
|
||||
attachment.isImage -> PendingPreviewState.Loading
|
||||
else -> PendingPreviewState.Ready(bitmap = null)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun formatAttachmentSize(bytes: Long): String {
|
||||
val safeBytes = bytes.coerceAtLeast(0)
|
||||
return when {
|
||||
safeBytes >= 1024L * 1024L * 1024L -> stringResource(
|
||||
R.string.media_bytes_gb,
|
||||
safeBytes / (1024.0 * 1024.0 * 1024.0),
|
||||
)
|
||||
safeBytes >= 1024L * 1024L -> stringResource(
|
||||
R.string.media_bytes_mb,
|
||||
safeBytes / (1024.0 * 1024.0),
|
||||
)
|
||||
safeBytes >= 1024L -> stringResource(R.string.media_bytes_kb, safeBytes / 1024.0)
|
||||
else -> stringResource(R.string.media_bytes_b, safeBytes)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun decodePendingAttachmentImage(attachment: Attachment): ImageBitmap? =
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val bytes = Base64.decode(attachment.content, Base64.DEFAULT)
|
||||
if (bytes.isEmpty()) return@runCatching null
|
||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
||||
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@runCatching null
|
||||
|
||||
var sample = 1
|
||||
while (
|
||||
bounds.outWidth / sample > PENDING_ATTACHMENT_THUMBNAIL_TARGET_PX ||
|
||||
bounds.outHeight / sample > PENDING_ATTACHMENT_THUMBNAIL_TARGET_PX
|
||||
) {
|
||||
sample *= 2
|
||||
}
|
||||
decodeOrientedBitmap(
|
||||
bytes,
|
||||
BitmapFactory.Options().apply { inSampleSize = sample },
|
||||
)?.asImageBitmap()
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private sealed interface PendingPreviewState {
|
||||
data object Loading : PendingPreviewState
|
||||
data class Ready(val bitmap: ImageBitmap?) : PendingPreviewState
|
||||
data object Failed : PendingPreviewState
|
||||
}
|
||||
|
||||
private const val PENDING_ATTACHMENT_THUMBNAIL_TARGET_PX = 256
|
||||
@@ -0,0 +1,527 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Home
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material.icons.filled.MoreHoriz
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material.icons.filled.Tune
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
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.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.disabled
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil3.compose.AsyncImage
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.AgentDisplay
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.ProfilePresentation
|
||||
import com.hermesandroid.relay.data.ProfilePresentationPolicy
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import java.io.File
|
||||
|
||||
data class ProfileChoice(
|
||||
val key: String,
|
||||
val profile: Profile?,
|
||||
) {
|
||||
val isServerDefault: Boolean get() = key == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
}
|
||||
|
||||
object ProfileShelfPolicy {
|
||||
fun choices(
|
||||
profiles: List<Profile>,
|
||||
presentation: ProfilePresentation,
|
||||
selectedProfileName: String?,
|
||||
): List<ProfileChoice> {
|
||||
val selectedKey = AgentDisplay.profileSessionKey(selectedProfileName)
|
||||
return ProfilePresentationPolicy
|
||||
.visibleKeys(profiles, presentation, selectedKey)
|
||||
.mapNotNull { key ->
|
||||
if (key == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY) {
|
||||
ProfileChoice(key, null)
|
||||
} else {
|
||||
profiles.firstOrNull { it.name == key }?.let { ProfileChoice(key, it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun canSwitch(isStreaming: Boolean, streamingEndpoint: String): Boolean =
|
||||
!isStreaming || streamingEndpoint == "gateway"
|
||||
|
||||
fun isSelected(choice: ProfileChoice, selectedProfileName: String?): Boolean =
|
||||
choice.key == AgentDisplay.profileSessionKey(selectedProfileName)
|
||||
|
||||
/** Local presentation assets follow the selected choice key, not the sticky profile it resolves to. */
|
||||
fun iconProfileName(choice: ProfileChoice): String? = choice.profile?.name
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ProfileShelf(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
profiles: List<Profile>,
|
||||
selectedProfile: Profile?,
|
||||
resolvedProfile: Profile?,
|
||||
presentation: ProfilePresentation,
|
||||
activeDisplayName: String,
|
||||
isProfileLocked: Boolean,
|
||||
lockedProfileName: String?,
|
||||
switchEnabled: Boolean,
|
||||
onSelect: (Profile?) -> Unit,
|
||||
onOpenPassport: () -> Unit,
|
||||
onOpenSwitcher: () -> Unit,
|
||||
onInspect: (String) -> Unit,
|
||||
onLock: (Profile?) -> Unit,
|
||||
onUnlock: () -> Unit,
|
||||
onHide: (String?) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name)
|
||||
}
|
||||
if (choices.size <= 1) return
|
||||
|
||||
var actionChoice by remember { mutableStateOf<ProfileChoice?>(null) }
|
||||
val lockedKey = lockedProfileName ?: AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 0.dp,
|
||||
) {
|
||||
Column {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 55.dp)
|
||||
.padding(start = 8.dp, end = 4.dp, top = 3.dp, bottom = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
choices.forEach { choice ->
|
||||
val selected = ProfileShelfPolicy.isSelected(choice, selectedProfile?.name)
|
||||
val label = if (selected) {
|
||||
activeDisplayName
|
||||
} else {
|
||||
profileChoiceLabel(choice, resolvedProfile)
|
||||
}
|
||||
if (selected) {
|
||||
val openPassportDescription = stringResource(R.string.profile_shelf_open_passport)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.heightIn(min = 48.dp)
|
||||
.widthIn(max = 190.dp)
|
||||
.combinedClickable(
|
||||
role = Role.Button,
|
||||
onClick = onOpenPassport,
|
||||
onLongClick = { actionChoice = choice },
|
||||
)
|
||||
.semantics {
|
||||
contentDescription = "$label. $openPassportDescription"
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(22.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.primary.copy(alpha = 0.72f),
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 7.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(7.dp),
|
||||
) {
|
||||
ProfileChoiceAvatar(
|
||||
connectionViewModel,
|
||||
choice,
|
||||
resolvedProfile,
|
||||
label,
|
||||
36,
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
modifier = Modifier.weight(1f, fill = false),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val enabled = switchEnabled && !isProfileLocked
|
||||
val switchToDescription = stringResource(R.string.profile_shelf_switch_to)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(48.dp)
|
||||
.clip(CircleShape)
|
||||
.combinedClickable(
|
||||
enabled = true,
|
||||
role = Role.Button,
|
||||
onClick = { if (enabled) onSelect(choice.profile) },
|
||||
onLongClick = { actionChoice = choice },
|
||||
)
|
||||
.semantics {
|
||||
if (!enabled) disabled()
|
||||
contentDescription = if (enabled) {
|
||||
"$label. $switchToDescription"
|
||||
} else {
|
||||
label
|
||||
}
|
||||
},
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
ProfileChoiceAvatar(
|
||||
connectionViewModel,
|
||||
choice,
|
||||
resolvedProfile,
|
||||
label,
|
||||
36,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(
|
||||
onClick = onOpenSwitcher,
|
||||
modifier = Modifier.size(48.dp),
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.size(40.dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerLow,
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.42f),
|
||||
),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
Icons.Filled.MoreHoriz,
|
||||
contentDescription = stringResource(R.string.profile_shelf_all_profiles),
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.32f))
|
||||
}
|
||||
}
|
||||
|
||||
actionChoice?.let { choice ->
|
||||
val selected = ProfileShelfPolicy.isSelected(choice, selectedProfile?.name)
|
||||
val target = choice.profile ?: resolvedProfile
|
||||
val label = profileChoiceLabel(choice, resolvedProfile)
|
||||
ProfileShelfActionsDialog(
|
||||
label = label,
|
||||
canSwitch = switchEnabled && !isProfileLocked,
|
||||
selected = selected,
|
||||
canInspect = target != null,
|
||||
lockedToChoice = isProfileLocked && lockedKey == choice.key,
|
||||
onInspect = {
|
||||
actionChoice = null
|
||||
target?.name?.let(onInspect)
|
||||
},
|
||||
onPassport = {
|
||||
actionChoice = null
|
||||
if (!selected && switchEnabled && !isProfileLocked) onSelect(choice.profile)
|
||||
onOpenPassport()
|
||||
},
|
||||
onToggleLock = {
|
||||
actionChoice = null
|
||||
if (isProfileLocked && lockedKey == choice.key) onUnlock() else onLock(choice.profile)
|
||||
},
|
||||
onHide = {
|
||||
actionChoice = null
|
||||
onHide(choice.profile?.name)
|
||||
},
|
||||
onDismiss = { actionChoice = null },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun ProfileSwitcherSheet(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
profiles: List<Profile>,
|
||||
selectedProfile: Profile?,
|
||||
resolvedProfile: Profile?,
|
||||
presentation: ProfilePresentation,
|
||||
isProfileLocked: Boolean,
|
||||
switchEnabled: Boolean,
|
||||
onSelect: (Profile?) -> Unit,
|
||||
onManageDisplay: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val choices = remember(profiles, presentation, selectedProfile?.name) {
|
||||
ProfileShelfPolicy.choices(profiles, presentation, selectedProfile?.name)
|
||||
}
|
||||
ModalBottomSheet(onDismissRequest = onDismiss) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 560.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(bottom = 24.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.profile_shelf_switch_agent),
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp),
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
if (isProfileLocked) {
|
||||
Text(
|
||||
text = stringResource(R.string.profile_shelf_locked_hint),
|
||||
modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
choices.forEach { choice ->
|
||||
val selected = ProfileShelfPolicy.isSelected(choice, selectedProfile?.name)
|
||||
val label = profileChoiceLabel(choice, resolvedProfile)
|
||||
val model = choice.profile?.model?.takeIf { it.isNotBlank() }
|
||||
ListItem(
|
||||
modifier = Modifier.selectable(
|
||||
selected = selected,
|
||||
enabled = selected || (switchEnabled && !isProfileLocked),
|
||||
role = Role.RadioButton,
|
||||
onClick = {
|
||||
if (!selected) onSelect(choice.profile)
|
||||
onDismiss()
|
||||
},
|
||||
),
|
||||
headlineContent = {
|
||||
Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
},
|
||||
supportingContent = if (model != null) {
|
||||
{ Text(model, maxLines = 1, overflow = TextOverflow.Ellipsis) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
leadingContent = {
|
||||
ProfileChoiceAvatar(connectionViewModel, choice, resolvedProfile, label, 42)
|
||||
},
|
||||
trailingContent = if (selected) {
|
||||
{ Icon(Icons.Filled.Check, contentDescription = null) }
|
||||
} else {
|
||||
null
|
||||
},
|
||||
)
|
||||
}
|
||||
HorizontalDivider(modifier = Modifier.padding(top = 8.dp))
|
||||
TextButton(
|
||||
onClick = onManageDisplay,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 4.dp),
|
||||
) {
|
||||
Icon(Icons.Filled.Tune, contentDescription = null)
|
||||
Spacer(Modifier.size(8.dp))
|
||||
Text(stringResource(R.string.conn_info_manage_profiles))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProfileChoiceAvatar(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
choice: ProfileChoice,
|
||||
resolvedProfile: Profile?,
|
||||
label: String,
|
||||
size: Int,
|
||||
) {
|
||||
val iconProfileName = ProfileShelfPolicy.iconProfileName(choice)
|
||||
val iconPath by connectionViewModel.profileIconFlow(iconProfileName).collectAsState(initial = null)
|
||||
Box(modifier = Modifier.size(size.dp)) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f),
|
||||
),
|
||||
) {
|
||||
when {
|
||||
!iconPath.isNullOrBlank() -> AsyncImage(
|
||||
model = File(iconPath.orEmpty()),
|
||||
contentDescription = null,
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
resolvedProfile == null && choice.isServerDefault -> Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
Icons.Filled.Home,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size((size * 0.48f).dp),
|
||||
tint = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
}
|
||||
else -> Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
text = label.trim().firstOrNull()?.uppercase() ?: "H",
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (choice.isServerDefault && resolvedProfile != null) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomStart)
|
||||
.size((size * 0.38f).dp),
|
||||
shape = CircleShape,
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.surface),
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
Icons.Filled.Home,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size((size * 0.22f).dp),
|
||||
tint = MaterialTheme.colorScheme.onSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProfileShelfActionsDialog(
|
||||
label: String,
|
||||
canSwitch: Boolean,
|
||||
selected: Boolean,
|
||||
canInspect: Boolean,
|
||||
lockedToChoice: Boolean,
|
||||
onInspect: () -> Unit,
|
||||
onPassport: () -> Unit,
|
||||
onToggleLock: () -> Unit,
|
||||
onHide: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(label, maxLines = 1, overflow = TextOverflow.Ellipsis) },
|
||||
text = {
|
||||
Column {
|
||||
ProfileActionRow(Icons.Filled.Visibility, stringResource(R.string.profile_shelf_inspect), canInspect, onInspect)
|
||||
ProfileActionRow(
|
||||
Icons.Filled.Person,
|
||||
stringResource(R.string.conn_info_agent_passport),
|
||||
selected || canSwitch,
|
||||
onPassport,
|
||||
)
|
||||
ProfileActionRow(
|
||||
Icons.Filled.Lock,
|
||||
stringResource(if (lockedToChoice) R.string.settings_unlock else R.string.settings_profile_lock),
|
||||
true,
|
||||
onToggleLock,
|
||||
)
|
||||
ProfileActionRow(
|
||||
Icons.Filled.VisibilityOff,
|
||||
stringResource(R.string.profile_shelf_hide),
|
||||
!selected,
|
||||
onHide,
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.chat_dismiss)) } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProfileActionRow(
|
||||
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||
label: String,
|
||||
enabled: Boolean,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
TextButton(onClick = onClick, enabled = enabled, modifier = Modifier.fillMaxWidth()) {
|
||||
Icon(icon, contentDescription = null)
|
||||
Spacer(Modifier.size(12.dp))
|
||||
Text(label, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun profileChoiceLabel(choice: ProfileChoice, resolvedProfile: Profile?): String =
|
||||
if (choice.isServerDefault) {
|
||||
stringResource(R.string.conn_info_server_default)
|
||||
} else {
|
||||
choice.profile?.let(AgentDisplay::profileDisplayName)
|
||||
?: choice.profile?.name?.replaceFirstChar { it.uppercase() }
|
||||
?: resolvedProfile?.let(AgentDisplay::profileDisplayName)
|
||||
?: stringResource(R.string.chat_agent_default)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
/**
|
||||
* Model identity shown by chat-scoped controls.
|
||||
*
|
||||
* A running/resumed session owns its runtime model. Profile and server values
|
||||
* are defaults only, and may seed a fresh draft, but must never repaint an
|
||||
* existing session merely because a picker or Agent Passport was opened.
|
||||
*/
|
||||
internal data class SessionModelUiState(
|
||||
val model: String?,
|
||||
val provider: String?,
|
||||
val pickerModel: String?,
|
||||
val pickerProvider: String?,
|
||||
val inheritsProfileDefault: Boolean,
|
||||
)
|
||||
|
||||
internal fun resolveSessionModelUiState(
|
||||
hasSession: Boolean,
|
||||
pendingModel: String?,
|
||||
pendingProvider: String?,
|
||||
gatewayModel: String?,
|
||||
gatewayProvider: String?,
|
||||
persistedSessionModel: String?,
|
||||
profileDefaultModel: String?,
|
||||
serverDefaultModel: String?,
|
||||
): SessionModelUiState {
|
||||
fun String?.present(): String? = this?.trim()?.takeIf(String::isNotEmpty)
|
||||
|
||||
val pending = pendingModel.present()
|
||||
val gateway = gatewayModel.present()
|
||||
val persisted = persistedSessionModel.present()
|
||||
val profileDefault = profileDefaultModel.present()
|
||||
val serverDefault = serverDefaultModel.present()
|
||||
val effectiveModel = if (hasSession) {
|
||||
pending ?: gateway ?: persisted ?: profileDefault ?: serverDefault
|
||||
} else {
|
||||
pending ?: profileDefault ?: gateway ?: serverDefault
|
||||
}
|
||||
val effectiveProvider = pendingProvider.present()
|
||||
?: gatewayProvider.present()
|
||||
|
||||
return SessionModelUiState(
|
||||
model = effectiveModel,
|
||||
provider = effectiveProvider,
|
||||
// A live session highlights what it is actually running. On a fresh
|
||||
// draft, null remains the explicit "inherit profile default" state.
|
||||
pickerModel = if (hasSession) effectiveModel else pending,
|
||||
pickerProvider = if (hasSession) effectiveProvider else pendingProvider.present(),
|
||||
inheritsProfileDefault = !hasSession && pending == null,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import kotlinx.serialization.json.Json
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
|
||||
sealed interface SphereSkinImportResult {
|
||||
data class Success(val id: String, val label: String) : SphereSkinImportResult
|
||||
data class Failure(val reason: String) : SphereSkinImportResult
|
||||
}
|
||||
|
||||
/** Imports one declarative sphere-skin JSON file into app-scoped local storage. */
|
||||
object SphereSkinImporter {
|
||||
private const val TAG = "SphereSkinImporter"
|
||||
private const val MAX_BYTES = 256L * 1024L
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
}
|
||||
|
||||
fun importUri(context: Context, uri: Uri): SphereSkinImportResult {
|
||||
val input = try {
|
||||
context.contentResolver.openInputStream(uri)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "openInputStream failed: ${t.message}")
|
||||
null
|
||||
} ?: return SphereSkinImportResult.Failure("Couldn't open that file.")
|
||||
|
||||
return input.use { importStream(it, SphereSkinLoader.userDir(context)) }
|
||||
}
|
||||
|
||||
/** Pure import core used by tests: bounds, parses, validates, then swaps with rollback. */
|
||||
internal fun importStream(input: InputStream, skinsDir: File): SphereSkinImportResult {
|
||||
return try {
|
||||
val bytes = readBounded(input)
|
||||
?: return SphereSkinImportResult.Failure("That sphere file is too large.")
|
||||
val spec = try {
|
||||
json.decodeFromString(SphereSpec.serializer(), bytes.decodeToString())
|
||||
} catch (_: Throwable) {
|
||||
return SphereSkinImportResult.Failure("That sphere file isn't valid JSON.")
|
||||
}
|
||||
val resolved = spec.copy(id = spec.id.ifBlank { "custom-sphere" })
|
||||
val skin = try {
|
||||
resolved.toSkin()
|
||||
} catch (t: Throwable) {
|
||||
return SphereSkinImportResult.Failure(t.message ?: "That isn't a valid sphere skin.")
|
||||
}
|
||||
|
||||
skinsDir.mkdirs()
|
||||
val target = File(skinsDir, "${safeFileName(skin.id)}.json")
|
||||
val staging = File(skinsDir, ".${target.name}.tmp")
|
||||
val backup = File(skinsDir, ".${target.name}.bak")
|
||||
staging.writeBytes(bytes)
|
||||
if (backup.exists() && !target.exists()) backup.renameTo(target)
|
||||
if (backup.exists() && target.exists()) backup.delete()
|
||||
if (target.exists() && !target.renameTo(backup)) {
|
||||
staging.delete()
|
||||
return SphereSkinImportResult.Failure("Couldn't replace the existing sphere skin.")
|
||||
}
|
||||
if (!staging.renameTo(target)) {
|
||||
staging.delete()
|
||||
if (backup.exists()) backup.renameTo(target)
|
||||
return SphereSkinImportResult.Failure("Couldn't save that sphere skin.")
|
||||
}
|
||||
backup.delete()
|
||||
SphereSkinImportResult.Success(skin.id, skin.label)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "import failed: ${t.message}")
|
||||
SphereSkinImportResult.Failure("Couldn't import that sphere skin.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun readBounded(input: InputStream): ByteArray? {
|
||||
val buffer = ByteArray(8 * 1024)
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
if (total > MAX_BYTES) return null
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
private fun safeFileName(id: String): String = id.trim()
|
||||
.map { if (it.isLetterOrDigit() || it == '-' || it == '_' || it == '.') it else '-' }
|
||||
.joinToString("")
|
||||
.trim('.', '-')
|
||||
.ifBlank { "custom-sphere" }
|
||||
}
|
||||
@@ -15,12 +15,11 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.Psychology
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -29,6 +28,9 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalLocale
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import com.hermesandroid.relay.R
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -49,7 +51,12 @@ fun ThinkingBlock(
|
||||
/** Stable key when this interactive block participates in Chat pet terrain. */
|
||||
petObstacleKey: String? = null,
|
||||
) {
|
||||
if (thinkingContent.isBlank()) return
|
||||
var expanded by remember { mutableStateOf(isStreaming) }
|
||||
var userToggled by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(isStreaming) {
|
||||
if (!userToggled) expanded = isStreaming
|
||||
}
|
||||
val locale = LocalLocale.current.platformLocale
|
||||
val timeLabel = timestamp?.let {
|
||||
remember(it, locale) {
|
||||
@@ -57,8 +64,13 @@ fun ThinkingBlock(
|
||||
.format(java.util.Date(it))
|
||||
}
|
||||
}
|
||||
val expansionState = if (expanded) {
|
||||
stringResource(R.string.tool_progress_state_expanded)
|
||||
} else {
|
||||
stringResource(R.string.tool_progress_state_collapsed)
|
||||
}
|
||||
|
||||
Card(
|
||||
Column(
|
||||
modifier = modifier
|
||||
.then(
|
||||
if (petObstacleKey != null) {
|
||||
@@ -71,18 +83,20 @@ fun ThinkingBlock(
|
||||
},
|
||||
)
|
||||
.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(8.dp)) {
|
||||
// Header row
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { expanded = !expanded },
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(role = Role.Button) {
|
||||
userToggled = true
|
||||
expanded = !expanded
|
||||
}
|
||||
.semantics {
|
||||
stateDescription = expansionState
|
||||
}
|
||||
.padding(horizontal = 4.dp, vertical = 3.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Psychology,
|
||||
contentDescription = accessibilityLabel,
|
||||
@@ -91,9 +105,13 @@ fun ThinkingBlock(
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = headerText ?: if (isStreaming) stringResource(R.string.thinking_thinking) else stringResource(R.string.thinking_title),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.tertiary
|
||||
text = headerText ?: if (isStreaming) {
|
||||
stringResource(R.string.thinking_thinking)
|
||||
} else {
|
||||
stringResource(R.string.thinking_settled)
|
||||
},
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
Spacer(modifier = Modifier.weight(1f))
|
||||
if (!isStreaming && timeLabel != null) {
|
||||
@@ -110,25 +128,23 @@ fun ThinkingBlock(
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Collapsible content
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically(),
|
||||
exit = shrinkVertically()
|
||||
) {
|
||||
Text(
|
||||
text = thinkingContent,
|
||||
style = MaterialTheme.typography.bodySmall.copy(
|
||||
fontFamily = FontFamily.Default,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
),
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
maxLines = if (isStreaming) Int.MAX_VALUE else 50,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically(),
|
||||
exit = shrinkVertically()
|
||||
) {
|
||||
Text(
|
||||
text = thinkingContent,
|
||||
style = MaterialTheme.typography.bodySmall.copy(
|
||||
fontFamily = FontFamily.Default,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
),
|
||||
modifier = Modifier.padding(start = 26.dp, top = 2.dp, end = 4.dp, bottom = 4.dp),
|
||||
maxLines = if (isStreaming) Int.MAX_VALUE else 50,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.slideInVertically
|
||||
import androidx.compose.animation.slideOutVertically
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.MoreHoriz
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalResources
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.stateDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.ToolCall
|
||||
import com.hermesandroid.relay.ui.components.pet.petObstacleSurface
|
||||
|
||||
private val TOOL_ACTIVITY_PET_ROUTES = setOf("chat")
|
||||
private val FILE_EDIT_TOOLS = setOf("edit_file", "write_file", "apply_patch", "patch")
|
||||
private val ATTENTION_TOOLS = setOf(
|
||||
"clarify",
|
||||
"delegate_task",
|
||||
"image_generate",
|
||||
"approval",
|
||||
"request_user_input",
|
||||
"ask_user",
|
||||
"sudo",
|
||||
"secret",
|
||||
)
|
||||
|
||||
internal sealed interface ToolTranscriptItem {
|
||||
data class ActivityRun(val calls: List<ToolCall>) : ToolTranscriptItem
|
||||
data class Standalone(val call: ToolCall) : ToolTranscriptItem
|
||||
}
|
||||
|
||||
/** Off suppresses diagnostics, never an attention or deliverable surface. */
|
||||
internal fun ToolTranscriptItem.isVisibleForToolDisplay(toolDisplay: String): Boolean =
|
||||
this is ToolTranscriptItem.Standalone || toolDisplay != "off"
|
||||
|
||||
/**
|
||||
* Preserve source order while folding only routine activity. Calls that are
|
||||
* actionable, security-relevant, failed, or deliver a file/media result split
|
||||
* the run and retain their own surface.
|
||||
*/
|
||||
internal fun groupTranscriptTools(calls: List<ToolCall>): List<ToolTranscriptItem> {
|
||||
val result = mutableListOf<ToolTranscriptItem>()
|
||||
val run = mutableListOf<ToolCall>()
|
||||
|
||||
fun flushRun() {
|
||||
if (run.isNotEmpty()) {
|
||||
result += ToolTranscriptItem.ActivityRun(run.toList())
|
||||
run.clear()
|
||||
}
|
||||
}
|
||||
|
||||
calls.forEach { call ->
|
||||
if (call.requiresStandaloneToolSurface()) {
|
||||
flushRun()
|
||||
result += ToolTranscriptItem.Standalone(call)
|
||||
} else {
|
||||
run += call
|
||||
}
|
||||
}
|
||||
flushRun()
|
||||
return result
|
||||
}
|
||||
|
||||
internal fun ToolCall.requiresStandaloneToolSurface(): Boolean {
|
||||
val normalized = name.trim().lowercase()
|
||||
return success == false ||
|
||||
!error.isNullOrBlank() ||
|
||||
outputRisk != null ||
|
||||
normalized in FILE_EDIT_TOOLS ||
|
||||
normalized in ATTENTION_TOOLS
|
||||
}
|
||||
|
||||
internal data class ToolActivityCounts(
|
||||
val reads: Int = 0,
|
||||
val searches: Int = 0,
|
||||
val commands: Int = 0,
|
||||
val browserActions: Int = 0,
|
||||
val deviceActions: Int = 0,
|
||||
val other: Int = 0,
|
||||
)
|
||||
|
||||
internal fun countToolActivity(calls: List<ToolCall>): ToolActivityCounts {
|
||||
var counts = ToolActivityCounts()
|
||||
calls.forEach { call ->
|
||||
val name = call.name.trim().lowercase()
|
||||
counts = when {
|
||||
name.contains("search") || name.contains("grep") || name.contains("find") ->
|
||||
counts.copy(searches = counts.searches + 1)
|
||||
name.contains("terminal") || name.contains("shell") || name.contains("exec") ||
|
||||
name.contains("command") || name.contains("bash") || name.contains("powershell") ->
|
||||
counts.copy(commands = counts.commands + 1)
|
||||
name.contains("browser") || name.contains("chrome") || name.contains("playwright") ||
|
||||
name.startsWith("web_") -> counts.copy(browserActions = counts.browserActions + 1)
|
||||
name.contains("android") || name.contains("adb") || name.contains("device") ||
|
||||
name.contains("tap") || name.contains("swipe") ->
|
||||
counts.copy(deviceActions = counts.deviceActions + 1)
|
||||
name.contains("read") || name.contains("list") || name.contains("glob") ||
|
||||
name.contains("open") || name.contains("inspect") -> counts.copy(reads = counts.reads + 1)
|
||||
else -> counts.copy(other = counts.other + 1)
|
||||
}
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun ToolActivityRun(
|
||||
calls: List<ToolCall>,
|
||||
live: Boolean,
|
||||
detailed: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
messageTimestamp: Long? = null,
|
||||
petObstacleKey: String? = null,
|
||||
onExpandedChange: (Boolean) -> Unit = {},
|
||||
) {
|
||||
if (calls.isEmpty()) return
|
||||
var expanded by rememberSaveable(calls.first().uiKey) { mutableStateOf(false) }
|
||||
val summary = toolActivitySummary(countToolActivity(calls), live)
|
||||
val stateLabel = if (expanded) {
|
||||
stringResource(R.string.tool_progress_cd_collapse)
|
||||
} else {
|
||||
stringResource(R.string.tool_progress_cd_expand)
|
||||
}
|
||||
val expansionState = if (expanded) {
|
||||
stringResource(R.string.tool_progress_state_expanded)
|
||||
} else {
|
||||
stringResource(R.string.tool_progress_state_collapsed)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.then(
|
||||
if (petObstacleKey != null) {
|
||||
Modifier.petObstacleSurface(petObstacleKey, TOOL_ACTIVITY_PET_ROUTES)
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
)
|
||||
.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(role = Role.Button) {
|
||||
expanded = !expanded
|
||||
onExpandedChange(expanded)
|
||||
}
|
||||
.semantics {
|
||||
contentDescription = summary
|
||||
stateDescription = expansionState
|
||||
}
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.MoreHoriz,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = if (live) MaterialTheme.colorScheme.tertiary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(modifier = Modifier.width(6.dp))
|
||||
Text(
|
||||
text = summary,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Icon(
|
||||
imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
|
||||
contentDescription = stateLabel,
|
||||
modifier = Modifier.size(16.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
if (live && !expanded) {
|
||||
val latest = calls.last()
|
||||
AnimatedContent(
|
||||
targetState = latest.uiKey,
|
||||
transitionSpec = {
|
||||
(slideInVertically { it / 2 } + fadeIn()) togetherWith
|
||||
(slideOutVertically { -it / 2 } + fadeOut())
|
||||
},
|
||||
label = "toolActivityTicker",
|
||||
) { latestKey ->
|
||||
val visible = calls.lastOrNull { it.uiKey == latestKey } ?: latest
|
||||
Text(
|
||||
text = toolActivityTickerLabel(visible),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.78f),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(start = 26.dp, end = 4.dp, bottom = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically(),
|
||||
exit = shrinkVertically(),
|
||||
) {
|
||||
Column(modifier = Modifier.padding(start = 22.dp, top = 2.dp)) {
|
||||
calls.forEach { call ->
|
||||
key(call.uiKey) {
|
||||
if (detailed) {
|
||||
ToolProgressCard(
|
||||
toolCall = call,
|
||||
messageTimestamp = messageTimestamp,
|
||||
onExpandedChange = onExpandedChange,
|
||||
)
|
||||
} else {
|
||||
CompactToolCall(toolCall = call)
|
||||
}
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun toolActivitySummary(counts: ToolActivityCounts, live: Boolean): String {
|
||||
val resources = LocalResources.current
|
||||
val clauses = buildList {
|
||||
fun addClause(count: Int, liveRes: Int, settledRes: Int) {
|
||||
if (count > 0) add(resources.getQuantityString(if (live) liveRes else settledRes, count, count))
|
||||
}
|
||||
addClause(counts.reads, R.plurals.tool_run_reading, R.plurals.tool_run_read)
|
||||
addClause(counts.searches, R.plurals.tool_run_searching, R.plurals.tool_run_searched)
|
||||
addClause(counts.commands, R.plurals.tool_run_running_commands, R.plurals.tool_run_ran_commands)
|
||||
addClause(counts.browserActions, R.plurals.tool_run_browsing, R.plurals.tool_run_browsed)
|
||||
addClause(counts.deviceActions, R.plurals.tool_run_using_device, R.plurals.tool_run_used_device)
|
||||
addClause(counts.other, R.plurals.tool_run_using_tools, R.plurals.tool_run_used_tools)
|
||||
}
|
||||
return clauses.joinToString(" · ")
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun toolActivityTickerLabel(call: ToolCall): String {
|
||||
val name = localizeToolName(call.name).ifBlank { stringResource(R.string.tool_preparing) }
|
||||
return when {
|
||||
call.isGenerating && !call.isComplete -> stringResource(R.string.tool_run_preparing, name)
|
||||
!call.isComplete -> stringResource(R.string.tool_run_running, name)
|
||||
else -> stringResource(R.string.tool_run_finished, name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.platform.testTag
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.ui.theme.LocalBrand
|
||||
|
||||
@Immutable
|
||||
data class TranscriptMatch(
|
||||
val messageUiKey: String,
|
||||
val messageIndex: Int,
|
||||
val start: Int,
|
||||
val endExclusive: Int,
|
||||
)
|
||||
|
||||
@Immutable
|
||||
data class TranscriptTurnMarker(
|
||||
val messageUiKey: String,
|
||||
val messageIndex: Int,
|
||||
val turnNumber: Int,
|
||||
val label: String,
|
||||
val matchCount: Int,
|
||||
val containsActiveMatch: Boolean,
|
||||
)
|
||||
|
||||
@Immutable
|
||||
data class TranscriptNavigationModel(
|
||||
val matches: List<TranscriptMatch>,
|
||||
val turns: List<TranscriptTurnMarker>,
|
||||
)
|
||||
|
||||
/**
|
||||
* User-facing copy is injectable so the component remains reusable and its
|
||||
* eventual ChatScreen integration can supply localized resources without
|
||||
* coupling the pure navigation model to Android resources.
|
||||
*/
|
||||
@Immutable
|
||||
data class TranscriptNavigatorStrings(
|
||||
val searchPlaceholder: String = "Search conversation",
|
||||
val previousMatch: String = "Previous match",
|
||||
val nextMatch: String = "Next match",
|
||||
val closeSearch: String = "Close search",
|
||||
val noResults: String = "No results",
|
||||
val resultCount: (current: Int, total: Int) -> String = { current, total -> "$current of $total" },
|
||||
val resultCountDescription: (current: Int, total: Int) -> String = { current, total ->
|
||||
if (total == 0) "No search results" else "Search result $current of $total"
|
||||
},
|
||||
val turnDescription: (turn: Int, label: String, matches: Int) -> String = { turn, label, matches ->
|
||||
val suffix = if (matches == 1) ", 1 match" else if (matches > 1) ", $matches matches" else ""
|
||||
"Jump to turn $turn: $label$suffix"
|
||||
},
|
||||
)
|
||||
|
||||
object TranscriptNavigatorTestTags {
|
||||
const val Query = "transcript-search-query"
|
||||
const val ResultCount = "transcript-search-result-count"
|
||||
const val Previous = "transcript-search-previous"
|
||||
const val Next = "transcript-search-next"
|
||||
const val Close = "transcript-search-close"
|
||||
const val TurnPrefix = "transcript-turn-"
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact, self-contained find bar plus prompt rail for an active transcript.
|
||||
* All jump callbacks use [ChatMessage.uiKey], the same stable identity used by
|
||||
* Chat's LazyColumn, so a history reconciliation cannot invalidate a target.
|
||||
*/
|
||||
@Composable
|
||||
fun TranscriptSearchNavigator(
|
||||
messages: List<ChatMessage>,
|
||||
onJumpToMessage: (messageUiKey: String) -> Unit,
|
||||
onClose: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
initialQuery: String = "",
|
||||
strings: TranscriptNavigatorStrings = TranscriptNavigatorStrings(),
|
||||
) {
|
||||
val brand = LocalBrand.current
|
||||
var query by rememberSaveable { mutableStateOf(initialQuery) }
|
||||
var activeMatchIndex by rememberSaveable { mutableIntStateOf(0) }
|
||||
val model = remember(messages, query, activeMatchIndex) {
|
||||
buildTranscriptNavigationModel(messages, query, activeMatchIndex)
|
||||
}
|
||||
val normalizedActiveIndex = activeMatchIndex.coerceIn(0, (model.matches.size - 1).coerceAtLeast(0))
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
runCatching { focusRequester.requestFocus() }
|
||||
}
|
||||
|
||||
fun selectMatch(index: Int) {
|
||||
if (model.matches.isEmpty()) return
|
||||
val normalized = Math.floorMod(index, model.matches.size)
|
||||
activeMatchIndex = normalized
|
||||
onJumpToMessage(model.matches[normalized].messageUiKey)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.background(brand.navy)
|
||||
.border(1.dp, brand.line, RoundedCornerShape(14.dp))
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(brand.surfaceLow)
|
||||
.border(1.dp, brand.line, RoundedCornerShape(10.dp))
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Search,
|
||||
contentDescription = null,
|
||||
tint = brand.muted,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
BasicTextField(
|
||||
value = query,
|
||||
onValueChange = {
|
||||
query = it
|
||||
activeMatchIndex = 0
|
||||
},
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.focusRequester(focusRequester)
|
||||
.testTag(TranscriptNavigatorTestTags.Query),
|
||||
singleLine = true,
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(color = brand.ink),
|
||||
cursorBrush = SolidColor(brand.relay),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { selectMatch(normalizedActiveIndex) }),
|
||||
decorationBox = { inner ->
|
||||
Box {
|
||||
if (query.isEmpty()) {
|
||||
Text(
|
||||
text = strings.searchPlaceholder,
|
||||
color = brand.dim,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
}
|
||||
inner()
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
val current = if (model.matches.isEmpty()) 0 else normalizedActiveIndex + 1
|
||||
Text(
|
||||
text = if (model.matches.isEmpty() && query.isNotBlank()) {
|
||||
strings.noResults
|
||||
} else {
|
||||
strings.resultCount(current, model.matches.size)
|
||||
},
|
||||
color = brand.muted,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
modifier = Modifier
|
||||
.testTag(TranscriptNavigatorTestTags.ResultCount)
|
||||
.semantics {
|
||||
contentDescription = strings.resultCountDescription(current, model.matches.size)
|
||||
},
|
||||
)
|
||||
IconButton(
|
||||
onClick = { selectMatch(normalizedActiveIndex - 1) },
|
||||
enabled = model.matches.isNotEmpty(),
|
||||
modifier = Modifier.testTag(TranscriptNavigatorTestTags.Previous),
|
||||
) {
|
||||
Icon(Icons.Filled.KeyboardArrowUp, strings.previousMatch, tint = brand.ink)
|
||||
}
|
||||
IconButton(
|
||||
onClick = { selectMatch(normalizedActiveIndex + 1) },
|
||||
enabled = model.matches.isNotEmpty(),
|
||||
modifier = Modifier.testTag(TranscriptNavigatorTestTags.Next),
|
||||
) {
|
||||
Icon(Icons.Filled.KeyboardArrowDown, strings.nextMatch, tint = brand.ink)
|
||||
}
|
||||
IconButton(
|
||||
onClick = onClose,
|
||||
modifier = Modifier.testTag(TranscriptNavigatorTestTags.Close),
|
||||
) {
|
||||
Icon(Icons.Filled.Close, strings.closeSearch, tint = brand.ink)
|
||||
}
|
||||
}
|
||||
|
||||
TranscriptTurnRail(
|
||||
turns = model.turns,
|
||||
onJumpToMessage = onJumpToMessage,
|
||||
strings = strings,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun TranscriptTurnRail(
|
||||
turns: List<TranscriptTurnMarker>,
|
||||
onJumpToMessage: (messageUiKey: String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
strings: TranscriptNavigatorStrings = TranscriptNavigatorStrings(),
|
||||
) {
|
||||
if (turns.isEmpty()) return
|
||||
val brand = LocalBrand.current
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.horizontalScroll(rememberScrollState()),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
turns.forEach { turn ->
|
||||
IconButton(
|
||||
onClick = { onJumpToMessage(turn.messageUiKey) },
|
||||
modifier = Modifier
|
||||
.testTag("${TranscriptNavigatorTestTags.TurnPrefix}${turn.messageUiKey}")
|
||||
.semantics {
|
||||
contentDescription = strings.turnDescription(
|
||||
turn.turnNumber,
|
||||
turn.label,
|
||||
turn.matchCount,
|
||||
)
|
||||
},
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(if (turn.containsActiveMatch) 12.dp else 8.dp)
|
||||
.clip(RoundedCornerShape(50))
|
||||
.background(
|
||||
when {
|
||||
turn.containsActiveMatch -> brand.relay
|
||||
turn.matchCount > 0 -> brand.purple
|
||||
else -> brand.dim
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun buildTranscriptNavigationModel(
|
||||
messages: List<ChatMessage>,
|
||||
query: String,
|
||||
activeMatchIndex: Int = 0,
|
||||
): TranscriptNavigationModel {
|
||||
val needle = query.trim()
|
||||
val matches = if (needle.isEmpty()) {
|
||||
emptyList()
|
||||
} else {
|
||||
buildList {
|
||||
messages.forEachIndexed { messageIndex, message ->
|
||||
val text = message.searchableRenderedText()
|
||||
var start = 0
|
||||
while (start <= text.length - needle.length) {
|
||||
val found = text.indexOf(needle, startIndex = start, ignoreCase = true)
|
||||
if (found < 0) break
|
||||
add(TranscriptMatch(message.uiKey, messageIndex, found, found + needle.length))
|
||||
start = found + needle.length.coerceAtLeast(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val activeMatch = matches.getOrNull(activeMatchIndex.coerceIn(0, (matches.size - 1).coerceAtLeast(0)))
|
||||
val userIndexes = messages.indices.filter { messages[it].role == MessageRole.USER }
|
||||
val turns = userIndexes.mapIndexed { ordinal, messageIndex ->
|
||||
val endExclusive = userIndexes.getOrNull(ordinal + 1) ?: messages.size
|
||||
val turnMatches = matches.count { it.messageIndex in messageIndex until endExclusive }
|
||||
val prompt = messages[messageIndex]
|
||||
TranscriptTurnMarker(
|
||||
messageUiKey = prompt.uiKey,
|
||||
messageIndex = messageIndex,
|
||||
turnNumber = ordinal + 1,
|
||||
label = prompt.content.compactTranscriptLabel("Prompt ${ordinal + 1}"),
|
||||
matchCount = turnMatches,
|
||||
containsActiveMatch = activeMatch?.messageIndex?.let { it in messageIndex until endExclusive } == true,
|
||||
)
|
||||
}
|
||||
return TranscriptNavigationModel(matches = matches, turns = turns)
|
||||
}
|
||||
|
||||
internal fun ChatMessage.searchableRenderedText(): String = buildList {
|
||||
add(content)
|
||||
add(thinkingContent)
|
||||
moaReferences.forEach {
|
||||
add(it.label)
|
||||
add(it.text)
|
||||
}
|
||||
toolCalls.forEach {
|
||||
add(it.name)
|
||||
add(it.taskLabel.orEmpty())
|
||||
add(it.args.orEmpty())
|
||||
add(it.result.orEmpty())
|
||||
add(it.error.orEmpty())
|
||||
}
|
||||
attachments.forEach {
|
||||
add(it.fileName.orEmpty())
|
||||
add(it.errorMessage.orEmpty())
|
||||
}
|
||||
cards.forEach { card ->
|
||||
add(card.title.orEmpty())
|
||||
add(card.subtitle.orEmpty())
|
||||
add(card.body.orEmpty())
|
||||
card.fields.forEach {
|
||||
add(it.label)
|
||||
add(it.value)
|
||||
}
|
||||
card.actions.forEach { add(it.label) }
|
||||
add(card.footer.orEmpty())
|
||||
}
|
||||
}.filter(String::isNotBlank).joinToString("\n")
|
||||
|
||||
private fun String.compactTranscriptLabel(fallback: String): String {
|
||||
val compact = trim().replace(Regex("\\s+"), " ")
|
||||
return when {
|
||||
compact.isEmpty() -> fallback
|
||||
compact.length <= 64 -> compact
|
||||
else -> compact.take(61).trimEnd() + "…"
|
||||
}
|
||||
}
|
||||
@@ -104,8 +104,8 @@ interface AgentAvatar {
|
||||
}
|
||||
|
||||
/**
|
||||
* Legacy ambient-visualization seam. The app now provides [SphereAvatar] here;
|
||||
* floating companions are published through [LocalFloatingPet].
|
||||
* Central/ambient visualization seam. The app provides the independently saved
|
||||
* Sphere or pet-format background here; floating companions use [LocalFloatingPet].
|
||||
*/
|
||||
val LocalAgentAvatar = staticCompositionLocalOf<AgentAvatar> { SphereAvatar }
|
||||
|
||||
@@ -117,14 +117,20 @@ val LocalAvailableAvatars = staticCompositionLocalOf<List<AgentAvatar>> { listOf
|
||||
|
||||
/**
|
||||
* The optional floating pet companion. Unlike [LocalAgentAvatar], this does not
|
||||
* replace the ambient sphere or the active profile's identity image. `null`
|
||||
* means the user has not selected a companion.
|
||||
* replace the independently selected central/background visualization or the
|
||||
* active profile's identity image. `null` means no companion is selected.
|
||||
*/
|
||||
val LocalFloatingPet = staticCompositionLocalOf<AgentAvatar?> { null }
|
||||
|
||||
/** User-installed pets available to the companion picker (sphere excluded). */
|
||||
val LocalAvailablePets = staticCompositionLocalOf<List<AgentAvatar>> { emptyList() }
|
||||
|
||||
/** Resolve a central visualization without ever coupling it to floating state. */
|
||||
internal fun resolveBackgroundAvatar(
|
||||
selectedId: String,
|
||||
availablePets: List<AgentAvatar>,
|
||||
): AgentAvatar = availablePets.firstOrNull { it.id == selectedId } ?: SphereAvatar
|
||||
|
||||
/** Ambient sphere/background visibility, independent of the motion setting. */
|
||||
val LocalBackgroundVisualizationEnabled = staticCompositionLocalOf { true }
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ import androidx.compose.ui.geometry.Rect
|
||||
import androidx.compose.ui.layout.boundsInRoot
|
||||
import androidx.compose.ui.layout.onGloballyPositioned
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import com.hermesandroid.relay.ui.components.SphereState
|
||||
import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
|
||||
|
||||
@@ -100,6 +102,7 @@ class PetCompanionCoordinator {
|
||||
private var renderState by mutableStateOf(AvatarRenderState(SphereState.Idle))
|
||||
private var visitRequestState by mutableStateOf(PetVisitRequestState())
|
||||
private val surfaces = mutableStateMapOf<String, PetCompanionSurface>()
|
||||
private val interactionLayers = mutableStateMapOf<String, Boolean>()
|
||||
|
||||
val pendingVisitRequest: PetVisitRequest?
|
||||
get() = visitRequestState.pending
|
||||
@@ -141,20 +144,49 @@ class PetCompanionCoordinator {
|
||||
surfaces.remove(owner)
|
||||
}
|
||||
|
||||
/** App-wide UI ownership gate for drawers and other same-window overlays. */
|
||||
fun publishInteractionLayer(owner: String, active: Boolean) {
|
||||
require(owner.isNotBlank()) { "Pet interaction-layer owner must not be blank." }
|
||||
if (active) interactionLayers[owner] = true else interactionLayers.remove(owner)
|
||||
}
|
||||
|
||||
fun clearInteractionLayer(owner: String) {
|
||||
interactionLayers.remove(owner)
|
||||
}
|
||||
|
||||
fun activityFor(owner: String?): PetCompanionActivity {
|
||||
val surface = owner?.let(surfaces::get)
|
||||
return PetCompanionActivity(
|
||||
renderState = renderState,
|
||||
scrolling = surface?.scrolling == true,
|
||||
hidden = surface?.hidden == true,
|
||||
hidden = surface?.hidden == true || interactionLayers.values.any { it },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private data class PetCompanionSurface(val scrolling: Boolean, val hidden: Boolean)
|
||||
|
||||
/** A pet-owned popup may take window focus without becoming a competing modal. */
|
||||
internal fun platformModalOwnsPetLayer(
|
||||
windowFocused: Boolean,
|
||||
petMenuExpanded: Boolean,
|
||||
): Boolean = !windowFocused && !petMenuExpanded
|
||||
|
||||
val LocalPetCompanionCoordinator = staticCompositionLocalOf { PetCompanionCoordinator() }
|
||||
|
||||
/**
|
||||
* Declares that a same-window interaction layer currently owns input. Platform
|
||||
* dialogs and modal sheets are covered separately by root window-focus state.
|
||||
*/
|
||||
@Composable
|
||||
fun PetInteractionLayer(owner: String, active: Boolean) {
|
||||
val coordinator = LocalPetCompanionCoordinator.current
|
||||
SideEffect { coordinator.publishInteractionLayer(owner, active) }
|
||||
DisposableEffect(coordinator, owner) {
|
||||
onDispose { coordinator.clearInteractionLayer(owner) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explicit UI surfaces measured by their owners. Their top edges become
|
||||
* walkable perches, matching Hermes Desktop's live-DOM ledge model without
|
||||
|
||||
@@ -60,6 +60,7 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.PhysicalKeyboardEnterBehavior
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.ServerCapabilities
|
||||
import com.hermesandroid.relay.ui.components.ChatTransportStatus
|
||||
@@ -443,6 +444,48 @@ fun ChatSettingsScreen(
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
val physicalKeyboardEnterBehavior by
|
||||
connectionViewModel.physicalKeyboardEnterBehavior.collectAsState()
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.chat_settings_physical_keyboard_enter),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.chat_settings_physical_keyboard_enter_desc),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
val enterBehaviors = PhysicalKeyboardEnterBehavior.entries
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
enterBehaviors.forEachIndexed { index, behavior ->
|
||||
SegmentedButton(
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = enterBehaviors.size,
|
||||
),
|
||||
onClick = {
|
||||
connectionViewModel.setPhysicalKeyboardEnterBehavior(behavior)
|
||||
},
|
||||
selected = behavior == physicalKeyboardEnterBehavior,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (behavior == PhysicalKeyboardEnterBehavior.SendMessage) {
|
||||
R.string.chat_input_send_message
|
||||
} else {
|
||||
R.string.chat_settings_insert_newline
|
||||
},
|
||||
),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
|
||||
// Background chat-alert toggle. First enable on
|
||||
// API 33+ runs the POST_NOTIFICATIONS request (the
|
||||
// BridgeScreen master-toggle precedent); if the user
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.hermesandroid.relay.ui.screens
|
||||
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.AutoAwesome
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.TopAppBarDefaults
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
internal enum class CustomPetKind { STATIC, ANIMATED }
|
||||
|
||||
internal fun buildCustomPetPrompt(
|
||||
name: String,
|
||||
description: String,
|
||||
kind: CustomPetKind,
|
||||
): String {
|
||||
val safeName = name.trim().ifBlank { "My Hermes companion" }
|
||||
val safeDescription = description.trim().ifBlank {
|
||||
"a friendly companion that remains recognizable at small mobile sizes"
|
||||
}
|
||||
val output = if (kind == CustomPetKind.STATIC) {
|
||||
"Create one transparent PNG or WebP image. Keep the subject centered with generous edge padding."
|
||||
} else {
|
||||
"Create a validated Hermes pet pack ZIP using pet.json plus transparent sprite sheets. " +
|
||||
"Include idle, walk-left/right, thinking or working, writing, speaking, listening, greet, done, and error where practical. " +
|
||||
"Frames must show real motion while keeping the character, scale, baseline, and anchor consistent. " +
|
||||
"At minimum, pet.json must use schemaVersion 1, a stable id and label, and an idle state. " +
|
||||
"A frame-list state is shaped like {\"frames\":[\"idle-01.png\"],\"fps\":8}; a sheet state is shaped like " +
|
||||
"{\"sheet\":\"idle.png\",\"frameWidth\":256,\"frameHeight\":256,\"frameCount\":16,\"fps\":8}. " +
|
||||
"All referenced files must remain inside the pack folder."
|
||||
}
|
||||
return """
|
||||
Help me create a custom floating pet for the Hermes Relay Android app.
|
||||
|
||||
Pet name: $safeName
|
||||
Character direction: $safeDescription
|
||||
Format: ${if (kind == CustomPetKind.STATIC) "single static image" else "animated pet pack"}
|
||||
|
||||
$output
|
||||
|
||||
Follow the current Hermes Relay pet contract above. If the repository docs/pet-spec.md or user-docs/features/custom-avatars.md are available, use them as the final authority. Use image-generation tools only if they are available in this chat. Do not upload my reference image, generated art, or pet pack anywhere except through tools I explicitly approve. Work locally where possible.
|
||||
|
||||
Before returning anything, validate the manifest and every referenced file, reject path traversal, verify decoded image dimensions and safe margins, and check that animated frames differ visibly without drifting. Then show me a concise review summary and attach the final PNG/WebP or ZIP for me to inspect. Do not install, publish, or share it automatically. I will review it and import it from Appearance > Floating pet.
|
||||
|
||||
If you need a visual reference, ask me to attach it in this chat before generating the pet.
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
fun CustomPetGuideScreen(
|
||||
connectionViewModel: ConnectionViewModel,
|
||||
onBack: () -> Unit,
|
||||
onStartNewChat: (String) -> Unit,
|
||||
) {
|
||||
var name by remember { mutableStateOf("") }
|
||||
var description by remember { mutableStateOf("") }
|
||||
var kind by remember { mutableStateOf(CustomPetKind.ANIMATED) }
|
||||
val prompt = remember(name, description, kind) { buildCustomPetPrompt(name, description, kind) }
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val copiedMessage = stringResource(R.string.pet_creator_copied)
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val importLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
|
||||
uri?.let(connectionViewModel::importPet)
|
||||
}
|
||||
LaunchedEffect(connectionViewModel) {
|
||||
connectionViewModel.avatarEvents.collect { snackbarHostState.showSnackbar(it) }
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.pet_creator_title)) },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.appearance_back))
|
||||
}
|
||||
},
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
) { innerPadding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(innerPadding)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.pet_creator_intro),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
GuideCard(step = "1", title = stringResource(R.string.pet_creator_step_idea)) {
|
||||
OutlinedTextField(
|
||||
value = name,
|
||||
onValueChange = { name = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.pet_creator_name)) },
|
||||
singleLine = true,
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = description,
|
||||
onValueChange = { description = it },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
label = { Text(stringResource(R.string.pet_creator_description)) },
|
||||
supportingText = { Text(stringResource(R.string.pet_creator_description_hint)) },
|
||||
minLines = 3,
|
||||
)
|
||||
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip(
|
||||
selected = kind == CustomPetKind.ANIMATED,
|
||||
onClick = { kind = CustomPetKind.ANIMATED },
|
||||
label = { Text(stringResource(R.string.pet_creator_animated)) },
|
||||
)
|
||||
FilterChip(
|
||||
selected = kind == CustomPetKind.STATIC,
|
||||
onClick = { kind = CustomPetKind.STATIC },
|
||||
label = { Text(stringResource(R.string.pet_creator_static)) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
GuideCard(step = "2", title = stringResource(R.string.pet_creator_step_create)) {
|
||||
Text(
|
||||
text = stringResource(R.string.pet_creator_review_copy),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
) {
|
||||
Text(
|
||||
text = prompt,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
clipboard.setText(AnnotatedString(prompt))
|
||||
scope.launch { snackbarHostState.showSnackbar(copiedMessage) }
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(Icons.Filled.ContentCopy, null)
|
||||
Text(stringResource(R.string.pet_creator_copy), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
Button(
|
||||
onClick = { onStartNewChat(prompt) },
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(Icons.Filled.AutoAwesome, null)
|
||||
Text(stringResource(R.string.pet_creator_new_chat), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GuideCard(step = "3", title = stringResource(R.string.pet_creator_step_review)) {
|
||||
Text(
|
||||
text = stringResource(R.string.pet_creator_review_desc),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
importLauncher.launch(arrayOf("application/zip", "image/*", "application/octet-stream", "*/*"))
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(Icons.Filled.Add, null)
|
||||
Text(stringResource(R.string.pet_creator_import), modifier = Modifier.padding(start = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GuideCard(step: String, title: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "$step · $title",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -424,7 +424,6 @@ fun SettingsScreen(
|
||||
val lockedDisplayName: String? = when {
|
||||
!isProfileLocked -> null
|
||||
lockedProfileName == null ||
|
||||
AgentDisplay.isServerDefaultAlias(lockedProfileName) ||
|
||||
lockedProfileName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY ->
|
||||
serverDefaultLabel
|
||||
else ->
|
||||
@@ -1055,13 +1054,12 @@ private fun ProfileLockDialog(
|
||||
onUnlock: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
// Selectable rows: a synthetic "Server default" sentinel + the advertised
|
||||
// profiles, minus the synthetic "default" alias (folded into Server default).
|
||||
val selectableProfiles = profiles.filterNot { AgentDisplay.isServerDefaultAlias(it.name) }
|
||||
// Selectable rows: a synthetic "Server default" sentinel + every advertised
|
||||
// profile, including a profile literally named `default`.
|
||||
val selectableProfiles = profiles
|
||||
|
||||
// Is the stored lock target Server default (sentinel / "default" alias / null)?
|
||||
// Is the stored lock target Server default (sentinel / null)?
|
||||
val lockedIsServerDefault = lockedProfileName == null ||
|
||||
AgentDisplay.isServerDefaultAlias(lockedProfileName) ||
|
||||
lockedProfileName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
val lockedProfile = if (lockedIsServerDefault) {
|
||||
null
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hermesandroid.relay.ui.theme
|
||||
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Shapes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
enum class AppearanceShape(val id: String) {
|
||||
SOFT("soft"),
|
||||
BALANCED("balanced"),
|
||||
SHARP("sharp");
|
||||
|
||||
companion object {
|
||||
val DEFAULT = SOFT
|
||||
|
||||
fun fromId(id: String?): AppearanceShape = entries.firstOrNull { it.id == id } ?: DEFAULT
|
||||
}
|
||||
}
|
||||
|
||||
fun appearanceShapes(shapeId: String?): Shapes = when (AppearanceShape.fromId(shapeId)) {
|
||||
AppearanceShape.SOFT -> Shapes(
|
||||
extraSmall = RoundedCornerShape(8.dp),
|
||||
small = RoundedCornerShape(12.dp),
|
||||
medium = RoundedCornerShape(18.dp),
|
||||
large = RoundedCornerShape(24.dp),
|
||||
extraLarge = RoundedCornerShape(30.dp),
|
||||
)
|
||||
AppearanceShape.BALANCED -> Shapes(
|
||||
extraSmall = RoundedCornerShape(5.dp),
|
||||
small = RoundedCornerShape(8.dp),
|
||||
medium = RoundedCornerShape(12.dp),
|
||||
large = RoundedCornerShape(16.dp),
|
||||
extraLarge = RoundedCornerShape(20.dp),
|
||||
)
|
||||
AppearanceShape.SHARP -> Shapes(
|
||||
extraSmall = RoundedCornerShape(2.dp),
|
||||
small = RoundedCornerShape(4.dp),
|
||||
medium = RoundedCornerShape(6.dp),
|
||||
large = RoundedCornerShape(8.dp),
|
||||
extraLarge = RoundedCornerShape(10.dp),
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
|
||||
/**
|
||||
* Theme-scoped brand token bundle.
|
||||
@@ -79,6 +80,41 @@ val LocalBrand = staticCompositionLocalOf { BrandPalettes.HermesDark }
|
||||
private fun Color.lighten(f: Float): Color = lerp(this, Color.White, f)
|
||||
private fun Color.darken(f: Float): Color = lerp(this, Color.Black, f)
|
||||
|
||||
/** User-selectable accent seeds. Stored as stable RGB strings in DataStore. */
|
||||
val AccentSwatches = listOf(
|
||||
"#356CFF", "#00B5A0", "#62C51E", "#ED4E8B", "#FF4B00",
|
||||
)
|
||||
|
||||
fun normalizeAccentHex(value: String?): String? {
|
||||
val normalized = value?.trim()?.uppercase()?.let { if (it.startsWith("#")) it else "#$it" }
|
||||
return normalized?.takeIf { it.matches(Regex("#[0-9A-F]{6}")) }
|
||||
}
|
||||
|
||||
fun accentColor(value: String?): Color? = normalizeAccentHex(value)?.let {
|
||||
Color(0xFF000000L or it.drop(1).toLong(16))
|
||||
}
|
||||
|
||||
fun contrastRatio(foreground: Color, background: Color): Float {
|
||||
val light = maxOf(foreground.luminance(), background.luminance())
|
||||
val dark = minOf(foreground.luminance(), background.luminance())
|
||||
return (light + 0.05f) / (dark + 0.05f)
|
||||
}
|
||||
|
||||
fun readableContentColor(background: Color): Color =
|
||||
listOf(Color.Black, Color.White).maxBy { contrastRatio(it, background) }
|
||||
|
||||
/** Apply one accent seed without changing surfaces or semantic status colors. */
|
||||
fun BrandPalette.withAccent(accentHex: String?): BrandPalette {
|
||||
val accent = accentColor(accentHex) ?: return this
|
||||
return copy(
|
||||
relay = if (isDark) accent.lighten(0.34f) else accent.darken(0.08f),
|
||||
electric = accent,
|
||||
electricMuted = if (isDark) accent.lighten(0.18f) else accent.lighten(0.12f),
|
||||
purple = lerp(accent, purple, 0.38f),
|
||||
cyan = lerp(accent, cyan, 0.45f),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a complete Material 3 [ColorScheme] from the palette. Dark and light
|
||||
* palettes use distinct mappings; the "text on a deep accent chip" slots use
|
||||
@@ -87,15 +123,15 @@ private fun Color.darken(f: Float): Color = lerp(this, Color.Black, f)
|
||||
fun BrandPalette.toColorScheme(): ColorScheme = if (isDark) {
|
||||
darkColorScheme(
|
||||
primary = relay,
|
||||
onPrimary = background,
|
||||
onPrimary = readableContentColor(relay),
|
||||
primaryContainer = electric,
|
||||
onPrimaryContainer = paper,
|
||||
onPrimaryContainer = readableContentColor(electric),
|
||||
secondary = purple,
|
||||
onSecondary = paper,
|
||||
onSecondary = readableContentColor(purple),
|
||||
secondaryContainer = navy3,
|
||||
onSecondaryContainer = paper,
|
||||
tertiary = cyan,
|
||||
onTertiary = background,
|
||||
onTertiary = readableContentColor(cyan),
|
||||
tertiaryContainer = purple.copy(alpha = 0.42f),
|
||||
onTertiaryContainer = paper,
|
||||
background = background,
|
||||
@@ -119,15 +155,15 @@ fun BrandPalette.toColorScheme(): ColorScheme = if (isDark) {
|
||||
} else {
|
||||
lightColorScheme(
|
||||
primary = electric,
|
||||
onPrimary = Color.White,
|
||||
onPrimary = readableContentColor(electric),
|
||||
primaryContainer = relay.copy(alpha = 0.22f),
|
||||
onPrimaryContainer = electric.darken(0.32f),
|
||||
secondary = purple,
|
||||
onSecondary = Color.White,
|
||||
onSecondary = readableContentColor(purple),
|
||||
secondaryContainer = purple.copy(alpha = 0.16f),
|
||||
onSecondaryContainer = purple.darken(0.38f),
|
||||
tertiary = cyan,
|
||||
onTertiary = Color.White,
|
||||
onTertiary = readableContentColor(cyan),
|
||||
tertiaryContainer = cyan.copy(alpha = 0.16f),
|
||||
onTertiaryContainer = cyan.darken(0.42f),
|
||||
background = background,
|
||||
|
||||
@@ -24,6 +24,7 @@ import androidx.compose.ui.unit.Density
|
||||
* for [ThemeMode.BOTH] themes; fixed-mode themes ignore it.
|
||||
* @param appFontId id from [AppFont]; selects the body typeface for the whole
|
||||
* app. Defaults to Inter. Code/metadata styles stay monospaced regardless.
|
||||
* @param accentHex optional locally persisted RGB override for brand accents.
|
||||
*/
|
||||
@Composable
|
||||
fun HermesRelayTheme(
|
||||
@@ -31,12 +32,15 @@ fun HermesRelayTheme(
|
||||
themePreference: String = "auto",
|
||||
fontScale: Float = 1.0f,
|
||||
appFontId: String = AppFont.DEFAULT.id,
|
||||
accentHex: String? = null,
|
||||
shapeId: String = AppearanceShape.DEFAULT.id,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val appTheme = AppThemes.byId(appThemeId)
|
||||
val useDarkTheme = appTheme.resolveDark(themePreference, isSystemInDarkTheme())
|
||||
val palette = appTheme.paletteFor(useDarkTheme)
|
||||
val palette = appTheme.paletteFor(useDarkTheme).withAccent(accentHex)
|
||||
val colorScheme = palette.toColorScheme()
|
||||
val shapes = remember(shapeId) { appearanceShapes(shapeId) }
|
||||
|
||||
// Build the Material typography from the selected font. Remembered per id so
|
||||
// a recomposition (e.g. theme/mode change) doesn't rebuild the FontFamily
|
||||
@@ -60,6 +64,7 @@ fun HermesRelayTheme(
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = typography,
|
||||
shapes = shapes,
|
||||
content = content
|
||||
)
|
||||
} else {
|
||||
@@ -72,6 +77,7 @@ fun HermesRelayTheme(
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = typography,
|
||||
shapes = shapes,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.hermesandroid.relay.util
|
||||
|
||||
import android.content.Intent
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
|
||||
data class SharedTextDraftRequest(
|
||||
val id: Long,
|
||||
val text: String,
|
||||
)
|
||||
|
||||
/**
|
||||
* Process-local handoff from Android's sharesheet entry point to the app-owned
|
||||
* chat runtime. A StateFlow keeps a cold-start request alive until RelayApp has
|
||||
* initialized its ViewModels; [consume] is identity-checked so an older UI
|
||||
* completion cannot clear a newer share intent.
|
||||
*/
|
||||
object SharedTextRequest {
|
||||
private val nextId = AtomicLong(0L)
|
||||
private val _pending = MutableStateFlow<SharedTextDraftRequest?>(null)
|
||||
|
||||
val pending: StateFlow<SharedTextDraftRequest?> = _pending.asStateFlow()
|
||||
|
||||
fun tryRequest(text: CharSequence?): Boolean {
|
||||
val value = text?.toString()?.takeIf { it.isNotBlank() } ?: return false
|
||||
_pending.value = SharedTextDraftRequest(
|
||||
id = nextId.incrementAndGet(),
|
||||
text = value,
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
fun consume(id: Long) {
|
||||
_pending.update { request -> request?.takeUnless { it.id == id } }
|
||||
}
|
||||
}
|
||||
|
||||
/** Accept only Android's single-item text share contract. */
|
||||
internal fun extractSharedText(
|
||||
action: String?,
|
||||
mimeType: String?,
|
||||
text: CharSequence?,
|
||||
): String? {
|
||||
if (action != Intent.ACTION_SEND) return null
|
||||
if (mimeType?.startsWith("text/", ignoreCase = true) != true) return null
|
||||
return text?.toString()?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import com.hermesandroid.relay.data.AttachmentState
|
||||
import com.hermesandroid.relay.data.BackgroundTaskPhase
|
||||
import com.hermesandroid.relay.data.BackgroundTaskState
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.ChatComposerDraftStore
|
||||
import com.hermesandroid.relay.data.ChatQueuedMessageCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatSession
|
||||
import com.hermesandroid.relay.data.ChatTurnAskCheckpoint
|
||||
@@ -24,11 +25,13 @@ import com.hermesandroid.relay.data.ChatTurnMoaReferenceCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnToolCheckpoint
|
||||
import com.hermesandroid.relay.data.ChatTurnUserCheckpoint
|
||||
import com.hermesandroid.relay.data.DataStoreChatTurnCheckpointStore
|
||||
import com.hermesandroid.relay.data.InMemoryChatComposerDraftStore
|
||||
import com.hermesandroid.relay.data.DemoContent
|
||||
import com.hermesandroid.relay.data.MediaSettings
|
||||
import com.hermesandroid.relay.data.MediaSettingsRepository
|
||||
import com.hermesandroid.relay.data.MessageDeliveryStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.parseChatQuotedPrompt
|
||||
import com.hermesandroid.relay.data.Profile
|
||||
import com.hermesandroid.relay.data.RealtimeConversationContextMessage
|
||||
import com.hermesandroid.relay.data.RealtimeTurnTrace
|
||||
@@ -78,6 +81,7 @@ import com.hermesandroid.relay.network.upstream.ApiModelRoutingException
|
||||
import com.hermesandroid.relay.network.upstream.ApiModelSelectionAck
|
||||
import com.hermesandroid.relay.network.upstream.HermesApiClient
|
||||
import com.hermesandroid.relay.network.upstream.isCurrentModelOptionsResponse
|
||||
import com.hermesandroid.relay.network.upstream.modelOptionsIdentityToPublish
|
||||
import com.hermesandroid.relay.network.upstream.parsePersonalityPrompts
|
||||
import com.hermesandroid.relay.network.upstream.sessionTurnModelHint
|
||||
import com.hermesandroid.relay.network.relay.ProactiveMessage
|
||||
@@ -88,6 +92,8 @@ import com.hermesandroid.relay.network.upstream.ChatHandler
|
||||
import com.hermesandroid.relay.network.shared.LocalDispatchResult
|
||||
import com.hermesandroid.relay.network.upstream.formatPhoneActionResult
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.SESSION_MESSAGE_PAGE_SIZE
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.models.SkillInfo
|
||||
import com.hermesandroid.relay.network.upstream.models.UsageInfo
|
||||
@@ -109,12 +115,14 @@ import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.channels.BufferOverflow
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.receiveAsFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -157,17 +165,21 @@ data class ContextWindowUsage(
|
||||
/**
|
||||
* A successful Sessions SSE turn still needs the server-authoritative transcript
|
||||
* because that transport does not stream every persisted message boundary.
|
||||
* Gateway turns already deliver the assistant, reasoning, and tool lifecycle
|
||||
* directly; reloading their full transcript only republishes a healthy live turn.
|
||||
* A successful socket rejoin is the exception because events emitted during the
|
||||
* gap cannot be replayed.
|
||||
* Gateway normally delivers the assistant, reasoning, and tool lifecycle
|
||||
* directly, but upstream versions can persist tool calls without emitting the
|
||||
* corresponding live lifecycle events. Inspect structured history after every
|
||||
* successful Gateway turn, then reload only when activity is missing (or socket
|
||||
* recovery requires it), so healthy turns keep their existing UI identity. This
|
||||
* deliberately never infers tool activity from assistant text.
|
||||
*/
|
||||
internal fun shouldReloadHistoryAfterSuccessfulTurn(
|
||||
actualTransport: String,
|
||||
gatewayReconcileRequired: Boolean,
|
||||
missingPersistedToolActivity: Boolean,
|
||||
): Boolean =
|
||||
actualTransport == "sessions" ||
|
||||
(actualTransport == "gateway" && gatewayReconcileRequired)
|
||||
(actualTransport == "gateway" &&
|
||||
(gatewayReconcileRequired || missingPersistedToolActivity))
|
||||
|
||||
internal fun shouldSuppressPassiveSessionError(context: String?, error: Throwable?): Boolean {
|
||||
if (context != "load_sessions" && context != "load_profile_sessions") return false
|
||||
@@ -509,7 +521,7 @@ class ChatViewModel : ViewModel() {
|
||||
val recentPrompts: StateFlow<List<String>> = _recentPrompts.asStateFlow()
|
||||
|
||||
private fun recordRecentPrompt(text: String) {
|
||||
val t = text.trim()
|
||||
val t = (parseChatQuotedPrompt(text)?.body ?: text).trim()
|
||||
if (t.isBlank() || t.startsWith("/")) return // skip blanks + slash commands
|
||||
_recentPrompts.update { prev ->
|
||||
(listOf(t) + prev.filterNot { it == t }).take(RECENT_PROMPTS_LIMIT)
|
||||
@@ -539,6 +551,9 @@ class ChatViewModel : ViewModel() {
|
||||
private val _pendingAttachments = MutableStateFlow<List<Attachment>>(emptyList())
|
||||
val pendingAttachments: StateFlow<List<Attachment>> = _pendingAttachments.asStateFlow()
|
||||
|
||||
/** Session-keyed composer state; intentionally memory-only for attachment privacy. */
|
||||
val composerDraftStore: ChatComposerDraftStore = InMemoryChatComposerDraftStore()
|
||||
|
||||
fun addAttachment(attachment: Attachment) {
|
||||
_pendingAttachments.update { it + attachment }
|
||||
}
|
||||
@@ -549,6 +564,22 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
fun replacePendingAttachments(attachments: List<Attachment>) {
|
||||
_pendingAttachments.value = attachments.toList()
|
||||
}
|
||||
|
||||
fun moveAttachment(fromIndex: Int, toIndex: Int) {
|
||||
_pendingAttachments.update { attachments ->
|
||||
if (fromIndex !in attachments.indices || toIndex !in attachments.indices) {
|
||||
attachments
|
||||
} else {
|
||||
attachments.toMutableList().apply {
|
||||
add(toIndex, removeAt(fromIndex))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearAttachments() {
|
||||
_pendingAttachments.value = emptyList()
|
||||
}
|
||||
@@ -703,9 +734,13 @@ class ChatViewModel : ViewModel() {
|
||||
* Refresh the gateway's curated provider/model list (`model.options`).
|
||||
* Connects the gateway on demand. No-op without a gateway client.
|
||||
* [refresh] is the explicit upstream refresh path for dynamic/custom-provider catalogs;
|
||||
* automatic picker opens stay on the cheap cached path.
|
||||
* automatic picker opens stay on the cheap cached path. [catalogOnly] updates
|
||||
* choices and capability metadata without publishing a model identity.
|
||||
*/
|
||||
fun refreshModelOptions(refresh: Boolean = false) {
|
||||
fun refreshModelOptions(
|
||||
refresh: Boolean = false,
|
||||
catalogOnly: Boolean = false,
|
||||
) {
|
||||
val gateway = gatewayClient ?: run {
|
||||
android.util.Log.i("ChatViewModel", "refreshModelOptions: no gateway client")
|
||||
if (refresh) _modelOptionsRefreshing.value = false
|
||||
@@ -729,8 +764,19 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
modelOptionsByProfile[profileKey] = it
|
||||
_modelProviders.value = it.providers
|
||||
_gatewayCurrentModel.value = it.currentModel
|
||||
_gatewayCurrentProvider.value = it.currentProvider
|
||||
// Opening a picker refreshes catalog metadata, not session
|
||||
// identity. session.info/session.resume is canonical once a
|
||||
// live session exists; do not let a profile/global catalog
|
||||
// response repaint its controls.
|
||||
modelOptionsIdentityToPublish(
|
||||
catalogOnly = catalogOnly,
|
||||
hasLiveSession = hasLiveGatewaySession(),
|
||||
sessionIdentity = gateway.serverModelIdentity.value,
|
||||
options = it,
|
||||
)?.let { identity ->
|
||||
_gatewayCurrentModel.value = identity.model
|
||||
_gatewayCurrentProvider.value = identity.provider
|
||||
}
|
||||
refreshRelayReasoningCapabilities(refresh = refresh)
|
||||
android.util.Log.i(
|
||||
"ChatViewModel",
|
||||
@@ -977,7 +1023,10 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
}
|
||||
|
||||
fun fetchModels(userInitiated: Boolean = false) {
|
||||
fun fetchModels(
|
||||
userInitiated: Boolean = false,
|
||||
catalogOnly: Boolean = false,
|
||||
) {
|
||||
val client = apiClient ?: return
|
||||
val generation = modelOptionsGeneration.incrementAndGet()
|
||||
val profileKey = modelOptionsProfileKey()
|
||||
@@ -1002,8 +1051,15 @@ class ChatViewModel : ViewModel() {
|
||||
)
|
||||
modelOptionsByProfile[profileKey] = options
|
||||
_modelProviders.value = options.providers
|
||||
_gatewayCurrentModel.value = options.currentModel
|
||||
_gatewayCurrentProvider.value = options.currentProvider
|
||||
modelOptionsIdentityToPublish(
|
||||
catalogOnly = catalogOnly,
|
||||
hasLiveSession = hasLiveGatewaySession(),
|
||||
sessionIdentity = gatewayClient?.serverModelIdentity?.value,
|
||||
options = options,
|
||||
)?.let { identity ->
|
||||
_gatewayCurrentModel.value = identity.model
|
||||
_gatewayCurrentProvider.value = identity.provider
|
||||
}
|
||||
// Keep OpenAI route aliases visible alongside authenticated
|
||||
// provider inventory. An alias remains the request id while
|
||||
// its root is used only to validate the provider route.
|
||||
@@ -2260,12 +2316,37 @@ class ChatViewModel : ViewModel() {
|
||||
* (`{type:"prefill"}` — e.g. `/undo`). ChatScreen collects and sets the
|
||||
* input text.
|
||||
*/
|
||||
private val _composerPrefill = MutableSharedFlow<String>(
|
||||
replay = 0,
|
||||
extraBufferCapacity = 1,
|
||||
onBufferOverflow = BufferOverflow.DROP_OLDEST,
|
||||
)
|
||||
val composerPrefill: SharedFlow<String> = _composerPrefill.asSharedFlow()
|
||||
private val _composerPrefill = Channel<String>(capacity = Channel.CONFLATED)
|
||||
val composerPrefill = _composerPrefill.receiveAsFlow()
|
||||
|
||||
/**
|
||||
* Open a fresh draft for text received through Android's sharesheet.
|
||||
* The composer event is queued until Chat is composed and is never routed
|
||||
* through [sendMessage]. Existing new-chat transport and background-turn
|
||||
* ownership remain authoritative.
|
||||
*/
|
||||
fun openSharedTextDraft(text: String): Boolean {
|
||||
if (text.isBlank() || chatHandler == null) return false
|
||||
val canCreateDraft =
|
||||
(streamingEndpoint == "gateway" && gatewayClient != null) || apiClient != null
|
||||
if (!canCreateDraft) return false
|
||||
createNewChat()
|
||||
return _composerPrefill.trySend(text).isSuccess
|
||||
}
|
||||
|
||||
// Navigation-safe draft handoff for explicit in-app workflows (for example,
|
||||
// custom-pet creation). StateFlow keeps the reviewed text until ChatScreen
|
||||
// is mounted; consuming it never sends the message.
|
||||
private val _pendingComposerDraft = MutableStateFlow<String?>(null)
|
||||
val pendingComposerDraft: StateFlow<String?> = _pendingComposerDraft.asStateFlow()
|
||||
|
||||
fun stageComposerDraft(text: String) {
|
||||
_pendingComposerDraft.value = text.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
fun consumeComposerDraft(text: String) {
|
||||
_pendingComposerDraft.compareAndSet(text, null)
|
||||
}
|
||||
|
||||
/**
|
||||
* One-shot request to open the personality picker — emitted when a bare
|
||||
@@ -2457,9 +2538,16 @@ class ChatViewModel : ViewModel() {
|
||||
* once the drawer lists a non-default profile's sessions, opening one must
|
||||
* read that profile's own DB. Returns `null` off the dashboard surface.
|
||||
*/
|
||||
private var profileMessageLoader: (suspend (String) -> Result<List<MessageItem>>?)? = null
|
||||
private var profileMessageLoader:
|
||||
(suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?)? = null
|
||||
|
||||
fun setProfileMessageLoader(loader: suspend (String) -> Result<List<MessageItem>>?) {
|
||||
profileMessageLoader = { sessionId, _ -> loader(sessionId) }
|
||||
}
|
||||
|
||||
fun setProfileMessageLoaderWithMode(
|
||||
loader: suspend (String, SessionMessageLoadMode) -> Result<List<MessageItem>>?,
|
||||
) {
|
||||
profileMessageLoader = loader
|
||||
}
|
||||
|
||||
@@ -2472,11 +2560,12 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadSessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> {
|
||||
if (streamingEndpoint == "gateway") {
|
||||
return loadGatewaySessionHistory(sessionId, requireProfileScope)
|
||||
return loadGatewaySessionHistory(sessionId, requireProfileScope, mode)
|
||||
}
|
||||
return apiClient?.getMessages(sessionId) ?: emptyList()
|
||||
return apiClient?.getMessages(sessionId, mode) ?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2488,15 +2577,16 @@ class ChatViewModel : ViewModel() {
|
||||
private suspend fun loadGatewaySessionHistory(
|
||||
sessionId: String,
|
||||
requireProfileScope: Boolean = false,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): List<MessageItem> {
|
||||
val scoped = profileMessageLoader?.invoke(sessionId)
|
||||
val scoped = profileMessageLoader?.invoke(sessionId, mode)
|
||||
if (scoped != null) {
|
||||
// A gateway profile owns a distinct state.db. Never fall through to
|
||||
// the launch/default API database when its scoped read fails: an
|
||||
// empty/default transcript is not authoritative for this session.
|
||||
return if (requireProfileScope) scoped.getOrThrow() else scoped.getOrElse { emptyList() }
|
||||
}
|
||||
return apiClient?.getMessages(sessionId) ?: emptyList()
|
||||
return apiClient?.getMessages(sessionId, mode) ?: emptyList()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -3164,6 +3254,16 @@ class ChatViewModel : ViewModel() {
|
||||
selectedReasoningEffortConfirmedIdentity = null
|
||||
_reasoningDisplay.value = null
|
||||
_selectedPersonality.value = "default"
|
||||
// Model/provider overrides are session-scoped too. This reset is owned
|
||||
// by the context switch (not just activateGatewayProfile) so the SSE
|
||||
// path cannot carry the previous profile's explicit model into the
|
||||
// restored session or fresh draft.
|
||||
modelOptionsGeneration.incrementAndGet()
|
||||
_modelProviders.value = emptyList()
|
||||
_apiModelOptions.value = emptyList()
|
||||
_availableModels.value = emptyList()
|
||||
_selectedModelOverride.value = null
|
||||
_selectedProviderOverride.value = null
|
||||
// The agent display name was stamped above with the pre-reset persona —
|
||||
// recompute it now that the overlay is cleared so the header/bubbles read
|
||||
// the new profile's base identity, not the old persona.
|
||||
@@ -3291,8 +3391,11 @@ class ChatViewModel : ViewModel() {
|
||||
* groups refresh via [refreshModelOptions]; this covers [availableModels] used
|
||||
* when no gateway model.options groups exist. Fetched once otherwise.
|
||||
*/
|
||||
fun refreshModels(userInitiated: Boolean = false) {
|
||||
fetchModels(userInitiated)
|
||||
fun refreshModels(
|
||||
userInitiated: Boolean = false,
|
||||
catalogOnly: Boolean = false,
|
||||
) {
|
||||
fetchModels(userInitiated, catalogOnly)
|
||||
}
|
||||
|
||||
/** Clear server-owned catalogs before a different connection starts loading. */
|
||||
@@ -3834,7 +3937,11 @@ class ChatViewModel : ViewModel() {
|
||||
|
||||
// Mid-turn: redirect on the gateway transport, queue everywhere else.
|
||||
if (activeStream != null) {
|
||||
if (_steerableTurn.value && streamingEndpoint == "gateway") {
|
||||
if (
|
||||
_steerableTurn.value &&
|
||||
streamingEndpoint == "gateway" &&
|
||||
_pendingAttachments.value.isEmpty()
|
||||
) {
|
||||
steerActiveTurn(text.trim())
|
||||
} else {
|
||||
enqueueMessage(text.trim())
|
||||
@@ -3867,6 +3974,7 @@ class ChatViewModel : ViewModel() {
|
||||
role = MessageRole.USER,
|
||||
content = text,
|
||||
timestamp = System.currentTimeMillis(),
|
||||
deliveryStatus = MessageDeliveryStatus.STEERED,
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -4586,7 +4694,7 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
"prefill" -> {
|
||||
result.stringValue("notice")?.let { handler.addSystemNotice(it) }
|
||||
result.stringValue("message")?.let { _composerPrefill.tryEmit(it) }
|
||||
result.stringValue("message")?.let { _composerPrefill.trySend(it) }
|
||||
}
|
||||
else ->
|
||||
handler.addSystemNotice(result.stringValue("output") ?: "Command completed.")
|
||||
@@ -5401,9 +5509,24 @@ class ChatViewModel : ViewModel() {
|
||||
detail = cause,
|
||||
)
|
||||
|
||||
// A short transcript fits in Hermes' explicit latest window and can be
|
||||
// polled with one bounded request. Long transcripts retain complete
|
||||
// oldest-first pagination so the positional user anchor and visible
|
||||
// history cannot silently shift when the oldest rows fall outside 500.
|
||||
val recoveryLoadMode = if (handler.messages.value.size < SESSION_MESSAGE_PAGE_SIZE) {
|
||||
SessionMessageLoadMode.LATEST
|
||||
} else {
|
||||
SessionMessageLoadMode.COMPLETE
|
||||
}
|
||||
val recovery = ChatStreamRecovery(
|
||||
scope = viewModelScope,
|
||||
fetchHistory = { loadSessionHistory(checkpoint.sessionId, requireProfileScope = true) },
|
||||
fetchHistory = {
|
||||
loadSessionHistory(
|
||||
checkpoint.sessionId,
|
||||
requireProfileScope = true,
|
||||
mode = recoveryLoadMode,
|
||||
)
|
||||
},
|
||||
timing = recoveryTimingOverride ?: ChatStreamRecovery.Timing(),
|
||||
)
|
||||
streamRecovery = recovery
|
||||
@@ -5579,9 +5702,20 @@ class ChatViewModel : ViewModel() {
|
||||
val priorUserCount = (
|
||||
handler.messages.value.count { it.role == MessageRole.USER } - 1
|
||||
).coerceAtLeast(0)
|
||||
val recoveryLoadMode = if (handler.messages.value.size < SESSION_MESSAGE_PAGE_SIZE) {
|
||||
SessionMessageLoadMode.LATEST
|
||||
} else {
|
||||
SessionMessageLoadMode.COMPLETE
|
||||
}
|
||||
val recovery = ChatStreamRecovery(
|
||||
scope = viewModelScope,
|
||||
fetchHistory = { loadSessionHistory(sessionId, requireProfileScope = true) },
|
||||
fetchHistory = {
|
||||
loadSessionHistory(
|
||||
sessionId,
|
||||
requireProfileScope = true,
|
||||
mode = recoveryLoadMode,
|
||||
)
|
||||
},
|
||||
timing = recoveryTimingOverride ?: ChatStreamRecovery.Timing(),
|
||||
)
|
||||
streamRecovery = recovery
|
||||
@@ -7071,13 +7205,11 @@ class ChatViewModel : ViewModel() {
|
||||
refreshApprovalMode()
|
||||
}
|
||||
|
||||
// Sessions SSE does not stream every persisted message boundary, so it
|
||||
// still needs the server-authoritative transcript after success. A healthy
|
||||
// Gateway turn is already authoritative in memory through its structured
|
||||
// assistant/reasoning/tool events; reloading the full transcript here would
|
||||
// republish the entire visible list and cause a completion flash. A Gateway
|
||||
// socket rejoin explicitly flags this completion for the same profile-aware
|
||||
// history reconcile because events emitted during the gap may be missing.
|
||||
// Stateful transports reconcile from server-authoritative history after
|
||||
// success. Gateway usually streams every structured lifecycle event, but
|
||||
// some upstream versions persist tool_calls without emitting tool.start /
|
||||
// tool.complete. The structured reload recovers those calls without ever
|
||||
// parsing assistant prose and retains the profile-aware history boundary.
|
||||
val sid = handler.currentSessionId.value
|
||||
// A turn that ended in an error (gateway ❌ lifecycle → "Error" badge)
|
||||
// has NO assistant message persisted server-side, so reconciling the
|
||||
@@ -7087,18 +7219,24 @@ class ChatViewModel : ViewModel() {
|
||||
// local error visible — but still refresh the drawer + drain the queue.
|
||||
if (sid != null && (completedTransport == "sessions" || completedTransport == "gateway")) {
|
||||
viewModelScope.launch {
|
||||
if (!turnErrored && shouldReloadHistoryAfterSuccessfulTurn(
|
||||
completedTransport,
|
||||
gatewayHistoryReconcileRequired,
|
||||
)
|
||||
) {
|
||||
if (!turnErrored) {
|
||||
// Profile-aware read: a gateway turn on a non-default profile
|
||||
// persists into THAT profile's own state.db, so the bare
|
||||
// api_server `/api/sessions/{id}/messages` 404s → emptyList()
|
||||
// → a silent wipe of the just-finished turn. loadSessionHistory
|
||||
// prefers the `?profile=` dashboard loader on gateway connections.
|
||||
val serverMessages = loadSessionHistory(sid)
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
val missingPersistedToolActivity =
|
||||
completedTransport == "gateway" &&
|
||||
handler.hasMissingPersistedToolActivity(serverMessages)
|
||||
if (shouldReloadHistoryAfterSuccessfulTurn(
|
||||
actualTransport = completedTransport,
|
||||
gatewayReconcileRequired = gatewayHistoryReconcileRequired,
|
||||
missingPersistedToolActivity = missingPersistedToolActivity,
|
||||
)
|
||||
) {
|
||||
handler.loadMessageHistory(serverMessages)
|
||||
}
|
||||
}
|
||||
// Re-sync the drawer now that the turn is persisted server-side.
|
||||
// The only other auto-refresh fires ~160ms after session creation
|
||||
@@ -8398,7 +8536,9 @@ class ChatViewModel : ViewModel() {
|
||||
}
|
||||
|
||||
private fun queuedPromptPreview(prompt: String, maxChars: Int = 96): String {
|
||||
val compact = prompt.replace(Regex("\\s+"), " ").trim()
|
||||
val compact = (parseChatQuotedPrompt(prompt)?.body ?: prompt)
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
return if (compact.length <= maxChars) compact else compact.take(maxChars - 1).trimEnd() + "…"
|
||||
}
|
||||
|
||||
|
||||
@@ -14,10 +14,14 @@ import com.hermesandroid.relay.auth.AuthManager
|
||||
import com.hermesandroid.relay.auth.AuthState
|
||||
import com.hermesandroid.relay.ui.theme.AppFont
|
||||
import com.hermesandroid.relay.ui.theme.AppThemes
|
||||
import com.hermesandroid.relay.ui.theme.normalizeAccentHex
|
||||
import com.hermesandroid.relay.ui.theme.AppearanceShape
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetImporter
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetImportResult
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetLoader
|
||||
import com.hermesandroid.relay.ui.components.avatar.SphereAvatar
|
||||
import com.hermesandroid.relay.ui.components.SphereSkinImportResult
|
||||
import com.hermesandroid.relay.ui.components.SphereSkinImporter
|
||||
import com.hermesandroid.relay.ui.components.pet.PetLogicalEdge
|
||||
import com.hermesandroid.relay.ui.components.pet.PetPlacement
|
||||
import com.hermesandroid.relay.auth.PairedDeviceInfo
|
||||
@@ -37,6 +41,8 @@ import com.hermesandroid.relay.data.DEFAULT_PET_SIZE_SCALE
|
||||
import com.hermesandroid.relay.data.PetBehaviorPreferences
|
||||
import com.hermesandroid.relay.data.PetBehaviorPreferencesRepository
|
||||
import com.hermesandroid.relay.data.PetTemperament
|
||||
import com.hermesandroid.relay.data.ChatInputPreferencesRepository
|
||||
import com.hermesandroid.relay.data.PhysicalKeyboardEnterBehavior
|
||||
import com.hermesandroid.relay.data.RelayEndpoint
|
||||
import com.hermesandroid.relay.data.primaryRouteUrl
|
||||
import com.hermesandroid.relay.data.routeAuthority
|
||||
@@ -70,6 +76,7 @@ import com.hermesandroid.relay.network.relay.ConnectionState
|
||||
import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardChatDisplaySettings
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.upstream.mirrorDashboardSessionCookies
|
||||
import com.hermesandroid.relay.network.upstream.DashboardAuthSession
|
||||
@@ -343,6 +350,11 @@ internal fun profileApiCredential(
|
||||
connectionKey: String,
|
||||
): String = if (usesMultiplexProfileKey) profileKey.orEmpty() else connectionKey
|
||||
|
||||
internal fun migratedBackgroundAvatar(
|
||||
storedBackgroundAvatar: String?,
|
||||
legacyAgentAvatar: String?,
|
||||
): String = storedBackgroundAvatar ?: legacyAgentAvatar ?: SphereAvatar.id
|
||||
|
||||
class ConnectionViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private val ctx: Context get() = getApplication()
|
||||
@@ -396,6 +408,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// Selected app theme id (palette/personality). Orthogonal to KEY_THEME,
|
||||
// which is the light/dark/auto mode axis honored by BOTH-mode themes.
|
||||
private val KEY_APP_THEME = stringPreferencesKey("app_theme")
|
||||
// Optional RGB accent override applied on top of the selected preset.
|
||||
// Null means the preset's authored accent remains authoritative.
|
||||
private val KEY_APPEARANCE_ACCENT = stringPreferencesKey("appearance_accent")
|
||||
private val KEY_APPEARANCE_SHAPE = stringPreferencesKey("appearance_shape")
|
||||
// Selected app font id (body typeface). Resolved against AppFont at the
|
||||
// Compose theme root; defaults to Inter. Orthogonal to KEY_FONT_SCALE
|
||||
// (which scales sizes); this picks the family.
|
||||
@@ -403,12 +419,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
// Selected sphere skin id. "auto" (SphereRegistry.AUTO_ID) follows the
|
||||
// active theme's preferred skin; any other id pins a specific skin.
|
||||
private val KEY_SPHERE_SKIN = stringPreferencesKey("sphere_skin")
|
||||
// Legacy combined sphere/pet choice. Read for one release so existing
|
||||
// users keep their selected pet when the concepts split.
|
||||
// Legacy combined sphere/pet choice. Read during migration so existing
|
||||
// users retain both their prior central visual and companion choice.
|
||||
private val KEY_AGENT_AVATAR = stringPreferencesKey("agent_avatar")
|
||||
// Optional floating companion id. The explicit sentinel distinguishes
|
||||
// "no pet" from a preference that has not yet been migrated.
|
||||
private val KEY_FLOATING_PET = stringPreferencesKey("floating_pet")
|
||||
// Central visualization selection, independent from the floating pet.
|
||||
private val KEY_BACKGROUND_AVATAR = stringPreferencesKey("background_avatar")
|
||||
// Reserved storage sentinel. Pet ids may legitimately be ordinary words
|
||||
// such as "none", so keep the no-selection marker outside that space.
|
||||
private const val NO_FLOATING_PET = "__none__"
|
||||
@@ -466,6 +484,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
private val petBehaviorPreferencesRepository =
|
||||
PetBehaviorPreferencesRepository(application)
|
||||
private val chatInputPreferencesRepository =
|
||||
ChatInputPreferencesRepository(application)
|
||||
|
||||
// --- Core networking components ---
|
||||
|
||||
@@ -1302,6 +1322,14 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, AppThemes.DEFAULT_ID)
|
||||
|
||||
val appearanceAccent: StateFlow<String?> = application.relayDataStore.data
|
||||
.map { preferences -> normalizeAccentHex(preferences[KEY_APPEARANCE_ACCENT]) }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
||||
|
||||
val appearanceShape: StateFlow<String> = application.relayDataStore.data
|
||||
.map { preferences -> AppearanceShape.fromId(preferences[KEY_APPEARANCE_SHAPE]).id }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, AppearanceShape.DEFAULT.id)
|
||||
|
||||
// Selected app font id (body typeface). Defaults to Inter. Resolved against
|
||||
// AppFont.byId at the Compose theme root, which rebuilds Typography so the
|
||||
// whole app re-themes live when this changes.
|
||||
@@ -1319,8 +1347,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, "auto")
|
||||
|
||||
// Optional floating companion. For one release, an absent new key reads the
|
||||
// legacy combined selection: sphere -> no companion; a pet id -> companion.
|
||||
// Optional floating companion. An absent split key reads the legacy combined
|
||||
// selection: sphere -> no companion; a pet id -> companion.
|
||||
val floatingPet: StateFlow<String?> = application.relayDataStore.data
|
||||
.map { preferences ->
|
||||
val selected = preferences[KEY_FLOATING_PET]
|
||||
@@ -1330,6 +1358,16 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
|
||||
|
||||
/** Sphere or a validated pet-format asset rendered on central/ambient surfaces. */
|
||||
val backgroundAvatar: StateFlow<String> = application.relayDataStore.data
|
||||
.map { preferences ->
|
||||
migratedBackgroundAvatar(
|
||||
storedBackgroundAvatar = preferences[KEY_BACKGROUND_AVATAR],
|
||||
legacyAgentAvatar = preferences[KEY_AGENT_AVATAR],
|
||||
)
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, SphereAvatar.id)
|
||||
|
||||
/** Whether the selected companion may autonomously move between safe perches. */
|
||||
val petRoamingEnabled: StateFlow<Boolean> = application.relayDataStore.data
|
||||
.map { preferences -> preferences[KEY_PET_ROAMING_ENABLED] ?: false }
|
||||
@@ -1455,8 +1493,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
suspend fun listProfileScopedSessions(limit: Int = 200): Result<List<SessionItem>>? =
|
||||
profileController.listProfileScopedSessions(limit)
|
||||
|
||||
suspend fun loadProfileScopedMessages(sessionId: String): Result<List<MessageItem>>? =
|
||||
profileController.loadProfileScopedMessages(sessionId)
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): Result<List<MessageItem>>? = profileController.loadProfileScopedMessages(sessionId, mode)
|
||||
|
||||
/**
|
||||
* Delete a session scoped to the ACTIVE PROFILE via the dashboard
|
||||
@@ -1523,6 +1563,9 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
/** The active profile's local agent-icon path (client-side, never sent to Hermes). */
|
||||
val profileIcon: StateFlow<String?> get() = profileController.profileIcon
|
||||
|
||||
/** A local icon path for a specific profile identity on the active connection. */
|
||||
fun profileIconFlow(profileName: String?) = profileController.profileIconFlow(profileName)
|
||||
|
||||
val hostProfileIconImportState: StateFlow<ProfileController.HostIconImportState>
|
||||
get() = profileController.hostIconImportState
|
||||
|
||||
@@ -1548,7 +1591,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
|
||||
/** Lock the active connection to [profile] (null = Server default). */
|
||||
fun lockProfile(profile: Profile?) {
|
||||
viewModelScope.launch { profileController.lockProfile(profile) }
|
||||
profileController.lockProfile(profile)
|
||||
}
|
||||
|
||||
/** Remove the active connection's profile lock. */
|
||||
@@ -1811,8 +1854,8 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
|
||||
init {
|
||||
// Materialize the split preference once. Keeping the legacy read above
|
||||
// for one release also covers interrupted upgrades and older backups.
|
||||
// Materialize the independent central and floating preferences. Legacy
|
||||
// users retain the prior visual in both roles until they choose otherwise.
|
||||
viewModelScope.launch {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
if (preferences[KEY_FLOATING_PET] == null) {
|
||||
@@ -1820,6 +1863,12 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
?.takeUnless { it == SphereAvatar.id }
|
||||
?: NO_FLOATING_PET
|
||||
}
|
||||
if (preferences[KEY_BACKGROUND_AVATAR] == null) {
|
||||
preferences[KEY_BACKGROUND_AVATAR] = migratedBackgroundAvatar(
|
||||
storedBackgroundAvatar = null,
|
||||
legacyAgentAvatar = preferences[KEY_AGENT_AVATAR],
|
||||
)
|
||||
}
|
||||
// Before presence and motion were split, animation_enabled also
|
||||
// controlled whether the Sphere was shown. Preserve that choice
|
||||
// on upgrade; users can then re-enable a static Sphere separately.
|
||||
@@ -1950,6 +1999,15 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
fun setBackgroundAvatar(avatarId: String) {
|
||||
viewModelScope.launch {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
preferences[KEY_BACKGROUND_AVATAR] = avatarId.ifBlank { SphereAvatar.id }
|
||||
preferences[KEY_BACKGROUND_VISUALIZATION_ENABLED] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setImageGenerationStyle(value: String) {
|
||||
val normalized = value.takeIf {
|
||||
it in setOf("rotate", "grid", "sphere", "nodes")
|
||||
@@ -2053,6 +2111,20 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
val physicalKeyboardEnterBehavior: StateFlow<PhysicalKeyboardEnterBehavior> =
|
||||
chatInputPreferencesRepository.physicalKeyboardEnterBehavior
|
||||
.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.Eagerly,
|
||||
PhysicalKeyboardEnterBehavior.SendMessage,
|
||||
)
|
||||
|
||||
fun setPhysicalKeyboardEnterBehavior(behavior: PhysicalKeyboardEnterBehavior) {
|
||||
viewModelScope.launch {
|
||||
chatInputPreferencesRepository.setPhysicalKeyboardEnterBehavior(behavior)
|
||||
}
|
||||
}
|
||||
|
||||
// Turn-complete notification (default ON). RelayApp mirrors this into
|
||||
// ChatViewModel.notifyOnTurnComplete; ChatSettingsScreen owns the toggle
|
||||
// + the POST_NOTIFICATIONS runtime request on first enable.
|
||||
@@ -6435,7 +6507,10 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
fun saveLastSessionId(sessionId: String?) {
|
||||
_lastSessionId.value = sessionId
|
||||
val connectionId = activeConnectionId.value
|
||||
val profileName = profileController.resolveSessionProfileName()
|
||||
// Last-session persistence follows the selected UI profile identity.
|
||||
// The null Server-default sentinel stays separate from whichever named
|
||||
// profile the server's sticky default currently resolves to.
|
||||
val profileName = profileController.selectedProfile.value?.name
|
||||
viewModelScope.launch {
|
||||
if (connectionId != null) {
|
||||
if (sessionId != null) {
|
||||
@@ -6467,7 +6542,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
}
|
||||
if (profileName == null || AgentDisplay.isServerDefaultAlias(profileName)) {
|
||||
if (profileName == null) {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
if (sessionId != null) {
|
||||
preferences[KEY_LAST_SESSION_ID] = sessionId
|
||||
@@ -6594,6 +6669,59 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply or reset the local accent override. Invalid values safely reset. */
|
||||
fun setAppearanceAccent(accentHex: String?) {
|
||||
viewModelScope.launch {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
val normalized = normalizeAccentHex(accentHex)
|
||||
if (normalized == null) preferences.remove(KEY_APPEARANCE_ACCENT)
|
||||
else preferences[KEY_APPEARANCE_ACCENT] = normalized
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setAppearanceShape(shapeId: String) {
|
||||
viewModelScope.launch {
|
||||
getApplication<Application>().relayDataStore.edit { preferences ->
|
||||
preferences[KEY_APPEARANCE_SHAPE] = AppearanceShape.fromId(shapeId).id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Import one declarative sphere-skin JSON file, select it, then hot-refresh Appearance. */
|
||||
fun importSphereSkin(uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
SphereSkinImporter.importUri(getApplication<Application>(), uri)
|
||||
}
|
||||
when (result) {
|
||||
is SphereSkinImportResult.Success -> {
|
||||
setSphereSkin(result.id)
|
||||
refreshAgentAvatars()
|
||||
_avatarEvents.tryEmit("Imported “${result.label}”")
|
||||
}
|
||||
is SphereSkinImportResult.Failure -> _avatarEvents.tryEmit(result.reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Import a validated pet-format asset for the central/background renderer. */
|
||||
fun importBackgroundAnimation(uri: Uri) {
|
||||
viewModelScope.launch {
|
||||
val result = withContext(Dispatchers.IO) {
|
||||
PetImporter.importUri(getApplication<Application>(), uri)
|
||||
}
|
||||
when (result) {
|
||||
is PetImportResult.Success -> {
|
||||
setBackgroundAvatar(result.id)
|
||||
refreshAgentAvatars()
|
||||
_avatarEvents.tryEmit("Imported background “${result.label}”")
|
||||
}
|
||||
is PetImportResult.Failure -> _avatarEvents.tryEmit(result.reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete a user pet by id; clear it if it was the selected companion. */
|
||||
fun deleteUserAvatar(avatarId: String, label: String) {
|
||||
viewModelScope.launch {
|
||||
@@ -6602,6 +6730,7 @@ class ConnectionViewModel(application: Application) : AndroidViewModel(applicati
|
||||
}
|
||||
if (deleted) {
|
||||
if (floatingPet.value == avatarId) setFloatingPet(null)
|
||||
if (backgroundAvatar.value == avatarId) setBackgroundAvatar(SphereAvatar.id)
|
||||
refreshAgentAvatars()
|
||||
_avatarEvents.tryEmit("Removed “$label”")
|
||||
} else {
|
||||
|
||||
@@ -93,6 +93,16 @@ import com.hermesandroid.relay.data.VoiceAudioRoute
|
||||
*/
|
||||
enum class VoiceState { Idle, Listening, Transcribing, Thinking, Speaking, Error }
|
||||
|
||||
internal fun canSpeakSettledResponse(
|
||||
state: VoiceUiState,
|
||||
providerRealtimeAgentTurnActive: Boolean,
|
||||
): Boolean = state.state == VoiceState.Idle && !providerRealtimeAgentTurnActive
|
||||
|
||||
internal fun ownsVoiceAudioCompletion(
|
||||
voiceMode: Boolean,
|
||||
responseSpeechActive: Boolean,
|
||||
): Boolean = voiceMode || responseSpeechActive
|
||||
|
||||
private enum class StandardSpeechStreamState {
|
||||
Idle,
|
||||
Opening,
|
||||
@@ -731,6 +741,10 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
private val _uiState = MutableStateFlow(VoiceUiState())
|
||||
val uiState: StateFlow<VoiceUiState> = _uiState.asStateFlow()
|
||||
|
||||
/** True only for one-shot narration started from a settled chat message. */
|
||||
private val _responseSpeechActive = MutableStateFlow(false)
|
||||
val responseSpeechActive: StateFlow<Boolean> = _responseSpeechActive.asStateFlow()
|
||||
|
||||
private val _voicePreviewState = MutableStateFlow(VoicePreviewUiState())
|
||||
val voicePreviewState: StateFlow<VoicePreviewUiState> = _voicePreviewState.asStateFlow()
|
||||
private var voicePreviewJob: Job? = null
|
||||
@@ -2233,7 +2247,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
* per-turn state, and go back to Idle ("stop" means ready to start a
|
||||
* new turn on the next mic tap).
|
||||
*/
|
||||
fun interruptSpeaking(): Job? {
|
||||
fun interruptSpeaking(cancelActiveTurn: Boolean = true): Job? {
|
||||
cancelPendingListeningStart()
|
||||
Log.i(
|
||||
TAG,
|
||||
@@ -2242,13 +2256,14 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
// Stop = "stop talking", not "kill my task": with a background run
|
||||
// active, silence the audio pipeline below but leave the run alive —
|
||||
// the chip's ✕ is the explicit cancel affordance.
|
||||
val realtimeTurnWasActive =
|
||||
_responseSpeechActive.value = false
|
||||
val realtimeTurnWasActive = cancelActiveTurn &&
|
||||
voiceEngineMode == VoiceEngineMode.RealtimeAgent && providerRealtimeAgentTurnActive.get()
|
||||
val backgroundPhase = _uiState.value.backgroundRun?.phase
|
||||
val backgroundRunActive = preserveRealtimeTurnOnStop(backgroundPhase)
|
||||
val backgroundRunActive = cancelActiveTurn && preserveRealtimeTurnOnStop(backgroundPhase)
|
||||
if (backgroundRunActive) {
|
||||
Log.i(TAG, "Interrupt with background run active — stopping audio only")
|
||||
} else {
|
||||
} else if (cancelActiveTurn) {
|
||||
cancelRealtimeAgentTurn("interrupt")
|
||||
}
|
||||
if (realtimeTurnWasActive && rtAssistantMessageId.isNotBlank() && !backgroundRunActive) {
|
||||
@@ -2278,13 +2293,17 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
drainRealtimeTtsQueue()
|
||||
try { player?.stop() } catch (_: Exception) { /* ignore */ }
|
||||
try { realtimePcmPlayer?.stop() } catch (_: Exception) { /* ignore */ }
|
||||
// Stop the upstream SSE stream so the agent quits generating tokens.
|
||||
try { chatViewModel?.cancelStream() } catch (_: Exception) { /* ignore */ }
|
||||
streamObserverJob?.cancel()
|
||||
streamObserverJob = null
|
||||
currentTurnJob?.cancel()
|
||||
currentTurnJob = null
|
||||
continuousLoopArmed = false
|
||||
if (cancelActiveTurn) {
|
||||
// Voice-mode Stop owns the turn and cancels generation. A context-
|
||||
// menu narration owns audio only; stopping it must not cancel a new
|
||||
// chat turn the user may have submitted while listening.
|
||||
try { chatViewModel?.cancelStream() } catch (_: Exception) { /* ignore */ }
|
||||
streamObserverJob?.cancel()
|
||||
streamObserverJob = null
|
||||
currentTurnJob?.cancel()
|
||||
currentTurnJob = null
|
||||
continuousLoopArmed = false
|
||||
}
|
||||
continuousResumeJob?.cancel()
|
||||
continuousResumeJob = null
|
||||
realtimeAmplitudeDecayJob?.cancel()
|
||||
@@ -2336,18 +2355,22 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
return bargeInReaderRelease
|
||||
}
|
||||
|
||||
/** Stop one-shot message narration without cancelling chat generation. */
|
||||
fun stopResponseSpeech(): Boolean {
|
||||
if (!_responseSpeechActive.value) return false
|
||||
interruptSpeaking(cancelActiveTurn = false)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays a completed chat response through the currently selected voice
|
||||
* output. The UI exposes this only in idle Conversation mode, but the
|
||||
* state checks remain here so non-UI callers cannot overlap a live turn.
|
||||
* output. This is intentionally independent of Voice Mode: a configured
|
||||
* voice can read a settled chat reply directly from its message menu. The
|
||||
* state checks remain here so non-UI callers cannot overlap live playback.
|
||||
*/
|
||||
fun speakResponse(text: String): Boolean {
|
||||
val state = _uiState.value
|
||||
if (
|
||||
!state.voiceMode ||
|
||||
state.state != VoiceState.Idle ||
|
||||
providerRealtimeAgentTurnActive.get()
|
||||
) {
|
||||
if (!canSpeakSettledResponse(state, providerRealtimeAgentTurnActive.get())) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -2355,6 +2378,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
if (spoken.isBlank()) return false
|
||||
|
||||
realtimeAudioSuppressed = false
|
||||
_responseSpeechActive.value = true
|
||||
_uiState.update {
|
||||
it.copy(
|
||||
state = VoiceState.Speaking,
|
||||
@@ -2365,6 +2389,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
}
|
||||
val queued = enqueueSentenceForTts(spoken, immediate = true)
|
||||
if (!queued) {
|
||||
_responseSpeechActive.value = false
|
||||
_uiState.update {
|
||||
it.copy(state = VoiceState.Idle, outputAudioActive = false)
|
||||
}
|
||||
@@ -5435,7 +5460,9 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
delay(initialDelayMs.coerceIn(AUDIO_COMPLETION_RETRY_MS, AUDIO_COMPLETION_MAX_SLEEP_MS))
|
||||
repeat(120) {
|
||||
val state = _uiState.value
|
||||
if (!state.voiceMode || isMicCaptureActive()) {
|
||||
if (!ownsVoiceAudioCompletion(state.voiceMode, _responseSpeechActive.value) ||
|
||||
isMicCaptureActive()
|
||||
) {
|
||||
return@launch
|
||||
}
|
||||
|
||||
@@ -5483,7 +5510,10 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
estimate
|
||||
}
|
||||
return decideAgentAudioCompletion(
|
||||
voiceMode = _uiState.value.voiceMode,
|
||||
voiceMode = ownsVoiceAudioCompletion(
|
||||
_uiState.value.voiceMode,
|
||||
_responseSpeechActive.value,
|
||||
),
|
||||
observerStopped = streamObserverJob?.isActive != true,
|
||||
pendingTtsWork = pendingInTtsQueue.get() +
|
||||
if (standardSpeechStreamState == StandardSpeechStreamState.Opening ||
|
||||
@@ -5501,6 +5531,7 @@ class VoiceViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private fun finishAgentAudioOutput() {
|
||||
continuousResumeJob = null
|
||||
_responseSpeechActive.value = false
|
||||
stopBargeInListener()
|
||||
cancelStandardSpeechStream("audio output finished")
|
||||
realtimeAmplitudeDecayJob?.cancel()
|
||||
|
||||
@@ -18,11 +18,13 @@ import com.hermesandroid.relay.network.upstream.DashboardApiClient
|
||||
import com.hermesandroid.relay.network.upstream.DashboardProfileScope
|
||||
import com.hermesandroid.relay.network.upstream.GatewayAvailability
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.SessionMessageLoadMode
|
||||
import com.hermesandroid.relay.network.upstream.models.SessionItem
|
||||
import com.hermesandroid.relay.network.relay.RelayHttpClient
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
@@ -181,7 +183,7 @@ class ProfileController(
|
||||
// Pending state still points at a previous connection mid-switch —
|
||||
// hold until this connection's restore re-stamps the pending name.
|
||||
pendingConnId != connId -> false
|
||||
pendingName == null || AgentDisplay.isServerDefaultAlias(pendingName) ->
|
||||
pendingName == null || pendingName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY ->
|
||||
serverDefaultSettled
|
||||
// Non-default name pending: settled once the profile list is present
|
||||
// (resolution attempted), even if the name turns out to be gone.
|
||||
@@ -269,6 +271,13 @@ class ProfileController(
|
||||
}
|
||||
}.stateIn(scope, SharingStarted.Eagerly, null)
|
||||
|
||||
/** Local icon for any profile identity on the active connection. */
|
||||
fun profileIconFlow(profileName: String?): Flow<String?> = activeConnectionId
|
||||
.flatMapLatest { connectionId ->
|
||||
if (connectionId == null) flowOf(null)
|
||||
else profileIconStore.iconFlow(connectionId, profileName)
|
||||
}
|
||||
|
||||
data class HostIconImportState(
|
||||
val loading: Boolean = false,
|
||||
val error: String? = null,
|
||||
@@ -340,12 +349,15 @@ class ProfileController(
|
||||
* `/api/sessions/{id}/messages?profile=`. Returns `null` off the dashboard
|
||||
* surface so the caller falls back to the api_server transcript.
|
||||
*/
|
||||
suspend fun loadProfileScopedMessages(sessionId: String): Result<List<MessageItem>>? {
|
||||
suspend fun loadProfileScopedMessages(
|
||||
sessionId: String,
|
||||
mode: SessionMessageLoadMode = SessionMessageLoadMode.COMPLETE,
|
||||
): Result<List<MessageItem>>? {
|
||||
val connectionId = activeConnectionId.value ?: return null
|
||||
val dashboardUrl = activeDashboardUrlProvider() ?: return null
|
||||
val profileName = resolveSessionProfileName()
|
||||
return dashboardClientFactory(connectionId, dashboardUrl)
|
||||
.getSessionMessages(sessionId, profileName)
|
||||
.getSessionMessages(sessionId, profileName, mode)
|
||||
}
|
||||
|
||||
suspend fun deleteProfileScopedSession(sessionId: String): Boolean {
|
||||
@@ -499,8 +511,8 @@ class ProfileController(
|
||||
|
||||
/**
|
||||
* The stored lock-token for a (possibly null) profile. Server default —
|
||||
* including the synthetic "default" alias — maps to
|
||||
* [AgentDisplay.SERVER_DEFAULT_PROFILE_KEY]; everything else to its name.
|
||||
* A null selection maps to [AgentDisplay.SERVER_DEFAULT_PROFILE_KEY]; a
|
||||
* profile literally named `default`, like every named profile, maps to its name.
|
||||
* Mirrors [AgentDisplay.profileSessionKey] so the lock token and the
|
||||
* session/selection key for the same profile always agree.
|
||||
*/
|
||||
@@ -610,11 +622,6 @@ class ProfileController(
|
||||
}
|
||||
val current = _selectedProfile.value
|
||||
if (current != null) {
|
||||
if (AgentDisplay.isServerDefaultAlias(current.name)) {
|
||||
_selectedProfile.value = null
|
||||
_pendingSelectedProfileName.value = null
|
||||
return true
|
||||
}
|
||||
val refreshed = list.firstOrNull { it.name == current.name }
|
||||
if (refreshed != null) {
|
||||
if (refreshed != current) {
|
||||
@@ -628,7 +635,7 @@ class ProfileController(
|
||||
return true
|
||||
}
|
||||
val pendingName = _pendingSelectedProfileName.value ?: return false
|
||||
if (AgentDisplay.isServerDefaultAlias(pendingName)) {
|
||||
if (pendingName == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY) {
|
||||
_pendingSelectedProfileName.value = null
|
||||
_selectedProfile.value = null
|
||||
return true
|
||||
@@ -652,9 +659,7 @@ class ProfileController(
|
||||
* can name it and so a later list arrival can recover it.
|
||||
*/
|
||||
private fun resolveLockedProfileFrom(token: String, list: List<Profile>): Boolean {
|
||||
if (AgentDisplay.isServerDefaultAlias(token) ||
|
||||
token == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY
|
||||
) {
|
||||
if (token == AgentDisplay.SERVER_DEFAULT_PROFILE_KEY) {
|
||||
_pendingSelectedProfileName.value = null
|
||||
val changed = _selectedProfile.value != null
|
||||
_selectedProfile.value = null
|
||||
@@ -678,22 +683,21 @@ class ProfileController(
|
||||
/**
|
||||
* Lock the active connection to [profile]. A `null` argument locks to
|
||||
* **Server default** (stored as the [AgentDisplay.SERVER_DEFAULT_PROFILE_KEY]
|
||||
* sentinel so it's distinct from "unlocked"). Persists the lock, then forces
|
||||
* the selection to the locked target via the normal [selectProfile] path so
|
||||
* sentinel so it's distinct from "unlocked"). Forces the selection at the
|
||||
* ViewModel boundary, then persists the lock so
|
||||
* the existing profile-switch machinery (fresh draft, gateway hot-swap, chat
|
||||
* API rebuild) runs. Locking to the already-selected profile is effectively
|
||||
* a no-op for the selection but still records the lock.
|
||||
*/
|
||||
suspend fun lockProfile(profile: Profile?) {
|
||||
fun lockProfile(profile: Profile?) {
|
||||
val connectionId = activeConnectionId.value ?: return
|
||||
val normalizedProfile = AgentDisplay.normalizeSelection(profile)
|
||||
val token = lockTokenFor(normalizedProfile)
|
||||
// Persist the lock first, then force-select via the un-gated body so the
|
||||
// switch lands even when re-locking from a different target (the
|
||||
// lockedProfileName StateFlow may still hold the previous token until the
|
||||
// DataStore emission propagates).
|
||||
profileLockStore.setLockedProfile(connectionId, token)
|
||||
// Force-select synchronously so callers can immediately detach/clear the
|
||||
// old Gateway session against the new profile identity. Persistence is
|
||||
// serialized by DataStore and the lock StateFlow catches up afterward.
|
||||
applyProfileSelection(normalizedProfile)
|
||||
scope.launch { profileLockStore.setLockedProfile(connectionId, token) }
|
||||
}
|
||||
|
||||
/** Remove the lock for the active connection (back to free profile choice). */
|
||||
@@ -729,7 +733,11 @@ class ProfileController(
|
||||
// current transport can't resume is exactly what forks a session
|
||||
// mid-conversation on a non-default profile.
|
||||
val transport = activeSessionTransport() ?: return
|
||||
val sessionProfileName = resolveSessionProfileName(profileName)
|
||||
// Persist the UI selection identity, not the resolved server route.
|
||||
// Server default may currently route to a sticky profile named
|
||||
// `default` (or any other name), but its last-session slot must remain
|
||||
// distinct from explicitly selecting that named profile.
|
||||
val sessionProfileName = profileName
|
||||
scope.launch {
|
||||
val profileScoped = profileSessionStore
|
||||
.sessionIdFlow(connectionId, sessionProfileName, transport)
|
||||
@@ -738,7 +746,7 @@ class ProfileController(
|
||||
// pre-transport (untransported) pointer is still resumable — surface
|
||||
// it as the fallback only for the server-default context.
|
||||
val legacyDefault = if (
|
||||
sessionProfileName == null || AgentDisplay.isServerDefaultAlias(sessionProfileName)
|
||||
sessionProfileName == null
|
||||
) {
|
||||
legacyDefaultSessionId()
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">Prévia de %1$s</string>
|
||||
<string name="pending_attachment_remove">Remover %1$s</string>
|
||||
<string name="pending_attachment_move_left">Mover %1$s para a esquerda</string>
|
||||
<string name="pending_attachment_move_right">Mover %1$s para a direita</string>
|
||||
<string name="pending_attachment_status_loading">Preparando prévia</string>
|
||||
<string name="pending_attachment_status_ready">Pronto</string>
|
||||
<string name="pending_attachment_status_failed">Prévia indisponível</string>
|
||||
</resources>
|
||||
@@ -694,6 +694,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">Mostre suas mensagens recentes como chips tocáveis acima do editor para enviá-las novamente. Desativado por padrão.</string>
|
||||
<string name="chat_settings_keep_keyboard_open">Manter o teclado aberto ao enviar</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Permaneça no editor após enviar. Desative para fechar o teclado depois de cada mensagem enviada.</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Tecla Enter do teclado físico</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Escolha se Enter envia ou insere uma nova linha. Ctrl+Enter sempre envia.</string>
|
||||
<string name="chat_settings_insert_newline">Inserir nova linha</string>
|
||||
<string name="chat_settings_notify_when_finishes">Alertas de chat em segundo plano</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notifique quando o Hermes precisar de uma resposta ou terminar em segundo plano</string>
|
||||
<string name="chat_settings_share_phone_status">Compartilhar o status do celular com o agente</string>
|
||||
@@ -2445,6 +2448,23 @@
|
||||
<string name="image_generation_rendering">Gerando imagem</string>
|
||||
<string name="tool_progress_cd_collapse">Recolher</string>
|
||||
<string name="tool_progress_cd_expand">Expandir</string>
|
||||
<string name="tool_progress_state_expanded">Expandido</string>
|
||||
<string name="tool_progress_state_collapsed">Recolhido</string>
|
||||
<string name="tool_run_preparing">Preparando %1$s</string>
|
||||
<string name="tool_run_running">Executando %1$s</string>
|
||||
<string name="tool_run_finished">%1$s concluído</string>
|
||||
<plurals name="tool_run_reading"><item quantity="one">Lendo %d item</item><item quantity="many">Lendo %d itens</item><item quantity="other">Lendo %d itens</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="one">Leu %d item</item><item quantity="many">Leu %d itens</item><item quantity="other">Leu %d itens</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="one">Pesquisando %d fonte</item><item quantity="many">Pesquisando %d fontes</item><item quantity="other">Pesquisando %d fontes</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="one">Pesquisou %d fonte</item><item quantity="many">Pesquisou %d fontes</item><item quantity="other">Pesquisou %d fontes</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="one">Executando %d comando</item><item quantity="many">Executando %d comandos</item><item quantity="other">Executando %d comandos</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="one">Executou %d comando</item><item quantity="many">Executou %d comandos</item><item quantity="other">Executou %d comandos</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="one">Executando %d ação do navegador</item><item quantity="many">Executando %d ações do navegador</item><item quantity="other">Executando %d ações do navegador</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="one">Executou %d ação do navegador</item><item quantity="many">Executou %d ações do navegador</item><item quantity="other">Executou %d ações do navegador</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="one">Executando %d ação do dispositivo</item><item quantity="many">Executando %d ações do dispositivo</item><item quantity="other">Executando %d ações do dispositivo</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="one">Executou %d ação do dispositivo</item><item quantity="many">Executou %d ações do dispositivo</item><item quantity="other">Executou %d ações do dispositivo</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="one">Usando %d ferramenta</item><item quantity="many">Usando %d ferramentas</item><item quantity="other">Usando %d ferramentas</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="one">Usou %d ferramenta</item><item quantity="many">Usou %d ferramentas</item><item quantity="other">Usou %d ferramentas</item></plurals>
|
||||
<!-- AgentIconRow -->
|
||||
<string name="agent_icon_title">Ícone do agente</string>
|
||||
<string name="agent_icon_set">Escolher arquivo</string>
|
||||
@@ -3483,6 +3503,7 @@
|
||||
<string name="tool_name_android">Ação no telefone</string>
|
||||
<string name="timeline_no_checks">sem verificações</string>
|
||||
<string name="thinking_title">Processo de raciocínio</string>
|
||||
<string name="thinking_settled">Pensamento</string>
|
||||
<string name="thinking_thinking_short">Pensando</string>
|
||||
<string name="thinking_thinking">Pensando...</string>
|
||||
<string name="task_status_working">Trabalhando</string>
|
||||
@@ -3608,6 +3629,7 @@
|
||||
<string name="voice_overlay_attachment_ready">Anexo pronto</string>
|
||||
<string name="conn_info_active_profile">Perfil ativo</string>
|
||||
<string name="msg_bubble_speak_response">Falar resposta</string>
|
||||
<string name="msg_bubble_stop_speaking">Parar fala</string>
|
||||
<string name="voice_overlay_engine_standard">Modo padrão</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Abrir Hermes</string>
|
||||
@@ -3726,4 +3748,81 @@
|
||||
<string name="support_bundle_copied">Informações de suporte copiadas</string>
|
||||
<string name="support_bundle_no_share">Informações de suporte copiadas — nenhum app encontrado para compartilhar</string>
|
||||
<string name="support_bundle_share_title">Compartilhar informações de suporte do Hermes-Relay</string>
|
||||
<string name="chat_search_conversation">Pesquisar conversa</string>
|
||||
<string name="chat_search_close">Fechar pesquisa</string>
|
||||
<string name="chat_search_no_results">Nenhum resultado</string>
|
||||
<string name="chat_search_result_count">%1$d de %2$d</string>
|
||||
<string name="msg_bubble_queued">Na fila</string>
|
||||
<string name="msg_bubble_steered">Correção enviada</string>
|
||||
<string name="chat_quote_you">Você</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">Abrir mensagem original de %1$s</string>
|
||||
<string name="chat_quote_remove">Remover citação</string>
|
||||
<string name="profile_shelf_switch_agent">Trocar agente</string>
|
||||
<string name="profile_shelf_all_profiles">Abrir todos os perfis de agente</string>
|
||||
<string name="profile_shelf_open_passport">Abrir Passaporte do agente</string>
|
||||
<string name="profile_shelf_switch_to">Trocar para este agente</string>
|
||||
<string name="profile_shelf_locked_hint">A troca de perfil está bloqueada. Toque e segure o agente ativo para desbloquear.</string>
|
||||
<string name="profile_shelf_inspect">Inspecionar perfil</string>
|
||||
<string name="profile_shelf_hide">Ocultar da estante de perfis</string>
|
||||
<string name="profile_shelf_expand">Expandir a estante de perfis</string>
|
||||
<string name="profile_shelf_collapse">Recolher a estante de perfis</string>
|
||||
<string name="appearance_intro">Escolha uma predefinição e veja o resultado ao vivo na prévia.</string>
|
||||
<string name="appearance_preset_gallery">Galeria de predefinições</string>
|
||||
<string name="appearance_preview_relay">Prévia · Relay</string>
|
||||
<string name="appearance_preview_user_message">Dê três dicas rápidas para uma manhã focada.</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. Escolha uma conquista real antes de conferir os feeds.\n2. Reserve os primeiros 45–90 minutos.\n3. Comece com um ritual de preparação, não com “motivação”.</string>
|
||||
<string name="appearance_preview_time">19:00</string>
|
||||
<string name="appearance_preview_voice">Voz</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 tokens · 137,2 mil</string>
|
||||
<string name="appearance_preview_message_placeholder">Mensagem…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / perfil: padrão</string>
|
||||
<string name="appearance_preview_live_note">Esta prévia é atualizada imediatamente com a predefinição, o modo, a fonte e a aparência da Sphere.</string>
|
||||
<string name="appearance_customize_theme">Personalizar %1$s</string>
|
||||
<string name="appearance_accent_preset">Cor de destaque predefinida</string>
|
||||
<string name="appearance_accent_custom">Cor de destaque personalizada aplicada</string>
|
||||
<string name="appearance_accent_preview_only">As alterações ficam na prévia até você aplicá-las.</string>
|
||||
<string name="appearance_accent_preview_only_short">Somente prévia</string>
|
||||
<string name="appearance_apply_changes">Aplicar alterações</string>
|
||||
<string name="appearance_customize_summary">Destaque, superfícies, forma e densidade</string>
|
||||
<string name="appearance_shape">Forma</string>
|
||||
<string name="appearance_shape_soft">Suave</string>
|
||||
<string name="appearance_shape_balanced">Equilibrada</string>
|
||||
<string name="appearance_shape_sharp">Angular</string>
|
||||
<string name="appearance_contrast_passes">Contraste aprovado</string>
|
||||
<string name="appearance_contrast_fails">O contraste precisa melhorar</string>
|
||||
<string name="appearance_contrast_aa">AA para texto normal</string>
|
||||
<string name="appearance_typography_density">Tipografia e densidade</string>
|
||||
<string name="appearance_readability">Legibilidade</string>
|
||||
<string name="appearance_default">Padrão</string>
|
||||
<string name="appearance_font_normal_summary">Tamanho da fonte: Normal</string>
|
||||
<string name="appearance_reset_draft">Redefinir rascunho</string>
|
||||
<string name="appearance_accent">Cor de destaque</string>
|
||||
<string name="appearance_contrast_status">Contraste legível · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">A tipografia e a densidade usam os controles específicos de Fonte e Tamanho da fonte abaixo.</string>
|
||||
<string name="appearance_readability_summary">Ajuste a densidade do texto aqui; escolha a tipografia na seção Fonte abaixo.</string>
|
||||
<string name="appearance_reset">Redefinir</string>
|
||||
<string name="appearance_apply">Aplicar</string>
|
||||
<string name="appearance_background_installed">Animações instaladas</string>
|
||||
<string name="appearance_import_background">Importar animação de fundo</string>
|
||||
<string name="appearance_import_background_desc">Importa o mesmo ZIP seguro de pet do Relay ou formato de imagem única, mas o usa apenas na visualização central ou de fundo. Não ativa a movimentação nem altera o pet flutuante.</string>
|
||||
<string name="appearance_import_sphere">Importar aparência da Sphere</string>
|
||||
<string name="appearance_create_pet">Criar um pet personalizado</string>
|
||||
<string name="pet_creator_title">Criar um pet personalizado</string>
|
||||
<string name="pet_creator_intro">Descreva seu companheiro, revise as instruções geradas e escolha onde criá-lo. Nada é enviado até você mesmo enviar o novo chat.</string>
|
||||
<string name="pet_creator_step_idea">Escolher a ideia</string>
|
||||
<string name="pet_creator_name">Nome do pet</string>
|
||||
<string name="pet_creator_description">Direção do personagem</string>
|
||||
<string name="pet_creator_description_hint">Descreva o personagem, os materiais, as cores, o clima e qualquer imagem de referência que você pretende anexar.</string>
|
||||
<string name="pet_creator_animated">Pacote animado</string>
|
||||
<string name="pet_creator_static">Imagem estática</string>
|
||||
<string name="pet_creator_step_create">Revisar e criar</string>
|
||||
<string name="pet_creator_review_copy">Estas instruções completas incluem o formato atual de pets e os limites de validação, privacidade e revisão.</string>
|
||||
<string name="pet_creator_copy">Copiar</string>
|
||||
<string name="pet_creator_copied">Instruções copiadas</string>
|
||||
<string name="pet_creator_new_chat">Novo chat</string>
|
||||
<string name="pet_creator_step_review">Revisar e importar</string>
|
||||
<string name="pet_creator_review_desc">Inspecione primeiro a imagem ou o ZIP retornado. A importação copia os arquivos validados para o armazenamento do app; ela não os publica.</string>
|
||||
<string name="pet_creator_import">Importar pet concluído</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">预览 %1$s</string>
|
||||
<string name="pending_attachment_remove">移除 %1$s</string>
|
||||
<string name="pending_attachment_move_left">将 %1$s 向左移动</string>
|
||||
<string name="pending_attachment_move_right">将 %1$s 向右移动</string>
|
||||
<string name="pending_attachment_status_loading">正在准备预览</string>
|
||||
<string name="pending_attachment_status_ready">已就绪</string>
|
||||
<string name="pending_attachment_status_failed">预览不可用</string>
|
||||
</resources>
|
||||
@@ -736,6 +736,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">在输入栏上方显示最近消息为可点击的标签以便重发。默认关闭。</string>
|
||||
<string name="chat_settings_keep_keyboard_open">发送时保持键盘打开</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">发送后留在输入栏。关闭则在每条消息发送后收起键盘。</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">实体键盘 Enter 键</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">选择按 Enter 是发送消息还是插入新行。Ctrl+Enter 始终发送。</string>
|
||||
<string name="chat_settings_insert_newline">插入新行</string>
|
||||
<string name="chat_settings_notify_when_finishes">后台聊天提醒</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Hermes 在后台需要输入或完成回复时通知</string>
|
||||
<string name="chat_settings_share_phone_status">与代理分享手机状态</string>
|
||||
@@ -2554,6 +2557,23 @@
|
||||
<string name="image_generation_rendering">正在生成图像</string>
|
||||
<string name="tool_progress_cd_collapse">折叠</string>
|
||||
<string name="tool_progress_cd_expand">展开</string>
|
||||
<string name="tool_progress_state_expanded">已展开</string>
|
||||
<string name="tool_progress_state_collapsed">已折叠</string>
|
||||
<string name="tool_run_preparing">正在准备%1$s</string>
|
||||
<string name="tool_run_running">正在运行%1$s</string>
|
||||
<string name="tool_run_finished">已完成%1$s</string>
|
||||
<plurals name="tool_run_reading"><item quantity="other">正在读取 %d 项</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="other">已读取 %d 项</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="other">正在搜索 %d 个来源</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="other">已搜索 %d 个来源</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="other">正在运行 %d 个命令</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="other">已运行 %d 个命令</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="other">正在执行 %d 个浏览器操作</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="other">已执行 %d 个浏览器操作</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="other">正在执行 %d 个设备操作</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="other">已执行 %d 个设备操作</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="other">正在使用 %d 个工具</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="other">已使用 %d 个工具</item></plurals>
|
||||
|
||||
<!-- AgentIconRow -->
|
||||
<string name="agent_icon_title">代理图标</string>
|
||||
@@ -3571,6 +3591,7 @@
|
||||
<string name="tool_name_android">手机操作</string>
|
||||
<string name="timeline_no_checks">无检查</string>
|
||||
<string name="thinking_title">思考过程</string>
|
||||
<string name="thinking_settled">思考</string>
|
||||
<string name="thinking_thinking_short">思考中</string>
|
||||
<string name="thinking_thinking">思考中…</string>
|
||||
<string name="task_status_working">处理中</string>
|
||||
@@ -3696,6 +3717,7 @@
|
||||
<string name="voice_overlay_attachment_ready">附件已就绪</string>
|
||||
<string name="conn_info_active_profile">活跃个人资料</string>
|
||||
<string name="msg_bubble_speak_response">朗读回复</string>
|
||||
<string name="msg_bubble_stop_speaking">停止朗读</string>
|
||||
<string name="voice_overlay_engine_standard">标准模式</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">打开 Hermes</string>
|
||||
@@ -3814,4 +3836,81 @@
|
||||
<string name="support_bundle_copied">支持信息已复制</string>
|
||||
<string name="support_bundle_no_share">支持信息已复制 — 未找到可分享的应用</string>
|
||||
<string name="support_bundle_share_title">分享 Hermes-Relay 支持信息</string>
|
||||
<string name="chat_search_conversation">搜索对话</string>
|
||||
<string name="chat_search_close">关闭搜索</string>
|
||||
<string name="chat_search_no_results">无结果</string>
|
||||
<string name="chat_search_result_count">%1$d / %2$d</string>
|
||||
<string name="msg_bubble_queued">已排队</string>
|
||||
<string name="msg_bubble_steered">更正已发送</string>
|
||||
<string name="chat_quote_you">你</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">打开 %1$s 的原始消息</string>
|
||||
<string name="chat_quote_remove">移除引用</string>
|
||||
<string name="profile_shelf_switch_agent">切换智能体</string>
|
||||
<string name="profile_shelf_all_profiles">打开所有智能体配置</string>
|
||||
<string name="profile_shelf_open_passport">打开智能体护照</string>
|
||||
<string name="profile_shelf_switch_to">切换到此智能体</string>
|
||||
<string name="profile_shelf_locked_hint">配置切换已锁定。长按当前智能体即可解锁。</string>
|
||||
<string name="profile_shelf_inspect">查看配置</string>
|
||||
<string name="profile_shelf_hide">从配置架中隐藏</string>
|
||||
<string name="profile_shelf_expand">展开配置架</string>
|
||||
<string name="profile_shelf_collapse">收起配置架</string>
|
||||
<string name="appearance_intro">选择一个预设,即时查看预览效果。</string>
|
||||
<string name="appearance_preset_gallery">预设库</string>
|
||||
<string name="appearance_preview_relay">预览 · Relay</string>
|
||||
<string name="appearance_preview_user_message">给我三个专注开启早晨的小建议。</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. 查看信息流之前,先选定一个真正的成果。\n2. 留出最初的 45–90 分钟。\n3. 从准备仪式开始,而不是等待“动力”。</string>
|
||||
<string name="appearance_preview_time">晚上 7:00</string>
|
||||
<string name="appearance_preview_voice">语音</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 个 token · 137.2K</string>
|
||||
<string name="appearance_preview_message_placeholder">消息…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / 配置文件:默认</string>
|
||||
<string name="appearance_preview_live_note">更改预设、模式、字体或 Sphere 皮肤后,此预览会立即更新。</string>
|
||||
<string name="appearance_customize_theme">自定义 %1$s</string>
|
||||
<string name="appearance_accent_preset">预设强调色</string>
|
||||
<string name="appearance_accent_custom">已应用自定义强调色</string>
|
||||
<string name="appearance_accent_preview_only">应用之前,更改只会显示在预览中。</string>
|
||||
<string name="appearance_accent_preview_only_short">仅预览</string>
|
||||
<string name="appearance_apply_changes">应用更改</string>
|
||||
<string name="appearance_customize_summary">强调色、表面、形状和密度</string>
|
||||
<string name="appearance_shape">形状</string>
|
||||
<string name="appearance_shape_soft">柔和</string>
|
||||
<string name="appearance_shape_balanced">均衡</string>
|
||||
<string name="appearance_shape_sharp">锐利</string>
|
||||
<string name="appearance_contrast_passes">对比度达标</string>
|
||||
<string name="appearance_contrast_fails">对比度需要改进</string>
|
||||
<string name="appearance_contrast_aa">普通文本 AA 标准</string>
|
||||
<string name="appearance_typography_density">排版和密度</string>
|
||||
<string name="appearance_readability">可读性</string>
|
||||
<string name="appearance_default">默认</string>
|
||||
<string name="appearance_font_normal_summary">字体大小:标准</string>
|
||||
<string name="appearance_reset_draft">重置草稿</string>
|
||||
<string name="appearance_accent">强调色</string>
|
||||
<string name="appearance_contrast_status">易读对比度 · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">排版和密度使用下方独立的字体和字体大小控件。</string>
|
||||
<string name="appearance_readability_summary">在此调整文本密度;在下方的字体部分选择字形。</string>
|
||||
<string name="appearance_reset">重置</string>
|
||||
<string name="appearance_apply">应用</string>
|
||||
<string name="appearance_background_installed">已安装的动画</string>
|
||||
<string name="appearance_import_background">导入背景动画</string>
|
||||
<string name="appearance_import_background_desc">导入与安全 Relay 宠物 ZIP 或单张图片相同的格式,但仅用于中央或背景可视化。它不会启用漫游,也不会更改悬浮宠物。</string>
|
||||
<string name="appearance_import_sphere">导入 Sphere 皮肤</string>
|
||||
<string name="appearance_create_pet">创建自定义宠物</string>
|
||||
<string name="pet_creator_title">创建自定义宠物</string>
|
||||
<string name="pet_creator_intro">描述你的伙伴,检查生成的说明,然后选择创建位置。在你自行发送新聊天之前,不会发送任何内容。</string>
|
||||
<string name="pet_creator_step_idea">选择构思</string>
|
||||
<string name="pet_creator_name">宠物名称</string>
|
||||
<string name="pet_creator_description">角色方向</string>
|
||||
<string name="pet_creator_description_hint">描述角色、材质、颜色、氛围以及计划附加的参考图片。</string>
|
||||
<string name="pet_creator_animated">动画包</string>
|
||||
<string name="pet_creator_static">静态图片</string>
|
||||
<string name="pet_creator_step_create">检查并创建</string>
|
||||
<string name="pet_creator_review_copy">这些完整说明涵盖当前宠物格式、验证、隐私和审查边界。</string>
|
||||
<string name="pet_creator_copy">复制</string>
|
||||
<string name="pet_creator_copied">说明已复制</string>
|
||||
<string name="pet_creator_new_chat">新聊天</string>
|
||||
<string name="pet_creator_step_review">检查并导入</string>
|
||||
<string name="pet_creator_review_desc">请先检查返回的图片或 ZIP。导入会将经过验证的文件复制到应用专属存储空间,不会发布它们。</string>
|
||||
<string name="pet_creator_import">导入完成的宠物</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">Vorschau für %1$s</string>
|
||||
<string name="pending_attachment_remove">%1$s entfernen</string>
|
||||
<string name="pending_attachment_move_left">%1$s nach links verschieben</string>
|
||||
<string name="pending_attachment_move_right">%1$s nach rechts verschieben</string>
|
||||
<string name="pending_attachment_status_loading">Vorschau wird vorbereitet</string>
|
||||
<string name="pending_attachment_status_ready">Bereit</string>
|
||||
<string name="pending_attachment_status_failed">Vorschau nicht verfügbar</string>
|
||||
</resources>
|
||||
@@ -736,6 +736,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">Letzte Nachrichten als antippbare Chips über dem Eingabefeld anzeigen, um sie erneut zu senden. Standardmäßig aus.</string>
|
||||
<string name="chat_settings_keep_keyboard_open">Tastatur nach dem Senden geöffnet lassen</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Nach dem Senden im Eingabefeld bleiben. Ausschalten, um die Tastatur nach jeder gesendeten Nachricht zu schließen.</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Eingabetaste der physischen Tastatur</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Wähle, ob die Eingabetaste sendet oder eine neue Zeile einfügt. Strg+Eingabetaste sendet immer.</string>
|
||||
<string name="chat_settings_insert_newline">Neue Zeile einfügen</string>
|
||||
<string name="chat_settings_notify_when_finishes">Chat-Benachrichtigungen im Hintergrund</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Benachrichtigen, wenn Hermes Eingaben benötigt oder im Hintergrund fertig wird</string>
|
||||
<string name="chat_settings_share_phone_status">Smartphone-Status mit Agent teilen</string>
|
||||
@@ -2557,6 +2560,23 @@
|
||||
<string name="image_generation_rendering">Bild wird erstellt</string>
|
||||
<string name="tool_progress_cd_collapse">Einklappen</string>
|
||||
<string name="tool_progress_cd_expand">Ausklappen</string>
|
||||
<string name="tool_progress_state_expanded">Ausgeklappt</string>
|
||||
<string name="tool_progress_state_collapsed">Eingeklappt</string>
|
||||
<string name="tool_run_preparing">%1$s wird vorbereitet</string>
|
||||
<string name="tool_run_running">%1$s wird ausgeführt</string>
|
||||
<string name="tool_run_finished">%1$s abgeschlossen</string>
|
||||
<plurals name="tool_run_reading"><item quantity="one">%d Element wird gelesen</item><item quantity="other">%d Elemente werden gelesen</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="one">%d Element gelesen</item><item quantity="other">%d Elemente gelesen</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="one">%d Quelle wird durchsucht</item><item quantity="other">%d Quellen werden durchsucht</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="one">%d Quelle durchsucht</item><item quantity="other">%d Quellen durchsucht</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="one">%d Befehl wird ausgeführt</item><item quantity="other">%d Befehle werden ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="one">%d Befehl ausgeführt</item><item quantity="other">%d Befehle ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="one">%d Browseraktion wird ausgeführt</item><item quantity="other">%d Browseraktionen werden ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="one">%d Browseraktion ausgeführt</item><item quantity="other">%d Browseraktionen ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="one">%d Geräteaktion wird ausgeführt</item><item quantity="other">%d Geräteaktionen werden ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="one">%d Geräteaktion ausgeführt</item><item quantity="other">%d Geräteaktionen ausgeführt</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="one">%d Werkzeug wird verwendet</item><item quantity="other">%d Werkzeuge werden verwendet</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="one">%d Werkzeug verwendet</item><item quantity="other">%d Werkzeuge verwendet</item></plurals>
|
||||
|
||||
<!-- AgentIconRow -->
|
||||
<string name="agent_icon_title">Agentensymbol</string>
|
||||
@@ -3638,6 +3658,7 @@
|
||||
<string name="tool_name_android">Telefonaktion</string>
|
||||
<string name="timeline_no_checks">keine Prüfungen</string>
|
||||
<string name="thinking_title">Denkprozess</string>
|
||||
<string name="thinking_settled">Gedanke</string>
|
||||
<string name="thinking_thinking_short">Denkt nach</string>
|
||||
<string name="thinking_thinking">Denkt nach…</string>
|
||||
<string name="task_status_working">In Arbeit</string>
|
||||
@@ -3768,6 +3789,7 @@
|
||||
<string name="voice_overlay_attachment_ready">Anhang bereit</string>
|
||||
<string name="conn_info_active_profile">Aktives Profil</string>
|
||||
<string name="msg_bubble_speak_response">Antwort vorlesen</string>
|
||||
<string name="msg_bubble_stop_speaking">Wiedergabe stoppen</string>
|
||||
<string name="voice_overlay_engine_standard">Standardmodus</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Hermes öffnen</string>
|
||||
@@ -3886,4 +3908,81 @@
|
||||
<string name="support_bundle_copied">Supportinformationen kopiert</string>
|
||||
<string name="support_bundle_no_share">Supportinformationen kopiert — keine App zum Teilen gefunden</string>
|
||||
<string name="support_bundle_share_title">Hermes-Relay-Supportinformationen teilen</string>
|
||||
<string name="chat_search_conversation">Unterhaltung durchsuchen</string>
|
||||
<string name="chat_search_close">Suche schließen</string>
|
||||
<string name="chat_search_no_results">Keine Ergebnisse</string>
|
||||
<string name="chat_search_result_count">%1$d von %2$d</string>
|
||||
<string name="msg_bubble_queued">In Warteschlange</string>
|
||||
<string name="msg_bubble_steered">Korrektur gesendet</string>
|
||||
<string name="chat_quote_you">Du</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">Ursprüngliche Nachricht von %1$s öffnen</string>
|
||||
<string name="chat_quote_remove">Zitat entfernen</string>
|
||||
<string name="profile_shelf_switch_agent">Agent wechseln</string>
|
||||
<string name="profile_shelf_all_profiles">Alle Agentenprofile öffnen</string>
|
||||
<string name="profile_shelf_open_passport">Agentenpass öffnen</string>
|
||||
<string name="profile_shelf_switch_to">Zu diesem Agenten wechseln</string>
|
||||
<string name="profile_shelf_locked_hint">Der Profilwechsel ist gesperrt. Halten Sie den aktiven Agenten gedrückt, um die Sperre aufzuheben.</string>
|
||||
<string name="profile_shelf_inspect">Profil prüfen</string>
|
||||
<string name="profile_shelf_hide">Aus der Profilablage ausblenden</string>
|
||||
<string name="profile_shelf_expand">Profilablage erweitern</string>
|
||||
<string name="profile_shelf_collapse">Profilablage einklappen</string>
|
||||
<string name="appearance_intro">Wählen Sie eine Vorlage und sehen Sie sie direkt in der Vorschau.</string>
|
||||
<string name="appearance_preset_gallery">Vorlagengalerie</string>
|
||||
<string name="appearance_preview_relay">Vorschau · Relay</string>
|
||||
<string name="appearance_preview_user_message">Gib mir drei kurze Tipps für einen konzentrierten Morgen.</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. Wähle einen echten Erfolg, bevor du Feeds prüfst.\n2. Blockiere die ersten 45–90 Minuten.\n3. Beginne mit einem Einrichtungsritual statt mit „Motivation“.</string>
|
||||
<string name="appearance_preview_time">19:00</string>
|
||||
<string name="appearance_preview_voice">Sprache</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 Token · 137,2K</string>
|
||||
<string name="appearance_preview_message_placeholder">Nachricht…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / Profil: Standard</string>
|
||||
<string name="appearance_preview_live_note">Diese Vorschau wird sofort mit Vorlage, Modus, Schrift und Sphere-Skin aktualisiert.</string>
|
||||
<string name="appearance_customize_theme">%1$s anpassen</string>
|
||||
<string name="appearance_accent_preset">Voreingestellte Akzentfarbe</string>
|
||||
<string name="appearance_accent_custom">Eigene Akzentfarbe angewendet</string>
|
||||
<string name="appearance_accent_preview_only">Änderungen bleiben in der Vorschau, bis Sie sie anwenden.</string>
|
||||
<string name="appearance_accent_preview_only_short">Nur Vorschau</string>
|
||||
<string name="appearance_apply_changes">Änderungen anwenden</string>
|
||||
<string name="appearance_customize_summary">Akzent, Flächen, Form & Dichte</string>
|
||||
<string name="appearance_shape">Form</string>
|
||||
<string name="appearance_shape_soft">Weich</string>
|
||||
<string name="appearance_shape_balanced">Ausgewogen</string>
|
||||
<string name="appearance_shape_sharp">Kantig</string>
|
||||
<string name="appearance_contrast_passes">Kontrast ausreichend</string>
|
||||
<string name="appearance_contrast_fails">Kontrast muss verbessert werden</string>
|
||||
<string name="appearance_contrast_aa">AA für normalen Text</string>
|
||||
<string name="appearance_typography_density">Typografie & Dichte</string>
|
||||
<string name="appearance_readability">Lesbarkeit</string>
|
||||
<string name="appearance_default">Standard</string>
|
||||
<string name="appearance_font_normal_summary">Schriftgröße: Normal</string>
|
||||
<string name="appearance_reset_draft">Entwurf zurücksetzen</string>
|
||||
<string name="appearance_accent">Akzentfarbe</string>
|
||||
<string name="appearance_contrast_status">Lesbarer Kontrast · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">Typografie und Dichte verwenden die gezielten Einstellungen für Schrift und Schriftgröße unten.</string>
|
||||
<string name="appearance_readability_summary">Passen Sie hier die Textdichte an; wählen Sie die Schriftart im Abschnitt „Schrift“ unten.</string>
|
||||
<string name="appearance_reset">Zurücksetzen</string>
|
||||
<string name="appearance_apply">Anwenden</string>
|
||||
<string name="appearance_background_installed">Installierte Animationen</string>
|
||||
<string name="appearance_import_background">Hintergrundanimation importieren</string>
|
||||
<string name="appearance_import_background_desc">Importiert dasselbe sichere Relay-Pet-ZIP- oder Einzelbildformat, verwendet es aber nur für die zentrale Hintergrunddarstellung. Roaming wird nicht aktiviert und das schwebende Pet nicht geändert.</string>
|
||||
<string name="appearance_import_sphere">Sphere-Skin importieren</string>
|
||||
<string name="appearance_create_pet">Eigenes Pet erstellen</string>
|
||||
<string name="pet_creator_title">Eigenes Pet erstellen</string>
|
||||
<string name="pet_creator_intro">Beschreiben Sie Ihren Begleiter, prüfen Sie die erzeugten Anweisungen und wählen Sie dann, wo Sie ihn erstellen. Es wird nichts gesendet, bis Sie den neuen Chat selbst absenden.</string>
|
||||
<string name="pet_creator_step_idea">Idee auswählen</string>
|
||||
<string name="pet_creator_name">Pet-Name</string>
|
||||
<string name="pet_creator_description">Charakterrichtung</string>
|
||||
<string name="pet_creator_description_hint">Beschreiben Sie Charakter, Materialien, Farben, Stimmung und alle Referenzbilder, die Sie anhängen möchten.</string>
|
||||
<string name="pet_creator_animated">Animiertes Paket</string>
|
||||
<string name="pet_creator_static">Statisches Bild</string>
|
||||
<string name="pet_creator_step_create">Prüfen und erstellen</string>
|
||||
<string name="pet_creator_review_copy">Diese vollständigen Anweisungen enthalten das aktuelle Pet-Format sowie Validierungs-, Datenschutz- und Prüfgrenzen.</string>
|
||||
<string name="pet_creator_copy">Kopieren</string>
|
||||
<string name="pet_creator_copied">Anweisungen kopiert</string>
|
||||
<string name="pet_creator_new_chat">Neuer Chat</string>
|
||||
<string name="pet_creator_step_review">Prüfen und importieren</string>
|
||||
<string name="pet_creator_review_desc">Prüfen Sie zuerst das zurückgegebene Bild oder ZIP. Beim Import werden die validierten Dateien in den App-Speicher kopiert; sie werden nicht veröffentlicht.</string>
|
||||
<string name="pet_creator_import">Fertiges Pet importieren</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">Vista previa de %1$s</string>
|
||||
<string name="pending_attachment_remove">Quitar %1$s</string>
|
||||
<string name="pending_attachment_move_left">Mover %1$s a la izquierda</string>
|
||||
<string name="pending_attachment_move_right">Mover %1$s a la derecha</string>
|
||||
<string name="pending_attachment_status_loading">Preparando vista previa</string>
|
||||
<string name="pending_attachment_status_ready">Listo</string>
|
||||
<string name="pending_attachment_status_failed">Vista previa no disponible</string>
|
||||
</resources>
|
||||
@@ -661,6 +661,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">Muestre sus mensajes recientes como chips que se pueden tocar encima del redactor para enviarlos nuevamente. Desactivado de forma predeterminada.</string>
|
||||
<string name="chat_settings_keep_keyboard_open">Mantener el teclado abierto al enviar</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Permanece en el compositor después del envío. Desactívelo para descartar el teclado después de cada mensaje enviado.</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Tecla Intro del teclado físico</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Elige si Intro envía o inserta una línea nueva. Ctrl+Intro siempre envía.</string>
|
||||
<string name="chat_settings_insert_newline">Insertar línea nueva</string>
|
||||
<string name="chat_settings_notify_when_finishes">Alertas de chat en segundo plano</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notificar cuando Hermes necesite información o termine en segundo plano</string>
|
||||
<string name="chat_settings_share_phone_status">Compartir el estado del teléfono con el agente</string>
|
||||
@@ -2330,6 +2333,23 @@
|
||||
<string name="image_generation_rendering">Generando imagen</string>
|
||||
<string name="tool_progress_cd_collapse">Colapsar</string>
|
||||
<string name="tool_progress_cd_expand">Expandir</string>
|
||||
<string name="tool_progress_state_expanded">Expandido</string>
|
||||
<string name="tool_progress_state_collapsed">Contraído</string>
|
||||
<string name="tool_run_preparing">Preparando %1$s</string>
|
||||
<string name="tool_run_running">Ejecutando %1$s</string>
|
||||
<string name="tool_run_finished">%1$s finalizado</string>
|
||||
<plurals name="tool_run_reading"><item quantity="one">Leyendo %d elemento</item><item quantity="other">Leyendo %d elementos</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="one">Se leyó %d elemento</item><item quantity="other">Se leyeron %d elementos</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="one">Buscando en %d fuente</item><item quantity="other">Buscando en %d fuentes</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="one">Se buscó en %d fuente</item><item quantity="other">Se buscó en %d fuentes</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="one">Ejecutando %d comando</item><item quantity="other">Ejecutando %d comandos</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="one">Se ejecutó %d comando</item><item quantity="other">Se ejecutaron %d comandos</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="one">Ejecutando %d acción del navegador</item><item quantity="other">Ejecutando %d acciones del navegador</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="one">Se ejecutó %d acción del navegador</item><item quantity="other">Se ejecutaron %d acciones del navegador</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="one">Ejecutando %d acción del dispositivo</item><item quantity="other">Ejecutando %d acciones del dispositivo</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="one">Se ejecutó %d acción del dispositivo</item><item quantity="other">Se ejecutaron %d acciones del dispositivo</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="one">Usando %d herramienta</item><item quantity="other">Usando %d herramientas</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="one">Se usó %d herramienta</item><item quantity="other">Se usaron %d herramientas</item></plurals>
|
||||
<string name="agent_icon_title">Icono de agente</string>
|
||||
<string name="agent_icon_set">Elegir archivo</string>
|
||||
<string name="agent_icon_change">Elegir archivo</string>
|
||||
@@ -3323,6 +3343,7 @@
|
||||
<string name="tool_name_android">Acción en el teléfono</string>
|
||||
<string name="timeline_no_checks">sin comprobaciones</string>
|
||||
<string name="thinking_title">Proceso de pensamiento</string>
|
||||
<string name="thinking_settled">Pensamiento</string>
|
||||
<string name="thinking_thinking_short">Pensando</string>
|
||||
<string name="thinking_thinking">Pensando…</string>
|
||||
<string name="task_status_working">Trabajando</string>
|
||||
@@ -3453,6 +3474,7 @@
|
||||
<string name="voice_overlay_attachment_ready">Adjunto listo</string>
|
||||
<string name="conn_info_active_profile">Perfil activo</string>
|
||||
<string name="msg_bubble_speak_response">Leer respuesta</string>
|
||||
<string name="msg_bubble_stop_speaking">Detener lectura</string>
|
||||
<string name="voice_overlay_engine_standard">Modo estándar</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Abrir Hermes</string>
|
||||
@@ -3571,4 +3593,81 @@
|
||||
<string name="support_bundle_copied">Información de soporte copiada</string>
|
||||
<string name="support_bundle_no_share">Información de soporte copiada — no se encontró una aplicación para compartir</string>
|
||||
<string name="support_bundle_share_title">Compartir información de soporte de Hermes-Relay</string>
|
||||
<string name="chat_search_conversation">Buscar en la conversación</string>
|
||||
<string name="chat_search_close">Cerrar búsqueda</string>
|
||||
<string name="chat_search_no_results">Sin resultados</string>
|
||||
<string name="chat_search_result_count">%1$d de %2$d</string>
|
||||
<string name="msg_bubble_queued">En cola</string>
|
||||
<string name="msg_bubble_steered">Corrección enviada</string>
|
||||
<string name="chat_quote_you">Tú</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">Abrir mensaje original de %1$s</string>
|
||||
<string name="chat_quote_remove">Quitar cita</string>
|
||||
<string name="profile_shelf_switch_agent">Cambiar de agente</string>
|
||||
<string name="profile_shelf_all_profiles">Abrir todos los perfiles de agente</string>
|
||||
<string name="profile_shelf_open_passport">Abrir Pasaporte del agente</string>
|
||||
<string name="profile_shelf_switch_to">Cambiar a este agente</string>
|
||||
<string name="profile_shelf_locked_hint">El cambio de perfil está bloqueado. Mantén pulsado el agente activo para desbloquearlo.</string>
|
||||
<string name="profile_shelf_inspect">Inspeccionar perfil</string>
|
||||
<string name="profile_shelf_hide">Ocultar de la bandeja de perfiles</string>
|
||||
<string name="profile_shelf_expand">Expandir la bandeja de perfiles</string>
|
||||
<string name="profile_shelf_collapse">Contraer la bandeja de perfiles</string>
|
||||
<string name="appearance_intro">Elige un ajuste predefinido y míralo al instante en la vista previa.</string>
|
||||
<string name="appearance_preset_gallery">Galería de ajustes</string>
|
||||
<string name="appearance_preview_relay">Vista previa · Relay</string>
|
||||
<string name="appearance_preview_user_message">Dame tres consejos rápidos para una mañana productiva.</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. Elige un logro real antes de revisar tus novedades.\n2. Reserva los primeros 45–90 minutos.\n3. Empieza con un ritual de preparación, no con «motivación».</string>
|
||||
<string name="appearance_preview_time">19:00</string>
|
||||
<string name="appearance_preview_voice">Voz</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 tokens · 137,2K</string>
|
||||
<string name="appearance_preview_message_placeholder">Mensaje…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / perfil: predeterminado</string>
|
||||
<string name="appearance_preview_live_note">Esta vista previa se actualiza al instante con el ajuste, modo, fuente y aspecto de Sphere.</string>
|
||||
<string name="appearance_customize_theme">Personalizar %1$s</string>
|
||||
<string name="appearance_accent_preset">Color de acento predefinido</string>
|
||||
<string name="appearance_accent_custom">Color de acento personalizado aplicado</string>
|
||||
<string name="appearance_accent_preview_only">Los cambios permanecen en la vista previa hasta que los apliques.</string>
|
||||
<string name="appearance_accent_preview_only_short">Solo vista previa</string>
|
||||
<string name="appearance_apply_changes">Aplicar cambios</string>
|
||||
<string name="appearance_customize_summary">Acento, superficies, forma y densidad</string>
|
||||
<string name="appearance_shape">Forma</string>
|
||||
<string name="appearance_shape_soft">Suave</string>
|
||||
<string name="appearance_shape_balanced">Equilibrada</string>
|
||||
<string name="appearance_shape_sharp">Angular</string>
|
||||
<string name="appearance_contrast_passes">El contraste es suficiente</string>
|
||||
<string name="appearance_contrast_fails">El contraste necesita mejoras</string>
|
||||
<string name="appearance_contrast_aa">AA para texto normal</string>
|
||||
<string name="appearance_typography_density">Tipografía y densidad</string>
|
||||
<string name="appearance_readability">Legibilidad</string>
|
||||
<string name="appearance_default">Predeterminado</string>
|
||||
<string name="appearance_font_normal_summary">Tamaño de fuente: Normal</string>
|
||||
<string name="appearance_reset_draft">Restablecer borrador</string>
|
||||
<string name="appearance_accent">Color de acento</string>
|
||||
<string name="appearance_contrast_status">Contraste legible · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">La tipografía y la densidad usan los controles específicos de Fuente y Tamaño de fuente de abajo.</string>
|
||||
<string name="appearance_readability_summary">Ajusta aquí la densidad del texto; elige la tipografía en la sección Fuente de abajo.</string>
|
||||
<string name="appearance_reset">Restablecer</string>
|
||||
<string name="appearance_apply">Aplicar</string>
|
||||
<string name="appearance_background_installed">Animaciones instaladas</string>
|
||||
<string name="appearance_import_background">Importar animación de fondo</string>
|
||||
<string name="appearance_import_background_desc">Importa el mismo ZIP seguro de mascota de Relay o formato de imagen única, pero lo usa solo para la visualización central o de fondo. No activa el movimiento ni cambia tu mascota flotante.</string>
|
||||
<string name="appearance_import_sphere">Importar aspecto de Sphere</string>
|
||||
<string name="appearance_create_pet">Crear una mascota personalizada</string>
|
||||
<string name="pet_creator_title">Crear una mascota personalizada</string>
|
||||
<string name="pet_creator_intro">Describe a tu acompañante, revisa las instrucciones generadas y elige dónde crearlo. No se envía nada hasta que tú mismo envíes el nuevo chat.</string>
|
||||
<string name="pet_creator_step_idea">Elegir la idea</string>
|
||||
<string name="pet_creator_name">Nombre de la mascota</string>
|
||||
<string name="pet_creator_description">Dirección del personaje</string>
|
||||
<string name="pet_creator_description_hint">Describe el personaje, materiales, colores, ambiente y cualquier imagen de referencia que quieras adjuntar.</string>
|
||||
<string name="pet_creator_animated">Paquete animado</string>
|
||||
<string name="pet_creator_static">Imagen estática</string>
|
||||
<string name="pet_creator_step_create">Revisar y crear</string>
|
||||
<string name="pet_creator_review_copy">Estas instrucciones completas incluyen el formato actual de mascotas y los límites de validación, privacidad y revisión.</string>
|
||||
<string name="pet_creator_copy">Copiar</string>
|
||||
<string name="pet_creator_copied">Instrucciones copiadas</string>
|
||||
<string name="pet_creator_new_chat">Nuevo chat</string>
|
||||
<string name="pet_creator_step_review">Revisar e importar</string>
|
||||
<string name="pet_creator_review_desc">Inspecciona primero la imagen o el ZIP recibido. Al importar se copian los archivos validados al almacenamiento de la aplicación; no se publican.</string>
|
||||
<string name="pet_creator_import">Importar mascota terminada</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">%1$sをプレビュー</string>
|
||||
<string name="pending_attachment_remove">%1$sを削除</string>
|
||||
<string name="pending_attachment_move_left">%1$sを左へ移動</string>
|
||||
<string name="pending_attachment_move_right">%1$sを右へ移動</string>
|
||||
<string name="pending_attachment_status_loading">プレビューを準備中</string>
|
||||
<string name="pending_attachment_status_ready">準備完了</string>
|
||||
<string name="pending_attachment_status_failed">プレビューできません</string>
|
||||
</resources>
|
||||
@@ -736,6 +736,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">最近のメッセージをコンポーザーの上にタップ可能なチップとして表示し、再送信します。デフォルトではオフです。</string>
|
||||
<string name="chat_settings_keep_keyboard_open">送信時にキーボードを開いたままにする</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">送信後はコンポーザー内に留まります。メッセージを送信するたびにキーボードを閉じるには、オフにします。</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">物理キーボードの Enter キー</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Enter で送信するか改行するかを選択します。Ctrl+Enter は常に送信します。</string>
|
||||
<string name="chat_settings_insert_newline">改行を挿入</string>
|
||||
<string name="chat_settings_notify_when_finishes">バックグラウンドのチャット通知</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">バックグラウンドで Hermes が入力を必要としたとき、または完了したときに通知します</string>
|
||||
<string name="chat_settings_share_phone_status">電話のステータスをエージェントと共有する</string>
|
||||
@@ -2568,6 +2571,23 @@
|
||||
<string name="image_generation_rendering">画像を生成中</string>
|
||||
<string name="tool_progress_cd_collapse">崩壊</string>
|
||||
<string name="tool_progress_cd_expand">拡大する</string>
|
||||
<string name="tool_progress_state_expanded">展開済み</string>
|
||||
<string name="tool_progress_state_collapsed">折りたたみ済み</string>
|
||||
<string name="tool_run_preparing">%1$s を準備中</string>
|
||||
<string name="tool_run_running">%1$s を実行中</string>
|
||||
<string name="tool_run_finished">%1$s が完了</string>
|
||||
<plurals name="tool_run_reading"><item quantity="other">%d 件を読み取り中</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="other">%d 件を読み取り</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="other">%d 件のソースを検索中</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="other">%d 件のソースを検索</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="other">%d 件のコマンドを実行中</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="other">%d 件のコマンドを実行</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="other">%d 件のブラウザー操作を実行中</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="other">%d 件のブラウザー操作を実行</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="other">%d 件のデバイス操作を実行中</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="other">%d 件のデバイス操作を実行</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="other">%d 個のツールを使用中</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="other">%d 個のツールを使用</item></plurals>
|
||||
|
||||
<!-- AgentIconRow -->
|
||||
<string name="agent_icon_title">エージェントアイコン</string>
|
||||
@@ -3642,6 +3662,7 @@
|
||||
<string name="tool_name_android">電話アクション</string>
|
||||
<string name="timeline_no_checks">チェックなし</string>
|
||||
<string name="thinking_title">思考プロセス</string>
|
||||
<string name="thinking_settled">思考</string>
|
||||
<string name="thinking_thinking_short">考え中</string>
|
||||
<string name="thinking_thinking">考え中…</string>
|
||||
<string name="task_status_working">作業中</string>
|
||||
@@ -3767,6 +3788,7 @@
|
||||
<string name="voice_overlay_attachment_ready">添付ファイルの準備ができました</string>
|
||||
<string name="conn_info_active_profile">アクティブなプロフィール</string>
|
||||
<string name="msg_bubble_speak_response">応答を読み上げる</string>
|
||||
<string name="msg_bubble_stop_speaking">読み上げを停止</string>
|
||||
<string name="voice_overlay_engine_standard">標準モード</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Hermes を開く</string>
|
||||
@@ -3885,4 +3907,81 @@
|
||||
<string name="support_bundle_copied">サポート情報をコピーしました</string>
|
||||
<string name="support_bundle_no_share">サポート情報をコピーしました — 共有できるアプリがありません</string>
|
||||
<string name="support_bundle_share_title">Hermes-Relay サポート情報を共有</string>
|
||||
<string name="chat_search_conversation">会話を検索</string>
|
||||
<string name="chat_search_close">検索を閉じる</string>
|
||||
<string name="chat_search_no_results">結果なし</string>
|
||||
<string name="chat_search_result_count">%1$d / %2$d</string>
|
||||
<string name="msg_bubble_queued">キュー済み</string>
|
||||
<string name="msg_bubble_steered">修正を送信しました</string>
|
||||
<string name="chat_quote_you">あなた</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">%1$s の元のメッセージを開く</string>
|
||||
<string name="chat_quote_remove">引用を削除</string>
|
||||
<string name="profile_shelf_switch_agent">エージェントを切り替え</string>
|
||||
<string name="profile_shelf_all_profiles">すべてのエージェントプロフィールを開く</string>
|
||||
<string name="profile_shelf_open_passport">エージェントパスポートを開く</string>
|
||||
<string name="profile_shelf_switch_to">このエージェントに切り替え</string>
|
||||
<string name="profile_shelf_locked_hint">プロフィールの切り替えはロックされています。解除するには、使用中のエージェントを長押ししてください。</string>
|
||||
<string name="profile_shelf_inspect">プロフィールを確認</string>
|
||||
<string name="profile_shelf_hide">プロフィールシェルフに表示しない</string>
|
||||
<string name="profile_shelf_expand">プロフィールシェルフを展開</string>
|
||||
<string name="profile_shelf_collapse">プロフィールシェルフを折りたたむ</string>
|
||||
<string name="appearance_intro">プリセットを選ぶと、プレビューですぐに確認できます。</string>
|
||||
<string name="appearance_preset_gallery">プリセットギャラリー</string>
|
||||
<string name="appearance_preview_relay">プレビュー · Relay</string>
|
||||
<string name="appearance_preview_user_message">集中できる朝のための簡単なヒントを3つ教えて。</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. フィードを見る前に、確実に達成することを1つ決めます。\n2. 最初の45〜90分を確保します。\n3. 「やる気」ではなく準備の習慣から始めます。</string>
|
||||
<string name="appearance_preview_time">19:00</string>
|
||||
<string name="appearance_preview_voice">音声</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206トークン · 137.2K</string>
|
||||
<string name="appearance_preview_message_placeholder">メッセージ…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / プロファイル: デフォルト</string>
|
||||
<string name="appearance_preview_live_note">このプレビューには、プリセット、モード、フォント、Sphereスキンの変更がすぐに反映されます。</string>
|
||||
<string name="appearance_customize_theme">%1$sをカスタマイズ</string>
|
||||
<string name="appearance_accent_preset">プリセットのアクセント</string>
|
||||
<string name="appearance_accent_custom">カスタムアクセントを適用済み</string>
|
||||
<string name="appearance_accent_preview_only">適用するまで変更はプレビュー内だけに反映されます。</string>
|
||||
<string name="appearance_accent_preview_only_short">プレビューのみ</string>
|
||||
<string name="appearance_apply_changes">変更を適用</string>
|
||||
<string name="appearance_customize_summary">アクセント、サーフェス、形状、密度</string>
|
||||
<string name="appearance_shape">形状</string>
|
||||
<string name="appearance_shape_soft">ソフト</string>
|
||||
<string name="appearance_shape_balanced">バランス</string>
|
||||
<string name="appearance_shape_sharp">シャープ</string>
|
||||
<string name="appearance_contrast_passes">コントラスト基準を満たしています</string>
|
||||
<string name="appearance_contrast_fails">コントラストの改善が必要です</string>
|
||||
<string name="appearance_contrast_aa">通常テキストのAA基準</string>
|
||||
<string name="appearance_typography_density">文字と密度</string>
|
||||
<string name="appearance_readability">読みやすさ</string>
|
||||
<string name="appearance_default">デフォルト</string>
|
||||
<string name="appearance_font_normal_summary">フォントサイズ: 標準</string>
|
||||
<string name="appearance_reset_draft">下書きをリセット</string>
|
||||
<string name="appearance_accent">アクセントカラー</string>
|
||||
<string name="appearance_contrast_status">読みやすいコントラスト · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">文字と密度には、下にあるフォントとフォントサイズの専用設定が使用されます。</string>
|
||||
<string name="appearance_readability_summary">ここで文字の密度を調整し、下のフォントセクションで書体を選択します。</string>
|
||||
<string name="appearance_reset">リセット</string>
|
||||
<string name="appearance_apply">適用</string>
|
||||
<string name="appearance_background_installed">インストール済みアニメーション</string>
|
||||
<string name="appearance_import_background">背景アニメーションをインポート</string>
|
||||
<string name="appearance_import_background_desc">安全なRelayペットZIPまたは単一画像と同じ形式を読み込み、中央または背景の表示だけに使用します。移動は有効にならず、フローティングペットも変更されません。</string>
|
||||
<string name="appearance_import_sphere">Sphereスキンをインポート</string>
|
||||
<string name="appearance_create_pet">カスタムペットを作成</string>
|
||||
<string name="pet_creator_title">カスタムペットを作成</string>
|
||||
<string name="pet_creator_intro">コンパニオンを説明し、生成された手順を確認してから作成場所を選びます。新しいチャットを自分で送信するまで何も送られません。</string>
|
||||
<string name="pet_creator_step_idea">アイデアを選ぶ</string>
|
||||
<string name="pet_creator_name">ペットの名前</string>
|
||||
<string name="pet_creator_description">キャラクターの方向性</string>
|
||||
<string name="pet_creator_description_hint">キャラクター、素材、色、雰囲気、添付予定の参照画像について説明します。</string>
|
||||
<string name="pet_creator_animated">アニメーションパック</string>
|
||||
<string name="pet_creator_static">静止画像</string>
|
||||
<string name="pet_creator_step_create">確認して作成</string>
|
||||
<string name="pet_creator_review_copy">この完全な手順には、現在のペット形式、検証、プライバシー、確認の境界が含まれています。</string>
|
||||
<string name="pet_creator_copy">コピー</string>
|
||||
<string name="pet_creator_copied">手順をコピーしました</string>
|
||||
<string name="pet_creator_new_chat">新しいチャット</string>
|
||||
<string name="pet_creator_step_review">確認してインポート</string>
|
||||
<string name="pet_creator_review_desc">返された画像またはZIPを最初に確認してください。インポートすると検証済みファイルがアプリ専用ストレージにコピーされますが、公開はされません。</string>
|
||||
<string name="pet_creator_import">完成したペットをインポート</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">Предпросмотр: %1$s</string>
|
||||
<string name="pending_attachment_remove">Удалить %1$s</string>
|
||||
<string name="pending_attachment_move_left">Переместить %1$s влево</string>
|
||||
<string name="pending_attachment_move_right">Переместить %1$s вправо</string>
|
||||
<string name="pending_attachment_status_loading">Подготовка предпросмотра</string>
|
||||
<string name="pending_attachment_status_ready">Готово</string>
|
||||
<string name="pending_attachment_status_failed">Предпросмотр недоступен</string>
|
||||
</resources>
|
||||
@@ -704,6 +704,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">Показывать ваши недавние сообщения как нажимаемые чипы над композитором, чтобы отправить их снова. По умолчанию выключено.</string>
|
||||
<string name="chat_settings_keep_keyboard_open">Оставить клавиатуру открытой при отправке</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Оставаться в композиторе после отправки. Выключите, чтобы скрыть клавиатуру после каждого отправленного сообщения.</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Клавиша Enter на физической клавиатуре</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Выберите, отправляет ли Enter сообщение или добавляет новую строку. Ctrl+Enter всегда отправляет.</string>
|
||||
<string name="chat_settings_insert_newline">Вставить новую строку</string>
|
||||
<string name="chat_settings_notify_when_finishes">Уведомления о фоновом чате</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Уведомлять, когда Гермес требует ввода или заканчивает работу, когда приложение находится в фоновом режиме</string>
|
||||
<string name="chat_settings_share_phone_status">Поделиться статусом телефона с агентом</string>
|
||||
@@ -2533,6 +2536,23 @@
|
||||
<string name="image_generation_rendering">Рендеринг изображения</string>
|
||||
<string name="tool_progress_cd_collapse">Свернуть</string>
|
||||
<string name="tool_progress_cd_expand">Развернуть</string>
|
||||
<string name="tool_progress_state_expanded">Развернуто</string>
|
||||
<string name="tool_progress_state_collapsed">Свернуто</string>
|
||||
<string name="tool_run_preparing">Подготовка: %1$s</string>
|
||||
<string name="tool_run_running">Выполняется: %1$s</string>
|
||||
<string name="tool_run_finished">Завершено: %1$s</string>
|
||||
<plurals name="tool_run_reading"><item quantity="one">Чтение %d элемента</item><item quantity="few">Чтение %d элементов</item><item quantity="many">Чтение %d элементов</item><item quantity="other">Чтение %d элементов</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="one">Прочитан %d элемент</item><item quantity="few">Прочитано %d элемента</item><item quantity="many">Прочитано %d элементов</item><item quantity="other">Прочитано %d элементов</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="one">Поиск в %d источнике</item><item quantity="few">Поиск в %d источниках</item><item quantity="many">Поиск в %d источниках</item><item quantity="other">Поиск в %d источниках</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="one">Выполнен поиск в %d источнике</item><item quantity="few">Выполнен поиск в %d источниках</item><item quantity="many">Выполнен поиск в %d источниках</item><item quantity="other">Выполнен поиск в %d источниках</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="one">Выполняется %d команда</item><item quantity="few">Выполняется %d команды</item><item quantity="many">Выполняется %d команд</item><item quantity="other">Выполняется %d команд</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="one">Выполнена %d команда</item><item quantity="few">Выполнено %d команды</item><item quantity="many">Выполнено %d команд</item><item quantity="other">Выполнено %d команд</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="one">Выполняется %d действие браузера</item><item quantity="few">Выполняется %d действия браузера</item><item quantity="many">Выполняется %d действий браузера</item><item quantity="other">Выполняется %d действий браузера</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="one">Выполнено %d действие браузера</item><item quantity="few">Выполнено %d действия браузера</item><item quantity="many">Выполнено %d действий браузера</item><item quantity="other">Выполнено %d действий браузера</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="one">Выполняется %d действие устройства</item><item quantity="few">Выполняется %d действия устройства</item><item quantity="many">Выполняется %d действий устройства</item><item quantity="other">Выполняется %d действий устройства</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="one">Выполнено %d действие устройства</item><item quantity="few">Выполнено %d действия устройства</item><item quantity="many">Выполнено %d действий устройства</item><item quantity="other">Выполнено %d действий устройства</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="one">Используется %d инструмент</item><item quantity="few">Используется %d инструмента</item><item quantity="many">Используется %d инструментов</item><item quantity="other">Используется %d инструментов</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="one">Использован %d инструмент</item><item quantity="few">Использовано %d инструмента</item><item quantity="many">Использовано %d инструментов</item><item quantity="other">Использовано %d инструментов</item></plurals>
|
||||
<string name="agent_icon_title">Иконка агента</string>
|
||||
<string name="agent_icon_set">Выбрать файл</string>
|
||||
<string name="agent_icon_change">Выбрать файл</string>
|
||||
@@ -3263,6 +3283,7 @@
|
||||
</plurals>
|
||||
<string name="tool_preparing">Подготовка инструмента…</string>
|
||||
<string name="thinking_title">Ход мыслей</string>
|
||||
<string name="thinking_settled">Мысль</string>
|
||||
<string name="thinking_thinking">Обдумывает...</string>
|
||||
<string name="thinking_thinking_short">Обдумывает</string>
|
||||
<string name="task_background_prefix">Фоновая задача, </string>
|
||||
@@ -3491,6 +3512,7 @@
|
||||
<string name="voice_overlay_attachment_ready">Вложение готово</string>
|
||||
<string name="conn_info_active_profile">Активный профиль</string>
|
||||
<string name="msg_bubble_speak_response">Озвучить ответ</string>
|
||||
<string name="msg_bubble_stop_speaking">Остановить озвучивание</string>
|
||||
<string name="voice_overlay_engine_standard">Стандартный режим</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Открыть Hermes</string>
|
||||
@@ -3607,4 +3629,81 @@
|
||||
<string name="support_bundle_copied">Сведения для поддержки скопированы</string>
|
||||
<string name="support_bundle_no_share">Сведения для поддержки скопированы — приложение для отправки не найдено</string>
|
||||
<string name="support_bundle_share_title">Поделиться сведениями поддержки Hermes-Relay</string>
|
||||
<string name="chat_search_conversation">Поиск по беседе</string>
|
||||
<string name="chat_search_close">Закрыть поиск</string>
|
||||
<string name="chat_search_no_results">Ничего не найдено</string>
|
||||
<string name="chat_search_result_count">%1$d из %2$d</string>
|
||||
<string name="msg_bubble_queued">В очереди</string>
|
||||
<string name="msg_bubble_steered">Исправление отправлено</string>
|
||||
<string name="chat_quote_you">Вы</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">Открыть исходное сообщение от %1$s</string>
|
||||
<string name="chat_quote_remove">Убрать цитату</string>
|
||||
<string name="profile_shelf_switch_agent">Сменить агента</string>
|
||||
<string name="profile_shelf_all_profiles">Открыть все профили агентов</string>
|
||||
<string name="profile_shelf_open_passport">Открыть паспорт агента</string>
|
||||
<string name="profile_shelf_switch_to">Переключиться на этого агента</string>
|
||||
<string name="profile_shelf_locked_hint">Переключение профилей заблокировано. Нажмите и удерживайте активного агента, чтобы снять блокировку.</string>
|
||||
<string name="profile_shelf_inspect">Просмотреть профиль</string>
|
||||
<string name="profile_shelf_hide">Скрыть с полки профилей</string>
|
||||
<string name="profile_shelf_expand">Развернуть полку профилей</string>
|
||||
<string name="profile_shelf_collapse">Свернуть полку профилей</string>
|
||||
<string name="appearance_intro">Выберите шаблон и сразу посмотрите результат.</string>
|
||||
<string name="appearance_preset_gallery">Галерея шаблонов</string>
|
||||
<string name="appearance_preview_relay">Предпросмотр · Relay</string>
|
||||
<string name="appearance_preview_user_message">Дай три коротких совета для продуктивного утра.</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. Выберите одну реальную цель до просмотра ленты.\n2. Выделите первые 45–90 минут.\n3. Начните с ритуала подготовки, а не с «мотивации».</string>
|
||||
<string name="appearance_preview_time">19:00</string>
|
||||
<string name="appearance_preview_voice">Голос</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 токенов · 137,2 тыс.</string>
|
||||
<string name="appearance_preview_message_placeholder">Сообщение…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / профиль: по умолчанию</string>
|
||||
<string name="appearance_preview_live_note">Предпросмотр сразу обновляется при изменении шаблона, режима, шрифта и оформления Sphere.</string>
|
||||
<string name="appearance_customize_theme">Настроить %1$s</string>
|
||||
<string name="appearance_accent_preset">Предустановленный акцент</string>
|
||||
<string name="appearance_accent_custom">Пользовательский акцент применён</string>
|
||||
<string name="appearance_accent_preview_only">Изменения остаются в предпросмотре, пока вы их не примените.</string>
|
||||
<string name="appearance_accent_preview_only_short">Только предпросмотр</string>
|
||||
<string name="appearance_apply_changes">Применить изменения</string>
|
||||
<string name="appearance_customize_summary">Акцент, поверхности, форма и плотность</string>
|
||||
<string name="appearance_shape">Форма</string>
|
||||
<string name="appearance_shape_soft">Мягкая</string>
|
||||
<string name="appearance_shape_balanced">Сбалансированная</string>
|
||||
<string name="appearance_shape_sharp">Угловатая</string>
|
||||
<string name="appearance_contrast_passes">Контраст достаточный</string>
|
||||
<string name="appearance_contrast_fails">Контраст нужно улучшить</string>
|
||||
<string name="appearance_contrast_aa">AA для обычного текста</string>
|
||||
<string name="appearance_typography_density">Типографика и плотность</string>
|
||||
<string name="appearance_readability">Читаемость</string>
|
||||
<string name="appearance_default">По умолчанию</string>
|
||||
<string name="appearance_font_normal_summary">Размер шрифта: обычный</string>
|
||||
<string name="appearance_reset_draft">Сбросить черновик</string>
|
||||
<string name="appearance_accent">Цвет акцента</string>
|
||||
<string name="appearance_contrast_status">Читаемый контраст · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">Типографика и плотность используют отдельные настройки шрифта и его размера ниже.</string>
|
||||
<string name="appearance_readability_summary">Настройте здесь плотность текста, а гарнитуру выберите в разделе «Шрифт» ниже.</string>
|
||||
<string name="appearance_reset">Сбросить</string>
|
||||
<string name="appearance_apply">Применить</string>
|
||||
<string name="appearance_background_installed">Установленные анимации</string>
|
||||
<string name="appearance_import_background">Импортировать фоновую анимацию</string>
|
||||
<string name="appearance_import_background_desc">Импортирует тот же безопасный ZIP питомца Relay или одно изображение, но использует его только для центральной или фоновой визуализации. Это не включает перемещение и не меняет плавающего питомца.</string>
|
||||
<string name="appearance_import_sphere">Импортировать оформление Sphere</string>
|
||||
<string name="appearance_create_pet">Создать своего питомца</string>
|
||||
<string name="pet_creator_title">Создать своего питомца</string>
|
||||
<string name="pet_creator_intro">Опишите спутника, проверьте созданные инструкции и выберите, где его создать. Ничего не отправляется, пока вы сами не отправите новый чат.</string>
|
||||
<string name="pet_creator_step_idea">Выбрать идею</string>
|
||||
<string name="pet_creator_name">Имя питомца</string>
|
||||
<string name="pet_creator_description">Образ персонажа</string>
|
||||
<string name="pet_creator_description_hint">Опишите персонажа, материалы, цвета, настроение и изображения-образцы, которые планируете прикрепить.</string>
|
||||
<string name="pet_creator_animated">Анимированный пакет</string>
|
||||
<string name="pet_creator_static">Статичное изображение</string>
|
||||
<string name="pet_creator_step_create">Проверить и создать</string>
|
||||
<string name="pet_creator_review_copy">Эти полные инструкции включают текущий формат питомца, проверку, конфиденциальность и границы проверки.</string>
|
||||
<string name="pet_creator_copy">Копировать</string>
|
||||
<string name="pet_creator_copied">Инструкции скопированы</string>
|
||||
<string name="pet_creator_new_chat">Новый чат</string>
|
||||
<string name="pet_creator_step_review">Проверить и импортировать</string>
|
||||
<string name="pet_creator_review_desc">Сначала проверьте полученное изображение или ZIP. При импорте проверенные файлы копируются в хранилище приложения и не публикуются.</string>
|
||||
<string name="pet_creator_import">Импортировать готового питомца</string>
|
||||
</resources>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="pending_attachment_preview_named">Preview %1$s</string>
|
||||
<string name="pending_attachment_remove">Remove %1$s</string>
|
||||
<string name="pending_attachment_move_left">Move %1$s left</string>
|
||||
<string name="pending_attachment_move_right">Move %1$s right</string>
|
||||
<string name="pending_attachment_status_loading">Preparing preview</string>
|
||||
<string name="pending_attachment_status_ready">Ready</string>
|
||||
<string name="pending_attachment_status_failed">Preview unavailable</string>
|
||||
</resources>
|
||||
@@ -133,6 +133,10 @@
|
||||
|
||||
<!-- Chat screen UI chrome -->
|
||||
<string name="chat_share_conversation">Share conversation</string>
|
||||
<string name="chat_search_conversation">Search conversation</string>
|
||||
<string name="chat_search_close">Close search</string>
|
||||
<string name="chat_search_no_results">No results</string>
|
||||
<string name="chat_search_result_count">%1$d of %2$d</string>
|
||||
<string name="chat_retry">Retry</string>
|
||||
<string name="chat_dismiss">Dismiss</string>
|
||||
<string name="chat_open_settings">Open Settings</string>
|
||||
@@ -755,6 +759,9 @@
|
||||
<string name="chat_settings_recent_prompt_chips_desc">Show your recent messages as tappable chips above the composer to send them again. Off by default.</string>
|
||||
<string name="chat_settings_keep_keyboard_open">Keep keyboard open on send</string>
|
||||
<string name="chat_settings_keep_keyboard_open_desc">Stay in the composer after sending. Turn off to dismiss the keyboard after each sent message.</string>
|
||||
<string name="chat_settings_physical_keyboard_enter">Physical keyboard Enter key</string>
|
||||
<string name="chat_settings_physical_keyboard_enter_desc">Choose whether Enter sends or inserts a new line. Ctrl+Enter always sends.</string>
|
||||
<string name="chat_settings_insert_newline">Insert new line</string>
|
||||
<string name="chat_settings_notify_when_finishes">Background chat alerts</string>
|
||||
<string name="chat_settings_notify_when_finishes_desc">Notify when Hermes needs input or finishes while the app is in the background</string>
|
||||
<string name="chat_settings_share_phone_status">Share phone status with agent</string>
|
||||
@@ -1233,6 +1240,18 @@
|
||||
|
||||
<!-- P1: AppearanceSettingsScreen -->
|
||||
<string name="appearance_title">Appearance</string>
|
||||
<string name="appearance_intro">Pick a preset. See it live in the preview.</string>
|
||||
<string name="appearance_preset_gallery">Preset gallery</string>
|
||||
<string name="appearance_preview_relay">Preview · Relay</string>
|
||||
<string name="appearance_preview_user_message">Give me three quick tips for a focused morning.</string>
|
||||
<string name="appearance_preview_agent">Hermes</string>
|
||||
<string name="appearance_preview_agent_message">1. Pick one real win before checking feeds.\n2. Block the first 45–90 minutes.\n3. Start with a setup ritual, not “motivation.”</string>
|
||||
<string name="appearance_preview_time">7:00 PM</string>
|
||||
<string name="appearance_preview_voice">Voice</string>
|
||||
<string name="appearance_preview_tool_meta">tool_executor · 206 tokens · 137.2K</string>
|
||||
<string name="appearance_preview_message_placeholder">Message…</string>
|
||||
<string name="appearance_preview_gateway">Gateway · LAN · gpt-5.5 / profile: default</string>
|
||||
<string name="appearance_preview_live_note">This preview updates immediately with your preset, mode, font, and sphere skin.</string>
|
||||
<string name="appearance_back">Back</string>
|
||||
<string name="appearance_remove_pet_title">Remove pet?</string>
|
||||
<string name="appearance_remove_pet_body">Remove \"%1$s\"? You can re-import it later.</string>
|
||||
@@ -1252,6 +1271,31 @@
|
||||
<string name="appearance_language_russian">Русский</string>
|
||||
<string name="appearance_appearance">Appearance</string>
|
||||
<string name="appearance_light_dark">Light / Dark</string>
|
||||
<string name="appearance_customize_theme">Customize %1$s</string>
|
||||
<string name="appearance_accent_preset">Preset accent</string>
|
||||
<string name="appearance_accent_custom">Custom accent applied</string>
|
||||
<string name="appearance_accent_preview_only">Changes stay in the preview until you apply them.</string>
|
||||
<string name="appearance_accent_preview_only_short">Preview only</string>
|
||||
<string name="appearance_apply_changes">Apply changes</string>
|
||||
<string name="appearance_customize_summary">Accent, surfaces, shape & density</string>
|
||||
<string name="appearance_shape">Shape</string>
|
||||
<string name="appearance_shape_soft">Soft</string>
|
||||
<string name="appearance_shape_balanced">Balanced</string>
|
||||
<string name="appearance_shape_sharp">Sharp</string>
|
||||
<string name="appearance_contrast_passes">Contrast passes</string>
|
||||
<string name="appearance_contrast_fails">Contrast needs work</string>
|
||||
<string name="appearance_contrast_aa">AA for normal text</string>
|
||||
<string name="appearance_typography_density">Typography & density</string>
|
||||
<string name="appearance_readability">Readability</string>
|
||||
<string name="appearance_default">Default</string>
|
||||
<string name="appearance_font_normal_summary">Font size: Normal</string>
|
||||
<string name="appearance_reset_draft">Reset draft</string>
|
||||
<string name="appearance_accent">Accent color</string>
|
||||
<string name="appearance_contrast_status">Readable contrast · %1$.1f:1</string>
|
||||
<string name="appearance_typography_density_summary">Typography and density use the focused Font and Font size controls below.</string>
|
||||
<string name="appearance_readability_summary">Tune text density here; choose the typeface in the focused Font section below.</string>
|
||||
<string name="appearance_reset">Reset</string>
|
||||
<string name="appearance_apply">Apply</string>
|
||||
<string name="appearance_fixed_light">%1$s is a fixed light theme.</string>
|
||||
<string name="appearance_fixed_dark">%1$s is a fixed dark theme. Switch to Hermes Relay for light/dark control.</string>
|
||||
<string name="appearance_font_size">Font size</string>
|
||||
@@ -1282,7 +1326,8 @@
|
||||
<string name="appearance_stabilize_desc">Auto-centers each frame so the pet doesn\'t drift or jump between frames (fixes wobbly AI sheets).</string>
|
||||
<string name="appearance_preview">Preview</string>
|
||||
<string name="appearance_sphere_skin">Sphere skin — choose the orb\'s look.</string>
|
||||
<string name="appearance_sphere_custom_desc">Add your own: drop a sphere JSON spec into the app\'s private spheres/ folder, then reopen this screen. See docs/sphere-spec.md for the format.</string>
|
||||
<string name="appearance_sphere_custom_desc">Import a declarative sphere JSON file. It stays on this device, is validated before use, and can never run code.</string>
|
||||
<string name="appearance_import_sphere">Import sphere skin</string>
|
||||
<string name="appearance_greet">Greet</string>
|
||||
<string name="appearance_done">Done</string>
|
||||
<string name="appearance_preview_tip">Tap a state to preview it; Greet/Done replay the one-shot reactions. Reflects the speed and stabilize settings above.</string>
|
||||
@@ -2407,6 +2452,15 @@
|
||||
<string name="conn_info_bypassed">Bypassed</string>
|
||||
<string name="conn_info_customize_identity">Customize identity</string>
|
||||
<string name="conn_info_agent_passport">Agent Passport</string>
|
||||
<string name="profile_shelf_switch_agent">Switch agent</string>
|
||||
<string name="profile_shelf_all_profiles">Open all agent profiles</string>
|
||||
<string name="profile_shelf_open_passport">Open Agent Passport</string>
|
||||
<string name="profile_shelf_switch_to">Switch to this agent</string>
|
||||
<string name="profile_shelf_locked_hint">Profile switching is locked. Long-press the active agent to unlock.</string>
|
||||
<string name="profile_shelf_inspect">Inspect profile</string>
|
||||
<string name="profile_shelf_hide">Hide from Profile Shelf</string>
|
||||
<string name="profile_shelf_expand">Expand Profile Shelf</string>
|
||||
<string name="profile_shelf_collapse">Collapse Profile Shelf</string>
|
||||
<string name="conn_info_chat_override">Chat override</string>
|
||||
<string name="conn_info_chat_override_inherited_desc">Use the profile approval policy for this chat.</string>
|
||||
<string name="conn_info_fast_tier">Fast tier</string>
|
||||
@@ -2690,6 +2744,23 @@
|
||||
<string name="image_generation_rendering">Rendering image</string>
|
||||
<string name="tool_progress_cd_collapse">Collapse</string>
|
||||
<string name="tool_progress_cd_expand">Expand</string>
|
||||
<string name="tool_progress_state_expanded">Expanded</string>
|
||||
<string name="tool_progress_state_collapsed">Collapsed</string>
|
||||
<string name="tool_run_preparing">Preparing %1$s</string>
|
||||
<string name="tool_run_running">Running %1$s</string>
|
||||
<string name="tool_run_finished">Finished %1$s</string>
|
||||
<plurals name="tool_run_reading"><item quantity="one">Reading %d item</item><item quantity="other">Reading %d items</item></plurals>
|
||||
<plurals name="tool_run_read"><item quantity="one">Read %d item</item><item quantity="other">Read %d items</item></plurals>
|
||||
<plurals name="tool_run_searching"><item quantity="one">Searching %d source</item><item quantity="other">Searching %d sources</item></plurals>
|
||||
<plurals name="tool_run_searched"><item quantity="one">Searched %d source</item><item quantity="other">Searched %d sources</item></plurals>
|
||||
<plurals name="tool_run_running_commands"><item quantity="one">Running %d command</item><item quantity="other">Running %d commands</item></plurals>
|
||||
<plurals name="tool_run_ran_commands"><item quantity="one">Ran %d command</item><item quantity="other">Ran %d commands</item></plurals>
|
||||
<plurals name="tool_run_browsing"><item quantity="one">Running %d browser action</item><item quantity="other">Running %d browser actions</item></plurals>
|
||||
<plurals name="tool_run_browsed"><item quantity="one">Ran %d browser action</item><item quantity="other">Ran %d browser actions</item></plurals>
|
||||
<plurals name="tool_run_using_device"><item quantity="one">Running %d device action</item><item quantity="other">Running %d device actions</item></plurals>
|
||||
<plurals name="tool_run_used_device"><item quantity="one">Ran %d device action</item><item quantity="other">Ran %d device actions</item></plurals>
|
||||
<plurals name="tool_run_using_tools"><item quantity="one">Using %d tool</item><item quantity="other">Using %d tools</item></plurals>
|
||||
<plurals name="tool_run_used_tools"><item quantity="one">Used %d tool</item><item quantity="other">Used %d tools</item></plurals>
|
||||
|
||||
<!-- AgentIconRow -->
|
||||
<string name="agent_icon_title">Agent icon</string>
|
||||
@@ -2896,6 +2967,12 @@
|
||||
<string name="msg_bubble_reconnecting">Reconnecting to your answer…</string>
|
||||
<string name="msg_bubble_still_working">Still working…</string>
|
||||
<string name="msg_bubble_sending">Sending…</string>
|
||||
<string name="msg_bubble_queued">Queued</string>
|
||||
<string name="msg_bubble_steered">Correction sent</string>
|
||||
<string name="chat_quote_you">You</string>
|
||||
<string name="chat_quote_hermes">Hermes</string>
|
||||
<string name="chat_quote_open">Open original message from %1$s</string>
|
||||
<string name="chat_quote_remove">Remove quote</string>
|
||||
<string name="msg_bubble_delivered">Delivered</string>
|
||||
<string name="msg_bubble_not_sent">Not sent</string>
|
||||
|
||||
@@ -3550,6 +3627,7 @@
|
||||
</plurals>
|
||||
<string name="tool_preparing">Preparing tool…</string>
|
||||
<string name="thinking_title">Thought process</string>
|
||||
<string name="thinking_settled">Thought</string>
|
||||
<string name="thinking_thinking">Thinking...</string>
|
||||
<string name="thinking_thinking_short">Thinking</string>
|
||||
<string name="task_background_prefix">Background task, </string>
|
||||
@@ -3692,9 +3770,12 @@
|
||||
<string name="chat_copy_session_id">Copy session ID</string>
|
||||
<string name="voice_no_speech_try_again">I didn’t catch that. Tap the mic and try again.</string>
|
||||
<string name="appearance_background_visualization">Background visualization</string>
|
||||
<string name="appearance_background_visualization_desc">Choose the ambient visualization behind chat. This is separate from your floating pet.</string>
|
||||
<string name="appearance_background_visualization_desc">Choose the central animation used in chat, clean mode, ambient mode, and voice. This is separate from your floating pet.</string>
|
||||
<string name="appearance_background_off">Off</string>
|
||||
<string name="appearance_background_sphere">Sphere</string>
|
||||
<string name="appearance_background_installed">Installed animations</string>
|
||||
<string name="appearance_import_background">Import background animation</string>
|
||||
<string name="appearance_import_background_desc">Imports the same safe Relay pet ZIP or single-image format, but uses it only for the central/background visualization. It does not enable roaming or change your floating pet.</string>
|
||||
<string name="appearance_floating_pet">Floating pet</string>
|
||||
<string name="appearance_floating_pet_desc">Choose a companion that floats near the conversation. It does not replace the agent\'s profile avatar.</string>
|
||||
<string name="appearance_floating_pet_none">None</string>
|
||||
@@ -3725,6 +3806,23 @@
|
||||
<string name="floating_pet_state_speaking">Speaking</string>
|
||||
<string name="floating_pet_state_error">Error</string>
|
||||
<string name="appearance_browse_petdex">Browse Petdex</string>
|
||||
<string name="appearance_create_pet">Create a custom pet</string>
|
||||
<string name="pet_creator_title">Create a custom pet</string>
|
||||
<string name="pet_creator_intro">Describe your companion, review the generated instructions, then choose where to create it. Nothing is sent until you submit the new chat yourself.</string>
|
||||
<string name="pet_creator_step_idea">Choose the idea</string>
|
||||
<string name="pet_creator_name">Pet name</string>
|
||||
<string name="pet_creator_description">Character direction</string>
|
||||
<string name="pet_creator_description_hint">Describe the character, materials, colors, mood, and any reference image you plan to attach.</string>
|
||||
<string name="pet_creator_animated">Animated pack</string>
|
||||
<string name="pet_creator_static">Static image</string>
|
||||
<string name="pet_creator_step_create">Review and create</string>
|
||||
<string name="pet_creator_review_copy">These complete instructions include the current pet format, validation, privacy, and review boundaries.</string>
|
||||
<string name="pet_creator_copy">Copy</string>
|
||||
<string name="pet_creator_copied">Instructions copied</string>
|
||||
<string name="pet_creator_new_chat">New chat</string>
|
||||
<string name="pet_creator_step_review">Review and import</string>
|
||||
<string name="pet_creator_review_desc">Inspect the returned image or ZIP first. Importing copies the validated files into app-scoped storage; it does not publish them.</string>
|
||||
<string name="pet_creator_import">Import finished pet</string>
|
||||
<string name="petdex_title">Browse Petdex</string>
|
||||
<string name="petdex_description">Browse the public Petdex catalog. Catalog entries are cached briefly; pet files download only when you tap Install.</string>
|
||||
<string name="petdex_source_link">Open petdex.dev</string>
|
||||
@@ -3776,6 +3874,7 @@
|
||||
<string name="voice_overlay_attachment_ready">Attachment ready</string>
|
||||
<string name="conn_info_active_profile">Active profile</string>
|
||||
<string name="msg_bubble_speak_response">Speak response</string>
|
||||
<string name="msg_bubble_stop_speaking">Stop speaking</string>
|
||||
<string name="voice_overlay_engine_standard">Standard mode</string>
|
||||
<string name="voice_overlay_caption_hermes">Hermes</string>
|
||||
<string name="voice_overlay_open_hermes">Open Hermes</string>
|
||||
|
||||
@@ -238,17 +238,18 @@ class AgentDisplayTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun profileRequestName_normalizesDefaultAliasAndDropsBlankOrNull() {
|
||||
fun profileRequestName_keepsLiteralDefaultDistinctFromServerDefault() {
|
||||
assertNull(AgentDisplay.profileRequestName(null))
|
||||
assertNull(AgentDisplay.profileRequestName(" "))
|
||||
assertNull(AgentDisplay.profileRequestName(" default "))
|
||||
assertEquals("default", AgentDisplay.profileRequestName(" default "))
|
||||
assertNull(AgentDisplay.profileRequestName(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY))
|
||||
assertEquals("mizu", AgentDisplay.profileRequestName("mizu"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun effectiveSessionProfileName_resolvesServerDefaultWithoutOverridingExplicitPick() {
|
||||
assertEquals("victor", AgentDisplay.effectiveSessionProfileName(null, " victor "))
|
||||
assertEquals("victor", AgentDisplay.effectiveSessionProfileName("default", "victor"))
|
||||
assertEquals("default", AgentDisplay.effectiveSessionProfileName("default", "victor"))
|
||||
assertEquals("default", AgentDisplay.effectiveSessionProfileName(null, "default"))
|
||||
assertEquals("mizu", AgentDisplay.effectiveSessionProfileName("mizu", "victor"))
|
||||
assertNull(AgentDisplay.effectiveSessionProfileName(null, null))
|
||||
@@ -262,17 +263,18 @@ class AgentDisplayTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalizeSelection_collapsesSyntheticDefaultProfile() {
|
||||
assertNull(AgentDisplay.normalizeSelection(defaultProfile))
|
||||
fun normalizeSelection_keepsLiteralDefaultProfile() {
|
||||
assertEquals(defaultProfile, AgentDisplay.normalizeSelection(defaultProfile))
|
||||
assertEquals(mizu, AgentDisplay.normalizeSelection(mizu))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun profileContextKey_treatsDefaultAliasAsServerDefault() {
|
||||
fun profileContextKey_distinguishesLiteralDefaultFromServerDefault() {
|
||||
assertEquals(
|
||||
"conn::__server_default__",
|
||||
"conn::default",
|
||||
AgentDisplay.profileContextKey("conn", "default"),
|
||||
)
|
||||
assertEquals("conn::__server_default__", AgentDisplay.profileContextKey("conn", null))
|
||||
assertEquals("conn::mizu", AgentDisplay.profileContextKey("conn", "mizu"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChatComposerDraftStoreTest {
|
||||
private val store = InMemoryChatComposerDraftStore()
|
||||
|
||||
@Test
|
||||
fun draftsAreIsolatedByCompleteOwnerIdentity() {
|
||||
val original = key(connection = "connection-a", profile = "coder", session = "session-a")
|
||||
val otherConnection = original.copy(connectionId = "connection-b")
|
||||
val otherProfile = original.copy(profileId = "default")
|
||||
val otherSession = original.copy(sessionId = "session-b")
|
||||
val otherSlot = original.copy(draftId = "alternate")
|
||||
|
||||
store.save(original, ChatComposerDraft(text = "owned by original"))
|
||||
|
||||
assertEquals("owned by original", store.snapshot(original).text)
|
||||
listOf(otherConnection, otherProfile, otherSession, otherSlot).forEach { owner ->
|
||||
assertEquals(ChatComposerDraft(), store.snapshot(owner))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun preservesSelectionContextAndPendingAttachments() {
|
||||
val attachment = Attachment(
|
||||
contentType = "image/jpeg",
|
||||
content = "base64-payload",
|
||||
fileName = "portrait.jpg",
|
||||
fileSize = 42L,
|
||||
)
|
||||
val pendingAttachments = mutableListOf(attachment)
|
||||
val draft = ChatComposerDraft(
|
||||
text = "hello world",
|
||||
selectionStart = 2,
|
||||
selectionEnd = 7,
|
||||
context = ChatComposerDraftContext(
|
||||
quotedMessageId = "quoted-message",
|
||||
editingMessageId = "edited-message",
|
||||
),
|
||||
attachments = pendingAttachments,
|
||||
)
|
||||
|
||||
store.save(key(), draft)
|
||||
pendingAttachments.clear()
|
||||
|
||||
assertEquals("hello world", store.snapshot(key()).text)
|
||||
assertEquals(2, store.snapshot(key()).selectionStart)
|
||||
assertEquals(7, store.snapshot(key()).selectionEnd)
|
||||
assertEquals("quoted-message", store.snapshot(key()).context.quotedMessageId)
|
||||
assertEquals("edited-message", store.snapshot(key()).context.editingMessageId)
|
||||
assertEquals(listOf(attachment), store.snapshot(key()).attachments)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateUsesCurrentSessionDraftWithoutTouchingAnotherSession() {
|
||||
val first = key(session = "first")
|
||||
val second = key(session = "second")
|
||||
store.save(first, ChatComposerDraft(text = "one"))
|
||||
store.save(second, ChatComposerDraft(text = "two"))
|
||||
|
||||
store.update(first) { it.copy(text = "one updated", selectionStart = 3) }
|
||||
|
||||
assertEquals("one updated", store.snapshot(first).text)
|
||||
assertEquals(3, store.snapshot(first).selectionStart)
|
||||
assertEquals("two", store.snapshot(second).text)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidSelectionIsClampedAndOrderedWhenSaved() {
|
||||
store.save(
|
||||
key(),
|
||||
ChatComposerDraft(text = "hello", selectionStart = 99, selectionEnd = -4),
|
||||
)
|
||||
|
||||
assertEquals(0, store.snapshot(key()).selectionStart)
|
||||
assertEquals(5, store.snapshot(key()).selectionEnd)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blankContextIdsNormalizeAndEmptyDraftRemovesStoredState() = runBlocking {
|
||||
val owner = key()
|
||||
store.save(owner, ChatComposerDraft(text = "temporary"))
|
||||
|
||||
store.save(
|
||||
owner,
|
||||
ChatComposerDraft(
|
||||
context = ChatComposerDraftContext(
|
||||
quotedMessageId = " ",
|
||||
editingMessageId = "",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(ChatComposerDraft(), store.snapshot(owner))
|
||||
assertEquals(ChatComposerDraft(), store.observe(owner).first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun removeSessionClearsEveryDraftSlotOnlyForExactNamespace() {
|
||||
val primary = key()
|
||||
val alternate = primary.copy(draftId = "alternate")
|
||||
val otherProfile = primary.copy(profileId = "other")
|
||||
store.save(primary, ChatComposerDraft(text = "primary"))
|
||||
store.save(alternate, ChatComposerDraft(text = "alternate"))
|
||||
store.save(otherProfile, ChatComposerDraft(text = "keep"))
|
||||
|
||||
store.removeSession(primary.connectionId, primary.profileId, primary.sessionId)
|
||||
|
||||
assertTrue(store.snapshot(primary).isEmpty)
|
||||
assertTrue(store.snapshot(alternate).isEmpty)
|
||||
assertEquals("keep", store.snapshot(otherProfile).text)
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException::class)
|
||||
fun blankIdentityIsRejected() {
|
||||
key(session = "")
|
||||
}
|
||||
|
||||
private fun key(
|
||||
connection: String = "connection-a",
|
||||
profile: String = "coder",
|
||||
session: String = "session-a",
|
||||
) = ChatComposerDraftKey(
|
||||
connectionId = connection,
|
||||
profileId = profile,
|
||||
sessionId = session,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import androidx.datastore.preferences.core.mutablePreferencesOf
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class ChatInputPreferencesTest {
|
||||
|
||||
@Test
|
||||
fun `enter defaults to send and unknown values fall back safely`() = runTest {
|
||||
assertEquals(
|
||||
PhysicalKeyboardEnterBehavior.SendMessage,
|
||||
ChatInputPreferencesRepository(InMemoryChatInputDataStore())
|
||||
.physicalKeyboardEnterBehavior.first(),
|
||||
)
|
||||
val futureStore = InMemoryChatInputDataStore(
|
||||
mutablePreferencesOf(
|
||||
ChatInputPreferencesRepository.KEY_PHYSICAL_KEYBOARD_ENTER to "future_mode",
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
PhysicalKeyboardEnterBehavior.SendMessage,
|
||||
ChatInputPreferencesRepository(futureStore).physicalKeyboardEnterBehavior.first(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `all enter behaviors round trip without replacing unrelated settings`() = runTest {
|
||||
val unrelatedKey = stringPreferencesKey("unrelated_chat_input_test")
|
||||
val store = InMemoryChatInputDataStore(mutablePreferencesOf(unrelatedKey to "keep-me"))
|
||||
val repository = ChatInputPreferencesRepository(store)
|
||||
|
||||
PhysicalKeyboardEnterBehavior.entries.forEach { behavior ->
|
||||
repository.setPhysicalKeyboardEnterBehavior(behavior)
|
||||
assertEquals(behavior, repository.physicalKeyboardEnterBehavior.first())
|
||||
assertEquals("keep-me", store.data.first()[unrelatedKey])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class InMemoryChatInputDataStore(
|
||||
initial: Preferences = emptyPreferences(),
|
||||
) : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow(initial)
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(
|
||||
transform: suspend (t: Preferences) -> Preferences,
|
||||
): Preferences = transform(state.value).also { state.value = it }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ChatQuoteReferenceTest {
|
||||
@Test
|
||||
fun `quote envelope round trips without changing authored body`() {
|
||||
val reference = ChatQuoteReference(
|
||||
messageId = "message/id with spaces",
|
||||
authorLabel = "Hermes",
|
||||
excerpt = "First line\nsecond line",
|
||||
)
|
||||
|
||||
val encoded = buildChatQuotedPrompt("My reply", reference)
|
||||
val parsed = parseChatQuotedPrompt(encoded)
|
||||
|
||||
assertEquals("My reply", parsed?.body)
|
||||
assertEquals("message/id with spaces", parsed?.reference?.messageId)
|
||||
assertEquals("Hermes", parsed?.reference?.authorLabel)
|
||||
assertEquals("First line second line", parsed?.reference?.excerpt)
|
||||
assertTrue(encoded.startsWith("> **Replying to [@Hermes](hermes-message://"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `plain and malformed text stay ordinary`() {
|
||||
assertNull(parseChatQuotedPrompt("ordinary message"))
|
||||
assertNull(
|
||||
parseChatQuotedPrompt(
|
||||
"> **Replying to [@Hermes](hermes-message://not+base64):** text\n\nbody",
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `null reference does not alter transport text`() {
|
||||
assertEquals("My reply", buildChatQuotedPrompt("My reply", null))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ProfilePresentationStoreTest {
|
||||
@@ -40,11 +41,11 @@ class ProfilePresentationStoreTest {
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("beta", AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "alpha", "gamma"),
|
||||
listOf("beta", AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "alpha", "default", "gamma"),
|
||||
ProfilePresentationPolicy.orderedKeys(profiles, presentation),
|
||||
)
|
||||
assertEquals(
|
||||
listOf("beta", AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "gamma"),
|
||||
listOf("beta", AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "default", "gamma"),
|
||||
ProfilePresentationPolicy.visibleKeys(
|
||||
profiles,
|
||||
presentation,
|
||||
@@ -58,7 +59,7 @@ class ProfilePresentationStoreTest {
|
||||
val presentation = ProfilePresentation(hidden = setOf("beta"))
|
||||
|
||||
assertEquals(
|
||||
listOf(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "alpha", "beta", "gamma"),
|
||||
listOf(AgentDisplay.SERVER_DEFAULT_PROFILE_KEY, "alpha", "default", "beta", "gamma"),
|
||||
ProfilePresentationPolicy.visibleKeys(profiles, presentation, selectedKey = "beta"),
|
||||
)
|
||||
}
|
||||
@@ -79,6 +80,26 @@ class ProfilePresentationStoreTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shelfHidesForOneVisibleIdentityAndShowsForTwo() {
|
||||
val onlyDefault = listOf(Profile(name = "default", model = "root"))
|
||||
|
||||
assertTrue(
|
||||
ProfilePresentationPolicy.shouldShowShelf(
|
||||
profiles = onlyDefault,
|
||||
presentation = ProfilePresentation(hidden = setOf("default")),
|
||||
selectedKey = AgentDisplay.SERVER_DEFAULT_PROFILE_KEY,
|
||||
).not(),
|
||||
)
|
||||
assertTrue(
|
||||
ProfilePresentationPolicy.shouldShowShelf(
|
||||
profiles = onlyDefault,
|
||||
presentation = ProfilePresentation(),
|
||||
selectedKey = AgentDisplay.SERVER_DEFAULT_PROFILE_KEY,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun clearRemovesOnlyOneConnectionsPreferences() = runBlocking {
|
||||
store.setOrder("one", listOf("beta"))
|
||||
|
||||
@@ -2,58 +2,27 @@ package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/**
|
||||
* Unit tests for [ProfileSelectionStore].
|
||||
*
|
||||
* Follows the pattern in `BargeInPreferencesTest` — bypasses
|
||||
* [android.content.Context] by feeding the store a filesystem-backed
|
||||
* [DataStore] via [PreferenceDataStoreFactory.create]. That only works
|
||||
* because [ProfileSelectionStore]'s primary constructor takes a raw
|
||||
* DataStore (the Context secondary resolves to the same shape in prod).
|
||||
* Bypasses [android.content.Context] by feeding the store an in-memory
|
||||
* [DataStore]. [ProfileSelectionStore]'s primary constructor takes the same
|
||||
* raw DataStore shape that its Context constructor resolves in production.
|
||||
*/
|
||||
class ProfileSelectionStoreTest {
|
||||
|
||||
@get:Rule
|
||||
val tempFolder = TemporaryFolder()
|
||||
|
||||
private lateinit var scope: CoroutineScope
|
||||
private lateinit var dataStore: DataStore<Preferences>
|
||||
private lateinit var store: ProfileSelectionStore
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
val file: File = tempFolder.newFile("profile_selections_test.preferences_pb")
|
||||
// PreferenceDataStoreFactory requires the backing file NOT exist yet;
|
||||
// TemporaryFolder.newFile() creates it, so we delete first.
|
||||
if (file.exists()) file.delete()
|
||||
dataStore = PreferenceDataStoreFactory.create(
|
||||
scope = scope,
|
||||
produceFile = { file },
|
||||
)
|
||||
store = ProfileSelectionStore(dataStore)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
scope.cancel()
|
||||
}
|
||||
private val store = ProfileSelectionStore(InMemoryPreferencesDataStore())
|
||||
|
||||
@Test
|
||||
fun unset_connection_emitsNull() = runBlocking {
|
||||
@@ -110,4 +79,17 @@ class ProfileSelectionStoreTest {
|
||||
store.setSelectedProfile("conn-1", "coder")
|
||||
assertEquals("coder", store.selectedProfileFlow("conn-1").first())
|
||||
}
|
||||
|
||||
/** Avoids AndroidX's Windows-only atomic-rename failure in filesystem DataStore tests. */
|
||||
private class InMemoryPreferencesDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow<Preferences>(emptyPreferences())
|
||||
private val updateMutex = Mutex()
|
||||
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences =
|
||||
updateMutex.withLock {
|
||||
transform(state.value).also { state.value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,50 +1,23 @@
|
||||
package com.hermesandroid.relay.data
|
||||
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.emptyPreferences
|
||||
import com.hermesandroid.relay.data.SessionTransport.GATEWAY
|
||||
import com.hermesandroid.relay.data.SessionTransport.SSE
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Before
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class ProfileSessionStoreTest {
|
||||
|
||||
@get:Rule
|
||||
val tempFolder = TemporaryFolder()
|
||||
|
||||
private lateinit var scope: CoroutineScope
|
||||
private lateinit var dataStore: DataStore<Preferences>
|
||||
private lateinit var store: ProfileSessionStore
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
val file: File = tempFolder.newFile("profile_sessions_test.preferences_pb")
|
||||
if (file.exists()) file.delete()
|
||||
dataStore = PreferenceDataStoreFactory.create(
|
||||
scope = scope,
|
||||
produceFile = { file },
|
||||
)
|
||||
store = ProfileSessionStore(dataStore)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
scope.cancel()
|
||||
}
|
||||
private val store = ProfileSessionStore(InMemoryPreferencesDataStore())
|
||||
|
||||
@Test
|
||||
fun setAndGet_defaultProfileSession() = runBlocking {
|
||||
@@ -69,6 +42,21 @@ class ProfileSessionStoreTest {
|
||||
assertEquals("session-other", store.sessionIdFlow("conn-2", "mizu", GATEWAY).first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun literalDefaultProfileDoesNotShareServerDefaultSessionSlot() = runBlocking {
|
||||
store.setSessionId("conn-1", null, GATEWAY, "sticky-default-session")
|
||||
store.setSessionId("conn-1", "default", GATEWAY, "root-profile-session")
|
||||
|
||||
assertEquals(
|
||||
"sticky-default-session",
|
||||
store.sessionIdFlow("conn-1", null, GATEWAY).first(),
|
||||
)
|
||||
assertEquals(
|
||||
"root-profile-session",
|
||||
store.sessionIdFlow("conn-1", "default", GATEWAY).first(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun gatewayAndSseSlotsAreIndependentForSameProfile() = runBlocking {
|
||||
// The core of the continuity fix: a profile's gateway session and its
|
||||
@@ -126,4 +114,17 @@ class ProfileSessionStoreTest {
|
||||
assertEquals(SSE, SessionTransport.forEndpoint("completions"))
|
||||
assertEquals(SSE, SessionTransport.forEndpoint("runs"))
|
||||
}
|
||||
|
||||
/** Avoids AndroidX's Windows-only atomic-rename failure in filesystem DataStore tests. */
|
||||
private class InMemoryPreferencesDataStore : DataStore<Preferences> {
|
||||
private val state = MutableStateFlow<Preferences>(emptyPreferences())
|
||||
private val updateMutex = Mutex()
|
||||
|
||||
override val data: Flow<Preferences> = state
|
||||
|
||||
override suspend fun updateData(transform: suspend (t: Preferences) -> Preferences): Preferences =
|
||||
updateMutex.withLock {
|
||||
transform(state.value).also { state.value = it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
@@ -929,6 +930,88 @@ class ChatHandlerTest {
|
||||
assertEquals(MessageRole.ASSISTANT, handler.messages.value[1].role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_recoversStructuredToolCallsWithoutLiveEvents() {
|
||||
val toolCalls = buildJsonArray {
|
||||
add(
|
||||
buildJsonObject {
|
||||
put("call_id", "call-history-1")
|
||||
put("name", "terminal")
|
||||
put("args", buildJsonObject { put("command", "git status") })
|
||||
},
|
||||
)
|
||||
}
|
||||
handler.loadMessageHistory(
|
||||
listOf(
|
||||
MessageItem(
|
||||
id = "assistant-history-1",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("The workspace is clean."),
|
||||
toolCalls = toolCalls,
|
||||
),
|
||||
MessageItem(
|
||||
id = "tool-history-1",
|
||||
role = "tool",
|
||||
content = JsonPrimitive("nothing to commit"),
|
||||
toolCallId = "call-history-1",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
val message = handler.messages.value.single()
|
||||
val call = message.toolCalls.single()
|
||||
assertEquals("terminal", call.name)
|
||||
assertEquals("call-history-1", call.id)
|
||||
assertEquals("nothing to commit", call.result)
|
||||
assertTrue(call.isComplete)
|
||||
assertTrue(call.success == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun persistedToolActivityPreflight_keepsHealthyLiveTranscriptUnchanged() {
|
||||
handler.addPlaceholderMessage(
|
||||
ChatMessage(
|
||||
id = "assistant-live-1",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "The workspace is clean.",
|
||||
timestamp = 1L,
|
||||
isStreaming = true,
|
||||
),
|
||||
)
|
||||
handler.onToolCallStart("assistant-live-1", "call-history-1", "terminal", "git status")
|
||||
handler.onToolCallComplete("assistant-live-1", "call-history-1", "nothing to commit")
|
||||
handler.onStreamComplete("assistant-live-1")
|
||||
val before = handler.messages.value
|
||||
val history = listOf(
|
||||
MessageItem(
|
||||
id = "assistant-history-1",
|
||||
role = "assistant",
|
||||
content = JsonPrimitive("The workspace is clean."),
|
||||
toolCalls = buildJsonArray {
|
||||
add(
|
||||
buildJsonObject {
|
||||
put("call_id", "call-history-1")
|
||||
put("name", "terminal")
|
||||
put("args", JsonPrimitive("git status"))
|
||||
},
|
||||
)
|
||||
},
|
||||
),
|
||||
MessageItem(
|
||||
id = "tool-history-1",
|
||||
role = "tool",
|
||||
content = JsonPrimitive("nothing to commit"),
|
||||
toolCallId = "call-history-1",
|
||||
),
|
||||
)
|
||||
|
||||
assertFalse(handler.hasMissingPersistedToolActivity(history))
|
||||
assertSame(before, handler.messages.value)
|
||||
|
||||
handler = ChatHandler()
|
||||
assertTrue(handler.hasMissingPersistedToolActivity(history))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun loadMessageHistory_skipsUnknownRoles() {
|
||||
val items = listOf(
|
||||
|
||||
@@ -901,11 +901,45 @@ class DashboardApiClientTest {
|
||||
val url = request.requestUrl!!
|
||||
assertEquals("/api/sessions/sess-a/messages", url.encodedPath)
|
||||
assertEquals("mizu", url.queryParameter("profile"))
|
||||
assertEquals("500", url.queryParameter("limit"))
|
||||
assertEquals("0", url.queryParameter("offset"))
|
||||
assertEquals("oldest", url.queryParameter("order"))
|
||||
assertEquals(2, messages.size)
|
||||
assertEquals("user", messages[0].role)
|
||||
assertEquals("assistant", messages[1].role)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSessionMessages_pagesCompleteHistoryAndPreservesProfileScope() = runTest {
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 0, count = 500, returned = 500))
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.getSessionMessages("sess-a", profile = "mizu")
|
||||
.getOrThrow()
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
val second = server.takeRequest().requestUrl!!
|
||||
assertEquals(listOf("0", "500"), listOf(first, second).map { it.queryParameter("offset") })
|
||||
assertEquals(listOf("mizu", "mizu"), listOf(first, second).map { it.queryParameter("profile") })
|
||||
assertEquals((0..500).map(Int::toString), messages.map { it.id })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getSessionMessages_latestUsesOneBoundedPage() = runTest {
|
||||
server.enqueue(messagePageResponse(key = "messages", start = 500, count = 500, returned = 500))
|
||||
|
||||
val messages = DashboardApiClient(baseUrl = server.url("/").toString())
|
||||
.getSessionMessages("sess-a", profile = null, mode = SessionMessageLoadMode.LATEST)
|
||||
.getOrThrow()
|
||||
|
||||
val request = server.takeRequest().requestUrl!!
|
||||
assertEquals("latest", request.queryParameter("order"))
|
||||
assertEquals("0", request.queryParameter("offset"))
|
||||
assertEquals(500, messages.size)
|
||||
assertEquals(1, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parseChatDisplaySettings_readsNestedDisplayConfig() {
|
||||
val root = Json.parseToJsonElement(
|
||||
@@ -1287,3 +1321,19 @@ class DashboardApiClientTest {
|
||||
assertEquals("off", settings.toolDisplay)
|
||||
}
|
||||
}
|
||||
|
||||
private fun messagePageResponse(
|
||||
key: String,
|
||||
start: Int,
|
||||
count: Int,
|
||||
returned: Int,
|
||||
): MockResponse {
|
||||
val messages = (start until start + count).joinToString(",") { index ->
|
||||
"""{"id":"$index","role":"user","content":"m$index"}"""
|
||||
}
|
||||
return MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"session_id":"sess-a","$key":[$messages],"pagination":{"limit":500,"offset":$start,"order":"oldest","returned":$returned}}""",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2099,7 +2099,7 @@ class GatewayChatClientTest {
|
||||
// --- Edit & regenerate ---
|
||||
|
||||
@Test
|
||||
fun `truncate ordinal rides prompt submit`() {
|
||||
fun `later truncate ordinal carries destructive confirmation only`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
@@ -2111,6 +2111,42 @@ class GatewayChatClientTest {
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(2, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
assertFalse(submit.containsKey("confirm_empty_truncate"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `first user truncate carries empty-history confirmation`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
text = "replace first message",
|
||||
newSessionTitle = null,
|
||||
callbacks = r.callbacks,
|
||||
truncateBeforeUserOrdinal = 0,
|
||||
onPreflightFailure = { r.preflightFailures += it },
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(0, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
assertEquals(true, (submit["confirm_empty_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `middle truncate ordinal omits empty-history confirmation`() {
|
||||
val r = Recorder()
|
||||
client.sendTurn(
|
||||
sessionId = null,
|
||||
text = "replace middle message",
|
||||
newSessionTitle = null,
|
||||
callbacks = r.callbacks,
|
||||
truncateBeforeUserOrdinal = 1,
|
||||
onPreflightFailure = { r.preflightFailures += it },
|
||||
)
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertEquals(1, (submit["truncate_before_user_ordinal"] as? JsonPrimitive)?.intOrNull)
|
||||
assertEquals(true, (submit["confirm_truncate"] as? JsonPrimitive)?.booleanOrNull)
|
||||
assertFalse(submit.containsKey("confirm_empty_truncate"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2119,6 +2155,8 @@ class GatewayChatClientTest {
|
||||
client.sendTurn(null, "plain", null, r.callbacks) { r.preflightFailures += it }
|
||||
val submit = harness.awaitRpc("prompt.submit")
|
||||
assertFalse(submit.containsKey("truncate_before_user_ordinal"))
|
||||
assertFalse(submit.containsKey("confirm_truncate"))
|
||||
assertFalse(submit.containsKey("confirm_empty_truncate"))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2138,18 +2176,26 @@ class GatewayChatClientTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active session cap rejection surfaces error without preflight fallback`() {
|
||||
val message = "Active session limit reached; close the session held by another client"
|
||||
harness.rpcErrors["prompt.submit"] = 4090 to message
|
||||
val r = Recorder()
|
||||
fun `authoritative prompt rejections surface server message without preflight fallback`() {
|
||||
val cases = listOf(
|
||||
4028 to "Empty-history truncate confirmation required",
|
||||
4029 to "Truncate confirmation required",
|
||||
4090 to "Active session limit reached; close the session held by another client",
|
||||
5070 to "Session storage is full; free disk space and retry",
|
||||
5071 to "Initial session persistence failed",
|
||||
)
|
||||
|
||||
client.sendTurn(null, "hello", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitRpc("prompt.submit")
|
||||
cases.forEachIndexed { index, (code, message) ->
|
||||
harness.rpcErrors["prompt.submit"] = code to message
|
||||
val r = Recorder()
|
||||
client.sendTurn(null, "hello-$code", null, r.callbacks) { r.preflightFailures += it }
|
||||
harness.awaitRpc("prompt.submit")
|
||||
|
||||
waitUntil { r.errors.isNotEmpty() }
|
||||
assertEquals(listOf(message), r.errors.toList())
|
||||
assertTrue("authoritative rejection must not trigger SSE fallback", r.preflightFailures.isEmpty())
|
||||
assertEquals(1, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
waitUntil { r.errors.isNotEmpty() }
|
||||
assertEquals(listOf(message), r.errors.toList())
|
||||
assertTrue("$code must not trigger SSE fallback", r.preflightFailures.isEmpty())
|
||||
assertEquals(index + 1, harness.rpcLog.count { it.first == "prompt.submit" })
|
||||
}
|
||||
}
|
||||
|
||||
// --- HRUI-016: long / fire-and-forget prompt.submit ack semantics.
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.SkillListResponse
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
@@ -18,6 +21,48 @@ import org.junit.Test
|
||||
*/
|
||||
class HermesApiClientTest {
|
||||
|
||||
@Test
|
||||
fun getMessages_pagesApiFallbackOldestFirst() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
try {
|
||||
server.enqueue(apiMessagePageResponse(start = 0, count = 500, returned = 500))
|
||||
server.enqueue(apiMessagePageResponse(start = 500, count = 1, returned = 1))
|
||||
|
||||
val messages = HermesApiClient(server.url("/").toString(), "test-key")
|
||||
.getMessages("sess-a")
|
||||
|
||||
val first = server.takeRequest().requestUrl!!
|
||||
val second = server.takeRequest().requestUrl!!
|
||||
assertEquals(listOf("0", "500"), listOf(first, second).map { it.queryParameter("offset") })
|
||||
assertEquals(listOf("oldest", "oldest"), listOf(first, second).map { it.queryParameter("order") })
|
||||
assertEquals((0..500).map(Int::toString), messages.map { it.id })
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun getMessages_acceptsLegacyUnpaginatedApiEnvelope() = runTest {
|
||||
val server = MockWebServer()
|
||||
server.start()
|
||||
try {
|
||||
server.enqueue(
|
||||
MockResponse().setHeader("Content-Type", "application/json").setBody(
|
||||
"""{"object":"list","data":[{"id":"1","role":"user","content":"hi"}]}""",
|
||||
),
|
||||
)
|
||||
|
||||
val messages = HermesApiClient(server.url("/").toString(), "test-key")
|
||||
.getMessages("sess-a")
|
||||
|
||||
assertEquals(listOf("1"), messages.map { it.id })
|
||||
assertEquals(1, server.requestCount)
|
||||
} finally {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toolsetInventory_parserPreservesEnabledAndResolvedTools() {
|
||||
val parsed = parseToolsetListBody(
|
||||
@@ -596,3 +641,14 @@ class HermesApiClientTest {
|
||||
assertEquals("http://localhost:8642/api/sessions/sess-789", url)
|
||||
}
|
||||
}
|
||||
|
||||
private fun apiMessagePageResponse(start: Int, count: Int, returned: Int): MockResponse {
|
||||
val messages = (start until start + count).joinToString(",") { index ->
|
||||
"""{"id":"$index","role":"user","content":"m$index"}"""
|
||||
}
|
||||
return MockResponse()
|
||||
.setHeader("Content-Type", "application/json")
|
||||
.setBody(
|
||||
"""{"object":"list","session_id":"sess-a","data":[$messages],"pagination":{"limit":500,"offset":$start,"order":"oldest","returned":$returned}}""",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
@@ -11,4 +13,42 @@ class ModelOptionsResponseFenceTest {
|
||||
assertFalse(isCurrentModelOptionsResponse(3, 4, "connection::alpha", "connection::alpha"))
|
||||
assertFalse(isCurrentModelOptionsResponse(4, 4, "connection::alpha", "connection::beta"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun catalogRefreshNeverPublishesDefaultIdentity() {
|
||||
val options = GatewayModelOptions(
|
||||
providers = emptyList(),
|
||||
currentModel = "server-default",
|
||||
currentProvider = "server",
|
||||
)
|
||||
|
||||
assertNull(
|
||||
modelOptionsIdentityToPublish(
|
||||
catalogOnly = true,
|
||||
hasLiveSession = true,
|
||||
sessionIdentity = GatewayModelIdentity("session-model", "session-provider"),
|
||||
options = options,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun normalRefreshKeepsCanonicalLiveSessionIdentity() {
|
||||
val sessionIdentity = GatewayModelIdentity("session-model", "session-provider")
|
||||
val options = GatewayModelOptions(
|
||||
providers = emptyList(),
|
||||
currentModel = "server-default",
|
||||
currentProvider = "server",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
sessionIdentity,
|
||||
modelOptionsIdentityToPublish(
|
||||
catalogOnly = false,
|
||||
hasLiveSession = true,
|
||||
sessionIdentity = sessionIdentity,
|
||||
options = options,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.hermesandroid.relay.network.upstream
|
||||
|
||||
import com.hermesandroid.relay.network.upstream.models.MessageItem
|
||||
import com.hermesandroid.relay.network.upstream.models.MessagePagination
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class SessionMessagePaginationTest {
|
||||
|
||||
@Test
|
||||
fun `complete history pages oldest first without gaps`() = runTest {
|
||||
val requests = mutableListOf<SessionMessagePageRequest>()
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) { request ->
|
||||
requests += request
|
||||
val count = if (request.offset == 0) 500 else 1
|
||||
Result.success(page(request.offset, count, returned = count))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals((0..500).map(Int::toString), result.map { it.id })
|
||||
assertEquals(listOf(0, 500), requests.map { it.offset })
|
||||
assertEquals(listOf("oldest", "oldest"), requests.map { it.order })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `exact 500 requests one terminal page and returns no duplicates`() = runTest {
|
||||
val requests = mutableListOf<SessionMessagePageRequest>()
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) { request ->
|
||||
requests += request
|
||||
val count = if (request.offset == 0) 500 else 0
|
||||
Result.success(page(request.offset, count, returned = count))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(500, result.size)
|
||||
assertEquals(listOf(0, 500), requests.map { it.offset })
|
||||
assertEquals(500, result.mapNotNull { it.id }.distinct().size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `legacy envelope is accepted as one complete response`() = runTest {
|
||||
var calls = 0
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
calls++
|
||||
Result.success(page(0, 499, pagination = null))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(499, result.size)
|
||||
assertEquals(1, calls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `latest mode makes exactly one bounded latest request`() = runTest {
|
||||
var captured: SessionMessagePageRequest? = null
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.LATEST) { request ->
|
||||
captured = request
|
||||
Result.success(page(500, 500, returned = 500))
|
||||
}.getOrThrow()
|
||||
|
||||
assertEquals(500, result.size)
|
||||
assertEquals("latest", captured?.order)
|
||||
assertEquals(0, captured?.offset)
|
||||
assertEquals(500, captured?.limit)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `cancellation is never converted to an empty transcript`() = runTest {
|
||||
try {
|
||||
loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
throw CancellationException("session switched")
|
||||
}
|
||||
throw AssertionError("expected cancellation")
|
||||
} catch (error: CancellationException) {
|
||||
assertEquals("session switched", error.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `payload safety bound fails clearly before another page`() = runTest {
|
||||
val result = loadSessionMessages(SessionMessageLoadMode.COMPLETE) {
|
||||
Result.success(
|
||||
SessionMessagePage(
|
||||
messages = emptyList(),
|
||||
pagination = MessagePagination(returned = 0),
|
||||
payloadChars = 32_000_001,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
assertEquals(SessionTranscriptTooLargeException::class, result.exceptionOrNull()?.let { it::class })
|
||||
}
|
||||
|
||||
private fun page(
|
||||
start: Int,
|
||||
count: Int,
|
||||
returned: Int = count,
|
||||
pagination: MessagePagination? = MessagePagination(
|
||||
limit = SESSION_MESSAGE_PAGE_SIZE,
|
||||
offset = start,
|
||||
order = "oldest",
|
||||
returned = returned,
|
||||
),
|
||||
): SessionMessagePage = SessionMessagePage(
|
||||
messages = (start until start + count).map { index ->
|
||||
MessageItem(id = index.toString(), role = "user", content = JsonPrimitive("m$index"))
|
||||
},
|
||||
pagination = pagination,
|
||||
payloadChars = count * 20,
|
||||
)
|
||||
}
|
||||
@@ -6,9 +6,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.AutoAwesome
|
||||
import androidx.compose.material.icons.filled.GraphicEq
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material.icons.filled.Schedule
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
@@ -56,21 +54,46 @@ import com.github.takahirom.roborazzi.captureRoboImage
|
||||
import com.hermesandroid.relay.ui.screens.AppearanceSettingsScreen
|
||||
import com.hermesandroid.relay.viewmodel.ConnectionViewModel
|
||||
import com.hermesandroid.relay.data.ChatMessage
|
||||
import com.hermesandroid.relay.data.ChatSession
|
||||
import com.hermesandroid.relay.data.Connection
|
||||
import com.hermesandroid.relay.data.DashboardConnectionStatus
|
||||
import com.hermesandroid.relay.data.MessageRole
|
||||
import com.hermesandroid.relay.data.PetBehaviorPreferences
|
||||
import com.hermesandroid.relay.ui.components.ChatInputBar
|
||||
import com.hermesandroid.relay.ui.components.ChatInputPickerControl
|
||||
import com.hermesandroid.relay.ui.components.ChatInputTrailing
|
||||
import com.hermesandroid.relay.ui.components.ContextMeterBar
|
||||
import com.hermesandroid.relay.ui.components.ConversationVoiceDock
|
||||
import com.hermesandroid.relay.ui.components.MessageBubble
|
||||
import com.hermesandroid.relay.ui.components.MorphingSphere
|
||||
import com.hermesandroid.relay.ui.components.RelayChromeIconButton
|
||||
import com.hermesandroid.relay.ui.components.RelayStatusStrip
|
||||
import com.hermesandroid.relay.ui.components.SphereState
|
||||
import com.hermesandroid.relay.ui.components.SphereReactivity
|
||||
import com.hermesandroid.relay.ui.components.VoiceModeOverlay
|
||||
import com.hermesandroid.relay.ui.components.FloatingPetCompanion
|
||||
import com.hermesandroid.relay.ui.components.SessionDrawerContent
|
||||
import com.hermesandroid.relay.ui.components.pet.PetLogicalEdge
|
||||
import com.hermesandroid.relay.ui.components.pet.PetPlacement
|
||||
import com.hermesandroid.relay.ui.screens.ConnectionsSettingsScreen
|
||||
import com.hermesandroid.relay.ui.theme.HermesRelayTheme
|
||||
import com.hermesandroid.relay.ui.theme.RelayRefresh
|
||||
import com.hermesandroid.relay.R
|
||||
import com.hermesandroid.relay.data.VoicePresentationMode
|
||||
import com.hermesandroid.relay.ui.components.avatar.AgentAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.AvatarRenderState
|
||||
import com.hermesandroid.relay.ui.components.avatar.AvatarSource
|
||||
import com.hermesandroid.relay.ui.components.avatar.FrameSequenceClip
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAgentAvatar
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalAvailablePets
|
||||
import com.hermesandroid.relay.ui.components.avatar.LocalFloatingPet
|
||||
import com.hermesandroid.relay.ui.components.avatar.PetAvatar
|
||||
import com.hermesandroid.relay.ui.components.LocalSphereSkin
|
||||
import com.hermesandroid.relay.ui.components.SphereRegistry
|
||||
import com.hermesandroid.relay.viewmodel.InteractionMode
|
||||
import com.hermesandroid.relay.viewmodel.VoiceState
|
||||
import com.hermesandroid.relay.viewmodel.VoiceUiState
|
||||
import com.hermesandroid.relay.viewmodel.RelayUiState
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.ui.res.painterResource
|
||||
@@ -78,11 +101,13 @@ import androidx.compose.ui.test.junit4.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.onRoot
|
||||
import androidx.compose.ui.test.performScrollTo
|
||||
import androidx.compose.ui.test.performClick
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Deterministic, host-side marketing frames with Roborazzi.
|
||||
@@ -92,7 +117,7 @@ import org.robolectric.annotation.GraphicsMode
|
||||
* ContextMeterBar, RelayModeStrip, ChatInputBar, RelayStatusStrip) and REAL
|
||||
* leaf components (MorphingSphere, MessageBubble) fed mock, public-safe data —
|
||||
* so what renders is the app's own UI, not a mock-up. The sphere is pinned with
|
||||
* fixedTime/fixedColorPhase for byte-identical renders; the same scene
|
||||
* fixedTime/fixedColorPhase for pixel-identical renders; the same scene
|
||||
* re-renders in any theme by swapping appThemeId.
|
||||
*
|
||||
* Run: ./gradlew :app:testGooglePlayDebugUnitTest --tests "*StoreScreenshotTest*"
|
||||
@@ -100,7 +125,7 @@ import org.robolectric.annotation.GraphicsMode
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w360dp-h720dp-xxhdpi") // 1080x2160 px @ density 3.0
|
||||
@Config(qualifiers = "w400dp-h800dp-432dpi") // 1080x2160 px, Galaxy Ultra-like 400x800dp viewport
|
||||
class StoreScreenshotTest {
|
||||
|
||||
@get:Rule
|
||||
@@ -124,22 +149,80 @@ class StoreScreenshotTest {
|
||||
@Test fun s01_landing_nousBlue() = capture("01_landing_nous-blue", "nous-blue") { LandingScene() }
|
||||
@Test fun s01_landing_cyberpunk() = capture("01_landing_cyberpunk", "cyberpunk") { LandingScene() }
|
||||
|
||||
@Test fun s02_chat_brand() = capture("02_chat", "hermes-relay") { ChatScene() }
|
||||
// "Blend" chat surface — wider bubbles + assistant avatar + grouped turns +
|
||||
// a code block, in the Inter default. The self-verification frame for the
|
||||
// chat UI refresh. Rendered in two themes to check dark + light contrast.
|
||||
// The grouped chat scene is the canonical store frame: it exercises the
|
||||
// current wider bubbles, assistant avatar, grouped turns, code rendering,
|
||||
// model/effort controls, and the complete production chrome.
|
||||
@Test fun s02_chat_brand() {
|
||||
val pet = marketingPet()
|
||||
capture("02_chat", "hermes-relay") { ChatWithPetScene(pet) }
|
||||
}
|
||||
// Keep a second filename plus a light-theme render as visual-regression
|
||||
// diagnostics; only 02_chat is promoted to the store listing.
|
||||
@Test fun s09_blend_chat() = capture("09_blend_chat", "hermes-relay") { BlendChatScene() }
|
||||
@Test fun s09_blend_chat_light() = capture("09_blend_chat_nous-blue", "nous-blue") { BlendChatScene() }
|
||||
@Test fun s03_voice() = capture("03_voice", "hermes-relay") { VoiceScene() }
|
||||
@Test fun s03_voice() {
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(
|
||||
LocalSphereSkin provides SphereRegistry.Adaptive,
|
||||
LocalAgentAvatar provides FrozenMarketingSphere,
|
||||
) {
|
||||
VoiceScene()
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeByFrame()
|
||||
compose.onRoot().captureRoboImage("build/store-shots/03_voice.png")
|
||||
}
|
||||
@Test fun s11_voice_conversation() {
|
||||
compose.mainClock.autoAdvance = false
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalSphereSkin provides SphereRegistry.Adaptive) {
|
||||
VoiceConversationScene()
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.mainClock.advanceTimeByFrame()
|
||||
compose.onRoot().captureRoboImage("build/store-shots/11_voice_conversation.png")
|
||||
}
|
||||
// Real screen (1:1, auto-updates on layout changes). ConnectionViewModel
|
||||
// takes only an Application; Robolectric provides it. Renders every section
|
||||
// the production Appearance screen has — theme grid, mode, font, animation,
|
||||
// avatar, and skins — not a hand-rebuilt slice.
|
||||
@Test fun s05_themes() {
|
||||
val vm = ConnectionViewModel(ApplicationProvider.getApplicationContext<Application>())
|
||||
capture("05_themes", "hermes-relay") {
|
||||
AppearanceSettingsScreen(connectionViewModel = vm, onBack = {})
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalSphereSkin provides SphereRegistry.Adaptive) {
|
||||
AppearanceSettingsScreen(
|
||||
connectionViewModel = vm,
|
||||
onBack = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onRoot().captureRoboImage("build/store-shots/05_themes.png")
|
||||
}
|
||||
|
||||
@Test fun s05_theme_customizer() {
|
||||
val vm = ConnectionViewModel(ApplicationProvider.getApplicationContext<Application>())
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalSphereSkin provides SphereRegistry.Adaptive) {
|
||||
AppearanceSettingsScreen(
|
||||
connectionViewModel = vm,
|
||||
onBack = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
compose.onNodeWithText("Customize Relay").performScrollTo()
|
||||
compose.onNodeWithText("Customize Relay").performClick()
|
||||
compose.mainClock.advanceTimeBy(500)
|
||||
compose.onNodeWithText("Shape").performScrollTo()
|
||||
compose.onRoot().captureRoboImage("build/store-shots/05_theme_customizer.png")
|
||||
}
|
||||
@Test fun s06_manage() = capture("06_manage", "hermes-relay") { ManageScene() }
|
||||
@Test fun s04_sessions() = capture("04_sessions", "hermes-relay") { SessionsScene() }
|
||||
@@ -162,19 +245,40 @@ class StoreScreenshotTest {
|
||||
// Same real Appearance screen, scrolled to the avatar + sphere-skin sections.
|
||||
@Test fun s08_appearance() {
|
||||
val vm = ConnectionViewModel(ApplicationProvider.getApplicationContext<Application>())
|
||||
val pet = marketingPet()
|
||||
compose.setContent {
|
||||
HermesRelayTheme(appThemeId = "hermes-relay", themePreference = "dark") {
|
||||
CompositionLocalProvider(LocalSphereSkin provides SphereRegistry.Adaptive) {
|
||||
CompositionLocalProvider(
|
||||
LocalSphereSkin provides SphereRegistry.Adaptive,
|
||||
LocalAvailablePets provides listOf(pet),
|
||||
LocalFloatingPet provides pet,
|
||||
) {
|
||||
AppearanceSettingsScreen(connectionViewModel = vm, onBack = {})
|
||||
}
|
||||
}
|
||||
}
|
||||
// Scroll to a skin card (unique to the skin grid, near the bottom) so the
|
||||
// viewport frames the Agent avatar + Sphere skin sections together.
|
||||
compose.onNodeWithText("Solar").performScrollTo()
|
||||
// The earlier frame scrolled past the pet controls and showed only the
|
||||
// sphere-skin grid. Frame the independently selected floating companion,
|
||||
// its real PetAvatar preview, Petdex/import actions, and tuning controls.
|
||||
compose.onNodeWithText("Browse Petdex").performScrollTo()
|
||||
compose.onRoot().captureRoboImage("build/store-shots/08_appearance.png")
|
||||
}
|
||||
|
||||
/** Pinned Petdex Teknium idle frame rendered through the production PetAvatar. */
|
||||
private fun marketingPet(): PetAvatar {
|
||||
val output = File("src/test/resources/marketing/petdex-teknium-idle.png")
|
||||
val clip = FrameSequenceClip(files = listOf(output), fps = 1f)
|
||||
val stateClips = SphereState.entries.associateWith { clip }
|
||||
return PetAvatar(
|
||||
id = "petdex-teknium",
|
||||
label = "Teknium",
|
||||
description = "Petdex companion by asimons81",
|
||||
reactivity = SphereReactivity(voice = true, tools = true, intensity = true, gaze = false),
|
||||
activityClips = stateClips,
|
||||
workingClip = clip,
|
||||
)
|
||||
}
|
||||
|
||||
// Theme gallery — the same content-rich chat scene reskinned by every theme
|
||||
// (content scenes carry light themes better than the sphere hero). One test
|
||||
// per theme: createComposeRule allows a single setContent per test method.
|
||||
@@ -233,10 +337,15 @@ private fun ChatScene() = StoreCockpit(contextUsage = 0.04f) {
|
||||
// surface, and the compact 340dp cap + tightened density match production.
|
||||
@Composable
|
||||
private fun BlendChatScene() = StoreCockpit(contextUsage = 0.06f) {
|
||||
BlendThread()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun BlendThread() {
|
||||
val thread = MockChat.blendThread
|
||||
Column(
|
||||
Modifier.fillMaxSize().padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp)
|
||||
Modifier.fillMaxSize().padding(start = 18.dp, top = 14.dp, end = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.Bottom)
|
||||
) {
|
||||
thread.forEachIndexed { i, m ->
|
||||
val first = i == 0 || thread[i - 1].role != m.role
|
||||
@@ -244,7 +353,7 @@ private fun BlendChatScene() = StoreCockpit(contextUsage = 0.06f) {
|
||||
MessageBubble(
|
||||
message = m,
|
||||
modifier = Modifier.padding(top = if (first) 6.dp else 1.dp),
|
||||
maxBubbleWidth = 340.dp,
|
||||
maxBubbleWidth = 344.dp,
|
||||
isFirstInGroup = first,
|
||||
isLastInGroup = last,
|
||||
)
|
||||
@@ -262,6 +371,7 @@ private fun BlendChatScene() = StoreCockpit(contextUsage = 0.06f) {
|
||||
private fun StoreCockpit(
|
||||
contextUsage: Float? = null,
|
||||
showInput: Boolean = true,
|
||||
conversationVoiceState: VoiceUiState? = null,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val dark = MaterialTheme.colorScheme.background.luminance() < 0.5f
|
||||
@@ -281,7 +391,7 @@ private fun StoreCockpit(
|
||||
}
|
||||
Column(Modifier.padding(start = 10.dp)) {
|
||||
Text("Hermes", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text("gpt-5.5", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
Text("gpt-5.6-sol", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -310,11 +420,35 @@ private fun StoreCockpit(
|
||||
showVoiceHint = false,
|
||||
onVoiceHintShown = {},
|
||||
isDarkTheme = dark,
|
||||
modelControl = ChatInputPickerControl(value = "gpt-5.5", contentDescription = "Select model", options = emptyList()),
|
||||
modelControl = ChatInputPickerControl(value = "gpt-5.6-sol", contentDescription = "Select model", options = emptyList()),
|
||||
effortControl = ChatInputPickerControl(value = "High", contentDescription = "Select reasoning effort", options = emptyList()),
|
||||
topContent = {
|
||||
conversationVoiceState?.let { state ->
|
||||
ConversationVoiceDock(
|
||||
uiState = state,
|
||||
engineMode = "hermes_voice_output",
|
||||
provider = "OpenAI",
|
||||
model = "gpt-4o-mini-tts",
|
||||
voice = "alloy",
|
||||
profileName = "Hermes",
|
||||
outputEnabled = true,
|
||||
onMicTap = {},
|
||||
onMicRelease = {},
|
||||
onInterrupt = {},
|
||||
onPauseAutoMode = {},
|
||||
onModeChange = {},
|
||||
onFocusRequest = {},
|
||||
onOverlayRequest = {},
|
||||
onOpenSettings = {},
|
||||
onExit = {},
|
||||
)
|
||||
}
|
||||
},
|
||||
topContentVisible = conversationVoiceState != null,
|
||||
suppressVoiceTrailing = conversationVoiceState != null,
|
||||
)
|
||||
}
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.5 / profile: default")
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.6-sol / profile: default")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,7 +474,7 @@ private fun StoreSettings(title: String, content: @Composable androidx.compose.f
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
content = content,
|
||||
)
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.5 / profile: default")
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.6-sol / profile: default")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -349,34 +483,99 @@ private fun StoreSettings(title: String, content: @Composable androidx.compose.f
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@Composable
|
||||
private fun VoiceScene() {
|
||||
// Full-screen voice modal — sphere hero + transcript prompt + mic FAB.
|
||||
Column(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Row(
|
||||
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(androidx.compose.material.icons.Icons.Filled.GraphicEq, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp))
|
||||
Text(" Voice", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text(" Realtime Agent / default profile", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Box(Modifier.size(300.dp).padding(top = 24.dp)) {
|
||||
MorphingSphere(Modifier.fillMaxSize(), state = SphereState.Listening, intensity = 0.5f, voiceAmplitude = 0.4f, voiceMode = true, fixedTime = 5f, fixedColorPhase = 1.0f)
|
||||
}
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.weight(1f))
|
||||
Text("Tap the mic to speak", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Box(
|
||||
Modifier.padding(vertical = 40.dp).size(76.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primary),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Icon(androidx.compose.material.icons.Icons.Filled.Mic, "Mic", tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(34.dp))
|
||||
}
|
||||
private fun VoiceScene() = VoiceModeOverlay(
|
||||
uiState = VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Speaking,
|
||||
amplitude = 0.58f,
|
||||
outputAudioActive = true,
|
||||
interactionMode = InteractionMode.Continuous,
|
||||
),
|
||||
onMicTap = {},
|
||||
onMicRelease = {},
|
||||
onInterrupt = {},
|
||||
onDismiss = {},
|
||||
onModeChange = {},
|
||||
onClearError = {},
|
||||
transcriptMessages = MockChat.voiceThread,
|
||||
showThinking = true,
|
||||
voiceEngineMode = "hermes_voice_output",
|
||||
voiceOutputProvider = "OpenAI",
|
||||
voiceOutputModel = "gpt-4o-mini-tts",
|
||||
voiceOutputVoice = "alloy",
|
||||
voiceProfileName = "default",
|
||||
voiceOutputEnabled = true,
|
||||
voiceOutputFallbackEnabled = true,
|
||||
presentationMode = VoicePresentationMode.Focus,
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun VoiceConversationScene() = StoreCockpit(
|
||||
contextUsage = 0.05f,
|
||||
conversationVoiceState = marketingVoiceUiState,
|
||||
) {
|
||||
BlendThread()
|
||||
}
|
||||
|
||||
/** The real sphere renderer pinned to one frame for pixel-identical marketing output. */
|
||||
private object FrozenMarketingSphere : AgentAvatar {
|
||||
override val id = "marketing-sphere"
|
||||
override val label = "Sphere"
|
||||
override val description = "Deterministic marketing renderer"
|
||||
override val source = AvatarSource.BUILT_IN
|
||||
override val reactivity = SphereReactivity(voice = true, tools = true, intensity = true, gaze = false)
|
||||
|
||||
@Composable
|
||||
override fun Render(state: AvatarRenderState, modifier: Modifier) {
|
||||
MorphingSphere(
|
||||
modifier = modifier,
|
||||
state = state.state,
|
||||
intensity = state.intensity,
|
||||
toolCallBurst = state.toolCallBurst,
|
||||
voiceAmplitude = state.voiceAmplitude,
|
||||
voiceMode = state.voiceMode,
|
||||
fixedTime = 5f,
|
||||
fixedColorPhase = 1f,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Production chat chrome and production app-level companion layered exactly as RelayApp does. */
|
||||
@Composable
|
||||
private fun ChatWithPetScene(pet: AgentAvatar) {
|
||||
Box(Modifier.fillMaxSize()) {
|
||||
BlendChatScene()
|
||||
FloatingPetCompanion(
|
||||
pet = pet,
|
||||
state = AvatarRenderState(state = SphereState.Idle, paused = true),
|
||||
placement = PetPlacement(PetLogicalEdge.End, 0.93f),
|
||||
roamingEnabled = false,
|
||||
roamingAllowed = false,
|
||||
behaviorPreferences = PetBehaviorPreferences(sizeScale = 1.05f),
|
||||
surfaceScrolling = false,
|
||||
compact = true,
|
||||
animationEnabled = false,
|
||||
appForeground = true,
|
||||
route = null,
|
||||
visitRequest = null,
|
||||
onVisitRequestConsumed = {},
|
||||
onPlacementChanged = {},
|
||||
onRoamingEnabledChanged = {},
|
||||
onResetPlacement = {},
|
||||
onHide = {},
|
||||
onOpenAppearance = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val marketingVoiceUiState = VoiceUiState(
|
||||
voiceMode = true,
|
||||
state = VoiceState.Listening,
|
||||
amplitude = 0.42f,
|
||||
interactionMode = InteractionMode.Continuous,
|
||||
)
|
||||
|
||||
|
||||
@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun ManageScene() {
|
||||
@@ -417,7 +616,7 @@ private fun ManageScene() {
|
||||
com.hermesandroid.relay.ui.components.RelayNavTile(ic.Tune, "Models", "Pick provider + default model", {})
|
||||
}
|
||||
}
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.5 / profile: default")
|
||||
RelayStatusStrip(leading = "⚡ Gateway · LAN", trailing = "gpt-5.6-sol / profile: default")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,26 +650,44 @@ private object MockChat {
|
||||
outputTokens = 206
|
||||
)
|
||||
|
||||
val voiceThread = listOf(
|
||||
ChatMessage(
|
||||
id = "voice-user",
|
||||
role = MessageRole.USER,
|
||||
content = "Give me the quick version of today's project changes.",
|
||||
timestamp = 0L,
|
||||
),
|
||||
ChatMessage(
|
||||
id = "voice-assistant",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "Appearance is more flexible, pets can roam safely, and voice now keeps the conversation visible while you work hands-free.",
|
||||
timestamp = 0L,
|
||||
agentName = "Hermes",
|
||||
badges = listOf("Voice"),
|
||||
),
|
||||
)
|
||||
|
||||
// A grouped thread for the "Blend" capture: user → two-message assistant
|
||||
// group (avatar once, code block in the first) → user follow-up.
|
||||
val blendThread = listOf(
|
||||
ChatMessage(
|
||||
id = "bu1",
|
||||
role = MessageRole.USER,
|
||||
content = "How do I deploy to prod? Walk me through it.",
|
||||
content = "How should I handle a flaky network call?",
|
||||
timestamp = 0L,
|
||||
),
|
||||
ChatMessage(
|
||||
id = "ba1",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = """
|
||||
Run the deploy script — it stages the build, applies migrations, then ships. It's idempotent, so re-running after a failure is safe:
|
||||
Use bounded exponential backoff and retry only transient failures:
|
||||
|
||||
```bash
|
||||
./scripts/deploy.sh prod --yes
|
||||
```kotlin
|
||||
val delayMs = minOf(1_000L shl attempt, 8_000L)
|
||||
delay(delayMs)
|
||||
```
|
||||
|
||||
Use `--dry-run` first if you want to preview the migration plan.
|
||||
Keep the retry budget small, add a timeout, and surface the final error clearly.
|
||||
""".trimIndent(),
|
||||
timestamp = 0L,
|
||||
agentName = "Hermes",
|
||||
@@ -479,7 +696,7 @@ private object MockChat {
|
||||
ChatMessage(
|
||||
id = "ba2",
|
||||
role = MessageRole.ASSISTANT,
|
||||
content = "Want me to tail the logs once it's live and ping you if anything errors?",
|
||||
content = "Want me to adapt this to the networking layer in your project?",
|
||||
timestamp = 0L,
|
||||
inputTokens = 138_010,
|
||||
outputTokens = 212,
|
||||
@@ -487,7 +704,7 @@ private object MockChat {
|
||||
ChatMessage(
|
||||
id = "bu2",
|
||||
role = MessageRole.USER,
|
||||
content = "Yes please — keep an eye on the error rate.",
|
||||
content = "Yes — keep cancellation and offline mode intact.",
|
||||
timestamp = 0L,
|
||||
),
|
||||
)
|
||||
@@ -499,133 +716,73 @@ private object MockChat {
|
||||
|
||||
@Composable
|
||||
private fun SessionsScene() {
|
||||
Column(
|
||||
Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface).padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Text("Server default sessions", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface)
|
||||
Text("Connection: Hermes", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Surface(color = MaterialTheme.colorScheme.primary, shape = RoundedCornerShape(24.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.padding(vertical = 14.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Add, null, tint = MaterialTheme.colorScheme.onPrimary)
|
||||
Text(" New Chat", color = MaterialTheme.colorScheme.onPrimary, fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
Surface(color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f), shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Row(Modifier.padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Search, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
|
||||
Text(" Search sessions or id…", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
FilterChip("All", true); FilterChip("Pinned", false); FilterChip("Archive", false)
|
||||
}
|
||||
SessionRow("Morning focus tips", "Active 4m ago", "2 msgs")
|
||||
SessionRow("Weekly report draft", "Active 18m ago", "11 msgs")
|
||||
SessionRow("Trip planning", "Active 1h ago", "23 msgs")
|
||||
SessionRow("Code review notes", "Active 3h ago", "6 msgs")
|
||||
SessionRow("Recipe ideas", "Active 5h ago", "9 msgs")
|
||||
SessionRow("Untitled", "Active yesterday", "1 msg")
|
||||
// The production drawer intentionally caps itself at 320dp inside a wider
|
||||
// phone. Keep the full app viewport as the capture root so Roborazzi does
|
||||
// not shrink-wrap the image to the drawer's intrinsic width.
|
||||
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.scrim)) {
|
||||
SessionDrawerContent(
|
||||
sessions = marketingSessions,
|
||||
currentSessionId = "morning-focus",
|
||||
scopeTitle = "Hermes",
|
||||
scopeSubtitle = "Server default sessions",
|
||||
animationEnabled = false,
|
||||
threadsCapabilityActive = true,
|
||||
onNewThread = {},
|
||||
onNewChat = {},
|
||||
onSelectSession = {},
|
||||
onDeleteSession = {},
|
||||
onRenameSession = { _, _ -> },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FilterChip(label: String, selected: Boolean) {
|
||||
Surface(
|
||||
color = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f) else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.labelMedium, color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 6.dp))
|
||||
}
|
||||
}
|
||||
private fun ConnectionsScene() = ConnectionsSettingsScreen(
|
||||
connections = marketingConnections,
|
||||
activeConnectionId = "home",
|
||||
activeRelayUiState = RelayUiState.Connected,
|
||||
onOpenConnection = {},
|
||||
onAddConnection = {},
|
||||
onBack = {},
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun SessionRow(title: String, active: String, msgs: String) {
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(title, style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text("$active · $msgs", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
Icon(Icons.Filled.Star, null, tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f), modifier = Modifier.size(20.dp))
|
||||
Icon(Icons.Filled.MoreVert, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 12.dp))
|
||||
}
|
||||
}
|
||||
private val marketingSessions = listOf(
|
||||
ChatSession("morning-focus", "Morning focus tips", "gpt-5.6-sol", 8, lastActivityAt = 1_780_000_000_000, pinned = true),
|
||||
ChatSession("android-polish", "Android appearance polish", "gpt-5.6-sol", 23, lastActivityAt = 1_779_999_900_000, source = "phone"),
|
||||
ChatSession("weekly-report", "Weekly report draft", "gpt-5.6-sol", 11, lastActivityAt = 1_779_999_800_000),
|
||||
ChatSession("voice-notes", "Voice workflow notes", "gpt-5.6-sol", 17, lastActivityAt = 1_779_999_700_000),
|
||||
ChatSession("trip-planning", "Trip planning", "gpt-5.6-sol", 31, lastActivityAt = 1_779_999_600_000),
|
||||
)
|
||||
|
||||
@Composable
|
||||
private fun ConnectionsScene() = StoreSettings("Connections") {
|
||||
// Level-1 list: scannable connection cards, the active one badged, each
|
||||
// with the capability timeline. Tapping opens the tabbed detail.
|
||||
ConnCard(label = "Hermes", active = true, status = "Connected · Tailscale") {
|
||||
FeatureRow("API", "Ready", true)
|
||||
FeatureRow("Dashboard", "Signed in", true)
|
||||
FeatureRow("Voice", "Ready", true)
|
||||
FeatureRow("Relay", "Connected", true)
|
||||
}
|
||||
ConnCard(label = "Lab NAS", active = false, status = "Paired 2 days ago") {
|
||||
FeatureRow("API", "Configured", false)
|
||||
FeatureRow("Dashboard", "Unchecked", false)
|
||||
FeatureRow("Voice", "Optional", false)
|
||||
FeatureRow("Relay", "Paired", true)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConnCard(
|
||||
label: String,
|
||||
active: Boolean,
|
||||
status: String,
|
||||
rows: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
color = if (active) {
|
||||
RelayRefresh.ElectricMuted.copy(alpha = 0.42f)
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceVariant
|
||||
},
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (active) com.hermesandroid.relay.ui.components.RelayStatusPill("Active", active = true)
|
||||
Icon(
|
||||
androidx.compose.material.icons.Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(start = 4.dp),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
status,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Surface(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.4f),
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Column(Modifier.padding(vertical = 4.dp), content = rows)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FeatureRow(name: String, status: String, ok: Boolean) {
|
||||
Row(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.size(8.dp).clip(CircleShape).background(if (ok) RelayRefresh.Green else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)))
|
||||
Text(" $name", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.weight(1f))
|
||||
Text(status, style = MaterialTheme.typography.labelMedium, color = if (ok) RelayRefresh.Green else MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
private val marketingConnections = listOf(
|
||||
Connection(
|
||||
id = "home",
|
||||
label = "Hermes",
|
||||
apiServerUrl = "https://hermes.example.com:8642",
|
||||
relayUrl = "wss://hermes.example.com:8767",
|
||||
dashboardUrl = "https://hermes.example.com:9119",
|
||||
tokenStoreKey = "marketing-home",
|
||||
dashboardAuthRequired = true,
|
||||
dashboardLastStatus = DashboardConnectionStatus(
|
||||
reachable = true,
|
||||
authenticated = true,
|
||||
gatewayTicketAvailable = true,
|
||||
gatewayMode = "gateway",
|
||||
profiles = listOf("default", "work"),
|
||||
),
|
||||
transportHint = "tailscale",
|
||||
pairedAt = 1_779_900_000_000,
|
||||
),
|
||||
Connection(
|
||||
id = "lab",
|
||||
label = "Lab server",
|
||||
apiServerUrl = "https://lab.example.com:8642",
|
||||
relayUrl = "wss://lab.example.com:8767",
|
||||
dashboardUrl = "https://lab.example.com:9119",
|
||||
tokenStoreKey = "marketing-lab",
|
||||
pairedAt = 1_779_800_000_000,
|
||||
),
|
||||
)
|
||||
|
||||
// NOTE: scenes 05 + 08 render the REAL AppearanceSettingsScreen (1:1, see the
|
||||
// s05_themes / s08_appearance test methods). The earlier hand-built theme/skin
|
||||
|
||||
@@ -160,7 +160,7 @@ class AgentPassportSheetTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun downwardGestureAtTop_dismissesSheet() {
|
||||
fun boundaryGesture_doesNotCompeteWithFullHeightSheet() {
|
||||
var dismissals = 0
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
@@ -176,7 +176,8 @@ class AgentPassportSheetTest {
|
||||
compose.onNodeWithTag(AGENT_PASSPORT_SCROLL_TAG)
|
||||
.performTouchInput { swipeDown() }
|
||||
|
||||
compose.waitUntil(timeoutMillis = 5_000) { dismissals == 1 }
|
||||
compose.runOnIdle { assertEquals(0, dismissals) }
|
||||
compose.onNodeWithTag(AGENT_PASSPORT_SHEET_TAG).assertIsDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.test.assertIsFocused
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithTag
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.test.performImeAction
|
||||
import androidx.compose.ui.test.performKeyInput
|
||||
import androidx.compose.ui.test.performTextInput
|
||||
import androidx.compose.ui.test.pressKey
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
class ChatInputBarTest {
|
||||
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `hardware enter submits through the composer action`() {
|
||||
var sent = 0
|
||||
setComposer(value = "Hello") { sent++ }
|
||||
|
||||
input().performClick().performKeyInput { pressKey(Key.Enter) }
|
||||
|
||||
compose.runOnIdle { assertEquals(1, sent) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `shift enter inserts a newline without submitting`() {
|
||||
var value = "Hello"
|
||||
var sent = 0
|
||||
setComposer(value = value, onValueChange = { value = it }) { sent++ }
|
||||
|
||||
input().performClick().performKeyInput {
|
||||
keyDown(Key.ShiftLeft)
|
||||
pressKey(Key.Enter)
|
||||
keyUp(Key.ShiftLeft)
|
||||
}
|
||||
|
||||
compose.runOnIdle {
|
||||
assertEquals("Hello\n", value)
|
||||
assertEquals(0, sent)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `plain enter inserts newline when configured while ctrl enter submits`() {
|
||||
var value = "Hello"
|
||||
var sent = 0
|
||||
setComposer(
|
||||
value = value,
|
||||
onValueChange = { value = it },
|
||||
physicalEnterSends = false,
|
||||
) { sent++ }
|
||||
|
||||
input().performClick().performKeyInput { pressKey(Key.Enter) }
|
||||
compose.runOnIdle {
|
||||
assertEquals("Hello\n", value)
|
||||
assertEquals(0, sent)
|
||||
}
|
||||
|
||||
input().performKeyInput {
|
||||
keyDown(Key.CtrlLeft)
|
||||
pressKey(Key.Enter)
|
||||
keyUp(Key.CtrlLeft)
|
||||
}
|
||||
compose.runOnIdle { assertEquals(1, sent) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hardware submit preserves steer action`() {
|
||||
var submitted = 0
|
||||
setComposer(value = "Correct this", trailing = ChatInputTrailing.STEER) { submitted++ }
|
||||
|
||||
input().performClick().performKeyInput { pressKey(Key.Enter) }
|
||||
|
||||
compose.runOnIdle { assertEquals(1, submitted) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `steer state is named visibly and not only by color`() {
|
||||
setComposer(
|
||||
value = "Correct this",
|
||||
trailing = ChatInputTrailing.STEER,
|
||||
caption = "Sends into the active response",
|
||||
)
|
||||
|
||||
compose.onNodeWithText("Correct the response").assertExists()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `hardware submit preserves queue action`() {
|
||||
var submitted = 0
|
||||
setComposer(value = "Follow up", trailing = ChatInputTrailing.QUEUE) { submitted++ }
|
||||
|
||||
input().performClick().performKeyInput { pressKey(Key.Enter) }
|
||||
|
||||
compose.runOnIdle { assertEquals(1, submitted) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `queue state is named visibly and not only by icon`() {
|
||||
setComposer(
|
||||
value = "Follow up",
|
||||
trailing = ChatInputTrailing.QUEUE,
|
||||
caption = "Delivers after this turn",
|
||||
)
|
||||
|
||||
compose.onNodeWithText("Queue message").assertExists()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `arrow keys keep focus and move the text caret`() {
|
||||
var value = "abc"
|
||||
setComposer(value = value, onValueChange = { value = it })
|
||||
|
||||
input().performClick().performKeyInput { pressKey(Key.DirectionLeft) }
|
||||
input().assertIsFocused().performTextInput("X")
|
||||
|
||||
compose.runOnIdle { assertEquals("abXc", value) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ime send uses the same composer action`() {
|
||||
var sent = 0
|
||||
setComposer(value = "Hello") { sent++ }
|
||||
|
||||
input().performClick().performImeAction()
|
||||
|
||||
compose.runOnIdle { assertEquals(1, sent) }
|
||||
}
|
||||
|
||||
private fun setComposer(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit = {},
|
||||
trailing: ChatInputTrailing = ChatInputTrailing.SEND,
|
||||
physicalEnterSends: Boolean = true,
|
||||
caption: String? = null,
|
||||
onSend: () -> Unit = {},
|
||||
) {
|
||||
var currentValue by mutableStateOf(value)
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
ChatInputBar(
|
||||
value = currentValue,
|
||||
onValueChange = {
|
||||
currentValue = it
|
||||
onValueChange(it)
|
||||
},
|
||||
placeholder = "Message",
|
||||
trailing = trailing,
|
||||
onSend = onSend,
|
||||
onVoice = {},
|
||||
onStop = {},
|
||||
onAttachPhotos = {},
|
||||
onAttachFiles = {},
|
||||
onAttachCamera = {},
|
||||
onPasteImage = {},
|
||||
onLongPressAttach = {},
|
||||
charLimit = 4_000,
|
||||
caption = caption,
|
||||
voiceReady = true,
|
||||
showVoiceHint = false,
|
||||
onVoiceHintShown = {},
|
||||
isDarkTheme = false,
|
||||
physicalEnterSends = physicalEnterSends,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun input() = compose.onNodeWithTag(CHAT_INPUT_FIELD_TEST_TAG)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.hermesandroid.relay.ui.components
|
||||
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.test.assertHasClickAction
|
||||
import androidx.compose.ui.test.assertHeightIsAtLeast
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertWidthIsAtLeast
|
||||
import androidx.compose.ui.test.junit4.v2.createComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithContentDescription
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import com.hermesandroid.relay.data.ChatQuoteReference
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.annotation.GraphicsMode
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
@GraphicsMode(GraphicsMode.Mode.NATIVE)
|
||||
@Config(qualifiers = "w360dp-h720dp-xhdpi")
|
||||
class ChatQuoteReferenceChipTest {
|
||||
@get:Rule
|
||||
val compose = createComposeRule()
|
||||
|
||||
@Test
|
||||
fun `chip colors use semantic readable roles in light and dark themes`() {
|
||||
listOf(
|
||||
lightColorScheme(),
|
||||
darkColorScheme(),
|
||||
lightColorScheme(primary = Color.Yellow, onPrimary = Color.Black),
|
||||
darkColorScheme(primary = Color.Magenta, onPrimary = Color.Black),
|
||||
).forEach { scheme ->
|
||||
val colors = chatQuoteReferenceColors(scheme)
|
||||
|
||||
assertEquals(scheme.surfaceContainerHigh, colors.background)
|
||||
assertEquals(scheme.onSurface, colors.author)
|
||||
assertEquals(scheme.onSurfaceVariant, colors.excerpt)
|
||||
assertEquals(scheme.primary, colors.accent)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `chip highlights author opens original and exposes accessible remove`() {
|
||||
var opens = 0
|
||||
var removes = 0
|
||||
compose.setContent {
|
||||
MaterialTheme {
|
||||
ChatQuoteReferenceChip(
|
||||
reference = ChatQuoteReference("message-1", "Hermes", "Original answer"),
|
||||
onOpenOriginal = { opens++ },
|
||||
onRemove = { removes++ },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compose.onNodeWithText("@Hermes").assertIsDisplayed()
|
||||
compose.onNodeWithText("Original answer").assertIsDisplayed()
|
||||
compose.onNodeWithContentDescription("Open original message from Hermes. Original answer")
|
||||
.assertHasClickAction()
|
||||
.performClick()
|
||||
compose.onNodeWithContentDescription("Remove quote")
|
||||
.assertWidthIsAtLeast(48.dp)
|
||||
.assertHeightIsAtLeast(48.dp)
|
||||
.performClick()
|
||||
|
||||
compose.runOnIdle {
|
||||
assertEquals(1, opens)
|
||||
assertEquals(1, removes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,64 @@ class FloatingPetCompanionTest {
|
||||
assertTrue(shouldDockFloatingPet(roamingEnabled = true, roamingAllowed = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `paused chat pet follows the live composer dock`() {
|
||||
val manual = PetPoint(40f, 900f)
|
||||
val roaming = PetPoint(320f, 540f)
|
||||
val composerBeforeIme = PetPoint(320f, 820f)
|
||||
val composerWithIme = PetPoint(320f, 430f)
|
||||
|
||||
assertEquals(
|
||||
composerBeforeIme,
|
||||
floatingPetHomePoint(
|
||||
route = "chat",
|
||||
roamingEnabled = false,
|
||||
roamingAllowed = true,
|
||||
manualHomePoint = manual,
|
||||
roamingHomePoint = roaming,
|
||||
pausedChatDockPoint = composerBeforeIme,
|
||||
),
|
||||
)
|
||||
assertEquals(
|
||||
composerWithIme,
|
||||
floatingPetHomePoint(
|
||||
route = "chat",
|
||||
roamingEnabled = false,
|
||||
roamingAllowed = true,
|
||||
manualHomePoint = manual,
|
||||
roamingHomePoint = roaming,
|
||||
pausedChatDockPoint = composerWithIme,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `active roaming and non-chat docking retain their existing homes`() {
|
||||
val manual = PetPoint(40f, 900f)
|
||||
val roaming = PetPoint(320f, 540f)
|
||||
val composer = PetPoint(320f, 820f)
|
||||
|
||||
assertEquals(
|
||||
roaming,
|
||||
floatingPetHomePoint("chat", true, true, manual, roaming, composer),
|
||||
)
|
||||
assertEquals(
|
||||
manual,
|
||||
floatingPetHomePoint("settings", false, true, manual, roaming, composer),
|
||||
)
|
||||
assertEquals(
|
||||
manual,
|
||||
floatingPetHomePoint(null, true, false, manual, roaming, composer),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `paused chat dock exposes only meaningful movement axes`() {
|
||||
assertFalse(floatingPetAllowsVerticalMoveActions("chat", roamingEnabled = false))
|
||||
assertTrue(floatingPetAllowsVerticalMoveActions("chat", roamingEnabled = true))
|
||||
assertTrue(floatingPetAllowsVerticalMoveActions("settings", roamingEnabled = false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `behavior director applies user agent response roam idle priority`() {
|
||||
assertEquals(
|
||||
|
||||