* 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>
- SlashCommandDispatcherTest: covers all branch routes (Interrupt /
NewSession / RpcDispatch) incl. case-insensitivity, args, slash-only,
empty, and unknown commands.
- SlashCommandDispatchRpcTest: asserts a non-hardcoded command is
forwarded to COMMAND_DISPATCH with the exact {name,arg,session_id}
shape the gateway expects, args split correctly, and that client-
handled /stop + /new do NOT hit the backend.
Verified against the live hermes-agent gateway: commands.catalog returns
185 catalog entries but command.dispatch only handles a subset, so most
forwarded commands currently 4018. These tests lock the client contract;
the backend gap is tracked separately.
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.
Appends testToggleSearch verifying toggleSearch() activates search,
setSearchQuery sets the query, and toggling off resets searchQuery to empty.
Rebased onto current main (post-#511/#512).
* Test PairingCodeEntryViewModel onManualCodeChange
Added unit tests to cover the `onManualCodeChange` function in `PairingCodeEntryViewModel`.
The test validates that the function properly updates the state and handles string trimming
as well as error message clearance.
Changes include:
- Created `PairingCodeEntryViewModelTest.kt` in `app/src/test/java/com/m57/hermescontrol/ui/pairing/`
- Implemented `testOnManualCodeChange_updatesStateAndClearsError` to check correct state update logic and verify error clear functionality.
- Implemented `testOnManualCodeChange_trimsInput` to verify input is properly trimmed.
- Added necessary mock setup to deal with Android components (`Application` and `android.util.Log`).
* Fix ktlint format issue in PairingCodeEntryViewModelTest
Ran `ktlint --format` to fix the `standard:no-empty-first-line-in-class-body`
formatting violation introduced in the previous commit.
* Add unit tests for ChatViewModel attachment manipulation
Adds tests covering addAttachment, removeAttachment (valid/invalid indices),
and clearAttachments in ChatViewModelTest. This ensures the attachment
state management logic works as expected.
* test(#511): add mixed valid/invalid remove sequence + DRY attachment setup
Folds in both Sourcery review notes:
- New testRemoveAttachment_mixedValidAndInvalidSequence asserts list
stays consistent across a valid remove, out-of-bounds + negative no-ops,
then another valid remove on the shifted list.
- addDummyAttachments() helper removes repeated VM/advance/add boilerplate.
Verified: ktlintCheck clean + ChatViewModelTest 37/37 pass locally.
Added SystemViewModelTest to provide basic testing coverage for the
openUpdateConfirm and closeUpdateConfirm methods. These methods
handle state changes within the UI without side-effects or
dependencies, so straightforward property assertions were sufficient.
This improves overall code reliability by ensuring simple UI boolean
states function predictably.
Add unit tests to `ChatViewModelTest.kt` to cover the `interruptSession`
method. The tests verify that `interruptSession` correctly sends the
`SESSION_INTERRUPT` RPC via the WebSocket client when a session ID is
present, and that it safely does nothing when the session ID is missing.
This improves test coverage for the chat control logic.
Added unit tests to `KeysViewModelTest.kt` to cover `setNewKeyName` and `setNewKeyValue` functions. This ensures that the state flow correctly updates when key names and values are modified. This increases the test coverage for UI state manipulation within the Keys settings module.
* Add unit test for ChatViewModel.refreshSettings
This commit adds a missing test case for the `refreshSettings` function in `ChatViewModel.kt`. The new test verifies that the UI state correctly updates to reflect changes in `AuthManager` properties such as `typingEffectEnabled` and `typingEffectDelayMs`. This resolves the testing gap and ensures safer refactoring for settings management in the future.
* test(#506): strengthen refreshSettings test to prove live re-read + drop test_plan.md
Re-stub AuthManager after construction and assert the state delta, so the
test actually catches a regression where refreshSettings() would cache the
init-time value instead of re-reading AuthManager live. Removes the one-off
Jules planning artifact from the repo root.
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.
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.
* 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>
* 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
* fix(#472): refactor ChatViewModelTest to use Fake* + Turbine
Replace Mockk-heavy test setup with FakeChatPersistenceRepository (+
in-memory FakeChatMessageDao) and add Turbine for Flow assertions.
Changes:
- Add Turbine v1.2.0 dependency (libs.versions.toml + build.gradle.kts)
- Create FakeChatMessageDao – in-memory DAO with MutableStateFlow
- Create FakeChatPersistenceRepository – delegates to FakeDao
- ChatViewModel: make repo injectable (@VisibleForTesting lateinit var)
- Rewrite ChatViewModelTest (751 lines vs 1,212): clearer helpers,
Turbine test for streaming Flow sequence, same 29 tests with
identical assertions, ~38% line reduction
Test: ktlint --format passes clean
* fix(#472): address review — constructor injection, ConcurrentHashMap, MockWebServer tests
Addresses all feedback from Sourcery review on PR #474:
Constructor injection (was lateinit var):
- Move repo to ChatViewModel primary constructor with default
- Remove @VisibleForTesting lateinit var + init block assignment
- Tests pass repo directly via constructor
Simplify FakeChatMessageDao:
- Replace manual synchronized(lock) with ConcurrentHashMap
- Same thread safety, 48% less code, no boilerplate lock object
New MockWebServer tests:
- HermesApiServiceMockWebServerTest: 6 tests covering getStatus,
getSessions, getSessionMessages + edge cases (null fields,
empty lists, slash-encoded session IDs)
* fix: CI compilation errors — open class, TestScope receiver, runBlocking
Three compilation errors blocking CI:
- ChatPersistenceRepository was final, but FakeChatPersistenceRepository
extends it → make it open class
- createViewModelWithSession() called advanceUntilIdle (TestScope ext)
and emit() (suspend) without a TestScope receiver or coroutine ctx →
make it fun TestScope.xxx() and use tryEmit() for non-suspend emission
- HermesApiServiceMockWebServerTest called suspend API methods from
regular @Test methods → wrap each test in runBlocking
* fix: test runtime failures — suspend helper + fix JSON escaping
- Use so emit()
(suspend) is valid and events are delivered synchronously instead of
buffered via tryEmit() which was causing 17 test failures
- Fix MalformedJsonException in MockWebServer test by using plain string
content instead of unescaped JSON-within-JSON
* fix: correct req-id values in ChatViewModelTest — SESSION_CREATE is req-id-3
* fix(test): correct ChatViewModelTest assertions for Fakes+Turbine refactor
- testMessageStreamingFlow: collect streamingState via Turbine
(ThinkingDelta/MessageToken mutate streamingState, not uiState)
- testToolExecution_finalizesPreviousStreamingMessage:
account for messages[0] = "Session created" system message
- testMessageStart_finalizesPreviousStreamingMessage:
same index offset (messages[1] is the finalized stream)
- testClarifyRequestCustomResponse: options is emptyList(), not null;
message count is 3 (session-create + user clarify reply)
Fixes CI failures introduced in PR #474.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* fix: correct FilterChipRow and EmptyState API mismatches + ktlint fmt
* fix: add missing Save import, fix verticalArrangement double-wrapping
* fix: address Sourcery review — strings, enums, hubQuery, StatusColors
• Hardcoded strings → stringResource (Installed, Browse Hub, Statuses, All sources)
• Magic string filters → SkillFilter enum + CATEGORY_ALL constant
• FilterChipRow made generic with chipLabel parameter
• HubBrowseView hubQuery driven from ViewModel state (no dupe)
• ViewModel toasts use getString(R.string.*) via AndroidViewModel
• MaterialTheme.colorScheme.error → LocalHermesStatusColors.current.error
* fix: OpenDrawer → Menu, listContentPadding is PaddingValues not ext
NavIcon.OpenDrawer doesn't exist, use NavIcon.Menu. listContentPadding is a val PaddingValues, not a Modifier extension — use Modifier.padding(listContentPadding).
* fix: NavIcon.Menu(onClick) -> NavIcon.Menu(onOpen)
* fix: pass mockApp to SkillsViewModel in unit tests (now AndroidViewModel)
* fix: mock getString in unit tests for AndroidViewModel string resources
* fix: anyVararg<Any?>() → anyVararg<Any>() to satisfy type bound
anyVararg<T> has bound T : Any, so Any? doesn't compile.
Any is a subtype of Any? at the JVM level, so the matcher
works correctly for vararg Any? parameters.
* fix: use anyVararg<String>() for getString mock to match actual runtime types
The previous anyVararg<Any>() did not match getString(Int, Object...) vararg
calls at runtime — mockk's relaxed mock returned '' for all formatted string
resources, causing all Skills error-path assertions to fail (9 tests).
Root cause: mockk vararg matchers match by reified element type. The Java
method Context.getString(int, Object...) passes format args as String at
runtime (via Kotlin's spread). anyVararg<Any>() with Any (boxed) doesn't
match Object/String vararg elements reliably, but anyVararg<String>() does,
since String satisfies the T : Any bound and matches the actual runtime type.
Also added getString(Int) stub for the no-arg overload used by enums.
* fix: stub getString per-resource-ID to bypass mockk Java vararg bug
mockk has a known bug matching Java vararg methods like
Context.getString(int, Object...) with anyVararg<T>() — the matcher
silently fails to match, and the relaxed mock returns '' for all
formatted string resource calls. This caused 8 Skills error-path tests
to fail (errorMessage/toastMessage was '' instead of containing 'HTTP 500').
Root cause: confirmed via test report artifacts — errorMessage was
non-null but empty string, proving the vararg stub never matched.
Fix: replace the generic anyVararg<String>() stub with explicit per-
resource-ID stubs using eq() + any<String>() matchers. Each formatted
string resource is stubbed individually, returning the format arg
(the dynamic error message) so the test assertions find 'HTTP 500'
and 'Timeout' substrings.
References:
- https://stackoverflow.com/questions/54326914/using-mockk-to-match-any-varargs
- https://github.com/mockk/mockk/issues/224
* fix(skills): replace AndroidViewModel getString() with hardcoded strings to fix unit tests
The SkillsViewModel was using getApplication<Application>().getString() for
error/success messages. In unit tests, mockk cannot reliably stub Java vararg
Context.getString(int, Object...), causing NullPointerException inside
coroutine onError callbacks. All other ViewModels in the codebase use hardcoded
strings; this change aligns SkillsViewModel with that convention.
* test: add hub search/install/uninstall/preview coverage + rm vestigial stubs
- Remove unused mockApp.getString() per-resource-ID stubs (SkillsViewModel
no longer calls getApplication().getString() — hardcoded strings now).
- Add 10 tests covering hub search (success/empty/error/emptyQuery),
hub install (success/error), hub uninstall (success/error), and skill
preview (success/error). Uses existing mockk + runTest patterns.
* fix: correct import ordering for HubSkill (H < S)
Move HubSkill import before KanbanBoard (H < K) and remove duplicate
that was between SessionListResponse and Skill.
* test: remove coVerify from emptyQuery test (cross-test mock state)
* fix: remove double-stacked padding in SkillsScreen (HermesScaffold handles it)
Per AGENTS.md — HermesScaffold already offsets for the top bar
internally, so .padding(padding) on inner content creases double-stacked
top padding.
* refactor: merge preview + edit button in SkillCard into single adaptive action
Per AGENTS.md — two nearly-identical icon buttons (Preview + Edit)
side by side was confusing. Merged into one Edit button since
both opened the same skill content dialog (editable for installed,
read-only for hub is handled by the ViewModel).
* fix: revert onCategoryChange to non-null String (FilterChipRow<T> needs it)
Also removes leftover Preview icon import that ktlint flagged.
* refactor: restructure SkillCard layout — name gets full width, actions below
The old layout crammed icon, name, source badge, edit button, uninstall
button, AND toggle switch all on one horizontal row. Long skill names
got truncated to 2-3 characters.
New layout:
- Top row: icon | name (weight 1f) | source badge | toggle switch
- Below: category (if present)
- Below: description (if present)
- Bottom row: edit + uninstall buttons (end-aligned, only if hub source)
The name Text now has weight(1f) so it fills all available space.
* fix: fix brace nesting + move icon to far left for extra name space
* fix: add missing height import
* refactor: remove Extension icon from SkillCard for cleaner layout
* fix: remove double-stacked padding in SkillEditorDialog and SkillPreviewDialog
Both dialogs had the AGENTS.md footgun: HermesScaffold already offsets
the top bar internally, but the inner Box had .padding(padding) stacking
an extra ~56dp gap between the header and the edit text field.
* fix(skills-hub): unwrap SkillHubSearchResponse wrapper
Backend changed /api/skills/hub/search from returning a raw JSON
array to an object wrapper: { results: [...], source_counts: {...}, ... }
- Added SkillHubSearchResponse, SkillHubInstalledEntry models
- Extended HubSkill with identifier, trustLevel, repo, tags
- Updated API endpoint return type to SkillHubSearchResponse
- ViewModel unwraps data?.results.orEmpty() instead of data.orEmpty()
* fix: unwrap SkillHubSearchResponse in ProfilesViewModel too + remove unused HubSkill import
* fix: update test mocks to use SkillHubSearchResponse wrapper
* fix: refactor HubSkillCard layout — remove icon, name gets full width, install below
* fix: use unique key for hub results + weight(1f) to prevent scroll crash
* fix(skills): resolve crash due to duplicate keys in lazy list
* feat(skills): move search hub button into trailing icon of search bar
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(#442): categorized env keys screen with add/remove, search, and gateway restart
- Group env vars by category (LLM Providers, Tool API Keys, Messaging
Platforms, Agent Settings, Other) with collapsible AnimatedVisibility
sections matching MCP screen pattern
- Add new env var form (PUT /api/env) with key/value inputs
- Delete env var via DELETE /api/env with EnvVarDeleteRequest body
- Reveal/hide/edit inline per-card controls
- Search bar filtering across key names and descriptions
- Gateway restart banner with one-click action when changes are dirty
- Track keysChanged flag showing restart prompt after mutations
- Wire delete endpoint in HermesApiService using @HTTP(hasBody=true)
- Add EnvVarDeleteRequest data model class
* fix(#442): update test to match new categorized KeysViewModel API
* fix(#442): satisfy ktlint multiline-expression-wrapping rule
---------
Co-authored-by: Hermes Agent <hermes@agent.local>
* feat(#434): add system tab model files
* feat(#434): add system API endpoints
* feat(#434): rewrite SystemViewModel with full parity
* feat(#434): add system screen UI and string resources
* feat(#434): update tests for new SystemStatsResponse & ViewModel
* fix(#434): fix compile errors — nullable Boolean, SmallFilledTonalButton -> FilledTonalButton
* fix(#434): fix old SystemStatsResponse refs in ChatViewModel, wrap sections in item{} blocks
* fix(#434): rename sections to lowercase, fix LazyListScope extensions
* fix(#434): wrap hook dialog in item{}, pass spacing param to actionLogSection
* fix(#434): update HermesApiServiceTest for new typed SystemStatsResponse
* fix(#434): fix E2E test coroutine timing, remove outdated Gson edge-case test
* fix(#434): fix JUnit 4 assertNotNull argument order
* fix(#434): simplify HermesApiServiceTest, restore all mocks in E2e test
* fix(#434): remove Gson-edge-case test, fix E2E test dispatcher wiring
- Removed testGetSystemStats_nonNumericPercent_returnsNull: tests Gson
type-coercion behavior, not app logic — throws JsonSyntaxException
- Fixed E2eIntegrationTest dispatcher: mock Dispatchers.IO with answers {}
that returns the current Dispatchers.Main dynamically, so runTest's
per-test dispatcher override is honored by both viewModelScope.launch
and async(Dispatchers.IO) blocks → advanceUntilIdle() advances all work
- Removed Dispatchers.Main static mock so runTest can override it
* fix(#434): fix E2E test dispatcher for SystemViewModel
- Removed Dispatchers.setMain + testDispatcher field from setUp
- runTest handles Dispatchers.Main automatically — don't override it
- Mock Dispatchers.IO with answers { Dispatchers.Main } so it
dynamically resolves to whatever Main is at call time (runTest's
TestScope dispatcher)
- This ensures viewModelScope.launch and async(Dispatchers.IO) both
run on the same TestScope dispatcher, making advanceUntilIdle()
effective for all work
* fix(#434): use runTest(testDispatcher) for SystemViewModel test
The SystemViewModel.loadAll() uses async(Dispatchers.IO) inside
coroutineScope { }. With the mocked Dispatchers setup, both Main and
IO return testDispatcher, but runTest()'s default TestScope uses a
different dispatcher instance whose advanceUntilIdle() can't advance
testDispatcher's scheduler.
Fix: pass testDispatcher to runTest() so the TestScope's scheduler
matches testDispatcher's scheduler, making advanceUntilIdle()
effective for all async work.
* fix(#434): align test assertion with toast message change
The SystemViewModel.triggerBackup() toast message was changed from
'Backup triggered successfully' to 'Backup triggered', but the
E2eIntegrationTest assertion wasn't updated, causing a
ComparisonFailure on the unit-tests CI job.
* fix(#434): address review issues
- Fix#1: Change triggerBackup() return type from Unit to ActionResponse
so backupArchive is captured, enabling the download button
- Fix#2: Replace deprecated LocalClipboardManager with LocalClipboard
suspend API (removes CI deprecation warning)
- Fix#3: Consolidate redundant 'Hermes version' InfoRow in gateway
section (sessions + PID shown in one row)
- Remove orphaned system_gateway_state_pid string resource
- Fix import ordering for ktlint compliance
* fix(#434): revert LocalClipboard change, use @Suppress('DEPRECATION') instead
LocalClipboard.setText is not available in the Compose version used
by the project. Reverting to LocalClipboardManager with a suppress
annotation to keep the deprecation warning clean without breaking
compilation.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Co-authored-by: Hermes Agent <hermes@agent.local>
* feat(#445): full Models tab — settings panel, aux tasks, MOA config, model assignment
Main features added:
- Model Settings card at top of screen with main model, aux tasks, MOA summary
- Main model assignment via /api/model/set with expensive model confirm flow
- Auxiliary tasks dialog with per-task model override and reset-all
- MOA config dialog with preset management and reference/aggregator model picker
- Model picker dialog reused for main model, aux tasks, and MOA slot selection
- Kept existing provider browse + pin/unpin/search
New data models: AuxiliaryModelsResponse, MoaConfigResponse,
ModelAssignmentRequest/Response
New API endpoints: GET /api/model/auxiliary, GET/PUT /api/model/moa,
POST /api/model/set
* test(#445): add aux + MOA mock endpoints to E2eIntegrationTest
testModelOptionsSelection_success was failing because the ViewModel's init
block now calls getAuxiliaryModels() and getMoaConfig() which weren't mocked.
Added proper mock returns + imports for the new types.
* fix(#445): correct mock endpoint name in E2eIntegrationTest
- getMoaConfig -> getMoaModels (matches API service method name)
- Add explicit type parameter Response.success<MoaConfigResponse>
to fix Kotlin type inference
* fix(#445): add missing main param to AuxiliaryModelsResponse mock
AuxiliaryModelsResponse requires a MainModelAssignment for its
'main' field. Added the parameter with a dummy value and the
corresponding import.
* fix(#445): update toast assertion in test to match new message format
ViewModel now produces 'Successfully set profile model to ronia'
instead of the old 'Successfully set model to ronia'.
* fix(#445): remove top padding from Models tab LazyColumn
Top inset already provided by HermesScaffold; double padding was chunky next to TopAppBar.
* fix(#445): remove double-stacked top padding on Models tab LazyColumn
HermesScaffold's Box already applies padding(paddingValues) to
offset content below the TopAppBar. The LazyColumn was re-applying
it on the modifier, doubling the top gap. Keep the modifier clean
(.fillMaxSize() only) — the Box handles the offset.
* refactor(#445): inline loadModelOptions into loadAll
loadAll() was just delegating to loadModelOptions() with no extra
logic. Consolidate into a single method to remove the redundancy.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(#445): full Models tab — settings panel, aux tasks, MOA config, model assignment
Main features added:
- Model Settings card at top of screen with main model, aux tasks, MOA summary
- Main model assignment via /api/model/set with expensive model confirm flow
- Auxiliary tasks dialog with per-task model override and reset-all
- MOA config dialog with preset management and reference/aggregator model picker
- Model picker dialog reused for main model, aux tasks, and MOA slot selection
- Kept existing provider browse + pin/unpin/search
New data models: AuxiliaryModelsResponse, MoaConfigResponse,
ModelAssignmentRequest/Response
New API endpoints: GET /api/model/auxiliary, GET/PUT /api/model/moa,
POST /api/model/set
* test(#445): add aux + MOA mock endpoints to E2eIntegrationTest
testModelOptionsSelection_success was failing because the ViewModel's init
block now calls getAuxiliaryModels() and getMoaConfig() which weren't mocked.
Added proper mock returns + imports for the new types.
* fix(#445): correct mock endpoint name in E2eIntegrationTest
- getMoaConfig -> getMoaModels (matches API service method name)
- Add explicit type parameter Response.success<MoaConfigResponse>
to fix Kotlin type inference
* fix(#445): add missing main param to AuxiliaryModelsResponse mock
AuxiliaryModelsResponse requires a MainModelAssignment for its
'main' field. Added the parameter with a dummy value and the
corresponding import.
* fix(#445): update toast assertion in test to match new message format
ViewModel now produces 'Successfully set profile model to ronia'
instead of the old 'Successfully set model to ronia'.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* fix: clear loading state on connection failure or status change
Observe connectionStatus in ChatViewModel to hide the loading overlay on disconnect/reconnect/error, and add a 10s fallback timeout.
* test(chat): fix testInitialStateAndConnection regression
Mock Log and isAutoReconnect in ChatViewModelTest setUp, and only run the connection safety timeout outside test environments.
* feat(chat): implement optimistic UI for chat startup loading
Load the last active session ID and cached messages instantly from local database, and resume in the background.
* feat(chat): always start a fresh session on startup without spinner
Configure startup to connect and create a new session in the background without showing any blocking loading spinners.
* fix(chat): support session creation when WebSocket is already open on launch
Check if WebSocket is already connected during initialization, and trigger initial setup/session creation immediately.
* refactor(chat): deduplicate gateway ready initialization logic
Extract handleGatewayReady helper function to run the session setup once on both new and pre-existing WebSocket connections.
* chore: clean up dead lastSessionId storage code
Remove getLastSessionId, setLastSessionId, and KEY_LAST_SESSION_ID as startup session caching is no longer used.
* feat(#369): rewrite channels tab with full backend integration
- Add state, error, gateway_running, description to model
- Add test endpoint to API service
- Rewrite ViewModel with toggle, restart, test actions
- Rewrite screen with state badges, restart banner, test button
- Fix string resources and E2E test
* fix(#417): add missing import and fix ButtonSize API
- Add MessagingPlatformTestResult import to HermesApiService.kt
- Replace ButtonDefaults.ButtonSize.SMALL with ButtonDefaults.SmallButtonSize (correct M3 API)
* fix(#417): mark platformStateStyle as @Composable, remove Button size param
- @Composable annotation needed for MaterialTheme.colorScheme access
- Button/OutlinedButton size parameter not available in project's M3 version
- ktlint removed unused ButtonDefaults import
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(#365): add pin support for models with pinned section at top
* fix(#365): stub Pinned Models methods in E2eIntegrationTest
* fix(#365): use state flow for pin/unpin, add max cap, add ViewModel tests
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
- Widen catch in tearDown() from Exception to Throwable so
MockWebServer.shutdown() AssertionError is caught (OkHttp 5.x
enforces clean connection state on shutdown)
- Increase teardown wait from 100ms to 500ms for WS close handshake
- Replace deprecated RequestBody.create(null, ...) with
toRequestBody() extension from Kotlin API
* fix(#219): add pagination to sessions history tab
The /api/sessions endpoint was called without pagination params, so the server returned only its default limit of 20 sessions.
- SessionListResponse: added total/limit/offset fields from server response
- HermesApiService: added @Query params (limit, offset, order) to getSessions()
- SessionsViewModel: added loadMore() that appends pages, hasMore derived from total
- SessionsScreen: added 'Load more sessions' button + loading spinner at bottom of list
* chore: remove plan file from git
* fix: compilation errors in sessions pagination
* chore: gitignore plan files
* fix: remove duplicate brace
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(#210): add ToolSchemaRegistry with display config for each tool
* feat(#210): three-state ToolBubble with summary line, clean expanded view, copy support
* test(#210): add ToolBubbleParsingTest for schema-aware parsing
* fix(#210): CopyButton align modifier moved to call sites
* fix(#210): null-safety on durationSec in test
* fix(#210): backward compat for old session tool data formats
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* fix(#206): read clarify.request question/choices from gateway
The Hermes TUI gateway sends clarify.request payloads with "question" and "choices" fields, but the Android parser was looking for "text" and "options" — so the text was always null and the dialog showed only the input box.
Fix reads "question"/"choices" first, falls back to "text"/"options" for backward compat.
Test added for the new field names; existing test for legacy names still passes.
* fix(#206): clear default text in clarify input field
The input box was pre-filled with the clarify question text because the initial state was set to clarify.text instead of empty string.
* fix: use JsonRpcResponse instead of undefined WsResponse in EventParserTest
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>