75ac0c47900159452d62648ec275ce619acc27d7
160
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
75ac0c4790 |
feat(profiles): first-class profile switching — phase 0 baseline port (#820)
* feat(profiles): make profile switching actually scope the app (issue #781 follow-up) * fix(profiles): inherit connection token when switching to same-dashboard profile (issue #781 follow-up) * fix(chat): reset open session on profile switch + prefill login profile (desktop parity) * fix(ws): inject profile into profile-scoped RPC params so chat follows the selected profile * test(chat): de-poison SlashCommandDispatchRpcTest (drop static Dispatchers mock) mockkStatic(Dispatchers::class) + a stubbed Dispatchers.IO bleeds JVM-wide and breaks later classes in suite order (CI 2026-08-06: COMMAND_DISPATCH captures cross-wired → ComparisonFailure on lower stack PRs). ChatViewModel gains an injected ioDispatcher (38 sites); the slash test constructs the VM with the test dispatcher so the IO stub is unnecessary. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
442e868ce2 |
feat(cron): blueprint start-from + delivery target picker in job editor (issue #780) (#822)
- New-job dialog gains a Start-from dropdown: pick a catalog blueprint, fill its typed slots (time/enum/weekdays/text), save instantiates it via POST /api/cron/blueprints/instantiate - Delivery field is now an editable picker fed by GET /api/cron/delivery-targets (origin + local + connected platforms) - Blueprints and targets fetched on editor open; 422 slot errors surface the backend detail Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
80be168801 |
feat(profiles): delete, rename, auto-describe and setup command (issue #781) (#818)
* feat(profiles): delete, rename, auto-describe and setup command (issue #781) * feat(profiles): use shared ModelPickerDialog for set model (issue #781) * fix(profiles): move overflow menu to card header so it can't be clipped (issue #781) --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
356ccc98b5 | fix(notification): resume stored session before reply (#805) | ||
|
|
e1a04a9396 |
⚡ Optimize PersistentCookieJar by removing runBlocking (#799)
* perf: remove runBlocking from PersistentCookieJar to fix overhead * perf: remove runBlocking from PersistentCookieJar to fix overhead * perf: fix PersistentCookieJar race condition using CountDownLatch * perf: remove runBlocking from PersistentCookieJar to fix overhead |
||
|
|
d1dac57ccb | fix(ws): reconnect after network handover (#808) | ||
|
|
83ec590ed8 |
fix(notifications): only run waiting-reply foreground service while a reply is pending (#795)
The chat notification FGS — and its mandatory persistent 'Waiting for Hermes replies' notification — was started on every ON_STOP of the chat screen, even when nothing was in flight, and lingered at app startup. Track a pending-reply flag on HermesWsClient (set when a prompt is submitted and on any in-flight turn event, cleared on MessageComplete), gate NotificationHelper.start() on it, and have the service retire itself after delivering the reply notification in the background. Replies sent from the notification re-arm the service for the follow-up turn. Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
1870b375b1 |
feat(skills): hub sources + featured landing and security scan (#779) (#793)
Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
00a0eedc77 |
feat(logs): server-side file/level/component/line filters (#777) (#792)
Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
5870b73397 |
feat(#776): pairing management screen (#791)
REST + Channels-style UI for DM pairing (list pending/approved, approve, revoke, clear). Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
44767fef4a |
feat(kanban): live board updates over plugin events WebSocket + kanban UI pass (#789)
* feat(kanban): live board updates over plugin events WebSocket (#775) Tail /api/plugins/kanban/events per board with cursor tracking and backoff reconnect; debounced REST reload on event batches (desktop's proven pattern — event payloads are partial updates). Board switch re-subscribes with a fresh stream. Reuses HermesWsClient's ticket refresh (now internal). Adds ServerEndpoint.webSocketUrl(path, ...) overload for non-chat WS endpoints. Kanban UI pass: add-task FAB (the AddTaskDialog was unreachable), live/offline status pill, assignee chip on task cards, 2-line description clamp, empty-column hint. Tests: KanbanEventsClient frame parsing, KanbanViewModel WS wiring (connect on load, debounced reload, board-switch reconnect, no-reconnect guard, onCleared), ServerEndpoint overload. * fix(kanban): create task response is wrapped {"task": ...} — read it as Unit Backend POST /api/plugins/kanban/tasks returns {"task": {...}} (wrapped), but the app declared Response<KanbanTask> — with ignoreUnknownKeys=true the wrapper key is skipped and the required id/title/status fields are missing, so deserialization threw and the create showed a failure toast while the task WAS created server-side (ghost tasks). The body is never consumed by the ViewModel, so Response<Unit> matches updateKanbanTask. FAB from the live-events PR (#775) made this latent bug reachable. Adds an E2e regression assertion for the create path. * feat(kanban): remove move left/right arrows — backend rejects the transitions The dashboard PATCH route's status whitelist omits 'review' (a first-class kanban_db status), so any move touching that column 400s, and reopen transitions (done->blocked) 409. Every task on the live board sits in 'done', making the arrows 100% failure. Removing them keeps the UI honest; tasks are managed from the desktop/CLI. Drops moveTask/revertTaskMove from the VM, the arrows from TaskCard, the now-dead updateKanbanTask API method and move strings; E2e test keeps load/create coverage. * feat(kanban): desktop-style task transitions — gated action sheet Mirrors the desktop kanban's move model: tap a card to open an action sheet with only the transitions the backend PATCH route accepts: - triage / ready from any status (direct write; unblock from blocked) - block only from running/ready, complete only from running/ready/blocked - archive from any non-archived status - never running (dispatcher-only, backend 400s) and never review (not in the dashboard whitelist) — the moves that made the old arrows lie Complete prompts for a mandatory completion summary (stored as result), matching the desktop; block/complete/archive ask for confirmation. Optimistic update with revert + toast on failure. Tests: transition-gating map, move PATCH body, failure revert, completion summary body; E2e kanban test covers a desktop-style todo->ready move. * ui(kanban): replace oversized FAB with compact top-bar add button The 56dp FAB floated over the board's bottom-right corner and covered a chunk of the last column. The add action now lives in the header row next to the live pill (input-top style), and the board's bottom contentPadding drops back to 16dp — no more reserved dead zone. * fix(kanban): mint an independent WS ticket — don't touch the chat's shared slot The dashboard WS ticket is single-use and consumed at handshake. Both the chat client and the kanban events client were refreshing into the SAME shared AuthManager token slot on their own schedules (the kanban client on every backoff reconnect, forever). Whichever client built its URL second grabbed the other's just-consumed ticket, got 1008, reconnected, and stole the other's next ticket — mutual starvation that left the app stuck at 'Reconnecting...' (repro on main: none, because main has one consumer). HermesWsClient now exposes mintWsTicket(): a ticket minted WITHOUT touching the shared slot (cookie-auth'd, same endpoint). The kanban events client uses its own ticket per connection; the chat WS keeps the shared slot. Refresh's HTTP-error -> status mapping is preserved via a small result holder. * fix(kanban): drop orphaned ko translations for removed move buttons The move arrows were removed earlier but values-ko still shipped content_desc_move_left/right — Android lint ExtraTranslation failed CI. * fix(ws): keep RECONNECTING on transient ticket-mint exceptions My refactor flattened the ticket-mint failure mapping: a network exception during POST /api/auth/ws-ticket was reported as a null HTTP code and mapped to DISCONNECTED, breaking the #740 contract that transient failures stay in RECONNECTING (and with it testGatedMode_transientTicketFailure- KeepsReconnectFlow). TicketRequestResult now carries an exception flag and refreshWsTicketIfNeeded maps it to RECONNECTING. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
37900a9af3 |
fix(#774): use GET for plugin rescan to match backend (#788)
Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
b4d0a7c9c3 |
fix(chat): preserve reasoning across tool calls + REST reload (#771) (#771)
* fix(chat): preserve reasoning across tool calls + REST reload (#771) A reasoning-model turn streams its thinking BEFORE the tool starts. The reducer wiped the streaming state at tool.start (returned a fresh StreamingState()), so the reasoning bubble vanished mid-turn and the finalized answer had no reasoning card. Real gateway capture for `run echo hi` (reasoning model): message.start reasoning.delta xN (thinking before the tool) tool.generating/start/complete (terminal) message.delta xN (answer after the tool) reasoning.available (FULL trace in payload text) message.complete (text + reasoning field) Fixes: - onToolStart keeps the streaming message + reasoningText alive across the tool call (only buffers are cleared via clearStreamingBuffers); an interim-text orphan still seals, but reasoning survives for the post-tool answer - EventParser now reads reasoning.available text and message.complete reasoning (the authoritative full trace the gateway sends) - onReasoningAvailable fills the streaming message with the full trace - onMessageComplete prefers the payload reasoning over delta leftovers - mapServerMessages folds reasoning-only empty assistant rows into the next real answer bubble (no more standalone reasoning ghost bubble) and carries tool names over from the live WS list by position (no more generic 'tool' title after a REST reload) Regression tests replay the captured sequence end-to-end. * fix(chat): dedupe WS + REST tool bubbles by result content (#771) The REST transcript tool rows carry no tool name, and WS messages (UUID ids) + REST rows (rest- ids) are BOTH persisted to Room — the cache paint and reloads could render the same tool call twice, with the second bubble falling back to the generic 'tool' title. Real captured pair for 'echo meow': terminal {tool_id, name, args, result:{...}} (WS) Tool {output, exit_code, error} (REST, no name) The previous positional carry-over misaligned whenever the REST page and the live tool list didn't line up 1:1 (multiple tool calls in history → newest call got null name). Fixes: - canonicalToolResultKey(): content-based matching between the WS tool.complete payload and the REST result row — int/float agnostic (0 vs 0.0), prefers the payload's 'result' field - mapServerMessages(): when a REST tool row's result matches a live WS tool message, REUSE the live message wholesale (same id + toolName + rich payload) so Room upserts instead of accumulating a rest- copy - dedupeCachedMessages(): cache paint drops rest- copies whenever a WS copy of the same logical message exists (tools matched by result, other roles by content) 11 new unit tests with the real captured payloads. * fix(chat): merge transcript reload with live WS bubbles (#771) The gateway persists a tool row only when the tool COMPLETES server-side. A REST transcript reload landing mid-turn (app background/foreground, reconnect re-resume, pull-refresh) therefore returned a page WITHOUT the in-flight tool row — replacing the message list outright made the tool bubble vanish and left tool.complete with no RUNNING message to update. - mergeTranscriptWithLive(): reload now merges instead of replacing — any current message the REST page doesn't cover (by id or logical content) survives, chronological order preserved - loadSessionMessages applies the merge before publishing state 4 new unit tests: in-flight RUNNING tool survives a mid-turn reload, reused-id and canonical-match cases don't duplicate, order preserved. * test(chat): end-to-end tool-bubble survival through mid-turn reload Chains the real user scenario at the state level: WS turn (message.start → reasoning → tool.start → tool.complete) + a transcript reload landing while the tool is still running server-side (REST page lacks the tool row) + stream finish. Asserts the tool bubble survives to the final list with its name and status intact. * debug(chat): add Logcat tracing for tool-bubble vanish (#771) Temporary diagnostic logging to catch the exact moment and code path where the tool bubble disappears. Logs to tag 'ChatReducer771' and 'ChatVM771' at every state mutation that touches messages: - onMessageComplete: message count + roles before the assistant append - loadSessionMessages: rest vs current vs merged counts and roles - syncCurrentSession: trigger + current tool count - sync merge: before/after merge counts and roles To reproduce: install this debug APK, run 'echo meow', watch the tool bubble vanish, then capture logcat: adb logcat -d -s ChatReducer771:D ChatVM771:D Will remove the logging once the root cause is pinned. * fix(chat): drop debug logging + harden sync merge (#771) The debug commit added android.util.Log calls in the reducer's onMessageComplete path, which is a Stub! in JVM unit tests — every test touching that path died with RuntimeException, and the long log lines broke ktlint (max-line-length). Remove them. Sync merge fix: the 5s sync poll could drop the newest WS tool bubble when the REST page lagged one row behind. Route the merge through sameLogicalMessage (canonical result-key match) and keep any WS message that has no REST counterpart. Adds 2 regression tests for the sync-merge scenario. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
e014d2a0e7 |
fix(chat): context meter reflects compression via session.context_breakdown RPC (#759)
* fix(chat): context meter reflects compression via session.context_breakdown RPC
The chat context meter read GET /api/sessions/{id} input_tokens — a
cumulative lifetime counter that compression never resets, so the meter
only ever grew and sat red after the first compaction.
Mirror the desktop: read live occupancy from the session.context_breakdown
WS RPC (context_used = compressor last_prompt_tokens, falling back to an
estimate of the live system prompt + tools + compacted history). The
compressor zeroes last_prompt_tokens when it runs, so the meter now drops
right after auto-compaction or /compress, exactly like desktop/web.
REST getSessionDetail is kept solely to feed the detail sheet's cumulative
token accounting. RPC failures keep the last known values; the meter never
blanks. Fixes #756.
* feat(chat): compressed xN badge on the context widget
The context chip now shows how many times the current session has been
context-compressed, sourced from the session.usage WS RPC (compressions =
context_compressor.compression_count) — the same usage snapshot the desktop
status bar reads. The badge explains a meter drop after auto-compaction or
/compress: the widget no longer just shows the number, it shows the story.
- UsageSnapshotResponse model + parseUsageSnapshot (Number-safe like the
breakdown parser — WS parser decodes JSON numbers as Double)
- compressionCount added to ChatUiState, reset on session switch/create/branch
- session.usage fires alongside session.context_breakdown in the 5s poll;
failures keep the last known badge value (best-effort, never blank)
- 3 parser tests; full local suite 615 tests green
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
|
||
|
|
63b966b133 |
feat(chat): add inline video player component and modal viewer (#722) (#732)
* feat(chat): add inline video player component and modal viewer Closes #722 * feat(chat): modernize video player with compact lock pill, save, and share * refactor(chat): simplify inline video thumbnail to launch fullscreen player on tap * fix(chat): pass session cookie and auth token headers to VideoView for protected media playback * fix(chat): format unquoted cookie header for VideoView auth * fix(chat): resolve video URLs via resolveImageUrl for gateway-hosted media |
||
|
|
422bb9f5e6 |
feat: support hosted OAuth for authenticated HTTP MCP servers (#751) (#752)
* feat: support hosted OAuth for authenticated HTTP MCP servers (#751) * fix(mcp): import McpOAuthFlowResponse in McpServersViewModel --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
1b596746af |
feat(chat/activity): Self-improvement event badges for memory & skill updates (#744)
* feat(chat/activity): Self-improvement event badges for memory & skill updates (#737) * feat(chat): Handle background review.summary WS events for self-improvement notices --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
e39544ebd5 |
fix: keep transient ticket failures reconnecting (#740)
* fix: keep transient ticket failures reconnecting * fix: recover rejected websocket sends * fix: serialize websocket reconnect scheduling |
||
|
|
5c1492a80e |
feat(chat): add animated GIF rendering with tap-to-play animation (#721) (#731)
* feat(chat): add animated GIF rendering with tap-to-play animation Closes #721 * fix(#721): add missing GifImageThumbnail component and format ktlint * fix(analytics): resolve ktlint indentation error in itemsIndexed * feat(chat): add interactive play/pause toggle for animated GIFs * fix(chat): control GIF playback via Animatable start and stop |
||
|
|
a1155e8015 |
feat(#724): full gateway-file support — attach MEDIA: files (images, audio, video, docs) (#725)
* fix(#724): inline host-path MEDIA: images on mobile (client-side) The previous approach re-fetched the REST session-messages endpoint, but that endpoint returns the raw MEDIA:<path> text (api_server._message_response does not inline, and the transcript stores raw content). The desktop app instead reads the file locally via readFileDataUrl because it is co-located with the host. Mirror that on mobile: on assistant message.complete/done, inline any MEDIA:<path> image into a base64 data:image/... markdown tag the renderer can show. Mobile-only, backend untouched. Unreachable tags are stripped (graceful degrade). Pure inlining logic extracted to MediaInline for unit testing. * fix: correct RegexOption name (IGNORE_CASE) in MediaInline * test: fix byte literal types in MediaInlineTest * fix(#724): rewrite host-path MEDIA: to gateway /api/files/download URL Pivot from the earlier base64-inline approach to the desktop-proven, remote-phone-working fix: rewrite MEDIA:<path> directives (delivered raw over the WS stream) into authenticated  markdown tags, mirroring desktop media.ts mediaExternalUrl. The mobile renderer (MarkdownText) shows http(s) ![]() via Coil, so agent-sent images now render on mobile too — including on a remote phone (real HTTP, unlike a host-local file read). Mobile-only, backend untouched. Pure rewrite logic in MediaUrlRewriter (replaces MediaInline) with unit tests. * feat(#724): full gateway-file support — attach MEDIA: files (not just images) Pivot the MEDIA: fix from image-only URL rewriting to real attachments: - Attachment: add gatewayUrl + AttachmentSource (LOCAL/GATEWAY) so gateway-hosted files are first-class and render via existing InlineAttachment. - HostMediaExtractor (replaces MediaUrlRewriter): parse ANY absolute MEDIA: directive (any extension) and strip them from message text. - ChatViewModel.attachHostMedia: build the authed /api/files/download URL via GatewayFileClient, classify via MediaTypes, attach as Attachment (images inline, every other file tappable). Idempotent. - InlineAttachment: tappable. Gateway files fetch via GatewayFileClient and share via a chooser Intent (FileProvider); images load the URL in Coil. - Hence agent-delivered images, audio, video, CSV, PDF and arbitrary files all work on mobile — including a remote phone. Backend untouched. Builds on #726 (GatewayFileClient). Rebased onto main after #726 merged. * fix(#724): resolve imports, bubble callback scope, and quoted media path regex * feat(chat): open attachment in-place on tap (#724) Tap opens LOCAL (content://) and GATEWAY (fetch->FileProvider) files via ACTION_VIEW; failures surface as a non-blocking snackbar via openError. * fix: remove redundant out-of-order io.mockk.* wildcard import (ktlint CI) ktlint import-ordering requires lexicographic order; the trailing wildcard 'import io.mockk.*' sorts before 'io.mockk.coEvery' and was redundant — every mockk symbol is already explicitly imported, and the single mockkConstructor call uses a fully-qualified io.mockk. prefix (needs no import). Fixes ktlint failure on PR #725. * fix(ci): mock android.jar Intent stub so openAttachment GATEWAY test passes android.jar unit-test stubs Intent.setDataAndType/addFlags to throw '... not mocked'. openWithView builds an Intent and calls them, so openBytes' runCatching swallowed the exception and startActivity never fired, failing the test. Mock the Intent constructor + setters and capture the constructed instance to assert the ACTION_VIEW contract. * fix(#724): resolve host media download URLs and deduplicate REST synced chat bubbles * fix(#724): add FLAG_ACTIVITY_NEW_TASK for file intents and update GatewayFileClientTest --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
6aee02c4da |
feat: add Files tab backed by the managed-files endpoint (#727)
* feat: add Files tab backed by the managed-files endpoint Add a Hermes Mobile tab that browses the gateway's managed-files root via the existing /api/files* backend routes: list/navigate folders, breadcrumb path, create folder, upload (streaming multipart), delete, and open files via the authenticated GatewayFileClient download URL. - data/model/ManagedFile: entry + list/read/upload/mkdir/delete models - HermesApiService: list/read/upload(+stream)/mkdir/delete endpoints - FilesViewModel: state, navigation, per-row busy, transient-state cleanup - FilesScreen: folder list, breadcrumb, FAB new folder, upload picker, delete confirm, open via system viewer - NavigationKeys + ScreenRegistry + strings: register in Inspect drawer section * fix(files): open files in-app via FileProvider instead of browser URL The previous file-open path handed a ?token=-authenticated URL to the system browser, but /api/files/download only accepts the ephemeral in-process session token as ?token=, not the mobile's Bearer token — so the request failed and the browser rendered the JSON error body instead of the file. Fix: download the file in-app through the authenticated client (Bearer/ session-cookie, same path as the rest of the app), decode the base64 data_url, write it to cacheDir, and open it via FileProvider.getUriForFile + ACTION_VIEW (mirrors the existing ChatScreen/SystemViewModel open-from-cache pattern). Works on a remote phone since the file is materialized locally first. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
439ae9fcba |
feat: gateway files client — fetch any gateway-hosted file over HTTP (#726)
* feat: gateway files client — fetch any gateway-hosted file over HTTP Add GatewayFileClient: a typed client for the gateway's managed-files download endpoint (GET /api/files/download?path=<enc>&token=<enc>), which streams the raw bytes of any file living on the gateway host. This is the mobile equivalent of desktop's mediaExternalUrl() and works on a remote phone (real HTTP, not a host-local file read). - buildDownloadUrl(): pure authed-URL builder (null on blank creds / non-absolute path), mirrors desktop's token-in-query auth. - fetch(): OkHttp GET via the shared client, maps 401/403/404/413 to typed GatewayFileResult variants; returns GatewayFile(name, mime, bytes). - MediaTypes: IMAGE/AUDIO/VIDEO/FILE classification by extension (mirrors desktop MEDIA_BY_EXT) so future consumers can present images, audio, video, or generic files — beyond just images. Pure builders/classifiers are unit-tested. Mobile-only, backend untouched. This is the foundation PR; issue #724's MEDIA: rendering will consume it. * fix: decode filename + handle download-URL in mediaNameFromPath - GatewayFileClient.parseFilename now URL-decodes the captured value so filename*=UTF-8''a%20b.png yields 'a b.png'. - MediaTypes.mediaNameFromPath extracts the filename from the percent-encoded path= query param of a full /api/files/download?path=<enc> URL (the real case), not just a bare path. * fix(remote): fix unit tests for gateway file client and media parsing Replace plus-encoded spaces with %20 in download URL builder, URL-decode filenames in parseFilename, and extract target filename from URL path parameters. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
0180fb12c2 |
Add used/full context meter to chat screen (#717)
* Adopt /api/health REST route (issue #713) Cheap liveness probe on the connection screen: GET /api/health surfaces backend version + auth mode (Token vs Gated/OAuth) without the heavier /api/status payload. Added HermesApiService.getHealth + HealthStatus model; ConnectViewModel.loadHealth probes on open (best-effort, silent on failure); ConnectScreen shows a read-only health card when reachable. Verified: ktlint clean, assembleDebug BUILD SUCCESSFUL locally. * Add used/full context meter to chat screen Shows session prompt tokens vs model context window above the composer, polled every 5s. Color-coded bar warns at 70%/90%. * fix(chat): fix unit tests for context usage meter Format >=100k tokens cleanly in ContextUsageChip and stub AuthManager profile ID in ChatViewModelTest. * Fix context meter: source used tokens from input_tokens Gateway /api/sessions/{id} has no last_prompt_tokens column; use input_tokens instead. Show meter as soon as full context is known. * Add tappable context breakdown sheet Chip opens a bottom sheet with input/output/cache/read/write/reasoning token rows + message count. Source breakdown from /api/sessions/{id}. * Refresh context meter on streaming complete Trigger fetchContextUsage immediately when a message finishes streaming instead of waiting for the 5s session-sync poll. * Fix context meter: source used tokens from live WS session.info The REST /api/sessions/{id} endpoint reads the DB input_tokens column, which is stale/0 for active sessions — that's why the meter was stuck at 0. Switch the meter to the live values the gateway pushes over the WS session.info payload after each turn: - used = last_prompt_tokens (real used context for the turn) - full = context_length (model-accurate window; keep /api/model/info as a fallback before the first turn completes) fetchContextUsage now only tops up the denominator from /api/model/info and no longer overwrites the live WS value with the stale REST input_tokens. The 5s poll remains as a fallback. * Revert "Fix context meter: source used tokens from live WS session.info" This reverts commit 932393fd80993d57e66fe93552a949460d646674. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
c181d1d593 |
Adopt session.redirect (issue #710) (#714)
* Add session.redirect affordance (issue #710) Route send through session.redirect while a turn is streaming and the prompt is plain text (no attachments, not a /command); otherwise prompt.submit. Adds WsMethods.SESSION_REDIRECT + HermesWsClient.sendRedirect. No separate button — the composer already sends mid-turn, so send just does the redirect. * fix(chat): capture typing state before sendMessage for redirect Capture wasStreaming state before updating uiState.isAgentTyping so normal sends call prompt.submit. --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
8c13f9bed0 |
perf: optimize synchronous I/O in AuthLoginViewModel (#699)
* 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> |
||
|
|
152b7d5c0d |
fix(#700): omit Bearer header on gated-mode REST calls (#701)
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> |
||
|
|
dcf26f1a16 |
Add comprehensive tests for ServerCollectionOps (#696)
* 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. |
||
|
|
7927944198 |
Revert "fix(#688): route expired auth sessions to sign-in (#689)" (#698)
This reverts commit
|
||
|
|
bc6c8a2e68 |
fix(chat): render reasoning card inside bubble and preserve persistence (#691)
* fix(chat): render reasoning card inside bubble and preserve persistence Move ReasoningCard inside AssistantBubble and preserve reasoningText across REST re-fetches, MessageStart, and buffer flushes. * style(chat): resolve ktlint unused imports and blank line formatting |
||
|
|
a5baf41545 |
fix(#688): route expired auth sessions to sign-in (#689)
* 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 |
||
|
|
def122ab58 |
fix(#686): implement robust history pagination (#687)
* 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> |
||
|
|
2e97ee9a84 |
refactor: remove verified dead code across data, UI, and resources (#680)
* refactor: remove unused dead code across data, UI, and resources * fix: resolve dangling references left by dead-code removal Restore empty object Motion (braces required) and remove the 12 stale test usages that still called the now-deleted production symbols: - ServerStoreTest: removeServer/switchToServer tests - ServerEndpointTest: isCleartext assertions - ConnectViewModelTest: onHostChange/onPortChange tests + 3 dropped R.string refs - SettingsViewModelTest: renameProfile tests + clearNavigateToLogin - E2eIntegrationTest: previewSkill tests + onHostChange/onPortChange calls Verified locally: compileDebugUnitTestKotlin + 48 tests pass. * fix: remove unused imports flagged by ktlint Drops 4 no-longer-referenced imports left by the dead-code removal: - HermesApiService: SkillScanResponse (scanHubSkill removed) - ServerEndpointTest: assertFalse, assertTrue (isCleartext assertions dropped) - SettingsViewModelTest: assertFalse (rename tests removed) --------- Co-authored-by: M57 <hy4ri@users.noreply.github.com> |
||
|
|
f7afbfae85 | perf(model): optimize model tab load speed with two-phase fetch and loadQuick (#677) | ||
|
|
0edb67338d |
refactor: remove bottom navigation bar (#665 #666 #667 #668) (#672)
* refactor(nav): remove bottom NavigationBar from Scaffold (#665) * refactor(theme): remove BottomNavDisplayMode enum (#666) * refactor(settings): remove nav bar customization page (#667) * chore: clean up unused imports after bottom nav removal (#668) * chore: remove dead bottom nav infrastructure after removal - Remove SettingsNavBar NavKey (NavigationKeys.kt) - Remove bottomNavItems field from ServerStoreState + migration code - Remove _bottomNavItemsFlow, getBottomNavItems, setBottomNavItems from AuthManager - Remove bottomNavItems handling from selfHealed() (ServerCollectionOps) - Remove redundant bottomBar={} from Scaffold (Navigation.kt) - Remove unused nav bar strings from values/strings.xml + values-ko/strings.xml - Remove content_desc_move_up/down/remove_item strings - Update SettingsViewModelTest.kt (drop stale getBottomNavItems mock) - Update ServerStoreTest.kt (remove bottomNavItems assertions) --------- Co-authored-by: M57 <Hy4ri@users.noreply.github.com> |
||
|
|
e12a23befe |
fix: correct bulk session delete endpoint + surface deleted count (#653)
* 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>
|
||
|
|
a62bc7e16c |
refactor: remove device Pairing feature entirely (issue #645) (#650)
* refactor: remove device Pairing feature entirely (issue #645) - Delete Pairing.kt model + pairing API endpoints (get/approve/revoke/clear) - Delete PairingScreen/PairingViewModel + PairingCodeEntryScreen/ViewModel - Remove NavKeys, ScreenRegistry drawer entry, Navigation.kt entry + Landing pairing button - Remove pairing string resources (en + ko); keep connect_* config-parse strings - Keep Telegram onboarding pairing_id flow (separate concept, per issue) - Fix related doc comments + remaining test reference * test: fix racy CONNECTED read in gated-mode WS test (issue #635 test) testGatedMode_attemptsTicketFetchWithoutBareCookie asserted CONNECTED immediately after the server-side onOpen latch fired, racing the client handshake (WsListenerImpl sets CONNECTED on receipt of the 101). Await the real status transition via connectionStatus.first{==CONNECTED} like the other connect tests do. No product behavior changed. --------- Co-authored-by: M57 <Hy4ri@users.noreply.github.com> |
||
|
|
e44a53366b |
Fix #647: resolve Default profile URL from top-level login URL (#649)
* 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> |
||
|
|
c8a5055a84 |
fix(auth): support __Host-/__Secure- prefixed session cookies and proxy-relative paths (issue #635) (#648)
- 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> |
||
|
|
26b104b2bb |
[feature] issue #634: HTTPS + reverse-proxy server endpoint support (#638)
* [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> |
||
|
|
d839c5e9ad |
fix(billing): align SubscriptionCurrent + SubscriptionTier to backend wire (issue #631) (#632)
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>
|
||
|
|
3363c1e586 |
perf(analytics): preload on launch + split-fetch + disk cache (issue #537) (#630)
* 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> |
||
|
|
00c0ddfb92 |
feat(billing): adopt subscription.* + usage.bars WS methods (issue #628) (#629)
* 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> |
||
|
|
228431d57a |
[enhancement] feat(#606): support auth mode + bearer token when adding HTTP MCP servers (#607)
* feat(#606): support auth mode + bearer token when adding HTTP MCP servers - Extend AddMcpServerRequest with auth (none|header|oauth) and bearerToken - Add auth mode FilterChip selector in HTTP add-server dialog - Conditionally show masked bearer token field when auth == header - Wire new fields through McpServersViewModel request builder Backend contract: exactly one of url/command required; bearer_token requires auth == "header"; args/env only for stdio. SnakeCase naming strategy auto-serializes bearerToken -> bearer_token. Fixes #606 * fix(#606): address agy review — remember PasswordVisualTransformation + FlowRow for auth chips - Wrap PasswordVisualTransformation in remember {} to avoid per-recomposition allocation - Use FlowRow for the 3 auth-mode FilterChips so they wrap on narrow screens instead of overflowing |
||
|
|
b3765bd106 |
feat: in-app display language switcher (Settings → Appearance) (#604)
Add a Language selector to Settings → Appearance that overrides the app display language independent of the device locale. Persists a BCP-47 code in ServerStoreState.appLanguage; MainActivity.attachBaseContext applies it via a ContextWrapper (works on minSdk 26, no AppCompat dependency needed since the Activity is a plain ComponentActivity). Selecting a language recreates the activity so resources re-resolve immediately. Includes System default / English / 한국어 options, plus a unit test for the locale-code resolver. Note: the new string keys (settings_item_language, language_system, language_english, language_korean) should be backfilled into values-ko once PR #602 lands. Co-authored-by: hy4ri <hy4ri@users.noreply.github.com> |
||
|
|
d9f20f8eb2 |
fix(#576): surface command.dispatch 4018 errors instead of silent dead-tap (#603)
* fix(#576): surface command.dispatch 4018 errors instead of silent dead-tap * fix(#576): fall back to slash.exec for command.dispatch 4018 registry misses * fix(#576): block cli_only/TUI-only commands at dispatch (blocklist deliverable) * review(#603): address agy findings — tighten 4018 match, case-insensitive filter, add double-fault + blank-output tests * fix(#576): surface command dispatch outputs and update tests --------- Co-authored-by: M57 <m57@hermes-control.app> |
||
|
|
d1fc477bcd |
fix: resolve all build compilation and style check warnings (#597)
* fix: resolve all build compilation and style check warnings * fix: remove unused import in SystemViewModel |
||
|
|
48f5ffbe52 |
fix(#589): show in-session model picker when user sends /model (#596)
* fix(#589): show in-session model picker when user sends /model Typing a bare '/model' in the chat composer now opens the model picker so the user can hot-swap the CURRENT session's model via the existing slash-command path, instead of hand-typing the provider/model string. - ChatViewModel.preloadModelOptions() caches GET /api/model/options at GatewayReady so the picker opens instantly; falls back to on-demand refresh if opened before preload finishes. - sendMessage() intercepts a bare '/model' (no arg) -> showModelPicker=true instead of dispatching; a typed '/model provider/model' still dispatches via handleSlashCommand. - sendSlashModel() routes through command.dispatch with session_id, so the swap is session-scoped (not the global POST /api/model/set). - Extracted ModelPickerDialog into ui/model/components and reused by both ModelScreen and ChatScreen (adds loading + empty states). - Added a top-bar model chip (current session model label) that opens the same picker. - Added unit tests: bare /model opens picker, picker selection hot-swaps via slash dispatch with session_id, typed /model with arg dispatches directly. Note: CI shows 2 pre-existing test failures (ChatViewModelTest.testToggleSearch, HermesWsClientTest.testAutoReconnect) that also fail on a clean main full suite (MockK static-mock leakage between classes). Unrelated to this change; compile + ktlint + the 3 new tests pass. * fix(#589): use backend-valid session-scoped /model command syntax The model picker now dispatches the canonical backend command form '/model <model> --provider <slug> --session' instead of the unsupported 'provider/model' slash form. The '--session' flag keeps the switch scoped to the current chat only (per-session override) and never writes the global model config, which matches the backend model-switch contract. - sendSlashModel builds '/model $model --provider $provider --session'. - Updated unit tests to assert the corrected arg payload ('gpt-4o --provider openai --session') and the fully-typed dispatch path. * fix(#589): add pinned-models section to in-session model picker - ModelPickerDialog now renders a Pinned section (mirrors global model screen) - search filter matches model names too, not just provider name/slug - ChatUiState gains modelPickerPinned, fed from AuthManager.getPinnedModels() - top-bar model chip removed; picker opens on /model only - test mock for getPinnedModels() added * fix(#589): route /model via prompt.submit instead of command.dispatch (resolves 4018) /model is a real backend slash command handled in the backend's message pipeline (_handle_message -> _handle_model_command), so it must arrive as a normal prompt.submit message, not the command.dispatch RPC (which only knows quick/plugin/bundle/skill commands and 4018s on /model). - SlashCommandDispatcher: add SlashResult.ModelSwitch, map /model -> ModelSwitch - ChatViewModel: handle ModelSwitch -> handleModelSwitch() sends via WsMethods.PROMPT_SUBMIT with {session_id, text} - Tests: rewrite the two /model tests to assert prompt.submit (previously asserted the buggy command.dispatch path); add /model -> ModelSwitch test Independent agy review: APPROVE, no blocking issues. * fix(#589): route /model via slash.exec (correct transport; prompt.submit made LLM treat it as text) Earlier attempt routed /model through prompt.submit, but the TUI gateway's prompt.submit handler does NOT parse slash commands — it runs the text as a normal agent turn, so the LLM received '/model ...' as a user message (the exact reported bug). The correct RPC is slash.exec, which runs the command through the slash worker and _mirror_slash_side_effects -> _apply_model_switch to hot-swap the live session model. command.dispatch is also wrong (only knows quick/plugin/bundle/skill commands -> 4018). - WsMethods: add SLASH_EXEC = "slash.exec" - ChatViewModel.handleModelSwitch: send slash.exec with {command, session_id} (previously prompt.submit with {text}); corrected doc comment - SlashCommandDispatcher: corrected comments (slash.exec, not prompt.submit) - ChatViewModelTest: rewrite both /model tests to assert slash.exec with the /model <model> --provider <slug> --session command string - SlashCommandDispatcherTest: /model -> ModelSwitch already covered Verified against hermes-agent tui_gateway/server.py: slash.exec (L13190) -> worker.run + _mirror_slash_side_effects (L13299) -> _apply_model_switch (L13118); parse_model_flags accepts --provider/--session (hermes_cli/model_switch.py:355). Independent agy review of the prior attempt: APPROVE (the wrong-transport assumption was the author's, not agy's). * fix(#589): route /model via config.set key=model (slash.exec 4001'd; prompt.submit made LLM treat it as text) Third transport attempt, now verified against the gateway source: - prompt.submit: gateway runs text as a normal agent turn -> LLM sees '/model' as a message (the original reported bug). WRONG. - slash.exec: gateway returns 4001 'session not found'. The slash worker path resolves the session differently / requires agent-built state the mobile session isn't in at switch time. WRONG. - config.set key=model: gateway (server.py config.set L10253) routes key=='model' straight to _apply_model_switch using the SAME _sessions.get(session_id) lookup that the working command.dispatch uses. CORRECT. sendSlashModel still builds '/model <model> --provider <slug> --session'; parse_model_flags (hermes_cli/model_switch.py:355) extracts model/provider/ session from it. handleModelSwitch now sends config.set {key:model, value: command, session_id}. - WsMethods: add CONFIG_SET = 'config.set' - ChatViewModel.handleModelSwitch: config.set instead of slash.exec - SlashCommandDispatcher: comments updated (config.set, not slash.exec) - ChatViewModelTest: both /model tests assert config.set key=model + command - also fixes the MockK testToggleSearch flake by preloading byte-buddy agent via JAVA_TOOL_OPTIONS locally (container blocks JVM self-attach) * fix(#589): strip /model prefix before config.set key=model (5001 'model names can't have spaces') config.set key=model passes the value DIRECTLY to parse_model_flags — it does NOT strip a leading '/model' the way slash.exec / prompt.submit do. Sending '/model <model> ...' made parse_model_flags treat '/model <model>' as the model name (contains a space) -> 5001. handleModelSwitch now strips the '/model' prefix and sends the bare spec '<model> --provider <slug> --session', matching the TUI client's modelValueForConfigSet (ui-tui session.ts:23) used by useMainApp.ts:123. - ChatViewModel.handleModelSwitch: spec = command.removePrefix('/model').trim() - ChatViewModelTest: assert bare spec 'gpt-4o --provider openai --session' - comment updated * fix(#589): strip /model prefix case-insensitively before config.set SlashCommandDispatcher and isModelPickerCommand match /model case-insensitively, but handleModelSwitch used removePrefix("/model") (case-sensitive). A typed /MODEL ... forwarded the literal slash prefix to config.set and the backend's parse_model_flags wouldn't recognize it — silent hot-swap failure. Use startsWith("/model", ignoreCase=true) + substring(6) so any casing is stripped. Added a regression test asserting /MODEL does not forward a leading slash. * fix(test): inject searchDispatcher to fix MockKException in testToggleSearch --------- Co-authored-by: M57 <m57@hermes-control.app> |
||
|
|
c543eb6470 |
feat(#530): server-backed session search (FTS5) (#555)
* feat(#530): add SessionSearch models + searchSessions endpoint + contract tests * feat(#530): wire server-backed search into Sessions screen (debounce + render) * style(#530): ktlint import ordering on HermesApiService * fix(#530): ktlint-clean overlap wrap + map search snippet to title * fix(#530): map search snippet to title so results show + highlight * fix(#530): render search hits as honest result cards instead of faking title Backend SessionSearchResult carries no session name (only snippet + metadata), so mapping snippet->title made the card show raw excerpt as the title. Instead, render a dedicated SearchResultCard: 'Match' label + session id, highlighted snippet as body, and source/model/played-at chips. Added SessionInfo.model and a friendly relative-time formatter. ktlint clean, compileDebugKotlin + unit tests pass. * fix(#530): strip JSON from search snippet + tighten result card padding * fix(#530): strip FTS highlight markers from search snippet on client agy's backend change re-wraps matched terms in >>>term<<< markers inside the clean snippet, but the mobile highlights by raw query term and never consumed those markers — so literal '>>>'/'<<<' would render in result text. Strip the markers before passing the snippet to highlightText so the query highlight still works on clean text. * fix(#530): integrate tree-flattening hierarchy with search modes in SessionsScreen * fix(#530): fix test assertion and mock ApiClient in SessionsViewModelTest * fix(#530): resolve compose PaddingValues compile error and fix slash-preservation test path * fix(#530): clean search snippet from JSON payload and add unit test --------- Co-authored-by: M57 <m57@hermes-control.app> |
||
|
|
907d247312 |
fix: refresh loopback dashboard token after restart (#568)
* 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> |
||
|
|
ee28ee5ce2 |
feat(#538): wire tool.progress/generating + subagent.* events into chat (#567)
* 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> |