* refactor(theme): split per-preset color schemes into theme/presets/
Move each ThemePreset's ColorScheme + status colors into its own file under
theme/presets/ (Default, Monochrome, Gruvbox, Catppuccin, Amoled, NeonNoir).
Theme.kt becomes a thin dispatcher via resolveColorScheme/resolveStatusColors,
making individual themes far easier to create and edit.
- AMOLED keeps a dark-only scheme (falls back to default light)
- MONOCHROME/AMOLED reuse default status colors (no bespoke semantic set)
- aligned to current Voltage Purple palette + on* status-color params
Verified: ktlint clean, compileDebugKotlin passes.
* refactor(theme): make all preset files uniform 4-token shape
Every preset file now exports XxxDarkColorScheme / XxxLightColorScheme /
XxxDarkStatusColors / XxxLightStatusColors so they share one shape and import
order. MONOCHROME + AMOLED alias the default status colors; AMOLED also gets an
explicit AmoledLightColorScheme = DefaultLightColorScheme alias.
Theme.kt dispatcher is now a pure lookup (no special-casing) for both color
scheme and status colors. No runtime behavior change — pure structural cleanup.
Verified: ktlint clean, compileDebugKotlin passes.
* docs(theme): add THEMES.md documenting the per-preset convention
Co-located in theme/ — covers layout, the uniform 4-token shape, the pure
lookup dispatcher, why DEFAULT uses design tokens (intentional, not a bug),
and a step-by-step 'add a new theme' recipe.
Verified: ktlint clean.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix(#584): follow stream without freezing (persistent snapshotFlow)
The auto-scroll LaunchedEffect was keyed on (messages.size,
streamingMessage?.content?.length, isThinking) — those change on EVERY
streamed token, so the effect restarted per token and cancelled the
in-flight animateScrollToItem, leaving the view stuck/frozen mid-stream.
Replace it with a single persistent LaunchedEffect(Unit) + snapshotFlow +
collectLatest. The streaming follow now uses an instant scrollToBottom
(animated=false) which is idempotent per token and has no animation to
cancel; a discrete new message arriving while at the bottom still animates.
Because the effect runs once, mirror the params through rememberUpdatedState
and read them live inside snapshotFlow/collectLatest so the flow actually
fires per token and session-switch detection uses the current session id
(rather than stale first-composition closure captures).
* fix(#584): leave scroll free during streaming (no auto-follow)
m57 follow-up: the previous fix stopped the freeze but still force-pinned
to the bottom while streaming. Now, while a message is streaming, the
scroll is left completely free — no auto-follow of the streaming message —
so the user can scroll up/down to read while it generates.
Auto-scroll only on explicit actions (send / FAB / session switch) and when
a discrete non-streaming message lands while already pinned to the bottom.
streamingMessage is dropped from the snapshotFlow keys so the flow no
longer churns per token.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix(#583): align last message bottom to viewport on scroll-to-bottom
animateScrollToItem(lastIndex) only top-aligns the last item, so when the
last message is taller than the viewport its bottom is clipped below the fold.
Replace the 4 scroll-to-bottom call sites (send auto-scroll, session-switch,
auto-scroll-on-new-message, and the FAB) with a scrollToBottom() helper that
top-aligns then scrolls the exact remaining delta so the last item's bottom
edge is visible.
Using the remaining delta (not scrollOffset=Int.MAX_VALUE) avoids integer
overflow in the internal scroll-position clamp, which would wrap the offset to
0 and scroll back to the top for tall items.
* fix(#583): keep smooth animation on scroll-to-bottom when animated
agy review (PR #590) flagged that the animated path did an instant
scrollToItem then only animated the small remaining delta, causing a hard
jump on FAB / send clicks instead of a smooth scroll. Use animateScrollToItem
when animated, scrollToItem when instant.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix(#587): forward session_id on image.attach_bytes and await the RPC
The mobile image-send path called image.attach_bytes without the required
session_id field, so the gateway resolver (_sess) returned
JsonRpcError(code=4001, message=session not found).
- Add "session_id" to agentSessionId to the image.attach_bytes params
(desktop reference client already does this; mobile was the outlier).
- Switch the image branch from fire-and-forget wsClient.send to the
awaited sendRpcAndAwait() layer (same awaited-RPC path used for
slash commands, #526). This also removes the race where prompt.submit
could fire before the image was staged, and surfaces RPC errors
instead of silently swallowing them.
Root cause verified against tui_gateway/server.py _sess() and the
desktop use-prompt-actions reference. ChatViewModel.kt passes ktlintCheck.
Closes#587
* fix(#587): also forward session_id on file.attach (same 4001 bug)
The image branch was fixed in the prior commit, but the file branch
(sendMessage else -> file.attach) omitted session_id too, so non-image
file uploads also hit JsonRpcError(code=4001, "session not found").
The backend file.attach handler (tui_gateway/server.py _sess) requires
session_id exactly like image.attach_bytes.
Add "session_id" to agentSessionId to the file.attach params, and
refresh the sendMessage flow comment (no longer fire-and-forget).
Verified by source: both image.attach_bytes and file.attach call the
same _sess resolver. Camera capture is unaffected (it produces an
image/jpeg attachment, which already routes through the fixed
image.attach_bytes branch).
ChatViewModel.kt passes ktlintCheck.
* test(#587): regression for image.attach_bytes session_id
Adds testSendMessage_imageAttachment_sendsSessionId, which proves the
image-attach RPC is issued with session_id (the missing field that
caused JsonRpcError 4001 'session not found').
Root blocker found: readContentUriBase64 constructs
android.util.Base64OutputStream, which throws MockK's 'Stub!' on the
JVM test, making the read return null and the image branch never run.
Mocking the Base64OutputStream constructor lets the read succeed so the
request(any(), capture(paramsSlot), any()) stub captures the params and
the session_id assertion holds.
Full ChatViewModelTest suite passes; ktlint-clean.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix(#575): drop description text from slash-command suggestions
* fix(#575): show /stop and /interrupt in slash-command menu
* fix(#574): hide desktop/CLI-only slash commands from mobile suggestion menu
Recreate hiddenSlashDisplay blocklist removed in 1f322e3 with the 33
cli_only/TUI-only commands that don't function on mobile (issue #574).
/stop and /interrupt intentionally remain visible (they work on mobile, #575).
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Co-authored-by: M57 <m57@hermes-control.app>
* fix(#575): drop description text from slash-command suggestions
* fix(#575): show /stop and /interrupt in slash-command menu
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* fix(#572): clarify Dismiss now informs agent instead of silently dropping
* fix(#572): clarify Dismiss rejects the question (no answer) instead of telling agent to proceed
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix: refresh loopback dashboard token after restart
The gateway regenerates its ephemeral session token on every restart, so the
token the app persisted becomes stale. After a dashboard restart REST calls
401 and the WebSocket auto-reconnect loop hangs in AUTH_EXPIRED until the user
manually re-authenticates.
- Add DashboardSessionTokenRefresher: re-reads the injected
window.__HERMES_SESSION_TOKEN__ from the dashboard SPA and writes it back to
AuthManager.
- TokenRefreshAuthenticator: on a 401 retry, scrape a fresh token from the
dashboard and retry instead of giving up.
- HermesWsClient: refresh the token before each non-gated WebSocket handshake so
reconnects don't get stuck on a stale token; guard serverStore read against
IllegalStateException.
Covers the loopback (--insecure) deployment path; gated/ticket mode is untouched.
* fix: harden dashboard token refresher (sync, body cap, blank-token test)
Second-opinion review flagged robustness gaps (no correctness/security
regressions in the happy path):
- DashboardSessionTokenRefresher.refresh(): @Synchronized to dedupe
concurrent 401 / reconnect storms instead of each firing its own GET.
- Cap SPA HTML read at 64 KiB before regex scan (defensive against OOM on
low-end devices); we only need the injected token near the document top.
- HermesWsClient: log (not silently swallow) the transient uninitialized
serverStore case so a real misconfig is still visible.
- Add test: blank-injected token returns null.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* feat(#538): wire tool.progress/generating + subagent.* events into chat
* fix(#538): remove subagent indicator on subagent.complete so it doesn't linger
* style(#538): drop dead Elvis on non-nullable event.text in onMessageComplete
---------
Co-authored-by: M57 <m57@hermes-control.app>
* feat(#533): add session.branch (fork a conversation) to mobile
The gateway already supports session.branch (tui_gateway/server.py), but
the mobile had no client surface. This adds:
- WsMethods.SESSION_BRANCH = "session.branch"
- A Branch (CallSplit) action on each session card that forks it via the
session.branch WS RPC with the source session_id (and optional name).
- branchedSessionId state -> SessionsScreen navigates to the freshly
forked session on success; RpcError -> toast; spinner while branching.
- SessionsViewModelTest (4 tests): forwards session_id, forwards name,
sets branchedSessionId on success, toast+no-branch on RpcError, and
consumeBranchedSession clears the pending id.
Verified against the live gateway contract: session.branch expects
{session_id, name?} and returns {session_id, title, parent}. Local
testDebugUnitTest: 4/4 pass, ktlint clean.
* refactor(#533): make /fork work via chat instead of a session-menu button
Per review feedback: the session.branch surface belongs in the chat
composer, not the session list menu.
- SlashCommandDispatcher: /fork and /branch -> new SlashResult.SessionBranch.
- ChatViewModel: handles SessionBranch by sending session.branch with the
active runtime session id (optional arg = branch title), and on the RPC
result switches the current session to the new forked one (mirrors the
SESSION_CREATE handler). This fixes /fork, which previously fell through to
command.dispatch and 4018'd (backend only knows session.branch).
- Removed the Branch (CallSplit) button + navigation LaunchedEffect from
SessionsScreen/SessionsViewModel (reverted those two files to main) and
dropped the now-unused sessions_action_branch string.
- Tests: deleted SessionsViewModelTest (branch-only); added /fork -> SessionBranch
to SlashCommandDispatcherTest and two ChatViewModel tests asserting /fork
sends session.branch with the session id + optional name.
Local testDebugUnitTest: SlashCommandDispatcherTest 8/8, ChatViewModelTest 50/50,
0 failures. ktlint clean.
---------
Co-authored-by: ronia <ronia@m57>
* fix(#548): stop System tab button text truncation + fix two wrong labels
* fix(system): remove inline icons from narrow system action buttons to prevent text cutoff
* fix(system): restore action icons and implement dynamic font scaling for button text
* fix: stack icon above text in system buttons to prevent label clipping
Replace horizontal Icon+Text layout with vertical Column stacking
(icon on top, text centered below) — the same pattern Material 3
NavigationBar items use. Gives text the full button width so labels
like 'Security Audit' and 'Config Migrate' never get cut off.
* fix: add missing ImageVector import for system buttons fix
---------
Co-authored-by: M57 <m57@hermes-control.app>
Mobile was silently dropping two event types the gateway emits. This adds
parsing + UI surfacing for both, bringing mobile to parity with desktop
(which shows gateway errors as red toasts).
- `error` (backend crash) -> WsEvent.GatewayError, surfaced in the existing
error banner (mirrors how RpcError is handled).
- `background.complete` (scheduled job finished) -> WsEvent.BackgroundComplete,
surfaced as a non-blocking snackbar in ChatScreen.
Changes:
- WsEvent.kt: add GatewayError(message?) + BackgroundComplete(data?) sealed subtypes.
- EventParser.kt: handle "error" + "background.complete"; unknowns still fall
through to Unknown (no behavior change for existing event types).
- ChatWsEventReducer.kt: onGatewayError (sets errorMessage, clears loading) +
onBackgroundComplete (sets backgroundCompleteMessage); mirrors onRpcError.
- ChatViewModel.kt: backgroundCompleteMessage state field, clearBackgroundComplete(),
handleWsEvent branches (ViewModel owns the snackbar trigger).
- ChatScreen.kt: pass backgroundCompleteMessage to ChatLifecycleEffects + a
LaunchedEffect that shows the snackbar and calls clearBackgroundComplete().
- EventParserTest.kt: cover both new events (incl. missing-message case).
Pure additive; sealed class + exhaustive when() preserved. Verified:
compileDebugKotlin + ktlintCheck green; EventParserTest passes.
Closes#527
Co-authored-by: M57 <m57@hermes-control.app>
* fix(ws): align RPC timeout to 120s + rejectAllPending on disconnect (fixes#526)
Mobile's pending-request handling diverged from the desktop contract
(apps/shared JsonRpcGatewayClient) in two ways that caused silent hangs:
1. Timeout was 30s while the desktop uses 120s (DEFAULT_REQUEST_TIMEOUT_MS),
so legitimately long agent turns were pruned early. Align to 120s and use
it for both the cleanup sweep and sendRpcAndAwait's per-call withTimeout.
2. The cleanup sweep only Log.w'd stale requests and dropped them — it never
failed the CompletableDeferred, so sendRpcAndAwait callers awaiting a
server that never answered HUNG FOREVER. And on disconnect/reconnect there
was NO rejectAllPending, so in-flight awaited RPCs also hung until their
own timeout.
Changes (all in ChatViewModel.kt):
- cleanup sweep now completeExceptionally()s the deferred AND surfaces a
'Request timed out' error for fire-and-forget RPCs (was silently dropped)
- new rejectAllPending() fails + clears every in-flight pending deferred;
wired into the disconnect-status collector and reconnect()
- PENDING_REQUEST_TIMEOUT_MS = 120_000 (matches desktop); sendRpcAndAwait
uses it instead of a hardcoded 30s
Tests: 2 new ChatViewModelTest cases cover rejectAllPending on disconnect
and on reconnect (no hang, VM stays usable). (Timeout-surfacing path shares
the deferred-fail logic with handleRpcError; the 120s sweep can't run under
the unit-test dispatcher's periodic-timer limitation, noted in PR.)
Mirrors the desktop-app audit in /opt/hermes-agent.
* fix(ws): aggregate pending-request cleanup into a single UI update (PR #541)
Sourcery review (PR #541): startPendingRequestCleanup emitted one
_uiState.update{} per stale request inside the loop, causing N separate
emissions / redundant recompositions when many RPCs time out at once.
Collect fire-and-forget methods and emit a single combined errorMessage
update after the loop.
rejectAllPending is intentionally left silent on disconnect/reconnect:
those are transient socket events (the RPC often completes on the new
socket), so surfacing a scary error banner is UX noise. Only the
timeout path surfaces errors — that is a genuine failure. This matches
the desktop JsonRpcGatewayClient.rejectAllPending semantics.
* refactor(ws): move awaited-RPC pending/timeout layer into HermesWsClient (closes#526)
Issue #526: port the JsonRpcGatewayClient.request() pattern into
HermesWsClient. HermesWsClient now owns the in-flight map, per-call
120s timeout, resolve-on-RpcResult/RpcError, and rejectAllPending on
disconnect/reconnect. ChatViewModel.sendRpcAndAwait simply delegates
to wsClient.request(...).await(); its local pendingRequests map,
PendingRequest, startPendingRequestCleanup loop and rejectAllPending
are removed. Fire-and-forget send() is unchanged.
---------
Co-authored-by: M57 <m57@hermes-control.app>
* fix(network): scope management REST calls with ?profile= (fixes#528)
Mobile fired all management REST calls with NO profile scope, so every
profile read/wrote the backend's implicit default profile — multi-profile
setups silently corrupted config/skills/toolsets/mcp/model/env.
Add ProfileScopeInterceptor (OkHttp) that appends ?profile=<activeProfile>
to the same endpoint families the desktop/web dashboard scopes
(web/src/lib/api.ts PROFILE_SCOPED_PREFIXES), respecting:
- no active profile -> pass through (legacy default behavior)
- explicit ?profile= on the URL wins over the global scope
- only scoped families rewritten; ops/pairing/cron/profiles stay global
Wired into ApiClient.buildService(). 5 MockWebServer tests cover scoped
append, explicit-param precedence, no-profile passthrough, non-scoped skip,
and skills scoping.
Mirrors desktop/web contract derived from audit of /opt/hermes-agent.
* fix(ci): stub getSelectedProfileId in ApiClientTest + harden prefix match (fixes PR #540)
- ApiClientTest: stub AuthManager.getSelectedProfileId() to null. The new
ProfileScopeInterceptor (registered in ApiClient.buildService) calls it, and
the unstubbed real method threw IllegalStateException at AuthManager.kt:56,
breaking all 4 auth-interceptor tests.
- ProfileScopeInterceptor: replace startsWith(prefix) with whole-segment match
(path == prefix || path.startsWith(prefix/)) so lookalike paths like
/api/statusXYZ are NOT wrongly scoped (Sourcery review, PR #540).
- ProfileScopeInterceptorTest: add lookalikePath_notScoped + scopedSubPath_isScoped
to lock the segment-boundary fix.
Previously mobile dropped the gateway's sudo.request and secret.request
events, so any agent turn needing a sudo password or a secret value hung
forever with no UI. Now:
- EventParser maps sudo.request / secret.request -> WsEvent.SudoRequest / SecretRequest
- ChatViewModel surfaces a secure dialog (SudoPromptUi / SecretPromptUi) and
replies via sudo.respond / secret.respond with session_id + request_id + payload
- ChatWsEventReducer explicitly branches the new events (no-op, VM-owned)
- ChatScreen renders password-masked SudoPromptDialog / SecretPromptDialog
- 6 unit tests cover prompt-state, RPC params, and prompt-clearing
Mirrors desktop/web contract (apps/shared GatewayEventName + tui_gateway).
Derives from audit of /opt/hermes-agent desktop app.
Explicit IO context for DB/WS/notify path. replyScope already uses
Dispatchers.IO; this makes the offload local and explicit. Keep return@withContext
only because nothing follows the withContext block today.
The parseToolOutput function in ChatBubble.kt was handling the specific
parsing and formatting logic for the "todo" tool inline, making the
function long and harder to read.
This commit extracts the todo-specific formatting logic into a new
private function formatTodoToolOutput, improving the readability and
maintainability of ChatBubble.kt without changing any behavior.
Refactored the deeply nested `parseDaysOfWeek` function using guard clauses to flatten the logic structure. By returning early on invalid conditions (`dowPart == "*" || domPart != "*" || monthPart != "*"` and `hoursList.size != 1 || minutesList.size != 1`), the remaining function body's indentation is reduced by two levels.
This improves overall code readability and maintainability without altering existing functionality. The change was verified against existing unit tests, which all pass.
The hub card UI is rendered by the local private HubSkillCard in SkillsScreen.kt (not the unused components/HubSkillsTab.kt copy). Moved SourceBadge out of the top-right name row to the left of the Install button in the card footer (left-aligned source, right-aligned action), tying the skill origin (hub/clawhub/etc) to the install action.
* feat(#500): tap-to-reveal detail dialog for truncated cards
Add shared DetailDialog composable and wire tap-to-open full metadata
dialogs across Skills (installed + hub), MCP servers, Plugins, Toolsets,
and Webhooks screens. Action buttons stay on the card (sticky); tapping
the card body reveals untruncated description + key metadata.
Refs: #500
* fix(#500): resolve compile errors from missing runtime imports + dialog scope
- add missing androidx.compose.runtime.mutableStateOf/remember imports
in InstalledSkillsTab + HubSkillsTab (caused 'Unresolved reference'
cascade on compileDebugKotlin)
- move PluginsScreen detail dialog inside the composable function scope
(was nested in OrphanPluginCard -> showDetail unresolved)
- DetailDialog rows type: Pair<String?,String?> -> Pair<String,String?>
(key always non-null; fixes type-inference failure)
- drop unnecessary safe call on non-null label
Verified locally with the Android SDK:
./gradlew :app:compileDebugKotlin -> BUILD SUCCESSFUL
./gradlew :app:testDebugUnitTest -> BUILD SUCCESSFUL
Refs: #500
* refactor(#500): extract toDetailRows() mappers + semantic status tones; wire SkillsScreen hub browse
- add DetailRows.kt with @Composable extension mappers for Skill/HubSkill/
McpServer/PluginInfo/Toolset/WebhookSubscription -> List<DetailRow>
- DetailDialog now renders status rows via LocalHermesStatusColors (review #2):
SUCCESS/NEUTRAL/WARNING/ERROR/INFO tones instead of plain onSurfaceVariant
- wire SkillsScreen.HubBrowseView/HubSkillCard tap -> DetailDialog (same UX as
other screens) — user request
- remove JVM-signature-clashing Pair overload; drop unused Color import
- add detail_dialog_trust_level string (HubSkill has no version field)
- verified: compileDebugKotlin + testDebugUnitTest PASS locally w/ ANDROID_HOME
* fix(#500): full hub description in dialog + no name truncation
- HubBrowseView (both SkillsScreen + HubSkillsTab): on card tap, fetch
previewHubSkill(identifier) to get the FULL SkillContentResponse.content
(search snippet was truncated); dialog shows full content once loaded,
with a spinner while previewing. Falls back to snippet if no identifier.
- SkillsViewModel: add hubPreviewContent/isHubPreviewing/hubPreviewError
state + previewHubSkill()/clearHubPreview() (uses existing preview endpoint)
- DetailDialog: title now wraps fully (removed maxLines=2 ellipsis cap) so
long skill names are never cut off
- verified: compileDebugKotlin PASS + ktlint clean (local ANDROID_HOME)
Backend commit 37a4cf900 (hermes-agent) flipped the default of
GET /api/model/options's include_unconfigured parameter from true
to false, so the mobile Models picker was silently regressing to
showing only configured/authenticated providers — the skeleton rows
for unconfigured providers (with setup-hint warnings) stopped arriving.
Add include_unconfigured as a @Query param defaulting to true so the
full provider universe is restored on the Models screen. Both current
call sites (ModelViewModel + ProfilesViewModel) invoke the API without
passing the new param, so they automatically pick up the true default.
* refactor(settings): remove current connection editor fields
Remove the active host, port, token fields, and clear token button from the main Connection tab, as profiles are now managed exclusively through the ProfileEditorDialog.
* feat(settings): migrate to full auto-save design and remove save button
Update settings change listeners (auto-reconnect, typing effect delay/toggle) to save state immediately to AuthManager. Remove the manual Save button from the scaffold's top bar and delete the redundant SaveIndicator.
* style(settings): clean up unused imports from settings UI cleanup
* fix(chat): resolve compose resource lint error and initial state test failure
Pre-resolve empty credentials string resource at the composable scope to fix LocalContext resource query lint error. Update testInitialStateAndConnection to use DISCONNECTED state to trigger connection and pass verification.
* fix(ws): stop chat opening from racing the singleton into a stuck RECONNECTING
Root cause: HermesWsClient is a global singleton connected once at login;
every tab observes its single connectionStatus. ChatViewModel is recreated
on every chat-tab open and its init calls connectWebSocket() -> wsClient.connect().
connect() only guarded the CONNECTED case, so when the socket had dropped
(singleton in RECONNECTING with its own scheduled reconnect) opening chat
spawned a SECOND socket on the same webSocket field. The orphaned socket's
later onClosed set connected=false + re-armed RECONNECTING after the new
socket connected, and currentBackoff kept resetting on each chat open,
leaving the status stuck on RECONNECTING while every other tab (which never
calls connect()) stayed healthy.
Fix:
- HermesWsClient.connect() now no-ops while CONNECTING/RECONNECTING (in-flight
socket already pending) and while AUTH_EXPIRED (needs re-auth, not a loop).
- ChatViewModel.connectWebSocket() mirrors the same terminal-state guard so
the chat tab never disturbs an already-working or already-recovering
connection. Behavior-preserving: happy path (CONNECTED) and genuine
terminal states (DISCONNECTED/NO_NETWORK) still connect as before.
* fix(#470): sync cookie store scope with selected profile ID
Update AuthManager to switch CookieManager to the active server profile ID on startup and on runtime profile change.
* fix(#470): prevent stale token cache and load initial cookie scope
Pass active profile scope to CookieManager.initialize on startup and update setProfileToken to sync the in-memory cachedToken.
* feat(chat): add re-login action and credentials popup to connection banner
Add a Re-login button to the connection status banner and a dialog to prompt for credentials, allowing the user to refresh session cookies/tokens and reconnect the WebSocket.
* fix(chat): address PR #495 review feedback
* fix(chat): restore reconnect action in banner
* fix: resolve composable invocation in ReloginDialog
* fix(chat): enable re-login action during reconnecting state
Add the Re-login button to the connection status banner when connectionStatus is RECONNECTING, allowing users to re-authenticate and resolve stuck reconnect loops.
* fix(chat): surface all disconnected states in reconnect banner (issue #491)
The connection-status banner only appeared for RECONNECTING/DISCONNECTED,
so NO_NETWORK and AUTH_EXPIRED left the user staring at a silent chat with
no feedback and no way to recover — the core of the 'reconnecting is not
user-friendly' complaint.
ChatTopBanner now shows for every non-connected, non-connecting state:
- RECONNECTING: spinner + 'Reconnecting to Hermes…' (auto, no button)
- DISCONNECTED: 'Disconnected from Hermes' + Reconnect
- NO_NETWORK: 'No network connection' + Reconnect (force a retry)
- AUTH_EXPIRED: 'Session expired' + 'Sign in again' -> AuthLoginScreen
The auto-reconnect engine (backoff, network-return trigger, in-flight
message queue in HermesWsClient) is untouched — this only makes the stuck
states visible and actionable.
* fix(chat): use LocalHermesStatusColors for reconnect banner (review fix)
Per AGENTS.md, semantic status colors must come from
LocalHermesStatusColors, never MaterialTheme.colorScheme. The reconnect
banner used errorContainer/onErrorContainer directly, which is both a
semantic-color violation and inconsistent with the rest of the app
(Navigation.kt maps DISCONNECTED/NO_NETWORK/AUTH_EXPIRED -> .error;
TelegramOnboardingDialog uses .errorContainer for error surfaces).
Switch Surface bg to errorContainer and foreground (spinner, text,
button content) to error via LocalHermesStatusColors.current.
* fix(chat): make search bar clickable by giving ChatMessageList a vertical layout
The search bar (AnimatedVisibility) and the message LazyColumn were
emitted as siblings with no container. The call site is a Box, which
overlays children — so the LazyColumn rendered on top of the search bar,
intercepting every pointer event. The bar stayed visible but was dead
(nothing inside clickable: input, nav arrows, close).
Wrap ChatMessageList's children in a Column so the bar occupies real
layout space above the list; the LazyColumn now takes weight(1f) and
scrolls independently. Fixes#490.
* refactor(chat): simplify search-list LazyColumn modifier
Use fillMaxWidth().weight(1f) instead of fillMaxSize().weight(1f) inside
the new Column — weight already claims the remaining vertical space, so
fillMaxSize was redundant/contradictory (Sourcery review nit).
Note: the Sourcery 'use LocalHermesStatusColors' suggestion on the search
bar Surface is a false positive — that rule covers SEMANTIC status colors
(success/warning/error/info) only. surfaceContainerLow/outline are neutral
Material surface chrome, not status colors; LocalHermesStatusColors does
not even expose them. The corresponding status dot correctly uses StatusRed.
* refactor(chat): extract streaming state into ChatStreamingController
Moves streaming buffers, streamingMessageId, and the two token/delta
handlers out of ChatViewModel into a dedicated controller. Mirrors the
ChatSearchDelegate seam; _streamingState stays VM-owned and the WS
reducer is untouched. Behavior-preserving, ChatScreen unchanged.
* refactor(chat): drop write-only streamingMessageId in ChatStreamingController
Sourcery flagged streamingMessageId as write-only. Verified via git grep
that it was write-only in origin/main too (zero readers anywhere in the
repo), so removing it is behavior-preserving. beginStreamingMessage() now
delegates its buffer reset to resetStreaming() to remove the duplication
Sourcery noted. Kept the injected scope param — it mirrors the
ChatSearchDelegate seam (that delegate uses scope.launch) and keeps the
controller constructor shape consistent.
* refactor(chat): extract ChatSearchDelegate from ChatViewModel god-object
Move the 4 search methods (toggleSearch/setSearchQuery/navigateSearchMatch/
clearSearch) + searchJob field into a dedicated ChatSearchDelegate that owns the
chat-search state transitions against the shared _uiState flow. ChatViewModel
keeps thin one-line delegating wrappers so its public API (used by ChatScreen)
is unchanged.
This is the first separable slice of the ChatViewModel god-object (1421 LOC,
47 funcs). Streaming/session/WS clusters are intentionally left in place - they
are entangled and will be addressed separately to avoid splitting one logical
op across classes.
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(chat): extract ChatAttachmentsDelegate from ChatViewModel
Move addAttachment/removeAttachment/clearAttachments into a dedicated
ChatAttachmentsDelegate that owns pendingAttachments state transitions against
the shared _uiState flow. ChatViewModel keeps 3 one-line delegating wrappers -
public API unchanged. Read sites (sendMessage) already read pendingAttachments
straight off uiState, so no delegate read API needed.
Second separable slice of the ChatViewModel god-object (after #486 search).
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(chat): address Sourcery review on search extraction
- Inject the CoroutineDispatcher into ChatSearchDelegate instead of
hardcoding Dispatchers.Default (defaults to Dispatchers.Default so
behavior is unchanged; now customizable per environment).
- Group the four search delegating methods in ChatViewModel under a
'Compatibility façade' comment marking them as the transitional API
surface around ChatSearchDelegate.
* refactor(ui): extract SkillsStep to components package
Move the 252-LOC SkillsStep composable out of ProfilesScreen.kt into
ui/profiles/components/SkillsStep.kt. Body is verbatim (behavior-preserving);
only package + imports changed. Parent now imports and calls it directly.
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
Note: sibling screens resolve Modifier.weight() without an explicit import;
matching that convention (no spurious weight import) to avoid the
internal RowColumnParentData.weight shadowing error.
* refactor(ui): extract ProfileBuilderView cluster to components package
Move the Profile Builder wizard (ProfileBuilderView + validateProfileName +
IdentityStep/ModelStep/McpStep/AddMcpDialog/ReviewStep) out of ProfilesScreen.kt
into ui/profiles/components/ProfileBuilderView.kt. Body is verbatim
(behavior-preserving); only package + imports changed.
Notable wiring required:
- validateProfileName kept as internal fun: it is also used by the parent's
clone dialog, so both the screen and the builder share it via import.
- ProfilesUiState/ProfilesViewModel imported from the ui.profiles package.
- SkillsStep call resolves to the already-extracted sibling file (same package).
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(ui): extract MoaConfigDialog cluster to components package
Move the Mixture-of-Agents config dialog (MoaConfigDialog + MoaConfigEditor +
MoaSlotPicker + MoaPickerTarget sealed class) out of ModelScreen.kt into
ui/model/components/MoaConfigDialog.kt. Body is verbatim (behavior-preserving);
only package + imports + entry visibility changed.
- Entry MoaConfigDialog is internal (called by ModelScreen root); the editor,
slot picker, and sealed class stay private to the new file.
- The @Composable annotation preceding the declaration is moved with the
cluster (earlier attempt left it orphaned, causing a duplicate-annotation
compile error at the next declaration).
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(ui): extract PlatformCard + TelegramOnboardingDialog clusters
Move two self-contained clusters out of ChannelsScreen.kt:
- PlatformCard.kt: StateStyle (private data class) + platformStateStyle +
StateBadge + PlatformCard. Entry PlatformCard is internal (called by
ChannelsScreen root); StateStyle/StateBadge/platformStateStyle stay private.
- TelegramOnboardingDialog.kt: TelegramOnboardingDialog. Entry internal.
Wiring required:
- ConfigureForm kept in ChannelsScreen as internal (shared by PlatformCard
and the screen root) and imported into PlatformCard.kt.
- ChannelsUiState/OnboardingPhase imported from the ui.channels package.
- formatTimestamp left in the screen (used by ConfigureForm).
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(ui): extract SkillsScreen sub-composables to components package
Split the 914-line SkillsScreen.kt into the screen root plus 4 cohesive
component files under ui/skills/components/:
- SourceBadge.kt: shared SourceBadge (internal, used by both tabs)
- InstalledSkillsTab.kt: InstalledSkillsView + SkillCard + SkillPreviewDialog
- HubSkillsTab.kt: HubBrowseView + HubSkillCard
- SkillEditorDialog.kt: SkillEditorDialog
Wiring required:
- CATEGORY_ALL promoted private -> internal in SkillsScreen (shared by the
screen root and InstalledSkillsView) and imported where needed.
- SkillFilter / SkillsUiState imported from the ui.skills package.
- HubBrowseView now reads isHubSearching/hubResults/hubSearchError off its
SkillsUiState param (fields, not locals) - no behavior change.
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* refactor(ui): extract SettingsScreen + SystemScreen sub-composables
SettingsScreen.kt (1238 -> ~340): move self-contained sections into
ui/settings/components/ - ConnectionSection (+TestResultCard/SaveIndicator/
TestConnectionButton), BehaviorSection, AppearanceSection (+ChatSection/
NavBarSection), AboutSection, ProfileEditorDialog (+DeleteProfileConfirmDialog).
Shared leaves SectionCard/InfoRow kept in the screen as internal and imported
by the extracted files.
SystemScreen.kt (1755 -> 1619): move CredentialEntryRow + HookCard into
ui/system/components/ (both internal). formatBytes/formatDuration helpers stay
in the screen (used by the root and remaining content).
Verified: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
* fix(#485): use LocalHermesStatusColors for PlatformCard state colors
Map platform connection-status badges to semantic LocalHermesStatusColors
slots (success/warning/error) + add neutral slot for not_configured/disabled.
Removes hardcoded hex (Color(0xFF...)) and MaterialTheme.colorScheme usage
flagged by Sourcery; neutral defaults to StatusGrey so existing theme
providers are untouched.
Replace the manual session-cookie interceptor in ApiClient and the
manual cookie branch in TokenRefreshAuthenticator with a shared
PersistentCookieJar backed by an encrypted, per-server EncryptedCookieStore.
- Add CookieStore iface + EncryptedCookieStore (EncryptedSharedPreferences,
per-server scope, legacy single-cookie migration)
- Add CookieSerialization (OkHttp Cookie <-> holder) + PersistentCookieJar
(in-mem cache, async persist, atomic useStore scope switching, prune,
session-cookie accessor)
- Add CookieManager coordinator (init/useStore/prune/clear) and wire its
cookieJar into OkHttpProvider base/websocket/probe (lazy)
- AuthManager.get/setSessionCookie now delegate to CookieManager; add
pruneServerCache(); clear path drops the scope's session cookie
- AuthLoginViewModel + HermesWsClient rely on the jar for Set-Cookie capture
and session-cookie re-attachment (no manual header injection)
- Add fakes (FakeEncryptedCookieStore/buildFakePersistentCookieJar) + unit
tests (PersistentCookieJarTest, CookieManagerTest); inject fake jar into
ApiClientTest/HermesWsClientTest setup
WS token-out-of-URL (step 5) deferred: backend hermes-agent authenticates
WS only via ws.query_params, so moving it requires a coordinated backend
change (noted for follow-up).
Verified: testDebugUnitTest (334 passing) + assembleDebug green via local SDK.
* Remove Settings connection profile dropdown; make saved-profile cards tappable to switch
The profile dropdown in the Settings > Connection tab was the only way to
switch the active profile from Settings. Removing it left a regression, so
each saved-profile Card now has clickable { viewModel.selectProfile(profile.id) }
reusing the existing isActive highlight. The isNotEmpty guard stays so the
section hides cleanly when there are no profiles.
* Tighten spacing between Test Connection and Logout buttons (16dp -> 8dp)
* Tighten Test Connection / Logout spacing further (8dp -> 4dp)
* Tighten Test Connection / Logout spacing further (4dp -> 2dp)
* Add accessibility role to profile cards (clickable role = Role.Button)
Sourcery flagged the now-clickable profile Card as missing semantics for
assistive tech. Use clickable(role = Role.Button) so TalkBack announces it
as an actionable control. Role import added.
- Remove the Logout button from the About tab content.
- Add the Logout button at the bottom of the Connection tab so users
can sign out directly where they manage their connection.
- Delete the unused, duplicate AboutSection() composable (it was never
called and carried its own Logout button) to keep a single source of
truth for the action.
Logout behavior is unchanged: it still calls viewModel.logout() then
onLogout() (navigates to login). Verified with assembleDebug + ktlint.
* fix(#478): rework default login to use unified ConnectionProfile model
- AuthManager: drop legacy auth_token path; getToken/setToken now delegate
to the selected profile (profile token only, no global fallback)
- setHost/setPort always write the selected profile (no top-level host/port branch)
- Add DEFAULT_PROFILE_ID + ensureDefaultProfile()/ensureDefaultSelected() so the
selected profile is never null; ensureDefaultSelected() only falls back when
nothing is selected (never clobbers an existing choice); ensureDefaultProfile()
only injects a Default profile on fresh install, never into an existing list
- One-time migration folds legacy standalone auth_token into the Default profile,
batched into a single SharedPreferences transaction (guarded by legacy_default_migrated)
- ConnectViewModel.connect() persists via setToken/setHost/setPort (delegate to
the selected profile) — keeps the existing persistence contract
- Connect/Settings: remove the '(none)'/standalone profile option; deleteProfile
falls back to Default profile instead of null selection
- Update AuthManagerTest/ConnectViewModelTest to the unified model; fix test
stub ordering + migration re-init; remove dead connect_profile_none / settings_profile_none strings
Closes#478
* fix: stub AuthManager.ensureDefaultSelected() in E2eIntegrationTest
The #478 ConnectViewModel.connect() success branch now calls
AuthManager.ensureDefaultSelected() on the non-saveProfile path.
E2eIntegrationTest.setUp() mocks AuthManager as a non-relaxed mockkObject
but never stubs that method, so the unstubbed call throws MockKException inside
viewModelScope.launch, leaving connectionSuccess unset and failing 3 tests:
- testFullUserSessionFlow
- testConnectViewModel_onPairingString_base64Format
- testConnectViewModel_onPairingString_urlFormat
Add the missing stub. Verified locally: full suite 322/322 passing.
---------
Co-authored-by: ronia <ronia@m57>
- ChatViewModel: drop fetchAndDisplayStatus/Sessions/Stats — left behind
after slash-command dispatch rework (e7b2973c); /status /sessions /stats
now route to backend via SlashCommandDispatcher.RpcDispatch -> WS COMMAND_DISPATCH.
Zero call sites, grep-confirmed.
- AuthManager: drop KEY_SELECTED_PROFILE_ID const — selected profile id
moved to ServerStore StateFlow (getSelectedProfileId/setSelectedProfileId).
Legacy PREFS key never read.
- Theme: drop ENABLE_DYNAMIC_COLOR const — theming reads useDynamicColors
setting (Theme.kt:318), not this const. Dead since that refactor.
Verification: ktlintCheck PASS, compileDebugKotlin PASS (local SDK).
Per behavior-preserving-cleanup: grep zero refs, not exported, no
dynamic/reflection access, git blame shows original intent superseded.
* feat(#480): pass refresh=true on Models pull-to-refresh to re-probe custom providers
* test(#480): assert refresh flag propagation for default vs pull-to-refresh loads
* fix(#480): capture refresh arg via slot instead of brittle coVerify in propagation test
---------
Co-authored-by: ronia <ronia@m57>
* feat(#471): implement DataStore-based server configuration and self-healing
* refactor(#471): address Sourcery feedback on ANR risk and reset method splitting
* refactor(#471): implement synchronous ServerStore initialization to fully remove ANR risk
* feat(#471): show profile name, host and port on add profile, redirect to login on save, and support shortcut login buttons for existing profiles
* refactor: migrate Gson serialization to kotlinx.serialization
* fix(dto): resolve serializing Any? and Map<String, Any?> with JsonElement
* test(refactor): fix unit test issues under kotlinx.serialization and update nullable DTO defaults
* fix(chat): support flexible numeric and string decoding for message timestamps
* fix(chat): sequentialize cache loading to avoid overwriting network state