* fix(chat): meter flashes stale window on mid-chat model swap (issue #817)
session.info updates the model label as soon as the backend applies a
swap, but the context meter's denominator kept the old model's window
until the next fetch — the chip briefly rendered the new label over the
old window (e.g. 1M flashing before settling on 262k).
- session.info with a DIFFERENT model now blanks the denominator (chip
hides while resolving) and immediately re-fires fetchContextUsage()
- fetchContextUsage writes the denominator ONCE, atomically: RPC
context_max wins, REST model/info is the fallback — a stale pre-swap
response can never override a fresh one
- regression tests: swap re-fires the fetch and lands the new window;
an identical session.info leaves the meter untouched
* fix(chat): don't fall back to profile REST window on model swap (issue #817)
After a session-scoped swap the live agent's context_breakdown can
return empty (context_max 0) while the runtime warms up. The refetch
then fell back to GET /api/model/info — PROFILE-scoped — which reports
the profile's main-model window (e.g. 1M), resurrecting the stale
window under the new label. The swap-triggered refetch now trusts only
the RPC's live context_max; the chip stays hidden until the real
window lands.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
The gateway replays the full transcript over a new socket on
session.resume unless omit_messages is set; mobile hydrates history via
REST in parallel, so the replay is redundant. When a reconnect lands
mid-stream, the replayed message gets a fresh UUID and dedup can't
collapse the 90% orphan with the 100% replay (different ids + content),
leaving a duplicate bubble. Desktop already sends omit_messages: true;
mirror that in both resume paths (ChatViewModel + NotificationReplyReceiver)
and pin it in the exact-map test verifies.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(sessions): empty-session cleanup button + latest-descendant resume + fresh-session 404 fix (issues #787, #840)
- Sessions top bar: Delete-empty icon with count badge, grey/disabled when 0
(GET /api/sessions/empty/count + DELETE /api/sessions/empty, confirm dialog)
- Resume flow resolves GET /api/sessions/{id}/latest-descendant first —
branched sessions continue in the newest child leaf, not the stale parent
(best-effort; falls back to the requested id)
- syncCurrentSession guarded by sessionHasServerPresence — a freshly created
(never prompted) session has no server row yet; the REST transcript 404s
and the resume retry spun forever (logcat 404 evidence)
* fix(sessions): clamp message-count fallback to backend limit cap (422)
fetchServerMessageCount requested limit=500 but the backend caps
session list page size at 100 (sessions.py Query le=100) — every
fallback scan 422'd (seen in device logcat after a branch). Sessions
are ordered recent, so the target is always in the top page.
* test(slash): make dispatch-capture assertions order-independent (CI flake)
The capture-race flake (SlashCommandDispatchRpcTest, hit 3x across CI and
local runs 2026-08-07): tests asserted on methodSlot.captured — the LAST
request captured — but the create flow's session.usage/context_breakdown
requests can land after the slash-dispatch one depending on suite order
(the class's own comment documents this cross-wiring). Converted the
three capture-based tests to capture ALL requests and find the target
record by method, with dispatch-before-fallback ordering for the 4018
test. Same assertions, no dependence on request interleaving.
* test(slash): convert remaining capture-race assertions (flake round 2)
The capture race moved to the focus/init tests (:424) after the first
three were fixed — every request-capture test in the class used the
same last-captured assumption. Converted the remaining five (init,
init+arg, focus, focus on, type=send) to the find-record-by-method
pattern; the type=send answers block reads methodCalls.last() since the
capture precedes the answer. Zero request() slot captures remain.
* test(slash): blocklist assertion counts command RPCs only (flake round 3)
The blocklisted-command test counted ALL request() calls and asserted
zero — the create flow's session.usage/context_breakdown noise can land
in the window after the stub registers (the same capture race that hit
the dispatch tests). Asserted instead that no COMMAND_DISPATCH or
SLASH_EXEC fires, which is the actual blocklist contract. E2E's static
Dispatchers mock stays (E2E VMs need IO routed to the test dispatcher —
removing it broke 20 E2E tests).
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(memory): dedicated Memory screen — providers, builtin files & reset (moved from System tab)
* feat(memory): move self-improvement & learning activity section from System tab to Memory screen
* fix(memory): remove top padding, single-line reset buttons, providers spacing
* fix(memory): tighten provider card padding
* fix(memory): distinct AutoStories icon for Memory tab
* chore: ignore local debug apk
* feat(ui): fresh icon set for drawer screens
* feat(ui): custom Neurology icon for Memory tab
* fix(ui): theme-driven fill for NeurologyIcon (checkColorLiterals)
The custom Neurology vector used SolidColor(Color.Black), tripping the
hardcoded-color guard (issue #622). The fill only contributes alpha —
Icon()'s tint replaces the RGB at draw time, mirroring Material's own
icon set — so the literal belongs in theme/ like every other hardcoded
color: new IconDefaultFill token, scoped there by the guard's design.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(toolsets): per-toolset config/env/provider/post-setup management (#782)
* fix(toolsets): per-entry toolset name for shared detail ViewModel (#782)
NavDisplay uses the activity-level ViewModelStoreOwner, so class-keyed
viewModel{} returns the same ToolsetDetailViewModel for every detail
entry; the constructor-captured name froze the first-opened toolset into
all entries (on-device: every toolset showed web's providers, no further
/config calls after the first). The screen now drives setToolset(name) +
loadConfig() per entry, and setToolset resets per-toolset state
(config, revealed secrets, running post-setup) so nothing bleeds across
toolsets.
* style(toolsets): single-line scrollable tool chip strip (#782)
A wrapping FlowRow stacked chips vertically for toolsets with many
tools (web etc.), ballooning card height — especially on large font
scales. Chips now sit on one horizontally scrollable row.
* chore(toolsets): drop stray terminal-noise line from chip strip change
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* test(connect): pin restart-with-scoped-profile token resolution (phase 5)
* fix(profiles): scope switch via un-clamped active-profile state
The switch persisted the server profile through serverStore.selectedProfileId,
whose selfHealed() clamps ids absent from the local connection list — server
profiles like "meow" never exist there, so the scope silently reset to
default and the re-dialed socket created the fresh session in the wrong
profile (live logcat 2026-08-06: session.create carried profile=default
right after switching to meow).
- AuthManager: prefs-backed activeProfileId state, immune to the clamp,
restored on startup; resetAuthStateForTest clears it
- ProfileScopeInterceptor + WsProfileParams + ChatViewModel fetchContextUsage:
read the active profile instead of the connection selection
- ProfileSwitchCoordinator: write activeProfileId; dial the socket on
Dispatchers.IO (the ticket mint did blocking I/O on the main thread —
NetworkOnMainThreadException — and fell back to a 1s reconnect)
- ProfilesViewModel: inject the IO dispatcher; ProfilesViewModelTest drops
its static Dispatchers mock (JVM-wide bleed class)
- Tests: WsProfileParams/Interceptor tests use the real prefs-backed state
instead of mockkObject(AuthManager) (re-mock breaks in suite order after
real AuthManager init); AuthManagerTest + Issue647ProfileUrlTest cancel
the init() DataStore scope in tearDown (UncaughtExceptionsBeforeTest
phantoms); regression test pins the clamp on the old path vs the new state
* fix(profiles): resolve getter/property JVM collision; de-poison slash test
- AuthManager.activeProfileId (StateFlow) and a getActiveProfileId()
function generated the same JVM getter name — calls silently resolved to
the property getter at runtime (ReadonlyStateFlow -> String
ClassCastException, CI unit red 2026-08-06). Function removed; callers
read activeProfileId.value.
- ChatViewModel: inject ioDispatcher (38 sites) so SlashCommandDispatchRpcTest
can drop its mockkStatic(Dispatchers) bleed without racing real IO.
- SlashCommandDispatchRpcTest: drop the static Dispatchers mock (JVM-wide
bleed; CI cross-wired COMMAND_DISPATCH captures in suite order), construct
the VM with the test dispatcher.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* 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>
- 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>
* 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>
* 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
Replaces the `indexOfFirst` linear scan over the unmerged incoming messages with a `HashMap` mapping message IDs to their index. This reduces the time complexity of the server message reconciliation loop from O(N^2) to O(N). Additionally, `removeAt()` calls on the unmerged list (which carry an O(N) penalty due to array shifting) were replaced by setting matched indices in a `MutableList<ChatMessage?>` to `null`.
First open creates a session whose DB row the gateway persists lazily on the
first prompt, so a freshly created (never prompted) session CANNOT be resumed.
Any WS reconnect while sitting on it — tab switch + socket blip, app
background, gateway restart — re-fired session.resume on that key; the gateway
answered 4007 "session not found" and the bounded retry (desktop parity, #766)
burned its budget on a permanently invalid key, leaving an error popup whose
Retry could never succeed.
- Skip the reconnect re-resume (and the doomed REST transcript fetch) while the
current session has no confirmed server-side row (REST 200 / resume success /
first MessageStart = first prompt accepted). Sessions picked from History
stay optimistic-resumable even while their page transiently 5xxes.
- Treat a definitive "session not found" (4007 RPC / 404 REST) as terminal:
recover with a fresh chat + notice instead of the dead-end Retry overlay.
- session.branch: keep the storage key in currentSessionId (the handler stored
the runtime registry id, so every later resume 4007'd and the transcript 404).
Tests: reconnect on an unconfirmed session must not resume or error; 4007 must
recover with a new session (deduped, notice shown); branch keeps the storage id
(currentSessionId + transcript fetch key). RED-GREEN proven: all three fail on
the pre-fix code and pass with it.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* 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>
* 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>
Opening a session from history fired session.context_breakdown/session.usage
with the storage session id before session.resume had registered it on the
gateway. Those RPCs resolve against the LIVE runtime registry (_sess_nowait)
and returned 4001 "session not found", which the reducer surfaced as a
spurious snackbar even though the session loaded fine.
- fetchContextUsage() now skips the two live-registry RPCs while
runtimeSessionId is null (pre-resume window); the REST-based context
fallbacks stay live.
- runtimeSessionId is cleared on socket drop so a stale runtime id can't be
reused after a gateway restart/reconnect (same 4001 family).
- regression test: no context/usage RPC fires with the storage id during the
pre-resume window; after the resume result the RPCs fire with the runtime id.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Bring the desktop's session reconnection UX to mobile:
- Warm-cache fast-path: switchSession paints the cached Room transcript
immediately instead of blanking the screen, then refreshes from the
server in parallel (stale cache can't clobber a fresher server page)
- Bounded auto-retry: a failed session.resume (WS reject or REST
transcript failure) retries with exponential backoff 1s->2s->4s->8s,
capped at 4 attempts; WS + REST failures in the same cycle count as one
- Explicit error recovery: after exhaustion the chat shows an error card
with a manual Retry instead of latching the spinner forever; manual
retry resets the backoff cycle
- Reconnect-aware resume: gateway (re)connect clears stale error state
and re-resumes the current session on the new socket
- Unit tests: warm-cache paint, bounded retry exhaustion, WS+REST
dedupe, manual retry reset, reconnect restart
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(chat): rewire tool bubbles onto the desktop engine (stage 3)
parseToolOutput is now a thin adapter: it normalizes the payload shape
(args/result sub-objects, legacy top-level fallback, name resolution)
and delegates all per-tool formatting to ToolViewBuilder.
- ToolResultParser.kt: 1325 lines of bespoke formatters → 45-line adapter
- ParsedToolData deleted; ToolBubble renders ToolView directly:
collapsed = emoji + engine title (+countLabel) + subtitle line;
expanded = error → $ command / stdout / stderr / exit code →
DiffViewCard → search hits → detail → duration footer
- Gson-compat shims, formatTodoToolOutput, toIntOrNull and all
per-tool formatters died with the old parser (engine is idiomatic kotlinx)
- Kept mobile-only UI: progress preview, SecurityRiskChip, emoji
prefixes, raw-JSON toggle, DiffViewCard, copy
- ToolViewBuilder fixes found during the rewire: numberValue now accepts
numeric strings (TS Number() semantics — gateway ships exit_code as
string/float), memory title keeps its target suffix
ToolBubbleParsingTest rewritten as adapter-contract tests (14 cases);
per-tool behavior lives in ToolViewBuilderTest. Verified: ktlint +
full testDebugUnitTest.
* fix(chat): dedupe tool name in collapsed bubble summary
The header row already shows the tool name, but the collapsed summary
showed emoji + engine title — and for ~11 tools the engine title is just
the generic humanized name (fact_store -> "Fact Store", todo -> "Todo"),
so the bubble displayed the tool identity twice.
composeToolSummaryLines now drops the title when it equals the generic
humanized name and merges the subtitle into the emoji line instead
("🧠 Fact added (ID: 5)"), restoring the pre-engine one-line style.
Descriptive titles ("Searched \"cats\"", "Ran ls", "Read a.kt L10-14")
stay on line one with the subtitle on line two. A lone emoji with no
subtitle renders nothing.
ToolViewBuilder.genericTitleFor exposes the generic title for the
comparison. 9 new unit tests.
---------
Co-authored-by: hy4ri <hy4ri@users.noreply.github.com>
* feat(chat): port desktop heuristic JSON summarizer engine
New com.m57.hermescontrol.ui.chat.tool.ToolResultSummary — a faithful
Kotlin port of the desktop app's lib/tool-result-summary.ts (verified
against its vitest suite, ported 1:1 to JUnit):
- formatToolResultSummary: wrapper unwrap (data/result/output/response/
payload, up to 4 levels), priority-key ordering, array/record block
formatting with depth caps, noise filtering (success:true etc.)
- extractToolErrorMessage: cycle-safe nested hunt for real error text
through wrappers, with placeholder filtering (error:'none' ignored)
and stderr deliberately excluded as an error signal
Also handles stringified-JSON payloads (re-parse on demand) like the
desktop's tryJson/norm layer.
Ported contract tests: ToolResultSummaryTest (10 cases).
* feat(chat): port desktop per-tool display engine (ToolViewBuilder)
Second half of the desktop engine port, in the new ui.chat.tool package:
- ToolView: the render model the builder produces — status/title/subtitle/
detail/count/duration/stdout/stderr/exitCode/diff/searchHits/imageUrl —
no raw JSON in UI code
- ToolViewBuilder: port of the desktop buildToolView (fallback-model):
status heuristics (explicit success wins; non-zero exit alone is NOT an
error), dynamic titles (Read/Searched/Ran with summarized commands),
per-tool subtitle/detail (browser snapshot stats, terminal output
preview, memory message, cron job counts), count-label cascade,
web_search hit parsing, inline diff + stats, stdout/stderr split,
duration formatting, redundant-detail suppression
- Mobile-specific tool cases carried into the builder: todo, fact_store,
session_search, skills_list/view, skill_manage, process, x_search,
vision_analyze, tool_search, image_generate, project_*, read_terminal,
computer_use
- CommandSummarizer: port of the desktop summarize-command.ts (quote-aware
compound split, pipe-tail strip, redirect/env cleanup)
- Terminal stdout reads the gateway's canonical merged `output` key with
stdout/stderr fallback (mobile terminal_tool contract differs from
desktop)
Tests: ToolViewBuilderTest (18), CommandSummarizerTest (8), all ported
or derived from the desktop suite. Full suite green: 655 tests.
---------
Co-authored-by: hy4ri <hy4ri@users.noreply.github.com>
A new assistant message was seeded with the previous message's
reasoningText (and isReasoning flag) via onMessageStart, and
resetStreaming() never cleared the shared streaming state. If the
next reply produced no reasoning, the stale trace stayed glued to
the new bubble and got persisted to Room.
- onMessageStart: new message + StreamingState start with empty
reasoning instead of inheriting the previous turn's
- resetStreaming: clears isReasoning + reasoningText on the shared
state (finalized messages keep their own copy for the card)
- regression tests: MessageStart seeding, no-reasoning persistence,
reset clearing, finalized-message preservation
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* 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>
* 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
Both commands are real backend command.dispatch subcommands (name=="init" / name=="focus", hermes-agent 2b0fb72ac). Mobile already routes them generically via RpcDispatch (name/arg/session_id) and handles responses (type:send -> submitPrompt for /init, type:exec -> assistant message for /focus) + surfaces them from commands.catalog.
Adds 6 contract tests mirroring the existing /help + /queue + /status cases:
- /init and /focus forward name+arg+session_id to COMMAND_DISPATCH
- /init with extra arg and /focus on/off forward the arg
- type:send (init) submits the returned prompt via sendMessage
- type:exec (focus) surfaces output as an assistant message
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* feat(chat): full-screen image viewer (issue #723)
Tap any chat image (markdown , inline attachment thumbnail,
or bubble image) to open a full-screen viewer:
- pinch-zoom + pan via native detectTransformGestures
- downswipe-to-dismiss at min zoom
- Save -> device Downloads (MediaStore), Share -> Android share sheet
(both fully device-local; never sent back to the Hermes server)
Plumbing: onImageClick(ImageViewerModel) flows MarkdownText ->
ChatBubble/InlineAttachment -> ChatMessageList -> ChatScreen (state +
ImageViewerDialog). ImageBytesResolver reuses the existing authed
OkHttpProvider path for gateway http(s) sources; data:/content://
handled locally. No new dependencies.
Closes#723
* fix(chat): resolve strings at composable scope to satisfy LocalContextGetResourceValueCall lint
Lint forbids reading resource *values* from LocalContext.current inside
coroutine lambdas. Hoist all viewer strings via stringResource() at
composable scope and reuse them in onSave/onShare.
---------
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* 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>
* 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>
Assistant messages could not display inline images or attachments on the
mobile client. The markdown renderer had no image block, and
AssistantBubble only rendered MarkdownText + timestamp, ignoring
message.attachments (only UserBubble did).
- Add MdBlock.Image + standalone  parsing in MarkdownText.
Accepts http(s) gateway URLs and data:image/...;base64 inline media.
- Render message.attachments inside AssistantBubble (mirrors UserBubble)
via InlineAttachment / AsyncImage.
- Add parser unit tests for image blocks (url, data: URL, inline-in-paragraph).
Local verification: ./gradlew ktlintCheck compileDebugKotlin assembleDebug
all green; app-debug.apk produced.
Fixes feature gap where agent-delivered media (e.g. MEDIA:/ images
sent to chat) was invisible in the Android app.
Co-authored-by: M57 <hy4ri@users.noreply.github.com>
* 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>