Flush throttled reasoning before state-transition events (MessageStart/
Complete/Done/ToolStart) so a reasoning delta arriving just before a
transition is not dropped. Also compare reasoningText in sameMessages so
a reasoning-only restore actually re-merges.
- ChatStreamingController.flushPendingReasoning() forces a synchronous flush
- handleWsEvent calls it for the transition events
- sameMessages now includes reasoningText in its equality check
- tests: ChatStreamingControllerTest (flush + no-resurrect), reasoning survives
MessageDone after an unflushed delta
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Fix active saved profile visibility in Catppuccin light mode and Monochrome light/dark modes by adjusting primaryContainer contrast and adding a primary border stroke.
* fix(mcp): make Add Server + Catalog headers read distinctly from buttons
Both section headers reused the shared SectionHeader, which paints the
title in primary/bold — so each header row looked like a tappable
button next to its trailing TextButton. Add a scoped McpSectionHeader
with a distinct leading icon (➕ Add / 🗄 Explore) and a neutral
onSurface bold title, so they read as headers and look different
from each other.
* fix(mcp): give section header row + action button distinct backgrounds
- Whole header row now sits on a surfaceContainerLow rounded (12dp) surface
so it reads as a contained section header, not bare text.
- The trailing New/Browse action uses secondaryContainer (onSecondaryContainer
text) — a clearly different color from the row background, so button
vs header are visually distinct.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(keys): overhaul Keys screen UI and UX
Fix card padding alignment, add delete confirmation dialog, add FAB with AddKeyDialog, support copying revealed values, add status badges, and pin restart banner.
* fix(keys): fix scaffold actions parameter and missing string resource
Resolve compilation errors in KeysScreen by removing floatingActionButton from HermesScaffold and adding missing keys_action_open_url resource.
* feat(keys): replace dropdown headers with horizontal category filter chips
Add CategoryFilterBar featuring horizontal FilterChips for quick category filtering (All, LLM Providers, Tool API Keys, Messaging Platforms, Agent Settings) with total key counts.
* style(keys): enhance key card padding, spacing, borders, and surface contrast
Use surfaceContainerLow with subtle outlineVariant border and 16dp rounded corners for high contrast cards, and set 12dp list spacing between cards.
* fix(keys): wrap key title and status badge in FlowRow to prevent layout overflow on long key names
Prevent status badge from squishing or overflowing when displaying long API key names by using a FlowRow that wraps gracefully.
* fix(keys): add file-level OptIn for ExperimentalLayoutApi
Fix compilation error by adding @file:OptIn(ExperimentalLayoutApi::class, ExperimentalMaterial3Api::class) to KeysScreen.kt.
* fix(keys): fully qualify class names in file-level OptIn annotation
Fix unresolved reference build error by fully qualifying ExperimentalMaterial3Api and ExperimentalLayoutApi in @file:OptIn before package statement.
* fix(keys): remove invalid verticalAlignment parameter from FlowRow
* fix(keys): optimize long API key name readability and wrapping
Insert zero-width spaces after underscores to ensure clean word-boundary wrapping, add adaptive typography (titleSmall with 20sp line height for long names), and stack StatusBadge cleanly below the title.
* feat(keys): make API key names and values single-line and horizontally scrollable
Enforce singleLine=true / maxLines=1 with horizontalScroll(rememberScrollState()) for both key names and revealed key values so cards remain compact with uniform heights.
* feat(keys): keep single-line scrollable key values and clean multi-line key names
Keep secret key values single-line and horizontally scrollable, while restoring clean multi-line word-boundary breaking (at underscores) for key names.
* style(keys): format KeysScreen.kt with ktlint
Tighten FilledTonalButton contentPadding on the MCP server card action
row so the Restart label fits beside the icon in the weighted half-width
slot (default 24dp horizontal padding was eating the text).
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(skills): redesign tab switcher and fix status filter alignment and card padding
* fix(skills): replace status filter chips with SingleChoiceSegmentedButtonRow for precise alignment
* fix(skills): left-align status, category, and source filter chip rows
* fix(skills): explicitly left-align status FilterChips with 16dp start margin
* fix(skills): match status filter chip row styling and All label to category row below it
* fix(skills): remove extra Row wrapper padding from status filter chips in SkillsScreen
* feat(skills): enhance card background contrast and reduce side padding for Installed and Hub cards
* feat(skills): reduce card/search padding to 8dp and pin top controls with weight(1f) on LazyColumn
* style(skills): fix ktlint import-ordering and remove unused imports (PR #704)
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* perf: optimize synchronous I/O in AuthLoginViewModel
Replace blocking OkHttp .execute() with a suspending .await() extension
(CallExt.kt) backed by suspendCancellableCoroutine, freeing Dispatchers.IO
threads during network waits. Probe/connect paths made suspend.
- Call.await() guards both onResponse/onFailure with continuation.isActive
to avoid AlreadyResume on cancellation.
- Removes non-asserting AuthLoginViewModelBenchmark timing dump.
* perf: optimize synchronous I/O in AuthLoginViewModel
Replaced the blocking `.execute()` OkHttp calls with a suspending `.await()` extension function inside `AuthLoginViewModel`. This frees up the `Dispatchers.IO` threads by deferring the blocking operations to OkHttp's internal task runner, providing a safer async approach and preventing Thread pool starvation on slow network responses.
Modified `probeDashboardInternal` and `connectBasicAuth` to be proper `suspend` functions and resolved corresponding unit tests.
* fix(test): add missing import io.mockk.any in AuthLoginViewModelTest
* fix(test): fix mockk imports and Log matchers in AuthLoginViewModelTest
* fix(test): use persistent mockProbeClient in AuthLoginViewModelTest
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
In gated mode (basic-auth cookie flow) the dashboard 401s any request that
carries an Authorization: Bearer header alongside the valid session cookie
(verified live 2026-07-23). ApiClient.authInterceptor stamped the WS ticket
as a Bearer header on every REST call, so every non-chat tab (skills, cron,
config, tools, mcp, ...) failed with "token expired" while the WS chat
(?ticket=) kept working.
- Add AuthManager.isGatedMode() (wsAuthParam == "ticket").
- authInterceptor skips the Bearer header in gated mode; loopback/token
behavior unchanged.
- TokenRefreshAuthenticator bails in gated mode instead of attempting the
loopback-only SPA token refresh.
- ApiClientTest: add gated/loopback regression tests. 7/7 pass, ktlint clean.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* test: add comprehensive tests for loadSettings in SettingsViewModel
Adds `testLoadSettings_loadsAllProperties` to `SettingsViewModelTest.kt` to thoroughly verify that `loadSettings()` correctly maps all required settings properties from `AuthManager` to the `uiState`. The test utilizes `runTest` and `advanceUntilIdle()` to properly handle testing the coroutine launch in the ViewModel's init block.
* test: add comprehensive tests for loadSettings in SettingsViewModel
Adds `testLoadSettings_loadsAllProperties` to `SettingsViewModelTest.kt` to thoroughly verify that `loadSettings()` correctly maps all required settings properties from `AuthManager` to the `uiState`. The test utilizes `runTest` and `advanceUntilIdle()` to properly handle testing the coroutine launch in the ViewModel's init block. Fixes ktlint formatting issues on imports.
* Add edge case testing for DashboardSessionTokenRefresher
Added tests to `DashboardSessionTokenRefresherTest.kt` to cover
cases where `refresh()` catches exceptions or where `fetch()`
returns null. Included a happy-path test for `refresh()`.
* Add edge case testing for DashboardSessionTokenRefresher
Added tests to `DashboardSessionTokenRefresherTest.kt` to cover
cases where `refresh()` catches exceptions or where `fetch()`
returns null. Included a happy-path test for `refresh()`.
* 🧪 test: Add mapping tests for ChatMessageEntity to/from ChatMessage
* Added comprehensive tests to `ChatMessageMapperTest.kt` verifying the pure mappings between Room database entities (`ChatMessageEntity`) and UI models (`ChatMessage`).
* Verified fallback logics for enums (MessageRole and ToolStatus).
* Ensures regression prevention when underlying data models change.
* 🧪 test: Refactor mapper boolean assertions to assertTrue/assertFalse
* Changed assertEquals(true/false, isStreaming) to assertTrue/assertFalse
as suggested in the review.
* perf: Hoist regexes in MarkdownText.kt to avoid recompilation
Resolves a performance issue where `bulletRe`, `taskRe`, and `orderedRe`
were instantiated and compiled inside the `parseBlocks` function on every
call, causing unnecessary overhead during repeated markdown parsing (e.g.,
when chat messages stream in).
These regex objects have been hoisted to file-level `private val`
constants (`BULLET_RE`, `TASK_RE`, `ORDERED_RE`), ensuring they are compiled
only once when the class is loaded.
A benchmark `MarkdownTextBenchmark.kt` was added to verify the
performance change, showing an approximate 50ms improvement over 10k
iterations.
* perf: Hoist regexes in MarkdownText.kt to avoid recompilation
Resolves a performance issue where `bulletRe`, `taskRe`, and `orderedRe`
were instantiated and compiled inside the `parseBlocks` function on every
call, causing unnecessary overhead during repeated markdown parsing (e.g.,
when chat messages stream in).
These regex objects have been hoisted to file-level `private val`
constants (`BULLET_RE`, `TASK_RE`, `ORDERED_RE`), ensuring they are compiled
only once when the class is loaded.
A benchmark `MarkdownTextBenchmark.kt` was added to verify the
performance change, showing an approximate 50ms improvement over 10k
iterations.
* perf: Hoist regexes in MarkdownText.kt to avoid recompilation
Resolves a performance issue where `bulletRe`, `taskRe`, and `orderedRe`
were instantiated and compiled inside the `parseBlocks` function on every
call, causing unnecessary overhead during repeated markdown parsing (e.g.,
when chat messages stream in).
These regex objects have been hoisted to file-level `private val`
constants (`BULLET_RE`, `TASK_RE`, `ORDERED_RE`), ensuring they are compiled
only once when the class is loaded.
A benchmark `MarkdownTextBenchmark.kt` was added to verify the
performance change, showing an approximate 50ms improvement over 10k
iterations.
* Test ServerCollectionOps data manipulation utilities
Added comprehensive unit tests for `ServerCollectionOps.kt` to cover all scenarios for `addOrUpdate`, `selfHealed`, and resolution properties (`resolvedBaseUrl`, `resolvedHost`, `resolvedPort`). Also updated the function name `addOrReplaceServer` to `addOrUpdate` to match the intended signature in the issue description, and updated affected call sites.
* Fix ktlint formatting issues and ensure build succeeds
Fixed ktlint errors in `ServerCollectionOpsTest.kt` by correctly formatting arguments and expressions to comply with project style guidelines. Ran `assembleDebug` and tests locally to verify build health.
* test: add unit tests for ChatPersistenceRepository
Added ChatPersistenceRepositoryTest to verify the repository
correctly delegates to the ChatMessageDao and maps between
ChatMessage UI models and Room entity objects. Uses the
existing FakeChatMessageDao for reliable in-memory testing.
* test: fix ktlint issues in ChatPersistenceRepositoryTest
Formatted ChatPersistenceRepositoryTest to comply with standard
ktlint rules for the project.
* test: enhance ChatPersistenceRepositoryTest coverage
Added role and content assertions to `persistMessages_upsertsAllToDao`
and added a new `loadMessages_filtersBySessionId` test to verify
session isolation per PR feedback.
* fix(#688): route expired auth sessions to sign-in
Adopt global 401 latch, WS disconnect, and Back/profile guards.
* chore: clean up formatting noise
* fix(ktlint): reorder imports to place java and kotlinx at end
* fix(ktlint): place java.io.IOException at end of imports
* test: fix NavBackStack type parameter in AuthenticationRoutingTest
* test: add AuthSessionState tests to AuthLoginViewModelTest
* fix(ktlint): fix import order in AuthLoginViewModelTest
* fix(#686): implement robust history pagination
Honor server-returned offset, degrade gracefully on older servers, and parse JSON tool results.
* fix(ci): repair unit-test compilation and pagination test mocks
- Remove trailing blank line in SessionMessagesResponse.kt (ktlint)
- Replace unresolved io.mockk.eq/coAnswers usage in ChatViewModelTest with
an ordered-call counter inside coAnswers, which compiles and runs on
MockK 1.14.11 (eq is a matcher-scope member, not a top-level import)
- Align HermesApiServiceMockWebServerTest with the PR's JsonElement content
model (contentText) and the new include_compacted=true default query param
All unit tests pass locally with the ByteBuddy agent preload.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Introduce ChatScrollController owning all chat scroll behavior:
- continuous bottom-follow intent tracked from LazyListState (not only on data change)
- pixel-precise bottom detection (last item edge vs viewport, small tolerance)
- streaming follow that pauses on upward scroll and never forces the reader down
- tail updates keyed on messages/streaming/thinking/subagent/clarify
- unread (new-message) count shown on the scroll-to-bottom FAB, cleared on tap
- paging anchor preserved by message id across older-history prepend
- all scroll commands (send/FAB/session switch/search/paging) serialized via one scope
Closes#682
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(navigation): regroup Kanban to AUTOMATE and Gateway to INSPECT in navigation drawer
* feat(navigation): change Achievements screen icon to EmojiEvents (trophy)
* perf(model): optimize model tab load speed with two-phase fetch and loadQuick
* perf: optimize data loading across Config, System, Profiles, and Billing tabs
* chore: remove leftover bottom nav references and unused updatePrimaryScreens
* style: fix ktlint violations in Config/Profiles/Billing ViewModels
- property/argument-list wrapping for async(...) calls
- multiline-expression wrapping for async blocks
- remove unused import in ConfigViewModel
- break long error-message string literals to stay under 120 cols
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* ui: input bar reasoning chip tweaks
- Remove emoji from reasoning level labels (dropdown + chip text)
- Reduce reasoning chip horizontal padding (8dp -> 4dp)
- Move reasoning chip to right side (after spacer, next to mic)
- Increase model chip minimum width (120dp -> 140dp)
- Remove unused width import
* fix(ui): add missing widthIn import in ComposerToolbar
Resolves 'Unresolved reference widthIn' compile error at
ComposerToolbar.kt:95 that broke CI (unit-tests, android-lint,
instrumented-tests all fail on compileDebugKotlin).
* ui(chat): enhance input bar layout, reasoning menu header, and card shadow
Give ChatInputBar a floating rounded container with shadow contrast. Make model chip take available space and add header to reasoning menu.
* fix(ui): remove trailing blank line in ComposerToolbar for ktlint
Fix standard:no-consecutive-blank-lines ktlint violation.
* ui(model): enhance ModelPickerDialog with rounded cards and provider badges
Apply card styling, rounded corners (24dp dialog, 12dp cards), provider badges, and shadow contrast to ModelPickerDialog.
* feat(model): add in-dialog model pinning to ModelPickerDialog
Add pin/unpin icon buttons to model cards in ModelPickerDialog across both ModelScreen and ChatScreen.
* ui(model): remove provider badge chip and eliminate bottom whitespace in ModelPickerDialog
Replace bottom Cancel button with top-right Close icon to eliminate bottom whitespace. Remove inline provider badge chip from model cards.
* perf(model): optimize ModelPickerDialog load time with lazy items and O(1) set lookup
Lazy-register individual model items in LazyColumn and memoize pinnedSet to prevent synchronous rendering lag when opening dialog.
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
When the initial REST page returns empty messages, hasOlderMessages
was still set to true (offset > 0), causing an infinite loop of empty
load-more requests. Guard with && chatMessages.isNotEmpty().
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* feat(chat): rich message bubbles with reasoning, code, clarify, subagent cards (#659#660#661#662#663#664)
* fix(chat): render ClarifyBubble at bottom of message list, not as inline SYSTEM message
Fixes two on-device bugs:
1. ClarifyBubble now renders at the very bottom of the LazyColumn
(after all messages, streaming message, typing indicator, and subagent
indicators) instead of inline among regular messages.
2. Bubble disappears when an option is selected or dismissed — the
ClarifyBubble is driven by state.clarifyRequest instead of a
persisted ChatMessage.clarifyInfo, so clearing the request state
removes it from the list entirely.
* fix(chat): add text input field to ClarifyBubble for custom typed answers
* fix(chat): render ReasoningCard at list level with stable key, not inside AssistantBubble
* fix(chat): address agy review — hoist regex, fix a11y, cache anim specs, disable animateContentSize while streaming
* fix(chat): replace hardcoded Color() with theme constants to pass CI checkColorLiterals
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* feat(chat): add reasoningLevel to ChatUiState + ViewModel methods
* feat(chat): add ComposerToolbar with model + reasoning chips
* refactor(chat): rewrite ChatInputBar to two-row layout
* feat(chat): wire ComposerToolbar into ChatScreen
* fix(chat): make model chip fixed 120dp with horizontal scroll for long names
* feat(chat): reasoning chip opens dropdown menu with all 9 levels instead of cycling
* fix(chat): remove Auto level from reasoning menu — backend only supports none..ultra, default is medium
* feat(chat): sync model + reasoning level from backend session.resume response
* fix(chat): handle session.info events for model/reasoning sync + fix null value 4002
* fix(chat): safety timeout for createNewSession + try-catch event loop
* fix(chat): address agy review findings
- Restore InsertDriveFile icon for non-image attachments
- Add widthIn(max=120.dp) constraint on attachment filename
- Restore stringResource reference for remove-attachment description
- Remove dead cycleReasoningLevel() method (dropdown supersedes)
- Fix createNewSession timeout race with generation counter
* fix(chat): update instrumented test for two-row layout
chatScreen_renders_and_acceptsInput had an assertion that the mic
button disappears when text is entered — this was the OLD single-row
layout behavior. The new two-row composer always shows the mic button
in the toolbar row, independent of input state.
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* fix(chat): make chat input composer more compact and flush
* fix(chat): fix chat page compose structure (issue #652)
- Resolve EmptyState rendering alongside empty LazyColumn by wrapping in if/else
- Flatten nested weight(1f) layout by moving search bar to ChatScreen
* style(chat): run ktlint auto-format and fix missing padding import
* style(chat): remove unused imports in ChatComposer and ChatMessageList
* fix: correct bulk session delete endpoint + surface deleted count
- Fix Retrofit @POST path from 'api/sessions/delete' to 'api/sessions/bulk-delete'
- Change response type from Response<Unit> to Response<BulkDeleteResponse>
- Add BulkDeleteResponse model (ok, deleted) matching backend contract
- Surface backend 'deleted' count in toast message instead of using client-side count
Backend contract (web_server.py:10750):
POST /api/sessions/bulk-delete
Body: { "ids": [...], "delete_all": false }
Response: { "ok": true, "deleted": <count> }
Fixes#651
* fix: replace client-side session list filter with full refresh after bulk delete
- Call loadSessions() + loadStats() after successful bulk delete instead of
filtering sessions/searchResults locally via 'ids' — fixes state desync
when backend deletes fewer sessions than requested (partial success) and
is correct for delete_all=true where ids may be empty
- Show 'No sessions were deleted' toast when deletedCount == 0
- Extract toastMsg to separate val to satisfy ktlint lint rules
Addresses review findings: UI state desync, delete_all handling, hardcoded
pluralizing, and zero-deletion UX.
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* Fix#647: resolve Default profile URL from top-level login URL
ConnectionProfile.resolvedBaseUrl (used directly by ConnectionSection for
the profile list display) silently fell back to the hardcoded loopback
127.0.0.1:9119 whenever a profile's own baseUrl was null, instead of using
the URL the user actually authenticated against.
- Add ConnectionProfile.resolveBaseUrl(topLevelBaseUrl) that prefers the
profile's own baseUrl, then the top-level login URL, then legacy loopback.
- Store-level ServerCollectionOps.resolvedBaseUrl now applies the same
fallback so a null-baseUrl profile still shows the real gateway.
- ConnectionSection, SettingsViewModel and ConnectViewModel resolve against
AuthManager.getBaseUrl() so the loopback fallback can never surface.
- Add Issue647ProfileUrlTest covering login-stamp, null-baseUrl fallback,
own-URL precedence, fresh-install loopback, and store-level resolution.
- Update existing AuthManagerTest assertions to the new property form.
* Fix#647 (root cause): cache login URL at top-level baseUrl
The previous change only made profile resolution prefer the top-level
login URL, but setBaseUrl() never actually wrote the top-level baseUrl
field — so it stayed DEFAULT_BASE_URL (https://127.0.0.1:9119/) forever.
A Default profile seeded with the loopback default (or whose own baseUrl
was never stamped) therefore still displayed the loopback URL after
logging in via a custom LAN address.
setBaseUrl() now also stamps the top-level baseUrl, making it the
authoritative "last successful login URL" cache. getBaseUrl() and the
store-level resolvedBaseUrl (profile-list display) now reflect the URL
actually authenticated against.
Add regression tests mirroring the exact AuthLoginViewModel.connect()
sequence (seed with loopback -> setBaseUrl(loginUrl) -> token) asserting
the Default profile, top-level baseUrl and store display all resolve to
the login URL, never loopback.
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
- CookieSerialization: add SESSION_COOKIE_NAMES (__Host-, __Secure-, bare) and
isSessionCookieName(); isSessionCookie now matches any variant.
- PersistentCookieJar.getSessionCookieValue(): iterate SESSION_COOKIE_NAMES,
returning the strictest prefixed match when present.
- HermesWsClient.refreshWsTicketIfNeeded(): drop the bare-name session-cookie
preflight in gated mode — the server may hold a valid refresh cookie under a
prefixed name; the authenticated ticket endpoint is the authority. Ticket URL
already derived from endpoint (issue #634).
- HermesWsClient: stop logging WS close/failure reason strings and exception
messages (class name only) to avoid leaking server context / URLs.
- ProfileScopeInterceptor: match profile-scoped paths via endpoint-relative
request path so reverse-proxy prefixes (e.g. /hermes/api/...) are honored;
wrap endpoint read in runCatching.
Verified: ktlintCheck, testDebugUnitTest, lintDebug all green locally.
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* docs: update AGENTS.md, README.md, and CONTRIBUTING.md
Sync all three docs with current codebase state:
Kotlin 2.4.10, Kotlinx Serialization, 28 screens,
6 theme presets, CI instrumented-tests job, color guard.
* docs: missed control
* fix(ux): keep Settings highlighted in bottom nav on drill-down sub-pages (issue #637)
Map Settings drill-down destinations (SettingsConnection, SettingsAppearance, SettingsChat, SettingsNavBar, SettingsBehavior, SettingsAbout) back to SettingsScreen for bottom-nav selection only - navigation is unaffected.
- Add selectedBottomNavDestination() helper in Navigation.kt
- Extract bar-height logic into Modifier.bottomNavigationHeight() (ICON_AND_TEXT now uses heightIn(min=80.dp) so the standard bar can grow)
- BottomNavigationSelectionTest (JVM): selection mapping logic
- BottomNavigationLayoutTest (androidTest): per-mode bar height assertions
* docs(navigation): warn that new Settings sub-pages must be added to settingsDestinations
Addresses agy review (PR #643): documents the fragility of the hardcoded settingsDestinations set so future Settings drill-down screens don't silently drop the bottom-nav highlight. The sealed-class/marker-interface refactor was declined as scope creep (issue #637 explicitly scopes Settings-only; keys are flat data objects).
* fix: language selector
---------
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
Set android:allowBackup="false" to stop the OS from snapshotting
/data/data/com.m57.hermescontrol/ (server_store.json, SQLCipher DB,
EncryptedSharedPreferences tokens/cookies, PersistentCookieJar) into
the user's Google Drive. Removes a credential + chat-history exfil
surface via Google account compromise.
Co-authored-by: M57 <Hy4ri@users.noreply.github.com>
* [feature] issue #634: HTTPS + reverse-proxy server endpoint support
- Add ServerEndpoint model (scheme-aware base URL, resolve/webSocketUrl/relativeRequestPath, cleartext policy)
- AuthManager: baseUrl is canonical; setHost/setPort derive from endpoint; endpointForBuild() for scheme-aware URLs
- ApiClient/CookieManager/HermesWsClient: route through ServerEndpoint (no hardcoded http://)
- Data migration: ServerUrlMigration converts legacy host/port to baseUrl
- UI: Connect/AuthLogin/Settings now use a single Server URL field with transport warning
- Build: ALLOW_CLEARTEXT buildConfigField + manifest placeholder for dev
- Tests: ServerEndpointTest + ServerUrlMigrationTest; adapt existing suite to baseUrl API
Co-Authored-By: M57 <Hy4ri@users.noreply.github.com>
* fix(authlogin): basic-auth derives token automatically, no manual entry
connectBasicAuth() built a fresh OkHttpClient for the password-login call and
a different one for the ws-ticket call, so the Set-Cookie from
/auth/password-login (the session token lives in the cookie, not the JSON body)
never reached /api/auth/ws-ticket. That 401'd the ticket request, returned null,
and the UI fell back to asking the user to paste a token.
Both calls now use the shared OkHttpProvider.probe client (same CookieManager
jar), so the session cookie flows through and the WS ticket mints automatically —
matching the dashboard contract (routes.py: password-login sets Set-Cookie,
ws-ticket requires it).
Add AuthLoginBasicAuthFlowTest proving the cookie propagates on the shared
client (and that ws-ticket 401s without it).
Fixes the basic-auth token prompt reported against issue #634.
* chore: remove TASK-634-TESTS.md (stray task-tracking doc, not part of feature)
* ci: broaden .gitguardian.yml test-file ignores (unit + instrumented + variant dirs)
* feat(authlogin): smart auth-mode detection from /api/status + drop pairing-string login
- Replace 302-sniff probe with authoritative GET /api/status read
(auth_required + auth_providers) to derive DashboardAuthMode.
- Add OAUTH mode (stubbed, 'coming soon' UI, TODO tracks issue #639).
- Render login UI by detected mode: token (loopback), username+password
(basic/gated), or OAuth notice.
- Remove legacy pairing-string box + onPairingString/applyLegacyPairing.
- Extract internal deriveAuthMode() + add 5 unit tests.
Closes nothing; OAuth tracked in #639.
* fix(chat): don't block WS connect on empty token in gated (ticket) mode
connectWebSocket() gated on getToken() != null, correct for loopback
(token) mode but wrong for gated (ticket) mode: the ticket is minted
fresh by HermesWsClient.refreshWsTicketIfNeeded() from the persisted
session cookie, so getToken() is expected empty at connect time. The
early return left the WS unopened -> DISCONNECTED -> chat showed
'reconnect' immediately after basic-auth login.
Only require a non-blank token in non-gated mode.
Fixes#640.
* test: remove onPairingString test cases for deleted pairing-login path
The pairing-string login (onPairingString/applyLegacyPairing) was removed
from ConnectViewModel, so the 5 tests that exercised it (3 in
ConnectViewModelTest, 2 in E2eIntegrationTest) no longer compile. Remove
them. Also drop the now-orphaned connect_pairing_string from values-ko.
Fixes the Unit & Integration Tests CI failure on PR #638.
---------
Co-authored-by: hy4ri <hy4ri@users.noreply.github.com>
Verified against backend source at tip 299e409f15 (tui_gateway/server.py).
- SubscriptionCurrent: add cancel_at_period_end / cancellation_effective_at / cancellation_effective_display (emitted by _serialize_subscription_state, were missing on mobile).
- SubscriptionTier: align to wire shape {tier_id, name, tier_order, dollars_per_month_display, monthly_credits, is_current, is_enabled}; old {tier_name, price, currency, interval} never matched the backend and is unused in-app.
- NOTE: usage.bars UsageBar *_display string model is CORRECT — the backend serializes raw *_usd floats to *_display strings via _serialize_usage_bar before sending. Issue #631 misidentified this as a gap; switching to *_usd would break the bars. No change made there.
Co-authored-by: ronia <ronia@m57>
* feat(billing): adopt subscription.* + usage.bars WS methods (issue #628)
Add Billing/Plan screen + WS client surface for the backend release audit
(hermes-agent 0bf44d557..614dc194e). credits.view was removed upstream;
subscription.{state,preview,change,resume,upgrade} + usage.bars replace it.
- WsMethods: add SUBSCRIPTION_* + USAGE_BARS constants
- BillingModels: @Serializable request/response (snake_case, ignoreUnknownKeys)
- BillingRepository: WS dispatch via HermesWsClient.request + typed decode;
HermesRpcException (-32601) surfaces as featureUnavailable, not a crash
- BillingViewModel: plan/usage load + upgrade/change/resume/cancel actions
- BillingScreen: HermesScaffold composable (plan card, usage bars, actions)
- NavigationKeys + ScreenRegistry + strings (en/ko) wire BillingScreen into
the INSPECT drawer section
Verified: ./gradlew ktlintCheck + compileDebugKotlin both BUILD SUCCESSFUL.
* fix(billing): align models + UI to live gateway wire shape (issue #628)
Live-probed the 6 subscription.* / usage.bars RPCs against the running
backend (hermes-agent dashboard :9119, 2026-07-19). Findings:
- subscription.state returns logged_in / current / tiers / usage (nested),
NOT the legacy subscription_type_id / renews_at fields the models assumed.
- Mutating RPCs (preview/change/resume/upgrade) return ok:false *results*
with error/message/payload (e.g. invalid_token when not portal-authed),
not RPC-level errors — so the ViewModel's HermesRpcException guard never
fired and the screen silently half-decoded null fields.
- subscription.upgrade also returns an idempotency_key not in the model.
Changes:
- BillingModels: re-shape SubscriptionStateResponse around current/tiers/
usage; add ok/error/message/payload envelope + idempotency_key to the
action responses; add SubscriptionCurrent / SubscriptionTier / preview
payload types. All nullable + ignoreUnknownKeys (graceful degrade).
- BillingViewModel: detect ok:false results on every call and route to
featureUnavailable / errorMessage instead of swallowing them.
- BillingScreen: read plan from subscription.current; render a clean
'no active plan' / 'log in to Nous Portal' card on the logged-out path
instead of a broken null plan card.
- strings: add billing_no_active_plan / billing_login_required (en + ko).
Verified: ./gradlew ktlintCheck + compileDebugKotlin both BUILD SUCCESSFUL.
* fix(billing): address independent review (agy) — error routing + icon
Triage of the independent AGY review on PR #629:
Fixed (real issues):
- BillingViewModel: usage.bars RPC failure (-32601) no longer marks the
whole feature unavailable (was blocking the plan card despite the
'non-fatal' comment); it is now correctly non-fatal.
- BillingViewModel: a failed primary subscription load now surfaces
errorMessage even when usage bars loaded (was swallowed by
'sub == null && bars == null').
- BillingScreen: render state.errorMessage as an error card inside
BillingContent so failed mutating actions (upgrade/cancel) are visible
instead of silently disappearing.
- BillingScreen: wrap the dead AccountBalanceWallet expression in a real
Icon() composable in FeatureUnavailableState.
Declined (with rationale, recorded for maintainer):
- Tier-select / upgrade UI (review issue #4): explicitly out of scope per
the PR body — 'Plan-selection UI ... is not built ... left for a
follow-up once backend returns the available plans.'
- Rename snake_case Kotlin props to camelCase (review nit #2): incorrect —
OkHttpProvider uses JsonNamingStrategy.SnakeCase, which maps snake_case
wire keys onto snake_case properties; the props are correct. Fixed the
misleading doc comment instead.
* fix(billing): match REAL logged-in wire shapes + kill null-result crash
The live gateway probe (logged-in Nous Portal session, 2026-07-19) showed
the earlier models assumed the WRONG shape:
- subscription.state.current is {tier_id, tier_name, monthly_credits,
credits_remaining, cycle_ends_at, pending_downgrade_*} — NOT the legacy
subscription_type_id/status/renews_at fields. Screen rendered 'Free / no
plan' for a real logged-in user.
- usage.bars is {available, status, plan_name, plan_bar{remaining_display,
total_display, pct_used, fill_fraction}, topup_bar} — NOT a List<UsageBar>.
- Mutating RPCs return error:'insufficient_scope' when the Portal token
lacks billing:manage scope (ok:false result, not an RPC error).
Crash fix (root cause of 'Billing RPC returned no result payload'):
- BillingRepository.decode() now returns null on a missing/null result
instead of requireNotNull() -> IllegalStateException. All repo methods
return nullable; ViewModel handles null as a non-fatal 'No billing data
returned' instead of crashing.
- BillingScreen.PlanCard / UsageBarRow rewritten to the real fields; the
resume/cancel branch now gates on can_change_plan (no status field exists
on current anymore).
- UsageBarsResponse + UsageBar reshaped to plan_bar/topup_bar; added
billing_credits_remaining / billing_plan / billing_topup strings (en+ko).
Verified: ktlint clean + compileDebugKotlin BUILD SUCCESSFUL. Decode sim
against the captured live responses confirms PlanCard/UsageBarRow/error
paths all resolve with no null-crash.
* fix(billing): decode WS result that arrives as toAny() Map, not JsonElement
Root cause of 'No billing data returned' on a logged-in server: the backend
returns a valid subscription.state result, but HermesWsClient.request()
yields result already converted via JsonElement.toAny() (a Map<String,Any?>),
not a raw JsonElement. BillingRepository.decode() only accepted JsonElement,
so was null and the repo returned null -> ViewModel showed
the generic 'No billing data returned' message. The server DOES have billing
(logged_in:true, tier_name:Free, /usr/bin/bash.10 credits) — the app just couldn't parse it.
Fix: decode() now normalizes whatever arrives — a kotlinx JsonElement OR the
toAny() Map/List — back into a JsonElement via a recursive Any->JsonElement
walk, then deserializes. Both shapes decode correctly now.
This also means the previous 'Billing RPC returned no result payload' crash
and the generic 'no data' message were both symptoms of this same parse gap,
not a missing backend feature.
Verified: ktlint clean + compileDebugKotlin BUILD SUCCESSFUL.
* perf(analytics): preload on launch + split-fetch + disk cache (issue #537)
Cut perceived analytics-tab latency for every user regardless of backend
DB size:
A. Preload analytics (7/30/90) in the background on app launch
(AnalyticsPreloader) so the tab renders instantly when opened.
B. Split the two endpoint fetches: /models (~0.1s, carries the
totals card) now renders immediately while the slow /usage (insights
engine over full message history) streams in behind a placeholder.
C. Persist last successful response to DataStore so a cold app launch
serves last session's data instantly, then refreshes (AnalyticsCacheStore).
Root cause of the slowness is server-side (/api/analytics/usage cold
read of a multi-GB state.db); these client changes make the common
case instant and never block the UI on the slow call.
* fix(analytics): address agy review — null-safety, profile-keyed cache, no main-thread block
Triage of independent agy review (High model) on PR #630:
Fixed (real):
- Blank-on-cold-launch: AnalyticsContent early-returned on null
usage, blanking the tab while the slow /usage call loaded. Now
renders the fast /models half + placeholders; usage-only cards
(totals, daily chart) and Skills/Tools tabs guard on usage != null.
- Profile isolation: cache was keyed by days only -> cross-profile
data leak on switch/cold-start. Now keyed "$days:$profile".
- Main-thread block: ViewModel.init used runBlocking(IO) on the
UI thread at startup. Moved disk-seed into viewModelScope.launch.
- Serialization parity: cache used bare kotlinx Json; switch to
OkHttpProvider.json (ignoreUnknownKeys) so a backend field
addition can't break on-disk decode.
Declined (not introduced by this PR / protected by viewModelScope):
- "safeApiCall swallows CancellationException": pre-existing
NetworkResult.kt behavior; viewModelScope cancellation already
prevents post-clear state updates. Out of scope for this change.
* fix(analytics): crash on tab open — LocalContext is Activity, not Application
AnalyticsScreen cast LocalContext.current as Application, but under
Compose the composition context is the *Activity*, so the cast threw
ClassCastException the moment the tab composed (on tap). Use
.applicationContext, which resolves to the Application instance.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(billing): adopt subscription.* + usage.bars WS methods (issue #628)
Add Billing/Plan screen + WS client surface for the backend release audit
(hermes-agent 0bf44d557..614dc194e). credits.view was removed upstream;
subscription.{state,preview,change,resume,upgrade} + usage.bars replace it.
- WsMethods: add SUBSCRIPTION_* + USAGE_BARS constants
- BillingModels: @Serializable request/response (snake_case, ignoreUnknownKeys)
- BillingRepository: WS dispatch via HermesWsClient.request + typed decode;
HermesRpcException (-32601) surfaces as featureUnavailable, not a crash
- BillingViewModel: plan/usage load + upgrade/change/resume/cancel actions
- BillingScreen: HermesScaffold composable (plan card, usage bars, actions)
- NavigationKeys + ScreenRegistry + strings (en/ko) wire BillingScreen into
the INSPECT drawer section
Verified: ./gradlew ktlintCheck + compileDebugKotlin both BUILD SUCCESSFUL.
* fix(billing): align models + UI to live gateway wire shape (issue #628)
Live-probed the 6 subscription.* / usage.bars RPCs against the running
backend (hermes-agent dashboard :9119, 2026-07-19). Findings:
- subscription.state returns logged_in / current / tiers / usage (nested),
NOT the legacy subscription_type_id / renews_at fields the models assumed.
- Mutating RPCs (preview/change/resume/upgrade) return ok:false *results*
with error/message/payload (e.g. invalid_token when not portal-authed),
not RPC-level errors — so the ViewModel's HermesRpcException guard never
fired and the screen silently half-decoded null fields.
- subscription.upgrade also returns an idempotency_key not in the model.
Changes:
- BillingModels: re-shape SubscriptionStateResponse around current/tiers/
usage; add ok/error/message/payload envelope + idempotency_key to the
action responses; add SubscriptionCurrent / SubscriptionTier / preview
payload types. All nullable + ignoreUnknownKeys (graceful degrade).
- BillingViewModel: detect ok:false results on every call and route to
featureUnavailable / errorMessage instead of swallowing them.
- BillingScreen: read plan from subscription.current; render a clean
'no active plan' / 'log in to Nous Portal' card on the logged-out path
instead of a broken null plan card.
- strings: add billing_no_active_plan / billing_login_required (en + ko).
Verified: ./gradlew ktlintCheck + compileDebugKotlin both BUILD SUCCESSFUL.
* fix(billing): address independent review (agy) — error routing + icon
Triage of the independent AGY review on PR #629:
Fixed (real issues):
- BillingViewModel: usage.bars RPC failure (-32601) no longer marks the
whole feature unavailable (was blocking the plan card despite the
'non-fatal' comment); it is now correctly non-fatal.
- BillingViewModel: a failed primary subscription load now surfaces
errorMessage even when usage bars loaded (was swallowed by
'sub == null && bars == null').
- BillingScreen: render state.errorMessage as an error card inside
BillingContent so failed mutating actions (upgrade/cancel) are visible
instead of silently disappearing.
- BillingScreen: wrap the dead AccountBalanceWallet expression in a real
Icon() composable in FeatureUnavailableState.
Declined (with rationale, recorded for maintainer):
- Tier-select / upgrade UI (review issue #4): explicitly out of scope per
the PR body — 'Plan-selection UI ... is not built ... left for a
follow-up once backend returns the available plans.'
- Rename snake_case Kotlin props to camelCase (review nit #2): incorrect —
OkHttpProvider uses JsonNamingStrategy.SnakeCase, which maps snake_case
wire keys onto snake_case properties; the props are correct. Fixed the
misleading doc comment instead.
* fix(billing): match REAL logged-in wire shapes + kill null-result crash
The live gateway probe (logged-in Nous Portal session, 2026-07-19) showed
the earlier models assumed the WRONG shape:
- subscription.state.current is {tier_id, tier_name, monthly_credits,
credits_remaining, cycle_ends_at, pending_downgrade_*} — NOT the legacy
subscription_type_id/status/renews_at fields. Screen rendered 'Free / no
plan' for a real logged-in user.
- usage.bars is {available, status, plan_name, plan_bar{remaining_display,
total_display, pct_used, fill_fraction}, topup_bar} — NOT a List<UsageBar>.
- Mutating RPCs return error:'insufficient_scope' when the Portal token
lacks billing:manage scope (ok:false result, not an RPC error).
Crash fix (root cause of 'Billing RPC returned no result payload'):
- BillingRepository.decode() now returns null on a missing/null result
instead of requireNotNull() -> IllegalStateException. All repo methods
return nullable; ViewModel handles null as a non-fatal 'No billing data
returned' instead of crashing.
- BillingScreen.PlanCard / UsageBarRow rewritten to the real fields; the
resume/cancel branch now gates on can_change_plan (no status field exists
on current anymore).
- UsageBarsResponse + UsageBar reshaped to plan_bar/topup_bar; added
billing_credits_remaining / billing_plan / billing_topup strings (en+ko).
Verified: ktlint clean + compileDebugKotlin BUILD SUCCESSFUL. Decode sim
against the captured live responses confirms PlanCard/UsageBarRow/error
paths all resolve with no null-crash.
* fix(billing): decode WS result that arrives as toAny() Map, not JsonElement
Root cause of 'No billing data returned' on a logged-in server: the backend
returns a valid subscription.state result, but HermesWsClient.request()
yields result already converted via JsonElement.toAny() (a Map<String,Any?>),
not a raw JsonElement. BillingRepository.decode() only accepted JsonElement,
so was null and the repo returned null -> ViewModel showed
the generic 'No billing data returned' message. The server DOES have billing
(logged_in:true, tier_name:Free, /usr/bin/bash.10 credits) — the app just couldn't parse it.
Fix: decode() now normalizes whatever arrives — a kotlinx JsonElement OR the
toAny() Map/List — back into a JsonElement via a recursive Any->JsonElement
walk, then deserializes. Both shapes decode correctly now.
This also means the previous 'Billing RPC returned no result payload' crash
and the generic 'no data' message were both symptoms of this same parse gap,
not a missing backend feature.
Verified: ktlint clean + compileDebugKotlin BUILD SUCCESSFUL.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Turn dead-end empty states into on-ramps by wiring the existing
EmptyState actionLabel/onAction params to real next actions.
Screens wired (real, existing actions):
- Skills (installed): Browse skill hub -> setViewMode(HUB)
- Skills (hub): Retry search -> searchHub(hubQuery)
- Cron Jobs: Create your first job -> openNewJobDialog()
- MCP servers: Add a server -> toggleAddForm() (literal moved to strings.xml)
- Webhooks: Create subscription -> showCreateDialog() (literal moved to strings.xml)
- Channels: Connect a Telegram channel -> startTelegramOnboarding()
- Model: Configure model -> navigateTo(SettingsConnection)
- Sessions (history): Start a new chat -> navigateTo(ChatScreen)
- Analytics: Explore Skills or Cron jobs -> navigateTo(SkillsScreen)
- Keys (no match): Clear search -> query = ""
All new labels use strings.xml (empty_action_* / screenname_empty_*).
Deviations from issue (documented honestly):
- Toolsets, Profiles, Plugins keep Refresh. No in-app create path exists
(toolsets are server-defined toggles; profiles/plugins have no create
dialog wired in UI). Refresh is the correct recovery there, not a fake
'create' CTA. Flagged for follow-up if create flows get built.
- Skills: edited the real private InstalledSkillsView in SkillsScreen.kt;
the duplicate internal one in InstalledSkillsTab.kt is dead code.
Verified: ktlintCheck clean, assembleDebug green.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Co-authored-by: Ronia <ronia@hermes>
Removed docs/color-hardcoded-audit.md per request. Replaced 2 hardcoded
Color literals with theme tokens; added CI guard blocking new literals.
Co-authored-by: Hy4ri <hy4ri@users.noreply.github.com>