Compare commits

...

65 Commits

Author SHA1 Message Date
nesquena-hermes
d8aa387c3c Merge pull request #439 from nesquena/release/v0.50.37
Some checks failed
Release & Docker / release (push) Has been cancelled
release: v0.50.37 — fix onboarding wizard for existing Hermes users
2026-04-14 09:46:08 -07:00
Nathan Esquenazi
4ad7efe8cf fix(i18n): add onboarding_skip/onboarding_skipped keys to en+es locales 2026-04-14 16:45:13 +00:00
Nathan Esquenazi
57a50591ee fix(onboarding): skip wizard if Hermes already configured
Closes #420:
2026-04-14 16:45:12 +00:00
Nathan Esquenazi
16c58e60f4 docs: v0.50.37 CHANGELOG, version bump, test count 2026-04-14 16:44:58 +00:00
nesquena-hermes
37850a4dfd fix: workspace list cleaner — all 1055 tests pass (#418)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: workspace list cleaner — allow own-profile paths, remove brittle string filter

Two bugs in _clean_workspace_list() caused workspace adds to silently vanish
on the next load, making the duplicate-check test and workspace rename test fail:

1. Brittle string filter: 'if test-workspace in path or webui-mvp-test in path:
   continue' — removed. The test server's workspace IS under these paths, so any
   workspace added during testing got silently dropped on the next load_workspaces()
   call. The p.is_dir() check already handles non-existent paths.

2. Cross-profile filter too broad: 'if p is under ~/.hermes/profiles/: skip' —
   this correctly blocked cross-profile leakage but also blocked the current
   profile's own paths (e.g. ~/.hermes/profiles/webui/webui-mvp-test/...).
   Fixed: only skip if the path is under profiles/ AND under a DIFFERENT profile's
   directory. Paths under the current profile's own home are kept.

* docs: v0.50.36 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-14 00:14:25 -07:00
nesquena-hermes
415270ff03 fix: cross-platform multi-workspace trust boundary (#417)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: relax workspace trust boundary to user home directory

The previous restriction required workspaces to be under DEFAULT_WORKSPACE
(/home/hermes/workspace), which blocked all profile-specific workspaces
(~/CodePath, ~/General, ~/WebUI, ~/Camanji, etc.) since each profile uses
a different directory under home.

New boundary: any directory under Path.home() is trusted.
This still blocks /etc, /tmp, /var, /root, /usr and all paths outside the
user's home, while allowing any legitimate workspace under ~/

Also updates test assertions from 'trusted workspace root' to 'outside'
since the new error message says 'outside the user home directory'.

* fix: workspace trust uses home-dir + saved-list, not single ancestor

Three-layer trust model that works cross-platform and multi-workspace:

1. BLOCKLIST: /etc, /usr, /var, /bin, /sbin, /boot, /proc, /sys, /dev, /root,
   /lib, /lib64, /opt/homebrew — always rejected, even if somehow saved
2. HOME CHECK: any path under Path.home() is trusted — covers ~/CodePath,
   ~/hermes-webui-public, ~/WebUI, ~/General, ~/Camanji simultaneously;
   Path.home() is cross-platform (Linux ~/..., macOS ~/..., Windows C:\Users\...\...)
3. SAVED LIST ESCAPE HATCH: if a path is already in the saved workspace list,
   it's trusted regardless of location — covers self-hosted deployments where
   workspaces live outside home (/data/projects, /opt/workspace, etc.)

None/empty → DEFAULT_WORKSPACE (always trusted, validated at startup)

* docs: v0.50.35 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 23:57:51 -07:00
nesquena-hermes
2a7a5ddfaf [security] fix(workspace): restrict session workspaces to trusted roots (#416)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix(workspace): restrict session workspaces to trusted roots

* fix: use boot-time DEFAULT_WORKSPACE instead of profile default for trusted workspace root

_profile_default_workspace() reads the agent's terminal.cwd which may differ
from the WebUI's configured workspace root. Use _BOOT_DEFAULT_WORKSPACE (which
respects HERMES_WEBUI_DEFAULT_WORKSPACE for test isolation) to stay consistent
with how new_session() seeds the initial workspace.

* docs: v0.50.34 release — version badge and CHANGELOG

---------

Co-authored-by: hinotoi-agent <paperlantern.agent@gmail.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 23:44:03 -07:00
nesquena-hermes
a5abe51cc5 fix: workspace panel close button — no duplicate X on desktop, mobile X respects file preview (#414)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: workspace panel close button — no duplicate X on desktop, mobile X respects file preview

Two bugs fixed in the workspace right panel:

1. Duplicate X on desktop (bug): #btnClearPreview (the X icon) was always
   visible alongside #btnCollapseWorkspacePanel (the chevron), producing two
   close controls at once. Fixed in syncWorkspacePanelUI() — on desktop, the X
   is now hidden when no file preview is open (display:none), and only shown
   when the user is viewing a file. The chevron remains as the sole close
   control in browse mode.

2. Mobile X collapses panel instead of dismissing file (bug): .mobile-close-btn
   was calling closeWorkspacePanel() directly, which collapsed the whole panel
   even when a file was open. Changed to handleWorkspaceClose(), which already
   has the correct two-step logic: clear preview first, close panel only if
   no preview is visible.

Files changed:
- static/boot.js: syncWorkspacePanelUI() hides btnClearPreview on desktop
  when hasPreview is false, guarded by !isCompact so mobile is unaffected
- static/index.html: mobile-close-btn onclick changed from
  closeWorkspacePanel() to handleWorkspaceClose()
- tests/test_sprint44.py: 10 new regression tests
- tests/test_mobile_layout.py: updated test_workspace_close_button_present()
  to accept handleWorkspaceClose() as the valid onclick target

* fix: widen test_server_delete_invalidates_index window to 1200 chars

The test extracted a 600-char window starting from the session/delete
handler to check for SESSION_INDEX_FILE. Commit 3cc5839 added session_id
character validation and path traversal guards before the unlink call,
pushing SESSION_INDEX_FILE to ~764 chars from the match — beyond the
600-char limit, causing the test to fail on CI.

Widened the window to 1200 chars, which accommodates any reasonable
amount of guard code before the SESSION_INDEX_FILE.unlink() call.

* docs: v0.50.33 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 23:25:26 -07:00
nesquena-hermes
3cc5839bf3 [security] fix(sessions): validate session_id before deleting session files (#412)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix(sessions): validate session_id before deleting files

* fix: remove premature session index invalidation before validation check

* docs: v0.50.32 release — version badge and CHANGELOG

---------

Co-authored-by: hinotoi-agent <paperlantern.agent@gmail.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 23:10:46 -07:00
nesquena-hermes
539501ed2b fix: delegate all live model fetching to agent provider_model_ids() (#411)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: delegate all live model fetching to agent's provider_model_ids()

Previously _handle_live_models() maintained its own per-provider logic:
- anthropic, google, gemini returned 'not_supported' (hardcoded exclusions)
- openai-codex had a custom branch (added in v0.50.30)
- openai/copilot had hardcoded base URLs
- other providers fell through to a generic /v1/models fetch

Now the handler delegates entirely to hermes_cli.models.provider_model_ids(),
which is the agent's authoritative resolver:
- anthropic:    live fetch via /v1/models with correct API-key or OAuth headers
- copilot:      live fetch from api.githubcopilot.com/models with Copilot headers
- openai-codex: Codex OAuth endpoint + ~/.codex/ cache fallback
- nous:         live fetch from Nous inference portal
- deepseek, kimi-coding: generic OpenAI-compat /v1/models
- opencode-zen/go: OpenCode live catalog
- openrouter:   curated static list (live returns 300+ which is overwhelming)
- google/gemini, zai, minimax: static list (non-standard or Anthropic-compat endpoints)
- any others:   graceful static fallback

Also removed the client-side skip guard in _fetchLiveModels() (ui.js) that
blocked live fetching for anthropic, google, and gemini.

The hardcoded model lists in _PROVIDER_MODELS remain as the fallback when
credentials are missing or network is unavailable — they are never shown
when live data is available.

* docs: v0.50.31 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:57:58 -07:00
nesquena-hermes
c91eaaf05f fix: route openai-codex live model fetch through agent get_codex_model_ids() (#410)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: route openai-codex live model fetch through agent's get_codex_model_ids()

Previously _handle_live_models() grouped openai-codex with openai and sent a
request to https://api.openai.com/v1/models, which returns 403 because Codex
auth is OAuth-based via chatgpt.com, not a standard API key. The live fetch
silently failed and the UI showed only the hardcoded static list.

Now: openai-codex has a dedicated early-exit branch that calls
hermes_cli.codex_models.get_codex_model_ids() — the same path the agent CLI
uses. It resolves models in order: live Codex API (if OAuth token available) >
~/.codex/ local cache > DEFAULT_CODEX_MODELS. This means:

- If the user has a valid Codex OAuth session, the UI gets the exact model list
  their subscription provides (e.g. gpt-5.2, gpt-5.3-codex-spark that aren't
  in the hardcoded list)
- If the OAuth session is expired, falls back to local ~/.codex/ cache
- Always has DEFAULT_CODEX_MODELS as final fallback

Also: improved label generation for Codex model IDs (GPT-5.4 Mini vs GPT 5 4 Mini).
Added 1 structural regression test.

* docs: v0.50.30 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:49:04 -07:00
nesquena-hermes
d3fea34c41 fix: correct tool call card rendering on session load after context compaction (#408)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: correct tool call card rendering on session load

Two bugs caused duplicate/incorrect tool call cards when loading
sessions (especially after context compaction):

1. loadSession() sanitized messages (B9 filter) but did NOT update
   the session-level tool_calls array's assistant_msg_idx references.
   Since compact() returns only sanitized messages and recomputes
   tool_calls with indices into the compacted array, the original
   assistant_msg_idx values became stale/misaligned.

2. loadSession() then assigned the broken session-level tool_calls
   directly to S.toolCalls. This prevented renderMessages()'s fallback
   path (which derives tool_calls from per-message tool_calls using
   correct sanitized-array indices) from ever running.

Fix:
- Keep full sanitization loop with index remapping for session-level
  tool_calls (in case they're needed by other code paths).
- Instead of assigning broken session-level tool_calls to S.toolCalls,
  set S.toolCalls=[] so renderMessages() uses the fallback derivation
  from per-message tool_calls, which already have correct indices.

* test: add 8 regression tests for issue #401 tool call index remapping

* docs: v0.50.29 release — version badge and CHANGELOG

---------

Co-authored-by: Frank Song <franksong2702@gmail.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:41:31 -07:00
nesquena-hermes
a2258139f2 fix: expand openai-codex model catalog to match DEFAULT_CODEX_MODELS (#407)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: expand openai-codex model catalog to match agent DEFAULT_CODEX_MODELS

The _PROVIDER_MODELS["openai-codex"] catalog only listed codex-mini-latest,
so the model dropdown for profiles using openai-codex provider (e.g. CodePath)
showed only that one entry — even when the profile's saved default_model was
gpt-5.4 or another standard Codex model.

Updated to match DEFAULT_CODEX_MODELS from hermes_cli/codex_models.py:
- gpt-5.4
- gpt-5.4-mini
- gpt-5.3-codex
- gpt-5.2-codex
- gpt-5.1-codex-max
- gpt-5.1-codex-mini
- codex-mini-latest (kept, relabeled as 'Codex Mini (latest)')

Also adds 2 regression tests: catalog includes gpt-5.4, display name correct.

* docs: v0.50.28 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:35:27 -07:00
nesquena-hermes
1345ccccee feat: relative time labels in session sidebar (#406)
Some checks failed
Release & Docker / release (push) Has been cancelled
* feat: add relative time to session sidebar

(cherry picked from commit 272be9787fdff75d3da2dbc73175820477a3390e)

* fix: address session sidebar relative-time review feedback

* docs: v0.50.27 release — version badge and CHANGELOG

---------

Co-authored-by: Jordan SkyLF <jordan@skylinkfiber.net>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:26:05 -07:00
nesquena-hermes
4de4ed9a15 fix(sessions): redact sensitive titles in session list and search responses (#405)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix(sessions): redact titles in list and search responses

* docs: v0.50.26 release — version badge and CHANGELOG

---------

Co-authored-by: hinotoi-agent <paperlantern.agent@gmail.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:20:21 -07:00
nesquena-hermes
04ed0ff43d v0.50.25: mobile scroll, import timestamps, profile security, mic fallback (#404)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: restore mobile chat scrolling and drawer close (#397)

- static/style.css: add min-height:0 to .layout and .main (flex shrink chain fix for mobile scroll)
- static/style.css: add -webkit-overflow-scrolling:touch, touch-action:pan-y, overscroll-behavior-y:contain to .messages
- static/boot.js: call closeMobileSidebar() on new-conversation button onclick and Ctrl+K shortcut
- tests/test_mobile_layout.py: 41 new lines covering all three CSS fixes and both JS call sites

Original PR by @Jordan-SkyLF

* fix: preserve imported session timestamps (#395)

- api/models.py: add touch_updated_at: bool = True param to Session.save(); import_cli_session() accepts created_at/updated_at kwargs and saves with touch_updated_at=False
- api/routes.py: extract created_at/updated_at from get_cli_sessions() metadata and forward to import_cli_session(); use touch_updated_at=False on post-import save
- tests/test_gateway_sync.py: +53 lines — integration test verifying imported session keeps original timestamp and sorts correctly vs newer sessions; also fix: add WebUI session file cleanup in finally block

Original PR by @Jordan-SkyLF

* fix(profiles): block path traversal in profile switch and delete flows (#399)

Master was vulnerable: switch_profile and delete_profile_api joined user-supplied profile
names directly into filesystem paths with no validation. An attacker could send
'../../etc/passwd' as a profile name to traverse outside the profiles directory.

- api/profiles.py: add _resolve_named_profile_home(name) — validates name with
  ^[a-z0-9][a-z0-9_-]{0,63}$ regex then enforces path containment via
  candidate.resolve().relative_to(profiles_root); use in switch_profile()
- api/profiles.py: add _validate_profile_name() call to delete_profile_api() entry
- api/routes.py: add _validate_profile_name() call at HTTP handler level for
  both /api/profile/switch and /api/profile/delete (fail-fast at API boundary)
- tests/test_profile_path_security.py: 3 tests — traversal rejected, valid name passes

Cherry-picked commit aae7a30 from @Hinotoi-agent (PR was 62 commits behind master)

* feat: add desktop microphone transcription fallback (#396)

Mic button now works in browsers that support getUserMedia/MediaRecorder but
lack SpeechRecognition (e.g. Firefox desktop, some Chromium builds).

- static/boot.js: detect _canRecordAudio (navigator.mediaDevices + getUserMedia + MediaRecorder);
  keep mic button enabled when either SpeechRecognition or MediaRecorder is available;
  MediaRecorder fallback records audio, sends blob to /api/transcribe, inserts transcript
  into the composer; _stopMic() handles all three states (recognition, mediaRecorder, neither)
- api/upload.py: add transcribe_audio() helper — saves uploaded blob to temp file, calls
  transcription_tools.transcribe_audio(), always cleans up temp file
- api/routes.py: add /api/transcribe POST handler — CSRF protected, auth-gated, 20MB limit,
  returns {text:...} or {error:...}
- api/helpers.py: change Permissions-Policy microphone=() to microphone=(self) (required to
  allow getUserMedia in the same origin)
- tests/test_voice_transcribe_endpoint.py: 87 new lines — 3 tests with mocked transcription
- tests/test_sprint19.py: +1 regression guard (microphone=(self) in Permissions-Policy)
- tests/test_sprint20.py: 3 updated tests for new fallback-capability checks

Original PR by @Jordan-SkyLF

* docs: v0.50.25 release — version badge and CHANGELOG

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 22:11:45 -07:00
nesquena-hermes
2beebaa6a2 feat: opt-in chat bubble layout (closes #336) (#403)
Some checks failed
Release & Docker / release (push) Has been cancelled
* feat(ui): opt-in chat bubble layout

Closes #336.

Adds a settings toggle that right-aligns user messages and left-aligns
assistant replies. Off by default - the current full-width layout is
friendlier to code blocks and tool output, so bubbles are strictly
opt-in per the maintainer note on the issue.

Wiring follows the existing token-usage / cli-sessions pattern:

- api/config.py: new bubble_layout bool in _SETTINGS_DEFAULTS and
  _SETTINGS_BOOL_KEYS, validated + persisted like the rest.
- static/style.css: .bubble-layout gated selectors using :has() to
  tag msg-rows by .msg-role.user / .msg-role.assistant without any JS
  changes to message creation. User rows get align-self: flex-end,
  max-width: 75%, and a row-reverse header; assistant rows flex-start.
  A 700px media query widens the max to 92% on narrow screens.
- static/index.html: new checkbox with i18n keys next to the existing
  token-usage toggle.
- static/panels.js: loads the setting into the checkbox, saves it
  back, and toggles body.bubble-layout immediately on save.
- static/boot.js: applies the class on initial load so refreshed
  tabs honor the persisted setting without a flash.
- static/i18n.js: English label + description.

Test suite errors are environmental (test server fails to start on
port 8788 on main as well).

* i18n(es): add Spanish translations for bubble_layout setting

* fix+test: boot.js bubble-layout reset on failure; add 22 tests for issue #336

* docs: v0.50.24 release — version badge and CHANGELOG

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 21:42:01 -07:00
nesquena-hermes
0f8fec7ccd docs: v0.50.23 release — version badge and CHANGELOG (#393)
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 18:46:51 -07:00
nesquena-hermes
12a60faaee fix: add OpenCode Zen and Go provider support (closes #362) (#392)
* Add OpenCode Zen and OpenCode Go provider support

The webui model dropdown had no knowledge of these providers.
When hermes_cli detected them as authenticated, they fell through
to the unknown-provider fallback showing wrong models.

Changes:
- Add opencode-zen and opencode-go to _PROVIDER_DISPLAY
- Add model lists for both to _PROVIDER_MODELS
- Add OPENCODE_ZEN_API_KEY and OPENCODE_GO_API_KEY to env-var fallback detection
- Fix custom:* provider IDs (e.g. custom:my-server) displaying raw ID instead of "Custom"

* Add tests for OpenCode provider registration and detection

---------

Co-authored-by: David Case <david.case@shruggr.cloud>
2026-04-13 18:46:11 -07:00
nesquena-hermes
2acee7fc34 fix: onboarding unblocked for reverse proxy / SSH tunnel deployments (fixes #390) (#391)
Some checks failed
Release & Docker / release (push) Has been cancelled
- Read X-Forwarded-For and X-Real-IP before falling back to raw socket IP
- Add HERMES_WEBUI_ONBOARDING_OPEN=1 env var escape hatch for remote servers
- Error message now includes the env var hint
- 18 new tests (TestOnboardingIPLogic + TestOnboardingSetupEndpoint)

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 17:52:07 -07:00
nesquena-hermes
acc14f2f0b docs: update ROADMAP, SPRINTS, TESTING to v0.50.21 (961 tests)
ROADMAP.md:
- Header: v0.49.1/700 → v0.50.21/961
- Sprint history table: 12 new rows covering v0.40 → v0.50.21 (500+ commits)
- Architecture block: updated line counts and module list

SPRINTS.md:
- Header state: v0.36/433 → v0.50.21/961
- 'Where we are now' section updated with parity status
- Historical planning content preserved as reference

TESTING.md:
- Version reference: v0.36.2 → v0.50.21
- Test count: 700 → 961 (two places)

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 17:43:16 -07:00
nesquena-hermes
9948fcf1db docs: fix CHANGELOG ordering + README architecture counts
- CHANGELOG: reorder v0.50.19/v0.50.20/v0.50.21 to correct newest-first
  (v0.50.19 was mistakenly at the top above v0.50.21 and v0.50.20)
- README: fix architecture block test count 51 files/802 functions → 61 files/961
- README: update line counts to actual wc -l values:
  routes.py ~2250, streaming.py ~660, ui.js ~1740,
  messages.js ~655, sessions.js ~800

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 17:34:22 -07:00
nesquena-hermes
6a1dda4082 docs: add remaining contributors — Argonaut790, indigokarasu, zenc-cp (complete to 33)
- @Argonaut790 (#239): HTML entity decode fix + Traditional Chinese locale
  (fix shipped in v0.46.0; zh-Hant locale added same PR)
- @indigokarasu (#213): CSS-only visual redesign proposal — design token system
  + icon rail + 7 themes (influenced v0.50.0 design language)
- @zenc-cp (#133): Anti-hallucination guard for ReAct loop — streaming token
  buffer + post-run scrub pattern

README now has 33 contributors covering full project history.

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 16:52:39 -07:00
nesquena-hermes
56944cc0ab docs: update contributors, test count, line counts (v0.50.21)
- Add 21 new contributor entries covering v0.50.x era and all external
  contributions that were incorporated via review branches
- Fix test count: 802 → 961
- Fix line counts for routes.py, streaming.py, ui.js, messages.js, sessions.js
  (all grew significantly from live reasoning, reload recovery, CSRF fixes etc.)
- New major tier: Jordan-SkyLF (live streaming + session recovery)
- New feature tier: gabogabucho, bergeouss, ccqqlo, betamod, TaraTheStar,
  thadreber-web, deboste
- New bug/security tier: Hinotoi-agent, lawrencel1ng, lx3133584, DelightRun,
  shaoxianbilly, huangzt, kcclaw001, mbac, andrewy-wizard, mmartial,
  vCillusion, carlytwozero, mangodxd

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 16:47:28 -07:00
nesquena-hermes
7f69155904 docs: v0.50.21 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 16:26:48 -07:00
nesquena-hermes
54181d1a07 fix: durable inflight reload snapshots via localStorage (#367)
* fix: persist durable inflight reload snapshots

* fix: remove duplicate loadInflightState stub, update CHANGELOG test count

The stub added in the previous review branch is superseded by the author's
real localStorage-backed implementation in the cherry-picked commit 36051c0.
Remove the duplicate. Update CHANGELOG to 961 tests and document the durable
inflight state feature.

---------

Co-authored-by: Jordan SkyLF <jordan@skylinkfiber.net>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 16:25:31 -07:00
nesquena-hermes
9542639a90 fix: live reasoning, tool progress, in-flight session recovery (#367)
* fix: preserve live session output across chat switches

(cherry picked from commit 401e3b643d25e8dad8c06883b478b3c3073f07a5)

* fix: preserve todo state after session reload

(cherry picked from commit 7ee093ba19978af23b79148df2f2347e2f1e5bde)

* fix: preserve live assistant anchor across rerenders

* fix: stream live reasoning and tool progress

* fix: recover inflight session state after reload

* fix: add loadInflightState stub + CHANGELOG v0.50.21

- static/ui.js: add loadInflightState() function (currently returns null —
  the typeof guard in sessions.js means reload recovery works via the
  else-path attachLiveStream call; this stub satisfies the guard cleanly
  and documents the extension point for future localStorage-backed state)
- CHANGELOG.md: v0.50.21 entry; 960 tests (up from 949)

---------

Co-authored-by: Jordan SkyLF <jordan@skylinkfiber.net>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 16:18:15 -07:00
nesquena-hermes
bcdd7ed3f3 docs: v0.50.20 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 15:53:52 -07:00
nesquena-hermes
7a80e73eb2 fix: silent agent errors, stale model list, live model fetching (#377)
* fix: silent errors, stale models, live model fetching (#373, #374, #375)

- api/streaming.py: detect empty agent response (_assistant_added check),
  emit apperror(type='no_response' or 'auth_mismatch') instead of silent done
- api/streaming.py: add _token_sent flag so guard works for streaming agents
- static/messages.js: done handler belt-and-suspenders guard for zero replies
- static/messages.js: apperror handler labels 'no_response' type distinctly

- api/config.py: remove gpt-4o and o3 from _FALLBACK_MODELS and
  _PROVIDER_MODELS['openai'] (superseded by gpt-5.4-mini and o4-mini)

- api/routes.py: new /api/models/live?provider= endpoint, fetches /v1/models
  from provider API with B310 scheme check + SSRF guard
- static/ui.js: _fetchLiveModels() background fetch after static list loads,
  appends new models to dropdown, caches per session, skips unsupported providers

Other:
- tests/test_issues_373_374_375.py: 25 new structural tests
- tests/test_regressions.py: extend done-handler window 1500->2500 chars
- CHANGELOG.md: v0.50.19 entry; 947 tests (up from 922)

* fix: SSRF hostname bypass + auth detection operator precedence

1. routes.py: SSRF guard used substring matching (any(k in hostname))
   which allows bypass via hostnames like evil-ollama.attacker.com.
   Changed to exact hostname matching against a fixed set of known
   local hostnames (localhost, 127.0.0.1, 0.0.0.0, ::1).

2. streaming.py: _is_auth detection had a Python operator precedence
   bug on the ternary expression. The line:
     'AuthenticationError' in type(...).__name__ if _last_err else False
   parsed as the ternary absorbing the rest of the or-chain when
   _last_err was falsy. Fixed to: (_last_err and 'AuthenticationError' in ...)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: fix v0.50.20 CHANGELOG version number and test count (949 tests)

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 15:52:35 -07:00
nesquena-hermes
78de40e015 docs: v0.50.19 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 15:44:19 -07:00
nesquena-hermes
00eb13b316 fix: unicode filenames in Content-Disposition headers (#378)
* Fix unicode filenames in file download headers

* docs: v0.50.19 CHANGELOG entry for unicode filename fix (PR #378)

* docs: fix test count in v0.50.19 CHANGELOG (924 not 926)

---------

Co-authored-by: shaoxianbilly <40623436+shaoxianbilly@users.noreply.github.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 15:43:01 -07:00
nesquena-hermes
a71047bbc3 docs: v0.50.18 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 14:38:21 -07:00
nesquena-hermes
68426124c5 fix: recover from invalid default workspace paths (#366)
* fix: recover from bad default workspace paths

(cherry picked from commit 789d7537a325d1c7d3aa03c387918dddd2d0897d)

* fix: recover from invalid default workspace paths — 7 tests, CHANGELOG (#366)

- tests/test_default_workspace_fallback.py: 5 additional tests (dedup,
  RuntimeError, env var priority, mkdir on missing dir, unwritable path)
- CHANGELOG.md: v0.50.18 entry; 922 tests (up from 915)

---------

Co-authored-by: Jordan SkyLF <jordan@skylinkfiber.net>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 14:28:24 -07:00
nesquena-hermes
4c8042ea00 docs: v0.50.17 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 12:38:00 -07:00
nesquena-hermes
a6484f69a8 fix: Docker uv pre-install at build time + workspace permissions (#365)
* fix: pre-install uv in Docker image + fix workspace dir permissions (#357)

Two fixes for Docker startup reliability:

1. Install uv at build time in the Dockerfile so the container works
   without internet access at runtime. The init script now skips the
   download when uv is already on PATH.

2. Use sudo mkdir/chown for the workspace directory, matching the
   pattern used for /app. Docker auto-creates bind-mount directories
   as root, leaving them unwritable by the hermeswebui user.

Fixes #357

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: Docker uv pre-install as root to /usr/local/bin + tests + CHANGELOG

Dockerfile: install uv as root with UV_INSTALL_DIR=/usr/local/bin so it
lands in /usr/local/bin (system PATH) rather than /home/hermeswebuitoo/.local/bin
which the hermeswebui runtime user can't see.

tests/test_issue357.py: 15 structural tests covering Dockerfile uv build-time
install (system-wide, as root, before COPY), init script skip-if-present
logic, and workspace sudo mkdir/chown.

CHANGELOG.md: v0.50.17 entry; 915 tests (up from 900)

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 12:36:11 -07:00
nesquena-hermes
f13f753de8 docs: v0.50.16 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 12:24:35 -07:00
nesquena-hermes
f948baceb6 fix: CSRF check fails behind reverse proxy on non-standard ports (#360)
* fix: CSRF check fails behind reverse proxy on non-standard ports

When serving behind a reverse proxy (e.g. Nginx Proxy Manager) on a
non-standard port like 8000, the browser sends
`Origin: https://example.com:8000` but the proxy forwards `Host: example.com`
(without the port). The existing CSRF check compared these as raw strings,
causing all POST requests to be rejected with 403.

This commit:
- Adds `_normalize_host_port()` to properly parse host:port pairs (incl. IPv6)
- Adds `_ports_match()` that treats absent port as equivalent to 80/443
- Adds `HERMES_WEBUI_ALLOWED_ORIGINS` env var for explicitly trusting origins
  when port normalization alone isn't sufficient (e.g. port 8000)
- Adds unit tests covering port normalization, allowlist, and rejection cases

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: CSRF port normalization — scheme-aware, allowlist validation, 29 tests (#360)

api/routes.py:
- _normalize_host_port(): parse host:port including IPv6 bracket notation
- _ports_match(scheme, origin_port, allowed_port): scheme-aware — http absent=:80,
  https absent=:443; prevents cross-protocol false match (http://host:80 no
  longer passes for https://host:443 server)
- _allowed_public_origins(): parse HERMES_WEBUI_ALLOWED_ORIGINS env var;
  warn and skip entries missing scheme prefix
- _check_csrf(): extract origin scheme, pass to _ports_match; add origin_scheme

tests/test_sprint29.py: 29 new tests (5 from PR + 24 added in review)
- Unit tests for _normalize_host_port and _ports_match helpers
- Cross-protocol rejection (http vs https default ports)
- Explicit :80 / :443 same-origin pass
- Non-default port rejection
- Bug scenario with/without allowlist
- Comma-separated allowlist
- No-scheme allowlist warning
- Trailing-slash normalization

CHANGELOG.md: v0.50.16 entry; 900 tests total (up from 871)

---------

Co-authored-by: liangxu.5 <liangxu.5@bytedance.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 12:23:16 -07:00
nesquena-hermes
5bdeb93559 docs: v0.50.15 release — version badge
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 11:43:17 -07:00
nesquena-hermes
d0e08fee88 feat: KaTeX math rendering for LaTeX in chat + workspace previews (#352)
* feat: KaTeX math rendering for $..$ and $$..$$ in chat and previews (fixes #347)

- Stash math delimiters before markdown pipeline, restore as .katex-block/.katex-inline elements
- KaTeX JS lazy-loaded from CDN on first math block (mirrors mermaid pattern)
- KaTeX CSS loaded eagerly in <head> to prevent layout shift
- SRI hashes on both CDN tags
- throwOnError:false — bad LaTeX degrades to code span
- Supports $$, $, \\(...\\), \\[...\\] delimiters
- 18 new tests, 831/831 passing

* fix: remove invalid \' escape sequences in math stash lines

Lines 311, 314, 316, 317 had \' (backslash-quote) instead of plain '
in the arrow function bodies. This is a JS syntax error — node --check
fails with 'Invalid or unexpected token'. Likely caused by a
serialization artifact during code generation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: swap stash order (fence before math) to protect code spans; add renderKatexBlocks to workspace preview

- static/ui.js: fence_stash now runs BEFORE math_stash so dollar signs
  inside backtick code spans are not extracted as math. Previously
  `$x$` would render as KaTeX inside a <code> tag instead of
  showing the literal string $x$.
- static/workspace.js: add requestAnimationFrame(renderKatexBlocks)
  after markdown preview renders so math works in workspace file
  previews, not only in chat messages.

* feat: KaTeX math rendering + stash order fix + workspace wiring (#352)

- tests/test_issue347.py: 11 new tests (29 total) covering fence-before-math
  ordering, workspace.js renderKatexBlocks call, stash token distinctness,
  false-positive prevention, safe-tags boundary check
- CHANGELOG.md: v0.50.15 entry; 870 tests total (up from 841)

* fix: use literal null byte (\x00M) in math stash token — matches restore regex

The original PR's second commit (fix: remove invalid \' escapes) accidentally
doubled the backslash in the math stash tokens: '\\x00M' is a 5-char string
(backslash + x + 0 + 0 + M) but the restore regex /\x00M/ expects a null byte.
Result: $...$ in messages produced visible \x00M0\x00 tokens instead of
KaTeX spans.

Changed all 4 math stash return statements to use '\x00M' (single backslash =
null byte, same convention as fence_stash's '\x00F').

Also updates test_stash_tokens_distinct to check for the correct pattern.

* fix: add null-byte token test; update CHANGELOG to v0.50.15 with fixes

- tests/test_issue347.py: add test_math_stash_token_uses_single_backslash_null_byte
  to catch the \\x00M double-backslash regression; 30 tests total (up from 29)
- CHANGELOG.md: v0.50.15 entry documents all fixes including the token bug
  and workspace preview wiring; 871 tests total

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 11:40:15 -07:00
nesquena-hermes
dd17a0e9b7 security: bandit fixes B310/B324/B110 + QuietHTTPServer (#354)
Some checks failed
Release & Docker / release (push) Has been cancelled
* security: fix bandit security issues (B310, B324)

- Add usedforsecurity=False to MD5 hash in gateway_watcher.py
- Add URL scheme validation to prevent file:// access in config.py
- Add URL validation to bootstrap.py health check
- Add nosec comments where runtime validation exists

* fix: handle ConnectionResetError gracefully and add debug logging

- Add QuietHTTPServer class to suppress noisy connection reset errors
  caused by clients disconnecting abruptly (fixes log spam from
  'ConnectionResetError: [Errno 54] Connection reset by peer')

- Replace silent 'pass' statements with logger.debug() calls across
  api/auth.py, api/config.py, api/gateway_watcher.py, api/models.py,
  and api/onboarding.py for better observability during troubleshooting

- All tests pass (25 passed in test_regressions.py)

* chore: add debug logging to profiles and routes modules

- Replace silent 'pass' statements with logger.debug() calls in
  api/profiles.py for better error visibility during profile switching
  and module patching

- Add logger initialization to api/routes.py

* security: fix B110 bare except/pass issues (bandit security scan)

- Replace bare except/pass patterns with logger.debug() calls
- Fixes CWE-703 (improper check/handling of exceptional conditions)
- Files affected: routes.py, state_sync.py, streaming.py, workspace.py, server.py
- All tests pass successfully

* security: bandit fixes B310/B324/B110 + QuietHTTPServer (#354)

- api/gateway_watcher.py: MD5 usedforsecurity=False (B324)
- api/config.py, bootstrap.py: URL scheme validation before urlopen (B310)
- 12 files: replace bare except/pass with logger.debug() (B110)
- server.py: QuietHTTPServer suppresses client disconnect log noise
- server.py: fix sys.exc_info() (was traceback.sys.exc_info(), impl detail)
- tests/test_sprint43.py: 19 new tests covering all security fixes
- CHANGELOG.md: v0.50.14 entry; 841 tests total (up from 822)

---------

Co-authored-by: lawrencel1ng <lawrence.ling@global.ntt>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 11:11:56 -07:00
nesquena-hermes
04401787ec fix: inject SessionDB into AIAgent for WebUI sessions — enables session_search (#356)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: inject SessionDB into AIAgent for WebUI sessions

session_search tool requires a SessionDB instance passed via the
session_db parameter. The CLI and gateway paths already do this,
but the WebUI streaming path was missing it, causing every
session_search call to return 'Session database not available'.

Initialize SessionDB before creating the AIAgent and pass it through.
Failure is non-fatal — a warning is printed and session_search
gracefully degrades.

* fix: inject SessionDB into AIAgent for WebUI sessions (enables session_search) (#356)

- api/streaming.py: initialize SessionDB() before AIAgent construction and
  pass session_db= kwarg so session_search works in WebUI sessions
- tests/test_sprint42.py: 7 new tests covering SessionDB injection, try/except
  guard, WARNING log, ordering, and AST lock-safety check
- CHANGELOG.md: v0.50.13 entry; 822 tests total (up from 815)

---------

Co-authored-by: 王昌旭 <wangchangxu@xiaohongshu.com>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 10:53:58 -07:00
nesquena-hermes
09bbbfc657 docs: v0.50.12 release — CHANGELOG + version badge (#353)
Some checks failed
Release & Docker / release (push) Has been cancelled
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 00:53:32 -07:00
Hinotobi
88dc8bbe26 fix: isolate profile .env secrets on switch (#351)
* fix: isolate profile .env secrets on switch

* fix: move direct os.environ set after _reload_dotenv to survive profile isolation

The profile env isolation in _reload_dotenv now clears previously tracked
env keys before re-reading .env. When apply_onboarding_setup set
os.environ BEFORE _reload_dotenv, the key was immediately cleared.
Move the belt-and-braces os.environ set to AFTER _reload_dotenv so
the API key survives regardless of profile tracking state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 00:51:55 -07:00
nesquena-hermes
1fee123ac8 docs: note test_sprint34 pathlib fix in v0.50.11 CHANGELOG (#350)
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 00:23:38 -07:00
nesquena-hermes
a683553699 fix: use pathlib in test_sprint34 static file opens (no bare relative paths) (#349)
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 00:22:58 -07:00
nesquena-hermes
63fb22b7ee fix: add table styles to .msg-body for readable bordered chat tables (fixes #341) (#345)
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix: add table CSS to .msg-body for readable bordered tables in chat (fixes #341)

* fix: remove accidentally included ui.js and test_issue342.py from CSS-only PR

* docs: combine v0.50.11 CHANGELOG entries, bump version badge

* fix: restore ui.js from master (autolink already landed in #346)

* fix: restore test_issue342.py deleted by cleanup commit (already on master)

---------

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 00:08:30 -07:00
nesquena-hermes
05f09012a5 feat: autolink plain URLs in chat messages (fixes #342) (#346)
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-13 00:05:04 -07:00
Nathan Esquenazi
3c771c4d2c Merge pull request #344 from nesquena/fix/testing-md-port-8786
docs: fix stale port 8786 in TESTING.md prerequisites
2026-04-12 23:49:22 -07:00
Nathan Esquenazi
2398ec51fe docs: fix stale port 8786 in TESTING.md prerequisites — correct port is 8787 2026-04-13 06:38:14 +00:00
nesquena-hermes
4eaf4e0743 docs: fix stale test count in README architecture block (791 → 802) (#340)
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-12 22:07:36 -07:00
nesquena-hermes
1c0d13c6d9 fix: title auto-generation + mobile close button (PR #333) + v0.50.10
Some checks failed
Release & Docker / release (push) Has been cancelled
* fix(merge): preserve auth errors + fix title auto-generation

* fix(css): hide mobile close button on desktop for workspace panel

* fix: hide duplicate collapse button in mobile workspace panel view

* docs: v0.50.10 — title auto-generation fix + mobile close button (PR #333)

---------

Co-authored-by: MILO <milo@MILOdeMacMINI-2.local>
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-12 21:45:25 -07:00
nesquena-hermes
4c78d8a56b fix: correct Simplified Chinese (zh) locale — remove Traditional Chinese strings (#338)
fix: correct Simplified Chinese (zh) locale — remove Traditional Chinese strings
2026-04-12 19:20:20 -07:00
Hermes Agent
229680ae1e fix: zh-Hant approval_btn_always — use Traditional Chinese chars (始終允許 not 始终允许) 2026-04-13 02:19:57 +00:00
Nathan Esquenazi
e0e642a239 fix: apply reviewer correction for zh-Hant approval_btn_always
Per @shiqingshan review: use Simplified Chinese for approval_btn_always.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 18:53:37 -07:00
Nathan Esquenazi
e684fdd731 fix: replace Traditional Chinese with Simplified in zh locale (#337)
The zh (Simplified Chinese) locale had ~40 strings from a "missing keys"
section that were actually Traditional Chinese or garbled text. This
replaces them with correct Simplified Chinese, removes duplicate keys,
and fixes a garbled zh-Hant string (姊妹允許 → 始終允許).

Fixes #337

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 18:10:37 -07:00
Nathan Esquenazi
2a3324c201 fix: allow onboarding from Docker bridge networks (closes #334) (#335)
Some checks failed
Release & Docker / release (push) Has been cancelled
Expands the onboarding setup IP check from 127.0.0.1-only to any loopback or RFC-1918 private address. Docker containers connect via 172.17.x.x — previously blocked with a 403. Public IPs still blocked unless auth enabled. 791 tests pass.
2026-04-12 16:35:47 -07:00
Nathan Esquenazi
39d42be396 fix: deduplicate model dropdown (hyphen vs dot) + README accuracy (#332)
Some checks failed
Release & Docker / release (push) Has been cancelled
Normalizes hyphens to dots in backend model-ID comparison so claude-sonnet-4-6 (hermes-agent format) matches claude-sonnet-4.6 (WebUI list) and no duplicate entry is injected. README line counts and test count corrected. 791 tests, all pass.
2026-04-12 14:45:39 -07:00
nesquena-hermes
2fc19a8326 feat: OAuth provider onboarding path — Codex/Copilot no longer blocks setup (#331)
Some checks failed
Release & Docker / release (push) Has been cancelled
Fixes bug 2 from issue #329. current_is_oauth flag; confirmation card for OAuth providers; KeyError fix in _build_setup_catalog. 15 new tests, 791 total.
2026-04-12 14:28:16 -07:00
nesquena-hermes
7d9d7e7b66 feat: HERMES_WEBUI_SKIP_ONBOARDING env var + synchronous key reload (#330)
Some checks failed
Release & Docker / release (push) Has been cancelled
Fixes bugs 1+3 from issue #329. Skip-onboarding env var (with chat_ready guard); os.environ set synchronously after key write. 8 new tests, 776 total.
2026-04-12 14:26:00 -07:00
nesquena-hermes
9c44d0cf3e fix: strip think tags when model emits leading whitespace before <think> (#327)
Some checks failed
Release & Docker / release (push) Has been cancelled
Remove ^ anchor from think/Gemma regexes in ui.js; trimStart() before startsWith checks in messages.js streaming path. Fixes MiniMax M2.7 and any model emitting leading newlines before <think>. 10 new tests, 768 total.
2026-04-12 14:07:00 -07:00
Nathan Esquenazi
7552cd3e9b Merge pull request #328 from nesquena/fix/docker-compose-workspace-volume
Some checks failed
Release & Docker / release (push) Has been cancelled
fix: add missing workspace volume to two-container compose (#326)
2026-04-12 13:47:17 -07:00
Nathan Esquenazi
f316fb7502 fix: add missing workspace volume to two-container compose (#326)
docker-compose.two-container.yml was missing the ~/workspace:/workspace
volume mount that the single-container compose already has. Without it
the workspace directory inside the container is ephemeral and the user
can't browse their actual files.

Fixes #326

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 13:46:59 -07:00
Nathan Esquenazi
50583f0667 Merge pull request #325 from nesquena/fix/docker-restart-venv
fix: Docker container restart without recreating (#324)
2026-04-12 13:27:41 -07:00
Nathan Esquenazi
26c24867e6 fix: Docker container restart without recreating (#324)
uv venv fails with 'A virtual environment already exists' when the
container is stopped and started (not removed). The venv persists in
the container filesystem between stop/start cycles.

Fix: skip venv creation and dependency installation if they already
exist from a previous run. Uses two checks:
- /app/venv/bin/python3 exists → skip venv creation
- /app/venv/.deps_installed marker → skip pip install

This also makes restarts much faster since deps don't need to be
reinstalled every time the container starts.

Fixes #324

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 13:27:21 -07:00
Nathan Esquenazi
2562567730 fix: onboarding completes gracefully for pre-configured providers (closes #322) (#323)
Some checks failed
Release & Docker / release (push) Has been cancelled
OAuth/CLI-configured providers (openai-codex, copilot, nous) no longer blocked by onboarding wizard. 5 new tests, 758 total.
2026-04-12 13:22:48 -07:00
67 changed files with 6990 additions and 456 deletions

View File

@@ -1,10 +1,354 @@
# Hermes Web UI -- Changelog
## [v0.50.37] fix(onboarding): skip wizard when Hermes is already configured
Fixes #420 — existing Hermes users with a valid `config.yaml` were shown the first-run
onboarding wizard on every WebUI load because the only completion gate was
`settings.onboarding_completed` in the WebUI's own settings file. Users who configured
Hermes via the CLI before the WebUI existed had no such flag, so the wizard always fired
and could silently overwrite their working config.
**Changes:**
1. `api/onboarding.py` `get_onboarding_status()`: auto-complete when `config.yaml` exists
AND `chat_ready=True`. Existing configured users are never shown the wizard.
2. `api/onboarding.py` `apply_onboarding_setup()`: refuse to overwrite an existing
`config.yaml` without `confirm_overwrite=True` in the request body. Returns
`{error: "config_exists", requires_confirm: true}` for the frontend to handle.
3. `static/index.html`: "Skip setup" button added to wizard footer — users are never
trapped in the wizard.
4. `static/onboarding.js`: `skipOnboarding()` calls `/api/onboarding/complete` without
modifying config, then closes the overlay.
5. `static/boot.js`: Escape key now dismisses the onboarding overlay.
6. `static/i18n.js`: `onboarding_skip` / `onboarding_skipped` keys added to en + es locales.
7. `tests/test_onboarding_existing_config.py`: 8 new unit tests covering gate logic and
overwrite guard.
- Total tests: 1063 (was 1055)
## [v0.50.36] fix: workspace list cleaner — allow own-profile paths, remove brittle string filter
Two bugs in `_clean_workspace_list()` caused workspace additions to silently disappear on the next `load_workspaces()` call, breaking `test_workspace_add_no_duplicate` and `test_workspace_rename` (and potentially causing real-world workspace list corruption):
**Bug 1 — Brittle string filter removed:** `if 'test-workspace' in path or 'webui-mvp-test' in path: continue` dropped any workspace path containing those substrings. In the test server, `TEST_WORKSPACE` is `~/.hermes/profiles/webui/webui-mvp-test/test-workspace`, so every workspace added during tests was silently discarded on the next `load_workspaces()` call. The `p.is_dir()` check already handles genuinely non-existent paths — the string filter was redundant and harmful.
**Bug 2 — Cross-profile filter was too broad:** `if p is under ~/.hermes/profiles/: skip` was designed to block cross-profile workspace leakage, but it also removed paths under the *current* profile's own directory (e.g. `~/.hermes/profiles/webui/...`). Fixed: now only skips paths under `profiles/` that are NOT under the current profile's own `hermes_home`.
- `api/workspace.py`: remove string-match filter; fix cross-profile check to allow own-profile paths
- All 1055 tests now pass (was 1053 pass + 2 fail)
## [v0.50.35] fix: workspace trust boundary — cross-platform, multi-workspace support
v0.50.34's workspace trust check was too restrictive: it required all workspaces to be under `DEFAULT_WORKSPACE` (/home/hermes/workspace), which blocked every profile-specific workspace (~/CodePath, ~/hermes-webui-public, ~/WebUI, ~/Camanji, etc.) and prevented switching between workspaces at all.
Replaced with a three-layer model that works cross-platform and supports multiple workspaces per profile:
1. **Blocklist**`/etc`, `/usr`, `/var`, `/bin`, `/sbin`, `/boot`, `/proc`, `/sys`, `/dev`, `/root`, `/lib`, `/lib64`, `/opt/homebrew` always rejected, closing the original CVSS 8.8 vulnerability
2. **Home-directory check** — any path under `Path.home()` is trusted; `Path.home()` is cross-platform (`~/...` on Linux/macOS, `C:\\Users\\...` on Windows); allows all profile workspaces simultaneously since they don't need to share a single ancestor
3. **Saved-workspace escape hatch** — paths already in the profile's saved workspace list are trusted regardless of location, covering self-hosted deployments with workspaces outside home (`/data/projects`, `/opt/workspace`, etc.)
- `api/workspace.py`: rewritten `resolve_trusted_workspace()` with the three-layer model
- `tests/test_sprint3.py`: updated error-message assertions from `"trusted workspace root"``"outside"` (covers both old and new error strings)
- 1053 tests total (unchanged)
## [v0.50.34] fix(workspace): restrict session workspaces to trusted roots [SECURITY] (#415)
Session creation, update, chat-start, and workspace-add endpoints accepted arbitrary caller-supplied workspace paths. An authenticated caller could repoint a session to any directory the process could access, then use normal file read/write APIs to operate on attacker-chosen locations. CVSS 8.8 High (AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H).
- `api/workspace.py`: new `resolve_trusted_workspace(path)` helper — resolves path, checks existence + is_dir, enforces `path.relative_to(_BOOT_DEFAULT_WORKSPACE)` containment; requests outside the WebUI workspace root fail with 400
- `api/routes.py`: apply `resolve_trusted_workspace()` to all four entry points — `POST /api/session/new`, `POST /api/session/update`, `POST /api/chat/start` (workspace override), `POST /api/workspaces/add`
- `tests/test_sprint3.py`, `tests/test_sprint5.py`: regression tests for rejected outside-root paths on all four entry points; existing workspace tests updated to use trusted child directories
- `tests/test_sprint1.py`, `tests/test_sprint4.py`, `tests/test_sprint13.py`: aligned to new trusted-root contract
- Fix: use `_BOOT_DEFAULT_WORKSPACE` (respects `HERMES_WEBUI_DEFAULT_WORKSPACE` env for test isolation) rather than `_profile_default_workspace()` (reads agent terminal.cwd which may differ)
- Original PR by @Hinotoi-agent (cherry-picked; branch was 6 commits behind master)
- 1053 tests total (up from 1051; 2 pre-existing test_sprint5 isolation failures on master, not introduced by this PR)
## [v0.50.33] fix: workspace panel close button — no duplicate X on desktop, mobile X respects file preview (#413)
**Bug 1 — Duplicate X on desktop:** `#btnClearPreview` (the X icon) was always visible regardless of panel state, so desktop browse mode showed both the chevron collapse button and the X simultaneously. Fixed in `syncWorkspacePanelUI()`: on non-compact (desktop) viewports, `clearBtn.style.display` is set to `none` when no file preview is open, and cleared (shown) when a preview is active.
**Bug 2 — Mobile X collapsed the whole panel instead of dismissing the file:** `.mobile-close-btn` was wired to `closeWorkspacePanel()` directly, bypassing the two-step close logic. Fixed by changing `onclick` to `handleWorkspaceClose()`, which calls `clearPreview()` first if a file is open, and falls through to `closeWorkspacePanel()` otherwise.
**Also:** widened the `test_server_delete_invalidates_index` window from 600 → 1200 chars to accommodate the session_id validation guards added in v0.50.32 (#412).
- `static/boot.js`: `syncWorkspacePanelUI()` sets `clearBtn.style.display` based on `hasPreview` when `!isCompact`
- `static/index.html`: `.mobile-close-btn` onclick changed from `closeWorkspacePanel()` to `handleWorkspaceClose()`
- `tests/test_sprint44.py`: 10 new regression tests covering both fixes
- `tests/test_mobile_layout.py`: updated to accept `handleWorkspaceClose()` as valid onclick
- `tests/test_regressions.py`: widened delete handler window to 1200 chars
- 1051 tests total (up from 1041)
## [v0.50.32] fix(sessions): validate session_id before deleting session files [SECURITY] (#409)
`/api/session/delete` accepted arbitrary `session_id` values from the request body and built the delete path directly as `SESSION_DIR / f"{sid}.json"`. Because pathlib discards the prefix when `sid` is an absolute path, an attacker could supply `/tmp/victim` and cause the server to unlink `victim.json` outside the session store. Traversal-style values (`../../etc/target`) were also accepted. CVSS 8.1 High (AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:H).
- `api/routes.py`: validate `session_id` against `[0-9a-z_]+` allowlist (covers `uuid4().hex[:12]` WebUI IDs and `YYYYMMDD_HHMMSS_hex` CLI IDs) before path construction; resolve candidate path and enforce `path.relative_to(SESSION_DIR)` containment before unlinking; only invalidate session index on successful deletion path, not on rejected requests
- `tests/test_sprint3.py`: 2 new regression tests — absolute-path payload rejected and file preserved, traversal payload rejected and file preserved
- Original PR by @Hinotoi-agent (cherry-picked; branch was 4 commits behind master)
- 1041 tests total (up from 1039)
## [v0.50.31] fix: delegate all live model fetching to agent's provider_model_ids()
`_handle_live_models()` in `api/routes.py` previously maintained its own per-provider fetch logic and returned `not_supported` for Anthropic, Google, and Gemini. Now it delegates entirely to the agent's `hermes_cli.models.provider_model_ids()` — the single authoritative resolver — and `_fetchLiveModels()` in `ui.js` no longer skips any provider.
**What each provider now returns (live data where credentials are present, static fallback otherwise):**
- `anthropic` — live from `api.anthropic.com/v1/models` (API key or OAuth token with correct beta headers)
- `copilot` — live from `api.githubcopilot.com/models` with required Copilot headers
- `openai-codex` — Codex OAuth endpoint → `~/.codex/` cache → `DEFAULT_CODEX_MODELS`
- `nous` — live from Nous inference portal
- `deepseek`, `kimi-coding` — generic OpenAI-compat `/v1/models`
- `opencode-zen`, `opencode-go` — OpenCode live catalog
- `openrouter` — curated static list (live returns 300+ which floods the picker)
- `google`, `gemini`, `zai`, `minimax` — static list (non-standard or Anthropic-compat endpoints)
- All others — graceful static fallback from `_PROVIDER_MODELS`
The hardcoded lists in `_PROVIDER_MODELS` remain as credential-missing / network-unavailable fallbacks. `api/routes.py` shrank by ~100 lines. Updated 2 tests to reflect the improved behavior.
- 1039 tests total (up from 1038)
## [v0.50.30] fix: openai-codex live model fetch routes through agent's get_codex_model_ids()
`_handle_live_models()` was grouping `openai-codex` with `openai` and sending `GET https://api.openai.com/v1/models` — which returns 403 because Codex auth is OAuth-based via `chatgpt.com`, not a standard API key. The live fetch silently failed, so users only ever saw the hardcoded static list.
- `api/routes.py`: dedicated early-return branch for `openai-codex` that calls `hermes_cli.codex_models.get_codex_model_ids()` — the same resolver the agent CLI uses. Resolution order: live Codex API (if OAuth token available, hits `chatgpt.com/backend-api/codex/models`) → `~/.codex/` local cache (written by the Codex CLI) → `DEFAULT_CODEX_MODELS` hardcoded fallback. Users with a valid Codex session now get their exact subscription model list including any models not in the hardcoded list.
- `api/routes.py`: improved label generation for Codex model IDs (e.g. `gpt-5.4-mini``GPT 5.4 Mini`)
- `tests/test_opencode_providers.py`: structural regression test verifying the dedicated `openai-codex` branch exists and calls `get_codex_model_ids()`
- 1038 tests total (up from 1037)
## [v0.50.29] fix: correct tool call card rendering on session load after context compaction (closes #401) (#402)
- `static/sessions.js`: replace the flat B9 filter in `loadSession()` with a full sanitization pass that builds `origIdxToSanitizedIdx` — each `session.tool_calls[].assistant_msg_idx` is remapped to the new sanitized-array position as messages are filtered; for tool calls whose empty-assistant host was filtered out, they attach to the nearest prior kept assistant
- `static/sessions.js`: set `S.toolCalls=[]` instead of pre-filling from session-level `tool_calls` — this lets `renderMessages()` use its fallback derivation from per-message `tool_calls` (which already carry correct indices into the sanitized message array); the fix eliminates the "200+ tool cards all on the wrong message" symptom on context-compacted session load
- `tests/test_issue401.py`: 8 regression tests — 4 static structural checks and 4 behavioural Node.js tests covering index remapping, multiple consecutive empty assistants, no-filtering pass-through, and `tool`-role message exclusion
- Original PR by @franksong2702 (cherry-picked onto master; branch was 31 commits behind)
- 1037 tests total (up from 1029)
## [v0.50.28] fix: expand openai-codex model catalog to match DEFAULT_CODEX_MODELS
`_PROVIDER_MODELS["openai-codex"]` only listed `codex-mini-latest`, so profiles using the `openai-codex` provider (e.g. a CodePath profile with `default: gpt-5.4`) showed only one entry in the model dropdown. Updated to mirror the agent's authoritative `DEFAULT_CODEX_MODELS` list: `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.3-codex`, `gpt-5.2-codex`, `gpt-5.1-codex-max`, `gpt-5.1-codex-mini`, `codex-mini-latest`. Added 2 regression tests.
- 1029 tests total (up from 1027)
## [v0.50.27] feat: relative time labels in session sidebar (#394)
- `static/sessions.js`: new `_sessionCalendarBoundaries()` (DST-safe via `new Date(y,m,d)` construction), `_localDayOrdinal()`, `_formatSessionDate()` (includes year for dates from prior years); `_formatRelativeSessionTime()` now uses calendar midnight boundaries consistent with `_sessionTimeBucketLabel()` — no more label/bucket mismatch; all relative time strings call `t()` for localization; meta row only appended when non-empty (removes redundant group-header fallback); dead `ONE_DAY` constant removed
- `static/style.css`: add `session-item.active .session-title{color:#1a5a8a}` to light-theme block (fixes active title color in light mode)
- `static/i18n.js`: 11 new i18n keys (`session_time_*`) in both English and Spanish locale blocks; callable keys use arrow-function pattern consistent with existing `n_messages`
- `tests/test_session_sidebar_relative_time.py`: 5 tests — structural presence checks, behavioral Node.js tests via subprocess (yesterday/week boundary correctness, `just now` threshold, year-in-date for old sessions, full i18n key coverage for en+es)
- Original PR by @Jordan-SkyLF (two-pass review: blocking issues fixed in second commit)
- 1027 tests total (up from 1022)
## [v0.50.26] fix(sessions): redact sensitive titles in session list and search responses [SECURITY] (#400)
- `api/routes.py`: apply `_redact_text()` to session titles in all four response paths — `/api/sessions` merged list, `/api/sessions/search` empty-q, title-match, and content-match; use `dict(s)` copy before mutating to avoid corrupting the in-memory session cache
- `tests/test_session_summary_redaction.py`: 2 integration tests verifying `sk-` prefixed secrets in session titles are redacted from both list and search endpoint responses
- Original PR by @Hinotoi-agent (note: fix commit had a display artifact — `sk-` prefix was visually rendered as `***` in terminal output but the actual bytes were correct and the token was recognized by the redaction engine)
- 1022 tests total (up from 1020)
## [v0.50.25] Multi-PR batch: mobile scroll, import timestamps, profile security, mic fallback
### fix: restore mobile chat scrolling and drawer close (#397)
- `static/style.css`: `min-height:0` on `.layout` and `.main` (flex shrink chain fix); `-webkit-overflow-scrolling:touch`, `touch-action:pan-y`, `overscroll-behavior-y:contain` on `.messages`
- `static/boot.js`: call `closeMobileSidebar()` on new-conversation button and Ctrl+K shortcut so the transcript is visible immediately after starting a chat
- `tests/test_mobile_layout.py`: 41 new lines covering CSS fixes and both JS call sites
- Original PR by @Jordan-SkyLF
### fix: preserve imported session timestamps (#395)
- `api/models.py`: `Session.save(touch_updated_at=True)` — new flag; `import_cli_session()` accepts `created_at`/`updated_at` kwargs and saves with `touch_updated_at=False`
- `api/routes.py`: extract `created_at`/`updated_at` from `get_cli_sessions()` metadata and forward to import; post-import save also uses `touch_updated_at=False`
- `tests/test_gateway_sync.py`: +53 lines — integration test verifying imported session keeps original timestamp and sorts correctly; also fix session file cleanup in test finally block
- Original PR by @Jordan-SkyLF
### fix(profiles): block path traversal in profile switch and delete flows (#399) [SECURITY]
- `api/profiles.py`: new `_resolve_named_profile_home(name)` — validates name via `^[a-z0-9][a-z0-9_-]{0,63}$` regex then enforces path containment via `candidate.resolve().relative_to(profiles_root)`; use in `switch_profile()`
- `api/profiles.py`: add `_validate_profile_name()` call to `delete_profile_api()` entry
- `api/routes.py`: add `_validate_profile_name()` at HTTP handler level for both `/api/profile/switch` and `/api/profile/delete`
- `tests/test_profile_path_security.py`: 3 new tests — traversal rejected, valid name passes (cherry-picked from @Hinotoi-agent's PR, which was 62 commits behind master)
### feat: add desktop microphone transcription fallback (#396)
- `static/boot.js`: detect `_canRecordAudio`; keep mic button enabled when MediaRecorder available even without SpeechRecognition; full MediaRecorder recording → `/api/transcribe` fallback path with proper cleanup and error handling
- `api/upload.py`: add `transcribe_audio()` helper — temp file, calls transcription_tools, always cleans up
- `api/routes.py`: add `/api/transcribe` POST handler — CSRF-protected, auth-gated, 20MB limit
- `api/helpers.py`: change `Permissions-Policy` `microphone=()``microphone=(self)` (required for getUserMedia)
- `tests/test_voice_transcribe_endpoint.py`: 87 new lines (3 tests with mocked transcription)
- `tests/test_sprint19.py`: regression guard for microphone Permissions-Policy
- `tests/test_sprint20.py`: 3 updated tests for new fallback capability checks
- Original PR by @Jordan-SkyLF
- 1020 tests total (up from 1003)
## [v0.50.24] feat: opt-in chat bubble layout (closes #336)
- `api/config.py`: Add `bubble_layout` bool to `_SETTINGS_DEFAULTS` (default `False`) and `_SETTINGS_BOOL_KEYS` — new setting is opt-in, server-persisted, and coerced to bool on save
- `static/style.css`: 11 lines of CSS-only bubble layout — user rows `align-self:flex-end` / max-width 75%, assistant rows `flex-start`, all gated on `body.bubble-layout` class so the default full-width canvas is untouched; 700px responsive rule widens to 92%
- `static/boot.js`: Apply `body.bubble-layout` class from settings on page load; explicitly remove the class in the catch path so the feature stays off on API failure
- `static/panels.js`: Load checkbox state in `loadSettingsPanel`; write `body.bubble_layout` in `saveSettings` and immediately toggle `body.bubble-layout` class for live preview without a page reload
- `static/index.html`: Checkbox in the Appearance settings group, positioned between Show token usage and Show agent sessions
- `static/i18n.js`: English label + description keys; Spanish translations included in the same PR
- `tests/test_issue336.py`: 22 new tests covering config registration, JS class management in boot and panels, CSS selectors, HTML structure, i18n coverage for en+es, and API round-trip (default false, persist true/false, bool coercion)
- 1003 tests total (up from 981)
## [v0.50.23] Add OpenCode Zen and Go provider support (fixes #362)
- `api/config.py`: Add `opencode-zen` and `opencode-go` to `_PROVIDER_DISPLAY` — providers now show human-readable names in the UI instead of raw IDs
- `api/config.py`: Add full model catalogs for both providers to `_PROVIDER_MODELS` — Zen (pay-as-you-go credits, 32 models) and Go (flat-rate $10/month, 7 models) now show the correct model list in the dropdown instead of falling through to the unknown-provider fallback
- `api/config.py`: Add `OPENCODE_ZEN_API_KEY` / `OPENCODE_GO_API_KEY` to the env-var fallback detection path — providers are correctly detected as authenticated when keys are set in `.env`
- `tests/test_opencode_providers.py`: 6 new tests covering display registration, model catalog registration, and env-var detection for both providers
- 985 tests total (up from 979)
## [v0.50.22] Onboarding unblocked for reverse proxy / SSH tunnel deployments (fixes #390)
- `api/routes.py`: Onboarding setup endpoint now reads `X-Forwarded-For` and `X-Real-IP` headers before falling back to raw socket IP — reverse proxy (nginx/Caddy/Traefik) and SSH tunnel users are no longer incorrectly blocked
- Added `HERMES_WEBUI_ONBOARDING_OPEN=1` env var escape hatch for operators on remote servers who control network access themselves
- Error message now includes the env var hint so users know how to unblock themselves
- 18 new tests covering all IP resolution paths (`TestOnboardingIPLogic`, `TestOnboardingSetupEndpoint`)
> Living document. Updated at the end of every sprint.
> Repository: https://github.com/nesquena/hermes-webui
---
## [v0.50.21] Live reasoning, tool progress, and in-flight session recovery (PR #367)
- **Durable inflight reload recovery** (`static/ui.js`, `static/messages.js`): `saveInflightState` / `loadInflightState` / `clearInflightState` backed by `localStorage` (`hermes-webui-inflight-state` key, per-session, 10-minute TTL). Snapshots are saved on every token, tool event, and tool completion, and cleared when the run ends/errors/cancels. On a full page reload with an active stream, `loadSession()` hydrates from the snapshot before calling `attachLiveStream(..., {reconnecting:true})` — partial messages, live tool cards, and reasoning text all survive the reload.
- **Live reasoning cards during streaming** (`static/ui.js`, `static/messages.js`): The generic thinking spinner now upgrades to a live reasoning card when the backend streams reasoning text. `_thinkingMarkup(text)` and `updateThinking(text)` centralize the markup so the spinner and card share the same DOM slot. Works with models that emit reasoning via the agent's `reasoning_callback` or `tool_progress_callback`.
- **`tool_complete` SSE events** (`api/streaming.py`, `static/messages.js`): Tool progress callback now accepts the current agent signature `on_tool(*cb_args, **cb_kwargs)` — handles both the old 3-arg `(name, preview, args)` form and the new 4-arg `(event_type, name, preview, args)` form. `tool.completed` events transition live tool cards from running to done cleanly.
- **In-flight session state stable across switches** (`static/messages.js`, `static/sessions.js`): `attachLiveStream` refactored out of `send()` into a standalone function; partial assistant text mirrored into `INFLIGHT` state on every token; `data-live-assistant` DOM anchor preserved across `renderMessages()` calls so switching away and back doesn't lose or duplicate live output.
- **Reload recovery** (`api/models.py`, `api/routes.py`, `api/streaming.py`, `static/sessions.js`): `active_stream_id`, `pending_user_message`, `pending_attachments`, and `pending_started_at` now persisted on the session object before streaming starts and cleared on completion (or exception). `/api/session` returns these fields. After a page reload or session switch, `loadSession()` detects `active_stream_id` and calls `attachLiveStream(..., {reconnecting:true})` to reattach to the live SSE stream.
- **Session-scoped message queue** (`static/ui.js`, `static/messages.js`): Global `MSG_QUEUE` replaced with `SESSION_QUEUES` keyed by session ID. Queued follow-up messages are associated with the session they were typed in and only drained when that session becomes idle — no cross-session bleed.
- **`newSession()` idle reset** (`static/sessions.js`): Sets `S.busy=false`, `S.activeStreamId=null`, clears the cancel button, resets composer status — ensures a fresh chat is immediately usable even if another session's stream is still running.
- **Todos survive session reload** (`static/panels.js`): `loadTodos()` now reads from `S.session.messages` (raw, includes tool-role messages) rather than `S.messages` (filtered display), so todo state reconstructed from tool outputs survives reloads.
- 12 new regression tests in `tests/test_regressions.py`; 961 tests total (up from 949)
## [v0.50.20] Silent error fix, stale model cleanup, live model fetching (fixes #373, #374, #375)
### Fix: Chat no longer silently swallows agent failures (fixes #373)
- **`api/streaming.py`**: After `run_conversation()` completes, the server now checks whether the agent produced any assistant reply. If not (e.g., auth error swallowed internally, model unavailable, network timeout), it emits an `apperror` SSE event with a clear message and type (`auth_mismatch` or `no_response`) instead of silently emitting `done`. A `_token_sent` flag tracks whether any streaming tokens were sent.
- **`static/messages.js`**: The `done` handler has a belt-and-suspenders guard — if `done` arrives but no assistant message exists in the session (the `apperror` path should usually catch this first), an inline "**No response received.**" message is shown. The `apperror` handler now also recognises the new `no_response` type with a distinct label.
### Cleanup: Remove stale OpenAI models from default list (fixes #374)
- **`api/config.py`**: `gpt-4o` and `o3` removed from `_FALLBACK_MODELS` and `_PROVIDER_MODELS["openai"]`. Both are superseded by newer models already in the list (`gpt-5.4-mini` for general use, `o4-mini` for reasoning). The Copilot provider list retains `gpt-4o` as it remains available via the Copilot API.
### Feature: Live model fetching from provider API (closes #375)
- **`api/routes.py`**: New `/api/models/live?provider=openai` endpoint. Fetches the actual model list from the provider's `/v1/models` API using the user's configured credentials. Includes URL scheme validation (B310), SSRF guard (private IP block), and graceful `not_supported` response for providers without a standard `/v1/models` endpoint (Anthropic, Google). Response normalised to `{id, label}` list, filtered to chat models.
- **`static/ui.js`**: `populateModelDropdown()` now calls `_fetchLiveModels()` in the background after rendering the static list. Live models that aren't already in the dropdown are appended to the provider's optgroup. Results are cached per session so only one fetch per provider per page load. Skips Anthropic and Google (unsupported). Falls back to static list silently if the fetch fails.
- 25 new tests in `tests/test_issues_373_374_375.py`; 949 tests total (up from 924)
## [v0.50.19] Fix UnicodeEncodeError when downloading files with non-ASCII filenames (PR #378)
- **Workspace file downloads no longer crash for Unicode filenames** (`api/routes.py`): Clicking a PDF or other file with Chinese, Japanese, Arabic, or other non-ASCII characters in its name caused a `UnicodeEncodeError` because Python's HTTP server requires header values to be latin-1 encodable. A new `_content_disposition_value(disposition, filename)` helper centralises `Content-Disposition` generation: it strips CR/LF (injection guard), builds an ASCII fallback for the legacy `filename=` parameter (non-ASCII chars replaced with `_`), and preserves the full UTF-8 name in `filename*=UTF-8''...` per RFC 5987. Both `attachment` and `inline` responses use it.
- 2 new integration tests in `tests/test_sprint29.py` covering Chinese filenames for both download and inline responses, verifying the header is latin-1 encodable and `filename*=UTF-8''` is present; 924 tests total (up from 922)
## [v0.50.18] Recover from invalid default workspace paths (PR #366)
- **WebUI no longer breaks when the configured default workspace is unavailable** (`api/config.py`): The workspace resolution path was refactored into three composable functions — `_workspace_candidates()`, `_ensure_workspace_dir()`, and `resolve_default_workspace()`. When the configured workspace (from env var, settings file, or passed path) cannot be created or accessed, the server falls back through an ordered priority list: `HERMES_WEBUI_DEFAULT_WORKSPACE` env var → `~/workspace` (if exists) → `~/work` (if exists) → `~/workspace` (create it) → `STATE_DIR/workspace`.
- **`save_settings()` now validates and corrects the workspace path** (`api/config.py`): If a client posts an invalid or inaccessible `default_workspace`, the saved value is corrected to the nearest valid fallback rather than persisting an unusable path.
- **Startup normalizes stale workspace paths** (`api/config.py`): If the settings file stores a workspace that no longer exists, the server rewrites it with the resolved fallback on startup so the problem self-heals.
- 7 tests in `tests/test_default_workspace_fallback.py` (2 from PR + 5 added during review: fallback creation, RuntimeError on all-fail, deduplication, env var priority, unwritable path returns False); 922 tests total (up from 915)
## [v0.50.17] Docker: pre-install uv at build time + fix workspace permissions (fixes #357)
- **Docker containers no longer need internet access at startup** (`Dockerfile`): `uv` is now installed at image build time via `RUN curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh` (run as root, so `uv` lands in `/usr/local/bin` — accessible to all users). The init script skips the download if `uv` is already on PATH (`command -v uv`), and falls back to downloading with a proper `error_exit` if it isn't. This fixes startup failures in air-gapped, firewalled, or isolated Docker networks where `github.com` is unreachable at runtime.
- **Fix applied during review**: the original PR installed `uv` as the `hermeswebuitoo` user (to `~hermeswebuitoo/.local/bin`), which is not on the `hermeswebui` runtime user's `PATH`. Changed to install as `root` with `UV_INSTALL_DIR=/usr/local/bin` so `uv` is in the system PATH for all users.
- **Workspace directory now writable by the hermeswebui user** (`docker_init.bash`): The init script now uses `sudo mkdir -p` and `sudo chown hermeswebui:hermeswebui` for `HERMES_WEBUI_DEFAULT_WORKSPACE`. Docker auto-creates bind-mount directories as `root` if they don't exist on the host, making them unwritable by the app user. The `sudo chown` corrects ownership after creation.
- 15 new structural tests in `tests/test_issue357.py`; 915 tests total (up from 900)
## [v0.50.16] Fix CSRF check failing behind reverse proxy on non-standard ports (PR #360)
- **CSRF no longer rejects POST requests from reverse-proxied deployments on non-standard ports** (`api/routes.py`, fixes #355): When serving behind Nginx Proxy Manager or similar on a port like `:8000`, browsers send `Origin: https://app.example.com:8000` while the proxy forwards `Host: app.example.com` (port stripped). The old string comparison failed this as cross-origin. Two changes fix it:
- `_normalize_host_port()`: properly splits host:port strings including IPv6 bracket notation (`[::1]:8080`)
- `_ports_match(scheme, origin_port, allowed_port)`: scheme-aware port equivalence — absent port equals `:80` for `http://` and `:443` for `https://`. This prevents the previous cross-protocol confusion where `http://host` could incorrectly match an `https://host:443` server (security fix applied on top of the original PR)
- `HERMES_WEBUI_ALLOWED_ORIGINS` env var: comma-separated explicit origin allowlist for cases where port normalization alone isn't sufficient (e.g. non-standard ports like `:8000` where the proxy strips the port entirely). Entries without a scheme (`https://`) are rejected with a startup warning.
- **Security fix applied during review**: the original `_ports_match` treated both port 80 and port 443 as interchangeable with "absent port", which is scheme-unaware. An `http://host` origin would pass for an `https://host:443` server. Fixed by making the default-port lookup scheme-specific.
- 29 new tests in `tests/test_sprint29.py` (5 from PR + 24 added during review): cover scheme-aware port matching, cross-protocol rejection, unit tests for `_normalize_host_port` and `_ports_match`, allowlist validation, comma-separated origins, no-scheme allowlist warning, the bug scenario with and without the allowlist; 900 tests total (up from 871)
## [v0.50.15] KaTeX math rendering for LaTeX in chat and workspace previews (fixes #347)
- **LaTeX / KaTeX math now renders in chat messages and workspace file previews** (`static/ui.js`, `static/workspace.js`, `static/style.css`, `static/index.html`): Inline math (`$...$`, `\(...\)`) and display math (`$$...$$`, `\[...\]`) are rendered via KaTeX instead of displaying as raw text. Follows the existing mermaid lazy-load pattern: delimiters are stashed before markdown processing, placeholder elements are emitted, and KaTeX JS is loaded from CDN on first use — no KaTeX JS is loaded unless math is present.
- `$$...$$` and `\[...\]` → centered display math (`<div class="katex-block">`)
- `$...$` and `\(...\)` → inline math (`<span class="katex-inline">`); requires non-space at `$` boundaries to avoid false positives on currency amounts like `$5`
- KaTeX JS lazy-loaded from jsdelivr CDN with SRI hash; KaTeX CSS loaded eagerly in `<head>` to prevent layout shift
- `throwOnError:false` — invalid LaTeX degrades to a `<code>` span rather than crashing the message
- `trust:false` — disables KaTeX commands that could execute code
- `<span>` added to `SAFE_TAGS` allowlist for inline math spans (tag name boundary check preserved)
- **Fix: fence stash now runs before math stash** (`static/ui.js`): The original PR had math stash before fence stash, meaning `\`$x$\`` inside backtick code spans was incorrectly extracted as math instead of being protected as code. Order corrected — fence_stash runs first so code spans protect their contents.
- **Workspace file previews now render math** (`static/workspace.js`): Added `requestAnimationFrame(renderKatexBlocks)` after markdown file preview renders, matching the chat message path. Without this, math placeholders appeared in previews but were never rendered.
- 29 tests in `tests/test_issue347.py` (18 original + 11 new covering stash ordering, workspace wiring, false-positive prevention); 870 tests total (up from 841)
## [v0.50.14] Security fixes: B310 urlopen scheme validation, B324 MD5 usedforsecurity, B110 bare except logging + QuietHTTPServer (PR #354)
- **B324 — MD5 no longer triggers crypto warnings** (`api/gateway_watcher.py`): `_snapshot_hash` uses MD5 only as a non-cryptographic change-detection hash. Added `usedforsecurity=False` so systems with strict crypto policies (FIPS mode etc.) don't reject the call.
- **B310 — urlopen now validates URL scheme** (`api/config.py`, `bootstrap.py`): Both `get_available_models()` and `wait_for_health()` validate that the URL scheme is `http` or `https` before calling `urllib.request.urlopen`, preventing `file://` or other dangerous scheme injection. Added `# nosec B310` suppression after each validated call.
- **B110 — bare `except: pass` blocks replaced with `logger.debug()`** (12 files): All `except Exception: pass` and `except: pass` blocks now log the failure at DEBUG level so operators can diagnose issues in production without changing behavior. A module-level `logger = logging.getLogger(__name__)` was added to each file.
- **`QuietHTTPServer`** (`server.py`): Subclass of `ThreadingHTTPServer` that overrides `handle_error()` to silently drop `ConnectionResetError`, `BrokenPipeError`, `ConnectionAbortedError`, and socket errno 32/54/104 (client disconnect races). Real errors still delegate to the default handler. Reduces log spam from SSE clients that disconnect mid-stream.
- **Session title redaction** (`api/routes.py`): The `/api/sessions` list endpoint now applies `_redact_text` to session titles before returning them, consistent with the per-session `redact_session_data()` already applied elsewhere.
- **Fix**: `QuietHTTPServer.handle_error` uses `sys.exc_info()` (standard library) not `traceback.sys.exc_info()` (implementation detail); `sys` is now explicitly imported in `server.py`.
- 19 new tests in `tests/test_sprint43.py`; 841 tests total (up from 822)
## [v0.50.13] Fix session_search in WebUI sessions — inject SessionDB into AIAgent (PR #356)
- **`session_search` now works in WebUI sessions** (`api/streaming.py`): The agent's `session_search` tool returned "Session database not available" for all WebUI sessions. The CLI and gateway code paths both initialize a `SessionDB` instance and pass it via `session_db=` to `AIAgent.__init__()`, but the WebUI streaming path was missing this step. `_run_agent_streaming` now initializes `SessionDB()` before constructing the agent and passes it in. A `try/except` wrapper makes the init non-fatal — if `hermes_state` is unavailable (older installs, test environments), a `WARNING` is printed and `session_db=None` is passed instead, preserving the prior behavior gracefully.
- 7 new tests in `tests/test_sprint42.py`; 822 tests total (up from 815)
## [v0.50.12] Profile .env isolation — prevent API key leakage on profile switch (fixes #351)
- **API keys no longer leak between profiles on switch** (`api/profiles.py`): `_reload_dotenv()` now tracks which env vars were loaded from the active profile's `.env` and clears them before loading the next profile. Previously, switching from a profile with `OPENAI_API_KEY=X` to a profile without that key left `X` in `os.environ` for the duration of the process — effectively leaking credentials across the profile boundary. A module-level `_loaded_profile_env_keys: set[str]` tracks loaded keys; it is cleared and repopulated on every `_reload_dotenv()` call.
- **`apply_onboarding_setup()` ordering fixed** (`api/onboarding.py`): the belt-and-braces `os.environ[key] = api_key` direct assignment is now placed **after** `_reload_dotenv()`. Previously the key was wiped by the isolation cleanup when `_reload_dotenv()` ran immediately after the direct set.
- 2 new tests in `tests/test_profile_env_isolation.py`; 815 tests total (up from 813)
## [v0.50.11] Chat table styles + plain URL auto-linking (fixes #341, #342)
- **Tables in chat messages now render with visible borders** (`static/style.css`): The `.msg-body` area had no table CSS, so markdown tables sent by the assistant were unstyled and unreadable. Four new rules mirror the existing `.preview-md` table styles: `border-collapse:collapse`, per-cell padding and borders via `var(--border2)`, and an alternating-row tint. Two `:root[data-theme="light"]` overrides ensure the borders and header background adapt correctly in light mode. (fixes #341)
- **Plain URLs in chat messages are now clickable** (`static/ui.js`): Bare URLs like `https://example.com` were rendered as plain text. A new autolink pass in `renderMd()` converts `https?://...` URLs to `<a>` tags automatically. Runs after the SAFE_TAGS escape pass (protecting code blocks), before paragraph wrapping. Also applied inside `inlineMd()` so URLs in list items, blockquotes, and table cells are linked too. Trailing punctuation stripped; `esc()` applied to both href and link text. (fixes #342)
- 11 new tests (4 in `tests/test_issue341.py`, 7 in `tests/test_issue342.py`); 813 tests total (up from 802)
- **Test infrastructure fix** (`tests/test_sprint34.py` #349): two static-file opens used bare relative paths that failed when pytest ran from outside the repo root; replaced with `pathlib.Path(__file__).parent.parent` consistent with the rest of the suite. 813/813 now pass from any working directory.
## [v0.50.10] Title auto-generation fix + mobile close button (PR #333)
- **Session title now auto-generates for all default title values** (`'Untitled'`, `'New Chat'`, empty string): The condition in `api/streaming.py` that triggers `title_from()` previously only matched `'Untitled'`. It now also covers `'New Chat'` (used by some external clients/forks) and any empty/falsy title, so sessions started from those states get a proper auto-generated title after the first message.
- **Redundant workspace panel close button hidden on mobile** (`static/style.css`): On viewports ≤900px wide, both the desktop collapse button (`#btnCollapseWorkspacePanel`) and the mobile-specific X button (`.mobile-close-btn`) were rendered simultaneously. The desktop button is now hidden on mobile and `.mobile-close-btn` is hidden by default (desktop) and shown only on mobile — eliminating the duplicate control.
- 11 new tests in `tests/test_sprint41.py`; 802 tests total (up from 791)
## [v0.50.9] Onboarding works from Docker bridge networks (PR #335, fixes #334)
- **Docker users can now complete onboarding without enabling auth first** (closes #334): The onboarding setup endpoint previously only accepted requests from `127.0.0.1`. Docker containers connect via bridge network IPs (`172.17.x.x`, etc.), so the endpoint returned a 403 mid-wizard with no clear explanation. The check now accepts any loopback or RFC-1918 private address (`127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) using Python's `ipaddress.is_loopback` and `is_private`. Public IPs are still blocked unless auth is enabled.
## [v0.50.8] Model dropdown deduplication — hyphen vs dot separator fix (PR #332)
- **Model dropdown no longer shows duplicates for hyphen-format configs** (e.g. `claude-sonnet-4-6` from hermes-agent config): The server-side normalization in `api/config.py` now unifies hyphens and dots when checking whether the default model is already in the dropdown. Previously, `claude-sonnet-4-6` (hermes-agent format) and `claude-sonnet-4.6` (WebUI list format) were treated as different models, causing the same model to appear twice — once as a raw unlabelled entry and once with the correct display name. The raw entry is now suppressed and the labelled one is selected as default.
- **README updated**: test count corrected to 791 / 51 files; all module line counts updated to current values; `onboarding.py`, `state_sync.py`, `updates.py` added to the architecture listing.
## [v0.50.7] OAuth provider onboarding path — Codex/Copilot no longer blocks setup (PR #331, fixes #329 bug 2)
- **OAuth providers now have a proper onboarding path** (closes bug 2): Users with `openai-codex`, `copilot`, `qwen-oauth`, or any other OAuth-authenticated provider now see a clear confirmation card instead of an unusable API key input form.
- If already authenticated (`chat_ready: true`): blue "Provider already authenticated" card with a direct Continue button — no key entry required.
- If not yet authenticated: amber card explaining how to run `hermes auth` or `hermes model` in a terminal to complete setup.
- Either state includes a collapsible "switch provider" section for users who want to move to an API-key provider instead.
- `_build_setup_catalog` now includes `current_is_oauth` boolean; fixed a latent `KeyError` crash when looking up `default_model` for OAuth providers.
- 5 new i18n keys in English and Spanish (`onboarding_oauth_*`).
- 15 new tests in `tests/test_sprint40.py`; 791 tests total (up from 776)
## [v0.50.6] Skip-onboarding env var + synchronous API key reload (PR #330, fixes #329 bugs 1+3)
- **`HERMES_WEBUI_SKIP_ONBOARDING=1`** (closes bug 1): Hosting providers can set this env var to bypass the first-run wizard entirely. Only takes effect when `chat_ready` is also true — a misconfigured deployment still shows the wizard. Accepts `1`, `true`, or `yes`.
- **API key takes effect immediately after onboarding** (closes bug 3): `apply_onboarding_setup` now sets `os.environ[env_var]` synchronously after writing the key to `.env`, so the running process can use it without a server restart. Also attempts to reload `hermes_cli`'s config cache as a belt-and-suspenders measure.
- 8 new tests in `tests/test_sprint39.py`; 776 tests total (up from 768)
## [v0.50.5] Think-tag stripping with leading whitespace (PR #327)
- **Fix think-tag rendering for models that emit leading whitespace** (e.g. MiniMax M2.7): Some models emit one or more newlines before the `<think>` opening tag. The previous regex used a `^` anchor, so it only matched when `<think>` was the very first character. When the anchor failed, the raw `</think>` tag appeared in the rendered message body.
- `static/ui.js` (stored messages): removed `^` anchor from `<think>` and Gemma channel-token regexes; switched from `.slice()` to `.replace()` + `.trimStart()` so stripping works regardless of position
- `static/messages.js` (live stream): `trimStart()` before `startsWith`/`indexOf` checks; partial-tag-prefix guard also uses trimmed buffer
- 10 new tests in `tests/test_sprint38.py`; 768 tests total (up from 758)
## [v0.50.3] Onboarding completes gracefully for pre-configured providers (PR #323, fixes #322)
- **OAuth/CLI-configured providers no longer blocked by onboarding** (closes #322): Users with providers already set up via the CLI (`openai-codex`, `copilot`, `nous`, etc.) hit `Unsupported provider for WebUI onboarding` when clicking "Open Hermes" on the finish page. The wizard now marks onboarding complete and lets them through — the agent setup is already done, no wizard steps needed.
- 5 new tests in `tests/test_sprint34.py`; 758 tests total (up from 753)
## [v0.50.2] Workspace panel state persists across refreshes

View File

@@ -67,6 +67,13 @@ RUN touch /.within_container
RUN rm -rf /var/lib/apt/lists/* /etc/apt/apt.conf.d/01proxy \
&& apt-get clean
USER root
# Pre-install uv system-wide so the container doesn't need internet access at runtime.
# Installing as root places uv in /usr/local/bin, available to all users.
# The init script will skip the download when uv is already on PATH.
RUN curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh
USER hermeswebuitoo
COPY . /apptoo

122
README.md
View File

@@ -339,8 +339,8 @@ Or using the agent venv explicitly:
```
Tests run against an isolated server on port 8788 with a separate state directory.
Production data and real cron jobs are never touched. Current count: **433 tests**
across 23 test files.
Production data and real cron jobs are never touched. Current count: **961 tests**
across 53 test files.
---
@@ -462,31 +462,33 @@ across 23 test files.
## Architecture
```
server.py HTTP routing shell + auth middleware (~83 lines)
server.py HTTP routing shell + auth middleware (~154 lines)
api/
auth.py Optional password authentication, signed cookies (~149 lines)
config.py Discovery, globals, model detection, reloadable config (~726 lines)
helpers.py HTTP helpers, security headers (~71 lines)
models.py Session model + CRUD + CLI bridge (~338 lines)
profiles.py Profile state management, hermes_cli wrapper (~366 lines)
routes.py All GET + POST route handlers (~1314 lines)
streaming.py SSE engine, run_agent, cancel support (~332 lines)
upload.py Multipart parser, file upload handler (~78 lines)
auth.py Optional password authentication, signed cookies (~201 lines)
config.py Discovery, globals, model detection, reloadable config (~1110 lines)
helpers.py HTTP helpers, security headers (~175 lines)
models.py Session model + CRUD + CLI bridge (~377 lines)
onboarding.py First-run onboarding wizard, OAuth provider support (~507 lines)
profiles.py Profile state management, hermes_cli wrapper (~411 lines)
routes.py All GET + POST route handlers (~2250 lines)
state_sync.py /insights sync — message_count to state.db (~113 lines)
streaming.py SSE engine, run_agent, cancel support (~660 lines)
updates.py Self-update check and release notes (~257 lines)
upload.py Multipart parser, file upload handler (~82 lines)
workspace.py File ops, workspace helpers, git detection (~288 lines)
static/
index.html HTML template (~600 lines)
style.css All CSS incl. mobile responsive, themes (~855 lines)
ui.js DOM helpers, renderMd, tool cards, context ring (~1090 lines)
workspace.js File preview, file ops, git badge (~247 lines)
sessions.js Session CRUD, ⋯ dropdown, collapsible groups, search (~600 lines)
messages.js send(), SSE handlers, rAF throttle (~352 lines)
panels.js Cron, skills, memory, profiles, control center (~1200 lines)
commands.js Slash command autocomplete (~170 lines)
boot.js Mobile nav, workspace state machine, composer chips, boot IIFE (~420 lines)
style.css All CSS incl. mobile responsive, themes (~1050 lines)
ui.js DOM helpers, renderMd, tool cards, context indicator (~1740 lines)
workspace.js File preview, file ops, git badge (~286 lines)
sessions.js Session CRUD, collapsible groups, search, reload recovery (~800 lines)
messages.js send(), SSE handlers, live streaming, session recovery (~655 lines)
panels.js Cron, skills, memory, profiles, settings (~1438 lines)
commands.js Slash command autocomplete (~267 lines)
boot.js Mobile nav, voice input, boot IIFE (~524 lines)
tests/
conftest.py Isolated test server (port 8788)
test_sprint{1-36}.py 36 test files, 742 test functions
test_regressions.py Permanent regression gate
61 test files 961 test functions
Dockerfile python:3.12-slim container image
docker-compose.yml Compose with named volume and optional auth
.github/workflows/ CI: multi-arch Docker build + GitHub Release on tag
@@ -522,18 +524,60 @@ Six consecutive security and reliability PRs: session memory leak fix (expired t
**[@DavidSchuchert](https://github.com/DavidSchuchert)** — German translation (PR #190)
Complete German locale (`de`) covering all UI strings, settings labels, commands, and system messages — and in doing so, stress-tested the i18n system and exposed several elements that weren't yet translatable, which got fixed as part of the same PR.
**[@Jordan-SkyLF](https://github.com/Jordan-SkyLF)** — Live streaming, session recovery, workspace fallback (PRs #366, #367)
Three interlocking improvements: workspace fallback resolution so the server recovers gracefully when the configured workspace is deleted or unavailable; live reasoning cards that upgrade the generic thinking spinner to a real-time reasoning display as the model thinks; and durable session state recovery via `localStorage` so in-flight tool cards, partial assistant output, and the live SSE stream all survive a full page reload or session switch.
### Feature contributions
**[@gabogabucho](https://github.com/gabogabucho)** — Spanish locale + onboarding wizard (PRs #275, #285)
Full Spanish (`es`) locale covering all 175 UI strings, plus the one-shot bootstrap onboarding wizard that guides new users through provider setup on first launch — the feature most responsible for new users actually getting started.
**[@bergeouss](https://github.com/bergeouss)** — Real-time gateway session sync (PR #274)
Bridged the gateway session database (Telegram, Discord, Slack, etc.) into the WebUI sidebar with live SSE polling. Gateway sessions now appear alongside WebUI sessions in real time, without any changes to hermes-agent.
**[@ccqqlo](https://github.com/ccqqlo)** — Terminal approval UX + custom model discovery + mobile close button (PRs #224, #225, #238, #333)
A run of focused quality-of-life improvements: terminal tool approval prompts that stay visible long enough to actually be read, restored custom model API key discovery, and the redundant mobile close button fix that had been confusing users on narrow screens.
**[@kevin-ho](https://github.com/kevin-ho)** — OLED theme (PR #168)
Added the 7th built-in theme: pure black backgrounds with warm accents tuned to reduce burn-in risk. Small diff, big impact for anyone on an OLED display.
**[@Bobby9228](https://github.com/Bobby9228)** — Mobile Profiles button (PR #265)
Added the Profiles tab to the mobile bottom navigation bar, making profile switching reachable on phones without digging into the sidebar.
**[@Bobby9228](https://github.com/Bobby9228)** — Mobile Profiles button + Android Chrome fixes (PRs #253, #263, #265)
Added the Profiles tab to the mobile bottom navigation bar, making profile switching reachable on phones, plus a set of Android Chrome-specific fixes for the profile dropdown.
**[@franksong2702](https://github.com/franksong2702)** — Session title guard + breadcrumb nav (PRs #301, #302)
Two clean bug fixes / features: the session title guard that stops `title_from()` from overwriting user-renamed sessions after every turn, and clickable breadcrumb navigation in the workspace file preview panel.
### Bug fix contributions
**[@betamod](https://github.com/betamod)** — Security hardening (PR #171)
A comprehensive security audit PR covering CSRF protection, SSRF guards, XSS escaping improvements, and the env race condition between concurrent agent sessions — foundational security work that shipped in v0.39.0.
**[@TaraTheStar](https://github.com/TaraTheStar)** — Bot name + thinking blocks + login refactor (PRs #132, #176, #181)
Made the assistant display name configurable throughout the UI, added thinking/reasoning block display in chat, and refactored the login page to use template variables instead of inline string replacement.
**[@thadreber-web](https://github.com/thadreber-web)** — CLI session bridge (PR #56)
The original CLI session bridge: reads CLI sessions from the agent's SQLite state store and surfaces them in the WebUI sidebar. This was the first bridge between the CLI and WebUI session worlds.
**[@deboste](https://github.com/deboste)** — Reverse proxy auth + mobile responsive layout + model routing (PRs #3, #4, #5)
Three of the very first community PRs: fixed EventSource/fetch to use the URL origin for reverse proxy setups, corrected model provider routing from config, and added mobile responsive layout with dvh viewport fix. Early foundation work.
### Bug fix and security contributions
**[@Hinotoi-agent](https://github.com/Hinotoi-agent)** — Profile .env secret isolation (PR #351)
Fixed API key leakage between profiles on switch — switching from a profile with `OPENAI_API_KEY` to one without it left the key in the process environment for the duration of the session, effectively leaking credentials. A subtle and important security fix.
**[@lawrencel1ng](https://github.com/lawrencel1ng)** — Bandit security fixes B310/B324/B110 + QuietHTTPServer (PR #354)
Systematic bandit security scan fixes: URL scheme validation before `urlopen`, MD5 `usedforsecurity=False`, and 40+ bare `except: pass` blocks replaced with proper logging — plus `QuietHTTPServer` to stop client-disconnect log spam from SSE streams.
**[@lx3133584](https://github.com/lx3133584)** — CSRF fix for reverse proxy on non-standard ports (PR #360)
Fixed CSRF rejection for deployments behind Nginx Proxy Manager or similar on non-standard ports — a real-world blocker for anyone hosting on a port other than 80/443.
**[@DelightRun](https://github.com/DelightRun)** — session_search fix for WebUI sessions (PR #356)
The `session_search` tool silently returned "Session database not available" in every WebUI session. Tracked down the missing `SessionDB` injection in the streaming path and fixed it.
**[@shaoxianbilly](https://github.com/shaoxianbilly)** — Unicode filename downloads (PR #378)
Fixed `UnicodeEncodeError` crashes when downloading workspace files with Chinese, Japanese, or other non-ASCII names. Implemented proper `Content-Disposition` header with RFC 5987 `filename*=UTF-8''...` encoding.
**[@huangzt](https://github.com/huangzt)** — Cancel interrupts agent (PR #244)
Made the Cancel button actually interrupt the running agent and clean up UI state, rather than just hiding the button while the agent kept running.
**[@tgaalman](https://github.com/tgaalman)** — Thinking card fix (PR #169)
Fixed top-level reasoning fields being missed in the thinking card display — an edge case in how Claude's extended thinking blocks surface in the API response.
@@ -544,6 +588,36 @@ Fixed model routing for slash-prefixed custom provider models, which were being
**[@jeffscottward](https://github.com/jeffscottward)** — Claude Haiku model ID fix (PR #145)
Caught and corrected the Claude Haiku model ID (`3-5``4-5`) immediately after the Anthropic release — the kind of quick community catch that keeps the model dropdown accurate.
**[@kcclaw001](https://github.com/kcclaw001)** — Credential redaction in API responses (PR #243)
Added credential redaction to all API response paths so API keys, tokens, and other secrets in session data or error messages are masked before reaching the browser.
**[@mbac](https://github.com/mbac)** — Phantom "Custom" provider group fix (PR #191)
Removed the phantom "Custom" optgroup that appeared in the model dropdown even when no custom provider was configured — a small but consistently confusing UI noise issue.
**[@andrewy-wizard](https://github.com/andrewy-wizard)** — Chinese localization (PR #177)
Added Simplified Chinese (`zh`) locale to the WebUI. One of the first non-English locales and the most-used non-English locale in the codebase.
**[@mmartial](https://github.com/mmartial)** — Docker UID/GID matching (PR #237)
Added Docker support for running as an arbitrary UID/GID matching the host user, eliminating permission issues with bind-mounted volumes — essential for Docker deployments where the host user isn't UID 1000.
**[@vCillusion](https://github.com/vCillusion)** — pip package resolution fix (PR #76)
Fixed agent dependency resolution to prefer packages from the venv's site-packages over the agent directory itself, preventing shadowing bugs when developing locally.
**[@carlytwozero](https://github.com/carlytwozero)** — API key pass-through for non-Anthropic providers (PR #78)
Fixed `api_key` not being passed to `AIAgent` for non-Anthropic `/anthropic` providers — a quiet regression that silently broke any non-default provider.
**[@mangodxd](https://github.com/mangodxd)** — Type hints cleanup (PR #115)
Added missing type hints across 10 files and corrected 9 inaccurate existing ones — the kind of maintenance work that makes the codebase easier to reason about.
**[@Argonaut790](https://github.com/Argonaut790)** — HTML entity decode + Traditional Chinese locale (PR #239)
Fixed double-escaping of HTML entities in `renderMd()` — LLM output containing `&lt;code&gt;` was being escaped a second time, rendering as literal text instead of the intended markdown. The same PR also completed the Simplified Chinese translation (40+ missing keys) and added a full Traditional Chinese (`zh-Hant`) locale.
**[@indigokarasu](https://github.com/indigokarasu)** — Visual redesign proposal: icon rail + design token system + 7 themes (PR #213)
A CSS-only redesign of the full UI — proper design tokens (`--bg-primary`, `--text-info`, spacing scale), an icon rail sidebar replacing the emoji tab strip, consistent form cards, breadcrumb nav, and 7 built-in themes as custom properties. The PR didn't merge as-is but directly shaped the design language and theme architecture that shipped in v0.50.0.
**[@zenc-cp](https://github.com/zenc-cp)** — Anti-hallucination guard for ReAct loop (PR #133)
Added a streaming token buffer and post-run message scrub to `streaming.py` to detect and strip fake tool execution JSON that weaker models write inline instead of calling tools properly. A three-layer approach: ephemeral anti-hallucination prompt, live token filtering, and session history cleanup. The pattern influenced later streaming.py improvements.
---
Want to contribute? See [ARCHITECTURE.md](ARCHITECTURE.md) for the codebase layout and [TESTING.md](TESTING.md) for how to run the test suite. The best contributions are focused, well-tested, and solve a real problem — exactly what every person on this list did.

View File

@@ -3,9 +3,10 @@
> Goal: Full 1:1 parity with the Hermes CLI experience via a clean dark web UI.
> Everything you can do from the CLI terminal, you can do from this UI.
>
> Last updated: v0.49.1 (April 12, 2026) — 700 tests, 700 passing
> Onboarding MVP now writes real Hermes provider config from the Web UI for OpenRouter, Anthropic, OpenAI, and custom OpenAI-compatible endpoints.
> Tests: 700 total (700 passing, 0 failures)
> Last updated: v0.50.21 (April 13, 2026) — 961 tests, 961 passing
> Full production-ready: onboarding wizard, multi-profile support, KaTeX math rendering,
> live reasoning cards with localStorage reload recovery, CSRF reverse proxy fixes, Docker improvements.
> Tests: 961 total (961 passing, 0 failures)
> Source: <repo>/
---
@@ -61,6 +62,18 @@
| v0.36v0.37 | Model routing, personality config, tool card reload, duplicate model fixes | Model routing by provider prefix, personality via config.yaml, tool cards reload on page refresh | 466 |
| v0.38.0v0.38.6 | Model selector, custom endpoints, OLED theme, reasoning display, insights sync | Custom endpoint URL fix, OLED theme, top-level reasoning field fix, message_count sync to state.db | 466 |
| v0.39.0 | Security hardening (Sprint 29) | CSRF, PBKDF2, rate limiting, session ID validation, SSRF, ENV_LOCK, XSS, HMAC, skills traversal, secure cookie, error sanitization, startup warning | 499 |
| v0.40v0.44.2 | Approval card + Lucide icons + sprint auth | Approval prompt surfaced in UI, emoji icons → Lucide SVG, login CSP inline fix, update diagnostics | 579 |
| v0.45v0.46 | Custom endpoints + security + i18n + cancel | Custom endpoint Base URL + API key on profile create, credential redaction (PR #243), Docker UID/GID (PR #237), HTML entity decode + zh/zh-Hant i18n, cancel interrupts agent | 624 |
| v0.47v0.47.1 | Dialogs + session menu + skills + mobile QA + Spanish | Shared app dialogs, session ⋯ menu, /skills command, mobile QA suite, Android Chrome fixes, Spanish locale (@gabogabucho) | 648 |
| v0.48v0.48.2 | Gateway session sync + table formatting + provider warnings | Real-time Telegram/Discord/Slack sessions in sidebar (@bergeouss), inlineMd() in table cells, provider/model mismatch toast | 679 |
| v0.49v0.49.1 | Onboarding wizard + Docker two-container | One-shot bootstrap + guided setup wizard, OpenRouter/Anthropic/OpenAI/Custom provider config, two-container Docker compose, mobile Profiles button | 700 |
| v0.50.0 | v0.50.0 UI overhaul (Sprint 34) | Composer-centric controls, Hermes Control Center modal, workspace panel state machine, collapsible date groups, rAF streaming throttle, context ring indicator (@aronprins) | 742 |
| v0.50.5v0.50.10 | Think-tag edge cases + onboarding hardening + mobile fixes | MiniMax M2.5 leading-whitespace think-tag fix, skip-onboarding env var, OAuth provider path, Docker bridge networks fix, model dropdown dedup, title auto-generation fix, mobile close button | 802 |
| v0.50.11v0.50.12 | Chat table styles + URL autolink + profile env isolation | .msg-body table borders, plain URL auto-linking, profile .env secret isolation on switch (prevents API key leakage across profiles, @Hinotoi-agent) | 815 |
| v0.50.13v0.50.15 | session_search + security sweep + KaTeX math | SessionDB injection for session_search in WebUI (@DelightRun), bandit B310/B324/B110 + QuietHTTPServer (@lawrencel1ng), KaTeX math rendering with fence-before-math fix | 871 |
| v0.50.16v0.50.17 | CSRF reverse proxy + Docker uv pre-install | Scheme-aware CSRF port normalization for non-standard ports (@lx3133584), Docker uv pre-installed at build time as root (fixes air-gapped startup, @mmartial-pattern) | 900 |
| v0.50.18v0.50.19 | Workspace fallback + Unicode filenames | Cascading workspace path recovery (@Jordan-SkyLF), Unicode Content-Disposition headers with RFC 5987 filename* (@shaoxianbilly), silent auth error surfacing, stale model cleanup | 924 |
| v0.50.20v0.50.21 | Silent errors + live model fetching + durable streaming recovery | apperror on empty agent response, /api/models/live endpoint with SSRF guard, live reasoning cards, tool_complete SSE events, SESSION_QUEUES, localStorage reload recovery (@Jordan-SkyLF) | 961 |
---
@@ -68,14 +81,14 @@
| Layer | Location | Status |
|-------|----------|--------|
| Python server | <repo>/server.py (~81 lines) + api/ modules (~3210 lines) | Thin shell + auth middleware + business logic in api/ |
| HTML template | <repo>/static/index.html (~364 lines) | Served from disk |
| CSS | <repo>/static/style.css (~670 lines) | Served from disk, incl. mobile responsive |
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands}.js | 7 modules, ~3610 lines total |
| Python server | <repo>/server.py (~165 lines) + api/ modules (~5000 lines) | Thin shell + QuietHTTPServer + auth middleware + business logic in api/ |
| HTML template | <repo>/static/index.html (~600 lines) | Served from disk |
| CSS | <repo>/static/style.css (~1050 lines) | Served from disk, incl. mobile responsive, KaTeX, table styles |
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands,icons,i18n,login}.js | 10 modules, ~7100 lines total |
| Docker | Dockerfile, docker-compose.yml, .dockerignore | python:3.12-slim, multi-arch (amd64+arm64) |
| CI/CD | .github/workflows/release.yml | Auto-release + GHCR publish on tag push |
| Runtime state | ~/.hermes/webui-mvp/sessions/ | Session JSON files |
| Test server | Port 8788, state dir ~/.hermes/webui-mvp-test/ | Isolated, wiped per run |
| Test server | Port 8788 (conftest.py), port 8789 (browser sanity) | Isolated, wiped per run |
| Production server | Port 8787 | SSH tunnel from Mac |
---

View File

@@ -1,22 +1,28 @@
# Hermes Web UI -- Forward Sprint Plan
> Current state: v0.36 | 433 tests | Daily driver ready
> This document plans the path from here to two targets:
> Current state: v0.50.21 | 961 tests | Full daily driver — CLI parity achieved
>
> Target A: 1:1 feature parity with the Hermes CLI (everything you can do from the
> terminal, you can do from the browser)
> NOTE: Most planned work in this document has now shipped. This file is preserved
> as a historical planning record. Current sprint state and version history live
> in CHANGELOG.md and ROADMAP.md.
>
> Target B: 1:1 parity with Claude's reproducible features (the full Claude
> browser UI experience, minus things only Anthropic can build)
> Target A (CLI parity): ✅ Complete — all core tools, workspace, cron, skills,
> memory, sessions, profiles, model routing, streaming, voice, mobile.
>
> Sprints are ordered by impact. Each builds on the one before.
> Past sprint history lives in CHANGELOG.md.
> Target B (Claude parity): ~90% — thinking display, math rendering (KaTeX),
> tool cards, workspace preview, onboarding, settings panel all done.
> Remaining: full subagent transparency UI, file diff viewer.
>
> Last meaningful update: v0.50.21 (April 13, 2026). See CHANGELOG.md for full history.
---
## Where we are now (v0.36)
## Where we are now (v0.50.21 — updated April 2026)
**CLI parity: ~95% complete.** Core agent loop, all tools visible, workspace
> The sections below describe the state as of v0.36 for historical reference.
> See ROADMAP.md for the current sprint history table (v0.36 → v0.50.21).
**CLI parity: ✅ Complete** as of v0.50.x. Core agent loop, all tools visible, workspace
file ops with tree view and git detection, cron/skills/memory CRUD, session
management, streaming with rAF throttle, cancel, multi-provider models, custom
endpoint discovery, slash commands (help/clear/model/workspace/new/usage/theme/compact),

View File

@@ -1,14 +1,14 @@
# Hermes Web UI: Browser Testing Plan
> This document is for manual browser testing by you or by a Claude browser agent.
> It covers user-facing features of the UI through Sprint 26 (v0.36.2) and later releases.
> It covers user-facing features of the UI through v0.50.21 and later releases.
> Each section is written as a step-by-step test procedure with expected outcomes.
> A browser agent (e.g. Claude with Chrome access) can execute this plan directly.
>
> Prerequisites: SSH tunnel is active on port 8786. Open http://localhost:8786 in browser.
> Server health check: curl http://127.0.0.1:8786/health should return {"status":"ok"}.
> Prerequisites: SSH tunnel is active on port 8787. Open http://localhost:8787 in browser.
> Server health check: curl http://127.0.0.1:8787/health should return {"status":"ok"}.
>
> Automated tests: 700 total (700 passing, 0 skipped, 0 known failures). Includes onboarding coverage for bootstrap/static wizard presence, real provider config persistence (`config.yaml` + `.env`), and the `/api/onboarding/*` backend.
> Automated tests: 1063 total (1063 passing, 0 known failures). Includes onboarding coverage for bootstrap/static wizard presence, real provider config persistence (`config.yaml` + `.env`), the `/api/onboarding/*` backend, and the onboarding skip/existing-config guard.
> Run: `pytest tests/ -v --timeout=60`
---

View File

@@ -6,12 +6,15 @@ or configuring a password in the Settings panel.
import hashlib
import hmac
import http.cookies
import logging
import os
import secrets
import time
from api.config import STATE_DIR, load_settings
logger = logging.getLogger(__name__)
# ── Public paths (no auth required) ─────────────────────────────────────────
PUBLIC_PATHS = frozenset({
'/login', '/health', '/favicon.ico',
@@ -54,7 +57,7 @@ def _signing_key():
if len(raw) >= 32:
return raw[:32]
except Exception:
pass
logger.debug("Failed to read signing key from file, generating new key")
# Generate a new random key
key = secrets.token_bytes(32)
try:
@@ -62,7 +65,7 @@ def _signing_key():
key_file.write_bytes(key)
key_file.chmod(0o600)
except Exception:
pass # key works for this process even if persist fails
logger.debug("Failed to persist signing key, using in-memory key only")
return key

View File

@@ -11,6 +11,7 @@ Discovery order for all paths:
import collections
import json
import logging
import os
import sys
import threading
@@ -48,6 +49,8 @@ SETTINGS_FILE = STATE_DIR / "settings.json"
LAST_WORKSPACE_FILE = STATE_DIR / "last_workspace.txt"
PROJECTS_FILE = STATE_DIR / "projects.json"
logger = logging.getLogger(__name__)
# ── Hermes agent directory discovery ─────────────────────────────────────────
def _discover_agent_dir() -> Path:
@@ -197,7 +200,7 @@ def reload_config() -> None:
if isinstance(loaded, dict):
_cfg_cache.update(loaded)
except Exception:
pass
logger.debug("Failed to load yaml config from %s", config_path)
# Initial load
@@ -206,21 +209,70 @@ cfg = _cfg_cache # alias for backward compat with existing references
# ── Default workspace discovery ───────────────────────────────────────────────
def _workspace_candidates(raw: str | Path | None = None) -> list[Path]:
"""Return ordered candidate workspace paths, de-duplicated."""
candidates: list[Path] = []
def add(candidate: str | Path | None) -> None:
if candidate in (None, ""):
return
try:
path = Path(candidate).expanduser().resolve()
except Exception:
return
if path not in candidates:
candidates.append(path)
add(raw)
if os.getenv("HERMES_WEBUI_DEFAULT_WORKSPACE"):
add(os.getenv("HERMES_WEBUI_DEFAULT_WORKSPACE"))
home_workspace = HOME / "workspace"
home_work = HOME / "work"
if home_workspace.exists():
add(home_workspace)
if home_work.exists():
add(home_work)
add(home_workspace)
add(STATE_DIR / "workspace")
return candidates
def _ensure_workspace_dir(path: Path) -> bool:
"""Best-effort check that a workspace directory exists and is writable."""
try:
path = path.expanduser().resolve()
path.mkdir(parents=True, exist_ok=True)
return path.is_dir() and os.access(path, os.R_OK | os.W_OK | os.X_OK)
except Exception:
return False
def resolve_default_workspace(raw: str | Path | None = None) -> Path:
"""Return the first usable workspace path, creating it when possible."""
for candidate in _workspace_candidates(raw):
if _ensure_workspace_dir(candidate):
return candidate
raise RuntimeError(
"Could not create or access any usable workspace directory. "
"Set HERMES_WEBUI_DEFAULT_WORKSPACE to a writable path."
)
def _discover_default_workspace() -> Path:
"""
Resolve the default workspace in order:
1. HERMES_WEBUI_DEFAULT_WORKSPACE env var
2. ~/workspace (common Hermes convention)
3. STATE_DIR / workspace (isolated fallback)
2. ~/workspace if it already exists
3. ~/work if it already exists
4. ~/workspace (create if needed)
5. STATE_DIR / workspace
"""
if os.getenv("HERMES_WEBUI_DEFAULT_WORKSPACE"):
return Path(os.getenv("HERMES_WEBUI_DEFAULT_WORKSPACE")).expanduser().resolve()
common = HOME / "workspace"
if common.exists():
return common.resolve()
return (STATE_DIR / "workspace").resolve()
return resolve_default_workspace()
DEFAULT_WORKSPACE = _discover_default_workspace()
@@ -354,8 +406,6 @@ CLI_TOOLSETS = get_config().get("platform_toolsets", {}).get("cli", _DEFAULT_TOO
# Hardcoded fallback models (used when no config.yaml or agent is available)
_FALLBACK_MODELS = [
{"provider": "OpenAI", "id": "openai/gpt-5.4-mini", "label": "GPT-5.4 Mini"},
{"provider": "OpenAI", "id": "openai/gpt-4o", "label": "GPT-4o"},
{"provider": "OpenAI", "id": "openai/o3", "label": "o3"},
{"provider": "OpenAI", "id": "openai/o4-mini", "label": "o4-mini"},
{
"provider": "Anthropic",
@@ -398,6 +448,8 @@ _PROVIDER_DISPLAY = {
"huggingface": "HuggingFace",
"alibaba": "Alibaba",
"ollama": "Ollama",
"opencode-zen": "OpenCode Zen",
"opencode-go": "OpenCode Go",
"lmstudio": "LM Studio",
}
@@ -411,12 +463,16 @@ _PROVIDER_MODELS = {
],
"openai": [
{"id": "gpt-5.4-mini", "label": "GPT-5.4 Mini"},
{"id": "gpt-4o", "label": "GPT-4o"},
{"id": "o3", "label": "o3"},
{"id": "o4-mini", "label": "o4-mini"},
],
"openai-codex": [
{"id": "codex-mini-latest", "label": "Codex Mini"},
{"id": "gpt-5.4", "label": "GPT-5.4"},
{"id": "gpt-5.4-mini", "label": "GPT-5.4 Mini"},
{"id": "gpt-5.3-codex", "label": "GPT-5.3 Codex"},
{"id": "gpt-5.2-codex", "label": "GPT-5.2 Codex"},
{"id": "gpt-5.1-codex-max", "label": "GPT-5.1 Codex Max"},
{"id": "gpt-5.1-codex-mini", "label": "GPT-5.1 Codex Mini"},
{"id": "codex-mini-latest", "label": "Codex Mini (latest)"},
],
"google": [
{"id": "gemini-2.5-pro", "label": "Gemini 2.5 Pro"},
@@ -461,6 +517,51 @@ _PROVIDER_MODELS = {
{"id": "claude-sonnet-4.6", "label": "Claude Sonnet 4.6"},
{"id": "gemini-2.5-pro", "label": "Gemini 2.5 Pro"},
],
# OpenCode Zen — curated models via opencode.ai/zen (pay-as-you-go credits)
"opencode-zen": [
{"id": "gpt-5.4-pro", "label": "GPT-5.4 Pro"},
{"id": "gpt-5.4", "label": "GPT-5.4"},
{"id": "gpt-5.4-mini", "label": "GPT-5.4 Mini"},
{"id": "gpt-5.4-nano", "label": "GPT-5.4 Nano"},
{"id": "gpt-5.3-codex", "label": "GPT-5.3 Codex"},
{"id": "gpt-5.3-codex-spark", "label": "GPT-5.3 Codex Spark"},
{"id": "gpt-5.2", "label": "GPT-5.2"},
{"id": "gpt-5.2-codex", "label": "GPT-5.2 Codex"},
{"id": "gpt-5.1", "label": "GPT-5.1"},
{"id": "gpt-5.1-codex", "label": "GPT-5.1 Codex"},
{"id": "gpt-5.1-codex-max", "label": "GPT-5.1 Codex Max"},
{"id": "gpt-5.1-codex-mini", "label": "GPT-5.1 Codex Mini"},
{"id": "gpt-5", "label": "GPT-5"},
{"id": "gpt-5-codex", "label": "GPT-5 Codex"},
{"id": "gpt-5-nano", "label": "GPT-5 Nano"},
{"id": "claude-opus-4-6", "label": "Claude Opus 4.6"},
{"id": "claude-opus-4-5", "label": "Claude Opus 4.5"},
{"id": "claude-opus-4-1", "label": "Claude Opus 4.1"},
{"id": "claude-sonnet-4-6", "label": "Claude Sonnet 4.6"},
{"id": "claude-sonnet-4-5", "label": "Claude Sonnet 4.5"},
{"id": "claude-sonnet-4", "label": "Claude Sonnet 4"},
{"id": "claude-haiku-4-5", "label": "Claude Haiku 4.5"},
{"id": "claude-3-5-haiku", "label": "Claude 3.5 Haiku"},
{"id": "gemini-3.1-pro", "label": "Gemini 3.1 Pro"},
{"id": "gemini-3-flash", "label": "Gemini 3 Flash"},
{"id": "glm-5.1", "label": "GLM-5.1"},
{"id": "glm-5", "label": "GLM-5"},
{"id": "kimi-k2.5", "label": "Kimi K2.5"},
{"id": "minimax-m2.5", "label": "MiniMax M2.5"},
{"id": "minimax-m2.5-free", "label": "MiniMax M2.5 Free"},
{"id": "nemotron-3-super-free", "label": "Nemotron 3 Super Free"},
{"id": "big-pickle", "label": "Big Pickle"},
],
# OpenCode Go — flat-rate models via opencode.ai/go ($10/month)
"opencode-go": [
{"id": "glm-5.1", "label": "GLM-5.1"},
{"id": "glm-5", "label": "GLM-5"},
{"id": "kimi-k2.5", "label": "Kimi K2.5"},
{"id": "mimo-v2-pro", "label": "MiMo V2 Pro"},
{"id": "mimo-v2-omni", "label": "MiMo V2 Omni"},
{"id": "minimax-m2.7", "label": "MiniMax M2.7"},
{"id": "minimax-m2.5", "label": "MiniMax M2.5"},
],
# 'gemini' is the hermes_cli provider ID for Google AI Studio
"gemini": [
{"id": "gemini-2.5-pro", "label": "Gemini 2.5 Pro"},
@@ -601,7 +702,7 @@ def get_available_models() -> dict:
auth_store = _j.loads(auth_store_path.read_text())
active_provider = auth_store.get("active_provider")
except Exception:
pass
logger.debug("Failed to load auth store from %s", auth_store_path)
# 4. Detect available providers.
# Primary: ask hermes-agent's auth layer — the authoritative source. It checks
@@ -629,11 +730,11 @@ def get_available_models() -> dict:
if _src == "gh auth token":
continue
except Exception:
pass
logger.debug("Failed to get key source for provider %s", _p.get("id", "unknown"))
detected_providers.add(_p["id"])
_hermes_auth_used = True
except Exception:
pass
logger.debug("Failed to detect auth providers from hermes")
if not _hermes_auth_used:
# Fallback: scan .env and os.environ for known API key variables
@@ -652,7 +753,7 @@ def get_available_models() -> dict:
k, v = line.split("=", 1)
env_keys[k.strip()] = v.strip().strip('"').strip("'")
except Exception:
pass
logger.debug("Failed to parse hermes env file")
all_env = {**env_keys}
for k in (
"ANTHROPIC_API_KEY",
@@ -662,6 +763,8 @@ def get_available_models() -> dict:
"GLM_API_KEY",
"KIMI_API_KEY",
"DEEPSEEK_API_KEY",
"OPENCODE_ZEN_API_KEY",
"OPENCODE_GO_API_KEY",
):
val = os.getenv(k)
if val:
@@ -682,6 +785,10 @@ def get_available_models() -> dict:
detected_providers.add("minimax")
if all_env.get("DEEPSEEK_API_KEY"):
detected_providers.add("deepseek")
if all_env.get("OPENCODE_ZEN_API_KEY"):
detected_providers.add("opencode-zen")
if all_env.get("OPENCODE_GO_API_KEY"):
detected_providers.add("opencode-go")
# 3. Fetch models from custom endpoint if base_url is configured
auto_detected_models = []
@@ -760,6 +867,9 @@ def get_available_models() -> dict:
parsed_url = urlparse(
endpoint_url if "://" in endpoint_url else f"http://{endpoint_url}"
)
# Validate URL scheme to prevent file:// and other dangerous schemes
if parsed_url.scheme not in ("", "http", "https"):
raise ValueError(f"Invalid URL scheme: {parsed_url.scheme}")
if parsed_url.hostname:
try:
resolved_ips = socket.getaddrinfo(parsed_url.hostname, None)
@@ -791,7 +901,7 @@ def get_available_models() -> dict:
req.add_header("User-Agent", "OpenAI/Python 1.0")
for k, v in headers.items():
req.add_header(k, v)
with urllib.request.urlopen(req, timeout=10) as response:
with urllib.request.urlopen(req, timeout=10) as response: # nosec B310
data = json.loads(response.read().decode("utf-8"))
# Handle both OpenAI-compatible and llama.cpp response formats
@@ -814,7 +924,7 @@ def get_available_models() -> dict:
auto_detected_models.append({"id": model_id, "label": model_name})
detected_providers.add(provider.lower())
except Exception:
pass # custom endpoint unreachable or misconfigured -- fail silently
logger.debug("Custom endpoint unreachable or misconfigured for provider: %s", provider)
# 3b. Include models from custom_providers config entries.
# These are explicitly configured and should always appear even when the
@@ -913,10 +1023,11 @@ def get_available_models() -> dict:
# Ensure the user's configured default_model always appears in the dropdown.
# It may be missing if the model isn't in any hardcoded list (e.g. openrouter/free,
# a custom local model, or any model.default not in _FALLBACK_MODELS).
# Normalize before comparing: strip provider prefix so 'anthropic/claude-opus-4.6'
# matches 'claude-opus-4.6' already in the list and avoids a duplicate entry.
# Normalize before comparing: strip provider prefix and unify separators so
# 'anthropic/claude-opus-4.6' matches 'claude-opus-4.6' and 'claude-sonnet-4-6'
# matches 'claude-sonnet-4.6' (hermes-agent uses hyphens, webui uses dots).
if default_model:
_norm = lambda mid: mid.split("/", 1)[-1] if "/" in mid else mid
_norm = lambda mid: (mid.split("/", 1)[-1] if "/" in mid else mid).replace("-", ".")
all_ids_norm = {_norm(m["id"]) for g in groups for m in g.get("models", [])}
if _norm(default_model) not in all_ids_norm:
# Determine which group to inject into. Compare against the
@@ -1012,6 +1123,7 @@ _SETTINGS_DEFAULTS = {
), # display name for the assistant
"sound_enabled": False, # play notification sound when assistant finishes
"notifications_enabled": False, # browser notification when tab is in background
"bubble_layout": False, # right-aligned user / left-aligned assistant chat bubbles
"password_hash": None, # PBKDF2-HMAC-SHA256 hash; None = auth disabled
}
@@ -1025,7 +1137,7 @@ def load_settings() -> dict:
if isinstance(stored, dict):
settings.update(stored)
except Exception:
pass
logger.debug("Failed to load settings from %s", SETTINGS_FILE)
return settings
@@ -1041,6 +1153,7 @@ _SETTINGS_BOOL_KEYS = {
"check_for_updates",
"sound_enabled",
"notifications_enabled",
"bubble_layout",
}
# Language codes are validated as short alphanumeric BCP-47-like tags (e.g. 'en', 'zh', 'fr')
_SETTINGS_LANG_RE = __import__("re").compile(r"^[a-zA-Z]{2,10}(-[a-zA-Z0-9]{2,8})?$")
@@ -1073,6 +1186,10 @@ def save_settings(settings: dict) -> dict:
if k in _SETTINGS_BOOL_KEYS:
v = bool(v)
current[k] = v
current["default_workspace"] = str(
resolve_default_workspace(current.get("default_workspace"))
)
SETTINGS_FILE.write_text(
json.dumps(current, ensure_ascii=False, indent=2),
encoding="utf-8",
@@ -1082,7 +1199,7 @@ def save_settings(settings: dict) -> dict:
if "default_model" in current:
DEFAULT_MODEL = current["default_model"]
if "default_workspace" in current:
DEFAULT_WORKSPACE = Path(current["default_workspace"]).expanduser().resolve()
DEFAULT_WORKSPACE = resolve_default_workspace(current["default_workspace"])
return current
@@ -1091,10 +1208,18 @@ _startup_settings = load_settings()
if SETTINGS_FILE.exists():
if _startup_settings.get("default_model"):
DEFAULT_MODEL = _startup_settings["default_model"]
if _startup_settings.get("default_workspace"):
DEFAULT_WORKSPACE = (
Path(_startup_settings["default_workspace"]).expanduser().resolve()
)
DEFAULT_WORKSPACE = resolve_default_workspace(
_startup_settings.get("default_workspace")
)
if _startup_settings.get("default_workspace") != str(DEFAULT_WORKSPACE):
_startup_settings["default_workspace"] = str(DEFAULT_WORKSPACE)
try:
SETTINGS_FILE.write_text(
json.dumps(_startup_settings, ensure_ascii=False, indent=2),
encoding="utf-8",
)
except Exception:
pass
# ── SESSIONS in-memory cache (LRU OrderedDict) ───────────────────────────────
SESSIONS: collections.OrderedDict = collections.OrderedDict()

View File

@@ -10,6 +10,7 @@ requiring any changes to hermes-agent.
"""
import hashlib
import json
import logging
import os
import queue
import sqlite3
@@ -19,6 +20,8 @@ from pathlib import Path
from api.config import HOME
logger = logging.getLogger(__name__)
# ── State hash tracking ─────────────────────────────────────────────────────
@@ -28,7 +31,7 @@ def _snapshot_hash(sessions: list) -> str:
f"{s['session_id']}:{s.get('updated_at', 0)}:{s.get('message_count', 0)}"
for s in sorted(sessions, key=lambda x: x['session_id'])
)
return hashlib.md5(key.encode()).hexdigest()
return hashlib.md5(key.encode(), usedforsecurity=False).hexdigest()
# ── DB resolution (shared pattern with state_sync.py) ──────────────────────
@@ -124,7 +127,7 @@ class GatewayWatcher:
try:
q.put(None) # sentinel
except Exception:
pass
logger.debug("Failed to send sentinel to subscriber")
if self._thread:
self._thread.join(timeout=3)
self._thread = None
@@ -172,7 +175,7 @@ class GatewayWatcher:
try:
q.put_nowait(None)
except Exception:
pass
logger.debug("Failed to send sentinel to dead subscriber")
def _poll_loop(self):
"""Main polling loop. Runs in a daemon thread."""
@@ -186,7 +189,7 @@ class GatewayWatcher:
self._last_sessions = sessions
self._notify_subscribers(sessions)
except Exception:
pass # never crash the watcher
logger.debug("Error in gateway watcher poll loop", exc_info=True)
# Sleep in small increments so we can stop promptly
for _ in range(self.POLL_INTERVAL * 10):

View File

@@ -50,7 +50,7 @@ def _security_headers(handler):
)
handler.send_header(
'Permissions-Policy',
'camera=(), microphone=(), geolocation=()'
'camera=(), microphone=(self), geolocation=()'
)

View File

@@ -3,6 +3,7 @@ Hermes Web UI -- Session model and in-memory session store.
"""
import collections
import json
import logging
import time
import uuid
from pathlib import Path
@@ -14,6 +15,8 @@ from api.config import (
)
from api.workspace import get_last_workspace
logger = logging.getLogger(__name__)
def _write_session_index():
"""Rebuild the session index file for O(1) future reads."""
@@ -24,7 +27,7 @@ def _write_session_index():
s = Session.load(p.stem)
if s: entries.append(s.compact())
except Exception:
pass
logger.debug("Failed to load session from %s", p)
with LOCK:
for s in SESSIONS.values():
if not any(e['session_id'] == s.session_id for e in entries):
@@ -41,6 +44,10 @@ class Session:
project_id: str=None, profile=None,
input_tokens: int=0, output_tokens: int=0, estimated_cost=None,
personality=None,
active_stream_id: str=None,
pending_user_message: str=None,
pending_attachments=None,
pending_started_at=None,
**kwargs):
self.session_id = session_id or uuid.uuid4().hex[:12]
self.title = title
@@ -58,13 +65,18 @@ class Session:
self.output_tokens = output_tokens or 0
self.estimated_cost = estimated_cost
self.personality = personality
self.active_stream_id = active_stream_id
self.pending_user_message = pending_user_message
self.pending_attachments = pending_attachments or []
self.pending_started_at = pending_started_at
@property
def path(self):
return SESSION_DIR / f'{self.session_id}.json'
def save(self) -> None:
self.updated_at = time.time()
def save(self, touch_updated_at: bool = True) -> None:
if touch_updated_at:
self.updated_at = time.time()
self.path.write_text(
json.dumps(self.__dict__, ensure_ascii=False, indent=2),
encoding='utf-8',
@@ -151,7 +163,7 @@ def all_sessions():
s['profile'] = 'default'
return result
except Exception:
pass # fall through to full scan
logger.debug("Failed to load session index, falling back to full scan")
# Full scan fallback
out = []
for p in SESSION_DIR.glob('*.json'):
@@ -160,7 +172,7 @@ def all_sessions():
s = Session.load(p.stem)
if s: out.append(s)
except Exception:
pass
logger.debug("Failed to load session from %s", p)
for s in SESSIONS.values():
if all(s.session_id != x.session_id for x in out): out.append(s)
out.sort(key=lambda s: (getattr(s, 'pinned', False), s.updated_at), reverse=True)
@@ -200,7 +212,15 @@ def save_projects(projects) -> None:
PROJECTS_FILE.write_text(json.dumps(projects, ensure_ascii=False, indent=2), encoding='utf-8')
def import_cli_session(session_id: str, title: str, messages, model: str='unknown', profile=None):
def import_cli_session(
session_id: str,
title: str,
messages,
model: str='unknown',
profile=None,
created_at=None,
updated_at=None,
):
"""Create a new WebUI session populated with CLI messages.
Returns the Session object.
"""
@@ -211,8 +231,10 @@ def import_cli_session(session_id: str, title: str, messages, model: str='unknow
model=model,
messages=messages,
profile=profile,
created_at=created_at,
updated_at=updated_at,
)
s.save()
s.save(touch_updated_at=False)
return s

View File

@@ -2,6 +2,7 @@
from __future__ import annotations
import logging
import os
from pathlib import Path
from urllib.parse import urlparse
@@ -24,6 +25,8 @@ from api.config import (
)
from api.workspace import get_last_workspace, load_workspaces
logger = logging.getLogger(__name__)
_SUPPORTED_PROVIDER_SETUPS = {
"openrouter": {
@@ -234,7 +237,7 @@ def _provider_oauth_authenticated(provider: str, hermes_home: "Path") -> bool:
if isinstance(status, dict) and status.get("logged_in"):
return True
except Exception:
pass
logger.debug("Failed to get auth status for provider %s", provider)
# Fallback: parse auth.json ourselves for known OAuth provider IDs.
# Covers deployments where hermes_cli is installed but the import above
@@ -362,13 +365,23 @@ def _build_setup_catalog(cfg: dict) -> dict:
}
)
# Flag whether the currently-configured provider is OAuth-based (not in the
# API-key flow). The frontend uses this to show a confirmation card instead
# of a key input when the user has already authenticated via 'hermes auth'.
current_is_oauth = current_provider not in _SUPPORTED_PROVIDER_SETUPS and bool(
current_provider
)
return {
"providers": providers,
"unsupported_note": _UNSUPPORTED_PROVIDER_NOTE,
"current_is_oauth": current_is_oauth,
"current": {
"provider": current_provider,
"model": current_model
or _SUPPORTED_PROVIDER_SETUPS[current_provider]["default_model"],
or _SUPPORTED_PROVIDER_SETUPS.get(current_provider, {}).get(
"default_model", ""
),
"base_url": current_base_url,
},
}
@@ -383,8 +396,23 @@ def get_onboarding_status() -> dict:
last_workspace = get_last_workspace()
available_models = get_available_models()
# HERMES_WEBUI_SKIP_ONBOARDING=1 lets hosting providers (e.g. Agent37) ship
# a pre-configured instance without the wizard blocking the first load.
# Only takes effect when the system is actually chat_ready — a misconfigured
# deployment still shows the wizard so the user can fix it.
skip_env = os.environ.get("HERMES_WEBUI_SKIP_ONBOARDING", "").strip()
skip_requested = skip_env in {"1", "true", "yes"}
auto_completed = skip_requested and bool(runtime.get("chat_ready"))
# Auto-complete for existing Hermes users: if config.yaml already exists
# AND the system is chat_ready, treat onboarding as done. These users
# configured Hermes via the CLI before the Web UI existed; they must never
# be shown the first-run wizard — it would silently overwrite their config.
config_exists = Path(_get_config_path()).exists()
config_auto_completed = config_exists and bool(runtime.get("chat_ready"))
return {
"completed": bool(settings.get("onboarding_completed")),
"completed": bool(settings.get("onboarding_completed")) or auto_completed or config_auto_completed,
"settings": {
"default_model": settings.get("default_model") or DEFAULT_MODEL,
"default_workspace": settings.get("default_workspace")
@@ -417,7 +445,11 @@ def apply_onboarding_setup(body: dict) -> dict:
base_url = _normalize_base_url(str(body.get("base_url") or ""))
if provider not in _SUPPORTED_PROVIDER_SETUPS:
raise ValueError("Unsupported provider for WebUI onboarding.")
# Unsupported providers (openai-codex, copilot, nous, etc.) are already
# configured via the CLI. Just mark onboarding as complete and let the
# user through — the agent is already set up, no further setup needed.
save_settings({"onboarding_completed": True})
return get_onboarding_status()
if not model:
raise ValueError("model is required")
@@ -429,7 +461,21 @@ def apply_onboarding_setup(body: dict) -> dict:
if parsed.scheme not in {"http", "https"}:
raise ValueError("base_url must start with http:// or https://")
cfg = _load_yaml_config(_get_config_path())
config_path = _get_config_path()
# Guard: if config.yaml already exists and the caller did not explicitly
# acknowledge the overwrite, refuse to proceed. The frontend must pass
# confirm_overwrite=True after showing the user a confirmation step.
if Path(config_path).exists() and not body.get("confirm_overwrite"):
return {
"error": "config_exists",
"message": (
"Hermes is already configured (config.yaml exists). "
"Pass confirm_overwrite=true to overwrite it."
),
"requires_confirm": True,
}
cfg = _load_yaml_config(config_path)
env_path = _get_active_hermes_home() / ".env"
env_values = _load_env_file(env_path)
@@ -453,17 +499,31 @@ def apply_onboarding_setup(body: dict) -> dict:
model_cfg.pop("base_url", None)
cfg["model"] = model_cfg
_save_yaml_config(_get_config_path(), cfg)
_save_yaml_config(config_path, cfg)
if api_key:
_write_env_file(env_path, {provider_meta["env_var"]: api_key})
# Reload the hermes_cli provider/config cache so the next streaming call
# picks up the new key without requiring a server restart.
try:
from api.profiles import _reload_dotenv
_reload_dotenv(_get_active_hermes_home())
except Exception:
pass
logger.debug("Failed to reload dotenv")
# Belt-and-braces: set directly on os.environ AFTER _reload_dotenv so the
# value survives even if _reload_dotenv cleared it (e.g. when _write_env_file
# wrote to disk but the profile isolation tracking hasn't seen it yet).
if api_key:
os.environ[provider_meta["env_var"]] = api_key
try:
# hermes_cli may cache config at import time; ask it to reload if possible.
from hermes_cli.config import reload as _cli_reload
_cli_reload()
except Exception:
logger.debug("Failed to reload hermes_cli config")
reload_config()
return get_onboarding_status()

View File

@@ -9,12 +9,15 @@ cached paths in hermes-agent modules (skills_tool, cron/jobs) that snapshot
HERMES_HOME at import time.
"""
import json
import logging
import os
import re
import shutil
import threading
from pathlib import Path
logger = logging.getLogger(__name__)
# ── Constants (match hermes_cli.profiles upstream) ─────────────────────────
_PROFILE_ID_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{0,63}$')
_PROFILE_DIRS = [
@@ -26,6 +29,7 @@ _CLONE_CONFIG_FILES = ['config.yaml', '.env', 'SOUL.md']
# ── Module state ────────────────────────────────────────────────────────────
_active_profile = 'default'
_profile_lock = threading.Lock()
_loaded_profile_env_keys: set[str] = set()
def _resolve_base_hermes_home() -> Path:
"""Return the BASE ~/.hermes directory — the root that contains profiles/.
@@ -75,7 +79,7 @@ def _read_active_profile_file() -> str:
if name:
return name
except Exception:
pass
logger.debug("Failed to read active profile file")
return 'default'
@@ -106,7 +110,7 @@ def _set_hermes_home(home: Path):
_sk.HERMES_HOME = home
_sk.SKILLS_DIR = home / 'skills'
except (ImportError, AttributeError):
pass
logger.debug("Failed to patch skills_tool module")
# Patch cron/jobs module-level cache
try:
@@ -116,15 +120,28 @@ def _set_hermes_home(home: Path):
_cj.JOBS_FILE = _cj.CRON_DIR / 'jobs.json'
_cj.OUTPUT_DIR = _cj.CRON_DIR / 'output'
except (ImportError, AttributeError):
pass
logger.debug("Failed to patch cron.jobs module")
def _reload_dotenv(home: Path):
"""Load .env from the profile dir into os.environ (additive)."""
"""Load .env from the profile dir into os.environ with profile isolation.
Clears env vars that were loaded from the previously active profile before
applying the current profile's .env. This prevents API keys and other
profile-scoped secrets from leaking across profile switches.
"""
global _loaded_profile_env_keys
# Remove keys loaded from the previous profile first.
for key in list(_loaded_profile_env_keys):
os.environ.pop(key, None)
_loaded_profile_env_keys = set()
env_path = home / '.env'
if not env_path.exists():
return
try:
loaded_keys: set[str] = set()
for line in env_path.read_text().splitlines():
line = line.strip()
if line and not line.startswith('#') and '=' in line:
@@ -133,8 +150,11 @@ def _reload_dotenv(home: Path):
v = v.strip().strip('"').strip("'")
if k and v:
os.environ[k] = v
loaded_keys.add(k)
_loaded_profile_env_keys = loaded_keys
except Exception:
pass
_loaded_profile_env_keys = set()
logger.debug("Failed to reload dotenv from %s", env_path)
def init_profile_state() -> None:
@@ -176,7 +196,7 @@ def switch_profile(name: str) -> dict:
if name == 'default':
home = _DEFAULT_HERMES_HOME
else:
home = _DEFAULT_HERMES_HOME / 'profiles' / name
home = _resolve_named_profile_home(name)
if not home.is_dir():
raise ValueError(f"Profile '{name}' does not exist.")
@@ -190,7 +210,7 @@ def switch_profile(name: str) -> dict:
ap_file = _DEFAULT_HERMES_HOME / 'active_profile'
ap_file.write_text(name if name != 'default' else '')
except Exception:
pass
logger.debug("Failed to write active profile file")
# Reload config.yaml from the new profile
reload_config()
@@ -267,6 +287,24 @@ def _validate_profile_name(name: str):
)
def _profiles_root() -> Path:
"""Return the canonical root that contains named profiles."""
return (_DEFAULT_HERMES_HOME / 'profiles').resolve()
def _resolve_named_profile_home(name: str) -> Path:
"""Resolve a named profile to a directory under the profiles root.
Validates *name* as a logical profile identifier first, then resolves the
final filesystem path and enforces containment under ~/.hermes/profiles.
"""
_validate_profile_name(name)
profiles_root = _profiles_root()
candidate = (profiles_root / name).resolve()
candidate.relative_to(profiles_root)
return candidate
def _create_profile_fallback(name: str, clone_from: str = None,
clone_config: bool = False) -> Path:
"""Create a profile directory without hermes_cli (Docker/standalone fallback)."""
@@ -310,7 +348,7 @@ def _write_endpoint_to_config(profile_dir: Path, base_url: str = None, api_key:
if isinstance(loaded, dict):
cfg = loaded
except Exception:
pass
logger.debug("Failed to load config from %s", config_path)
model_section = cfg.get('model', {})
if not isinstance(model_section, dict):
model_section = {}
@@ -355,7 +393,7 @@ def create_profile_api(name: str, clone_from: str = None,
try:
profile_path = Path(p.get('path') or profile_path)
except Exception:
pass
logger.debug("Failed to parse profile path")
break
profile_path.mkdir(parents=True, exist_ok=True)
@@ -385,6 +423,7 @@ def delete_profile_api(name: str) -> dict:
"""Delete a profile. Switches to default first if it's the active one."""
if name == 'default':
raise ValueError("Cannot delete the default profile.")
_validate_profile_name(name)
# If deleting the active profile, switch to default first
if _active_profile == name:
@@ -402,7 +441,7 @@ def delete_profile_api(name: str) -> dict:
except ImportError:
# Manual fallback: just remove the directory
import shutil
profile_dir = _DEFAULT_HERMES_HOME / 'profiles' / name
profile_dir = _resolve_named_profile_home(name)
if profile_dir.is_dir():
shutil.rmtree(str(profile_dir))
else:

View File

@@ -5,6 +5,7 @@ Extracted from server.py (Sprint 11) so server.py is a thin shell.
import html as _html
import json
import logging
import os
import queue
import sys
@@ -14,6 +15,8 @@ import uuid
from pathlib import Path
from urllib.parse import parse_qs
logger = logging.getLogger(__name__)
from api.config import (
STATE_DIR,
SESSION_DIR,
@@ -55,6 +58,68 @@ from api.helpers import (
import re as _re
def _normalize_host_port(value: str) -> tuple[str, str | None]:
"""Split a host or host:port string into (hostname, port|None).
Handles IPv6 bracket notation, e.g. [::1]:8080."""
value = value.strip().lower()
if not value:
return '', None
if value.startswith('['):
end = value.find(']')
if end != -1:
host = value[1:end]
rest = value[end + 1 :]
if rest.startswith(':') and rest[1:].isdigit():
return host, rest[1:]
return host, None
if value.count(':') == 1:
host, port = value.rsplit(':', 1)
if port.isdigit():
return host, port
return value, None
def _ports_match(origin_scheme: str, origin_port: str | None, allowed_port: str | None) -> bool:
"""Return True when two ports should be considered equivalent, scheme-aware.
Treats an absent port as the scheme default: port 80 for http, port 443 for https.
Port 80 is NOT treated as equivalent to 443 (different protocols = different origins).
"""
if origin_port == allowed_port:
return True
# Determine the default port for the origin's scheme
default = '443' if origin_scheme == 'https' else '80'
if not origin_port and allowed_port == default:
return True
if not allowed_port and origin_port == default:
return True
return False
def _allowed_public_origins() -> set[str]:
"""Parse HERMES_WEBUI_ALLOWED_ORIGINS env var (comma-separated) into a set.
Each entry must include the scheme, e.g. https://myapp.example.com:8000.
Entries without a scheme are silently skipped and a warning is printed.
"""
raw = os.getenv('HERMES_WEBUI_ALLOWED_ORIGINS', '')
result = set()
for value in raw.split(','):
value = value.strip().rstrip('/').lower()
if not value:
continue
if not (value.startswith('http://') or value.startswith('https://')):
import sys
print(
f"[webui] WARNING: HERMES_WEBUI_ALLOWED_ORIGINS entry {value!r} is missing "
f"the scheme (expected https://hostname or http://hostname). Entry ignored.",
flush=True, file=sys.stderr,
)
continue
result.add(value)
return result
def _check_csrf(handler) -> bool:
"""Reject cross-origin POST requests. Returns True if OK."""
origin = handler.headers.get("Origin", "")
@@ -68,10 +133,16 @@ def _check_csrf(handler) -> bool:
if not m:
return False
origin_host = m.group(1)
origin_scheme = m.group(0).split('://')[0].lower() # 'http' or 'https'
origin_name, origin_port = _normalize_host_port(origin_host)
# Check against explicitly allowed public origins (env var)
origin_value = m.group(0).rstrip('/').lower()
if origin_value in _allowed_public_origins():
return True
# Allow same-origin: check Host, X-Forwarded-Host (reverse proxy), and
# X-Real-Host against the origin. Reverse proxies (Caddy, nginx) set
# X-Forwarded-Host to the client's original Host header.
allowed_hosts = {
allowed_hosts = [
h.strip()
for h in [
host,
@@ -79,9 +150,11 @@ def _check_csrf(handler) -> bool:
handler.headers.get("X-Real-Host", ""),
]
if h.strip()
}
if origin_host in allowed_hosts:
return True
]
for allowed in allowed_hosts:
allowed_name, allowed_port = _normalize_host_port(allowed)
if origin_name == allowed_name and _ports_match(origin_scheme, origin_port, allowed_port):
return True
return False
@@ -107,8 +180,9 @@ from api.workspace import (
list_dir,
read_file_content,
safe_resolve_ws,
resolve_trusted_workspace,
)
from api.upload import handle_upload
from api.upload import handle_upload, handle_transcribe
from api.streaming import _sse, _run_agent_streaming, cancel_stream
from api.onboarding import (
apply_onboarding_setup,
@@ -268,6 +342,9 @@ def handle_get(handler, parsed) -> bool:
if parsed.path == "/api/models":
return j(handler, get_available_models())
if parsed.path == "/api/models/live":
return _handle_live_models(handler, parsed)
if parsed.path == "/api/settings":
settings = load_settings()
# Never expose the stored password hash to clients
@@ -289,6 +366,10 @@ def handle_get(handler, parsed) -> bool:
raw = s.compact() | {
"messages": s.messages,
"tool_calls": getattr(s, "tool_calls", []),
"active_stream_id": getattr(s, "active_stream_id", None),
"pending_user_message": getattr(s, "pending_user_message", None),
"pending_attachments": getattr(s, "pending_attachments", []),
"pending_started_at": getattr(s, "pending_started_at", None),
}
return j(handler, {"session": redact_session_data(raw)})
except KeyError:
@@ -330,7 +411,13 @@ def handle_get(handler, parsed) -> bool:
deduped_cli = []
merged = webui_sessions + deduped_cli
merged.sort(key=lambda s: s.get("updated_at", 0) or 0, reverse=True)
return j(handler, {"sessions": merged, "cli_count": len(deduped_cli)})
safe_merged = []
for s in merged:
item = dict(s)
if isinstance(item.get("title"), str):
item["title"] = _redact_text(item["title"])
safe_merged.append(item)
return j(handler, {"sessions": safe_merged, "cli_count": len(deduped_cli)})
if parsed.path == "/api/projects":
return j(handler, {"projects": load_projects()})
@@ -546,10 +633,17 @@ def handle_post(handler, parsed) -> bool:
if parsed.path == "/api/upload":
return handle_upload(handler)
if parsed.path == "/api/transcribe":
return handle_transcribe(handler)
body = read_body(handler)
if parsed.path == "/api/session/new":
s = new_session(workspace=body.get("workspace"), model=body.get("model"))
try:
workspace = str(resolve_trusted_workspace(body.get("workspace"))) if body.get("workspace") else None
except ValueError as e:
return bad(handler, str(e))
s = new_session(workspace=workspace, model=body.get("model"))
return j(handler, {"session": s.compact() | {"messages": s.messages}})
if parsed.path == "/api/sessions/cleanup":
@@ -624,7 +718,10 @@ def handle_post(handler, parsed) -> bool:
s = get_session(body["session_id"])
except KeyError:
return bad(handler, "Session not found", 404)
new_ws = str(Path(body.get("workspace", s.workspace)).expanduser().resolve())
try:
new_ws = str(resolve_trusted_workspace(body.get("workspace", s.workspace)))
except ValueError as e:
return bad(handler, str(e))
s.workspace = new_ws
s.model = body.get("model", s.model)
s.save()
@@ -635,25 +732,31 @@ def handle_post(handler, parsed) -> bool:
sid = body.get("session_id", "")
if not sid:
return bad(handler, "session_id is required")
if not all(c in '0123456789abcdefghijklmnopqrstuvwxyz_' for c in sid):
return bad(handler, "Invalid session_id", 400)
# Delete from WebUI session store
with LOCK:
SESSIONS.pop(sid, None)
p = SESSION_DIR / f"{sid}.json"
try:
p = (SESSION_DIR / f"{sid}.json").resolve()
p.relative_to(SESSION_DIR.resolve())
except Exception:
return bad(handler, "Invalid session_id", 400)
try:
p.unlink(missing_ok=True)
except Exception:
pass
logger.debug("Failed to unlink session file %s", p)
try:
SESSION_INDEX_FILE.unlink(missing_ok=True)
except Exception:
pass
logger.debug("Failed to unlink session index")
# Also delete from CLI state.db (for CLI sessions shown in sidebar)
try:
from api.models import delete_cli_session
delete_cli_session(sid)
except Exception:
pass
logger.debug("Failed to delete CLI session %s", sid)
return j(handler, {"ok": True})
if parsed.path == "/api/session/clear":
@@ -761,8 +864,10 @@ def handle_post(handler, parsed) -> bool:
if not name:
return bad(handler, "name is required")
try:
from api.profiles import switch_profile
from api.profiles import switch_profile, _validate_profile_name
if name != 'default':
_validate_profile_name(name)
result = switch_profile(name)
return j(handler, result)
except (ValueError, FileNotFoundError) as e:
@@ -809,8 +914,9 @@ def handle_post(handler, parsed) -> bool:
if not name:
return bad(handler, "name is required")
try:
from api.profiles import delete_profile_api
from api.profiles import delete_profile_api, _validate_profile_name
_validate_profile_name(name)
result = delete_profile_api(name)
return j(handler, result)
except (ValueError, FileNotFoundError) as e:
@@ -827,10 +933,29 @@ def handle_post(handler, parsed) -> bool:
return j(handler, saved)
if parsed.path == "/api/onboarding/setup":
# Writing API keys to disk - restrict to loopback unless auth is active
# Writing API keys to disk - restrict to local/private networks unless auth is active.
# In Docker, requests arrive from the bridge network (172.x.x.x), not 127.0.0.1,
# even when the user accesses via localhost:8787 on the host.
# Behind a reverse proxy (nginx/Caddy/Traefik) or SSH tunnel, X-Forwarded-For
# carries the real origin IP — read it first before falling back to the raw socket addr.
# HERMES_WEBUI_ONBOARDING_OPEN=1 lets operators on remote servers explicitly bypass
# the check when they control network access themselves (e.g. firewall + VPN).
from api.auth import is_auth_enabled
if not is_auth_enabled() and handler.client_address[0] != "127.0.0.1":
return bad(handler, "Onboarding setup is only available from localhost when auth is not enabled.", 403)
import os as _os
if not is_auth_enabled() and not _os.getenv("HERMES_WEBUI_ONBOARDING_OPEN"):
import ipaddress
try:
# Prefer forwarded headers set by reverse proxies
_xff = handler.headers.get("X-Forwarded-For", "").split(",")[0].strip()
_xri = handler.headers.get("X-Real-IP", "").strip()
_raw = handler.client_address[0]
_ip_str = _xff or _xri or _raw
addr = ipaddress.ip_address(_ip_str)
is_local = addr.is_loopback or addr.is_private
except ValueError:
is_local = False
if not is_local:
return bad(handler, "Onboarding setup is only available from local networks when auth is not enabled. To bypass this on a remote server, set HERMES_WEBUI_ONBOARDING_OPEN=1.", 403)
try:
return j(handler, apply_onboarding_setup(body))
except ValueError as e:
@@ -954,9 +1079,9 @@ def handle_post(handler, parsed) -> bool:
s.project_id = None
s.save()
except Exception:
pass
logger.debug("Failed to update session %s", entry.get("session_id"))
except Exception:
pass
logger.debug("Failed to load session index for project unlink")
return j(handler, {"ok": True})
# ── Session import from JSON (POST) ──
@@ -1083,12 +1208,21 @@ def _handle_sessions_search(handler, parsed):
content_search = qs.get("content", ["1"])[0] == "1"
depth = int(qs.get("depth", ["5"])[0])
if not q:
return j(handler, {"sessions": all_sessions()})
safe_sessions = []
for s in all_sessions():
item = dict(s)
if isinstance(item.get("title"), str):
item["title"] = _redact_text(item["title"])
safe_sessions.append(item)
return j(handler, {"sessions": safe_sessions})
results = []
for s in all_sessions():
title_match = q in (s.get("title") or "").lower()
if title_match:
results.append(dict(s, match_type="title"))
item = dict(s, match_type="title")
if isinstance(item.get("title"), str):
item["title"] = _redact_text(item["title"])
results.append(item)
continue
if content_search:
try:
@@ -1103,7 +1237,10 @@ def _handle_sessions_search(handler, parsed):
if isinstance(p, dict) and p.get("type") == "text"
)
if q in str(c).lower():
results.append(dict(s, match_type="content"))
item = dict(s, match_type="content")
if isinstance(item.get("title"), str):
item["title"] = _redact_text(item["title"])
results.append(item)
break
except (KeyError, Exception):
pass
@@ -1216,6 +1353,29 @@ def _handle_gateway_sse_stream(handler):
return True
def _content_disposition_value(disposition: str, filename: str) -> str:
"""Build a latin-1-safe Content-Disposition value with RFC 5987 filename*."""
import urllib.parse as _up
safe_name = Path(filename).name.replace("\r", "").replace("\n", "")
ascii_fallback = "".join(
ch if 32 <= ord(ch) < 127 and ch not in {'"', '\\'} else "_"
for ch in safe_name
).strip(" .")
if not ascii_fallback:
suffix = Path(safe_name).suffix
ascii_suffix = "".join(
ch if 32 <= ord(ch) < 127 and ch not in {'"', '\\'} else "_"
for ch in suffix
)
ascii_fallback = f"download{ascii_suffix}" if ascii_suffix else "download"
quoted_name = _up.quote(safe_name, safe="")
return (
f'{disposition}; filename="{ascii_fallback}"; '
f"filename*=UTF-8''{quoted_name}"
)
def _handle_file_raw(handler, parsed):
qs = parse_qs(parsed.query)
sid = qs.get("session_id", [""])[0]
@@ -1233,9 +1393,6 @@ def _handle_file_raw(handler, parsed):
ext = target.suffix.lower()
mime = MIME_MAP.get(ext, "application/octet-stream")
raw_bytes = target.read_bytes()
import urllib.parse as _up
safe_name = _up.quote(target.name, safe="")
handler.send_response(200)
handler.send_header("Content-Type", mime)
handler.send_header("Content-Length", str(len(raw_bytes)))
@@ -1245,12 +1402,12 @@ def _handle_file_raw(handler, parsed):
if force_download or mime in dangerous_types:
handler.send_header(
"Content-Disposition",
f"attachment; filename=\"{target.name}\"; filename*=UTF-8''{safe_name}",
_content_disposition_value("attachment", target.name),
)
else:
handler.send_header(
"Content-Disposition",
f"inline; filename=\"{target.name}\"; filename*=UTF-8''{safe_name}",
_content_disposition_value("inline", target.name),
)
handler.end_headers()
handler.wfile.write(raw_bytes)
@@ -1304,6 +1461,91 @@ def _handle_approval_inject(handler, parsed):
return j(handler, {"error": "session_id required"}, status=400)
def _handle_live_models(handler, parsed):
"""Return the live model list for a provider.
Delegates to the agent's provider_model_ids() which handles:
- OpenRouter: live fetch from /api/v1/models
- Anthropic: live fetch from /v1/models (API key or OAuth token)
- Copilot: live fetch from api.githubcopilot.com/models with correct headers
- openai-codex: Codex OAuth endpoint + local ~/.codex/ cache fallback
- Nous: live fetch from inference-api.nousresearch.com/v1/models
- DeepSeek, kimi-coding, opencode-zen/go, custom: generic OpenAI-compat /v1/models
- ZAI, MiniMax, Google/Gemini: fall back to static list (non-standard endpoints)
- All others: static _PROVIDER_MODELS fallback
The agent already maintains all provider-specific auth and endpoint logic
in one place; the WebUI inherits it rather than duplicating it.
Query params:
provider (optional) — provider ID; defaults to active profile provider
"""
qs = parse_qs(parsed.query)
provider = (qs.get("provider", [""])[0] or "").lower().strip()
try:
from api.config import get_config as _gc
cfg = _gc()
if not provider:
provider = cfg.get("model", {}).get("provider") or ""
if not provider:
return j(handler, {"error": "no_provider", "models": []})
# Delegate to the agent's live-fetch + fallback resolver.
# provider_model_ids() tries live endpoints first and falls back to
# the static _PROVIDER_MODELS list — it never raises.
try:
import sys as _sys
import os as _os
_agent_dir = _os.path.join(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))),
"..", "..", ".hermes", "hermes-agent")
_agent_dir = _os.path.normpath(_agent_dir)
if _agent_dir not in _sys.path:
_sys.path.insert(0, _agent_dir)
from hermes_cli.models import provider_model_ids as _pmi
ids = _pmi(provider)
except Exception as _import_err:
logger.debug("provider_model_ids import failed for %s: %s", provider, _import_err)
# Last resort: return the WebUI's own static catalog
from api.config import _PROVIDER_MODELS as _pm
ids = [m["id"] for m in _pm.get(provider, [])]
if not ids:
return j(handler, {"provider": provider, "models": [], "count": 0})
# Normalise to {id, label} — provider_model_ids() returns plain string IDs
def _make_label(mid):
"""Best-effort human label from a model ID string."""
# Preserve slashes for router IDs like "anthropic/claude-sonnet-4.6"
display = mid.split("/")[-1] if "/" in mid else mid
parts = display.split("-")
result = []
for p in parts:
pl = p.lower()
if pl == "gpt":
result.append("GPT")
elif pl in ("claude", "gemini", "gemma", "llama", "mistral",
"qwen", "deepseek", "grok", "kimi", "glm"):
result.append(p.capitalize())
elif p[:1].isdigit():
result.append(p) # version numbers: 5.4, 3.5, 4.6 — unchanged
else:
result.append(p.capitalize())
label = " ".join(result)
# Restore well-known uppercase tokens that title-casing breaks
for orig in ("GPT", "GLM", "API", "AI", "XL", "MoE"):
label = label.replace(orig.title(), orig)
return label
models_out = [{"id": mid, "label": _make_label(mid)} for mid in ids if mid]
return j(handler, {"provider": provider, "models": models_out,
"count": len(models_out)})
except Exception as _e:
logger.debug("_handle_live_models failed for %s: %s", provider, _e)
return j(handler, {"error": str(_e), "models": []})
def _handle_cron_output(handler, parsed):
from cron.jobs import OUTPUT_DIR as CRON_OUT
@@ -1321,7 +1563,7 @@ def _handle_cron_output(handler, parsed):
txt = f.read_text(encoding="utf-8", errors="replace")
outputs.append({"filename": f.name, "content": txt[:8000]})
except Exception:
pass
logger.debug("Failed to read cron output file %s", f)
return j(handler, {"job_id": job_id, "outputs": outputs})
@@ -1415,7 +1657,7 @@ def _handle_sessions_cleanup(handler, body, zero_only=False):
p.unlink(missing_ok=True)
cleaned += 1
except Exception:
pass
logger.debug("Failed to clean up session file %s", p)
if SESSION_INDEX_FILE.exists():
SESSION_INDEX_FILE.unlink(missing_ok=True)
return j(handler, {"ok": True, "cleaned": cleaned})
@@ -1434,13 +1676,20 @@ def _handle_chat_start(handler, body):
if not msg:
return bad(handler, "message is required")
attachments = [str(a) for a in (body.get("attachments") or [])][:20]
workspace = str(Path(body.get("workspace") or s.workspace).expanduser().resolve())
try:
workspace = str(resolve_trusted_workspace(body.get("workspace") or s.workspace))
except ValueError as e:
return bad(handler, str(e))
model = body.get("model") or s.model
stream_id = uuid.uuid4().hex
s.workspace = workspace
s.model = model
s.active_stream_id = stream_id
s.pending_user_message = msg
s.pending_attachments = attachments
s.pending_started_at = time.time()
s.save()
set_last_workspace(workspace)
stream_id = uuid.uuid4().hex
q = queue.Queue()
with STREAMS_LOCK:
STREAMS[stream_id] = q
@@ -1562,7 +1811,7 @@ def _handle_chat_sync(handler, body):
message_count=len(s.messages),
)
except Exception:
pass
logger.debug("Failed to update session cost tracking")
return j(
handler,
{
@@ -1778,11 +2027,10 @@ def _handle_workspace_add(handler, body):
name = body.get("name", "").strip()
if not path_str:
return bad(handler, "path is required")
p = Path(path_str).expanduser().resolve()
if not p.exists():
return bad(handler, f"Path does not exist: {p}")
if not p.is_dir():
return bad(handler, f"Path is not a directory: {p}")
try:
p = resolve_trusted_workspace(path_str)
except ValueError as e:
return bad(handler, str(e))
wss = load_workspaces()
if any(w["path"] == str(p) for w in wss):
return bad(handler, "Workspace already in list")
@@ -1944,18 +2192,30 @@ def _handle_session_import_cli(handler, body):
title = title_from(msgs, "CLI Session")
model = "unknown"
# Get profile and model from CLI session metadata
# Get profile, model, and timestamps from CLI session metadata
profile = None
created_at = None
updated_at = None
for cs in get_cli_sessions():
if cs["session_id"] == sid:
profile = cs.get("profile")
model = cs.get("model", "unknown")
created_at = cs.get("created_at")
updated_at = cs.get("updated_at")
break
s = import_cli_session(sid, title, msgs, model, profile=profile)
s = import_cli_session(
sid,
title,
msgs,
model,
profile=profile,
created_at=created_at,
updated_at=updated_at,
)
s.is_cli_session = True
s._cli_origin = sid
s.save()
s.save(touch_updated_at=False)
return j(
handler,
{

View File

@@ -13,9 +13,12 @@ The bridge uses absolute token counts (not deltas) because the WebUI
Session object already accumulates totals across turns. This avoids
any double-counting risk.
"""
import logging
import os
from pathlib import Path
logger = logging.getLogger(__name__)
def _get_state_db():
"""Get a SessionDB instance for the active profile's state.db.
@@ -31,6 +34,7 @@ def _get_state_db():
from api.profiles import get_active_hermes_home
hermes_home = Path(get_active_hermes_home()).expanduser().resolve()
except Exception:
logger.debug("Failed to resolve hermes home, using default")
hermes_home = Path(os.getenv('HERMES_HOME', str(Path.home() / '.hermes')))
db_path = hermes_home / 'state.db'
@@ -40,6 +44,7 @@ def _get_state_db():
try:
return SessionDB(db_path)
except Exception:
logger.debug("Failed to open state.db")
return None
@@ -57,12 +62,12 @@ def sync_session_start(session_id: str, model=None) -> None:
model=model,
)
except Exception:
pass # never crash the WebUI for sync failures
logger.debug("Failed to sync session start to state.db")
finally:
try:
db.close()
except Exception:
pass
logger.debug("Failed to close state.db")
def sync_session_usage(session_id: str, input_tokens: int=0, output_tokens: int=0,
@@ -92,7 +97,7 @@ def sync_session_usage(session_id: str, input_tokens: int=0, output_tokens: int=
try:
db.set_session_title(session_id, title)
except Exception:
pass
logger.debug("Failed to sync session title to state.db")
# Update message count
if message_count is not None:
try:
@@ -103,11 +108,11 @@ def sync_session_usage(session_id: str, input_tokens: int=0, output_tokens: int=
)
db._execute_write(_set_msg_count)
except Exception:
pass
logger.debug("Failed to sync message count to state.db")
except Exception:
pass # never crash the WebUI for sync failures
logger.debug("Failed to sync session usage to state.db")
finally:
try:
db.close()
except Exception:
pass
logger.debug("Failed to close state.db")

View File

@@ -3,6 +3,7 @@ Hermes Web UI -- SSE streaming engine and agent thread runner.
Includes Sprint 10 cancel support via CANCEL_FLAGS.
"""
import json
import logging
import os
import queue
import threading
@@ -10,6 +11,8 @@ import time
import traceback
from pathlib import Path
logger = logging.getLogger(__name__)
from api.config import (
STREAMS, STREAMS_LOCK, CANCEL_FLAGS, AGENT_INSTANCES, CLI_TOOLSETS,
LOCK, SESSIONS, SESSION_DIR,
@@ -97,7 +100,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
try:
q.put_nowait((event, data))
except Exception:
pass
logger.debug("Failed to put event to queue")
try:
s = get_session(session_id)
@@ -157,35 +160,94 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
_reg_notify(session_id, _approval_notify_cb)
_approval_registered = True
except ImportError:
pass # approval module not available fall back to polling
logger.debug("Approval module not available, falling back to polling")
try:
_token_sent = False # tracks whether any streamed tokens were sent
def on_token(text):
nonlocal _token_sent
if text is None:
return # end-of-stream sentinel
_token_sent = True
put('token', {'text': text})
def on_tool(name, preview, args):
def on_reasoning(text):
if text is None:
return
put('reasoning', {'text': str(text)})
def on_tool(*cb_args, **cb_kwargs):
event_type = None
name = None
preview = None
args = None
if len(cb_args) >= 4:
event_type, name, preview, args = cb_args[:4]
elif len(cb_args) == 3:
name, preview, args = cb_args
event_type = 'tool.started'
elif len(cb_args) == 2:
event_type, name = cb_args
elif len(cb_args) == 1:
name = cb_args[0]
event_type = 'tool.started'
if event_type in ('reasoning.available', '_thinking'):
reason_text = preview if event_type == 'reasoning.available' else name
if reason_text:
put('reasoning', {'text': str(reason_text)})
return
args_snap = {}
if isinstance(args, dict):
for k, v in list(args.items())[:4]:
s2 = str(v); args_snap[k] = s2[:120]+('...' if len(s2)>120 else '')
put('tool', {'name': name, 'preview': preview, 'args': args_snap})
# Fallback: poll for pending approval in case notify_cb wasn't
# registered (e.g. older approval module without gateway support).
try:
from tools.approval import has_pending as _has_pending, _pending, _lock
if _has_pending(session_id):
with _lock:
p = dict(_pending.get(session_id, {}))
if p:
put('approval', p)
except ImportError:
pass
s2 = str(v)
args_snap[k] = s2[:120] + ('...' if len(s2) > 120 else '')
if event_type in (None, 'tool.started'):
put('tool', {
'event_type': event_type or 'tool.started',
'name': name,
'preview': preview,
'args': args_snap,
})
# Fallback: poll for pending approval in case notify_cb wasn't
# registered (e.g. older approval module without gateway support).
try:
from tools.approval import has_pending as _has_pending, _pending, _lock
if _has_pending(session_id):
with _lock:
p = dict(_pending.get(session_id, {}))
if p:
put('approval', p)
except ImportError:
pass
return
if event_type == 'tool.completed':
put('tool_complete', {
'event_type': event_type,
'name': name,
'preview': preview,
'args': args_snap,
'duration': cb_kwargs.get('duration'),
'is_error': bool(cb_kwargs.get('is_error', False)),
})
return
_AIAgent = _get_ai_agent()
if _AIAgent is None:
raise ImportError("AIAgent not available -- check that hermes-agent is on sys.path")
# Initialize SessionDB so session_search works in WebUI sessions
_session_db = None
try:
from hermes_state import SessionDB
_session_db = SessionDB()
except Exception as _db_err:
print(f"[webui] WARNING: SessionDB init failed — session_search will be unavailable: {_db_err}", flush=True)
resolved_model, resolved_provider, resolved_base_url = resolve_model_provider(model)
# Resolve API key via Hermes runtime provider (matches gateway behaviour).
@@ -235,7 +297,9 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
enabled_toolsets=_toolsets,
fallback_model=_fallback_resolved,
session_id=session_id,
session_db=_session_db,
stream_delta_callback=on_token,
reasoning_callback=on_reasoning,
tool_progress_callback=on_tool,
)
@@ -248,7 +312,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
try:
agent.interrupt("Cancelled before start")
except Exception:
pass
logger.debug("Failed to interrupt agent before start")
put('cancel', {'message': 'Cancelled by user'})
return
@@ -296,6 +360,45 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
)
s.messages = result.get('messages') or s.messages
# ── Detect silent agent failure (no assistant reply produced) ──
# When the agent catches an auth/network error internally it may return
# an empty final_response without raising — the stream would end with
# a done event containing zero assistant messages, leaving the user with
# no feedback. Emit an apperror so the client shows an inline error.
_assistant_added = any(
m.get('role') == 'assistant' and str(m.get('content') or '').strip()
for m in (result.get('messages') or [])
)
# _token_sent tracks whether on_token() was called (any streamed text)
if not _assistant_added and not _token_sent:
_last_err = getattr(agent, '_last_error', None) or result.get('error') or ''
_err_str = str(_last_err) if _last_err else ''
_is_auth = (
'401' in _err_str
or (_last_err and 'AuthenticationError' in type(_last_err).__name__)
or 'authentication' in _err_str.lower()
or 'unauthorized' in _err_str.lower()
or 'invalid api key' in _err_str.lower()
or 'invalid_api_key' in _err_str.lower()
)
if _is_auth:
put('apperror', {
'message': _err_str or 'Authentication failed — check your API key.',
'type': 'auth_mismatch',
'hint': (
'The selected model may not be supported by your configured provider or '
'your API key is invalid. Run `hermes model` in your terminal to '
'update credentials, then restart the WebUI.'
),
})
else:
put('apperror', {
'message': _err_str or 'The agent returned no response. Check your API key and model selection.',
'type': 'no_response',
'hint': 'Verify your API key is valid and the selected model is available for your account.',
})
return # Don't emit done — the apperror already closes the stream on the client
# ── Handle context compression side effects ──
# If compression fired inside run_conversation, the agent may have
# rotated its session_id. Detect and fix the mismatch so the WebUI
@@ -316,7 +419,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
try:
old_path.rename(new_path)
except OSError:
pass
logger.debug("Failed to rename session file during compression")
_compressed = True
# Also detect compression via the result dict or compressor state
if not _compressed:
@@ -335,7 +438,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
if isinstance(_m, dict) and not _m.get('timestamp') and not _m.get('_ts'):
_m['timestamp'] = int(_now)
# Only auto-generate title when still default; preserves user renames
if s.title == 'Untitled':
if s.title == 'Untitled' or s.title == 'New Chat' or not s.title:
s.title = title_from(s.messages, s.title)
# Read token/cost usage from the agent object (if available)
input_tokens = getattr(agent, 'session_prompt_tokens', 0) or 0
@@ -403,6 +506,10 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
'assistant_msg_idx': asst_idx, 'args': args_snap,
})
s.tool_calls = tool_calls
s.active_stream_id = None
s.pending_user_message = None
s.pending_attachments = []
s.pending_started_at = None
# Tag the matching user message with attachment filenames for display on reload
# Only tag a user message whose content relates to this turn's text
# (msg_text is the full message including the [Attached files: ...] suffix)
@@ -431,7 +538,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
message_count=len(s.messages),
)
except Exception:
pass # never crash the stream for sync failures
logger.debug("Failed to sync session to insights")
usage = {'input_tokens': input_tokens, 'output_tokens': output_tokens, 'estimated_cost': estimated_cost}
# Include context window data from the agent's compressor for the UI indicator
_cc = getattr(agent, 'context_compressor', None)
@@ -448,7 +555,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
try:
_unreg_notify(session_id)
except Exception:
pass
logger.debug("Failed to unregister approval callback")
with _ENV_LOCK:
if old_cwd is None: os.environ.pop('TERMINAL_CWD', None)
else: os.environ['TERMINAL_CWD'] = old_cwd
@@ -461,6 +568,15 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
except Exception as e:
print('[webui] stream error:\n' + traceback.format_exc(), flush=True)
if s is not None:
s.active_stream_id = None
s.pending_user_message = None
s.pending_attachments = []
s.pending_started_at = None
try:
s.save()
except Exception:
pass
err_str = str(e)
# Detect rate limit errors specifically so the client can show a helpful card
# rather than the generic "Connection lost" message
@@ -541,5 +657,5 @@ def cancel_stream(stream_id: str) -> bool:
try:
q.put_nowait(('cancel', {'message': 'Cancelled by user'}))
except Exception:
pass
logger.debug("Failed to put cancel event to queue")
return True

View File

@@ -3,6 +3,7 @@ Hermes Web UI -- File upload: multipart parser and upload handler.
"""
import re as _re
import email.parser
import tempfile
from pathlib import Path
from api.config import MAX_UPLOAD_BYTES
@@ -50,8 +51,15 @@ def parse_multipart(rfile, content_type, content_length) -> tuple:
return fields, files
def _sanitize_upload_name(filename: str) -> str:
safe_name = _re.sub(r'[^\w.\-]', '_', Path(filename).name)[:200]
if not safe_name or safe_name.strip('.') == '':
raise ValueError('Invalid filename')
return safe_name
def handle_upload(handler):
import re as _re, traceback as _tb
import traceback as _tb
try:
content_type = handler.headers.get('Content-Type', '')
content_length = int(handler.headers.get('Content-Length', 0) or 0)
@@ -69,14 +77,55 @@ def handle_upload(handler):
except KeyError:
return j(handler, {'error': 'Session not found'}, status=404)
workspace = Path(s.workspace)
safe_name = _re.sub(r'[^\w.\-]', '_', Path(filename).name)[:200]
# Reject names that are purely dots (path traversal: ".." survives regex)
if not safe_name or safe_name.strip('.') == '':
return j(handler, {'error': 'Invalid filename'}, status=400)
# Verify the resolved path stays within the workspace
safe_name = _sanitize_upload_name(filename)
dest = safe_resolve_ws(workspace, safe_name)
dest.write_bytes(file_bytes)
return j(handler, {'filename': safe_name, 'path': str(dest), 'size': dest.stat().st_size})
except Exception as e:
except ValueError as e:
return j(handler, {'error': str(e)}, status=400)
except Exception:
print('[webui] upload error: ' + _tb.format_exc(), flush=True)
return j(handler, {'error': 'Upload failed'}, status=500)
def handle_transcribe(handler):
import traceback as _tb
temp_path = None
try:
content_type = handler.headers.get('Content-Type', '')
content_length = int(handler.headers.get('Content-Length', 0) or 0)
if content_length > MAX_UPLOAD_BYTES:
return j(handler, {'error': f'File too large (max {MAX_UPLOAD_BYTES//1024//1024}MB)'}, status=413)
fields, files = parse_multipart(handler.rfile, content_type, content_length)
if 'file' not in files:
return j(handler, {'error': 'No file field in request'}, status=400)
filename, file_bytes = files['file']
if not filename:
return j(handler, {'error': 'No filename in upload'}, status=400)
safe_name = _sanitize_upload_name(filename)
suffix = Path(safe_name).suffix or '.webm'
with tempfile.NamedTemporaryFile(prefix='webui-stt-', suffix=suffix, delete=False) as tmp:
temp_path = tmp.name
tmp.write(file_bytes)
try:
from tools.transcription_tools import transcribe_audio
except ImportError:
return j(handler, {'error': 'Speech-to-text is unavailable on this server'}, status=503)
result = transcribe_audio(temp_path)
if not result.get('success'):
msg = str(result.get('error') or 'Transcription failed')
status = 503 if 'unavailable' in msg.lower() or 'not configured' in msg.lower() else 400
return j(handler, {'error': msg}, status=status)
transcript = str(result.get('transcript') or '').strip()
return j(handler, {'ok': True, 'transcript': transcript})
except ValueError as e:
return j(handler, {'error': str(e)}, status=400)
except Exception:
print('[webui] transcribe error: ' + _tb.format_exc(), flush=True)
return j(handler, {'error': 'Transcription failed'}, status=500)
finally:
if temp_path:
try:
Path(temp_path).unlink(missing_ok=True)
except Exception:
pass

View File

@@ -8,10 +8,13 @@ profile has its own workspace configuration. State files live at
paths are used as fallback when no profile module is available.
"""
import json
import logging
import os
import subprocess
from pathlib import Path
logger = logging.getLogger(__name__)
from api.config import (
WORKSPACES_FILE as _GLOBAL_WS_FILE,
LAST_WORKSPACE_FILE as _GLOBAL_LW_FILE,
@@ -37,7 +40,7 @@ def _profile_state_dir() -> Path:
d.mkdir(parents=True, exist_ok=True)
return d
except ImportError:
pass
logger.debug("Failed to import profiles module, using global state dir")
return _GLOBAL_WS_FILE.parent
@@ -80,7 +83,7 @@ def _profile_default_workspace() -> str:
if p.is_dir():
return str(p)
except (ImportError, Exception):
pass
logger.debug("Failed to load profile default workspace config")
return str(_BOOT_DEFAULT_WORKSPACE)
@@ -89,7 +92,6 @@ def _profile_default_workspace() -> str:
def _clean_workspace_list(workspaces: list) -> list:
"""Sanitize a workspace list:
- Remove entries whose paths no longer exist on disk.
- Remove entries that look like test artifacts (webui-mvp-test, test-workspace).
- Remove entries whose paths live inside another profile's directory
(e.g. ~/.hermes/profiles/X/... should not appear on a different profile).
- Rename any entry whose name is literally 'default' to 'Home' (avoids
@@ -102,18 +104,24 @@ def _clean_workspace_list(workspaces: list) -> list:
path = w.get('path', '')
name = w.get('name', '')
p = Path(path).resolve() if path else Path('/')
# Skip test artifacts
if 'test-workspace' in path or 'webui-mvp-test' in path:
continue
# Skip paths that no longer exist
if not p.is_dir():
continue
# Skip paths inside a named profile's directory (cross-profile leak)
# Skip paths inside a DIFFERENT profile's directory (cross-profile leak).
# Allow paths inside the CURRENT profile's own directory (e.g. test workspaces
# created under ~/.hermes/profiles/webui/webui-mvp-test/).
try:
p.relative_to(hermes_profiles)
continue # it IS under profiles/ — remove it
# p is under ~/.hermes/profiles/ — only skip if it's under a DIFFERENT profile
try:
from api.profiles import get_active_hermes_home
own_profile_dir = get_active_hermes_home().resolve()
p.relative_to(own_profile_dir)
# p is under our own profile dir — keep it
except (ValueError, Exception):
continue # under profiles/ but not our own — cross-profile leak, skip
except ValueError:
pass
pass # not under profiles/ at all — keep it
# Rename confusing 'default' label to 'Home'
if name.lower() == 'default':
name = 'Home'
@@ -156,10 +164,10 @@ def load_workspaces() -> list:
json.dumps(cleaned, ensure_ascii=False, indent=2), encoding='utf-8'
)
except Exception:
pass
logger.debug("Failed to persist cleaned workspace list")
return cleaned or [{'path': _profile_default_workspace(), 'name': 'Home'}]
except Exception:
pass
logger.debug("Failed to load workspaces from %s", ws_file)
# No profile-local file yet.
# For the DEFAULT profile: migrate from the legacy global file (one-time cleanup).
# For NAMED profiles: always start clean with just their own workspace.
@@ -190,7 +198,7 @@ def get_last_workspace() -> str:
if p and Path(p).is_dir():
return p
except Exception:
pass
logger.debug("Failed to read last workspace from %s", lw_file)
# Fallback: try global file
if _GLOBAL_LW_FILE.exists():
try:
@@ -198,7 +206,7 @@ def get_last_workspace() -> str:
if p and Path(p).is_dir():
return p
except Exception:
pass
logger.debug("Failed to read global last workspace")
return _profile_default_workspace()
@@ -208,8 +216,78 @@ def set_last_workspace(path: str) -> None:
lw_file.parent.mkdir(parents=True, exist_ok=True)
lw_file.write_text(str(path), encoding='utf-8')
except Exception:
logger.debug("Failed to set last workspace")
def resolve_trusted_workspace(path: str | Path | None = None) -> Path:
"""Resolve and validate a workspace path.
A path is trusted if it satisfies at least one of:
(A) It is under the user's home directory (Path.home()).
Works cross-platform: ~/... on Linux/macOS, C:\\Users\\... on Windows.
(B) It is already in the profile's saved workspace list.
This covers self-hosted deployments where workspaces live outside home
(e.g. /data/projects, /opt/workspace) — once a workspace is saved by
an admin, it can be reused without re-validation.
Additionally enforced regardless of (A)/(B):
1. The path must exist.
2. The path must be a directory.
3. The path must not be a known system root (/etc, /usr, /var, /bin, /sbin,
/boot, /proc, /sys, /dev, /root on Linux/macOS; Windows system dirs).
This prevents even admin-saved workspaces from pointing at OS internals.
None/empty path falls back to the boot-time DEFAULT_WORKSPACE, which is always
trusted (it was validated at server startup).
"""
_BLOCKED_SYSTEM_ROOTS = {
# Linux / macOS
Path('/etc'), Path('/usr'), Path('/var'), Path('/bin'), Path('/sbin'),
Path('/boot'), Path('/proc'), Path('/sys'), Path('/dev'), Path('/root'),
Path('/lib'), Path('/lib64'), Path('/opt/homebrew'),
}
if path in (None, ""):
return Path(_BOOT_DEFAULT_WORKSPACE).expanduser().resolve()
candidate = Path(path).expanduser().resolve()
if not candidate.exists():
raise ValueError(f"Path does not exist: {candidate}")
if not candidate.is_dir():
raise ValueError(f"Path is not a directory: {candidate}")
# Block known system roots and their children
for blocked in _BLOCKED_SYSTEM_ROOTS:
try:
candidate.relative_to(blocked)
raise ValueError(f"Path points to a system directory: {candidate}")
except ValueError as e:
if "system directory" in str(e):
raise
# relative_to raised ValueError = candidate is NOT under blocked = safe
# (A) Trusted if under the user's home directory — cross-platform via Path.home()
try:
candidate.relative_to(Path.home().resolve())
return candidate
except ValueError:
pass
# (B) Trusted if already in the saved workspace list — covers non-home installs
try:
saved = load_workspaces()
saved_paths = {Path(w["path"]).resolve() for w in saved if w.get("path")}
if candidate in saved_paths:
return candidate
except Exception:
pass
raise ValueError(
f"Path is outside the user home directory and not in the saved workspace "
f"list: {candidate}. Add it via Settings → Workspaces first."
)
def safe_resolve_ws(root: Path, requested: str) -> Path:
"""Resolve a relative path inside a workspace root, raising ValueError on traversal."""

View File

@@ -21,6 +21,8 @@ INSTALLER_URL = "https://raw.githubusercontent.com/NousResearch/hermes-agent/mai
REPO_ROOT = Path(__file__).resolve().parent
DEFAULT_HOST = os.getenv("HERMES_WEBUI_HOST", "127.0.0.1")
DEFAULT_PORT = int(os.getenv("HERMES_WEBUI_PORT", "8787"))
# Set HERMES_WEBUI_SKIP_ONBOARDING=1 to bypass the first-run wizard when
# the environment is already fully configured (e.g. managed hosting).
def info(msg: str) -> None:
@@ -128,9 +130,12 @@ def install_hermes_agent() -> None:
def wait_for_health(url: str, timeout: float = 25.0) -> bool:
deadline = time.time() + timeout
# Validate URL scheme to prevent file:// and other dangerous schemes
if not url.startswith(("http://", "https://")):
raise ValueError(f"Invalid health check URL: {url}")
while time.time() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
with urllib.request.urlopen(url, timeout=2) as response: # nosec B310
if b'"status": "ok"' in response.read():
return True
except Exception:

View File

@@ -39,6 +39,9 @@ services:
# uv pip install /home/hermeswebui/.hermes/hermes-agent
# which installs the agent and all its Python dependencies.
- hermes-agent-src:/home/hermeswebui/.hermes/hermes-agent
# Workspace directory — browse and edit files from the WebUI.
# Adapt the host path to your project directory.
- ~/workspace:/workspace
environment:
- HERMES_WEBUI_HOST=0.0.0.0
- HERMES_WEBUI_PORT=8787

View File

@@ -187,7 +187,10 @@ rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_STATE_DIR"
echo ""; echo "-- HERMES_WEBUI_DEFAULT_WORKSPACE: Default workspace directory shown on first launch"
if [ -z "${HERMES_WEBUI_DEFAULT_WORKSPACE+x}" ]; then echo "HERMES_WEBUI_DEFAULT_WORKSPACE not set, setting to /workspace"; export HERMES_WEBUI_DEFAULT_WORKSPACE="/workspace"; fi;
echo "-- HERMES_WEBUI_DEFAULT_WORKSPACE: $HERMES_WEBUI_DEFAULT_WORKSPACE"
if [ ! -d "$HERMES_WEBUI_DEFAULT_WORKSPACE" ]; then mkdir -p $HERMES_WEBUI_DEFAULT_WORKSPACE || error_exit "Failed to create default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"; fi
# Use sudo for mkdir/chown — Docker may auto-create bind-mount directories as root,
# leaving them unwritable by the hermeswebui user (#357).
sudo mkdir -p "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit "Failed to create default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"
sudo chown hermeswebui:hermeswebui "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit "Failed to set owner of $HERMES_WEBUI_DEFAULT_WORKSPACE"
if [ ! -d "$HERMES_WEBUI_DEFAULT_WORKSPACE" ]; then error_exit "HERMES_WEBUI_DEFAULT_WORKSPACE directory does not exist at $HERMES_WEBUI_DEFAULT_WORKSPACE"; fi
it="$HERMES_WEBUI_DEFAULT_WORKSPACE/.testfile"; touch $it || error_exit "Failed to verify default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"
rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_DEFAULT_WORKSPACE"
@@ -195,8 +198,13 @@ rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_DEFAULT_WOR
echo ""; echo "==================="
echo ""; echo "== Installing uv and creating a new virtual environment for hermes-webui"
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="/home/hermeswebui/.local/bin/:$PATH"
if command -v uv &>/dev/null; then
echo "-- uv already installed ($(uv --version)), skipping download"
else
echo "-- uv not found, downloading..."
curl -LsSf https://astral.sh/uv/install.sh | sh || error_exit "Failed to install uv — check network connectivity"
fi
export UV_PROJECT_ENVIRONMENT=venv
export UV_CACHE_DIR=/uv_cache
@@ -204,7 +212,12 @@ sudo mkdir -p ${UV_CACHE_DIR} || error_exit "Failed to create /uv_cache director
sudo chown hermeswebui:hermeswebui ${UV_CACHE_DIR} || error_exit "Failed to set owner of ${UV_CACHE_DIR} to hermeswebui user"
cd /app
uv venv venv
if [ -f /app/venv/bin/python3 ]; then
echo ""; echo "== Existing virtual environment found — reusing (fast restart)"
else
echo ""; echo "== Creating new virtual environment"
uv venv venv
fi
export VIRTUAL_ENV=/app/venv
test -d /app/venv
test -f /app/venv/bin/activate
@@ -213,13 +226,18 @@ echo "";echo "== Activating hermes webui's virtual environment"
source /app/venv/bin/activate || error_exit "Failed to activate hermeswebui virtual environment"
test -x /app/venv/bin/python3
echo ""; echo "== Installing hermes-webui dependencies"
uv pip install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org
uv pip install -U pip setuptools --trusted-host pypi.org --trusted-host files.pythonhosted.org
test -x /app/venv/bin/pip
if [ -f /app/venv/.deps_installed ]; then
echo ""; echo "== Dependencies already installed — skipping (fast restart)"
else
echo ""; echo "== Installing hermes-webui dependencies"
uv pip install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org
uv pip install -U pip setuptools --trusted-host pypi.org --trusted-host files.pythonhosted.org
test -x /app/venv/bin/pip
echo ""; echo "== Adding hermes-agent's pyproject.toml base dependencies to the virtual environment"
uv pip install /home/hermeswebui/.hermes/hermes-agent --trusted-host pypi.org --trusted-host files.pythonhosted.org || error_exit "Failed to install hermes-agent's requirements"
echo ""; echo "== Adding hermes-agent's pyproject.toml base dependencies to the virtual environment"
uv pip install /home/hermeswebui/.hermes/hermes-agent --trusted-host pypi.org --trusted-host files.pythonhosted.org || error_exit "Failed to install hermes-agent's requirements"
touch /app/venv/.deps_installed
fi
echo ""; echo "== Running hermes-webui"
cd /app; python server.py || error_exit "hermes-webui failed or exited with an error"

View File

@@ -3,11 +3,16 @@ Hermes Web UI -- Main server entry point.
Thin routing shell: imports Handler, delegates to api/routes.py, runs server.
All business logic lives in api/*.
"""
import logging
import socket
import sys
import time
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
from api.auth import check_auth
from api.config import HOST, PORT, STATE_DIR, SESSION_DIR, DEFAULT_WORKSPACE
from api.helpers import j
@@ -15,6 +20,28 @@ from api.routes import handle_get, handle_post
from api.startup import auto_install_agent_deps, fix_credential_permissions
class QuietHTTPServer(ThreadingHTTPServer):
"""Custom HTTP server that silently handles common network errors."""
def handle_error(self, request, client_address):
"""Override to suppress logging for common client disconnect errors."""
exc_type, exc_value, _ = sys.exc_info()
# Silently ignore common connection errors caused by client disconnects
if exc_type in (ConnectionResetError, BrokenPipeError, ConnectionAbortedError):
return
# Also handle socket errors that indicate client disconnect
if exc_type is socket.error:
# errno 54 is Connection reset by peer on macOS/BSD
# errno 104 is Connection reset by peer on Linux
if exc_value.errno in (54, 104, 32): # ECONNRESET, EPIPE
return
# For other errors, use default logging
super().handle_error(request, client_address)
class Handler(BaseHTTPRequestHandler):
timeout = 30 # seconds — kills idle/incomplete connections to prevent thread exhaustion
server_version = 'HermesWebUI/0.2'
@@ -118,7 +145,7 @@ def main() -> None:
except Exception as e:
print(f'[!!] WARNING: Gateway watcher failed to start: {e}', flush=True)
httpd = ThreadingHTTPServer((HOST, PORT), Handler)
httpd = QuietHTTPServer((HOST, PORT), Handler)
# ── TLS/HTTPS setup (optional) ─────────────────────────────────────────
from api.config import TLS_ENABLED, TLS_CERT, TLS_KEY
@@ -148,7 +175,7 @@ def main() -> None:
from api.gateway_watcher import stop_watcher
stop_watcher()
except Exception:
pass
logger.debug("Failed to stop gateway watcher during shutdown")
if __name__ == '__main__':
main()

View File

@@ -118,6 +118,10 @@ function syncWorkspacePanelUI(){
if(clearBtn){
clearBtn.disabled=!isOpen;
clearBtn.title=hasPreview?'Close preview':'Hide workspace panel';
// On desktop, only show the X button when a file preview is open.
// In browse mode the chevron (btnCollapseWorkspacePanel) already serves
// as the close control, so showing both produces a duplicate X.
if(!isCompact) clearBtn.style.display=hasPreview?'':'none';
}
}
@@ -172,24 +176,32 @@ function mobileSwitchPanel(name){
});
}
$('btnSend').onclick=()=>{if(window._micActive)_stopMic();send();};
$('btnSend').onclick=()=>{
if(window._micActive){
window._micPendingSend=true;
_stopMic();
return;
}
send();
};
$('btnAttach').onclick=()=>$('fileInput').click();
// ── Voice input (Web Speech API) ─────────────────────────────────────────
// ── Voice input (Web Speech API + MediaRecorder fallback) ───────────────────
(function(){
const SpeechRecognition=window.SpeechRecognition||window.webkitSpeechRecognition;
if(!SpeechRecognition) return; // Browser unsupported — mic button stays hidden
const _canRecordAudio=!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&window.MediaRecorder);
if(!SpeechRecognition&&!_canRecordAudio) return; // Browser unsupported — mic button stays hidden
const btn=$('btnMic');
const status=$('micStatus');
const ta=$('msg');
btn.style.display=''; // Show button — browser supports speech
const recognition=new SpeechRecognition();
recognition.continuous=false;
recognition.interimResults=true;
recognition.lang=(typeof _locale!=='undefined'&&_locale._speech)||'en-US';
const statusText=status?status.querySelector('.status-text'):null;
btn.style.display=''; // Show button — browser supports speech recognition or recording fallback
let recognition=SpeechRecognition?new SpeechRecognition():null;
let mediaRecorder=null;
let mediaStream=null;
let audioChunks=[];
let _finalText='';
let _prefix='';
@@ -197,67 +209,162 @@ $('btnAttach').onclick=()=>$('fileInput').click();
window._micActive=on;
btn.classList.toggle('recording',on);
status.style.display=on?'':'none';
if(statusText) statusText.textContent=on?'Listening':'Listening';
if(!on){ _finalText=''; _prefix=''; }
}
recognition.onstart=()=>{ _finalText=''; };
recognition.onresult=(event)=>{
let interim='';
let final=_finalText;
for(let i=event.resultIndex;i<event.results.length;i++){
const t=event.results[i][0].transcript;
if(event.results[i].isFinal){ final+=t; _finalText=final; }
else{ interim+=t; }
}
// Append to whatever was already in the textarea before mic started
ta.value=_prefix+(final||interim);
autoResize();
};
recognition.onend=()=>{
// Commit: prefix + final transcription; trim trailing space if prefix was non-empty
const committed=_finalText
function _commitTranscript(text){
const clean=(text||'').trim();
const committed=clean
? (_prefix&&!_prefix.endsWith(' ')&&!_prefix.endsWith('\n')
? _prefix+' '+_finalText.trimStart()
: _prefix+_finalText)
: ta.value; // no speech detected — leave whatever is there
_setRecording(false);
? _prefix+' '+clean.trimStart()
: _prefix+clean)
: ta.value;
ta.value=committed;
autoResize();
};
if(window._micPendingSend){
window._micPendingSend=false;
send();
}
}
recognition.onerror=(event)=>{
_setRecording(false);
const msgs={
'not-allowed':t('mic_denied'),
'no-speech':t('mic_no_speech'),
'network':t('mic_network'),
};
showToast(msgs[event.error]||t('mic_error')+event.error);
};
async function _transcribeBlob(blob){
const ext=(blob.type&&blob.type.includes('ogg'))?'ogg':'webm';
const form=new FormData();
form.append('file',new File([blob],`voice-input.${ext}`,{type:blob.type||`audio/${ext}`}));
setComposerStatus('Transcribing…');
try{
const res=await fetch('/api/transcribe',{method:'POST',body:form});
const data=await res.json().catch(()=>({}));
if(!res.ok) throw new Error(data.error||'Transcription failed');
_commitTranscript(data.transcript||'');
}catch(err){
window._micPendingSend=false;
showToast(err.message||t('mic_network'));
}finally{
setComposerStatus('');
}
}
function _stopTracks(){
if(mediaStream){
mediaStream.getTracks().forEach(track=>track.stop());
mediaStream=null;
}
}
function _stopMic(){
if(window._micActive){ recognition.stop(); }
if(!window._micActive) return;
if(recognition){
recognition.stop();
return;
}
if(mediaRecorder&&mediaRecorder.state!=='inactive'){
mediaRecorder.stop();
return;
}
_setRecording(false);
_stopTracks();
}
window._stopMic=_stopMic; // expose for send-guard above
btn.onclick=()=>{
if(recognition){
recognition.continuous=false;
recognition.interimResults=true;
recognition.lang=(typeof _locale!=='undefined'&&_locale._speech)||'en-US';
recognition.onstart=()=>{ _finalText=''; };
recognition.onresult=(event)=>{
let interim='';
let final=_finalText;
for(let i=event.resultIndex;i<event.results.length;i++){
const t=event.results[i][0].transcript;
if(event.results[i].isFinal){ final+=t; _finalText=final; }
else{ interim+=t; }
}
ta.value=_prefix+(final||interim);
autoResize();
};
recognition.onend=()=>{
const committed=_finalText
? (_prefix&&!_prefix.endsWith(' ')&&!_prefix.endsWith('\n')
? _prefix+' '+_finalText.trimStart()
: _prefix+_finalText)
: ta.value;
_setRecording(false);
ta.value=committed;
autoResize();
if(window._micPendingSend){
window._micPendingSend=false;
send();
}
};
recognition.onerror=(event)=>{
_setRecording(false);
window._micPendingSend=false;
const msgs={
'not-allowed':t('mic_denied'),
'no-speech':t('mic_no_speech'),
'network':t('mic_network'),
};
showToast(msgs[event.error]||t('mic_error')+event.error);
};
}
btn.onclick=async()=>{
if(window._micActive){
recognition.stop();
// _setRecording(false) will be called by onend
} else {
_finalText='';
// Snapshot existing textarea content so we append rather than replace
_prefix=ta.value;
_stopMic();
return;
}
_finalText='';
_prefix=ta.value;
if(recognition){
recognition.start();
_setRecording(true);
return;
}
if(!_canRecordAudio){
showToast(t('mic_network'));
return;
}
try{
mediaStream=await navigator.mediaDevices.getUserMedia({audio:true});
const preferredTypes=['audio/webm;codecs=opus','audio/webm','audio/ogg;codecs=opus','audio/ogg'];
const mimeType=preferredTypes.find(type=>window.MediaRecorder.isTypeSupported?.(type))||'';
mediaRecorder=new MediaRecorder(mediaStream,mimeType?{mimeType}:undefined);
audioChunks=[];
mediaRecorder.ondataavailable=e=>{if(e.data&&e.data.size)audioChunks.push(e.data);};
mediaRecorder.onerror=()=>{
_setRecording(false);
window._micPendingSend=false;
_stopTracks();
showToast(t('mic_network'));
};
mediaRecorder.onstop=async()=>{
const blob=new Blob(audioChunks,{type:mediaRecorder.mimeType||mimeType||'audio/webm'});
_setRecording(false);
_stopTracks();
if(blob.size){ await _transcribeBlob(blob); }
else if(window._micPendingSend){
window._micPendingSend=false;
}
};
mediaRecorder.start();
_setRecording(true);
}catch(err){
window._micPendingSend=false;
_stopTracks();
showToast(t('mic_denied'));
}
};
})();
window._micActive=window._micActive||false;
window._micPendingSend=window._micPendingSend||false;
$('fileInput').onchange=e=>{addFiles(Array.from(e.target.files));e.target.value='';};
$('btnNewChat').onclick=async()=>{await newSession();await renderSessionList();$('msg').focus();};
$('btnNewChat').onclick=async()=>{await newSession();await renderSessionList();closeMobileSidebar();$('msg').focus();};
$('btnDownload').onclick=()=>{
if(!S.session)return;
const blob=new Blob([transcript()],{type:'text/markdown'});
@@ -374,9 +481,15 @@ document.addEventListener('keydown',async e=>{
}
if((e.metaKey||e.ctrlKey)&&e.key==='k'){
e.preventDefault();
if(!S.busy){await newSession();await renderSessionList();$('msg').focus();}
if(!S.busy){await newSession();await renderSessionList();closeMobileSidebar();$('msg').focus();}
}
if(e.key==='Escape'){
// Close onboarding overlay if open (skip/dismiss the wizard)
const onboardingOverlay=$('onboardingOverlay');
if(onboardingOverlay&&onboardingOverlay.style.display!=='none'){
if(typeof skipOnboarding==='function') skipOnboarding();
return;
}
// Close settings overlay if open
const settingsOverlay=$('settingsOverlay');
if(settingsOverlay&&settingsOverlay.style.display!=='none'){_closeSettingsPanel();return;}
@@ -479,7 +592,7 @@ function applyBotName(){
(async()=>{
// Load send key preference
let _bootSettings={};
try{const s=await api('/api/settings');_bootSettings=s;window._sendKey=s.send_key||'enter';window._showTokenUsage=!!s.show_token_usage;window._showCliSessions=!!s.show_cli_sessions;window._soundEnabled=!!s.sound_enabled;window._notificationsEnabled=!!s.notifications_enabled;window._botName=s.bot_name||'Hermes';const _theme=s.theme||'dark';document.documentElement.dataset.theme=_theme;localStorage.setItem('hermes-theme',_theme);if(s.language&&typeof setLocale==='function'){setLocale(s.language);if(typeof applyLocaleToDOM==='function')applyLocaleToDOM();}applyBotName();}catch(e){window._sendKey='enter';window._showTokenUsage=false;window._showCliSessions=false;window._soundEnabled=false;window._notificationsEnabled=false;window._botName='Hermes';_bootSettings={check_for_updates:false};}
try{const s=await api('/api/settings');_bootSettings=s;window._sendKey=s.send_key||'enter';window._showTokenUsage=!!s.show_token_usage;window._showCliSessions=!!s.show_cli_sessions;window._soundEnabled=!!s.sound_enabled;window._notificationsEnabled=!!s.notifications_enabled;window._botName=s.bot_name||'Hermes';const _theme=s.theme||'dark';document.documentElement.dataset.theme=_theme;localStorage.setItem('hermes-theme',_theme);document.body.classList.toggle('bubble-layout',!!s.bubble_layout);if(s.language&&typeof setLocale==='function'){setLocale(s.language);if(typeof applyLocaleToDOM==='function')applyLocaleToDOM();}applyBotName();}catch(e){window._sendKey='enter';window._showTokenUsage=false;window._showCliSessions=false;window._soundEnabled=false;window._notificationsEnabled=false;window._botName='Hermes';_bootSettings={check_for_updates:false};document.body.classList.remove('bubble-layout');}
// Non-blocking update check (fire-and-forget, once per tab session)
// ?test_updates=1 in URL forces banner display for testing (bypasses sessionStorage guards)
const _testUpdates=new URLSearchParams(location.search).get('test_updates')==='1';

View File

@@ -131,6 +131,7 @@ const LOCALES = {
settings_label_theme: 'Theme',
settings_label_language: 'Language',
settings_label_token_usage: 'Show token usage',
settings_label_bubble_layout: 'Chat bubble layout',
settings_label_cli_sessions: 'Show agent sessions',
settings_label_sync_insights: 'Sync to insights',
settings_label_check_updates: 'Check for updates',
@@ -165,6 +166,17 @@ const LOCALES = {
tab_todos: 'Todos',
new_conversation: 'New conversation',
filter_conversations: 'Filter conversations...',
session_time_unknown: 'Unknown',
session_time_just_now: 'just now',
session_time_minutes_ago: (n) => `${n} minute${n === 1 ? '' : 's'} ago`,
session_time_hours_ago: (n) => `${n} hour${n === 1 ? '' : 's'} ago`,
session_time_days_ago: (n) => `${n} day${n === 1 ? '' : 's'} ago`,
session_time_last_week: 'last week',
session_time_bucket_today: 'Today',
session_time_bucket_yesterday: 'Yesterday',
session_time_bucket_this_week: 'This week',
session_time_bucket_last_week: 'Last week',
session_time_bucket_older: 'Older',
scheduled_jobs: 'Scheduled jobs',
new_job: 'New job',
loading: 'Loading...',
@@ -183,6 +195,7 @@ const LOCALES = {
settings_label_notifications: 'Browser notifications',
settings_desc_notifications: 'Show a system notification when a response completes while the tab is in the background.',
settings_desc_token_usage: 'Displays input/output token count below each assistant reply. Also toggled with /usage.',
settings_desc_bubble_layout: 'Right-align user messages and left-align assistant replies. Off by default to keep code blocks and tool output full-width.',
settings_desc_cli_sessions: 'Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.',
settings_desc_sync_insights: 'Mirrors WebUI token usage to state.db so hermes /insights includes browser session data. Off by default.',
settings_desc_check_updates: 'Show a banner when newer versions of the WebUI or Agent are available. Runs a background git fetch periodically.',
@@ -207,6 +220,8 @@ const LOCALES = {
onboarding_lead: 'A quick guided setup will verify Hermes, save a real provider configuration, choose a workspace and model, and optionally protect the app with a password.',
onboarding_back: 'Back',
onboarding_continue: 'Continue',
onboarding_skip: 'Skip setup',
onboarding_skipped: 'Setup skipped — using existing config.',
onboarding_open: 'Open Hermes',
onboarding_step_system_title: 'System check',
onboarding_step_system_desc: 'Verify Hermes Agent and config visibility.',
@@ -237,6 +252,11 @@ const LOCALES = {
onboarding_missing_imports: 'Missing imports:',
onboarding_notice_setup_required: 'Choose a simple provider path here. Advanced OAuth flows still belong in the Hermes CLI for now.',
onboarding_notice_setup_already_ready: 'A working Hermes provider setup is already detected. You can keep it or replace it here.',
onboarding_oauth_provider_ready_title: 'Provider already authenticated',
onboarding_oauth_provider_ready_body: 'This instance is configured to use an OAuth provider (<strong>{provider}</strong>) that was set up via the Hermes CLI. No API key is needed here — click Continue to finish setup.',
onboarding_oauth_provider_not_ready_title: 'OAuth provider not yet authenticated',
onboarding_oauth_provider_not_ready_body: 'This instance is configured to use <strong>{provider}</strong>, which uses OAuth rather than an API key. Run <code>hermes auth</code> or <code>hermes model</code> in a terminal to authenticate, then reload the Web UI.',
onboarding_oauth_switch_hint: 'Or choose a different provider below to switch to an API-key setup:',
onboarding_notice_workspace: 'These values reuse the same settings APIs as the normal app.',
onboarding_workspace_label: 'Workspace',
onboarding_workspace_or_path: 'Or enter a workspace path',
@@ -391,6 +411,7 @@ const LOCALES = {
settings_label_theme: 'Tema',
settings_label_language: 'Idioma',
settings_label_token_usage: 'Mostrar uso de tokens',
settings_label_bubble_layout: 'Disposición en burbujas',
settings_label_cli_sessions: 'Mostrar sesiones de CLI',
settings_label_sync_insights: 'Sincronizar con insights',
settings_label_check_updates: 'Buscar actualizaciones',
@@ -425,6 +446,17 @@ const LOCALES = {
tab_todos: 'Todos',
new_conversation: 'Nueva conversación',
filter_conversations: 'Filtrar conversaciones...',
session_time_unknown: 'Desconocido',
session_time_just_now: 'justo ahora',
session_time_minutes_ago: (n) => `hace ${n} minuto${n === 1 ? '' : 's'}`,
session_time_hours_ago: (n) => `hace ${n} hora${n === 1 ? '' : 's'}`,
session_time_days_ago: (n) => `hace ${n} día${n === 1 ? '' : 's'}`,
session_time_last_week: 'la semana pasada',
session_time_bucket_today: 'Hoy',
session_time_bucket_yesterday: 'Ayer',
session_time_bucket_this_week: 'Esta semana',
session_time_bucket_last_week: 'La semana pasada',
session_time_bucket_older: 'Más antiguo',
scheduled_jobs: 'Tareas programadas',
new_job: 'Nueva tarea',
loading: 'Cargando...',
@@ -443,6 +475,7 @@ const LOCALES = {
settings_label_notifications: 'Notificaciones del navegador',
settings_desc_notifications: 'Muestra una notificación del sistema cuando una respuesta termina mientras la pestaña está en segundo plano.',
settings_desc_token_usage: 'Muestra el conteo de tokens de entrada/salida debajo de cada respuesta del asistente. También se puede alternar con /usage.',
settings_desc_bubble_layout: 'Alinea los mensajes del usuario a la derecha y las respuestas del asistente a la izquierda. Desactivado por defecto para mantener los bloques de código y la salida de herramientas a ancho completo.',
settings_desc_cli_sessions: 'Fusiona las sesiones del CLI de Hermes (state.db) en la lista de sesiones. Haz clic en una sesión de CLI para importarla y continuar la conversación.',
settings_desc_sync_insights: 'Refleja el uso de tokens de la WebUI en state.db para que hermes /insights incluya datos de sesiones del navegador. Desactivado por defecto.',
settings_desc_check_updates: 'Muestra un banner cuando haya versiones más nuevas de la WebUI o del Agent. Ejecuta periódicamente un git fetch en segundo plano.',
@@ -467,6 +500,8 @@ const LOCALES = {
onboarding_lead: 'Una guía rápida verificará Hermes, guardará una configuración real del proveedor, elegirá un espacio de trabajo y un modelo, y opcionalmente protegerá la app con una contraseña.',
onboarding_back: 'Atrás',
onboarding_continue: 'Continuar',
onboarding_skip: 'Omitir configuración',
onboarding_skipped: 'Configuración omitida — se usa la configuración existente.',
onboarding_open: 'Abrir Hermes',
onboarding_step_system_title: 'Comprobación del sistema',
onboarding_step_system_desc: 'Verifica Hermes Agent y la visibilidad de la configuración.',
@@ -497,6 +532,11 @@ const LOCALES = {
onboarding_missing_imports: 'Importaciones faltantes:',
onboarding_notice_setup_required: 'Elige aquí una ruta simple de proveedor. Los flujos OAuth avanzados siguen siendo del CLI de Hermes por ahora.',
onboarding_notice_setup_already_ready: 'Ya se detectó una configuración funcional del proveedor de Hermes. Puedes conservarla o reemplazarla aquí.',
onboarding_oauth_provider_ready_title: 'Proveedor ya autenticado',
onboarding_oauth_provider_ready_body: 'Esta instancia está configurada para usar un proveedor OAuth (<strong>{provider}</strong>) configurado mediante la CLI de Hermes. No se necesita clave API aquí — haz clic en Continuar para finalizar la configuración.',
onboarding_oauth_provider_not_ready_title: 'Proveedor OAuth no autenticado aún',
onboarding_oauth_provider_not_ready_body: 'Esta instancia está configurada para usar <strong>{provider}</strong>, que utiliza OAuth en lugar de una clave API. Ejecuta <code>hermes auth</code> o <code>hermes model</code> en una terminal para autenticarte y recarga la interfaz web.',
onboarding_oauth_switch_hint: 'O elige un proveedor diferente a continuación para cambiar a la configuración con clave API:',
onboarding_notice_workspace: 'Estos valores reutilizan las mismas APIs de configuración que la app normal.',
onboarding_workspace_label: 'Espacio de trabajo',
onboarding_workspace_or_path: 'O introduce la ruta de un espacio de trabajo',
@@ -874,57 +914,48 @@ const LOCALES = {
login_btn: '\u767b\u5f55',
login_invalid_pw: '\u5bc6\u7801\u9519\u8bef',
login_conn_failed: '\u8fde\u63a5\u5931\u8d25',
dialog_confirm_title: '确认操作',
dialog_prompt_title: '输入内容',
dialog_confirm_btn: '确认',
discard: '放弃',
clear: '清空',
create: '创建',
remove: '移除',
project_name_prompt: '项目名称:',
// missing keys from English
tab_chat: '\u804a\u5929',
tab_memory: '\u8a18\u61b6',
tab_skills: '\u6280\u80fd',
tab_tasks: '\u4efb\u52d9',
tab_todos: '\u5f85\u8e29',
tab_workspaces: '\u5de5\u4f5c\u5340',
new_conversation: '\u65b0\u5b58\u5c0d\u8a71',
filter_conversations: '\u7b5c\u9078\u5b58\u5c0d\u8a71',
scheduled_jobs: '\u5b58\u5287\u4efb\u52d9',
new_job: '\u65b0\u4efb\u52d9',
search_skills: '\u641c\u5c0b\u6280\u80fd',
new_skill: '\u65b0\u6280\u80fd',
save_skill: '\u5132\u5b58\u6280\u80fd',
personal_memory: '\u500b\u4eba\u8a18\u61b6',
current_task_list: '\u76ee\u524d\u4efb\u52d9\u6e05\u55ae',
new_profile: '\u65b0\u914d\u7f6e\u6a94',
transcript: '\u8a18\u9304',
download_transcript: '\u4e0b\u8f09\u8a18\u9304',
import: '\u5c0e\u5165',
editing: '\u7de8\u8f2f\u4e2d',
empty_title: '\u7a7a\u767c\u5b58\u7a7a\u9593',
empty_subtitle: '\u9ede\u64ca\u4e0a\u65b9\u6309\u9215\u958b\u59cb\u5c0d\u8a71',
cancel: '\u53d6\u6d88',
loading: '\u52a0\u8f09\u4e2d',
create_job: '\u5efa\u7acb\u4efb\u52d9',
suggest_plan: '\u5efa\u8b70\u8a08\u5287',
suggest_schedule: '\u5efa\u8b70\u6642\u7a0b',
suggest_files: '\u5efa\u8b70\u6a94\u6848',
sign_out: '\u767b\u51fa',
password_placeholder: '\u5bc6\u7801',
disable_auth: '\u505c\u7528\u9a57\u8b49',
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
settings_label_notifications: '\u700f\u89bd\u901a\u77e5',
settings_desc_sound: '\u52a9\u624b\u5b8c\u6210\u56de\u7b54\u6642\u64a9\u653e\u8072\u97f3\u3002',
settings_desc_notifications: '\u7576\u5206\u9801\u5728\u5f8c\u53f0\u6642\uff0c\u6709\u56de\u7b54\u5b8c\u6210\u6e05\u55ae\u6703\u986f\u793a\u7cfb\u7d71\u901a\u77e5\u3002',
settings_desc_token_usage: '\u5728\u52a9\u624b\u6bcf\u6b21\u56de\u7b54\u4e0b\u65b9\u986f\u793a Input/Output token \u6578\u91cf\u3002\u4e5f\u53ef\u4ee5\u7528 /usage \u5207\u63db\u3002',
settings_desc_cli_sessions: '\u5c07 Hermes CLI (\u7684 state.db) \u4e2d\u7684\u4f1a\u8a71\u6dfb\u52a0\u5230\u4f1a\u8a71\u6e05\u55ae\u3002\u9ede\u64ca\u4e00\u500b CLI \u4f1a\u8a71\u5c07\u5c0e\u5165\u5b83\u7a0b\u5f0f\u4e26\u7e7c\u7e8c\u5b58\u5c0d\u8a71\u3002',
settings_desc_sync_insights: '\u5c07 WebUI token \u4f7f\u7528\u60c5\u6cc1\u540c\u6b65\u5230 state.db\uff0c\u8a93 hermes /insights \u5305\u542b\u700f\u89bd\u5668\u4f1a\u8a71\u6578\u64da\u3002\u9810\u8a2d\u70b8\u555f\u7528\u3002',
settings_desc_check_updates: '\u7576\u6709\u66f4\u65b0\u7684 WebUI \u6216\u52a9\u624b\u7248\u672c\u6642\u986f\u793a\u6a19\u8a18\u3002\u5c07\u5728\u5f8c\u81ea\u6b63\u5e38\u57f7\u884c Git-Fetch\u3002',
settings_desc_bot_name: '\u52a9\u624b\u5728 UI \u4e2d\u7684\u986f\u793a\u540d\u7a31\u3002\u9810\u8a2d\u70b8\u7528\u6539\u3002',
settings_desc_password: '\u8a2d\u5b9a WebUI \u767b\u5165\u5bc6\u7801\u3002\u5047\u5982\u5df2\u8a2d\u7f6e\uff0c\u6bcf\u6b21\u52a0\u8f09\u90fd\u9700\u8981\u767b\u5165\u3002',
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
// sidebar & navigation
tab_chat: '聊天',
tab_memory: '记忆',
tab_skills: '技能',
tab_tasks: '任务',
tab_todos: '待办',
tab_workspaces: '工作区',
new_conversation: '新建对话',
filter_conversations: '筛选对话…',
scheduled_jobs: '定时任务',
new_job: '新任务',
search_skills: '搜索技能…',
new_skill: '新技能',
save_skill: '保存技能',
personal_memory: '个人记忆',
current_task_list: '当前任务列表',
new_profile: '新配置',
transcript: '记录',
download_transcript: '下载为 Markdown',
import: '导入',
editing: '编辑中',
empty_title: '有什么可以帮您?',
empty_subtitle: '随时提问、运行命令、浏览文件或管理定时任务。',
cancel: '取消',
loading: '加载中…',
create_job: '创建任务',
suggest_plan: '帮我规划一个小项目。',
suggest_schedule: '今天有什么安排?',
suggest_files: '这个工作区有哪些文件?',
sign_out: '退出登录',
password_placeholder: '输入新密码…',
disable_auth: '停用认证',
settings_label_sound: '通知声音',
settings_label_notifications: '浏览器通知',
settings_desc_sound: '助手完成回复时播放提示音。',
settings_desc_notifications: '当标签页在后台时,回复完成后显示系统通知。',
settings_desc_token_usage: '在助手每次回复下方显示输入/输出 token 数量。也可以用 /usage 切换。',
settings_desc_cli_sessions: '将 Hermes CLIstate.db中的会话合并到会话列表。点击某个 CLI 会话可导入并继续对话。',
settings_desc_sync_insights: '将 WebUI token 使用情况同步到 state.db使 hermes /insights 包含浏览器会话数据。默认关闭。',
settings_desc_check_updates: '当有更新的 WebUI 或助手版本时显示横幅。会在后台定期执行 git fetch。',
settings_desc_bot_name: '助手在 UI 中的显示名称。默认为 Hermes。',
settings_desc_password: '输入新密码以设置或更改。留空保持当前设置。',
},
// Traditional Chinese (zh-Hant)
@@ -963,8 +994,8 @@ const LOCALES = {
approval_btn_once_title: '\u5141\u8a31\u57f7\u884c\u6b64\u547d\u4ee4\u4e00\u6b21\uff08Enter\uff09',
approval_btn_session: '\u672c\u6b21\u5141\u8a31',
approval_btn_session_title: '\u672c\u6b21\u6703\u8a71\u671f\u9593\u5141\u8a31',
approval_btn_always: '\u59c4\u59b9\u5141\u8a31',
approval_btn_always_title: '\u59c4\u59b9\u5141\u8a31\u6b64\u547d\u4ee4\u6a21\u5f0f',
approval_btn_always: '始終允許',
approval_btn_always_title: '始終允許此命令模式',
approval_btn_deny: '\u62d2\u7edd',
approval_btn_deny_title: '\u62d2\u7edd — \u4e0d\u57f7\u884c\u6b64\u547d\u4ee4',
approval_responding: '\u8655\u7406\u4e2d\u2026',

View File

@@ -6,6 +6,8 @@
<title>Hermes</title>
<script>(function(){var t=localStorage.getItem('hermes-theme');if(t&&t!=='dark')document.documentElement.dataset.theme=t;})()</script>
<link rel="stylesheet" href="/static/style.css">
<!-- KaTeX math rendering CSS (loaded eagerly to prevent layout shift) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css" integrity="sha384-5TcZemv2l/9On385z///+d7MSYlvIEw9FuZTIdZ14vJLqWphw7e7ZPuOiCHJcFCP" crossorigin="anonymous">
<!-- Prism.js syntax highlighting (loaded async, non-blocking) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css" integrity="sha384-wFjoQjtV1y5jVHbt0p35Ui8aV8GVpEZkyF99OXWqP/eNJDU93D3Ugxkoyh6Y2I4A" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js" integrity="sha384-MXybTpajaBV0AkcBaCPT4KIvo0FzoCiWXgcihYsw4FUkEz0Pv3JGV6tk2G8vJtDc" crossorigin="anonymous" defer></script>
@@ -356,7 +358,7 @@
<button class="panel-icon-btn" id="btnNewFolder" title="New folder" onclick="promptNewFolder()"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></button>
<button class="panel-icon-btn" id="btnRefreshPanel" title="Refresh" onclick="if(S.session)loadDir(S.currentDir)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button>
<button class="panel-icon-btn close-preview" id="btnClearPreview" title="Close preview"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
<button class="panel-icon-btn mobile-close-btn" onclick="closeWorkspacePanel()" title="Close" aria-label="Close workspace panel">×</button>
<button class="panel-icon-btn mobile-close-btn" onclick="handleWorkspaceClose()" title="Close" aria-label="Close workspace panel">×</button>
</div>
</div>
<div class="breadcrumb-bar" id="breadcrumbBar" style="display:none"></div>
@@ -389,6 +391,7 @@
<div class="onboarding-body" id="onboardingBody"></div>
<div class="onboarding-actions">
<button class="sm-btn" id="onboardingBackBtn" onclick="prevOnboardingStep()" style="display:none" data-i18n="onboarding_back">Back</button>
<button class="sm-btn" id="onboardingSkipBtn" onclick="skipOnboarding()" style="margin-right:auto;opacity:.7" data-i18n="onboarding_skip">Skip setup</button>
<button class="sm-btn" id="onboardingNextBtn" onclick="nextOnboardingStep()" style="font-weight:700;color:var(--blue);border-color:rgba(124,185,255,.32)" data-i18n="onboarding_continue">Continue</button>
</div>
</div>
@@ -492,6 +495,13 @@
</label>
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_token_usage">Displays input/output token count below each assistant reply. Also toggled with <code>/usage</code>.</div>
</div>
<div class="settings-field">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="settingsBubbleLayout" style="width:15px;height:15px;accent-color:var(--accent)">
<span data-i18n="settings_label_bubble_layout">Chat bubble layout</span>
</label>
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_bubble_layout">Right-align user messages and left-align assistant replies. Off by default to keep code blocks and tool output full-width.</div>
</div>
<div class="settings-field">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="settingsShowCliSessions" style="width:15px;height:15px;accent-color:var(--accent)">
@@ -526,7 +536,7 @@
<div class="settings-section-title">System</div>
<div class="settings-section-meta">Instance version and access controls.</div>
</div>
<span class="settings-version-badge">v0.50.2</span>
<span class="settings-version-badge">v0.50.37</span>
</div>
<div class="settings-field" style="border-top:1px solid var(--border);padding-top:12px;margin-top:8px">
<label for="settingsPassword" data-i18n="settings_label_password">Access Password</label>

View File

@@ -10,10 +10,12 @@ async function send(){
// If busy, queue the message instead of dropping it
if(S.busy){
if(text){
MSG_QUEUE.push(text);
if(!S.session){await newSession();await renderSessionList();}
queueSessionMessage(S.session.session_id,{text,files:[...S.pendingFiles]});
$('msg').value='';autoResize();
updateQueueBadge();
showToast(`Queued: "${text.slice(0,40)}${text.length>40?'\u2026':''}"`,2000);
S.pendingFiles=[];renderTray();
updateQueueBadge(S.session.session_id);
showToast(`Queued: "${text.slice(0,40)}${text.length>40?'…':''}"`,2000);
}
return;
}
@@ -37,7 +39,10 @@ async function send(){
S.toolCalls=[]; // clear tool calls from previous turn
clearLiveToolCards(); // clear any leftover live cards from last turn
S.messages.push(userMsg);renderMessages();appendThinking();setBusy(true);
INFLIGHT[activeSid]={messages:[...S.messages],uploaded};
INFLIGHT[activeSid]={messages:[...S.messages],uploaded,toolCalls:[]};
if(typeof saveInflightState==='function'){
saveInflightState(activeSid,{streamId:null,messages:INFLIGHT[activeSid].messages,uploaded,toolCalls:[]});
}
startApprovalPolling(activeSid);
S.activeStreamId = null; // will be set after stream starts
@@ -67,6 +72,9 @@ async function send(){
streamId=startData.stream_id;
S.activeStreamId = streamId;
markInflight(activeSid, streamId);
if(typeof saveInflightState==='function'){
saveInflightState(activeSid,{streamId,messages:INFLIGHT[activeSid].messages,uploaded,toolCalls:INFLIGHT[activeSid].toolCalls||[]});
}
// Show Cancel button
const cancelBtn=$('btnCancel');
if(cancelBtn) cancelBtn.style.display='inline-flex';
@@ -81,7 +89,32 @@ async function send(){
}
// Open SSE stream and render tokens live
attachLiveStream(activeSid, streamId, uploaded);
}
const LIVE_STREAMS={};
function closeLiveStream(sessionId, streamId){
const live=LIVE_STREAMS[sessionId];
if(!live) return;
if(streamId&&live.streamId!==streamId) return;
try{live.source.close();}catch(_){ }
delete LIVE_STREAMS[sessionId];
}
function attachLiveStream(activeSid, streamId, uploaded=[], options={}){
if(!activeSid||!streamId) return;
const reconnecting=!!options.reconnecting;
closeLiveStream(activeSid);
if(!INFLIGHT[activeSid]) INFLIGHT[activeSid]={messages:[...S.messages],uploaded:[...uploaded],toolCalls:[]};
else {
if(uploaded.length) INFLIGHT[activeSid].uploaded=[...uploaded];
if(!Array.isArray(INFLIGHT[activeSid].toolCalls)) INFLIGHT[activeSid].toolCalls=[];
}
let assistantText='';
let reasoningText='';
let assistantRow=null;
let assistantBody=null;
// Thinking tag patterns for streaming display
@@ -90,8 +123,57 @@ async function send(){
{open:'<|channel>thought\n',close:'<channel|>'}
];
function _isActiveSession(){
return !!(S.session&&S.session.session_id===activeSid);
}
function persistInflightState(){
const inflight=INFLIGHT[activeSid];
if(!inflight||typeof saveInflightState!=='function') return;
saveInflightState(activeSid,{
streamId,
messages:inflight.messages||[],
uploaded:inflight.uploaded||[...uploaded],
toolCalls:inflight.toolCalls||[],
});
}
function _closeSource(){
closeLiveStream(activeSid, streamId);
}
function syncInflightAssistantMessage(){
const inflight=INFLIGHT[activeSid];
if(!inflight) return;
if(!Array.isArray(inflight.messages)) inflight.messages=[];
let assistantIdx=-1;
for(let i=inflight.messages.length-1;i>=0;i--){
const msg=inflight.messages[i];
if(msg&&msg.role==='assistant'&&msg._live){assistantIdx=i;break;}
}
const ts=Date.now()/1000;
if(assistantIdx>=0){
inflight.messages[assistantIdx].content=assistantText;
inflight.messages[assistantIdx].reasoning=reasoningText||undefined;
inflight.messages[assistantIdx]._ts=inflight.messages[assistantIdx]._ts||ts;
persistInflightState();
return;
}
inflight.messages.push({role:'assistant',content:assistantText,reasoning:reasoningText||undefined,_live:true,_ts:ts});
persistInflightState();
}
function ensureAssistantRow(){
if(assistantRow)return;
if(!_isActiveSession()) return;
if(assistantRow&&!assistantRow.isConnected){assistantRow=null;assistantBody=null;}
if(!assistantRow){
const existing=$('msgInner').querySelector('.msg-row[data-live-assistant="1"]');
if(existing){
assistantRow=existing;
assistantBody=existing.querySelector('.msg-body');
}
}
if(assistantRow){
if(typeof placeLiveToolCardsHost==='function') placeLiveToolCardsHost();
return;
}
removeThinking();
const tr=$('toolRunningRow');if(tr)tr.remove();
$('emptyState').style.display='none';
@@ -115,31 +197,72 @@ async function send(){
// and hiding content still inside an open thinking block.
function _streamDisplay(){
const raw=assistantText;
if(reasoningText) return raw;
for(const {open,close} of _thinkPairs){
if(raw.startsWith(open)){
const ci=raw.indexOf(close,open.length);
// Trim leading whitespace before checking for the open tag — some models
// (e.g. MiniMax) emit newlines before <think>.
const trimmed=raw.trimStart();
if(trimmed.startsWith(open)){
const ci=trimmed.indexOf(close,open.length);
if(ci!==-1){
// Thinking block complete — strip it, show the rest
return raw.slice(ci+close.length).replace(/^\s+/,'');
return trimmed.slice(ci+close.length).replace(/^\s+/,'');
}
// Still inside thinking block — show placeholder
return '';
}
// Hide partial tag prefixes while streaming so users don't see
// `<thi`, `<think`, etc. before the model finishes the token.
if(open.startsWith(raw)) return '';
if(open.startsWith(trimmed)) return '';
}
return raw;
}
function _parseStreamState(){
const raw=assistantText;
if(reasoningText){
return {thinkingText:reasoningText, displayText:_streamDisplay(), inThinking:false};
}
for(const {open,close} of _thinkPairs){
const trimmed=raw.trimStart();
if(trimmed.startsWith(open)){
const ci=trimmed.indexOf(close,open.length);
if(ci!==-1){
return {
thinkingText: trimmed.slice(open.length, ci).trim(),
displayText: trimmed.slice(ci+close.length).replace(/^\s+/,''),
inThinking:false,
};
}
return {
thinkingText: trimmed.slice(open.length).trim(),
displayText:'',
inThinking:true,
};
}
if(open.startsWith(trimmed)){
return {thinkingText:'', displayText:'', inThinking:true};
}
}
return {thinkingText:'', displayText:raw, inThinking:false};
}
function _renderLiveThinking(parsed){
const text=(parsed&&parsed.thinkingText)||'';
if(text||(parsed&&parsed.inThinking)){
if(typeof updateThinking==='function') updateThinking(text||'Thinking…');
else appendThinking();
return;
}
removeThinking();
}
function _scheduleRender(){
if(_renderPending) return;
_renderPending=true;
requestAnimationFrame(()=>{
_renderPending=false;
const parsed=_parseStreamState();
_renderLiveThinking(parsed);
if(assistantBody){
const txt=_streamDisplay();
const isThinking=!txt&&assistantText.length>0;
assistantBody.innerHTML=txt?renderMd(txt):(isThinking?'<span style="color:var(--muted);font-size:13px">Thinking\u2026</span>':'');
assistantBody.innerHTML=parsed.displayText?renderMd(parsed.displayText):'';
}
scrollIfPinned();
});
@@ -150,17 +273,61 @@ async function send(){
if(!S.session||S.session.session_id!==activeSid) return;
const d=JSON.parse(e.data);
assistantText+=d.text;
syncInflightAssistantMessage();
if(!S.session||S.session.session_id!==activeSid) return;
ensureAssistantRow();
_scheduleRender();
});
source.addEventListener('reasoning',e=>{
const d=JSON.parse(e.data);
reasoningText += d.text || '';
syncInflightAssistantMessage();
if(!S.session||S.session.session_id!==activeSid) return;
_scheduleRender();
});
source.addEventListener('tool',e=>{
const d=JSON.parse(e.data);
const tc={name:d.name, preview:d.preview||'', args:d.args||{}, snippet:'', done:false, tid:d.tid||`live-${Date.now()}-${Math.random().toString(36).slice(2,8)}`};
if(!Array.isArray(INFLIGHT[activeSid].toolCalls)) INFLIGHT[activeSid].toolCalls=[];
INFLIGHT[activeSid].toolCalls.push(tc);
S.toolCalls=INFLIGHT[activeSid].toolCalls;
persistInflightState();
if(!S.session||S.session.session_id!==activeSid) return;
removeThinking();
const oldRow=$('toolRunningRow');if(oldRow)oldRow.remove();
const tc={name:d.name, preview:d.preview||'', args:d.args||{}, snippet:'', done:false};
S.toolCalls.push(tc);
appendLiveToolCard(tc);
scrollIfPinned();
});
source.addEventListener('tool_complete',e=>{
const d=JSON.parse(e.data);
const inflight=INFLIGHT[activeSid];
if(!inflight) return;
if(!Array.isArray(inflight.toolCalls)) inflight.toolCalls=[];
let tc=null;
for(let i=inflight.toolCalls.length-1;i>=0;i--){
const cur=inflight.toolCalls[i];
if(cur&&cur.done===false&&(!d.name||cur.name===d.name)){
tc=cur;
break;
}
}
if(!tc){
tc={name:d.name||'tool', preview:d.preview||'', args:d.args||{}, snippet:'', done:true};
inflight.toolCalls.push(tc);
}
tc.preview=d.preview||tc.preview||'';
tc.args=d.args||tc.args||{};
tc.done=true;
tc.is_error=!!d.is_error;
if(d.duration!==undefined) tc.duration=d.duration;
S.toolCalls=inflight.toolCalls;
persistInflightState();
if(!S.session||S.session.session_id!==activeSid) return;
appendLiveToolCard(tc);
scrollIfPinned();
});
@@ -177,7 +344,7 @@ async function send(){
source.close();
const d=JSON.parse(e.data);
delete INFLIGHT[activeSid];
clearInflight();
clearInflight();clearInflightState(activeSid);
stopApprovalPolling();
if(!_approvalSessionId || _approvalSessionId===activeSid) hideApprovalCard(true);
if(S.session&&S.session.session_id===activeSid){
@@ -201,6 +368,8 @@ async function send(){
}
clearLiveToolCards();
S.busy=false;
// No-reply guard (#373): if agent returned nothing, show inline error
if(!S.messages.some(m=>m.role==='assistant'&&String(m.content||'').trim())&&!assistantText){removeThinking();S.messages.push({role:'assistant',content:'**No response received.** Check your API key and model selection.'});}
syncTopbar();renderMessages();loadDir('.');
}
renderSessionList();setBusy(false);setStatus('');
@@ -224,7 +393,7 @@ async function send(){
// Application-level error sent explicitly by the server (rate limit, crash, etc.)
// This is distinct from the SSE network 'error' event below.
source.close();
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
delete INFLIGHT[activeSid];clearInflight();clearInflightState(activeSid);stopApprovalPolling();
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
if(S.session&&S.session.session_id===activeSid){
S.activeStreamId=null;const _cbe=$('btnCancel');if(_cbe)_cbe.style.display='none';
@@ -233,7 +402,8 @@ async function send(){
const d=JSON.parse(e.data);
const isRateLimit=d.type==='rate_limit';
const isAuthMismatch=d.type==='auth_mismatch';
const label=isRateLimit?'Rate limit reached':isAuthMismatch?(typeof t==='function'?t('provider_mismatch_label'):'Provider mismatch'):'Error';
const isNoResponse=d.type==='no_response';
const label=isRateLimit?'Rate limit reached':isAuthMismatch?(typeof t==='function'?t('provider_mismatch_label'):'Provider mismatch'):isNoResponse?'No response received':'Error';
const hint=d.hint?`\n\n*${d.hint}*`:'';
S.messages.push({role:'assistant',content:`**${label}:** ${d.message}${hint}`});
}catch(_){
@@ -284,7 +454,7 @@ async function send(){
source.addEventListener('cancel',e=>{
source.close();
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
delete INFLIGHT[activeSid];clearInflight();clearInflightState(activeSid);stopApprovalPolling();
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
if(S.session&&S.session.session_id===activeSid){
S.activeStreamId=null;const _cbc=$('btnCancel');if(_cbc)_cbc.style.display='none';
@@ -299,16 +469,15 @@ async function send(){
}
function _handleStreamError(){
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
delete INFLIGHT[activeSid];clearInflight();clearInflightState(activeSid);stopApprovalPolling();
_closeSource();
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
if(S.session&&S.session.session_id===activeSid){
S.activeStreamId=null;const _cbe=$('btnCancel');if(_cbe)_cbe.style.display='none';
clearLiveToolCards();if(!assistantText)removeThinking();
S.messages.push({role:'assistant',content:'**Error:** Connection lost'});renderMessages();
}else{
// User switched away — show background error banner
if(typeof trackBackgroundError==='function'){
// Look up session title from the session list cache so the banner names it correctly
const _errTitle=(typeof _allSessions!=='undefined'&&_allSessions.find(s=>s.session_id===activeSid)||{}).title||null;
trackBackgroundError(activeSid,_errTitle,'Connection lost');
}

View File

@@ -112,6 +112,61 @@ function _renderOnboardingBody(){
const provider=_getOnboardingSetupProvider(ONBOARDING.form.provider)||providers[0]||null;
const showBaseUrl=provider&&provider.requires_base_url;
const keyHelp=provider?`${t('onboarding_api_key_help_prefix')} ${esc(provider.env_var)}.`:'';
// OAuth provider path: configured via CLI, no API key input needed.
const currentIsOauth=!!(ONBOARDING.status.setup||{}).current_is_oauth;
const currentProviderName=((ONBOARDING.status.setup||{}).current||{}).provider||'';
if(currentIsOauth){
const isReady=!!(ONBOARDING.status.system||{}).chat_ready;
const providerLabel=esc(currentProviderName);
if(isReady){
_setOnboardingNotice(t('onboarding_notice_setup_already_ready'),'success');
body.innerHTML=`
<div class="onboarding-oauth-card onboarding-oauth-ready">
<div class="onboarding-oauth-icon">✓</div>
<div>
<strong>${t('onboarding_oauth_provider_ready_title')}</strong>
<p>${t('onboarding_oauth_provider_ready_body').replace('{provider}',providerLabel)}</p>
</div>
</div>
<p class="onboarding-copy" style="margin-top:20px">${t('onboarding_oauth_switch_hint')}</p>
<label class="onboarding-field">
<span>${t('onboarding_provider_label')}</span>
<select id="onboardingProviderSelect" onchange="syncOnboardingProvider(this.value)">${options}</select>
</label>
<label class="onboarding-field" id="onboardingApiKeyField">
<span>${t('onboarding_api_key_label')}</span>
<input id="onboardingApiKeyInput" type="password" value="${esc(ONBOARDING.form.apiKey||'')}" placeholder="${t('onboarding_api_key_placeholder')}" oninput="ONBOARDING.form.apiKey=this.value">
</label>
${showBaseUrl?`<label class="onboarding-field"><span>${t('onboarding_base_url_label')}</span><input id="onboardingBaseUrlInput" value="${esc(ONBOARDING.form.baseUrl||'')}" placeholder="${t('onboarding_base_url_placeholder')}" oninput="ONBOARDING.form.baseUrl=this.value"></label>`:''}
<p class="onboarding-copy">${keyHelp}</p>`;
} else {
_setOnboardingNotice(t('onboarding_notice_setup_required'),'warn');
body.innerHTML=`
<div class="onboarding-oauth-card onboarding-oauth-pending">
<div class="onboarding-oauth-icon">⚠</div>
<div>
<strong>${t('onboarding_oauth_provider_not_ready_title')}</strong>
<p>${t('onboarding_oauth_provider_not_ready_body').replace('{provider}',providerLabel)}</p>
</div>
</div>
<p class="onboarding-copy" style="margin-top:20px">${t('onboarding_oauth_switch_hint')}</p>
<label class="onboarding-field">
<span>${t('onboarding_provider_label')}</span>
<select id="onboardingProviderSelect" onchange="syncOnboardingProvider(this.value)">${options}</select>
</label>
<label class="onboarding-field" id="onboardingApiKeyField">
<span>${t('onboarding_api_key_label')}</span>
<input id="onboardingApiKeyInput" type="password" value="${esc(ONBOARDING.form.apiKey||'')}" placeholder="${t('onboarding_api_key_placeholder')}" oninput="ONBOARDING.form.apiKey=this.value">
</label>
${showBaseUrl?`<label class="onboarding-field"><span>${t('onboarding_base_url_label')}</span><input id="onboardingBaseUrlInput" value="${esc(ONBOARDING.form.baseUrl||'')}" placeholder="${t('onboarding_base_url_placeholder')}" oninput="ONBOARDING.form.baseUrl=this.value"></label>`:''}
<p class="onboarding-copy">${keyHelp}</p>`;
}
const providerSel=$('onboardingProviderSelect');
if(providerSel) providerSel.value=ONBOARDING.form.provider;
return;
}
_setOnboardingNotice(system.chat_ready?t('onboarding_notice_setup_already_ready'):t('onboarding_notice_setup_required'),system.chat_ready?'success':'info');
body.innerHTML=`
<label class="onboarding-field">
@@ -275,6 +330,18 @@ async function _finishOnboarding(){
}
}
async function skipOnboarding(){
try{
// Mark onboarding completed server-side without changing any config
await api('/api/onboarding/complete',{method:'POST',body:'{}'});
ONBOARDING.active=false;
$('onboardingOverlay').style.display='none';
showToast(t('onboarding_skipped')||'Setup skipped');
}catch(e){
_setOnboardingNotice((e.message||String(e)),'warn');
}
}
async function nextOnboardingStep(){
try{
if(ONBOARDING.steps[ONBOARDING.step]==='setup'){

View File

@@ -308,10 +308,11 @@ async function cronDelete(id) {
function loadTodos() {
const panel = $('todoPanel');
if (!panel) return;
const sourceMessages = (S.session && Array.isArray(S.session.messages) && S.session.messages.length) ? S.session.messages : S.messages;
// Parse the most recent todo state from message history
let todos = [];
for (let i = S.messages.length - 1; i >= 0; i--) {
const m = S.messages[i];
for (let i = sourceMessages.length - 1; i >= 0; i--) {
const m = sourceMessages[i];
if (m && m.role === 'tool') {
try {
const d = JSON.parse(typeof m.content === 'string' ? m.content : JSON.stringify(m.content));
@@ -1224,6 +1225,8 @@ async function loadSettingsPanel(){
if(soundCb){soundCb.checked=!!settings.sound_enabled;soundCb.addEventListener('change',_markSettingsDirty,{once:false});}
const notifCb=$('settingsNotificationsEnabled');
if(notifCb){notifCb.checked=!!settings.notifications_enabled;notifCb.addEventListener('change',_markSettingsDirty,{once:false});}
const bubbleCb=$('settingsBubbleLayout');
if(bubbleCb){bubbleCb.checked=!!settings.bubble_layout;bubbleCb.addEventListener('change',_markSettingsDirty,{once:false});}
// Bot name
const botNameField=$('settingsBotName');
if(botNameField){botNameField.value=settings.bot_name||'Hermes';botNameField.addEventListener('input',_markSettingsDirty,{once:false});}
@@ -1266,6 +1269,8 @@ async function saveSettings(andClose){
body.check_for_updates=!!($('settingsCheckUpdates')||{}).checked;
body.sound_enabled=!!($('settingsSoundEnabled')||{}).checked;
body.notifications_enabled=!!($('settingsNotificationsEnabled')||{}).checked;
body.bubble_layout=!!($('settingsBubbleLayout')||{}).checked;
document.body.classList.toggle('bubble-layout', body.bubble_layout);
const botName=(($('settingsBotName')||{}).value||'').trim();
body.bot_name=botName||'Hermes';
// Password: only act if the field has content; blank = leave auth unchanged

View File

@@ -11,7 +11,7 @@ const ICONS={
};
async function newSession(flash){
MSG_QUEUE.length=0;updateQueueBadge();
updateQueueBadge();
S.toolCalls=[];
clearLiveToolCards();
// Use profile default workspace for new sessions after a profile switch (one-shot),
@@ -20,9 +20,19 @@ async function newSession(flash){
S._profileDefaultWorkspace=null; // consume — only applies to the first new session after switch
const data=await api('/api/session/new',{method:'POST',body:JSON.stringify({model:$('modelSelect').value,workspace:inheritWs})});
S.session=data.session;S.messages=data.session.messages||[];
S.lastUsage={...(data.session.last_usage||{})};
if(flash)S.session._flash=true;
localStorage.setItem('hermes-webui-session',S.session.session_id);
syncTopbar();await loadDir('.');renderMessages();
// Reset per-session visual state: a fresh chat is idle even if another
// conversation is still streaming in the background.
S.busy=false;
S.activeStreamId=null;
updateSendBtn();
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
setStatus('');
setComposerStatus('');
updateQueueBadge(S.session.session_id);
syncTopbar();renderMessages();loadDir('.');
// don't call renderSessionList here - callers do it when needed
}
@@ -30,40 +40,104 @@ async function loadSession(sid){
stopApprovalPolling();hideApprovalCard();
const data=await api(`/api/session?session_id=${encodeURIComponent(sid)}`);
S.session=data.session;
S.lastUsage={...(data.session.last_usage||{})};
localStorage.setItem('hermes-webui-session',S.session.session_id);
// B9: sanitize empty assistant messages that can appear when agent only ran tool calls
data.session.messages=(data.session.messages||[]).filter(m=>{
if(!m||!m.role)return false;
if(m.role==='tool')return false;
if(m.role==='assistant'){let c=m.content||'';if(Array.isArray(c))c=c.filter(p=>p&&p.type==='text').map(p=>p.text||'').join('');return String(c).trim().length>0;}
return true;
});
// B9: sanitize empty assistant messages (PR #402) — build index map to remap
// session-level tool_calls.assistant_msg_idx to the new sanitized positions.
const allMsgs = data.session.messages || [];
const sanitized = [];
const origIdxToSanitizedIdx = {};
let lastKeptAsstIdx = -1;
for (let i = 0; i < allMsgs.length; i++) {
const m = allMsgs[i];
if (!m || !m.role) continue;
if (m.role === 'tool') continue;
if (m.role === 'assistant') {
let c = m.content || '';
if (Array.isArray(c)) c = c.filter(p => p && p.type === 'text').map(p => p.text || '').join('');
if (!String(c).trim().length) { continue; } // empty assistant — skip
lastKeptAsstIdx = sanitized.length;
}
origIdxToSanitizedIdx[i] = sanitized.length;
sanitized.push(m);
}
if (data.session.tool_calls && data.session.tool_calls.length) {
for (const tc of data.session.tool_calls) {
if (!tc || tc.assistant_msg_idx === undefined) continue;
const origIdx = tc.assistant_msg_idx;
tc.assistant_msg_idx = (origIdx in origIdxToSanitizedIdx)
? origIdxToSanitizedIdx[origIdx]
: (lastKeptAsstIdx >= 0 ? lastKeptAsstIdx : -1);
}
}
data.session.messages = sanitized;
const activeStreamId=data.session.active_stream_id||null;
if(!INFLIGHT[sid]&&activeStreamId&&typeof loadInflightState==='function'){
const stored=loadInflightState(sid, activeStreamId);
if(stored){
INFLIGHT[sid]={
messages:Array.isArray(stored.messages)&&stored.messages.length?stored.messages:[...(data.session.messages||[])],
uploaded:Array.isArray(stored.uploaded)?stored.uploaded:[...(data.session.pending_attachments||[])],
toolCalls:Array.isArray(stored.toolCalls)?stored.toolCalls:[],
reattach:true,
};
}
}
if(INFLIGHT[sid]){
S.messages=INFLIGHT[sid].messages;
// Restore live tool cards for this in-flight session
S.toolCalls=(INFLIGHT[sid].toolCalls||[]);
S.busy=true;
syncTopbar();renderMessages();appendThinking();loadDir('.');
clearLiveToolCards();
if(typeof placeLiveToolCardsHost==='function') placeLiveToolCardsHost();
for(const tc of (S.toolCalls||[])){
if(tc&&tc.name) appendLiveToolCard(tc);
}
syncTopbar();await loadDir('.');renderMessages();appendThinking();
setBusy(true);setComposerStatus('');
startApprovalPolling(sid);
S.activeStreamId=activeStreamId;
const _cb=$('btnCancel');if(_cb&&activeStreamId)_cb.style.display='inline-flex';
if(INFLIGHT[sid].reattach&&activeStreamId&&typeof attachLiveStream==='function'){
INFLIGHT[sid].reattach=false;
attachLiveStream(sid, activeStreamId, data.session.pending_attachments||[], {reconnecting:true});
}
}else{
MSG_QUEUE.length=0;updateQueueBadge(); // clear queue for the viewed session
updateQueueBadge(sid);
S.messages=data.session.messages||[];
S.toolCalls=(data.session.tool_calls||[]).map(tc=>({...tc,done:true}));
// Reset per-session visual state: the viewed session is idle even if another
// session's stream is still running in the background.
// We directly update the DOM instead of calling setBusy(false), because
// setBusy(false) drains MSG_QUEUE which we don't want here.
S.busy=false;
S.activeStreamId=null;
updateSendBtn();
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
setStatus('');
setComposerStatus('');
const pendingMsg=typeof getPendingSessionMessage==='function'?getPendingSessionMessage(data.session):null;
if(pendingMsg) S.messages.push(pendingMsg);
// Fix (PR #402): do NOT pre-fill S.toolCalls from session-level tool_calls —
// those have stale assistant_msg_idx values after B9 sanitization. Instead,
// set S.toolCalls=[] and let renderMessages() derive them from per-message
// tool_calls (which already have correct sanitized-array indices).
S.toolCalls=[];
clearLiveToolCards();
syncTopbar();await loadDir('.');renderMessages();highlightCode();
if(activeStreamId){
S.busy=true;
S.activeStreamId=activeStreamId;
updateSendBtn();
const _cb=$('btnCancel');if(_cb)_cb.style.display='inline-flex';
setStatus('');
setComposerStatus('');
syncTopbar();renderMessages();appendThinking();loadDir('.');
updateQueueBadge(sid);
startApprovalPolling(sid);
if(typeof attachLiveStream==='function') attachLiveStream(sid, activeStreamId, data.session.pending_attachments||[], {reconnecting:true});
else if(typeof watchInflightSession==='function') watchInflightSession(sid, activeStreamId);
}else{
// Reset per-session visual state: the viewed session is idle even if another
// session's stream is still running in the background.
// We directly update the DOM instead of calling setBusy(false), because
// setBusy(false) drains the viewed session's queued follow-up turns.
S.busy=false;
S.activeStreamId=null;
updateSendBtn();
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
setStatus('');
setComposerStatus('');
updateQueueBadge(sid);
syncTopbar();renderMessages();highlightCode();loadDir('.');
}
}
// Sync context usage indicator from session data
const _s=S.session;
@@ -300,6 +374,72 @@ function filterSessions(){
}, 350);
}
function _sessionTimestampMs(session) {
const raw = Number(session && (session.updated_at || session.created_at || 0));
return Number.isFinite(raw) ? raw * 1000 : 0;
}
function _localDayOrdinal(timestampMs) {
const date = new Date(timestampMs);
return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86400000);
}
function _sessionCalendarBoundaries(nowMs = Date.now()) {
const now = new Date(nowMs);
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const startOfYesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
const startOfWeek = new Date(startOfToday);
startOfWeek.setDate(startOfWeek.getDate() - ((startOfWeek.getDay() + 6) % 7));
const startOfLastWeek = new Date(startOfWeek);
startOfLastWeek.setDate(startOfLastWeek.getDate() - 7);
return {
startOfToday: startOfToday.getTime(),
startOfYesterday: startOfYesterday.getTime(),
startOfWeek: startOfWeek.getTime(),
startOfLastWeek: startOfLastWeek.getTime(),
};
}
function _formatSessionDate(timestampMs, nowMs = Date.now()) {
const date = new Date(timestampMs);
const now = new Date(nowMs);
const options = {month:'short', day:'numeric'};
if (date.getFullYear() !== now.getFullYear()) options.year = 'numeric';
return date.toLocaleDateString(undefined, options);
}
function _formatRelativeSessionTime(timestampMs, nowMs = Date.now()) {
if (!timestampMs) return t('session_time_unknown');
const diffMs = Math.max(0, nowMs - timestampMs);
const minute = 60 * 1000;
const hour = 60 * minute;
const {startOfToday, startOfYesterday, startOfWeek, startOfLastWeek} = _sessionCalendarBoundaries(nowMs);
const dayDiff = Math.max(0, _localDayOrdinal(nowMs) - _localDayOrdinal(timestampMs));
if (timestampMs >= startOfToday) {
if (diffMs < minute) return t('session_time_just_now');
if (diffMs < hour) {
const minutes = Math.floor(diffMs / minute);
return t('session_time_minutes_ago', minutes);
}
const hours = Math.floor(diffMs / hour);
return t('session_time_hours_ago', hours);
}
if (timestampMs >= startOfYesterday) return t('session_time_bucket_yesterday');
if (timestampMs >= startOfWeek) return t('session_time_days_ago', dayDiff);
if (timestampMs >= startOfLastWeek) return t('session_time_last_week');
return _formatSessionDate(timestampMs, nowMs);
}
function _sessionTimeBucketLabel(timestampMs, nowMs = Date.now()) {
if (!timestampMs) return t('session_time_bucket_older');
const {startOfToday, startOfYesterday, startOfWeek, startOfLastWeek} = _sessionCalendarBoundaries(nowMs);
if (timestampMs >= startOfToday) return t('session_time_bucket_today');
if (timestampMs >= startOfYesterday) return t('session_time_bucket_yesterday');
if (timestampMs >= startOfWeek) return t('session_time_bucket_this_week');
if (timestampMs >= startOfLastWeek) return t('session_time_bucket_last_week');
return t('session_time_bucket_older');
}
function renderSessionListFromCache(){
// Don't re-render while user is actively renaming a session (would destroy the input)
if(_renamingSid) return;
@@ -386,12 +526,12 @@ function renderSessionListFromCache(){
empty.textContent='No sessions in this project yet.';
list.appendChild(empty);
}
const orderedSessions=[...sessions].sort((a,b)=>_sessionTimestampMs(b)-_sessionTimestampMs(a));
// Separate pinned from unpinned
const pinned=sessions.filter(s=>s.pinned);
const unpinned=sessions.filter(s=>!s.pinned);
// Date grouping: Pinned / Today / Yesterday / Earlier
const pinned=orderedSessions.filter(s=>s.pinned);
const unpinned=orderedSessions.filter(s=>!s.pinned);
// Date grouping: Pinned / Today / Yesterday / This week / Last week / Older
const now=Date.now();
const ONE_DAY=86400000;
// Collapse state persisted in localStorage
let _groupCollapsed={};
try{_groupCollapsed=JSON.parse(localStorage.getItem('hermes-date-groups-collapsed')||'{}');}catch(e){}
@@ -401,8 +541,8 @@ function renderSessionListFromCache(){
let curLabel=null,curItems=[];
if(pinned.length) groups.push({label:'\u2605 Pinned',items:pinned,isPinned:true});
for(const s of unpinned){
const ts=(s.updated_at||s.created_at||0)*1000;
const label=ts>now-ONE_DAY?'Today':ts>now-2*ONE_DAY?'Yesterday':'Earlier';
const ts=_sessionTimestampMs(s);
const label=_sessionTimeBucketLabel(ts, now);
if(label!==curLabel){
if(curItems.length) groups.push({label:curLabel,items:curItems});
curLabel=label;curItems=[s];
@@ -447,10 +587,32 @@ function renderSessionListFromCache(){
const rawTitle=s.title||'Untitled';
const tags=(rawTitle.match(/#[\w-]+/g)||[]);
const cleanTitle=tags.length?rawTitle.replace(/#[\w-]+/g,'').trim():rawTitle;
const sessionText=document.createElement('div');
sessionText.className='session-text';
const titleRow=document.createElement('div');
titleRow.className='session-title-row';
const title=document.createElement('span');
title.className='session-title';
title.textContent=cleanTitle||'Untitled';
title.title='Double-click to rename';
const tsMs=_sessionTimestampMs(s);
const timeLabel=document.createElement('span');
timeLabel.className='session-time';
timeLabel.textContent=_formatRelativeSessionTime(tsMs, now);
if(tsMs) timeLabel.title=new Date(tsMs).toLocaleString();
titleRow.appendChild(title);
titleRow.appendChild(timeLabel);
const metaBits=[];
if(s.is_cli_session && s.source_tag) metaBits.push(s.source_tag);
if(s.message_count) metaBits.push(t('n_messages', s.message_count));
if(s.model) metaBits.push(String(s.model).split('/').pop());
sessionText.appendChild(titleRow);
if(metaBits.length){
const meta=document.createElement('div');
meta.className='session-meta';
meta.textContent=metaBits.join(' · ');
sessionText.appendChild(meta);
}
// Append tag chips after the title text
for(const tag of tags){
const chip=document.createElement('span');
@@ -517,7 +679,7 @@ function renderSessionListFromCache(){
title.appendChild(dot);
}
}
el.appendChild(title);
el.appendChild(sessionText);
// Single trigger button that opens a shared dropdown menu
const actions=document.createElement('div');
actions.className='session-actions';

View File

@@ -34,6 +34,7 @@
:root[data-theme="light"] .session-item{color:#5a544a;}
:root[data-theme="light"] .session-item:hover{background:rgba(0,0,0,.06);color:#2c2825;}
:root[data-theme="light"] .session-item.active{background:rgba(45,111,163,.1);color:#1a5a8a;}
:root[data-theme="light"] .session-item.active .session-title{color:#1a5a8a;}
:root[data-theme="light"] .session-pin-indicator{color:#996b15;}
:root[data-theme="light"] .session-date-header.pinned{color:#996b15;}
:root[data-theme="light"] .session-actions-trigger.active,
@@ -66,7 +67,9 @@
:root[data-theme="light"] .panel-icon-btn:hover{background:rgba(0,0,0,.06);}
:root[data-theme="light"] .file-item:hover{background:rgba(0,0,0,.04);}
:root[data-theme="light"] .preview-md th{background:rgba(0,0,0,.04);}
:root[data-theme="light"] .msg-body th{background:rgba(0,0,0,.04);}
:root[data-theme="light"] .preview-md td{border-color:rgba(0,0,0,.08);}
:root[data-theme="light"] .msg-body td{border-color:rgba(0,0,0,.08);}
:root[data-theme="light"] .preview-badge.code{background:rgba(0,0,0,.05);}
:root[data-theme="light"] .ctx-ring-center{background:var(--bg);color:#5a544a;}
:root[data-theme="light"] .ctx-ring-track{stroke:rgba(0,0,0,.12);}
@@ -112,7 +115,7 @@
--input-bg:rgba(255,255,255,.03);--hover-bg:rgba(255,255,255,.05);
}
body{background:var(--bg);color:var(--text);height:100vh;height:100dvh;overflow:hidden;display:flex;}
.layout{display:flex;width:100%;height:100vh;height:100dvh;}
.layout{display:flex;width:100%;height:100vh;height:100dvh;min-height:0;}
.sidebar{width:300px;background:var(--sidebar);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:visible;flex-shrink:0;}
.sidebar-header{padding:16px 18px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;}
.logo{width:32px;height:32px;border-radius:9px;background:linear-gradient(145deg,#e8a030,var(--accent));display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;color:#fff;flex-shrink:0;box-shadow:0 2px 8px rgba(233,69,96,.3);}
@@ -127,10 +130,15 @@
.session-search input::placeholder{color:var(--muted);opacity:.7;}
/* Inline session title edit */
.session-title-input{flex:1;background:var(--surface);border:1px solid rgba(124,185,255,.6);border-radius:6px;color:var(--text);padding:3px 8px;font-size:13px;outline:none;min-width:0;box-shadow:0 0 0 2px rgba(124,185,255,.15);font-family:inherit;}
.session-item{padding:8px 40px 8px 8px;margin-bottom:2px;border-radius:8px;cursor:pointer;font-size:13px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background .15s,color .15s;display:flex;align-items:center;gap:6px;min-width:0;position:relative;}
.session-item{padding:8px 40px 8px 8px;margin-bottom:2px;border-radius:8px;cursor:pointer;font-size:13px;color:var(--muted);transition:background .15s,color .15s;display:flex;align-items:flex-start;gap:8px;min-width:0;position:relative;}
.session-item:hover{background:var(--hover-bg);color:var(--text);}
.session-item.active{background:rgba(232,160,48,0.12);color:#e8a030;}
.session-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.session-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;overflow:hidden;}
.session-title-row{display:flex;align-items:flex-start;gap:8px;min-width:0;}
.session-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text);}
.session-item.active .session-title{color:#e8a030;}
.session-time{flex-shrink:0;font-size:11px;line-height:1.4;color:var(--muted);text-transform:lowercase;}
.session-meta{font-size:11px;line-height:1.35;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
/* ── Session action trigger + dropdown ── */
.session-actions{position:absolute;right:6px;top:50%;transform:translateY(-50%);display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .15s ease;}
.session-item:hover .session-actions,.session-item:focus-within .session-actions,.session-item.menu-open .session-actions{opacity:1;pointer-events:auto;}
@@ -214,6 +222,15 @@
.onboarding-summary div{padding:14px;border-radius:14px;background:rgba(255,255,255,.03);border:1px solid var(--border);display:flex;flex-direction:column;gap:5px;}
.onboarding-summary strong{font-size:12px;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);}
.onboarding-summary span{font-size:13px;color:var(--text);word-break:break-word;}
.onboarding-oauth-card{display:flex;align-items:flex-start;gap:14px;padding:16px 18px;border-radius:14px;border:1px solid var(--border);background:rgba(255,255,255,.03);margin-bottom:4px;}
.onboarding-oauth-card p{margin:6px 0 0;font-size:13px;color:var(--muted);line-height:1.5;}
.onboarding-oauth-card strong{font-size:13px;color:var(--text);}
.onboarding-oauth-card code{font-size:12px;background:rgba(255,255,255,.08);padding:1px 5px;border-radius:4px;}
.onboarding-oauth-icon{font-size:18px;flex-shrink:0;margin-top:1px;}
.onboarding-oauth-ready{border-color:rgba(124,185,255,.28);background:rgba(124,185,255,.08);}
.onboarding-oauth-ready .onboarding-oauth-icon{color:#7cb9ff;}
.onboarding-oauth-pending{border-color:rgba(201,168,76,.25);background:rgba(201,168,76,.08);}
.onboarding-oauth-pending .onboarding-oauth-icon{color:#c9a84c;}
.onboarding-actions{display:flex;justify-content:space-between;gap:10px;margin-top:auto;}
.onboarding-actions .sm-btn{padding:10px 16px;}
.reconnect-banner{display:none;background:var(--surface);border:1px solid rgba(201,168,76,0.4);border-radius:10px;padding:10px 16px;margin:10px auto;max-width:780px;font-size:13px;color:var(--gold);display:none;align-items:center;justify-content:space-between;gap:12px;}
@@ -323,7 +340,7 @@
.sm-btn{flex:1;padding:8px 0;border-radius:8px;font-size:11px;font-weight:500;background:var(--input-bg);border:1px solid var(--border);color:var(--muted);cursor:pointer;transition:all .15s;text-align:center;letter-spacing:.02em;}
.sm-btn:hover{background:rgba(255,255,255,0.09);color:var(--text);border-color:rgba(255,255,255,.15);}
.sm-btn:disabled{opacity:.45;cursor:not-allowed;}
.main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0;background:var(--main-bg);}
.main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0;min-height:0;background:var(--main-bg);}
.topbar{padding:12px 20px;border-bottom:1px solid var(--border);background:var(--topbar-bg);backdrop-filter:blur(12px);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;position:relative;z-index:10;}
.topbar-title{font-size:15px;font-weight:600;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.topbar-meta{font-size:11px;color:var(--muted);margin-top:3px;opacity:.75;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
@@ -333,12 +350,23 @@
.workspace-toggle-btn.active{color:var(--blue);border-color:rgba(124,185,255,.35);background:rgba(124,185,255,.1);}
.workspace-toggle-btn:disabled{opacity:.38;cursor:not-allowed;}
.chip.model{color:var(--blue);border-color:rgba(124,185,255,0.35);background:rgba(124,185,255,0.1);}
.messages{flex:1;overflow-y:auto;display:flex;flex-direction:column;min-height:0;position:relative;z-index:0;}
.messages{flex:1;overflow-y:auto;display:flex;flex-direction:column;min-height:0;position:relative;z-index:0;-webkit-overflow-scrolling:touch;touch-action:pan-y;overscroll-behavior-y:contain;}
.messages-inner{margin:0 auto;width:100%;padding:20px 24px 32px;display:flex;flex-direction:column;}
@media(min-width:1400px){.messages-inner{max-width:1100px;}}
@media(min-width:1800px){.messages-inner{max-width:1200px;}}
.msg-row{padding:10px 0;}
.msg-row+.msg-row{border-top:none;}
/* Bubble layout (issue #336): opt-in chat-bubble look with user messages right-aligned
and assistant messages left-aligned. Uses :has() to tag rows by role without JS
changes. Full-width by default -- enabled via body.bubble-layout from settings. */
body.bubble-layout .msg-row:has(.msg-role.user){align-self:flex-end;max-width:75%;}
body.bubble-layout .msg-row:has(.msg-role.user) .msg-body{padding-left:0;padding-right:30px;max-width:none;}
body.bubble-layout .msg-row:has(.msg-role.user) .msg-role{flex-direction:row-reverse;}
body.bubble-layout .msg-row:has(.msg-role.assistant){align-self:flex-start;max-width:75%;}
@media(max-width:700px){
body.bubble-layout .msg-row:has(.msg-role.user),
body.bubble-layout .msg-row:has(.msg-role.assistant){max-width:92%;}
}
.msg-role{font-size:12px;font-weight:500;letter-spacing:.01em;margin-bottom:8px;display:flex;align-items:center;gap:8px;}
.msg-role.user{color:rgba(124,185,255,0.65);}
.msg-role.assistant{color:rgba(201,168,76,0.6);}
@@ -360,6 +388,16 @@
.msg-body blockquote{border-left:3px solid var(--blue);padding-left:14px;color:var(--muted);font-style:italic;margin:10px 0;}
.msg-body a{color:var(--blue);text-decoration:underline;}
.msg-body hr{border:none;border-top:1px solid var(--border);margin:14px 0;}
.msg-body table{border-collapse:collapse;width:100%;margin:8px 0;font-size:12px;}
.msg-body th{background:rgba(255,255,255,.07);padding:6px 10px;text-align:left;font-weight:600;border:1px solid var(--border2);}
.msg-body td{padding:5px 10px;border:1px solid rgba(255,255,255,.06);}
.msg-body tr:nth-child(even){background:rgba(255,255,255,.03);}
/* KaTeX math rendering */
.katex-block{display:block;text-align:center;margin:12px 0;overflow-x:auto;}
.katex-inline{display:inline;}
.katex-block .katex-html{text-align:center;}
.msg-body .katex{font-size:1.1em;}
.msg-body .katex-display{margin:8px 0;}
.msg-files{display:flex;flex-wrap:wrap;gap:6px;padding-left:30px;margin-bottom:10px;}
.msg-file-badge{display:flex;align-items:center;gap:5px;background:rgba(124,185,255,0.1);border:1px solid rgba(124,185,255,0.25);border-radius:6px;padding:4px 9px;font-size:12px;color:var(--blue);}
.thinking{display:flex;align-items:center;gap:5px;color:var(--muted);font-size:13px;padding-left:30px;}
@@ -457,6 +495,7 @@
.git-badge{font-size:9px;font-weight:600;color:var(--muted);background:var(--hover-bg);padding:2px 7px;border-radius:4px;letter-spacing:.02em;margin-left:auto;margin-right:4px;white-space:nowrap;font-family:'SF Mono',ui-monospace,monospace;}
.git-badge.dirty{color:var(--gold);background:rgba(201,168,76,.1);}
.panel-actions{display:flex;gap:4px;}
.mobile-close-btn{display:none;}
.panel-icon-btn{width:24px;height:24px;background:none;border:none;color:var(--muted);cursor:pointer;border-radius:5px;font-size:13px;display:flex;align-items:center;justify-content:center;transition:all .15s;}
.panel-icon-btn:hover{background:rgba(255,255,255,.08);color:var(--text);}
.panel-icon-btn:disabled{opacity:.35;cursor:not-allowed;}
@@ -524,7 +563,12 @@
.layout.workspace-panel-collapsed .rightpanel{width:0 !important;opacity:0;transform:translateX(14px);border-left-color:transparent;pointer-events:none;}
}
@media(max-width:900px){.rightpanel{display:none}.workspace-toggle-btn,.mobile-files-btn{display:inline-flex!important;}}
@media(max-width:900px){
.rightpanel{display:none}
.workspace-toggle-btn,.mobile-files-btn{display:inline-flex!important;}
.mobile-close-btn{display:flex;}
#btnCollapseWorkspacePanel{display:none;}
}
@media(max-width:640px){
/* ── Sidebar: slide-in overlay instead of hidden ── */

View File

@@ -1,7 +1,28 @@
const S={session:null,messages:[],entries:[],busy:false,pendingFiles:[],toolCalls:[],activeStreamId:null,currentDir:'.',activeProfile:'default'};
const INFLIGHT={}; // keyed by session_id while request in-flight
const MSG_QUEUE=[]; // messages queued while a request is in-flight
const SESSION_QUEUES={}; // keyed by session_id for queued follow-up turns
const $=id=>document.getElementById(id);
function _getSessionQueue(sid, create=false){
if(!sid) return [];
if(!SESSION_QUEUES[sid]&&create) SESSION_QUEUES[sid]=[];
return SESSION_QUEUES[sid]||[];
}
function queueSessionMessage(sid, payload){
if(!sid||!payload) return 0;
const q=_getSessionQueue(sid,true);
q.push(payload);
return q.length;
}
function shiftQueuedSessionMessage(sid){
const q=_getSessionQueue(sid,false);
if(!q.length) return null;
const next=q.shift();
if(!q.length) delete SESSION_QUEUES[sid];
return next;
}
function getQueuedSessionCount(sid){
return _getSessionQueue(sid,false).length;
}
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
// Dynamic model labels -- populated by populateModelDropdown(), fallback to static map
@@ -68,6 +89,9 @@ async function populateModelDropdown(){
_applyModelToDropdown(data.default_model, sel);
}
if(typeof syncModelChip==='function') syncModelChip();
// Kick off a background live-model fetch for the active provider.
// This runs after the static list is already shown (no blocking flicker).
if(data.active_provider) _fetchLiveModels(data.active_provider, sel);
}catch(e){
// API unavailable -- keep the hardcoded HTML options as fallback
console.warn('Failed to load models from server:',e.message);
@@ -75,6 +99,60 @@ async function populateModelDropdown(){
}
}
// Cache so we don't re-fetch on every page load
const _liveModelCache={};
async function _fetchLiveModels(provider, sel){
if(!provider||!sel) return;
// Don't fetch for providers where we know it's unsupported or unnecessary
// All providers now supported via agent's provider_model_ids() — no exclusions needed
if(_liveModelCache[provider]) return; // already fetched this session
try{
const url=new URL('/api/models/live',location.origin);
url.searchParams.set('provider',provider);
const data=await fetch(url.href,{credentials:'include'}).then(r=>r.json());
if(!data.models||!data.models.length) return;
_liveModelCache[provider]=data.models;
// Remember current selection before rebuilding options
const currentVal=sel.value;
// Rebuild the optgroup for this provider with live models
// Keep other providers' optgroups intact
let providerGroup=null;
for(const og of sel.querySelectorAll('optgroup')){
if(og.label&&og.label.toLowerCase().includes(provider.toLowerCase())){
providerGroup=og; break;
}
}
if(!providerGroup){
// No existing group — add a new one
providerGroup=document.createElement('optgroup');
providerGroup.label=provider.charAt(0).toUpperCase()+provider.slice(1)+' (live)';
sel.appendChild(providerGroup);
}
// Rebuild options from live data
const existingIds=new Set([...sel.options].map(o=>o.value));
let added=0;
for(const m of data.models){
if(existingIds.has(m.id)) continue; // already shown from static list
const opt=document.createElement('option');
opt.value=m.id;
opt.textContent=m.label||m.id;
opt.title='Live model — fetched from provider';
providerGroup.appendChild(opt);
_dynamicModelLabels[m.id]=m.label||m.id;
added++;
}
if(added>0){
// Restore selection
if(currentVal) _applyModelToDropdown(currentVal, sel);
if(typeof syncModelChip==='function') syncModelChip();
console.log('[hermes] Live models loaded for',provider+':',added,'new models added');
}
}catch(e){
console.debug('[hermes] Live model fetch failed for',provider,e.message);
}
}
/**
* Check if the given model ID belongs to a different provider than the one
* currently configured in Hermes. Returns a warning string if mismatched,
@@ -304,8 +382,21 @@ function renderMd(raw){
// Only runs OUTSIDE fenced code blocks and backtick spans (stash + restore).
// Unsafe tags (anything not in the allowlist) are left as-is and will be
// HTML-escaped by esc() when they reach an innerHTML assignment -- no XSS risk.
// Fence stash: protect code blocks and backtick spans from all further processing
// Must run BEFORE math_stash so $..$ inside code spans is not extracted as math
const fence_stash=[];
s=s.replace(/(```[\s\S]*?```|`[^`\n]+`)/g,m=>{fence_stash.push(m);return '\x00F'+(fence_stash.length-1)+'\x00';});
// Math stash: protect $$..$$ and $..$ from markdown processing
// Runs AFTER fence_stash so backtick code spans protect their dollar-sign contents
const math_stash=[];
// Display math: $$...$$ (must come before inline to avoid mis-parsing)
s=s.replace(/\$\$([\s\S]+?)\$\$/g,(_,m)=>{math_stash.push({type:'display',src:m});return '\x00M'+(math_stash.length-1)+'\x00';});
// Inline math: $...$ — require non-space at boundaries to avoid false positives
// e.g. "costs $5 and $10" should not trigger (space after opening $)
s=s.replace(/\$([^\s$\n][^$\n]*?[^\s$\n]|\S)\$/g,(_,m)=>{math_stash.push({type:'inline',src:m});return '\x00M'+(math_stash.length-1)+'\x00';});
// Also stash \(...\) and \[...\] LaTeX delimiters
s=s.replace(/\\\\\((.+?)\\\\\)/g,(_,m)=>{math_stash.push({type:'inline',src:m});return '\x00M'+(math_stash.length-1)+'\x00';});
s=s.replace(/\\\\\[(.+?)\\\\\]/gs,(_,m)=>{math_stash.push({type:'display',src:m});return '\x00M'+(math_stash.length-1)+'\x00';});
// Safe tag → markdown equivalent (these produce the same output as **text** etc.)
s=s.replace(/<strong>([\s\S]*?)<\/strong>/gi,(_,t)=>'**'+t+'**');
s=s.replace(/<b>([\s\S]*?)<\/b>/gi,(_,t)=>'**'+t+'**');
@@ -331,6 +422,7 @@ function renderMd(raw){
t=t.replace(/\*([^*\n]+)\*/g,(_,x)=>`<em>${esc(x)}</em>`);
t=t.replace(/`([^`\n]+)`/g,(_,x)=>`<code>${esc(x)}</code>`);
t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,(_,lb,u)=>`<a href="${esc(u)}" target="_blank" rel="noopener">${esc(lb)}</a>`);
t=t.replace(/(https?:\/\/[^\s<>"')\]]+)/g,(url)=>{const trail=url.match(/[.,;:!?)]$/)?url.slice(-1):'';const clean=trail?url.slice(0,-1):url;return `<a href="${esc(clean)}" target="_blank" rel="noopener">${esc(clean)}</a>${trail}`;});
// Escape any plain text that isn't already wrapped in a tag we produced
// by escaping bare < > that aren't part of our own tags
const SAFE_INLINE=/^<\/?(strong|em|code|a)([\s>]|$)/i;
@@ -381,8 +473,24 @@ function renderMd(raw){
// Our pipeline only emits: <strong>,<em>,<code>,<pre>,<h1-6>,<ul>,<ol>,<li>,
// <table>,<thead>,<tbody>,<tr>,<th>,<td>,<hr>,<blockquote>,<p>,<br>,<a>,
// <div class="..."> (mermaid/pre-header). Everything else is untrusted input.
const SAFE_TAGS=/^<\/?(strong|em|code|pre|h[1-6]|ul|ol|li|table|thead|tbody|tr|th|td|hr|blockquote|p|br|a|div)([\s>]|$)/i;
const SAFE_TAGS=/^<\/?(strong|em|code|pre|h[1-6]|ul|ol|li|table|thead|tbody|tr|th|td|hr|blockquote|p|br|a|div|span)([\s>]|$)/i;
s=s.replace(/<\/?[a-z][^>]*>/gi,tag=>SAFE_TAGS.test(tag)?tag:esc(tag));
// Autolink: convert plain URLs to clickable links (not inside existing <a> tags, not in code)
s=s.replace(/(https?:\/\/[^\s<>"')\]]+)/g,(url)=>{
// Strip trailing punctuation that was likely not part of the URL
const trail=url.match(/[.,;:!?)]$/)?url.slice(-1):'';
const clean=trail?url.slice(0,-1):url;
return `<a href="${esc(clean)}" target="_blank" rel="noopener">${esc(clean)}</a>${trail}`;
});
// Restore math stash → katex placeholder spans/divs
// These will be rendered by renderKatexBlocks() after DOM insertion
s=s.replace(/\x00M(\d+)\x00/g,(_,i)=>{
const item=math_stash[+i];
if(item.type==='display'){
return `<div class="katex-block" data-katex="display">${esc(item.src)}</div>`;
}
return `<span class="katex-inline" data-katex="inline">${esc(item.src)}</span>`;
});
const parts=s.split(/\n{2,}/);
s=parts.map(p=>{p=p.trim();if(!p)return '';if(/^<(h[1-6]|ul|ol|pre|hr|blockquote)/.test(p))return p;return `<p>${p.replace(/\n/g,'<br>')}</p>`;}).join('\n');
return s;
@@ -426,28 +534,37 @@ function setBusy(v){
setComposerStatus('');
// Always hide Cancel button when not busy
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
updateQueueBadge();
// Drain one queued message after UI settles
if(MSG_QUEUE.length>0){
const next=MSG_QUEUE.shift();
updateQueueBadge();
setTimeout(()=>{ $('msg').value=next; send(); }, 120);
const sid=S.session&&S.session.session_id;
updateQueueBadge(sid);
// Drain one queued message for the currently viewed session after UI settles
const next=sid?shiftQueuedSessionMessage(sid):null;
if(next){
updateQueueBadge(sid);
setTimeout(()=>{
$('msg').value=next.text||'';
S.pendingFiles=Array.isArray(next.files)?[...next.files]:[];
autoResize();
renderTray();
send();
},120);
}
}
}
function updateQueueBadge(){
function updateQueueBadge(sessionId){
const sid=sessionId||(S.session&&S.session.session_id);
const count=sid?getQueuedSessionCount(sid):0;
let badge=$('queueBadge');
if(MSG_QUEUE.length>0){
if(count>0){
if(!badge){
badge=document.createElement('div');
badge.id='queueBadge';
badge.style.cssText='position:fixed;bottom:80px;right:24px;background:rgba(124,185,255,.18);border:1px solid rgba(124,185,255,.4);color:var(--blue);font-size:12px;font-weight:600;padding:6px 14px;border-radius:20px;z-index:50;pointer-events:none;backdrop-filter:blur(8px);';
document.body.appendChild(badge);
}
badge.textContent=MSG_QUEUE.length===1?'1 message queued':`${MSG_QUEUE.length} messages queued`;
} else {
if(badge) badge.remove();
badge.textContent=count===1?'1 message queued':`${count} messages queued`;
} else if(badge) {
badge.remove();
}
}
function showToast(msg,ms){const el=$('toast');el.textContent=msg;el.classList.add('show');clearTimeout(el._t);el._t=setTimeout(()=>el.classList.remove('show'),ms||2800);}
@@ -606,6 +723,47 @@ function copyMsg(btn){
// ── Reconnect banner (B4/B5: reload resilience) ──
const INFLIGHT_KEY = 'hermes-webui-inflight'; // localStorage key for in-flight session tracking
const INFLIGHT_STATE_KEY = 'hermes-webui-inflight-state'; // localStorage snapshots for mid-stream reload recovery
function _readInflightStateMap(){
try{
const raw=localStorage.getItem(INFLIGHT_STATE_KEY);
const parsed=raw?JSON.parse(raw):{};
return parsed&&typeof parsed==='object'?parsed:{};
}catch(_){
return {};
}
}
function saveInflightState(sid, state){
if(!sid||!state) return;
try{
const all=_readInflightStateMap();
all[sid]={...state,updated_at:Date.now()};
localStorage.setItem(INFLIGHT_STATE_KEY, JSON.stringify(all));
}catch(_){ }
}
function loadInflightState(sid, streamId){
if(!sid) return null;
const all=_readInflightStateMap();
const entry=all[sid];
if(!entry) return null;
if(streamId&&entry.streamId&&entry.streamId!==streamId) return null;
if(entry.updated_at&&Date.now()-entry.updated_at>10*60*1000){
clearInflightState(sid);
return null;
}
return entry;
}
function clearInflightState(sid){
if(!sid) return;
try{
const all=_readInflightStateMap();
if(!(sid in all)) return;
delete all[sid];
if(Object.keys(all).length) localStorage.setItem(INFLIGHT_STATE_KEY, JSON.stringify(all));
else localStorage.removeItem(INFLIGHT_STATE_KEY);
}catch(_){ }
}
function markInflight(sid, streamId) {
localStorage.setItem(INFLIGHT_KEY, JSON.stringify({sid, streamId, ts: Date.now()}));
@@ -627,11 +785,11 @@ async function refreshSession() {
try {
const data = await api(`/api/session?session_id=${encodeURIComponent(S.session.session_id)}`);
S.session = data.session;
S.messages = (data.session.messages || []).filter(m => {
if (!m || !m.role || m.role === 'tool') return false;
if (m.role === 'assistant') { let c = m.content || ''; if (Array.isArray(c)) c = c.map(p => p.text||'').join(''); return String(c).trim().length > 0; }
return true;
});
S.messages = data.session.messages || [];
const pendingMsg=getPendingSessionMessage(data.session);
if(pendingMsg) S.messages.push(pendingMsg);
S.activeStreamId=data.session.active_stream_id||null;
syncTopbar(); renderMessages();
showToast('Conversation refreshed');
} catch(e) { setStatus('Refresh failed: ' + e.message); }
@@ -677,12 +835,34 @@ async function applyUpdates(){
}
}
function getPendingSessionMessage(session){
const text=String(session?.pending_user_message||'').trim();
if(!text) return null;
const attachments=Array.isArray(session?.pending_attachments)?session.pending_attachments.filter(Boolean):[];
const messages=Array.isArray(session?.messages)?session.messages:[];
const lastUser=[...messages].reverse().find(m=>m&&m.role==='user');
if(lastUser){
const lastText=String(msgContent(lastUser)||'').trim();
if(lastText===text){
if(attachments.length&&!lastUser.attachments?.length) lastUser.attachments=attachments;
return null;
}
}
return {
role:'user',
content:text,
attachments:attachments.length?attachments:undefined,
_ts:session?.pending_started_at||Date.now()/1000,
_pending:true,
};
}
async function checkInflightOnBoot(sid) {
const raw = localStorage.getItem(INFLIGHT_KEY);
if (!raw) return;
try {
const {sid: inflightSid, streamId, ts} = JSON.parse(raw);
if (inflightSid !== sid) { clearInflight(); return; }
if (S.activeStreamId && S.activeStreamId === streamId) return;
// Only show banner if the in-flight entry is less than 10 minutes old
if (Date.now() - ts > 10 * 60 * 1000) { clearInflight(); return; }
// Check if stream is still active
@@ -801,19 +981,20 @@ function renderMessages(){
if(!thinkingText && m.reasoning){
thinkingText=m.reasoning;
}
// Parse inline thinking tags from plain text: <think>...</think> (DeepSeek, QwQ, etc.)
// Parse inline thinking tags from plain text: <think>...</think> (DeepSeek, QwQ, MiniMax, etc.)
// and Gemma 4 channel tokens: <|channel>thought\n...<channel|>
// Note: no ^ anchor — some models emit leading whitespace/newlines before <think>.
if(!thinkingText && typeof content==='string'){
const thinkMatch=content.match(/^<think>([\s\S]*?)<\/think>\s*/);
const thinkMatch=content.match(/<think>([\s\S]*?)<\/think>/);
if(thinkMatch){
thinkingText=thinkMatch[1].trim();
content=content.slice(thinkMatch[0].length);
content=content.replace(/<think>[\s\S]*?<\/think>\s*/,'').trimStart();
}
if(!thinkingText){
const gemmaMatch=content.match(/^<\|channel>thought\n([\s\S]*?)<channel\|>\s*/);
const gemmaMatch=content.match(/<\|channel>thought\n([\s\S]*?)<channel\|>/);
if(gemmaMatch){
thinkingText=gemmaMatch[1].trim();
content=content.slice(gemmaMatch[0].length);
content=content.replace(/<\|channel>thought\n[\s\S]*?<channel\|>\s*/,'').trimStart();
}
}
}
@@ -827,6 +1008,7 @@ function renderMessages(){
}
const row=document.createElement('div');row.className='msg-row';
row.dataset.msgIdx=rawIdx;row.dataset.role=m.role||'assistant';
if(m._live) row.setAttribute('data-live-assistant','1');
let filesHtml='';
if(m.attachments&&m.attachments.length)
filesHtml=`<div class="msg-files">${m.attachments.map(f=>`<div class="msg-file-badge">${li('paperclip',12)} ${esc(f)}</div>`).join('')}</div>`;
@@ -954,7 +1136,7 @@ function renderMessages(){
}
scrollToBottom();
// Apply syntax highlighting after DOM is built
requestAnimationFrame(()=>{highlightCode();addCopyButtons();renderMermaidBlocks();});
requestAnimationFrame(()=>{highlightCode();addCopyButtons();renderMermaidBlocks();renderKatexBlocks();});
// Refresh todo panel if it's currently open
if(typeof loadTodos==='function' && document.getElementById('panelTodos') && document.getElementById('panelTodos').classList.contains('active')){
loadTodos();
@@ -1228,12 +1410,70 @@ function renderMermaidBlocks(){
});
}
function appendThinking(){
$('emptyState').style.display='none';
const row=document.createElement('div');row.className='msg-row';row.id='thinkingRow';
row.innerHTML=`<div class="msg-role assistant"><div class="role-icon assistant">H</div>Hermes</div><div class="thinking"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>`;
$('msgInner').appendChild(row);scrollToBottom();
let _katexLoading=false;
let _katexReady=false;
function renderKatexBlocks(){
const blocks=document.querySelectorAll('.katex-block:not([data-rendered]),.katex-inline:not([data-rendered])');
if(!blocks.length) return;
if(!_katexReady){
if(!_katexLoading){
_katexLoading=true;
const script=document.createElement('script');
script.src='https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js';
script.integrity='sha384-cMkvdD8LoxVzGF/RPUKAcvmm49FQ0oxwDF3BGKtDXcEc+T1b2N+teh/OJfpU0jr6';
script.crossOrigin='anonymous';
script.onload=()=>{
if(typeof katex!=='undefined'){
_katexReady=true;
renderKatexBlocks();
}
};
document.head.appendChild(script);
}
return;
}
blocks.forEach(el=>{
el.dataset.rendered='true';
const src=el.textContent||'';
const displayMode=el.dataset.katex==='display';
try{
katex.render(src,el,{
displayMode,
throwOnError:false,
trust:false,
strict:'ignore',
});
}catch(e){
// Leave as raw text in a code span on failure
el.outerHTML=`<code>${esc(src)}</code>`;
}
});
}
function _thinkingMarkup(text=''){
const _bn=window._botName||'Hermes';
const icon=esc(_bn.charAt(0).toUpperCase());
const label=esc(_bn);
const body=(text&&String(text).trim())
? `<div class="thinking-card open"><div class="thinking-card-header"><span class="thinking-card-icon">${li('lightbulb',14)}</span><span class="thinking-card-label">${t('thinking')}</span></div><div class="thinking-card-body"><pre>${esc(String(text).trim())}</pre></div></div>`
: `<div class="thinking"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>`;
return `<div class="msg-role assistant"><div class="role-icon assistant">${icon}</div>${label}</div>${body}`;
}
function appendThinking(text=''){
$('emptyState').style.display='none';
let row=$('thinkingRow');
if(!row){
row=document.createElement('div');
row.className='msg-row';
row.id='thinkingRow';
$('msgInner').appendChild(row);
}
row.className=(text&&String(text).trim())?'msg-row thinking-card-row':'msg-row';
row.innerHTML=_thinkingMarkup(text);
scrollToBottom();
}
function updateThinking(text=''){appendThinking(text);}
function removeThinking(){const el=$('thinkingRow');if(el)el.remove();}
function fileIcon(name, type){

View File

@@ -150,7 +150,7 @@ async function toggleEditMode(){
_previewDirty=false;
// Update read-only views
if(_previewCurrentMode==='code') $('previewCode').textContent=content;
else $('previewMd').innerHTML=renderMd(content);
else { $('previewMd').innerHTML=renderMd(content); requestAnimationFrame(()=>{if(typeof renderKatexBlocks==='function')renderKatexBlocks();}); }
$('previewEditArea').style.display='none';
if(_previewCurrentMode==='code') $('previewCode').style.display='';
else $('previewMd').style.display='';
@@ -215,6 +215,7 @@ async function openFile(path){
showPreview('md');
_previewRawContent = data.content;
$('previewMd').innerHTML=renderMd(data.content);
requestAnimationFrame(()=>{if(typeof renderKatexBlocks==='function')renderKatexBlocks();});
}catch(e){setStatus(t('file_open_failed'));}
} else {
// Plain code / text -- but fall back to download if server signals binary

View File

@@ -0,0 +1,103 @@
import json
from pathlib import Path
import api.config as config
def test_resolve_default_workspace_falls_back_to_existing_home_work(monkeypatch, tmp_path):
preferred = tmp_path / "work"
preferred.mkdir()
state_dir = tmp_path / "state"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
resolved = config.resolve_default_workspace("/definitely/not/usable")
assert resolved == preferred.resolve()
def test_save_settings_rewrites_bad_default_workspace_to_fallback(monkeypatch, tmp_path):
preferred = tmp_path / "work"
preferred.mkdir()
state_dir = tmp_path / "state"
settings_file = tmp_path / "settings.json"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
monkeypatch.setattr(config, "SETTINGS_FILE", settings_file)
monkeypatch.setattr(config, "DEFAULT_WORKSPACE", preferred)
saved = config.save_settings({"default_workspace": "/definitely/not/usable"})
on_disk = json.loads(settings_file.read_text(encoding="utf-8"))
assert saved["default_workspace"] == str(preferred.resolve())
assert on_disk["default_workspace"] == str(preferred.resolve())
def test_resolve_default_workspace_creates_home_workspace_when_missing(monkeypatch, tmp_path):
"""When no preferred dir exists, resolve falls back to creating ~/workspace."""
state_dir = tmp_path / "state"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
# Neither ~/work nor ~/workspace exists yet
resolved = config.resolve_default_workspace(None)
assert resolved == (tmp_path / "workspace").resolve()
assert resolved.is_dir()
def test_resolve_default_workspace_raises_when_all_candidates_fail(monkeypatch, tmp_path):
"""RuntimeError is raised when every candidate is unwritable."""
import stat, pytest
# Make tmp_path read-only so mkdir inside it fails
tmp_path.chmod(stat.S_IRUSR | stat.S_IXUSR)
state_dir = tmp_path / "state"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
monkeypatch.delenv("HERMES_WEBUI_DEFAULT_WORKSPACE", raising=False)
try:
with pytest.raises(RuntimeError, match="Could not create or access"):
config.resolve_default_workspace(None)
finally:
tmp_path.chmod(stat.S_IRWXU) # restore for cleanup
def test_workspace_candidates_deduplicates_home_workspace(monkeypatch, tmp_path):
"""~/workspace must appear at most once in the candidates list even if it exists."""
ws = tmp_path / "workspace"
ws.mkdir()
state_dir = tmp_path / "state"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
monkeypatch.delenv("HERMES_WEBUI_DEFAULT_WORKSPACE", raising=False)
candidates = config._workspace_candidates(None)
paths = [str(p) for p in candidates]
assert paths.count(str(ws.resolve())) <= 1, "~/workspace must not appear twice"
def test_env_var_workspace_takes_priority_over_passed_raw(monkeypatch, tmp_path):
"""HERMES_WEBUI_DEFAULT_WORKSPACE env var overrides a None raw arg but not a valid one."""
env_ws = tmp_path / "env_workspace"
env_ws.mkdir()
state_dir = tmp_path / "state"
monkeypatch.setattr(config, "HOME", tmp_path)
monkeypatch.setattr(config, "STATE_DIR", state_dir)
monkeypatch.setenv("HERMES_WEBUI_DEFAULT_WORKSPACE", str(env_ws))
# When raw is None, env var should be used
resolved = config.resolve_default_workspace(None)
assert resolved == env_ws.resolve()
def test_ensure_workspace_dir_returns_false_for_unwritable_path(monkeypatch, tmp_path):
"""_ensure_workspace_dir returns False for a path that can't be created."""
import stat
# Make parent read-only so mkdir fails
parent = tmp_path / "ro_parent"
parent.mkdir()
parent.chmod(stat.S_IRUSR | stat.S_IXUSR)
try:
result = config._ensure_workspace_dir(parent / "child")
assert result is False
finally:
parent.chmod(stat.S_IRWXU)

View File

@@ -275,6 +275,64 @@ def test_gateway_session_messages_readable():
post('/api/settings', {'show_cli_sessions': False})
def test_importing_older_gateway_session_preserves_original_timestamps_and_order():
"""Importing an older gateway session should not bump it above newer WebUI sessions."""
conn = _ensure_state_db()
older_started_at = time.time() - 1800
imported_sid = 'gw_import_old_001'
newer_webui_sid = None
try:
newer_webui, status = post('/api/session/new', {'model': 'openai/gpt-5'})
assert status == 200, newer_webui
newer_webui_sid = newer_webui['session']['session_id']
rename, rename_status = post(
'/api/session/rename',
{'session_id': newer_webui_sid, 'title': 'Newer WebUI Session'},
)
assert rename_status == 200, rename
_insert_gateway_session(
conn,
session_id=imported_sid,
source='discord',
title='Older imported gateway session',
started_at=older_started_at,
)
post('/api/settings', {'show_cli_sessions': True})
imported, imported_status = post('/api/session/import_cli', {'session_id': imported_sid})
assert imported_status == 200, imported
imported_session = imported['session']
assert abs(imported_session['created_at'] - older_started_at) < 2, imported_session
assert abs(imported_session['updated_at'] - older_started_at) < 5, imported_session
sessions_payload, sessions_status = get('/api/sessions')
assert sessions_status == 200, sessions_payload
ordered_ids = [item['session_id'] for item in sessions_payload.get('sessions', [])]
assert newer_webui_sid in ordered_ids, ordered_ids
assert imported_sid in ordered_ids, ordered_ids
assert ordered_ids.index(newer_webui_sid) < ordered_ids.index(imported_sid), ordered_ids
finally:
try:
_remove_test_sessions(conn, imported_sid)
conn.close()
except Exception:
pass
if imported_sid:
try:
post('/api/session/delete', {'session_id': imported_sid})
except Exception:
pass
if newer_webui_sid:
try:
post('/api/session/delete', {'session_id': newer_webui_sid})
except Exception:
pass
post('/api/settings', {'show_cli_sessions': False})
def test_gateway_sse_stream_endpoint_exists():
"""GET /api/sessions/gateway/stream returns a response (200 or 200-range)."""
# The SSE endpoint requires show_cli_sessions to be enabled

322
tests/test_issue336.py Normal file
View File

@@ -0,0 +1,322 @@
"""
Tests for issue #336 — opt-in chat bubble layout (PR #398).
Covers:
- api/config.py: bubble_layout present in _SETTINGS_DEFAULTS with default False
- api/config.py: bubble_layout present in _SETTINGS_BOOL_KEYS
- api/config.py: bubble_layout not in password-filtered keys (safe to expose)
- static/boot.js: boot path applies bubble-layout class from settings
- static/boot.js: catch path removes bubble-layout class on API failure
- static/panels.js: loadSettingsPanel reads bubble_layout checkbox
- static/panels.js: saveSettings writes bubble_layout and toggles body class
- static/style.css: body.bubble-layout CSS selectors present
- static/style.css: responsive max-width rule for bubble layout
- static/index.html: settingsBubbleLayout checkbox element present
- static/index.html: i18n keys wired on label and description
- static/i18n.js: English label and description keys present
- static/i18n.js: Spanish label and description keys present
- Integration: bubble_layout default is False in GET /api/settings
- Integration: bubble_layout persists via POST /api/settings
- Integration: non-bool value is coerced to bool on POST
"""
import json
import pathlib
import re
import unittest
import urllib.error
import urllib.request
REPO_ROOT = pathlib.Path(__file__).parent.parent
CONFIG_PY = (REPO_ROOT / "api" / "config.py").read_text()
BOOT_JS = (REPO_ROOT / "static" / "boot.js").read_text()
PANELS_JS = (REPO_ROOT / "static" / "panels.js").read_text()
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text()
INDEX_HTML = (REPO_ROOT / "static" / "index.html").read_text()
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text()
BASE = "http://127.0.0.1:8788"
def _get(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return json.loads(r.read()), r.status
def _post(path, body=None):
data = json.dumps(body or {}).encode()
req = urllib.request.Request(
BASE + path, data=data, headers={"Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read()), r.status
except urllib.error.HTTPError as e:
return json.loads(e.read()), e.code
# ── config.py static checks ───────────────────────────────────────────────
class TestBubbleLayoutConfig(unittest.TestCase):
"""Verify bubble_layout is correctly registered in config.py."""
def test_bubble_layout_in_settings_defaults(self):
"""bubble_layout must appear in _SETTINGS_DEFAULTS."""
self.assertIn(
'"bubble_layout"',
CONFIG_PY,
"bubble_layout key missing from _SETTINGS_DEFAULTS in api/config.py",
)
def test_bubble_layout_default_is_false(self):
"""bubble_layout default value must be False (opt-in, off by default)."""
# Match "bubble_layout": False with optional spacing
self.assertRegex(
CONFIG_PY,
r'"bubble_layout"\s*:\s*False',
"bubble_layout default must be False in _SETTINGS_DEFAULTS",
)
def test_bubble_layout_in_bool_keys(self):
"""bubble_layout must be in _SETTINGS_BOOL_KEYS for coercion."""
# Find the _SETTINGS_BOOL_KEYS block and verify membership
bool_keys_match = re.search(
r"_SETTINGS_BOOL_KEYS\s*=\s*\{([^}]+)\}", CONFIG_PY, re.DOTALL
)
self.assertIsNotNone(
bool_keys_match, "_SETTINGS_BOOL_KEYS block not found in config.py"
)
self.assertIn(
'"bubble_layout"',
bool_keys_match.group(1),
"bubble_layout missing from _SETTINGS_BOOL_KEYS",
)
# ── boot.js static checks ────────────────────────────────────────────────
class TestBubbleLayoutBootJS(unittest.TestCase):
"""Verify bubble-layout class management in boot.js."""
def test_boot_applies_bubble_layout_class(self):
"""boot.js success path must toggle body.bubble-layout from settings."""
self.assertIn(
"classList.toggle('bubble-layout',!!s.bubble_layout)",
BOOT_JS,
"boot.js must call classList.toggle('bubble-layout', ...) on settings load",
)
def test_boot_catch_removes_bubble_layout_class(self):
"""boot.js catch path must remove bubble-layout (default off on API failure)."""
self.assertIn(
"classList.remove('bubble-layout')",
BOOT_JS,
"boot.js catch block must call classList.remove('bubble-layout') on API failure",
)
# ── panels.js static checks ──────────────────────────────────────────────
class TestBubbleLayoutPanelsJS(unittest.TestCase):
"""Verify settings panel wires the bubble_layout checkbox."""
def test_load_settings_reads_bubble_layout_checkbox(self):
"""loadSettingsPanel must read the settingsBubbleLayout checkbox state."""
self.assertIn(
"settingsBubbleLayout",
PANELS_JS,
"panels.js must reference settingsBubbleLayout checkbox",
)
def test_save_settings_writes_bubble_layout(self):
"""saveSettings must write body.bubble_layout from the checkbox."""
self.assertIn(
"body.bubble_layout",
PANELS_JS,
"saveSettings must set body.bubble_layout from checkbox",
)
def test_save_settings_toggles_body_class(self):
"""saveSettings must apply body class toggle for live preview."""
self.assertIn(
"classList.toggle('bubble-layout', body.bubble_layout)",
PANELS_JS,
"saveSettings must toggle 'bubble-layout' on document.body for live preview",
)
# ── style.css static checks ──────────────────────────────────────────────
class TestBubbleLayoutCSS(unittest.TestCase):
"""Verify CSS selectors for bubble layout are present and gated on body class."""
def test_user_row_right_align_selector_present(self):
"""CSS must right-align user message rows when bubble-layout is active."""
self.assertIn(
"body.bubble-layout .msg-row:has(.msg-role.user)",
STYLE_CSS,
"CSS selector for user bubble alignment missing from style.css",
)
def test_assistant_row_left_align_selector_present(self):
"""CSS must left-align assistant message rows when bubble-layout is active."""
self.assertIn(
"body.bubble-layout .msg-row:has(.msg-role.assistant)",
STYLE_CSS,
"CSS selector for assistant bubble alignment missing from style.css",
)
def test_bubble_layout_responsive_rule_present(self):
"""A responsive max-width rule for narrow screens must be present."""
# Both selectors must appear inside a @media block
self.assertRegex(
STYLE_CSS,
r"@media\([^)]*700px[^)]*\)[^{]*\{[^}]*bubble-layout",
"Responsive bubble-layout rule (700px breakpoint) missing from style.css",
)
# ── index.html static checks ─────────────────────────────────────────────
class TestBubbleLayoutHTML(unittest.TestCase):
"""Verify the settings checkbox is present and correctly wired in index.html."""
def test_settings_checkbox_present(self):
"""The settingsBubbleLayout checkbox must exist in index.html."""
self.assertIn(
'id="settingsBubbleLayout"',
INDEX_HTML,
"settingsBubbleLayout checkbox missing from index.html",
)
def test_settings_label_i18n_key_wired(self):
"""Label span must carry the settings_label_bubble_layout i18n key."""
self.assertIn(
'data-i18n="settings_label_bubble_layout"',
INDEX_HTML,
"settings_label_bubble_layout i18n key not wired on label span",
)
def test_settings_desc_i18n_key_wired(self):
"""Description div must carry the settings_desc_bubble_layout i18n key."""
self.assertIn(
'data-i18n="settings_desc_bubble_layout"',
INDEX_HTML,
"settings_desc_bubble_layout i18n key not wired on description div",
)
# ── i18n.js static checks ────────────────────────────────────────────────
class TestBubbleLayoutI18N(unittest.TestCase):
"""Verify English and Spanish locale keys are present in i18n.js."""
def _extract_locale_block(self, lang_start_marker, lang_end_marker):
"""Extract the content between two locale markers."""
start = I18N_JS.find(lang_start_marker)
end = I18N_JS.find(lang_end_marker, start)
self.assertGreater(start, -1, f"Start marker '{lang_start_marker}' not found")
self.assertGreater(end, start, f"End marker '{lang_end_marker}' not found after start")
return I18N_JS[start:end]
def test_english_label_key_present(self):
"""English locale must have settings_label_bubble_layout."""
en_block = self._extract_locale_block("\n en: {", "\n es: {")
self.assertIn(
"settings_label_bubble_layout",
en_block,
"settings_label_bubble_layout missing from English locale",
)
def test_english_desc_key_present(self):
"""English locale must have settings_desc_bubble_layout."""
en_block = self._extract_locale_block("\n en: {", "\n es: {")
self.assertIn(
"settings_desc_bubble_layout",
en_block,
"settings_desc_bubble_layout missing from English locale",
)
def test_spanish_label_key_present(self):
"""Spanish locale must have settings_label_bubble_layout."""
es_block = self._extract_locale_block("\n es: {", "\n de: {")
self.assertIn(
"settings_label_bubble_layout",
es_block,
"settings_label_bubble_layout missing from Spanish locale",
)
def test_spanish_desc_key_present(self):
"""Spanish locale must have settings_desc_bubble_layout."""
es_block = self._extract_locale_block("\n es: {", "\n de: {")
self.assertIn(
"settings_desc_bubble_layout",
es_block,
"settings_desc_bubble_layout missing from Spanish locale",
)
# ── Integration tests (require live server on port 8788) ─────────────────
class TestBubbleLayoutSettingsAPI(unittest.TestCase):
"""Integration tests: bubble_layout via GET/POST /api/settings."""
def test_bubble_layout_default_is_false(self):
"""GET /api/settings must return bubble_layout: false by default."""
try:
d, status = _get("/api/settings")
except OSError:
self.skipTest("Server not running on port 8788")
self.assertEqual(status, 200)
self.assertIn(
"bubble_layout",
d,
"bubble_layout missing from GET /api/settings response",
)
self.assertFalse(
d["bubble_layout"],
"bubble_layout default must be False (opt-in feature)",
)
def test_bubble_layout_persists_true(self):
"""POST /api/settings with bubble_layout:true must persist and round-trip."""
try:
_, status = _post("/api/settings", {"bubble_layout": True})
except OSError:
self.skipTest("Server not running on port 8788")
self.assertEqual(status, 200)
d, _ = _get("/api/settings")
self.assertTrue(d["bubble_layout"], "bubble_layout=True must persist after POST")
# Restore
_post("/api/settings", {"bubble_layout": False})
def test_bubble_layout_persists_false(self):
"""POST /api/settings with bubble_layout:false must persist and round-trip."""
try:
_post("/api/settings", {"bubble_layout": True})
_post("/api/settings", {"bubble_layout": False})
except OSError:
self.skipTest("Server not running on port 8788")
d, _ = _get("/api/settings")
self.assertFalse(d["bubble_layout"], "bubble_layout=False must persist after POST")
def test_bubble_layout_truthy_string_coerced_to_bool(self):
"""Non-bool truthy value must be coerced to bool by _SETTINGS_BOOL_KEYS logic."""
try:
_post("/api/settings", {"bubble_layout": "1"})
except OSError:
self.skipTest("Server not running on port 8788")
d, _ = _get("/api/settings")
self.assertIsInstance(
d["bubble_layout"],
bool,
"bubble_layout must be a bool in API response (bool coercion via _SETTINGS_BOOL_KEYS)",
)
# Restore
_post("/api/settings", {"bubble_layout": False})

34
tests/test_issue341.py Normal file
View File

@@ -0,0 +1,34 @@
"""Tests for GitHub issue #341: .msg-body table CSS styles."""
import os
CSS_PATH = os.path.join(os.path.dirname(__file__), "..", "static", "style.css")
def _read_css():
with open(CSS_PATH, "r") as f:
return f.read()
def test_msg_body_table_css_present():
css = _read_css()
assert ".msg-body table" in css, ".msg-body table rule missing from style.css"
assert "border-collapse:collapse" in css, "border-collapse:collapse missing from style.css"
def test_msg_body_table_th_td_present():
css = _read_css()
assert ".msg-body th" in css, ".msg-body th rule missing from style.css"
assert ".msg-body td" in css, ".msg-body td rule missing from style.css"
def test_msg_body_table_tr_stripe_present():
css = _read_css()
assert ".msg-body tr:nth-child(even)" in css, ".msg-body tr:nth-child(even) rule missing from style.css"
def test_msg_body_light_theme_overrides():
css = _read_css()
assert ':root[data-theme="light"] .msg-body th' in css, \
'Light-theme override for .msg-body th missing from style.css'
assert ':root[data-theme="light"] .msg-body td' in css, \
'Light-theme override for .msg-body td missing from style.css'

115
tests/test_issue342.py Normal file
View File

@@ -0,0 +1,115 @@
"""
Tests for GitHub issue #342: auto-link plain URLs in chat messages.
These are structural tests that verify the fix is present in static/ui.js
without requiring a running server or JavaScript engine.
"""
import os
import re
UI_JS = os.path.join(os.path.dirname(__file__), '..', 'static', 'ui.js')
def read_ui_js():
with open(UI_JS, 'r') as f:
return f.read()
def test_autolink_comment_present():
"""The Autolink comment should be present in renderMd() to document the feature."""
content = read_ui_js()
assert 'Autolink: convert plain URLs' in content, (
"Expected 'Autolink: convert plain URLs' comment not found in static/ui.js. "
"Did the autolink pass get added?"
)
def test_autolink_regex_in_rendermd():
"""The autolink regex pattern (https?://) should appear in renderMd()."""
content = read_ui_js()
# Locate the renderMd function body
rendermd_start = content.find('function renderMd(raw){')
assert rendermd_start != -1, "renderMd function not found in ui.js"
# Find the closing brace after renderMd (look for the autolink pattern within it)
rendermd_body = content[rendermd_start:rendermd_start + 5000]
assert 'https?:\\/\\/' in rendermd_body, (
"Autolink regex (https?:\\/\\/) not found inside renderMd() body."
)
def test_autolink_uses_esc_for_xss_safety():
"""The autolink code must use esc() to escape URLs, preventing XSS."""
content = read_ui_js()
# Find the autolink section (between the SAFE_TAGS pass and paragraph wrap)
autolink_idx = content.find('// Autolink: convert plain URLs')
assert autolink_idx != -1, "Autolink comment not found in ui.js"
# Extract the autolink block (next ~300 chars after the comment)
autolink_block = content[autolink_idx:autolink_idx + 400]
assert 'esc(clean)' in autolink_block, (
"Autolink block should use esc(clean) for XSS-safe URL escaping, but it was not found."
)
def test_autolink_in_inline_md():
"""The autolink pass should also be present inside the inlineMd() helper."""
content = read_ui_js()
# Find inlineMd function
inline_start = content.find('function inlineMd(t){')
assert inline_start != -1, "inlineMd function not found in ui.js"
# Find closing brace of inlineMd by looking for 'return t;' followed by '}'
inline_end = content.find('return t;\n }', inline_start)
assert inline_end != -1, "Could not locate end of inlineMd function"
inline_body = content[inline_start:inline_end + 20]
assert 'https?:\\/\\/' in inline_body, (
"Autolink regex not found inside inlineMd() — plain URLs in list items "
"and blockquotes won't be autolinked."
)
def test_autolink_after_safe_tags_pass():
"""The autolink pass must come AFTER the SAFE_TAGS escape pass (ordering matters)."""
content = read_ui_js()
safe_tags_idx = content.find('s=s.replace(/<\\/?[a-z][^>]*>/gi,tag=>SAFE_TAGS.test(tag)?tag:esc(tag));')
autolink_idx = content.find('// Autolink: convert plain URLs')
parts_idx = content.find('const parts=s.split(/\\n{2,}/);')
assert safe_tags_idx != -1, "SAFE_TAGS pass not found"
assert autolink_idx != -1, "Autolink pass not found"
assert parts_idx != -1, "Paragraph-wrap parts line not found"
assert safe_tags_idx < autolink_idx < parts_idx, (
f"Ordering wrong: SAFE_TAGS at {safe_tags_idx}, autolink at {autolink_idx}, "
f"parts (paragraph wrap) at {parts_idx}. "
"Autolink must come between SAFE_TAGS pass and paragraph wrap."
)
def test_autolink_target_blank_and_rel():
"""Autolinked URLs should open in a new tab with rel=noopener for security."""
content = read_ui_js()
autolink_idx = content.find('// Autolink: convert plain URLs')
assert autolink_idx != -1, "Autolink comment not found"
autolink_block = content[autolink_idx:autolink_idx + 400]
assert 'target="_blank"' in autolink_block, (
"Autolinked URLs should have target=\"_blank\""
)
assert 'rel="noopener"' in autolink_block, (
"Autolinked URLs should have rel=\"noopener\" for security"
)
def test_safe_tags_includes_anchor():
"""SAFE_TAGS regex must include 'a' so <a> tags from autolink are not escaped."""
content = read_ui_js()
# Find the SAFE_TAGS definition line — the pattern contains slashes so we
# search for the line directly rather than extracting the regex literal.
safe_tags_line = None
for line in content.splitlines():
if 'const SAFE_TAGS=' in line:
safe_tags_line = line
break
assert safe_tags_line is not None, "SAFE_TAGS const definition not found in ui.js"
# The pattern should include 'a' as a tag alternative (e.g. |a|)
assert '|a|' in safe_tags_line or '|a)' in safe_tags_line, (
f"SAFE_TAGS line does not include 'a' tag — "
"<a> tags emitted by autolink would be escaped!\n"
f"Line: {safe_tags_line}"
)

348
tests/test_issue347.py Normal file
View File

@@ -0,0 +1,348 @@
"""
Tests for GitHub issue #347: KaTeX / LaTeX math rendering in chat and workspace previews.
Structural tests — no server required. Verify:
- renderMd() stashes and restores $..$ and $$...$$ math delimiters
- KaTeX lazy-load function exists and follows the mermaid pattern
- KaTeX JS loaded from CDN with SRI integrity hash
- KaTeX CSS loaded in index.html with SRI hash
- CSS rules present for .katex-block and .katex-inline
- SAFE_TAGS updated to allow <span> (for inline math)
- renderKatexBlocks() is wired into the requestAnimationFrame call
"""
import pathlib
import re
REPO = pathlib.Path(__file__).parent.parent
UI_JS = (REPO / 'static' / 'ui.js').read_text(encoding='utf-8')
INDEX = (REPO / 'static' / 'index.html').read_text(encoding='utf-8')
CSS = (REPO / 'static' / 'style.css').read_text(encoding='utf-8')
# ── renderMd pipeline ──────────────────────────────────────────────────────────
def test_display_math_stash_present():
"""renderMd must stash $$...$$ display math before other processing."""
assert r'\$\$([\s\S]+?)\$\$' in UI_JS or '$$' in UI_JS, \
'Display math $$..$$ stash regex not found in ui.js'
# The stash uses \\x00M token
assert '\\x00M' in UI_JS, 'Math stash token \\x00M not found in renderMd'
def test_inline_math_stash_present():
"""renderMd must stash $..$ inline math."""
# Inline math regex must be present
assert 'math_stash' in UI_JS, 'math_stash array not found in renderMd'
def test_katex_block_placeholder_emitted():
"""renderMd restore pass must emit .katex-block divs for display math."""
assert 'katex-block' in UI_JS, \
'.katex-block placeholder div not emitted by renderMd restore pass'
def test_katex_inline_placeholder_emitted():
"""renderMd restore pass must emit .katex-inline spans for inline math."""
assert 'katex-inline' in UI_JS, \
'.katex-inline placeholder span not emitted by renderMd restore pass'
def test_data_katex_attribute_present():
"""Placeholders must carry data-katex attribute for display/inline distinction."""
assert 'data-katex' in UI_JS, \
'data-katex attribute not found — renderKatexBlocks cannot distinguish display from inline'
# ── renderKatexBlocks() ────────────────────────────────────────────────────────
def test_render_katex_blocks_function_exists():
"""renderKatexBlocks() function must exist in ui.js."""
assert 'function renderKatexBlocks()' in UI_JS, \
'renderKatexBlocks() function not found in ui.js'
def test_katex_lazy_load_follows_mermaid_pattern():
"""KaTeX must use the same lazy-load pattern as mermaid (load on first use)."""
assert '_katexLoading' in UI_JS, '_katexLoading flag not found'
assert '_katexReady' in UI_JS, '_katexReady flag not found'
def test_katex_js_loaded_from_cdn():
"""KaTeX JS must be loaded from jsdelivr CDN."""
assert 'katex@0.16' in UI_JS, \
'KaTeX JS CDN URL not found in ui.js — expected katex@0.16.x'
def test_katex_js_has_sri_hash():
"""KaTeX JS CDN tag must have an SRI integrity hash."""
# The hash is in the script.integrity assignment
assert "script.integrity='sha384-" in UI_JS or 'script.integrity="sha384-' in UI_JS, \
'KaTeX JS SRI integrity hash not found in ui.js'
def test_katex_display_mode_used():
"""renderKatexBlocks must pass displayMode based on data-katex attribute."""
assert 'displayMode' in UI_JS, \
'displayMode not passed to katex.render() — display math will render inline'
def test_katex_throw_on_error_false():
"""KaTeX must be configured with throwOnError:false to degrade gracefully."""
assert 'throwOnError:false' in UI_JS, \
'throwOnError:false not set — bad LaTeX will throw and break the message'
def test_render_katex_blocks_wired_into_raf():
"""renderKatexBlocks() must be called in the same requestAnimationFrame as renderMermaidBlocks()."""
# Check that renderKatexBlocks appears somewhere near requestAnimationFrame
raf_idx = UI_JS.find('requestAnimationFrame')
# Find the rAF call that also contains renderKatexBlocks
has_katex_in_raf = any(
'renderKatexBlocks' in UI_JS[m.start():m.start()+200]
for m in re.finditer(r'requestAnimationFrame', UI_JS)
)
assert has_katex_in_raf, \
'renderKatexBlocks() not found in any requestAnimationFrame call — math will not render'
# ── index.html ────────────────────────────────────────────────────────────────
def test_katex_css_in_index_html():
"""KaTeX CSS must be loaded in index.html."""
assert 'katex@0.16' in INDEX, \
'KaTeX CSS CDN link not found in index.html'
def test_katex_css_has_sri_hash():
"""KaTeX CSS link in index.html must have an SRI integrity hash."""
assert 'sha384-5TcZemv2l' in INDEX or 'integrity' in INDEX and 'katex' in INDEX, \
'KaTeX CSS SRI integrity hash not found in index.html'
# ── style.css ─────────────────────────────────────────────────────────────────
def test_katex_block_css_present():
""".katex-block CSS rule must exist for centered display math."""
assert '.katex-block' in CSS, \
'.katex-block CSS rule missing from style.css — display math will have no layout'
def test_katex_inline_css_present():
""".katex-inline CSS rule must exist."""
assert '.katex-inline' in CSS, \
'.katex-inline CSS rule missing from style.css'
def test_katex_block_text_align_center():
""".katex-block must be text-align:center for display math."""
assert 'text-align:center' in CSS, \
'text-align:center not found for .katex-block'
# ── SAFE_TAGS ──────────────────────────────────────────────────────────────────
def test_safe_tags_includes_span():
"""SAFE_TAGS must include <span> to allow .katex-inline spans through the escape pass."""
# The SAFE_TAGS regex should contain 'span'
safe_tags_match = re.search(r'SAFE_TAGS\s*=\s*/.*?/i', UI_JS)
assert safe_tags_match, 'SAFE_TAGS pattern not found in ui.js'
assert 'span' in safe_tags_match.group(), \
'<span> not in SAFE_TAGS — inline math spans will be HTML-escaped and rendered as text'
# ── Stash ordering: fence must protect code spans from math extraction ─────────
WORKSPACE_JS = (REPO / 'static' / 'workspace.js').read_text(encoding='utf-8')
def test_fence_stash_before_math_stash():
"""fence_stash must be initialized and populated BEFORE math_stash in renderMd.
If math_stash runs first, dollar signs inside backtick code spans are extracted
as math, leaving placeholder tokens inside the stashed code string. The code span
then renders with KaTeX inside <code> instead of the literal dollar-sign text.
"""
fence_pos = UI_JS.find("const fence_stash=[]")
math_pos = UI_JS.find("const math_stash=[]")
assert fence_pos != -1, "fence_stash not found in renderMd"
assert math_pos != -1, "math_stash not found in renderMd"
assert fence_pos < math_pos, (
"fence_stash must be declared BEFORE math_stash in renderMd "
f"(fence at char {fence_pos}, math at char {math_pos}). "
"If math runs first, `$x$` inside backticks gets extracted as math instead of code."
)
def test_fence_stash_populated_before_math_stash():
"""The fence_stash s.replace call must appear before any math_stash s.replace calls."""
# Find the s.replace call that populates each stash
fence_replace_pos = UI_JS.find("fence_stash.push(m)")
math_replace_pos = UI_JS.find("math_stash.push(")
assert fence_replace_pos != -1, "fence_stash population call not found"
assert math_replace_pos != -1, "math_stash population call not found"
assert fence_replace_pos < math_replace_pos, (
"fence_stash must be populated before math_stash to protect code span contents"
)
def test_math_stash_comment_says_after_fence():
"""The math stash comment should explain it runs AFTER fence_stash, not before."""
# Should not have the old misleading comment
assert "Must run BEFORE fence_stash" not in UI_JS, (
"Old misleading comment still present. Math stash runs AFTER fence_stash. "
"The comment should say 'Runs AFTER fence_stash'."
)
# ── Pipeline regression: code spans protect their contents ────────────────────
def test_math_restore_after_fence_restore():
"""Math stash tokens are restored AFTER fence restore, so code spans get
their raw text back (not KaTeX placeholders)."""
fence_restore_pos = UI_JS.find("fence_stash[+i]")
math_restore_pos = UI_JS.find("math_stash[+i]")
assert fence_restore_pos != -1, "fence_stash restore not found"
assert math_restore_pos != -1, "math_stash restore not found"
# Both restores must exist; their relative order doesn't matter for correctness
# (they use different tokens: \x00F vs \x00M), but we assert both exist
assert fence_restore_pos != math_restore_pos, "fence and math restore must be separate calls"
def test_stash_tokens_distinct():
"""fence_stash and math_stash must use distinct sentinel tokens to avoid collisions."""
# fence uses \x00F, math uses \x00M (or similar unique prefix)
# The JS source uses escaped \\x00F and \\x00M as sentinel characters
# In the Python string read from the file these appear as '\\\\x00F' and '\\\\x00M'
assert "'\\\\x00F'" in UI_JS or 'x00F' in UI_JS, (
"fence stash token (\\x00F) not found — must be distinct from math token"
)
assert "'\\\\x00M'" in UI_JS or 'x00M' in UI_JS, (
"math stash token (\\x00M) not found — must be distinct from fence token"
)
# The two tokens must use different discriminator characters
assert 'x00F' in UI_JS and 'x00M' in UI_JS, (
"Both \\x00F (fence) and \\x00M (math) tokens must exist"
)
# ── Workspace preview renderKatexBlocks wiring ────────────────────────────────
def test_workspace_calls_render_katex_after_preview():
"""workspace.js must call renderKatexBlocks() after setting previewMd.innerHTML.
Without this, math placeholders appear in workspace file previews but are never
rendered by KaTeX (renderKatexBlocks is only wired into renderMessages rAF).
"""
assert "renderKatexBlocks" in WORKSPACE_JS, (
"workspace.js must call renderKatexBlocks() after renderMd() for file previews"
)
def test_workspace_renders_katex_after_file_open():
"""workspace.js renderKatexBlocks call must come after the renderMd(data.content) assignment."""
preview_md_pos = WORKSPACE_JS.find("renderMd(data.content)")
# Use the actual call string (not a stray regex match on 'M' characters)
katex_call_str = "renderKatexBlocks==='function'"
katex_call_pos = WORKSPACE_JS.find(katex_call_str)
assert preview_md_pos != -1, "renderMd(data.content) not found in workspace.js"
assert katex_call_pos != -1, (
"renderKatexBlocks guard (typeof renderKatexBlocks==='function') not found in workspace.js"
)
# The call after 'renderMd(data.content)' — find the LAST occurrence
# (there may be an earlier one in the save path at line ~153)
last_katex_pos = WORKSPACE_JS.rfind(katex_call_str)
assert last_katex_pos > preview_md_pos, (
"renderKatexBlocks must be called AFTER renderMd(data.content) in workspace.js "
f"(renderMd at {preview_md_pos}, last renderKatexBlocks at {last_katex_pos})"
)
def test_workspace_katex_guarded_by_typeof():
"""workspace.js renderKatexBlocks call must guard with typeof check for safety
in case KaTeX feature is not loaded (e.g. test environments, offline)."""
assert "typeof renderKatexBlocks" in WORKSPACE_JS, (
"workspace.js must guard renderKatexBlocks call with typeof check: "
"if(typeof renderKatexBlocks==='function')renderKatexBlocks()"
)
# ── SAFE_TAGS: span addition should not expand attack surface ─────────────────
def test_safe_tags_span_is_narrowly_scoped():
"""SAFE_TAGS adding <span> is only a bypass if span carries dangerous attributes.
Verify the SAFE_TAGS regex tests the tag NAME only, not arbitrary attributes.
The rest of the pipeline uses esc() for user content, so attribute injection
into KaTeX spans isn't possible.
"""
# The SAFE_TAGS regex must still require a word boundary / tag-end pattern
safe_tags_match = re.search(r"SAFE_TAGS\s*=\s*/(.+?)/i", UI_JS)
if not safe_tags_match:
safe_tags_match = re.search(r'SAFE_TAGS\s*=\s*/(.*?)/i', UI_JS)
assert safe_tags_match, "SAFE_TAGS regex not found"
pattern = safe_tags_match.group(1)
# Must have a trailing boundary check — ([\s>]|$) or similar
assert r"[\s>]" in pattern or r'[\s>]' in pattern, (
"SAFE_TAGS must enforce a boundary after the tag name to prevent "
"<spanxss> from matching when checking for <span>"
)
# ── False-positive prevention ─────────────────────────────────────────────────
def test_inline_math_regex_requires_non_space_boundaries():
"""The $...$ inline regex must require non-space at both boundaries.
This prevents 'costs $5 and $10' from matching — the space after the opening
$ means it's a currency amount, not math.
"""
# The inline math stash push is type:'inline' — find its containing replace() line
inline_push_idx = UI_JS.find("type:'inline',src:m")
assert inline_push_idx != -1, "Inline math stash push not found"
# Get the text from the start of that line back to find the regex
line_start = UI_JS.rfind('\n', 0, inline_push_idx) + 1
inline_line = UI_JS[line_start:inline_push_idx + 50]
# The regex must use \s (via [^\s...]) to exclude spaces at boundaries
assert '\\s' in inline_line or '[^' in inline_line, (
f"Inline math regex must exclude spaces at boundaries to prevent false "
f"positives on currency like $5. Found: {inline_line[:120]}"
)
def test_display_math_stashed_before_inline():
"""$$...$$ display math must be stashed before $...$ inline math.
If inline runs first on '$$x$$', it could match '$' + 'x' + '$' leaving
a stray outer '$', corrupting the output.
"""
display_pos = UI_JS.find("type:'display',src:m")
inline_pos = UI_JS.find("type:'inline',src:m")
assert display_pos != -1, "display math stash not found"
assert inline_pos != -1, "inline math stash not found"
# First occurrence of display must be before first occurrence of inline
assert display_pos < inline_pos, (
"Display math ($$...$$) must be stashed before inline math ($...$) "
"to prevent $$ from being parsed as two adjacent inline delimiters"
)
def test_math_stash_token_uses_single_backslash_null_byte():
"""Math stash tokens must use the null-byte form (single backslash x00M).
The restore regex expects a null byte character. If the stash emits
a literal backslash+x00M (double backslash = 5-char string), the restore
regex never matches and the tokens appear verbatim in the rendered output.
The fence_stash correctly uses the null byte convention. Math stash must be consistent.
"""
# In the source file, the correct form is: return '\x00M'
# The wrong form (double backslash) would be: return '\\x00M'
# Check that no double-backslash form exists in the math stash return statements
import re
bad_returns = re.findall(r"return\s+'\\\\x00M'", UI_JS)
assert not bad_returns, (
f"Found {len(bad_returns)} math stash return(s) using double-backslash \\\\x00M. "
"Must use single backslash '\x00M' (null byte) to match the restore regex."
)
# Positive check: single-backslash form must exist
good_returns = re.findall(r"math_stash\.push.*?return '\\x00M'", UI_JS, re.DOTALL)
assert good_returns, (
"Math stash return must use single-backslash '\x00M' (null byte convention)"
)

189
tests/test_issue357.py Normal file
View File

@@ -0,0 +1,189 @@
"""
Tests for GitHub issue #357: Docker container fails to start without internet access.
Structural tests — verify Dockerfile and docker_init.bash contain the expected
patterns for pre-installed uv and workspace permission fixes.
Two problems fixed:
1. uv was downloaded at container startup; fails in air-gapped / firewalled environments.
Fix: pre-install uv in the Docker image at build time (system-wide in /usr/local/bin).
2. workspace directory created with plain mkdir (as root); bind-mount dirs created by
Docker as root are unwritable by the hermeswebui user.
Fix: sudo mkdir + sudo chown for workspace directory.
"""
import pathlib
import re
REPO = pathlib.Path(__file__).parent.parent
DOCKERFILE = (REPO / "Dockerfile").read_text(encoding="utf-8")
INIT_SCRIPT = (REPO / "docker_init.bash").read_text(encoding="utf-8")
# ── Dockerfile: uv pre-installed at build time ───────────────────────────────
class TestDockerfileUvPreinstall:
def test_dockerfile_installs_uv_at_build_time(self):
"""Dockerfile must install uv via RUN curl at build time (not only at runtime)."""
assert "RUN curl" in DOCKERFILE and "uv/install.sh" in DOCKERFILE, (
"Dockerfile must install uv at build time via RUN curl .../uv/install.sh"
)
def test_dockerfile_uv_installed_system_wide(self):
"""uv must be installed to a system-wide directory (/usr/local/bin) accessible
to all users, not to a user-specific ~/.local/bin that another user can't see."""
# The install command must target /usr/local/bin or use root to install globally
uv_install_line = next(
(line for line in DOCKERFILE.splitlines() if "uv/install.sh" in line),
None,
)
assert uv_install_line is not None, "Could not find uv install line in Dockerfile"
# Must either use UV_INSTALL_DIR pointing to /usr/local/bin, or run as root
# (so the default install location is accessible to hermeswebui user)
has_system_dir = "/usr/local/bin" in uv_install_line or "UV_INSTALL_DIR=/usr/local/bin" in DOCKERFILE
assert has_system_dir, (
"uv must be installed to /usr/local/bin (system-wide) so hermeswebui user "
"can find it. Installing as hermeswebuitoo puts it in /home/hermeswebuitoo/.local/bin "
"which is NOT on hermeswebui's PATH."
)
def test_dockerfile_uv_installed_before_copy(self):
"""uv installation must happen before COPY . /apptoo so it's in the image."""
uv_pos = DOCKERFILE.find("uv/install.sh")
copy_pos = DOCKERFILE.find("COPY . /apptoo")
assert uv_pos != -1, "uv install not found in Dockerfile"
assert copy_pos != -1, "COPY . /apptoo not found in Dockerfile"
assert uv_pos < copy_pos, "uv must be installed before COPY . /apptoo"
def test_dockerfile_uv_installed_as_root_or_before_user_switch(self):
"""uv must be installed as root (USER root) to reach /usr/local/bin.
If installed as hermeswebuitoo, it lands in ~hermeswebuitoo/.local/bin,
which the hermeswebui user at runtime can't see.
"""
lines = DOCKERFILE.splitlines()
uv_line_idx = next(i for i, l in enumerate(lines) if "uv/install.sh" in l)
# Find the last USER directive before the uv install line
user_before = None
for i in range(uv_line_idx - 1, -1, -1):
if lines[i].strip().startswith("USER "):
user_before = lines[i].strip().split()[1]
break
assert user_before == "root", (
f"uv install must run as USER root (found USER {user_before!r}). "
"Installing as hermeswebuitoo puts uv in /home/hermeswebuitoo/.local/bin "
"which is not accessible to the hermeswebui runtime user."
)
# ── docker_init.bash: skip uv download when already present ─────────────────
class TestInitScriptUvSkip:
def test_init_script_checks_uv_before_download(self):
"""docker_init.bash must check 'command -v uv' before attempting download."""
assert "command -v uv" in INIT_SCRIPT, (
"docker_init.bash must check 'command -v uv' to skip download "
"when uv is already pre-installed in the image (#357)"
)
def test_init_script_skips_download_if_present(self):
"""Init script must use conditional logic (if/else) around the uv download."""
# Pattern: if command -v uv ... else ... fi
assert re.search(r'if\s+command\s+-v\s+uv', INIT_SCRIPT), (
"docker_init.bash must use 'if command -v uv' guard around the download"
)
def test_init_script_curl_download_in_else_branch(self):
"""The curl download must be in the else branch (only runs if uv not found)."""
# Find the conditional block
m = re.search(
r'if\s+command\s+-v\s+uv.*?fi',
INIT_SCRIPT, re.DOTALL
)
assert m, "Could not find uv conditional block in docker_init.bash"
block = m.group(0)
# curl must appear after 'else' not in the 'then' branch
else_pos = block.find("else")
curl_pos = block.find("curl")
assert else_pos != -1, "No 'else' branch in uv conditional"
assert curl_pos != -1, "No 'curl' in uv conditional block"
assert curl_pos > else_pos, (
"curl download must be in the 'else' branch, not the 'if/then' branch"
)
def test_init_script_error_exit_on_download_failure(self):
"""Curl download must call error_exit on failure (not silently continue)."""
assert "error_exit" in INIT_SCRIPT and "Failed to install uv" in INIT_SCRIPT, (
"docker_init.bash must call error_exit if uv download fails, "
"so the container exits with a clear message instead of failing silently"
)
def test_init_script_path_includes_hermeswebui_local_bin(self):
"""PATH must include /home/hermeswebui/.local/bin for fallback runtime install."""
assert "/home/hermeswebui/.local/bin" in INIT_SCRIPT, (
"docker_init.bash must include /home/hermeswebui/.local/bin in PATH "
"for the case where uv is installed at runtime via curl"
)
# ── docker_init.bash: workspace directory permissions ────────────────────────
class TestWorkspacePermissions:
def test_workspace_uses_sudo_mkdir(self):
"""docker_init.bash must use 'sudo mkdir' for the workspace directory.
Docker auto-creates bind-mount directories as root if they don't exist,
leaving them unwritable by hermeswebui. sudo mkdir + chown fixes this.
"""
# Find the workspace section
ws_section = INIT_SCRIPT[
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE"):
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE") + 800
]
assert "sudo mkdir" in ws_section, (
"docker_init.bash must use 'sudo mkdir -p' for the workspace directory "
"to handle the case where Docker created the bind-mount dir as root (#357)"
)
def test_workspace_uses_sudo_chown(self):
"""docker_init.bash must chown the workspace to hermeswebui after mkdir."""
ws_section = INIT_SCRIPT[
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE"):
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE") + 800
]
assert "sudo chown" in ws_section and "hermeswebui" in ws_section, (
"docker_init.bash must 'sudo chown hermeswebui:hermeswebui' the workspace "
"directory after creating it, so the app user can write to it (#357)"
)
def test_workspace_mkdir_before_chown(self):
"""sudo mkdir must come before sudo chown in docker_init.bash."""
mkdir_pos = INIT_SCRIPT.find("sudo mkdir -p \"$HERMES_WEBUI_DEFAULT_WORKSPACE\"")
chown_pos = INIT_SCRIPT.find("sudo chown hermeswebui:hermeswebui \"$HERMES_WEBUI_DEFAULT_WORKSPACE\"")
assert mkdir_pos != -1, "sudo mkdir for workspace not found"
assert chown_pos != -1, "sudo chown for workspace not found"
assert mkdir_pos < chown_pos, "sudo mkdir must come before sudo chown"
def test_workspace_error_exit_on_mkdir_failure(self):
"""sudo mkdir must call error_exit on failure."""
assert 'sudo mkdir -p "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit' in INIT_SCRIPT, (
"sudo mkdir for workspace must call error_exit on failure"
)
def test_workspace_error_exit_on_chown_failure(self):
"""sudo chown must call error_exit on failure."""
assert 'sudo chown hermeswebui:hermeswebui "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit' in INIT_SCRIPT, (
"sudo chown for workspace must call error_exit on failure"
)
def test_init_script_syntax_valid(self):
"""docker_init.bash must pass bash -n syntax check."""
import subprocess
result = subprocess.run(
["bash", "-n", str(REPO / "docker_init.bash")],
capture_output=True, text=True
)
assert result.returncode == 0, (
f"docker_init.bash failed bash -n syntax check:\n{result.stderr}"
)

216
tests/test_issue401.py Normal file
View File

@@ -0,0 +1,216 @@
"""
Regression tests for issue #401 / PR #402:
Tool call cards show incorrect/duplicate entries on session load after context compaction.
Root cause: loadSession() applied its own B9 sanitization (producing a new message array
with different indices) but did not remap the session-level tool_calls.assistant_msg_idx
values to match. It then assigned the broken tool_calls directly to S.toolCalls, bypassing
renderMessages()'s fallback that correctly derives tool calls from per-message tool_calls.
Fix: build origIdxToSanitizedIdx during the B9 pass and remap each tc.assistant_msg_idx;
set S.toolCalls=[] so renderMessages() uses the fallback derivation.
These tests verify the JS logic statically (no server needed).
"""
import pathlib
import subprocess
import textwrap
import json
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
SESSIONS_JS = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
# --- Static structural checks ---
def test_loadsession_sets_toolcalls_empty():
"""loadSession must set S.toolCalls=[] instead of pre-filling from session-level tool_calls."""
assert "S.toolCalls=[]" in SESSIONS_JS, (
"loadSession() must set S.toolCalls=[] so renderMessages() uses its fallback "
"derivation from per-message tool_calls with correct sanitized-array indices"
)
def test_loadsession_does_not_assign_broken_tool_calls():
"""loadSession must NOT assign session.tool_calls directly to S.toolCalls (causes index mismatch)."""
# The old broken pattern: S.toolCalls=(data.session.tool_calls||[]).map(tc=>({...tc,done:true}))
assert "S.toolCalls=(data.session.tool_calls" not in SESSIONS_JS, (
"loadSession() must not assign session-level tool_calls directly to S.toolCalls — "
"those indices are relative to the pre-sanitization array and will be wrong after B9 filtering"
)
def test_loadsession_builds_idx_remap():
"""loadSession must build an origIdxToSanitizedIdx map during B9 sanitization."""
assert "origIdxToSanitizedIdx" in SESSIONS_JS, (
"loadSession() must build origIdxToSanitizedIdx during B9 sanitization "
"to remap session-level tool_calls.assistant_msg_idx"
)
def test_loadsession_remaps_assistant_msg_idx():
"""loadSession must remap tc.assistant_msg_idx using the index map."""
assert "tc.assistant_msg_idx" in SESSIONS_JS, (
"loadSession() must update tc.assistant_msg_idx using the sanitized index map"
)
# --- Behavioural Node.js tests ---
def _run_js(script_body: str) -> dict:
"""Run a JS snippet that exercises the B9 sanitization logic extracted from sessions.js."""
# Extract just the B9 + index-remap block from loadSession
# We'll re-implement it inline for testability
script = textwrap.dedent(f"""
// Simulate the B9 sanitization + index remap logic from loadSession()
function sanitizeAndRemap(messages, tool_calls) {{
const allMsgs = messages || [];
const sanitized = [];
const origIdxToSanitizedIdx = {{}};
let lastKeptAsstIdx = -1;
for (let i = 0; i < allMsgs.length; i++) {{
const m = allMsgs[i];
if (!m || !m.role) continue;
if (m.role === 'tool') continue;
if (m.role === 'assistant') {{
let c = m.content || '';
if (Array.isArray(c)) c = c.filter(p => p && p.type === 'text').map(p => p.text || '').join('');
if (!String(c).trim().length) {{ continue; }}
lastKeptAsstIdx = sanitized.length;
}}
origIdxToSanitizedIdx[i] = sanitized.length;
sanitized.push(m);
}}
const remapped = (tool_calls || []).map(tc => {{
if (!tc || tc.assistant_msg_idx === undefined) return tc;
const origIdx = tc.assistant_msg_idx;
const newIdx = (origIdx in origIdxToSanitizedIdx)
? origIdxToSanitizedIdx[origIdx]
: (lastKeptAsstIdx >= 0 ? lastKeptAsstIdx : -1);
return {{ ...tc, assistant_msg_idx: newIdx }};
}});
return {{ sanitized, remapped }};
}}
{script_body}
""")
proc = subprocess.run(
["node", "-e", script], check=True, capture_output=True, text=True
)
return json.loads(proc.stdout)
def test_b9_remaps_tool_call_idx_after_empty_assistant_filtered():
"""Tool call pointing to index 1 (empty assistant at orig idx 1, kept at idx 0) remaps correctly."""
result = _run_js("""
const messages = [
{ role: 'user', content: 'hello' }, // orig 0 -> sanitized 0
{ role: 'assistant', content: '' }, // orig 1 -> FILTERED (empty)
{ role: 'assistant', content: 'done.' }, // orig 2 -> sanitized 1
];
const tool_calls = [
{ name: 'terminal', assistant_msg_idx: 1 }, // pointed to filtered-out empty assistant
{ name: 'read_file', assistant_msg_idx: 2 }, // pointed to kept assistant
];
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
process.stdout.write(JSON.stringify({
sanitized_length: sanitized.length,
tc0_new_idx: remapped[0].assistant_msg_idx, // should attach to lastKeptAsstIdx = 1
tc1_new_idx: remapped[1].assistant_msg_idx, // should remap 2 -> 1
}));
""")
assert result["sanitized_length"] == 2, f"Expected 2 messages after B9, got {result['sanitized_length']}"
assert result["tc0_new_idx"] == 1, (
f"Tool call pointing to filtered empty assistant should attach to last kept assistant (idx 1), got {result['tc0_new_idx']}"
)
assert result["tc1_new_idx"] == 1, (
f"Tool call pointing to orig idx 2 should remap to sanitized idx 1, got {result['tc1_new_idx']}"
)
def test_b9_remaps_multiple_empty_assistants():
"""Multiple consecutive empty assistants all remap to the last (nearest) kept assistant.
Note: the remapping pass runs after the full sanitization loop, so lastKeptAsstIdx
already reflects the final kept-assistant position. This means even empty-assistant
tool calls that came BEFORE the kept assistant get attached to it — which is correct
behavior for context-compacted sessions where all tool calls belong to the one
non-empty assistant response.
"""
result = _run_js("""
const messages = [
{ role: 'user', content: 'go' }, // orig 0 -> sanitized 0
{ role: 'assistant', content: '' }, // orig 1 -> FILTERED
{ role: 'assistant', content: '' }, // orig 2 -> FILTERED
{ role: 'assistant', content: '' }, // orig 3 -> FILTERED
{ role: 'assistant', content: 'result' }, // orig 4 -> sanitized 1
];
const tool_calls = [
{ name: 'a', assistant_msg_idx: 1 },
{ name: 'b', assistant_msg_idx: 2 },
{ name: 'c', assistant_msg_idx: 3 },
{ name: 'd', assistant_msg_idx: 4 },
];
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
process.stdout.write(JSON.stringify({
sanitized_length: sanitized.length,
tc0_idx: remapped[0].assistant_msg_idx,
tc1_idx: remapped[1].assistant_msg_idx,
tc2_idx: remapped[2].assistant_msg_idx,
tc3_idx: remapped[3].assistant_msg_idx,
}));
""")
assert result["sanitized_length"] == 2
# Tool calls from filtered empty assistants: after the full loop, lastKeptAsstIdx=1,
# so all filtered-assistant tool calls correctly attach to the kept assistant at idx 1.
assert result["tc0_idx"] == 1, f"Expected 1 (last kept asst), got {result['tc0_idx']}"
assert result["tc1_idx"] == 1
assert result["tc2_idx"] == 1
# Tool call from the kept assistant at orig idx 4 -> sanitized idx 1
assert result["tc3_idx"] == 1, f"Expected 1, got {result['tc3_idx']}"
def test_b9_no_filtering_needed_indices_preserved():
"""When no empty assistant messages exist, indices should pass through unchanged."""
result = _run_js("""
const messages = [
{ role: 'user', content: 'hi' }, // orig 0 -> sanitized 0
{ role: 'assistant', content: 'hello' }, // orig 1 -> sanitized 1
{ role: 'user', content: 'more' }, // orig 2 -> sanitized 2
{ role: 'assistant', content: 'yes' }, // orig 3 -> sanitized 3
];
const tool_calls = [
{ name: 'x', assistant_msg_idx: 1 },
{ name: 'y', assistant_msg_idx: 3 },
];
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
process.stdout.write(JSON.stringify({
sanitized_length: sanitized.length,
tc0_idx: remapped[0].assistant_msg_idx,
tc1_idx: remapped[1].assistant_msg_idx,
}));
""")
assert result["sanitized_length"] == 4
assert result["tc0_idx"] == 1, f"Expected 1, got {result['tc0_idx']}"
assert result["tc1_idx"] == 3, f"Expected 3, got {result['tc1_idx']}"
def test_b9_tool_role_messages_filtered():
"""Messages with role='tool' must be filtered out and not affect index mapping."""
result = _run_js("""
const messages = [
{ role: 'user', content: 'run' }, // orig 0 -> sanitized 0
{ role: 'tool', content: 'output' }, // orig 1 -> FILTERED (tool role)
{ role: 'assistant', content: 'done' }, // orig 2 -> sanitized 1
];
const tool_calls = [
{ name: 'terminal', assistant_msg_idx: 2 },
];
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
process.stdout.write(JSON.stringify({
sanitized_length: sanitized.length,
tc0_idx: remapped[0].assistant_msg_idx,
}));
""")
assert result["sanitized_length"] == 2, f"tool-role message must be filtered, got {result['sanitized_length']}"
assert result["tc0_idx"] == 1, f"Expected orig idx 2 -> sanitized idx 1, got {result['tc0_idx']}"

View File

@@ -0,0 +1,230 @@
"""
Tests for issues #373, #374, and #375.
#373: Chat silently swallows errors — no feedback when agent fails to respond
#374: Remove stale OpenAI models from default list (gpt-4o, o3)
#375: Model dropdown should fetch live models from provider
"""
import pathlib
import re
REPO = pathlib.Path(__file__).parent.parent
STREAMING_PY = (REPO / "api" / "streaming.py").read_text(encoding="utf-8")
CONFIG_PY = (REPO / "api" / "config.py").read_text(encoding="utf-8")
ROUTES_PY = (REPO / "api" / "routes.py").read_text(encoding="utf-8")
MESSAGES_JS = (REPO / "static" / "messages.js").read_text(encoding="utf-8")
UI_JS = (REPO / "static" / "ui.js").read_text(encoding="utf-8")
# ── Issue #373: Silent error detection ──────────────────────────────────────
class TestSilentErrorDetection:
"""streaming.py must emit apperror when agent returns no assistant reply."""
def test_streaming_detects_no_assistant_reply(self):
"""streaming.py must check if any assistant message was produced."""
assert "_assistant_added" in STREAMING_PY, (
"streaming.py must check whether an assistant message was produced (#373)"
)
def test_streaming_emits_apperror_on_no_response(self):
"""streaming.py must emit apperror event when agent produced no reply."""
assert "no_response" in STREAMING_PY, (
"streaming.py must emit apperror with type='no_response' for silent failures (#373)"
)
def test_streaming_returns_early_after_apperror(self):
"""streaming.py must return after emitting apperror (not also emit done)."""
# The return statement must come after the put('apperror') for no_response
no_resp_pos = STREAMING_PY.find("'no_response'")
return_pos = STREAMING_PY.find("return # Don't emit done", no_resp_pos)
assert no_resp_pos != -1, "no_response type not found in streaming.py"
assert return_pos != -1, (
"streaming.py must return after emitting apperror to prevent also emitting done (#373)"
)
assert return_pos > no_resp_pos
def test_streaming_detects_auth_error_in_result(self):
"""streaming.py must detect auth errors from the result object."""
assert "_is_auth" in STREAMING_PY, (
"streaming.py must detect auth errors in silent failures (#373)"
)
assert "auth_mismatch" in STREAMING_PY, (
"streaming.py must emit auth_mismatch type for auth failures (#373)"
)
def test_messages_js_done_handler_detects_no_reply(self):
"""messages.js done handler must show an error if no assistant reply arrived."""
# Check for either the variable name or the inlined check pattern
has_no_reply_guard = (
"hasAssistantReply" in MESSAGES_JS
or ("role==='assistant'" in MESSAGES_JS and "No response received" in MESSAGES_JS)
)
assert has_no_reply_guard, (
"messages.js done handler must detect zero assistant replies (#373)"
)
assert "No response received" in MESSAGES_JS, (
"messages.js must show 'No response received' inline message (#373)"
)
def test_messages_js_handles_no_response_apperror_type(self):
"""messages.js apperror handler must recognise the no_response type."""
assert "isNoResponse" in MESSAGES_JS or "no_response" in MESSAGES_JS, (
"messages.js apperror handler must handle type='no_response' (#373)"
)
def test_messages_js_no_response_label(self):
"""messages.js must show a distinct label for no_response errors."""
assert "No response received" in MESSAGES_JS, (
"messages.js must display 'No response received' label for no_response errors (#373)"
)
# ── Issue #374: Stale model list cleanup ─────────────────────────────────────
class TestStaleModelListCleanup:
"""gpt-4o and o3 must be removed from the primary OpenAI model lists."""
def test_gpt4o_removed_from_fallback_models(self):
"""_FALLBACK_MODELS must not contain gpt-4o (issue #374)."""
fallback_block_start = CONFIG_PY.find("_FALLBACK_MODELS = [")
fallback_block_end = CONFIG_PY.find("]", fallback_block_start)
fallback_block = CONFIG_PY[fallback_block_start:fallback_block_end]
assert "gpt-4o" not in fallback_block, (
"_FALLBACK_MODELS still contains gpt-4o — remove it per issue #374"
)
def test_o3_removed_from_fallback_models(self):
"""_FALLBACK_MODELS must not contain o3 (issue #374)."""
fallback_block_start = CONFIG_PY.find("_FALLBACK_MODELS = [")
fallback_block_end = CONFIG_PY.find("]", fallback_block_start)
fallback_block = CONFIG_PY[fallback_block_start:fallback_block_end]
assert '"o3"' not in fallback_block and "'o3'" not in fallback_block, (
"_FALLBACK_MODELS still contains o3 — remove it per issue #374"
)
def test_gpt4o_removed_from_provider_models_openai(self):
"""_PROVIDER_MODELS['openai'] must not contain gpt-4o (issue #374)."""
openai_start = CONFIG_PY.find('"openai": [')
openai_end = CONFIG_PY.find("],", openai_start)
openai_block = CONFIG_PY[openai_start:openai_end]
assert "gpt-4o" not in openai_block, (
"_PROVIDER_MODELS['openai'] still contains gpt-4o — remove per issue #374"
)
def test_o3_removed_from_provider_models_openai(self):
"""_PROVIDER_MODELS['openai'] must not contain o3 (issue #374)."""
openai_start = CONFIG_PY.find('"openai": [')
openai_end = CONFIG_PY.find("],", openai_start)
openai_block = CONFIG_PY[openai_start:openai_end]
assert '"o3"' not in openai_block and "'o3'" not in openai_block, (
"_PROVIDER_MODELS['openai'] still contains o3 — remove per issue #374"
)
def test_fallback_still_has_gpt54_mini(self):
"""_FALLBACK_MODELS must still contain gpt-5.4-mini (not over-trimmed)."""
assert "gpt-5.4-mini" in CONFIG_PY, (
"_FALLBACK_MODELS must keep gpt-5.4-mini as primary OpenAI model (#374)"
)
def test_fallback_still_has_o4_mini(self):
"""_FALLBACK_MODELS must still contain o4-mini (reasoning model)."""
assert "o4-mini" in CONFIG_PY, (
"_FALLBACK_MODELS must keep o4-mini as reasoning model (#374)"
)
def test_copilot_list_unchanged(self):
"""Copilot provider model list should still include gpt-4o (it's a valid Copilot model)."""
copilot_start = CONFIG_PY.find('"copilot": [')
copilot_end = CONFIG_PY.find("],", copilot_start)
if copilot_start == -1:
return # No copilot list — that's fine
copilot_block = CONFIG_PY[copilot_start:copilot_end]
assert "gpt-4o" in copilot_block, (
"Copilot provider model list should keep gpt-4o (it's available via Copilot) (#374)"
)
# ── Issue #375: Live model fetching ─────────────────────────────────────────
class TestLiveModelFetching:
"""Backend and frontend must support live model fetching from provider APIs."""
def test_live_models_endpoint_exists_in_routes(self):
"""routes.py must have a /api/models/live endpoint (#375)."""
assert "/api/models/live" in ROUTES_PY, (
"routes.py must define /api/models/live endpoint (#375)"
)
def test_live_models_handler_function_exists(self):
"""routes.py must define _handle_live_models() function (#375)."""
assert "def _handle_live_models(" in ROUTES_PY, (
"routes.py must define _handle_live_models() for live model fetching (#375)"
)
def test_live_models_handler_validates_scheme(self):
"""_handle_live_models must validate URL scheme to prevent file:// injection (B310)."""
assert "nosec B310" in ROUTES_PY or ("scheme" in ROUTES_PY and "http" in ROUTES_PY), (
"_handle_live_models must validate URL scheme before urlopen (#375)"
)
def test_live_models_handler_has_ssrf_guard(self):
"""_handle_live_models must guard against SSRF (private IP access)."""
assert "ssrf_blocked" in ROUTES_PY or ("is_private" in ROUTES_PY and "live" in ROUTES_PY), (
"_handle_live_models must have SSRF protection for private IP ranges (#375)"
)
def test_live_models_all_providers_handled_via_agent(self):
"""_handle_live_models must delegate to provider_model_ids() which handles all
providers gracefully — live fetch where possible, static fallback otherwise.
The old 'not_supported' return for Anthropic/Google is superseded: those
providers now return live or static model lists via the agent delegate."""
assert "provider_model_ids" in ROUTES_PY, (
"_handle_live_models must delegate to hermes_cli.models.provider_model_ids() "
"so all providers are handled uniformly (#375 upgrade)"
)
def test_frontend_has_fetch_live_models_function(self):
"""ui.js must define _fetchLiveModels() for background live model loading (#375)."""
assert "function _fetchLiveModels(" in UI_JS or "async function _fetchLiveModels(" in UI_JS, (
"ui.js must define _fetchLiveModels() function (#375)"
)
def test_frontend_live_models_cache_exists(self):
"""ui.js must cache live model responses to avoid redundant API calls (#375)."""
assert "_liveModelCache" in UI_JS, (
"ui.js must use _liveModelCache to avoid re-fetching on every dropdown open (#375)"
)
def test_frontend_calls_live_models_after_static_load(self):
"""populateModelDropdown must call _fetchLiveModels after rendering the static list (#375)."""
assert "_fetchLiveModels" in UI_JS, (
"populateModelDropdown must call _fetchLiveModels for background update (#375)"
)
def test_frontend_live_fetch_only_adds_new_models(self):
"""_fetchLiveModels must not duplicate models already in the static list (#375)."""
assert "existingIds" in UI_JS, (
"_fetchLiveModels must track existing model IDs to avoid duplicates (#375)"
)
def test_frontend_live_fetch_covers_all_providers(self):
"""_fetchLiveModels no longer skips any provider — all providers return
live or fallback models via provider_model_ids() on the backend (#375 upgrade)."""
# The old skip list (anthropic, google, gemini) must be gone from the guard
skip_guard_pos = UI_JS.find("includes(provider)")
if skip_guard_pos != -1:
guard_line = UI_JS[max(0,skip_guard_pos-100):skip_guard_pos+50]
assert "anthropic" not in guard_line, (
"_fetchLiveModels must not skip anthropic — backend now handles it (#375 upgrade)"
)
def test_live_models_endpoint_wired_in_routes(self):
"""The /api/models/live path must be handled in handle_get()."""
# Find handle_get and check our route appears inside it
handle_get_pos = ROUTES_PY.find("def handle_get(")
live_route_pos = ROUTES_PY.find('"/api/models/live"')
assert handle_get_pos != -1 and live_route_pos != -1
assert live_route_pos > handle_get_pos, (
"/api/models/live must be inside handle_get() (#375)"
)

View File

@@ -115,13 +115,16 @@ def test_topbar_chips_mobile_overflow():
def test_workspace_close_button_present():
"""Workspace panel must have a close/hide button accessible on mobile."""
# Either a dedicated mobile close button or the toggle button that closes the panel
# Accept handleWorkspaceClose() (two-step close: file→browse→closed), or the
# lower-level functions directly. handleWorkspaceClose is preferred because
# it dismisses a file preview first before closing the panel.
has_close = (
'onclick="handleWorkspaceClose()"' in HTML or
'onclick="closeWorkspacePanel()"' in HTML or
'onclick="toggleWorkspacePanel()"' in HTML
)
assert has_close, \
"closeWorkspacePanel() or toggleWorkspacePanel() must be wired to a button to close the workspace panel on mobile"
"handleWorkspaceClose() or closeWorkspacePanel() must be wired to a button to close the workspace panel on mobile"
def test_toggle_mobile_files_js_defined():
@@ -133,6 +136,21 @@ def test_toggle_mobile_files_js_defined():
"toggleMobileFiles() must toggle mobile-open class on the right panel"
def test_new_conversation_closes_mobile_sidebar():
"""New conversation must close the mobile drawer so the chat pane is visible immediately."""
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
click_line = next((ln for ln in boot_js.splitlines() if "$('btnNewChat').onclick" in ln), "")
assert click_line, "btnNewChat onclick handler missing from static/boot.js"
assert "closeMobileSidebar" in click_line, \
"btnNewChat handler must closeMobileSidebar() after creating the new session"
shortcut_line = next((ln for ln in boot_js.splitlines() if "e.key==='k'" in ln or "e.key === 'k'" in ln), "")
assert shortcut_line, "Cmd/Ctrl+K new chat shortcut missing from static/boot.js"
shortcut_block = "\n".join(boot_js.splitlines()[boot_js.splitlines().index(shortcut_line):boot_js.splitlines().index(shortcut_line)+4])
assert "closeMobileSidebar" in shortcut_block, \
"Cmd/Ctrl+K new chat shortcut must closeMobileSidebar() after creating the new session"
# ── Viewport and scroll safety ────────────────────────────────────────────────
def test_body_overflow_hidden():
@@ -143,6 +161,32 @@ def test_body_overflow_hidden():
"body must have overflow:hidden to prevent double scrollbars"
def test_flex_parents_allow_message_scroller_to_shrink():
"""The top-level flex containers must opt into min-height:0 so .messages can scroll on mobile.
Mobile Safari/Chrome can trap scroll when a flex child with overflow:auto sits inside
parents whose min-height remains auto. Both .layout and .main need min-height:0.
"""
assert re.search(r'\.layout\{[^}]*min-height:0', CSS), \
".layout must set min-height:0 so the chat column can shrink and scroll"
assert re.search(r'\.main\{[^}]*min-height:0', CSS), \
".main must set min-height:0 so .messages remains scrollable while busy"
def test_messages_touch_scrolling_hints_present():
"""The messages scroller must advertise touch-friendly scrolling behavior.
On mobile browsers, momentum scrolling and explicit pan-y/overscroll behavior help
prevent the chat area from feeling locked while the app body itself stays overflow:hidden.
"""
assert re.search(r'\.messages\{[^}]*-webkit-overflow-scrolling:\s*touch', CSS), \
".messages must enable -webkit-overflow-scrolling:touch for mobile momentum scroll"
assert re.search(r'\.messages\{[^}]*touch-action:\s*pan-y', CSS), \
".messages must set touch-action:pan-y so vertical swipe gestures scroll the transcript"
assert re.search(r'\.messages\{[^}]*overscroll-behavior-y:\s*contain', CSS), \
".messages must contain vertical overscroll so the transcript keeps the gesture"
def test_100dvh_viewport_height():
"""Layout must use 100dvh (dynamic viewport height) for correct mobile sizing.

View File

@@ -0,0 +1,340 @@
"""Tests for fix: onboarding wizard must not fire when Hermes is already configured.
Issue #420 — existing Hermes users (config.yaml present + chat_ready) were
shown the first-run wizard because the only gate was settings.onboarding_completed.
Covers:
(a) config.yaml present + chat_ready=True → completed=True (no wizard)
(b) no config.yaml → completed=False (wizard fires)
(c) apply_onboarding_setup refuses to overwrite an existing config without
confirm_overwrite=True
"""
from __future__ import annotations
import json
import pathlib
import urllib.error
import urllib.request
from unittest import mock
import pytest
# ---------------------------------------------------------------------------
# Unit tests — no live server needed, test logic directly via imports
# ---------------------------------------------------------------------------
def _make_status(*, config_exists: bool, chat_ready: bool, onboarding_done: bool = False):
"""Call get_onboarding_status() with a controlled filesystem + settings."""
import importlib
# Import fresh copies each call so module-level state doesn't bleed across
import api.onboarding as mod
fake_config_path = pathlib.Path("/tmp/_test_config.yaml")
settings = {"onboarding_completed": onboarding_done}
# Build a minimal runtime dict that get_onboarding_status() would produce
# from _status_from_runtime. We only need the keys the gate checks.
runtime = {
"chat_ready": chat_ready,
"provider_configured": chat_ready,
"provider_ready": chat_ready,
"setup_state": "ready" if chat_ready else "needs_provider",
"provider_note": "test note",
"current_provider": "openrouter" if chat_ready else None,
"current_model": "anthropic/claude-sonnet-4.6" if chat_ready else None,
"current_base_url": None,
"env_path": "/tmp/.hermes_test/.env",
}
with (
mock.patch.object(mod, "load_settings", return_value=settings),
mock.patch.object(mod, "get_config", return_value={}),
mock.patch.object(
mod,
"verify_hermes_imports",
return_value=(chat_ready, [], {}),
),
mock.patch.object(mod, "_status_from_runtime", return_value=runtime),
mock.patch.object(mod, "load_workspaces", return_value=[]),
mock.patch.object(mod, "get_last_workspace", return_value=None),
mock.patch.object(mod, "get_available_models", return_value=[]),
mock.patch.object(mod, "_get_config_path", return_value=fake_config_path),
mock.patch.object(pathlib.Path, "exists") as mock_exists,
):
# Make Path(_get_config_path()).exists() return config_exists
mock_exists.return_value = config_exists
result = mod.get_onboarding_status()
return result
class TestOnboardingGate:
def test_config_exists_and_chat_ready_returns_completed_true(self):
"""Primary fix: existing valid config → wizard must NOT fire."""
result = _make_status(config_exists=True, chat_ready=True)
assert result["completed"] is True, (
"Wizard fired for existing Hermes user! "
"config.yaml + chat_ready must auto-complete onboarding."
)
def test_no_config_returns_completed_false(self):
"""Fresh install with no config → wizard should fire."""
result = _make_status(config_exists=False, chat_ready=False)
assert result["completed"] is False, (
"Fresh install must show the wizard (completed should be False)."
)
def test_config_exists_but_not_chat_ready_still_shows_wizard(self):
"""Broken/incomplete config (config.yaml exists but chat_ready=False) →
still show wizard so the user can fix it."""
result = _make_status(config_exists=True, chat_ready=False)
# Should NOT be auto-completed — config is present but broken
assert result["completed"] is False, (
"Broken config (chat_ready=False) must still show the wizard."
)
def test_onboarding_done_flag_always_respected(self):
"""If user already completed onboarding in settings, never show wizard."""
result = _make_status(config_exists=False, chat_ready=False, onboarding_done=True)
assert result["completed"] is True
def test_config_exists_always_exposed_in_system(self):
"""config_exists must still appear in the response system block."""
result = _make_status(config_exists=True, chat_ready=True)
assert "config_exists" in result["system"]
assert result["system"]["config_exists"] is True
class TestApplyOnboardingSetupGuard:
"""Fix #2: apply_onboarding_setup must not silently overwrite config.yaml."""
def _call_setup(self, body: dict, config_yaml_exists: bool):
import api.onboarding as mod
fake_config_path = pathlib.Path("/tmp/_test_config.yaml")
with (
mock.patch.object(mod, "_get_config_path", return_value=fake_config_path),
mock.patch.object(pathlib.Path, "exists", return_value=config_yaml_exists),
):
return mod.apply_onboarding_setup(body)
def test_setup_blocked_when_config_exists_without_confirm(self):
"""Must return an error dict (not raise) if config.yaml exists and no confirm_overwrite."""
result = self._call_setup(
{
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4.6",
"api_key": "test-key",
},
config_yaml_exists=True,
)
assert isinstance(result, dict), "Expected a dict response, not an exception"
assert result.get("error") == "config_exists", (
f"Expected error='config_exists', got: {result}"
)
assert result.get("requires_confirm") is True
def test_setup_allowed_with_confirm_overwrite(self):
"""With confirm_overwrite=True, setup may proceed (will hit real logic)."""
import api.onboarding as mod
fake_config_path = pathlib.Path("/tmp/_test_config_confirm.yaml")
fake_config_path.unlink(missing_ok=True) # start clean
try:
# Without patching Path.exists, use a non-existent path so it won't block
result = mod.apply_onboarding_setup(
{
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4.6",
"api_key": "test-key-confirm",
"confirm_overwrite": True,
}
)
# Should NOT return config_exists error
if isinstance(result, dict):
assert result.get("error") != "config_exists", (
"confirm_overwrite=True should bypass the config-exists guard."
)
finally:
fake_config_path.unlink(missing_ok=True)
def test_setup_allowed_when_no_config_exists(self):
"""Fresh install: no config.yaml → setup proceeds normally (no blocking error)."""
import api.onboarding as mod
fake_config_path = pathlib.Path("/tmp/_test_config_fresh.yaml")
fake_config_path.unlink(missing_ok=True)
try:
with mock.patch.object(mod, "_get_config_path", return_value=fake_config_path):
result = mod.apply_onboarding_setup(
{
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4.6",
"api_key": "test-key-fresh",
}
)
if isinstance(result, dict):
assert result.get("error") != "config_exists"
finally:
fake_config_path.unlink(missing_ok=True)
# ---------------------------------------------------------------------------
# Integration tests — require the live test server on port 8788
# ---------------------------------------------------------------------------
BASE = "http://127.0.0.1:8788"
def _http_get(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return json.loads(r.read()), r.status
def _http_post(path, body=None):
req = urllib.request.Request(
BASE + path,
data=json.dumps(body or {}).encode(),
headers={"Content-Type": "application/json"},
)
try:
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read()), r.status
except urllib.error.HTTPError as e:
return json.loads(e.read()), e.code
def _server_hermes_home() -> pathlib.Path:
data, _ = _http_get("/api/onboarding/status")
env_path = data.get("system", {}).get("env_path", "")
if env_path:
return pathlib.Path(env_path).parent
return pathlib.Path.home() / ".hermes" / "webui-mvp-test"
def _server_reachable() -> bool:
try:
_http_get("/health")
return True
except Exception:
return False
# Mark integration tests to only run when test server is up
requires_server = pytest.mark.skipif(
not _server_reachable(),
reason="Test server on :8788 not reachable",
)
try:
import yaml as _yaml
_HAS_YAML = True
except ImportError:
_HAS_YAML = False
_needs_yaml = pytest.mark.skipif(
not _HAS_YAML, reason="PyYAML not installed"
)
@requires_server
class TestOnboardingGateIntegration:
"""Live-server integration tests for the onboarding gate fix."""
@pytest.fixture(autouse=True)
def _clean(self):
hermes_home = _server_hermes_home()
for rel in ("config.yaml", ".env"):
(hermes_home / rel).unlink(missing_ok=True)
yield
for rel in ("config.yaml", ".env"):
(hermes_home / rel).unlink(missing_ok=True)
def test_no_config_wizard_fires(self):
"""No config.yaml → completed=False."""
data, status = _http_get("/api/onboarding/status")
assert status == 200
assert data["completed"] is False
@_needs_yaml
def test_existing_config_and_chat_ready_skips_wizard(self):
"""Write a valid config.yaml + .env → completed must be True."""
import yaml
hermes_home = _server_hermes_home()
# Write a real config.yaml
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
(hermes_home / "config.yaml").write_text(
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
)
# Write a fake API key so provider_ready (and thus chat_ready) fires
# — but only when hermes_cli imports are available
data, _ = _http_get("/api/onboarding/status")
if data["system"]["hermes_found"] and data["system"]["imports_ok"]:
(hermes_home / ".env").write_text(
"OPENROUTER_API_KEY=test-existing-key\n", encoding="utf-8"
)
data, status = _http_get("/api/onboarding/status")
assert status == 200
assert data["completed"] is True, (
"Existing config + chat_ready must auto-complete onboarding."
)
else:
# Agent not installed: chat_ready is always False, so wizard still
# fires — that is the correct behaviour (can't verify readiness).
assert data["completed"] is False
@_needs_yaml
def test_setup_blocked_for_existing_config(self):
"""POST /api/onboarding/setup must return config_exists error if config.yaml exists."""
import yaml
hermes_home = _server_hermes_home()
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
(hermes_home / "config.yaml").write_text(
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
)
data, status = _http_post(
"/api/onboarding/setup",
{
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4.6",
"api_key": "test-key",
},
)
assert status == 200
assert data.get("error") == "config_exists", (
f"Expected config_exists guard. Got: {data}"
)
assert data.get("requires_confirm") is True
@_needs_yaml
def test_setup_allowed_with_confirm_overwrite(self):
"""POST /api/onboarding/setup with confirm_overwrite=True succeeds."""
import yaml
hermes_home = _server_hermes_home()
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
(hermes_home / "config.yaml").write_text(
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
)
data, status = _http_post(
"/api/onboarding/setup",
{
"provider": "openrouter",
"model": "anthropic/claude-sonnet-4.6",
"api_key": "test-key",
"confirm_overwrite": True,
},
)
assert status == 200
assert data.get("error") != "config_exists", (
"confirm_overwrite=True must bypass the guard."
)

View File

@@ -0,0 +1,184 @@
"""
Tests: onboarding /api/onboarding/setup network restriction logic (issue #390).
Covers:
1. Request from 127.0.0.1 (loopback) is allowed without auth
2. Request from RFC-1918 private IP (172.x, 192.168.x, 10.x) is allowed without auth
3. Request from public IP is blocked without auth → 403
4. X-Forwarded-For loopback IP is trusted → allowed
5. X-Forwarded-For private IP is trusted → allowed
6. X-Forwarded-For public IP → still blocked
7. X-Real-IP loopback → allowed
8. HERMES_WEBUI_ONBOARDING_OPEN=1 bypasses the check entirely
9. Auth enabled → check skipped, any IP allowed
"""
import json
import os
import pathlib
import sys
import unittest.mock
import urllib.error
import urllib.request
import pytest
REPO = pathlib.Path(__file__).parent.parent
BASE = "http://127.0.0.1:8788"
# ---------------------------------------------------------------------------
# Unit tests — directly test the IP-resolution + guard logic in routes.py
# without needing a live server. We replicate the logic to keep tests fast
# and independent of server startup.
# ---------------------------------------------------------------------------
def _is_local_from_handler(
raw_ip: str,
xff: str = "",
xri: str = "",
auth_enabled: bool = False,
open_env: bool = False,
) -> bool | str:
"""
Mirror of the onboarding IP check in api/routes.py.
Returns True if the request would be allowed, False if blocked,
or the error message string if blocked.
"""
import ipaddress
if auth_enabled or open_env:
return True
_xff = xff.split(",")[0].strip() if xff else ""
_xri = xri.strip()
_ip_str = _xff or _xri or raw_ip
try:
addr = ipaddress.ip_address(_ip_str)
is_local = addr.is_loopback or addr.is_private
except ValueError:
is_local = False
return is_local
class TestOnboardingIPLogic:
"""Unit tests for the IP-resolution logic (no live server needed)."""
def test_loopback_allowed(self):
assert _is_local_from_handler("127.0.0.1") is True
def test_ipv6_loopback_allowed(self):
assert _is_local_from_handler("::1") is True
def test_private_172_allowed(self):
"""Docker bridge addresses (172.17.x.x) must be allowed."""
assert _is_local_from_handler("172.17.0.1") is True
def test_private_192168_allowed(self):
assert _is_local_from_handler("192.168.1.100") is True
def test_private_10_allowed(self):
assert _is_local_from_handler("10.0.0.5") is True
def test_public_ip_blocked(self):
assert _is_local_from_handler("8.8.8.8") is False
def test_xff_loopback_trusted(self):
"""Reverse proxy sets X-Forwarded-For to 127.0.0.1 — should be allowed."""
assert _is_local_from_handler("172.20.0.1", xff="127.0.0.1") is True
def test_xff_private_trusted(self):
"""Reverse proxy sets X-Forwarded-For to LAN IP — should be allowed."""
assert _is_local_from_handler("172.20.0.1", xff="192.168.1.50") is True
def test_xff_public_blocked(self):
"""Public IP in X-Forwarded-For should still be blocked."""
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8") is False
def test_xff_first_entry_used(self):
"""X-Forwarded-For may have multiple IPs; only the first (client) is used."""
# First entry is private → allowed
assert _is_local_from_handler("172.20.0.1", xff="10.0.0.1, 172.20.0.1") is True
# First entry is public → blocked
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8, 172.20.0.1") is False
def test_xreal_ip_loopback_trusted(self):
"""X-Real-IP loopback → allowed."""
assert _is_local_from_handler("172.20.0.1", xri="127.0.0.1") is True
def test_xreal_ip_private_trusted(self):
assert _is_local_from_handler("172.20.0.1", xri="10.1.2.3") is True
def test_xff_takes_priority_over_xri(self):
"""X-Forwarded-For wins over X-Real-IP when both present."""
# XFF says public, XRI says local → blocked (XFF takes priority)
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8", xri="127.0.0.1") is False
def test_open_env_bypasses_check(self):
"""HERMES_WEBUI_ONBOARDING_OPEN=1 allows any IP."""
assert _is_local_from_handler("8.8.8.8", open_env=True) is True
def test_auth_enabled_bypasses_check(self):
"""When auth is enabled, IP check is skipped entirely."""
assert _is_local_from_handler("8.8.8.8", auth_enabled=True) is True
def test_invalid_ip_blocked(self):
"""Malformed IP in header → treated as non-local → blocked."""
assert _is_local_from_handler("not-an-ip") is False
# ---------------------------------------------------------------------------
# Integration tests — hit the live test server at port 8788
# ---------------------------------------------------------------------------
@pytest.mark.integration
class TestOnboardingSetupEndpoint:
"""
Integration tests for /api/onboarding/setup.
These require the test server running on port 8788.
"""
def _post(self, path: str, data: dict, headers: dict | None = None) -> tuple[int, dict]:
payload = json.dumps(data).encode()
req = urllib.request.Request(
BASE + path,
data=payload,
method="POST",
headers={"Content-Type": "application/json", **(headers or {})},
)
try:
with urllib.request.urlopen(req, timeout=10) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read())
def test_loopback_request_allowed(self):
"""
Requests from 127.0.0.1 (which is what the test server sees) should
pass the IP check. We confirm no 403 is returned.
"""
# The test server runs on 127.0.0.1:8788 so client_address[0] is 127.0.0.1.
# A valid setup payload with a mock provider should not be rejected for IP reasons.
# We patch apply_onboarding_setup to avoid actually writing any config.
import unittest.mock
with unittest.mock.patch("api.onboarding.apply_onboarding_setup", return_value={"ok": True}):
status, body = self._post(
"/api/onboarding/setup",
{"provider": "anthropic", "model": "claude-sonnet-4.6", "api_key": "test-key"},
)
# Should not be 403 (IP blocked). May be 200 or another error from apply logic.
assert status != 403, f"Got 403 — IP check incorrectly blocked loopback. Body: {body}"
def test_xff_loopback_header_respected(self):
"""
Simulated reverse proxy: raw TCP is 127.0.0.1 but X-Forwarded-For is also
127.0.0.1. Should be allowed.
"""
import unittest.mock
with unittest.mock.patch("api.onboarding.apply_onboarding_setup", return_value={"ok": True}):
status, body = self._post(
"/api/onboarding/setup",
{"provider": "anthropic", "model": "claude-sonnet-4.6", "api_key": "test-key"},
headers={"X-Forwarded-For": "127.0.0.1"},
)
assert status != 403, f"Got 403 with XFF=127.0.0.1. Body: {body}"

View File

@@ -0,0 +1,121 @@
"""
Tests for OpenCode Zen and OpenCode Go provider support.
Verifies provider registration in display/model catalogs and
env-var fallback detection.
"""
import os
import sys
import types
import api.config as config
# ── Provider registration ─────────────────────────────────────────────
def test_opencode_zen_in_provider_display():
assert "opencode-zen" in config._PROVIDER_DISPLAY
assert config._PROVIDER_DISPLAY["opencode-zen"] == "OpenCode Zen"
def test_opencode_go_in_provider_display():
assert "opencode-go" in config._PROVIDER_DISPLAY
assert config._PROVIDER_DISPLAY["opencode-go"] == "OpenCode Go"
def test_opencode_zen_in_provider_models():
assert "opencode-zen" in config._PROVIDER_MODELS
ids = [m["id"] for m in config._PROVIDER_MODELS["opencode-zen"]]
assert "claude-opus-4-6" in ids
assert "gpt-5.4-pro" in ids
assert "glm-5.1" in ids
def test_opencode_go_in_provider_models():
assert "opencode-go" in config._PROVIDER_MODELS
ids = [m["id"] for m in config._PROVIDER_MODELS["opencode-go"]]
assert "glm-5.1" in ids
assert "glm-5" in ids
assert "mimo-v2-pro" in ids
# ── Env-var fallback detection ────────────────────────────────────────
def _models_with_env_key(monkeypatch, env_var, expected_provider_display):
"""Helper: fake hermes_cli unavailable, set an env var, check detection."""
# Force the env-var fallback path by making hermes_cli import fail
fake_mod = types.ModuleType("hermes_cli.models")
fake_mod.list_available_providers = None # will raise on call
monkeypatch.setitem(sys.modules, "hermes_cli.models", fake_mod)
monkeypatch.delattr(fake_mod, "list_available_providers")
old_cfg = dict(config.cfg)
config.cfg["model"] = {}
config.cfg.pop("custom_providers", None)
monkeypatch.setenv(env_var, "test-key")
try:
result = config.get_available_models()
providers = [g["provider"] for g in result["groups"]]
assert expected_provider_display in providers, (
f"Expected {expected_provider_display} in {providers}"
)
finally:
config.cfg.clear()
config.cfg.update(old_cfg)
def test_opencode_zen_detected_via_env_key(monkeypatch):
_models_with_env_key(monkeypatch, "OPENCODE_ZEN_API_KEY", "OpenCode Zen")
def test_opencode_go_detected_via_env_key(monkeypatch):
_models_with_env_key(monkeypatch, "OPENCODE_GO_API_KEY", "OpenCode Go")
def test_openai_codex_model_catalog_includes_gpt54():
"""openai-codex catalog must include gpt-5.4 and the standard Codex lineup."""
assert "openai-codex" in config._PROVIDER_MODELS
ids = [m["id"] for m in config._PROVIDER_MODELS["openai-codex"]]
assert "gpt-5.4" in ids, f"gpt-5.4 missing from openai-codex catalog: {ids}"
assert "gpt-5.4-mini" in ids, f"gpt-5.4-mini missing from openai-codex catalog: {ids}"
assert "gpt-5.3-codex" in ids, f"gpt-5.3-codex missing from openai-codex catalog: {ids}"
assert "gpt-5.2-codex" in ids, f"gpt-5.2-codex missing from openai-codex catalog: {ids}"
def test_openai_codex_display_name():
"""openai-codex must have a human-readable display name."""
assert "openai-codex" in config._PROVIDER_DISPLAY
assert config._PROVIDER_DISPLAY["openai-codex"] == "OpenAI Codex"
def test_live_models_handler_delegates_to_provider_model_ids():
"""_handle_live_models must delegate to the agent's provider_model_ids()
rather than maintain its own per-provider fetch logic.
"""
import pathlib
routes_src = (pathlib.Path(__file__).parent.parent / "api" / "routes.py").read_text()
assert "provider_model_ids" in routes_src, (
"_handle_live_models must call hermes_cli.models.provider_model_ids() "
"to delegate all provider-specific live-fetch logic to the agent"
)
# The old per-provider base_url hardcoding should be gone
assert "https://api.openai.com/v1" not in routes_src, (
"_handle_live_models must not hardcode api.openai.com — "
"provider resolution is handled by the agent"
)
assert "not_supported" not in routes_src, (
"_handle_live_models must not return not_supported for any provider — "
"provider_model_ids() falls back to static list automatically"
)
def test_live_models_ui_no_longer_skips_any_provider():
"""_fetchLiveModels in ui.js must not exclude any provider from live fetching.
Previously anthropic, google, and gemini were skipped — now provider_model_ids()
handles them all (with graceful fallback to static lists).
"""
import pathlib
ui_src = (pathlib.Path(__file__).parent.parent / "static" / "ui.js").read_text()
# The old exclusion list must be gone
assert "includes(provider)" not in ui_src or "anthropic" not in ui_src[:ui_src.find("includes(provider)")+100], (
"_fetchLiveModels must not skip anthropic, google, or gemini — "
"the backend now returns live models for all providers"
)

View File

@@ -0,0 +1,67 @@
import importlib
import os
import sys
from pathlib import Path
def test_profile_switch_clears_previous_profile_env_vars(monkeypatch, tmp_path):
base = tmp_path / ".hermes"
(base / "profiles" / "p1").mkdir(parents=True)
(base / "profiles" / "p2").mkdir(parents=True)
(base / "profiles" / "p1" / ".env").write_text(
"OPENAI_API_KEY=secret-from-p1\nCUSTOM_TOKEN=token-from-p1\n",
encoding="utf-8",
)
monkeypatch.setenv("HERMES_BASE_HOME", str(base))
monkeypatch.delenv("HERMES_HOME", raising=False)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.delenv("CUSTOM_TOKEN", raising=False)
sys.modules.pop("api.profiles", None)
profiles = importlib.import_module("api.profiles")
profiles = importlib.reload(profiles)
profiles.init_profile_state()
profiles.switch_profile("p1")
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p1"
assert os.environ.get("CUSTOM_TOKEN") == "token-from-p1"
profiles.switch_profile("p2")
assert os.environ.get("OPENAI_API_KEY") is None
assert os.environ.get("CUSTOM_TOKEN") is None
assert profiles.get_active_profile_name() == "p2"
def test_profile_switch_replaces_overlapping_keys(monkeypatch, tmp_path):
base = tmp_path / ".hermes"
(base / "profiles" / "p1").mkdir(parents=True)
(base / "profiles" / "p2").mkdir(parents=True)
(base / "profiles" / "p1" / ".env").write_text(
"OPENAI_API_KEY=secret-from-p1\nONLY_P1=one\n",
encoding="utf-8",
)
(base / "profiles" / "p2" / ".env").write_text(
"OPENAI_API_KEY=secret-from-p2\nONLY_P2=two\n",
encoding="utf-8",
)
monkeypatch.setenv("HERMES_BASE_HOME", str(base))
monkeypatch.delenv("HERMES_HOME", raising=False)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.delenv("ONLY_P1", raising=False)
monkeypatch.delenv("ONLY_P2", raising=False)
sys.modules.pop("api.profiles", None)
profiles = importlib.import_module("api.profiles")
profiles = importlib.reload(profiles)
profiles.init_profile_state()
profiles.switch_profile("p1")
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p1"
assert os.environ.get("ONLY_P1") == "one"
profiles.switch_profile("p2")
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p2"
assert os.environ.get("ONLY_P1") is None
assert os.environ.get("ONLY_P2") == "two"

View File

@@ -0,0 +1,63 @@
import importlib
import os
import sys
import tempfile
from pathlib import Path
import pytest
REPO_ROOT = Path(__file__).parent.parent.resolve()
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
def _reload_profiles_module(base_home: Path):
os.environ["HERMES_BASE_HOME"] = str(base_home)
os.environ["HERMES_HOME"] = str(base_home)
for name in ["api.config", "api.profiles"]:
if name in sys.modules:
del sys.modules[name]
profiles = importlib.import_module("api.profiles")
return profiles
def test_switch_profile_rejects_path_traversal():
with tempfile.TemporaryDirectory() as td:
temp_root = Path(td)
base = temp_root / ".hermes"
(base / "profiles").mkdir(parents=True)
(temp_root / "escape-target").mkdir()
profiles = _reload_profiles_module(base)
with pytest.raises(ValueError):
profiles.switch_profile("../../escape-target")
def test_delete_profile_rejects_path_traversal():
with tempfile.TemporaryDirectory() as td:
temp_root = Path(td)
base = temp_root / ".hermes"
(base / "profiles").mkdir(parents=True)
(temp_root / "escape-target").mkdir()
profiles = _reload_profiles_module(base)
with pytest.raises(ValueError):
profiles.delete_profile_api("../../escape-target")
def test_switch_profile_allows_valid_profile_name():
with tempfile.TemporaryDirectory() as td:
temp_root = Path(td)
base = temp_root / ".hermes"
profile_dir = base / "profiles" / "demo"
profile_dir.mkdir(parents=True)
profiles = _reload_profiles_module(base)
result = profiles.switch_profile("demo")
assert result["active"] == "demo"
assert Path(os.environ["HERMES_HOME"]).resolve() == profile_dir.resolve()

View File

@@ -241,6 +241,24 @@ def test_done_handler_guards_setbusy_with_inflight_check(cleanup_test_sessions):
assert "INFLIGHT[S.session.session_id]" in src, "messages.js must guard setBusy(false) with INFLIGHT check for current session"
def test_refresh_handler_does_not_drop_tool_messages_needed_by_todos(cleanup_test_sessions):
"""Todo panel state must survive session reload/refresh.
The UI can hide tool-role messages from the visible transcript, but it must not
destroy the raw session messages because loadTodos reconstructs state from the
latest todo tool output.
"""
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
ui_src = (REPO_ROOT / "static/ui.js").read_text()
panels_src = (REPO_ROOT / "static/panels.js").read_text()
assert "data.session.messages=(data.session.messages||[]).filter(" not in sessions_src, \
"sessions.js must not overwrite raw session.messages when filtering transcript display"
assert "S.messages = (data.session.messages || []).filter(" not in ui_src, \
"ui.js refreshSession must not rebuild S.messages by discarding tool messages from the raw session payload"
assert "const sourceMessages = (S.session && Array.isArray(S.session.messages) && S.session.messages.length) ? S.session.messages : S.messages;" in panels_src, \
"loadTodos must prefer raw S.session.messages so todo state survives reloads"
def test_cancel_button_not_cleared_across_sessions(cleanup_test_sessions):
"""R7c: The Cancel button and activeStreamId must only be cleared when the
done/error event belongs to the currently viewed session.
@@ -292,7 +310,10 @@ def test_server_delete_invalidates_index(cleanup_test_sessions):
text.find('if parsed.path == "/api/session/delete":'),
)
if delete_idx >= 0:
delete_block = text[delete_idx:delete_idx+600]
# Use 1200 chars to accommodate any validation/guard code added
# before the SESSION_INDEX_FILE.unlink() call (e.g. session_id
# character checks, path traversal guards).
delete_block = text[delete_idx:delete_idx+1200]
assert "SESSION_INDEX_FILE" in delete_block, \
f"{label} session/delete must invalidate SESSION_INDEX_FILE"
return
@@ -401,7 +422,7 @@ def test_done_handler_sets_busy_false_before_renderMessages(cleanup_test_session
if done_idx < 0:
done_idx = src.find("es.addEventListener('done'")
assert done_idx >= 0
done_block = src[done_idx:done_idx+1500]
done_block = src[done_idx:done_idx+2500]
# S.busy=false must appear before renderMessages() within the done handler
busy_pos = done_block.find("S.busy=false;")
render_pos = done_block.find("renderMessages()")
@@ -440,7 +461,166 @@ def test_newSession_clears_live_tool_cards(cleanup_test_sessions):
assert "clearLiveToolCards" in new_sess_body, "newSession() must call clearLiveToolCards() to clear stale live cards"
# ── R16: Stack traces must not leak to clients in 500 responses ────────────
def test_newSession_resets_busy_state_for_fresh_chat(cleanup_test_sessions):
"""R15b: newSession() must reset the viewed chat to idle state.
Without this, starting a second chat while another session is streaming leaves
S.busy=true, so the first send in the new chat gets incorrectly queued.
"""
src = (REPO_ROOT / "static/sessions.js").read_text()
new_sess_idx = src.find("async function newSession(")
assert new_sess_idx >= 0
next_fn = src.find("async function ", new_sess_idx + 10)
new_sess_body = src[new_sess_idx:next_fn]
assert "S.busy=false;" in new_sess_body, \
"newSession() must clear S.busy so a fresh chat is immediately sendable"
assert "S.activeStreamId=null;" in new_sess_body, \
"newSession() must clear the active stream id for the newly viewed chat"
assert "updateQueueBadge(S.session.session_id);" in new_sess_body, \
"newSession() must refresh the badge for the new session rather than leaving the old session's queue badge visible"
def test_session_scoped_message_queue_frontend_wiring(cleanup_test_sessions):
"""R15bb: queued follow-ups must stay attached to their originating session.
The frontend should use a session-keyed queue store and drain only the active
session's queued messages when that session becomes idle.
"""
ui_src = (REPO_ROOT / "static/ui.js").read_text()
messages_src = (REPO_ROOT / "static/messages.js").read_text()
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
assert "const SESSION_QUEUES" in ui_src
assert "function queueSessionMessage" in ui_src
assert "function shiftQueuedSessionMessage" in ui_src
assert "const sid=S.session&&S.session.session_id;" in ui_src
assert "const next=sid?shiftQueuedSessionMessage(sid):null;" in ui_src
assert "queueSessionMessage(S.session.session_id" in messages_src
assert "updateQueueBadge(S.session.session_id);" in messages_src
assert "updateQueueBadge(sid);" in sessions_src
def test_chat_start_persists_pending_turn_metadata_for_reload_recovery(cleanup_test_sessions):
"""R15c: chat/start must expose enough pending-turn metadata for a reload to
rebuild the in-flight conversation instead of showing a blank session.
"""
routes_src = (REPO_ROOT / "api/routes.py").read_text()
assert 's.active_stream_id = stream_id' in routes_src
assert 's.pending_user_message = msg' in routes_src
assert 's.pending_attachments = attachments' in routes_src
assert '"active_stream_id": getattr(s, "active_stream_id", None)' in routes_src
assert '"pending_user_message": getattr(s, "pending_user_message", None)' in routes_src
def test_reload_path_restores_pending_message_and_reattaches_live_stream(cleanup_test_sessions):
"""R15d: the frontend reload path must show the pending user turn and
reattach to the live SSE stream after loadSession().
"""
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
ui_src = (REPO_ROOT / "static/ui.js").read_text()
messages_src = (REPO_ROOT / "static/messages.js").read_text()
assert 'getPendingSessionMessage' in ui_src
assert 'pending_user_message' in ui_src
assert 'function attachLiveStream' in messages_src
assert 'const pendingMsg=typeof getPendingSessionMessage' in sessions_src
assert 'const activeStreamId=data.session.active_stream_id||null;' in sessions_src
assert 'attachLiveStream(sid, activeStreamId' in sessions_src
assert 'if (S.activeStreamId && S.activeStreamId === streamId) return;' in ui_src
# ── R16: Switching away/back must preserve live partial assistant output ─────
def test_live_stream_tokens_persist_partial_assistant_for_session_switch(cleanup_test_sessions):
"""R16: in-flight assistant text must be mirrored into INFLIGHT session state,
and the live stream must rebind to the rebuilt DOM after switching away and back.
Without this, partial assistant output disappears until the final done payload lands.
"""
messages_src = (REPO_ROOT / "static/messages.js").read_text()
ui_src = (REPO_ROOT / "static/ui.js").read_text()
assert "content:assistantText" in messages_src, \
"messages.js must persist the partial assistant text into INFLIGHT state"
assert "_live:true" in messages_src, \
"messages.js must mark the persisted in-flight assistant row so renderMessages can re-anchor it"
assert "syncInflightAssistantMessage();" in messages_src, \
"token handler must update INFLIGHT state before checking the active session"
assert "assistantRow&&!assistantRow.isConnected" in messages_src, \
"live stream must drop stale detached assistant DOM references after session switches"
assert "data-live-assistant" in ui_src, \
"renderMessages must preserve a live-assistant DOM anchor when rebuilding the thread"
def test_inflight_session_state_tracks_live_tool_cards_per_session(cleanup_test_sessions):
"""R16b: live tool cards must be stored on the in-flight session, not only in the
global S.toolCalls array, so switching chats does not lose or misattach them.
"""
messages_src = (REPO_ROOT / "static/messages.js").read_text()
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
assert "INFLIGHT[activeSid].toolCalls.push(tc);" in messages_src, \
"tool SSE handler must persist live tool calls onto the in-flight session"
assert "S.toolCalls=(INFLIGHT[sid].toolCalls||[]);" in sessions_src, \
"loadSession() must restore live tool calls from the in-flight session state"
def test_loadSession_inflight_sets_busy_before_renderMessages(cleanup_test_sessions):
"""R16c: loading an in-flight session must mark it busy before renderMessages().
Otherwise renderMessages() treats S.toolCalls as settled history cards and the
same tool call appears once inline and once in the live tool host after a
session switch.
"""
src = (REPO_ROOT / "static/sessions.js").read_text()
inflight_idx = src.find("if(INFLIGHT[sid]){")
assert inflight_idx >= 0, "INFLIGHT branch not found in loadSession"
inflight_block = src[inflight_idx:inflight_idx+700]
busy_pos = inflight_block.find("S.busy=true;")
render_pos = inflight_block.find("renderMessages();appendThinking();")
assert busy_pos >= 0, "loadSession INFLIGHT branch must set S.busy=true"
assert render_pos >= 0, "loadSession INFLIGHT branch must call renderMessages()"
assert busy_pos < render_pos, \
"loadSession must set S.busy=true before renderMessages() to avoid duplicate tool cards"
def test_streaming_bridge_accepts_current_tool_progress_callback_signature(cleanup_test_sessions):
"""R17: api/streaming.py must accept the current Hermes agent callback contract.
The agent now calls tool_progress_callback(event_type, name, preview, args, **kwargs).
If the WebUI bridge only accepts (name, preview, args), live tool updates silently vanish.
"""
src = (REPO_ROOT / "api/streaming.py").read_text()
assert "def on_tool(*cb_args, **cb_kwargs):" in src, \
"streaming.py must accept variable callback args for tool progress events"
assert "reasoning_callback=on_reasoning" in src, \
"streaming.py must wire the agent's reasoning callback into the SSE bridge"
assert "put('tool_complete'" in src or 'put("tool_complete"' in src, \
"streaming.py must emit live tool completion SSE events"
def test_messages_js_supports_live_reasoning_and_tool_completion(cleanup_test_sessions):
"""R18: messages.js must render live reasoning and react to tool completion events.
Without these handlers, the operator only sees generic Thinking… or nothing
until the final done snapshot redraws the whole turn.
"""
src = (REPO_ROOT / "static/messages.js").read_text()
assert "let reasoningText=''" in src, \
"messages.js must track streamed reasoning text separately from assistant text"
assert "source.addEventListener('reasoning'" in src or 'source.addEventListener("reasoning"' in src, \
"messages.js must listen for live reasoning SSE events"
assert "source.addEventListener('tool_complete'" in src or 'source.addEventListener("tool_complete"' in src, \
"messages.js must listen for live tool completion SSE events"
assert "function _parseStreamState()" in src, \
"messages.js must parse live stream state into reasoning + visible answer"
def test_ui_js_can_upgrade_thinking_spinner_into_live_reasoning_card(cleanup_test_sessions):
"""R19: ui.js must be able to replace the placeholder thinking spinner with
streamed reasoning text while a turn is in progress.
"""
src = (REPO_ROOT / "static/ui.js").read_text()
assert "function _thinkingMarkup(text='')" in src or 'function _thinkingMarkup(text="")' in src, \
"ui.js must centralize thinking row markup so it can switch between spinner and live text"
assert "function updateThinking(text=''){appendThinking(text);}" in src or 'function updateThinking(text=""){appendThinking(text);}' in src, \
"ui.js must expose an updateThinking helper for live reasoning rendering"
# ── R17: Stack traces must not leak to clients in 500 responses ────────────
def test_500_response_has_no_trace_field():
"""R16: HTTP 500 responses must not include a 'trace' field.
@@ -493,3 +673,24 @@ def test_skills_slash_command_defined():
# 3. i18n key cmd_skills must be referenced (wired to COMMANDS entry)
assert "cmd_skills" in src, \
"cmd_skills i18n key must be referenced in commands.js"
def test_reload_recovery_persists_durable_inflight_state(cleanup_test_sessions):
"""Reload recovery must persist a durable per-session inflight snapshot.
Without these helpers, loadSession() references loadInflightState() but a full
browser reload has no saved state to hydrate, so recovery silently no-ops.
"""
ui_src = (REPO_ROOT / "static/ui.js").read_text()
messages_src = (REPO_ROOT / "static/messages.js").read_text()
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
assert "const INFLIGHT_STATE_KEY = 'hermes-webui-inflight-state'" in ui_src
assert "function saveInflightState(sid, state)" in ui_src
assert "function loadInflightState(sid, streamId)" in ui_src
assert "function clearInflightState(sid)" in ui_src
assert "saveInflightState(activeSid" in messages_src, \
"messages.js must persist live stream snapshots while a turn is in flight"
assert "clearInflightState(activeSid)" in messages_src, \
"messages.js must clear durable inflight snapshots when the run ends/errors/cancels"
assert "const stored=loadInflightState(sid, activeStreamId);" in sessions_src, \
"loadSession() must hydrate in-flight state from durable browser storage on reload"

View File

@@ -0,0 +1,139 @@
import json
import pathlib
import subprocess
import textwrap
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
SESSIONS_JS = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text(encoding="utf-8")
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text(encoding="utf-8")
def _extract_function(source: str, name: str) -> str:
marker = f"function {name}"
start = source.index(marker)
brace_start = source.index("{", start)
depth = 0
for idx in range(brace_start, len(source)):
ch = source[idx]
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return source[start : idx + 1]
raise AssertionError(f"Could not extract {name}")
def _run_session_time_case(script_body: str) -> dict:
functions = "\n\n".join(
_extract_function(SESSIONS_JS, name)
for name in (
"_localDayOrdinal",
"_sessionCalendarBoundaries",
"_formatSessionDate",
"_formatRelativeSessionTime",
"_sessionTimeBucketLabel",
)
)
script = textwrap.dedent(
f"""
process.env.TZ = 'UTC';
const translations = {{
session_time_unknown: 'Unknown',
session_time_just_now: 'just now',
session_time_minutes_ago: (n) => `${{n}} minute${{n === 1 ? '' : 's'}} ago`,
session_time_hours_ago: (n) => `${{n}} hour${{n === 1 ? '' : 's'}} ago`,
session_time_days_ago: (n) => `${{n}} day${{n === 1 ? '' : 's'}} ago`,
session_time_last_week: 'last week',
session_time_bucket_today: 'Today',
session_time_bucket_yesterday: 'Yesterday',
session_time_bucket_this_week: 'This week',
session_time_bucket_last_week: 'Last week',
session_time_bucket_older: 'Older',
}};
function t(key, ...args) {{
const val = translations[key];
return typeof val === 'function' ? val(...args) : val;
}}
{functions}
{script_body}
"""
)
proc = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
return json.loads(proc.stdout)
def test_session_sidebar_js_has_dynamic_relative_time_helpers():
assert "function _sessionCalendarBoundaries" in SESSIONS_JS
assert "function _formatRelativeSessionTime" in SESSIONS_JS
assert "function _sessionTimeBucketLabel" in SESSIONS_JS
assert "session_time_bucket_last_week" in SESSIONS_JS
assert "session_time_bucket_this_week" in SESSIONS_JS
assert "session_time_bucket_older" in SESSIONS_JS
def test_session_sidebar_renders_relative_time_and_meta_rows():
assert "session-time" in SESSIONS_JS
assert "session-meta" in SESSIONS_JS
assert "orderedSessions" in SESSIONS_JS
assert ".session-time" in STYLE_CSS
assert ".session-meta" in STYLE_CSS
assert ".session-title-row" in STYLE_CSS
assert ".session-item.active .session-title" in STYLE_CSS
assert "metaBits.join(' · ')" in SESSIONS_JS
assert "|| _sessionTimeBucketLabel" not in SESSIONS_JS
assert "const ONE_DAY=86400000;" not in SESSIONS_JS
def test_relative_time_uses_calendar_boundaries_and_year_for_old_sessions():
result = _run_session_time_case(
"""
const now = Date.UTC(2026, 3, 15, 1, 0, 0);
const mondayLate = Date.UTC(2026, 3, 13, 23, 0, 0);
const oldSession = Date.UTC(2024, 2, 5, 12, 0, 0);
process.stdout.write(JSON.stringify({
relative: _formatRelativeSessionTime(mondayLate, now),
bucket: _sessionTimeBucketLabel(mondayLate, now),
oldDate: _formatRelativeSessionTime(oldSession, now),
}));
"""
)
assert result["relative"] == "2 days ago"
assert result["bucket"] == "This week"
assert "2024" in result["oldDate"]
def test_relative_time_handles_just_now_and_dst_safe_yesterday_boundary():
result = _run_session_time_case(
"""
const now = Date.UTC(2026, 2, 9, 12, 0, 0);
const justNow = now - 30 * 1000;
const yesterday = Date.UTC(2026, 2, 8, 23, 30, 0);
process.stdout.write(JSON.stringify({
justNow: _formatRelativeSessionTime(justNow, now),
yesterday: _formatRelativeSessionTime(yesterday, now),
yesterdayBucket: _sessionTimeBucketLabel(yesterday, now),
}));
"""
)
assert result["justNow"] == "just now"
assert result["yesterday"] == "Yesterday"
assert result["yesterdayBucket"] == "Yesterday"
def test_relative_time_strings_are_localized_in_english_and_spanish_bundles():
for key in (
"session_time_unknown",
"session_time_just_now",
"session_time_minutes_ago",
"session_time_hours_ago",
"session_time_days_ago",
"session_time_last_week",
"session_time_bucket_today",
"session_time_bucket_yesterday",
"session_time_bucket_this_week",
"session_time_bucket_last_week",
"session_time_bucket_older",
):
assert key in I18N_JS

View File

@@ -0,0 +1,66 @@
import json
import pathlib
import sys
import time
import urllib.parse
import urllib.request
import uuid
import pytest
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent.parent))
_needs_server = pytest.mark.usefixtures("test_server")
BASE = "http://127.0.0.1:8788"
_FULL_SECRET = "sk-" + ("B" * 24)
def _get(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return json.loads(r.read())
def _write_session_with_secret_title():
from tests.conftest import TEST_STATE_DIR
sid = "sec_summary_" + uuid.uuid4().hex[:8]
sessions_dir = TEST_STATE_DIR / "sessions"
sessions_dir.mkdir(parents=True, exist_ok=True)
now = time.time()
(sessions_dir / f"{sid}.json").write_text(json.dumps({
"session_id": sid,
"title": f"session with {_FULL_SECRET}",
"workspace": "/tmp",
"model": "test",
"created_at": now,
"updated_at": now,
"pinned": False,
"archived": False,
"project_id": None,
"profile": "default",
"input_tokens": 0,
"output_tokens": 0,
"estimated_cost": None,
"personality": None,
"messages": [],
"tool_calls": [],
}))
return sid
@_needs_server
def test_api_sessions_search_redacts_titles(test_server):
sid = _write_session_with_secret_title()
data = _get("/api/sessions/search?q=" + urllib.parse.quote("B" * 24))
dump = json.dumps(data)
assert sid in dump
assert _FULL_SECRET not in dump
@_needs_server
def test_api_sessions_list_redacts_secret_titles(test_server):
sid = _write_session_with_secret_title()
data = _get("/api/sessions")
dump = json.dumps(data)
assert sid in dump
assert _FULL_SECRET not in dump

View File

@@ -145,10 +145,13 @@ def test_session_update():
"""Create session, update workspace and model, verify persisted."""
data, _ = post("/api/session/new", {})
sid = data["session"]["session_id"]
current_ws = pathlib.Path(data["session"]["workspace"])
child_ws = current_ws / f"session-update-{uuid.uuid4().hex[:6]}"
child_ws.mkdir(parents=True, exist_ok=True)
updated, status = post("/api/session/update", {
"session_id": sid,
"workspace": "/tmp",
"workspace": str(child_ws),
"model": "anthropic/claude-sonnet-4.6"
})
assert status == 200

View File

@@ -107,14 +107,16 @@ def test_workspace_add_rejects_nonexistent():
assert status == 400
def test_workspace_add_accepts_real_dir():
"""Adding a real directory succeeds."""
import tempfile
tmp = tempfile.mkdtemp()
"""Adding a real directory under the trusted workspace root succeeds."""
d, _ = post("/api/session/new", {})
root = pathlib.Path(d["session"]["workspace"])
tmp = root / "trusted-add-test"
tmp.mkdir(parents=True, exist_ok=True)
try:
d, status = post("/api/workspaces/add", {"path": tmp, "name": "test-ws"})
d, status = post("/api/workspaces/add", {"path": str(tmp), "name": "test-ws"})
assert status == 200
assert d["ok"] is True
finally:
post("/api/workspaces/remove", {"path": tmp})
post("/api/workspaces/remove", {"path": str(tmp)})
import shutil
shutil.rmtree(tmp, ignore_errors=True)

View File

@@ -80,6 +80,16 @@ def test_security_headers_on_health():
assert headers.get("X-Content-Type-Options") == "nosniff"
def test_permissions_policy_does_not_disable_microphone():
"""Permissions-Policy must not hard-disable microphone access for same-origin voice input."""
_, status, headers = get("/health")
assert status == 200
policy = headers.get("Permissions-Policy", "")
assert policy, "Permissions-Policy header missing"
assert "microphone=()" not in policy, \
"Permissions-Policy must not block microphone access or desktop/mobile voice input cannot work"
def test_cache_control_no_store():
"""API responses should have Cache-Control: no-store."""
d, status, headers = get("/api/sessions")

View File

@@ -8,6 +8,7 @@ the browser with no server-side component.
import re
import urllib.request
import json
import pathlib
BASE = "http://127.0.0.1:8788"
@@ -315,15 +316,31 @@ def test_boot_js_iife_guard():
assert '(function(){' in js or '(function () {' in js
def test_boot_js_browser_unsupported_return():
"""boot.js must bail out (return) early when SpeechRecognition is unavailable."""
def test_boot_js_browser_unsupported_guard_uses_fallback_capabilities():
"""boot.js must keep the mic available when either speech recognition OR recorder capture exists."""
js, _ = get_text("/static/boot.js")
# The IIFE should have an early return when SpeechRecognition is falsy
assert 'if(!SpeechRecognition)' in js or 'if (!SpeechRecognition)' in js
assert 'navigator.mediaDevices' in js
assert 'getUserMedia' in js
assert 'MediaRecorder' in js
assert '_canRecordAudio' in js or 'canRecordAudio' in js, \
"boot.js should compute a recorder fallback instead of bailing only on SpeechRecognition"
def test_boot_js_shows_mic_button_when_supported():
"""boot.js must set display='' on btnMic when SpeechRecognition is available."""
def test_boot_js_media_recorder_fallback_posts_to_transcribe_api():
"""Desktop fallback must send recorded audio to /api/transcribe for transcription."""
js, _ = get_text("/static/boot.js")
assert '/api/transcribe' in js
assert 'fetch(' in js
def test_routes_define_transcribe_endpoint():
"""Server routes must expose /api/transcribe for MediaRecorder fallback uploads."""
routes = pathlib.Path(__file__).parent.parent.joinpath("api/routes.py").read_text(encoding="utf-8")
assert '"/api/transcribe"' in routes
def test_boot_js_shows_mic_button_when_any_voice_path_is_supported():
"""boot.js must reveal btnMic when speech recognition or recorder fallback is available."""
js, _ = get_text("/static/boot.js")
assert "btn.style.display=''" in js or 'btn.style.display = ""' in js

View File

@@ -21,6 +21,7 @@ import pathlib
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
sys.path.insert(0, str(pathlib.Path(__file__).parent))
@@ -51,10 +52,23 @@ def post(path, body=None, headers=None):
return json.loads(e.read()), e.code
def get_raw_with_headers(path):
req = urllib.request.Request(BASE + path)
with urllib.request.urlopen(req, timeout=10) as r:
return r.read(), dict(r.headers.items()), r.status
# ── 1. CSRF Protection ─────────────────────────────────────────────────────
class TestCSRF:
@staticmethod
def _csrf_allowed(headers):
from types import SimpleNamespace
from api.routes import _check_csrf
return _check_csrf(SimpleNamespace(headers=headers))
def test_no_origin_no_referer_allowed(self):
"""Curl-style request with no Origin/Referer must pass CSRF check."""
body, status = post("/api/sessions/new", {})
@@ -87,7 +101,212 @@ class TestCSRF:
{},
headers={"Referer": "http://127.0.0.1:8788/", "Host": "127.0.0.1:8788"},
)
assert status != 403, f"Expected non-403 for same-referer request, got {status}: {body}"
assert status != 403, f"Expected non-403 for same-referer request, got {status}"
def test_proxy_host_default_https_port_matches_http_origin(self):
"""http:// origin without port must NOT match X-Forwarded-Host with :443.
After the scheme-aware _ports_match fix: http:// absent port = :80,
which is not equal to :443. These are different protocols/ports and
should be rejected. In real reverse proxy scenarios where the external
URL is HTTPS, the browser sends Origin: https://... not http://...
See test_proxy_host_default_https_port_matches_https_origin for the
real-world proxy case that should pass.
"""
assert not self._csrf_allowed({
"Origin": "http://example.com",
"X-Forwarded-Host": "example.com:443",
}), 'http origin (port :80) must not match https host (:443)'
def test_proxy_host_default_https_port_matches_https_origin(self):
"""HTTPS Origin without port should match X-Forwarded-Host with explicit :443."""
assert self._csrf_allowed({
"Origin": "https://example.com",
"X-Forwarded-Host": "example.com:443",
})
def test_proxy_host_port_normalization_still_rejects_other_host(self):
"""Port normalization must not allow different hosts through."""
assert not self._csrf_allowed({
"Origin": "https://evil.com",
"X-Forwarded-Host": "example.com:443",
})
def test_allowed_public_origin_bypasses_missing_proxy_port(self, monkeypatch):
"""Explicitly configured public origins should pass even if proxy strips :port from Host."""
monkeypatch.setenv('HERMES_WEBUI_ALLOWED_ORIGINS', 'https://myapp.example.com:8000')
assert self._csrf_allowed({
'Origin': 'https://myapp.example.com:8000',
'Host': 'myapp.example.com',
'X-Forwarded-Proto': 'https',
})
def test_other_origin_not_allowed_by_public_origin_allowlist(self, monkeypatch):
"""Allowlist must stay exact; unrelated origins must still be rejected."""
monkeypatch.setenv('HERMES_WEBUI_ALLOWED_ORIGINS', 'https://myapp.example.com:8000')
assert not self._csrf_allowed({
'Origin': 'https://evil.com:8000',
'Host': 'myapp.example.com',
'X-Forwarded-Proto': 'https',
})
# ── Port normalization: scheme-aware (M-1 fix) ────────────────────────────
def test_cross_protocol_port_not_confused_http_origin_https_host(self):
"""http:// origin must NOT match a host with :443 (HTTPS default).
Before M-1 fix, _ports_match treated both 80 and 443 as equivalent to
absent port, allowing http://host to match https://host:443 servers.
"""
assert not self._csrf_allowed({
'Origin': 'http://example.com', # http, no port = :80
'X-Forwarded-Host': 'example.com:443', # HTTPS port
}), 'http origin should NOT match host advertising port 443'
def test_cross_protocol_port_not_confused_https_origin_http_host(self):
"""https:// origin must NOT match a host with :80 (HTTP default)."""
assert not self._csrf_allowed({
'Origin': 'https://example.com', # https, no port = :443
'X-Forwarded-Host': 'example.com:80', # HTTP port
}), 'https origin should NOT match host advertising port 80'
def test_http_explicit_port_80_matches_host_without_port(self):
"""http://example.com:80 is the same origin as http://example.com."""
assert self._csrf_allowed({
'Origin': 'http://example.com:80',
'Host': 'example.com',
})
def test_https_explicit_port_443_matches_host_without_port(self):
"""https://example.com:443 is the same origin as https://example.com."""
assert self._csrf_allowed({
'Origin': 'https://example.com:443',
'Host': 'example.com',
})
def test_non_default_port_not_waived(self):
"""Non-default ports (e.g. :8000) must not be treated as equivalent to absent."""
assert not self._csrf_allowed({
'Origin': 'https://example.com:8000',
'Host': 'example.com',
})
# ── Bug scenario: proxy strips non-standard port ──────────────────────────
def test_bug_origin_8000_host_without_port_rejected_without_allowlist(self, monkeypatch):
"""Without the allowlist, origin with :8000 must be rejected when proxy strips port.
This documents the original bug: Origin: https://app.com:8000 with
Host: app.com (proxy stripped the port). Before this PR that returned 403.
The fix (HERMES_WEBUI_ALLOWED_ORIGINS) handles it; without the env var
the request is still rejected, which is the safe default.
"""
monkeypatch.delenv('HERMES_WEBUI_ALLOWED_ORIGINS', raising=False)
assert not self._csrf_allowed({
'Origin': 'https://myapp.example.com:8000',
'Host': 'myapp.example.com',
}), 'without allowlist, port mismatch must be rejected (safe default)'
def test_allowed_origins_comma_separated(self, monkeypatch):
"""HERMES_WEBUI_ALLOWED_ORIGINS accepts multiple comma-separated origins."""
monkeypatch.setenv(
'HERMES_WEBUI_ALLOWED_ORIGINS',
'https://app1.example.com:8000, https://app2.example.com:9000',
)
assert self._csrf_allowed({'Origin': 'https://app1.example.com:8000', 'Host': 'proxy.internal'})
assert self._csrf_allowed({'Origin': 'https://app2.example.com:9000', 'Host': 'proxy.internal'})
assert not self._csrf_allowed({'Origin': 'https://evil.com:8000', 'Host': 'proxy.internal'})
def test_allowed_origins_without_scheme_ignored(self, monkeypatch, capsys):
"""Allowlist entries missing the scheme are skipped and a warning is printed."""
monkeypatch.setenv('HERMES_WEBUI_ALLOWED_ORIGINS', 'myapp.example.com:8000')
from api.routes import _allowed_public_origins
result = _allowed_public_origins()
assert len(result) == 0, 'entry without scheme must be ignored'
captured = capsys.readouterr()
assert 'WARNING' in captured.err and 'scheme' in captured.err.lower()
def test_allowed_origins_trailing_slash_normalized(self, monkeypatch):
"""Trailing slash in allowlist entry is stripped before comparison."""
monkeypatch.setenv('HERMES_WEBUI_ALLOWED_ORIGINS', 'https://myapp.example.com:8000/')
assert self._csrf_allowed({
'Origin': 'https://myapp.example.com:8000',
'Host': 'proxy.internal',
})
# ── CSRF helpers: unit tests ─────────────────────────────────────────────────
class TestCSRFHelpers:
"""Direct unit tests for _normalize_host_port and _ports_match."""
def test_normalize_host_only(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('example.com') == ('example.com', None)
def test_normalize_host_with_port(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('example.com:8000') == ('example.com', '8000')
def test_normalize_ipv6_no_port(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('[::1]') == ('::1', None)
def test_normalize_ipv6_with_port(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('[::1]:8080') == ('::1', '8080')
def test_normalize_empty(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('') == ('', None)
def test_normalize_whitespace_stripped(self):
from api.routes import _normalize_host_port
assert _normalize_host_port(' example.com ') == ('example.com', None)
def test_normalize_lowercases(self):
from api.routes import _normalize_host_port
assert _normalize_host_port('EXAMPLE.COM:80') == ('example.com', '80')
def test_ports_match_identical(self):
from api.routes import _ports_match
assert _ports_match('https', '8000', '8000') is True
def test_ports_match_both_absent(self):
from api.routes import _ports_match
assert _ports_match('https', None, None) is True
def test_ports_match_https_absent_vs_443(self):
from api.routes import _ports_match
assert _ports_match('https', None, '443') is True
assert _ports_match('https', '443', None) is True
def test_ports_match_http_absent_vs_80(self):
from api.routes import _ports_match
assert _ports_match('http', None, '80') is True
assert _ports_match('http', '80', None) is True
def test_ports_match_http_absent_vs_443_rejected(self):
"""http:// scheme: absent port is :80, not :443."""
from api.routes import _ports_match
assert _ports_match('http', None, '443') is False
assert _ports_match('http', '443', None) is False
def test_ports_match_https_absent_vs_80_rejected(self):
"""https:// scheme: absent port is :443, not :80."""
from api.routes import _ports_match
assert _ports_match('https', None, '80') is False
assert _ports_match('https', '80', None) is False
def test_ports_match_non_default_never_waived(self):
from api.routes import _ports_match
assert _ports_match('https', None, '8000') is False
assert _ports_match('https', '8000', None) is False
assert _ports_match('http', None, '8080') is False
def test_ports_match_different_non_default(self):
from api.routes import _ports_match
assert _ports_match('https', '8000', '9000') is False
# ── 2. Login Rate Limiting ─────────────────────────────────────────────────
@@ -338,6 +557,52 @@ class TestContentDisposition:
assert "image/svg+xml" in src
assert "dangerous_types" in src
def test_unicode_filename_download_header_is_latin1_safe(self, cleanup_test_sessions):
"""Unicode filenames must not crash download responses."""
body, status = post("/api/session/new", {})
assert status == 200, body
sid = body["session"]["session_id"]
cleanup_test_sessions.append(sid)
ws = pathlib.Path(body["session"]["workspace"])
filename = "中文对照表.pdf"
pdf_bytes = b"%PDF-1.3\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n"
(ws / filename).write_bytes(pdf_bytes)
encoded = urllib.parse.quote(filename)
raw, headers, raw_status = get_raw_with_headers(
f"/api/file/raw?session_id={sid}&path={encoded}&download=1"
)
assert raw_status == 200
assert raw == pdf_bytes
disp = headers["Content-Disposition"]
assert disp.startswith("attachment; ")
assert "filename*=UTF-8''" in disp
disp.encode("latin-1")
def test_unicode_filename_inline_header_is_latin1_safe(self, cleanup_test_sessions):
"""Inline responses must also work for unicode filenames."""
body, status = post("/api/session/new", {})
assert status == 200, body
sid = body["session"]["session_id"]
cleanup_test_sessions.append(sid)
ws = pathlib.Path(body["session"]["workspace"])
filename = "预览.pdf"
pdf_bytes = b"%PDF-1.3\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n"
(ws / filename).write_bytes(pdf_bytes)
encoded = urllib.parse.quote(filename)
raw, headers, raw_status = get_raw_with_headers(
f"/api/file/raw?session_id={sid}&path={encoded}"
)
assert raw_status == 200
assert raw == pdf_bytes
disp = headers["Content-Disposition"]
assert disp.startswith("inline; ")
assert "filename*=UTF-8''" in disp
disp.encode("latin-1")
# ── 9. PBKDF2 Password Hashing ───────────────────────────────────────────

View File

@@ -114,6 +114,24 @@ def test_session_delete_requires_session_id():
result, status = post("/api/session/delete", {})
assert status == 400
def test_session_delete_rejects_absolute_path_payload(tmp_path):
victim = tmp_path / "victim.json"
victim.write_text("TOPSECRET", encoding="utf-8")
result, status = post("/api/session/delete", {"session_id": str(victim.with_suffix(""))})
assert status == 400
assert victim.exists(), "absolute-path payload must not delete arbitrary files"
def test_session_delete_rejects_traversal_payload(tmp_path):
victim = tmp_path / "outside.json"
victim.write_text("TOPSECRET", encoding="utf-8")
traversal = f"../../../../{victim.with_suffix('').as_posix().lstrip('/')}"
result, status = post("/api/session/delete", {"session_id": traversal})
assert status == 400
assert victim.exists(), "traversal payload must not delete arbitrary files"
def test_chat_start_requires_session_id():
result, status = post("/api/chat/start", {"message": "hello"})
assert status == 400
@@ -127,6 +145,43 @@ def test_session_update_unknown_id_returns_404():
result, status = post("/api/session/update", {"session_id": "nosuchsession", "model": "openai/gpt-5.4-mini"})
assert status == 404
def test_session_update_rejects_workspace_outside_trusted_root(tmp_path):
d, _ = post("/api/session/new", {})
sid = d["session"]["session_id"]
outside = tmp_path / "outside"
outside.mkdir(parents=True, exist_ok=True)
result, status = post("/api/session/update", {"session_id": sid, "workspace": str(outside)})
assert status == 400
assert "outside" in result.get("error", "").lower()
def test_chat_start_rejects_workspace_outside_trusted_root(tmp_path):
d, _ = post("/api/session/new", {})
sid = d["session"]["session_id"]
outside = tmp_path / "outside-chat"
outside.mkdir(parents=True, exist_ok=True)
result, status = post("/api/chat/start", {"session_id": sid, "message": "hello", "workspace": str(outside)})
assert status == 400
assert "outside" in result.get("error", "").lower()
def test_workspace_add_rejects_path_outside_trusted_root(tmp_path):
outside = tmp_path / "outside-add"
outside.mkdir(parents=True, exist_ok=True)
result, status = post("/api/workspaces/add", {"path": str(outside), "name": "Outside"})
assert status == 400
assert "outside" in result.get("error", "").lower()
def test_session_new_rejects_workspace_outside_trusted_root(tmp_path):
outside = tmp_path / "outside-new"
outside.mkdir(parents=True, exist_ok=True)
result, status = post("/api/session/new", {"workspace": str(outside)})
assert status == 400
assert "outside" in result.get("error", "").lower()
def test_session_search_returns_matches(cleanup_test_sessions):
sid, _ = make_session_tracked(cleanup_test_sessions)
post("/api/session/rename", {"session_id": sid, "title": f"unique-s3-{sid}"})

View File

@@ -232,7 +232,7 @@ class TestOnboardingStatusApiOAuth:
def test_control_center_resets_active_section_on_close():
"""Closing the control center must reset _settingsSection to 'conversation'."""
src = open('static/panels.js').read()
src = open(pathlib.Path(__file__).parent.parent / 'static' / 'panels.js').read()
assert '_settingsSection' in src, '_settingsSection state variable missing from panels.js'
assert "_settingsSection = 'conversation'" in src or "_settingsSection='conversation'" in src, \
'Control center does not reset section to conversation on close'
@@ -240,5 +240,61 @@ def test_control_center_resets_active_section_on_close():
def test_control_center_tab_highlight_on_open():
"""Opening the control center must use settings-tabs for section navigation."""
css = open('static/style.css').read()
css = open(pathlib.Path(__file__).parent.parent / 'static' / 'style.css').read()
assert 'settings-tabs' in css, 'settings-tabs CSS class for control center tabs missing from style.css'
# ── apply_onboarding_setup: unsupported/OAuth providers complete gracefully ──
class TestApplyOnboardingSetupUnsupportedProvider:
"""PR #323 / Issue #322: apply_onboarding_setup must not raise ValueError for
providers already configured via CLI (openai-codex, copilot, nous, etc.).
Instead it marks onboarding complete and returns current status.
"""
def _call(self, provider: str) -> dict:
import sys, pathlib, unittest.mock, tempfile, os
repo = pathlib.Path(__file__).parent.parent
if str(repo) not in sys.path:
sys.path.insert(0, str(repo))
from api.onboarding import apply_onboarding_setup
with tempfile.TemporaryDirectory() as tmp:
with unittest.mock.patch("api.onboarding._get_active_hermes_home",
return_value=pathlib.Path(tmp)), \
unittest.mock.patch("api.onboarding._get_config_path",
return_value=pathlib.Path(tmp) / "config.yaml"), \
unittest.mock.patch("api.onboarding.save_settings") as mock_save, \
unittest.mock.patch("api.onboarding.get_onboarding_status",
return_value={"completed": True, "system": {}}):
result = apply_onboarding_setup({"provider": provider, "model": "", "api_key": ""})
return result, mock_save
def test_openai_codex_does_not_raise(self):
"""apply_onboarding_setup with openai-codex must not raise ValueError."""
result, _ = self._call("openai-codex")
assert result is not None
def test_copilot_does_not_raise(self):
"""apply_onboarding_setup with copilot must not raise ValueError."""
result, _ = self._call("copilot")
assert result is not None
def test_nous_does_not_raise(self):
"""apply_onboarding_setup with nous must not raise ValueError."""
result, _ = self._call("nous")
assert result is not None
def test_unsupported_provider_marks_onboarding_complete(self):
"""apply_onboarding_setup with an unsupported provider must save onboarding_completed=True."""
_, mock_save = self._call("openai-codex")
calls = [str(c) for c in mock_save.call_args_list]
assert any("onboarding_completed" in c for c in calls), \
"save_settings must be called with onboarding_completed=True for unsupported providers"
def test_unsupported_provider_returns_status_dict(self):
"""apply_onboarding_setup with an unsupported provider must return a status dict (not raise)."""
result, _ = self._call("openai-codex")
assert isinstance(result, dict), \
"apply_onboarding_setup must return a dict for unsupported providers, not raise"

111
tests/test_sprint38.py Normal file
View File

@@ -0,0 +1,111 @@
"""
Sprint 38 Tests: Think-tag stripping with leading whitespace (PR #327).
Covers the static render path (ui.js regex logic, verified against the JS source)
and the streaming render path (messages.js _streamDisplay logic).
"""
import pathlib
import re
REPO_ROOT = pathlib.Path(__file__).parent.parent
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text()
MSG_JS = (REPO_ROOT / "static" / "messages.js").read_text()
# ── ui.js: static render path ────────────────────────────────────────────────
def test_think_regex_has_no_anchor():
"""The <think> regex in ui.js must not use a ^ anchor so leading whitespace is allowed."""
# Find the thinkMatch line by locating the .match( call on that line
idx = UI_JS.find("const thinkMatch=content.match(")
assert idx >= 0, "thinkMatch line not found in ui.js"
line = UI_JS[idx:idx+100]
# The regex must NOT start with ^ right after the opening /
assert "/^<think>" not in line and "(/^" not in line, \
f"thinkMatch regex must not use ^ anchor — found: {line.strip()}"
def test_gemma_regex_has_no_anchor():
"""The Gemma channel-token regex in ui.js must not use a ^ anchor."""
match = re.search(r'const gemmaMatch=content\.match\((/[^/]+/)\)', UI_JS)
assert match, "gemmaMatch line not found in ui.js"
pattern = match.group(1)
assert not pattern.startswith('/^'), \
f"gemmaMatch regex must not use ^ anchor — got {pattern}"
def test_think_content_removal_uses_replace_not_slice():
"""After extracting thinkingText, content must use .replace() not .slice() to remove the tag."""
# Find the block that handles thinkMatch
idx = UI_JS.find("if(thinkMatch){")
assert idx >= 0, "thinkMatch handler block not found"
block = UI_JS[idx:idx+200]
assert "content.replace(" in block, \
"ui.js must use content.replace() to remove <think> block (not .slice())"
assert ".trimStart()" in block, \
"ui.js must call .trimStart() on content after removing the <think> block"
def test_gemma_content_removal_uses_replace_not_slice():
"""Gemma channel token removal must also use .replace() not .slice()."""
idx = UI_JS.find("if(gemmaMatch){")
assert idx >= 0, "gemmaMatch handler block not found"
block = UI_JS[idx:idx+200]
assert "content.replace(" in block, \
"ui.js must use content.replace() to remove Gemma channel block (not .slice())"
assert ".trimStart()" in block, \
"ui.js must call .trimStart() on content after removing the Gemma channel block"
# ── messages.js: streaming render path ───────────────────────────────────────
def test_stream_display_trims_before_startswith():
"""_streamDisplay in messages.js must call .trimStart() before .startsWith() check."""
fn_idx = MSG_JS.find("function _streamDisplay()")
assert fn_idx >= 0, "_streamDisplay function not found in messages.js"
fn_end = MSG_JS.find("\n }", fn_idx) + 4
fn_body = MSG_JS[fn_idx:fn_end]
assert "trimStart()" in fn_body, \
"_streamDisplay must call trimStart() to handle models that emit leading whitespace before <think>"
def test_stream_display_uses_trimmed_for_startswith():
"""_streamDisplay must check trimmed.startsWith(open), not raw.startsWith(open)."""
fn_idx = MSG_JS.find("function _streamDisplay()")
fn_end = MSG_JS.find("\n }", fn_idx) + 4
fn_body = MSG_JS[fn_idx:fn_end]
assert "trimmed.startsWith(open)" in fn_body, \
"_streamDisplay must use trimmed.startsWith(open) not raw.startsWith(open)"
def test_stream_display_partial_tag_uses_trimmed():
"""The partial-tag guard in _streamDisplay must also use trimmed, not raw."""
fn_idx = MSG_JS.find("function _streamDisplay()")
fn_end = MSG_JS.find("\n }", fn_idx) + 4
fn_body = MSG_JS[fn_idx:fn_end]
assert "open.startsWith(trimmed)" in fn_body, \
"Partial-tag guard must use open.startsWith(trimmed) not open.startsWith(raw)"
def test_stream_display_trims_return_after_close():
"""After stripping a completed think block, _streamDisplay must trim leading whitespace from the result."""
fn_idx = MSG_JS.find("function _streamDisplay()")
fn_end = MSG_JS.find("\n }", fn_idx) + 4
fn_body = MSG_JS[fn_idx:fn_end]
# The return after finding close must strip whitespace from the result
assert ".replace(/^" in fn_body and "s+/,'')" in fn_body, \
"_streamDisplay must strip leading whitespace from content after the closing think tag"
# ── Regression: existing anchored patterns must be gone ──────────────────────
def test_no_anchored_think_regex_in_ui_js():
"""The old anchored regex /^<think>/ must not exist in ui.js."""
assert "/^<think>" not in UI_JS, \
"Old anchored /^<think>/ regex still present in ui.js — fix not applied"
def test_no_anchored_gemma_regex_in_ui_js():
"""The old anchored Gemma regex must not exist in ui.js."""
assert "/^<|channel>" not in UI_JS, \
"Old anchored /^<|channel>/ regex still present in ui.js — fix not applied"

186
tests/test_sprint39.py Normal file
View File

@@ -0,0 +1,186 @@
"""
Sprint 39 Tests: Skip-onboarding env var + onboarding key reload fix (PR A of issue #329).
Covers:
- HERMES_WEBUI_SKIP_ONBOARDING=1 bypasses the wizard when chat_ready is true
- HERMES_WEBUI_SKIP_ONBOARDING=1 does NOT bypass when chat_ready is false
- HERMES_WEBUI_SKIP_ONBOARDING unset leaves default behaviour unchanged
- apply_onboarding_setup sets os.environ synchronously when an API key is saved
"""
import os
import unittest
from unittest.mock import patch
import api.onboarding as mod
_READY_RUNTIME = {
"chat_ready": True,
"provider_configured": True,
"provider_ready": True,
"setup_state": "ready",
"provider_note": "Ready",
"current_provider": "openai",
"current_model": "gpt-4o",
"current_base_url": None,
"env_path": "/tmp/test.env",
}
_NOT_READY_RUNTIME = {
"chat_ready": False,
"provider_configured": False,
"provider_ready": False,
"setup_state": "needs_provider",
"provider_note": "Needs setup",
"current_provider": None,
"current_model": None,
"current_base_url": None,
"env_path": "/tmp/test.env",
}
_COMMON_PATCHES = [
("api.onboarding.load_settings", lambda: {}),
("api.onboarding.get_config", lambda: {}),
("api.onboarding.verify_hermes_imports",lambda: (True, [], [])),
("api.onboarding.load_workspaces", lambda: []),
("api.onboarding.get_last_workspace", lambda: "/tmp"),
("api.onboarding.get_available_models", lambda: []),
("api.onboarding.is_auth_enabled", lambda: False),
("api.onboarding._build_setup_catalog", lambda cfg: {}),
("api.onboarding._get_config_path", lambda: __import__("pathlib").Path("/tmp/fake.yaml")),
]
def _apply_patches(extra_patches=()):
patches = []
for target, side_effect in _COMMON_PATCHES:
p = patch(target, side_effect=side_effect)
patches.append(p)
for target, side_effect in extra_patches:
p = patch(target, side_effect=side_effect)
patches.append(p)
return patches
class TestSkipOnboardingEnvVar(unittest.TestCase):
def _run_status(self, runtime, env_override):
runtime_patches = [("api.onboarding._status_from_runtime", lambda cfg, ok: runtime)]
all_patches = _apply_patches(runtime_patches)
with patch.dict(os.environ, env_override, clear=False):
for p in all_patches:
p.start()
try:
return mod.get_onboarding_status()
finally:
for p in all_patches:
p.stop()
def test_skip_env_1_and_chat_ready_marks_completed(self):
"""HERMES_WEBUI_SKIP_ONBOARDING=1 + chat_ready=True → completed=True."""
status = self._run_status(_READY_RUNTIME, {"HERMES_WEBUI_SKIP_ONBOARDING": "1"})
self.assertTrue(status["completed"],
"completed must be True when skip env var is 1 and chat_ready")
def test_skip_env_true_and_chat_ready_marks_completed(self):
"""HERMES_WEBUI_SKIP_ONBOARDING=true also accepted."""
status = self._run_status(_READY_RUNTIME, {"HERMES_WEBUI_SKIP_ONBOARDING": "true"})
self.assertTrue(status["completed"])
def test_skip_env_yes_and_chat_ready_marks_completed(self):
"""HERMES_WEBUI_SKIP_ONBOARDING=yes also accepted."""
status = self._run_status(_READY_RUNTIME, {"HERMES_WEBUI_SKIP_ONBOARDING": "yes"})
self.assertTrue(status["completed"])
def test_skip_env_set_but_not_chat_ready_does_not_skip(self):
"""HERMES_WEBUI_SKIP_ONBOARDING=1 + chat_ready=False → still shows wizard."""
status = self._run_status(_NOT_READY_RUNTIME, {"HERMES_WEBUI_SKIP_ONBOARDING": "1"})
self.assertFalse(status["completed"],
"completed must be False when not chat_ready even if skip env set")
def test_skip_env_unset_leaves_default_false(self):
"""Without the env var, completed is False when settings are empty."""
env = {k: v for k, v in os.environ.items() if k != "HERMES_WEBUI_SKIP_ONBOARDING"}
with patch.dict(os.environ, env, clear=True):
status = self._run_status(_READY_RUNTIME, {})
self.assertFalse(status["completed"],
"completed must be False when env var absent and settings empty")
def test_settings_completed_still_works_without_env_var(self):
"""onboarding_completed in settings → completed=True regardless of env var."""
runtime_patches = [("api.onboarding._status_from_runtime", lambda cfg, ok: _READY_RUNTIME)]
settings_patch = [("api.onboarding.load_settings", lambda: {"onboarding_completed": True})]
all_patches = _apply_patches(runtime_patches + settings_patch)
env = {k: v for k, v in os.environ.items() if k != "HERMES_WEBUI_SKIP_ONBOARDING"}
with patch.dict(os.environ, env, clear=True):
for p in all_patches:
p.start()
try:
status = mod.get_onboarding_status()
finally:
for p in all_patches:
p.stop()
self.assertTrue(status["completed"])
class TestApplyOnboardingKeySync(unittest.TestCase):
"""Verify that apply_onboarding_setup sets os.environ synchronously."""
def test_api_key_set_in_os_environ_after_apply(self):
"""After apply_onboarding_setup with a key, os.environ must have the key."""
import pathlib
os.environ.pop("OPENAI_API_KEY", None)
mock_cfg = {"model": {"provider": "openai", "default": "gpt-4o"}}
with patch("api.onboarding._load_yaml_config", return_value=mock_cfg), \
patch("api.onboarding._save_yaml_config"), \
patch("api.onboarding._write_env_file"), \
patch("api.onboarding.reload_config"), \
patch("api.onboarding.get_onboarding_status", return_value={"completed": True}), \
patch("api.onboarding._get_config_path", return_value=pathlib.Path("/tmp/fake.yaml")), \
patch("api.onboarding._load_env_file", return_value={}), \
patch("api.onboarding._provider_api_key_present", return_value=False), \
patch("api.onboarding._get_active_hermes_home", return_value=pathlib.Path("/tmp")):
mod.apply_onboarding_setup({
"provider": "openai",
"model": "gpt-4o",
"api_key": "sk-test-key-123",
})
self.assertEqual(os.environ.get("OPENAI_API_KEY"), "sk-test-key-123",
"OPENAI_API_KEY must be set directly on os.environ after apply")
os.environ.pop("OPENAI_API_KEY", None)
def test_no_key_provided_does_not_set_environ(self):
"""If no api_key is given (key already present), os.environ is not clobbered."""
import pathlib
os.environ["OPENAI_API_KEY"] = "sk-existing-key"
mock_cfg = {"model": {"provider": "openai", "default": "gpt-4o"}}
with patch("api.onboarding._load_yaml_config", return_value=mock_cfg), \
patch("api.onboarding._save_yaml_config"), \
patch("api.onboarding._write_env_file"), \
patch("api.onboarding.reload_config"), \
patch("api.onboarding.get_onboarding_status", return_value={"completed": True}), \
patch("api.onboarding._get_config_path", return_value=pathlib.Path("/tmp/fake.yaml")), \
patch("api.onboarding._load_env_file", return_value={"OPENAI_API_KEY": "sk-existing-key"}), \
patch("api.onboarding._provider_api_key_present", return_value=True), \
patch("api.onboarding._get_active_hermes_home", return_value=pathlib.Path("/tmp")):
mod.apply_onboarding_setup({
"provider": "openai",
"model": "gpt-4o",
})
# Key must be unchanged
self.assertEqual(os.environ.get("OPENAI_API_KEY"), "sk-existing-key")
os.environ.pop("OPENAI_API_KEY", None)
if __name__ == "__main__":
unittest.main()

View File

@@ -149,8 +149,10 @@ def test_file_requires_path(cleanup_test_sessions):
assert e.code == 400
def test_new_session_inherits_workspace(cleanup_test_sessions):
sid, _ = make_session_tracked(cleanup_test_sessions)
post("/api/session/update", {"session_id": sid, "workspace": "/tmp", "model": "openai/gpt-5.4-mini"})
sid, ws = make_session_tracked(cleanup_test_sessions)
child = ws / f"workspace-inherit-{uuid.uuid4().hex[:6]}"
child.mkdir(parents=True, exist_ok=True)
post("/api/session/update", {"session_id": sid, "workspace": str(child), "model": "openai/gpt-5.4-mini"})
sid2, _ = make_session_tracked(cleanup_test_sessions)
data, _ = get(f"/api/session?session_id={sid2}")
assert data["session"]["workspace"] == "/tmp"
assert data["session"]["workspace"] == str(child)

162
tests/test_sprint40.py Normal file
View File

@@ -0,0 +1,162 @@
"""
Sprint 40 Tests: OAuth provider onboarding path (PR B of issue #329).
Covers:
- _build_setup_catalog sets current_is_oauth=True for OAuth providers
- _build_setup_catalog sets current_is_oauth=False for API-key providers
- _build_setup_catalog sets current_is_oauth=False when no provider configured
- apply_onboarding_setup with unsupported provider marks onboarding complete directly
- i18n.js contains all required OAuth onboarding keys in both English and Spanish
"""
import pathlib
import re
import unittest
from unittest.mock import patch
import api.onboarding as mod
REPO_ROOT = pathlib.Path(__file__).parent.parent
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text()
ONBOARDING_JS = (REPO_ROOT / "static" / "onboarding.js").read_text()
# ── Backend: _build_setup_catalog ──────────────────────────────────────────
class TestBuildSetupCatalog(unittest.TestCase):
def _catalog(self, provider, model="gpt-4o", base_url=""):
cfg = {}
if provider:
cfg = {"model": {"provider": provider, "default": model, "base_url": base_url}}
with patch.object(mod, "get_config", return_value=cfg):
return mod._build_setup_catalog(cfg)
def test_oauth_provider_sets_current_is_oauth_true(self):
"""openai-codex is not in _SUPPORTED_PROVIDER_SETUPS → current_is_oauth=True."""
catalog = self._catalog("openai-codex", "gpt-5.4")
self.assertTrue(catalog["current_is_oauth"],
"current_is_oauth must be True for openai-codex")
def test_copilot_provider_sets_current_is_oauth_true(self):
"""copilot is also OAuth."""
catalog = self._catalog("copilot")
self.assertTrue(catalog["current_is_oauth"])
def test_openai_provider_sets_current_is_oauth_false(self):
"""openai is in _SUPPORTED_PROVIDER_SETUPS → current_is_oauth=False."""
catalog = self._catalog("openai", "gpt-4o")
self.assertFalse(catalog["current_is_oauth"],
"current_is_oauth must be False for API-key provider openai")
def test_anthropic_provider_sets_current_is_oauth_false(self):
catalog = self._catalog("anthropic", "claude-sonnet-4.6")
self.assertFalse(catalog["current_is_oauth"])
def test_no_provider_sets_current_is_oauth_false(self):
"""Empty config → current_is_oauth=False."""
catalog = self._catalog("")
self.assertFalse(catalog["current_is_oauth"])
def test_catalog_includes_current_is_oauth_key(self):
"""current_is_oauth must always be present in the catalog dict."""
catalog = self._catalog("openrouter")
self.assertIn("current_is_oauth", catalog)
# ── Backend: apply_onboarding_setup for OAuth providers ────────────────────
class TestApplyOnboardingOAuthPath(unittest.TestCase):
def test_unsupported_provider_skips_to_complete(self):
"""apply_onboarding_setup with an OAuth provider just marks onboarding done."""
saved = {}
def _save(d):
saved.update(d)
mock_status = {"completed": True, "system": {"chat_ready": True}}
with patch.object(mod, "save_settings", side_effect=_save), \
patch.object(mod, "get_onboarding_status", return_value=mock_status):
result = mod.apply_onboarding_setup({"provider": "openai-codex", "model": "gpt-5.4"})
self.assertTrue(saved.get("onboarding_completed"),
"save_settings must set onboarding_completed=True for OAuth provider")
self.assertEqual(result, mock_status)
def test_unsupported_provider_does_not_write_config_yaml(self):
"""OAuth path must not call _save_yaml_config — no config mutation."""
with patch.object(mod, "save_settings"), \
patch.object(mod, "get_onboarding_status", return_value={}), \
patch.object(mod, "_save_yaml_config") as mock_save_yaml:
mod.apply_onboarding_setup({"provider": "copilot", "model": "gpt-4o"})
mock_save_yaml.assert_not_called()
# ── Frontend: i18n keys ────────────────────────────────────────────────────
_REQUIRED_OAUTH_KEYS = [
"onboarding_oauth_provider_ready_title",
"onboarding_oauth_provider_ready_body",
"onboarding_oauth_provider_not_ready_title",
"onboarding_oauth_provider_not_ready_body",
"onboarding_oauth_switch_hint",
]
class TestOAuthI18nKeys(unittest.TestCase):
def test_english_locale_has_all_oauth_keys(self):
"""All OAuth onboarding i18n keys must be present in the English locale."""
missing = [k for k in _REQUIRED_OAUTH_KEYS if k not in I18N_JS]
self.assertFalse(missing,
f"English locale missing OAuth keys: {missing}")
def test_spanish_locale_has_all_oauth_keys(self):
"""All OAuth onboarding i18n keys must be present in the Spanish locale."""
# Spanish locale is the second occurrence of each key
counts = {k: I18N_JS.count(k) for k in _REQUIRED_OAUTH_KEYS}
under = [k for k, c in counts.items() if c < 2]
self.assertFalse(under,
f"Spanish locale missing OAuth keys (need 2 occurrences each): {under}")
def test_oauth_body_strings_contain_provider_placeholder(self):
"""Body strings must contain {provider} so JS can substitute the provider name."""
for key in ["onboarding_oauth_provider_ready_body",
"onboarding_oauth_provider_not_ready_body"]:
self.assertIn("{provider}", I18N_JS,
f"{key} must contain {{provider}} placeholder")
# ── Frontend: onboarding.js uses current_is_oauth ─────────────────────────
class TestOAuthOnboardingJs(unittest.TestCase):
def test_onboarding_js_reads_current_is_oauth(self):
"""onboarding.js must check current_is_oauth from the status payload."""
self.assertIn("current_is_oauth", ONBOARDING_JS,
"onboarding.js must read current_is_oauth from ONBOARDING.status.setup")
def test_onboarding_js_renders_oauth_ready_card(self):
"""onboarding.js must render the oauth-ready card class."""
self.assertIn("onboarding-oauth-ready", ONBOARDING_JS)
def test_onboarding_js_renders_oauth_pending_card(self):
"""onboarding.js must render the oauth-pending card class."""
self.assertIn("onboarding-oauth-pending", ONBOARDING_JS)
def test_style_css_has_oauth_card_rules(self):
"""style.css must contain the .onboarding-oauth-card rules."""
css = (REPO_ROOT / "static" / "style.css").read_text()
self.assertIn("onboarding-oauth-card", css)
self.assertIn("onboarding-oauth-ready", css)
self.assertIn("onboarding-oauth-pending", css)
if __name__ == "__main__":
unittest.main()

129
tests/test_sprint41.py Normal file
View File

@@ -0,0 +1,129 @@
"""
Sprint 41 Tests: Title auto-generation fix + mobile close button CSS (PR #333).
Covers:
- streaming.py: sessions titled 'New Chat' trigger auto-title generation
- streaming.py: sessions with empty/falsy title trigger auto-title generation
- streaming.py: sessions titled 'Untitled' (original guard) still trigger
- streaming.py: sessions with a user-set title do NOT trigger auto-title
- style.css: .mobile-close-btn is hidden by default (desktop rule present)
- style.css: .mobile-close-btn shown in <=900px media query
- style.css: #btnCollapseWorkspacePanel hidden in <=900px media query
- index.html: both .mobile-close-btn and #btnCollapseWorkspacePanel buttons exist
"""
import pathlib
import re
import unittest
REPO_ROOT = pathlib.Path(__file__).parent.parent
CSS = (REPO_ROOT / "static" / "style.css").read_text()
HTML = (REPO_ROOT / "static" / "index.html").read_text()
STREAMING_PY = (REPO_ROOT / "api" / "streaming.py").read_text()
# ── streaming.py: title auto-generation condition ─────────────────────────
class TestTitleAutoGenerationCondition(unittest.TestCase):
"""Verify the guarded condition in streaming.py covers all default title cases."""
def _titles_that_trigger(self):
"""Extract the condition from the source so tests stay in sync with code."""
# Find the if-condition that calls title_from
m = re.search(
r'if\s+(s\.title\s*==.*?):\s*\n\s*s\.title\s*=\s*title_from',
STREAMING_PY,
re.DOTALL,
)
self.assertIsNotNone(m, "Could not find title auto-generation condition in streaming.py")
return m.group(1)
def test_untitled_in_condition(self):
cond = self._titles_that_trigger()
self.assertIn("'Untitled'", cond, "Original 'Untitled' guard must be present")
def test_new_chat_in_condition(self):
cond = self._titles_that_trigger()
self.assertIn("'New Chat'", cond, "'New Chat' guard must be present (PR #333)")
def test_empty_title_guard_in_condition(self):
cond = self._titles_that_trigger()
self.assertIn("not s.title", cond, "Empty/falsy title guard must be present (PR #333)")
def test_condition_logic_covers_all_defaults(self):
"""The condition uses OR so any one default title triggers generation."""
cond = self._titles_that_trigger()
# All three guards must be joined by 'or'
parts = re.split(r'\bor\b', cond)
self.assertGreaterEqual(len(parts), 3,
"Expected at least 3 OR-joined sub-conditions (Untitled, New Chat, not s.title)")
# ── style.css: mobile close button visibility ─────────────────────────────
class TestMobileCloseButtonCSS(unittest.TestCase):
"""Verify CSS rules that control the duplicate close button on mobile."""
def test_mobile_close_btn_hidden_by_default(self):
"""Desktop default: .mobile-close-btn must be display:none outside any media query."""
# Find the rule before the first @media block that contains mobile-close-btn
# We look for the pattern in the desktop (non-media-query) section
self.assertIn(
".mobile-close-btn{display:none;}",
CSS.replace(" ", ""),
".mobile-close-btn should be hidden by default (desktop) — rule missing or wrong"
)
def test_mobile_close_btn_shown_in_900px_query(self):
"""Inside max-width:900px media query, .mobile-close-btn must be display:flex."""
# Extract the 900px media block
m = re.search(r'@media\s*\(max-width\s*:\s*900px\)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}',
CSS)
self.assertIsNotNone(m, "@media(max-width:900px) block not found in style.css")
block = m.group(1).replace(" ", "")
self.assertIn(".mobile-close-btn{display:flex;}",
block,
".mobile-close-btn must be display:flex inside the 900px media query")
def test_desktop_collapse_btn_hidden_in_900px_query(self):
"""Inside max-width:900px media query, #btnCollapseWorkspacePanel must be display:none."""
m = re.search(r'@media\s*\(max-width\s*:\s*900px\)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}',
CSS)
self.assertIsNotNone(m, "@media(max-width:900px) block not found in style.css")
block = m.group(1).replace(" ", "")
self.assertIn("#btnCollapseWorkspacePanel{display:none;}",
block,
"#btnCollapseWorkspacePanel must be display:none in 900px media query")
def test_900px_query_retains_existing_rules(self):
"""Ensure the PR didn't accidentally drop existing rules from the 900px block."""
m = re.search(r'@media\s*\(max-width\s*:\s*900px\)\s*\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}',
CSS)
self.assertIsNotNone(m)
block = m.group(1)
self.assertIn("rightpanel", block, ".rightpanel rule missing from 900px block")
self.assertIn("mobile-files-btn", block, ".mobile-files-btn rule missing from 900px block")
# ── index.html: button presence ───────────────────────────────────────────
class TestWorkspacePanelButtons(unittest.TestCase):
"""Verify both panel buttons are present in the HTML so CSS rules have targets."""
def test_desktop_collapse_button_exists(self):
self.assertIn("btnCollapseWorkspacePanel", HTML,
"#btnCollapseWorkspacePanel button must exist in index.html")
def test_mobile_close_button_exists(self):
self.assertIn("mobile-close-btn", HTML,
".mobile-close-btn button must exist in index.html")
def test_mobile_close_button_has_aria_label(self):
"""Accessibility: mobile close button must have an aria-label."""
m = re.search(r'class="[^"]*mobile-close-btn[^"]*"[^>]*>', HTML)
self.assertIsNotNone(m, "Could not find mobile-close-btn element")
self.assertIn("aria-label", m.group(0),
"mobile-close-btn must have aria-label for accessibility")
if __name__ == "__main__":
unittest.main()

107
tests/test_sprint42.py Normal file
View File

@@ -0,0 +1,107 @@
"""
Sprint 42 Tests: SessionDB injection into AIAgent for WebUI sessions (PR #356).
Covers:
- streaming.py: SessionDB is initialized inside _run_agent_streaming (import present)
- streaming.py: try/except guards SessionDB init so failures are non-fatal
- streaming.py: session_db= kwarg is passed to AIAgent constructor
- streaming.py: SessionDB init failure prints a WARNING (not silently swallowed)
- streaming.py: SessionDB init is placed before AIAgent construction
"""
import ast
import pathlib
import re
import unittest
REPO_ROOT = pathlib.Path(__file__).parent.parent
STREAMING_PY = (REPO_ROOT / "api" / "streaming.py").read_text()
class TestSessionDBInjection(unittest.TestCase):
"""Verify SessionDB is initialized and passed to AIAgent in streaming.py."""
def test_hermes_state_import_present(self):
"""SessionDB must be imported from hermes_state inside _run_agent_streaming."""
self.assertIn(
"from hermes_state import SessionDB",
STREAMING_PY,
"SessionDB import missing from streaming.py (PR #356)",
)
def test_session_db_kwarg_passed_to_agent(self):
"""session_db= must be passed to the AIAgent constructor call."""
self.assertIn(
"session_db=_session_db",
STREAMING_PY,
"session_db kwarg not passed to AIAgent (PR #356)",
)
def test_sessiondb_init_in_try_except(self):
"""SessionDB() init must be wrapped in try/except for non-fatal failure handling."""
# Check that the try/except pattern surrounding SessionDB() is present
pattern = r"try:\s*\n\s*from hermes_state import SessionDB\s*\n\s*_session_db\s*=\s*SessionDB\(\)"
self.assertRegex(
STREAMING_PY,
pattern,
"SessionDB() init must be inside a try block for non-fatal error handling (PR #356)",
)
def test_sessiondb_failure_logs_warning(self):
"""A failure initializing SessionDB must print a WARNING (not silently drop the error)."""
self.assertIn(
"WARNING: SessionDB init failed",
STREAMING_PY,
"SessionDB init failure must log a WARNING message (PR #356)",
)
def test_session_db_initialized_before_agent_construction(self):
"""SessionDB initialization must appear before the AIAgent(...) constructor call."""
db_pos = STREAMING_PY.find("from hermes_state import SessionDB")
agent_pos = STREAMING_PY.find("session_db=_session_db")
self.assertGreater(
agent_pos,
db_pos,
"SessionDB init must appear before AIAgent construction (PR #356)",
)
def test_session_db_default_is_none(self):
"""_session_db must be initialized to None before the try block (safe default)."""
# Pattern: _session_db = None followed (eventually) by the try/SessionDB block
pattern = r"_session_db\s*=\s*None\s*\n\s*try:"
self.assertRegex(
STREAMING_PY,
pattern,
"_session_db must default to None before try/except block (PR #356)",
)
class TestSessionDBAST(unittest.TestCase):
"""AST-level checks: verify the try/except is not inside _ENV_LOCK (deadlock guard)."""
def setUp(self):
self.tree = ast.parse(STREAMING_PY)
def test_sessiondb_try_not_inside_env_lock(self):
"""The try block that wraps SessionDB init must NOT be inside a 'with _ENV_LOCK:' block.
Putting a try/except inside _ENV_LOCK is the deadlock pattern caught by test_sprint34.
The SessionDB try/except is outside the lock scope, which is correct.
"""
# Find all 'with _ENV_LOCK:' nodes; check none of their bodies contain
# a Try node that also contains 'from hermes_state import SessionDB'
for node in ast.walk(self.tree):
if not isinstance(node, ast.With):
continue
names = [getattr(item.context_expr, "id", "") for item in node.items]
if "_ENV_LOCK" not in names:
continue
# Walk the with-body for Try nodes
for stmt in node.body:
if isinstance(stmt, ast.Try):
# Check if this try imports hermes_state
src = ast.unparse(stmt)
self.assertNotIn(
"hermes_state",
src,
"SessionDB try/except must NOT be inside _ENV_LOCK body (deadlock risk)",
)

253
tests/test_sprint43.py Normal file
View File

@@ -0,0 +1,253 @@
"""
Sprint 43 Tests: Bandit security fixes — B310, B324, B110 + QuietHTTPServer (PR #354).
Covers:
- gateway_watcher.py: MD5 uses usedforsecurity=False (B324)
- config.py: URL scheme validation before urlopen (B310)
- bootstrap.py: URL scheme validation in wait_for_health (B310)
- server.py: QuietHTTPServer class exists and extends ThreadingHTTPServer
- server.py: QuietHTTPServer.handle_error suppresses client disconnect errors
- server.py: QuietHTTPServer uses sys.exc_info() not traceback.sys.exc_info()
- Logging: at least 5 modules add a module-level logger (B110 remediation)
- routes.py: session titles redacted in /api/sessions list response
"""
import ast
import pathlib
import re
import sys
import unittest
REPO_ROOT = pathlib.Path(__file__).parent.parent
GATEWAY_WATCHER_PY = (REPO_ROOT / "api" / "gateway_watcher.py").read_text()
CONFIG_PY = (REPO_ROOT / "api" / "config.py").read_text()
BOOTSTRAP_PY = (REPO_ROOT / "bootstrap.py").read_text()
SERVER_PY = (REPO_ROOT / "server.py").read_text()
ROUTES_PY = (REPO_ROOT / "api" / "routes.py").read_text()
AUTH_PY = (REPO_ROOT / "api" / "auth.py").read_text()
PROFILES_PY = (REPO_ROOT / "api" / "profiles.py").read_text()
STREAMING_PY = (REPO_ROOT / "api" / "streaming.py").read_text()
WORKSPACE_PY = (REPO_ROOT / "api" / "workspace.py").read_text()
STATE_SYNC_PY = (REPO_ROOT / "api" / "state_sync.py").read_text()
# ── B324: MD5 usedforsecurity=False ─────────────────────────────────────────
class TestMD5SecurityFix(unittest.TestCase):
"""B324: hashlib.md5 must use usedforsecurity=False for non-crypto hashes."""
def test_gateway_watcher_md5_usedforsecurity_false(self):
"""_snapshot_hash must pass usedforsecurity=False to hashlib.md5 (PR #354)."""
self.assertIn(
"usedforsecurity=False",
GATEWAY_WATCHER_PY,
"gateway_watcher.py: MD5 must use usedforsecurity=False (B324)",
)
def test_gateway_watcher_md5_pattern(self):
"""Exact pattern: hashlib.md5(..., usedforsecurity=False)."""
# Use re.search with DOTALL since the arg may span parens internally
import re
self.assertIsNotNone(
re.search(r"hashlib\.md5\(.*?usedforsecurity=False\)", GATEWAY_WATCHER_PY, re.DOTALL),
"MD5 call must include usedforsecurity=False kwarg",
)
# ── B310: URL scheme validation ──────────────────────────────────────────────
class TestUrlSchemeValidation(unittest.TestCase):
"""B310: urllib.request.urlopen must not be called with arbitrary schemes."""
def test_config_scheme_validation_present(self):
"""config.py must validate URL scheme before urlopen (B310 fix)."""
self.assertIn(
"parsed_url.scheme",
CONFIG_PY,
"config.py: URL scheme validation missing (B310)",
)
# Must check against allowed schemes
self.assertRegex(
CONFIG_PY,
r'parsed_url\.scheme\s+not\s+in\s+\(',
"config.py: scheme check must use 'not in (...)' pattern",
)
def test_config_urlopen_has_nosec(self):
"""The urlopen call in config.py must have a # nosec B310 comment."""
self.assertIn(
"nosec B310",
CONFIG_PY,
"config.py: urlopen must have # nosec B310 after scheme validation",
)
def test_bootstrap_scheme_validation_present(self):
"""bootstrap.py wait_for_health must validate URL scheme before urlopen."""
self.assertIn(
"Invalid health check URL",
BOOTSTRAP_PY,
"bootstrap.py: URL scheme validation missing in wait_for_health (B310)",
)
self.assertRegex(
BOOTSTRAP_PY,
r'url\.startswith\([^)]+http',
"bootstrap.py: must check url starts with http:// or https://",
)
def test_bootstrap_urlopen_has_nosec(self):
"""The urlopen call in bootstrap.py must have a # nosec B310 comment."""
self.assertIn(
"nosec B310",
BOOTSTRAP_PY,
"bootstrap.py: urlopen must have # nosec B310 after scheme validation",
)
def test_config_allows_http_and_https(self):
"""config.py scheme check must permit both http and https."""
self.assertIn('"http"', CONFIG_PY, "config.py: http must be in allowed schemes")
self.assertIn('"https"', CONFIG_PY, "config.py: https must be in allowed schemes")
# ── B110: Bare except/pass → logger.debug() ─────────────────────────────────
class TestBareExceptLogging(unittest.TestCase):
"""B110: bare except/pass blocks must be replaced with logger.debug()."""
MODULES_REQUIRING_LOGGER = [
("api/auth.py", AUTH_PY),
("api/config.py", CONFIG_PY),
("api/gateway_watcher.py", GATEWAY_WATCHER_PY),
("api/profiles.py", PROFILES_PY),
("api/streaming.py", STREAMING_PY),
("api/workspace.py", WORKSPACE_PY),
("api/state_sync.py", STATE_SYNC_PY),
("api/routes.py", ROUTES_PY),
]
def test_module_level_loggers_present(self):
"""All fixed modules must have a module-level logger = logging.getLogger(__name__)."""
for name, src in self.MODULES_REQUIRING_LOGGER:
with self.subTest(module=name):
self.assertIn(
"logger = logging.getLogger(__name__)",
src,
f"{name}: module-level logger missing (B110 fix requires logger)",
)
def test_gateway_watcher_no_bare_pass_in_except(self):
"""gateway_watcher.py critical except blocks must not use bare pass."""
# The poll loop except block that previously had 'pass' must now use logger
self.assertIn(
"logger.debug",
GATEWAY_WATCHER_PY,
"gateway_watcher.py: must use logger.debug not bare pass (B110)",
)
def test_profiles_reload_dotenv_logs_on_error(self):
"""profiles.py _reload_dotenv except must log + reset _loaded_profile_env_keys."""
# Both the reset and the debug log should be present in the except block
self.assertIn(
"_loaded_profile_env_keys = set()",
PROFILES_PY,
"profiles.py: _reload_dotenv except must reset _loaded_profile_env_keys",
)
self.assertIn(
"Failed to reload dotenv",
PROFILES_PY,
"profiles.py: _reload_dotenv except must log a warning",
)
# ── QuietHTTPServer ──────────────────────────────────────────────────────────
class TestQuietHTTPServer(unittest.TestCase):
"""server.py: QuietHTTPServer suppresses client disconnect noise."""
def test_quiet_http_server_class_exists(self):
"""QuietHTTPServer must be defined in server.py."""
self.assertIn(
"class QuietHTTPServer",
SERVER_PY,
"server.py: QuietHTTPServer class missing (PR #354)",
)
def test_quiet_http_server_extends_threading_http_server(self):
"""QuietHTTPServer must extend ThreadingHTTPServer."""
self.assertRegex(
SERVER_PY,
r"class QuietHTTPServer\(ThreadingHTTPServer\)",
"QuietHTTPServer must extend ThreadingHTTPServer",
)
def test_quiet_http_server_used_as_server(self):
"""main() must instantiate QuietHTTPServer not raw ThreadingHTTPServer."""
# After the class is defined, the server creation should use QuietHTTPServer
after_class = SERVER_PY[SERVER_PY.find("class QuietHTTPServer"):]
self.assertIn(
"QuietHTTPServer(",
after_class,
"main() must use QuietHTTPServer, not ThreadingHTTPServer directly",
)
def test_handle_error_suppresses_connection_reset(self):
"""handle_error must suppress ConnectionResetError and BrokenPipeError."""
self.assertIn(
"ConnectionResetError",
SERVER_PY,
"QuietHTTPServer.handle_error must handle ConnectionResetError",
)
self.assertIn(
"BrokenPipeError",
SERVER_PY,
"QuietHTTPServer.handle_error must handle BrokenPipeError",
)
def test_uses_sys_exc_info_not_traceback_sys(self):
"""handle_error must use sys.exc_info() not traceback.sys.exc_info() (implementation detail)."""
self.assertNotIn(
"traceback.sys.exc_info()",
SERVER_PY,
"server.py: must use sys.exc_info() not traceback.sys.exc_info()",
)
self.assertIn(
"sys.exc_info()",
SERVER_PY,
"server.py: handle_error must call sys.exc_info()",
)
def test_sys_imported_in_server(self):
"""server.py must import sys (needed for sys.exc_info)."""
import re
self.assertIsNotNone(
re.search(r"^import sys", SERVER_PY, re.MULTILINE),
"server.py: sys must be imported",
)
def test_handle_error_calls_super(self):
"""handle_error must call super().handle_error for non-client-disconnect errors."""
self.assertIn(
"super().handle_error(request, client_address)",
SERVER_PY,
"QuietHTTPServer.handle_error must delegate to super for real errors",
)
# ── Session title redaction in /api/sessions ────────────────────────────────
class TestSessionTitleRedaction(unittest.TestCase):
"""routes.py: session titles must be redacted in the sessions list endpoint."""
def test_redact_text_called_on_session_titles(self):
"""routes.py must call _redact_text on session titles in /api/sessions."""
self.assertRegex(
ROUTES_PY,
r'_redact_text\([^)]*\btitle\b[^)]*\)',
"routes.py: session titles must be redacted via _redact_text in /api/sessions",
)
def test_redact_text_imported_in_routes(self):
"""routes.py must import _redact_text from api.helpers."""
self.assertIn(
"_redact_text",
ROUTES_PY,
"routes.py: _redact_text must be imported from api.helpers",
)

134
tests/test_sprint44.py Normal file
View File

@@ -0,0 +1,134 @@
"""
Sprint 44 Tests: Workspace panel close button fixes (PR #413).
Covers:
- index.html: mobile-close-btn now calls handleWorkspaceClose() instead of
closeWorkspacePanel(), so hitting X while a file is open returns you to the
file browser rather than collapsing the whole panel.
- boot.js: syncWorkspacePanelUI() hides #btnClearPreview (the X icon) on
desktop when no file preview is open, eliminating the duplicate X that
appeared alongside the chevron collapse button.
- boot.js: handleWorkspaceClose() logic — clears preview when one is visible,
closes panel otherwise (existing function, confirmed wired to both buttons).
"""
import pathlib
import re
import unittest
REPO = pathlib.Path(__file__).parent.parent
HTML = (REPO / "static" / "index.html").read_text(encoding="utf-8")
BOOT_JS = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
class TestMobileCloseButtonBehavior(unittest.TestCase):
"""mobile-close-btn must call handleWorkspaceClose(), not closeWorkspacePanel()."""
def test_mobile_close_btn_calls_handle_workspace_close(self):
"""mobile-close-btn onclick must be handleWorkspaceClose(), not closeWorkspacePanel()."""
m = re.search(r'class="[^"]*mobile-close-btn[^"]*"[^>]*>', HTML)
self.assertIsNotNone(m, "mobile-close-btn element not found in index.html")
btn_html = m.group(0)
self.assertIn(
'onclick="handleWorkspaceClose()"',
btn_html,
"mobile-close-btn must call handleWorkspaceClose() so that hitting X "
"while a file is open closes the file first, not the whole panel",
)
def test_mobile_close_btn_does_not_call_close_workspace_panel_directly(self):
"""mobile-close-btn must NOT call closeWorkspacePanel() directly."""
m = re.search(r'class="[^"]*mobile-close-btn[^"]*"[^>]*>', HTML)
self.assertIsNotNone(m, "mobile-close-btn element not found in index.html")
btn_html = m.group(0)
self.assertNotIn(
'onclick="closeWorkspacePanel()"',
btn_html,
"mobile-close-btn must not call closeWorkspacePanel() directly — "
"it would bypass the two-step close logic and collapse the panel even "
"when a file is being viewed",
)
def test_handle_workspace_close_defined_in_boot_js(self):
"""handleWorkspaceClose() must be defined in boot.js."""
self.assertIn(
"function handleWorkspaceClose()",
BOOT_JS,
"handleWorkspaceClose() is missing from boot.js",
)
def test_handle_workspace_close_clears_preview_first(self):
"""handleWorkspaceClose() must call clearPreview() when a preview is visible."""
# The function must check for visible preview and call clearPreview
self.assertIn(
"clearPreview()",
BOOT_JS,
"handleWorkspaceClose() must call clearPreview() when preview is visible",
)
def test_handle_workspace_close_falls_back_to_close_panel(self):
"""handleWorkspaceClose() must call closeWorkspacePanel() as fallback."""
# Find the function start and extract until the closing brace by scanning
start = BOOT_JS.find("function handleWorkspaceClose()")
self.assertNotEqual(start, -1, "handleWorkspaceClose() not found in boot.js")
# Extract a generous window after the function start
fn_window = BOOT_JS[start : start + 400]
self.assertIn(
"closeWorkspacePanel()",
fn_window,
"handleWorkspaceClose() must call closeWorkspacePanel() as its fallback path",
)
class TestDesktopNoDuplicateXButton(unittest.TestCase):
"""On desktop, only one X/close control should appear at a time."""
def test_sync_workspace_panel_ui_hides_clear_preview_on_desktop(self):
"""syncWorkspacePanelUI() must set display:none on btnClearPreview when no preview and desktop."""
self.assertIn(
"clearBtn.style.display",
BOOT_JS,
"syncWorkspacePanelUI() must control clearBtn.style.display to hide it "
"on desktop when no file preview is open",
)
def test_clear_preview_hidden_when_no_preview(self):
"""The display toggle for btnClearPreview must key off hasPreview."""
# Expect something like: clearBtn.style.display=hasPreview?'':'none'
# or clearBtn.style.display = hasPreview ? '' : 'none'
pattern = r"clearBtn\.style\.display\s*=\s*hasPreview"
self.assertRegex(
BOOT_JS,
pattern,
"btnClearPreview display must be conditioned on hasPreview in "
"syncWorkspacePanelUI() to avoid a duplicate X on desktop",
)
def test_clear_preview_toggle_only_applied_on_desktop(self):
"""The display toggle must be guarded by !isCompact so mobile is unaffected."""
# Expect: if(!isCompact) clearBtn.style.display=...
pattern = r"isCompact.*clearBtn\.style\.display|clearBtn\.style\.display.*isCompact"
self.assertRegex(
BOOT_JS,
pattern,
"btnClearPreview display toggle must be guarded by isCompact so the "
"mobile X button visibility is not accidentally affected",
)
def test_btnclearpreview_exists_in_html(self):
"""#btnClearPreview must still exist in the HTML (not removed)."""
self.assertIn(
'id="btnClearPreview"',
HTML,
"#btnClearPreview must remain in index.html",
)
def test_btncollapseWorkspacepanel_exists_in_html(self):
"""#btnCollapseWorkspacePanel (chevron) must still exist in the HTML."""
self.assertIn(
'id="btnCollapseWorkspacePanel"',
HTML,
"#btnCollapseWorkspacePanel must remain in index.html",
)
if __name__ == "__main__":
unittest.main()

View File

@@ -31,6 +31,12 @@ def make_session_tracked(created_list, ws=None):
return sid, _pathlib.Path(d["session"]["workspace"])
def make_workspace_child(base: pathlib.Path, name: str) -> pathlib.Path:
target = base / name
target.mkdir(parents=True, exist_ok=True)
return target
def test_server_running_from_new_location():
data, status = get("/health")
assert status == 200 and data["status"] == "ok"
@@ -44,11 +50,13 @@ def test_workspaces_list():
data, status = get("/api/workspaces")
assert status == 200 and "workspaces" in data and "last" in data
def test_workspace_add_valid():
post("/api/workspaces/remove", {"path": "/tmp"})
result, status = post("/api/workspaces/add", {"path": "/tmp", "name": "Temp"})
assert status == 200 and any(w["path"]=="/tmp" for w in result["workspaces"])
post("/api/workspaces/remove", {"path": "/tmp"})
def test_workspace_add_valid(cleanup_test_sessions):
_, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-add-{uuid.uuid4().hex[:6]}")
post("/api/workspaces/remove", {"path": str(child)})
result, status = post("/api/workspaces/add", {"path": str(child), "name": "Temp"})
assert status == 200 and any(w["path"] == str(child) for w in result["workspaces"])
post("/api/workspaces/remove", {"path": str(child)})
def test_workspace_add_validates_existence():
result, status = post("/api/workspaces/add", {"path": "/tmp/does_not_exist_xyz_999"})
@@ -58,40 +66,47 @@ def test_workspace_add_validates_is_dir():
result, status = post("/api/workspaces/add", {"path": "/etc/hostname"})
assert status == 400
def test_workspace_add_no_duplicate():
post("/api/workspaces/remove", {"path": "/tmp"})
post("/api/workspaces/add", {"path": "/tmp"})
result, status = post("/api/workspaces/add", {"path": "/tmp"})
def test_workspace_add_no_duplicate(cleanup_test_sessions):
_, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-dup-{uuid.uuid4().hex[:6]}")
post("/api/workspaces/remove", {"path": str(child)})
post("/api/workspaces/add", {"path": str(child)})
result, status = post("/api/workspaces/add", {"path": str(child)})
assert status == 400 and "already" in result.get("error","").lower()
post("/api/workspaces/remove", {"path": "/tmp"})
post("/api/workspaces/remove", {"path": str(child)})
def test_workspace_add_requires_path():
result, status = post("/api/workspaces/add", {})
assert status == 400
def test_workspace_remove():
post("/api/workspaces/remove", {"path": "/tmp"})
post("/api/workspaces/add", {"path": "/tmp", "name": "Temp"})
result, status = post("/api/workspaces/remove", {"path": "/tmp"})
assert status == 200 and "/tmp" not in [w["path"] for w in result["workspaces"]]
def test_workspace_remove(cleanup_test_sessions):
_, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-remove-{uuid.uuid4().hex[:6]}")
post("/api/workspaces/remove", {"path": str(child)})
post("/api/workspaces/add", {"path": str(child), "name": "Temp"})
result, status = post("/api/workspaces/remove", {"path": str(child)})
assert status == 200 and str(child) not in [w["path"] for w in result["workspaces"]]
def test_workspace_rename():
post("/api/workspaces/remove", {"path": "/tmp"})
post("/api/workspaces/add", {"path": "/tmp", "name": "Temp"})
result, status = post("/api/workspaces/rename", {"path": "/tmp", "name": "My Temp"})
def test_workspace_rename(cleanup_test_sessions):
_, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-rename-{uuid.uuid4().hex[:6]}")
post("/api/workspaces/remove", {"path": str(child)})
post("/api/workspaces/add", {"path": str(child), "name": "Temp"})
result, status = post("/api/workspaces/rename", {"path": str(child), "name": "My Temp"})
assert status == 200
assert {w["path"]: w["name"] for w in result["workspaces"]}.get("/tmp") == "My Temp"
post("/api/workspaces/remove", {"path": "/tmp"})
assert {w["path"]: w["name"] for w in result["workspaces"]}.get(str(child)) == "My Temp"
post("/api/workspaces/remove", {"path": str(child)})
def test_workspace_rename_unknown():
result, status = post("/api/workspaces/rename", {"path": "/no/such/path", "name": "X"})
assert status == 404
def test_last_workspace_updates_on_session_update(cleanup_test_sessions):
sid, _ = make_session_tracked(cleanup_test_sessions)
post("/api/session/update", {"session_id": sid, "workspace": "/tmp", "model": "openai/gpt-5.4-mini"})
sid, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-last-{uuid.uuid4().hex[:6]}")
post("/api/session/update", {"session_id": sid, "workspace": str(child), "model": "openai/gpt-5.4-mini"})
data, _ = get("/api/workspaces")
assert data["last"] == "/tmp"
assert data["last"] == str(child)
def test_file_save(cleanup_test_sessions):
sid, ws = make_session_tracked(cleanup_test_sessions)
@@ -133,8 +148,9 @@ def test_sessions_endpoint_returns_sorted():
assert sessions[0]["updated_at"] >= sessions[1]["updated_at"]
def test_new_session_inherits_last_workspace(cleanup_test_sessions):
sid, _ = make_session_tracked(cleanup_test_sessions)
post("/api/session/update", {"session_id": sid, "workspace": "/tmp", "model": "openai/gpt-5.4-mini"})
sid, ws = make_session_tracked(cleanup_test_sessions)
child = make_workspace_child(ws, f"workspace-inherit-{uuid.uuid4().hex[:6]}")
post("/api/session/update", {"session_id": sid, "workspace": str(child), "model": "openai/gpt-5.4-mini"})
sid2, _ = make_session_tracked(cleanup_test_sessions)
d, _ = get(f"/api/session?session_id={sid2}")
assert d["session"]["workspace"] == "/tmp"
assert d["session"]["workspace"] == str(child)

View File

@@ -0,0 +1,87 @@
import io
import json
import sys
import types
from api.upload import handle_transcribe
def _multipart_body(fields=None, files=None, boundary=b"voiceboundary"):
fields = fields or {}
files = files or {}
body = b""
for name, value in fields.items():
body += b"--" + boundary + b"\r\n"
body += f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode()
body += str(value).encode() + b"\r\n"
for name, (filename, data, content_type) in files.items():
body += b"--" + boundary + b"\r\n"
body += (
f'Content-Disposition: form-data; name="{name}"; filename="{filename}"\r\n'
f'Content-Type: {content_type}\r\n\r\n'
).encode()
body += data + b"\r\n"
body += b"--" + boundary + b"--\r\n"
return body, f"multipart/form-data; boundary={boundary.decode()}"
class _FakeHandler:
def __init__(self, body: bytes, content_type: str):
self.rfile = io.BytesIO(body)
self.wfile = io.BytesIO()
self.headers = {
"Content-Type": content_type,
"Content-Length": str(len(body)),
}
self.status = None
self.sent_headers = {}
def send_response(self, status):
self.status = status
def send_header(self, key, value):
self.sent_headers[key] = value
def end_headers(self):
pass
def payload(self):
return json.loads(self.wfile.getvalue().decode("utf-8"))
def test_handle_transcribe_requires_file_field():
body, content_type = _multipart_body(fields={"note": "missing file"})
handler = _FakeHandler(body, content_type)
handle_transcribe(handler)
assert handler.status == 400
assert handler.payload()["error"] == "No file field in request"
def test_handle_transcribe_returns_transcript(monkeypatch):
fake_mod = types.ModuleType("tools.transcription_tools")
fake_mod.transcribe_audio = lambda path: {"success": True, "transcript": "hello from audio"}
monkeypatch.setitem(sys.modules, "tools.transcription_tools", fake_mod)
body, content_type = _multipart_body(
files={"file": ("voice.webm", b"RIFFfakeaudio", "audio/webm")}
)
handler = _FakeHandler(body, content_type)
handle_transcribe(handler)
assert handler.status == 200
assert handler.payload() == {"ok": True, "transcript": "hello from audio"}
def test_handle_transcribe_surfaces_provider_error(monkeypatch):
fake_mod = types.ModuleType("tools.transcription_tools")
fake_mod.transcribe_audio = lambda path: {"success": False, "error": "STT not configured"}
monkeypatch.setitem(sys.modules, "tools.transcription_tools", fake_mod)
body, content_type = _multipart_body(
files={"file": ("voice.webm", b"RIFFfakeaudio", "audio/webm")}
)
handler = _FakeHandler(body, content_type)
handle_transcribe(handler)
assert handler.status == 503
assert handler.payload()["error"] == "STT not configured"