Compare commits

...

85 Commits

Author SHA1 Message Date
Nathan Esquenazi
dac58c8162 Merge pull request #70 from nesquena/fix/ui-polish-cli-badge-image-error-zindex
Some checks failed
Release & Docker / release (push) Has been cancelled
fix: UI polish -- image error, CLI badge overlap, dropdown z-index
2026-04-04 09:18:01 -07:00
Nathan Esquenazi
6a4b20f3f2 fix: three UI glitches -- image error, CLI badge overlap, dropdown z-index
1. Image preview onerror fires on clearPreview (#68)
   clearPreview() set previewImg.src='' which triggered the stale onerror
   handler, showing 'Could not load image' on every refresh/message.
   Fix: null out onerror before clearing src.

2. CLI session badge covers delete button (#69)
   The ::after 'cli' label occupied the same space as the hover-revealed
   .session-actions overlay, making delete unreachable.
   Fix: add padding-right to .cli-session, use margin-left:auto to push
   badge right, add pointer-events:none so clicks pass through.

3. Tool cards visible through profile dropdown
   The .messages container had no stacking context, so tool cards could
   render above the profile dropdown (z-index:200).
   Fix: add position:relative;z-index:0 to .messages to establish a
   stacking context that keeps all children below overlays.

Closes #68, closes #69

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 09:09:31 -07:00
Nathan Esquenazi
90b5ad8d99 fix: strip webui metadata from messages before sending to LLM API (#67)
Some checks failed
Release & Docker / release (push) Has been cancelled
The webui stores display-only fields on messages (attachments, timestamp,
_ts) for UI rendering. These leaked into the conversation_history passed
to AIAgent.run_conversation(). Most providers ignore unknown fields, but
Z.AI/GLM tries to deserialize 'attachments' as its native ChatAttachments
type, causing HTTP 400 on every subsequent message after an image upload.

Fix: _sanitize_messages_for_api() creates a clean copy with only
API-standard keys (role, content, tool_calls, tool_call_id, name,
refusal) before passing to run_conversation(). Applied to both the
streaming path (streaming.py) and non-streaming path (routes.py).

Closes #66

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 22:13:12 -07:00
nesquena-hermes
57a4f573f6 docs: HERMES.md deep-dive, Why Hermes in README, screenshot layout
* docs: add HERMES.md deep-dive, Why Hermes section in README, and screenshot layout

- HERMES.md: full why-Hermes document -- assistant vs. agent mental
  model, three pillars (memory/scheduling/reach), four-category
  taxonomy of AI tools, per-tool comparison sections with tables
  (Claude Code, Codex CLI, OpenCode, Cursor/Copilot, Claude.ai),
  compounding advantage, who it's for, what it's not, quick reference
- README: hero screenshot stays full-width; two new UI screenshots in
  side-by-side HTML table with captions below
- README: new Why Hermes section with 6-bullet summary, comparison
  table, and link to HERMES.md
- README: HERMES.md added to Docs section
- docs/images/: two UI screenshots (workspace browser, sessions view)

* docs: fact-check and update all comparisons; add Open Interpreter section

Researched current state of each tool before updating:

Claude Code:
- Scheduled jobs: now Partial (has /loop session-scoped, cloud-managed
  /schedule via claude.ai/code, and desktop app automations); updated
  table to reflect this with footnotes distinguishing self-hosted cron
- Persistent memory: Partial (CLAUDE.md, MEMORY.md, rolling auto-memory
  but not full automatic cross-session recall)
- Provider-agnostic: No -- supports Bedrock/Vertex but Claude models only
- Web UI: Yes but Anthropic-hosted (not self-hosted)

Codex CLI:
- Persistent memory: Partial (session history + AGENTS.md since v0.100.0)
- Scheduled jobs: Partial (desktop app Automations only; CLI has no native
  scheduling as of early 2026, open feature request)
- Provider-agnostic: Yes (10+ providers)

OpenCode:
- Web UI: now Yes (embedded in binary + official desktop app)
- Persistent memory: Partial (SQLite sessions + AGENTS.md, not semantic)
- Messaging: community Telegram bot only, not first-party

Open Interpreter: added as new comparison section
- Most common 'why not just use this' question; addressed head-on
- Session-scoped, no persistent memory by their own docs, no scheduler,
  no messaging integration; powerful for one-shot tasks, not always-on

README Why Hermes table: updated to include Open Interpreter column,
fixed Claude Code self-hosted row (No -- scheduling runs on Anthropic
cloud), added footnotes for partial entries

* docs: add OpenClaw comparison; update category framework and quick reference table

OpenClaw (openclaw.ai, MIT, 347k stars) is the most direct Hermes
competitor -- both are open-source, self-hosted, always-on agents with
persistent memory, cron, and messaging integration. Added:

- Full OpenClaw section in HERMES.md with honest comparison: where it
  wins (15+ messaging platforms incl. iMessage/WeChat, native Chrome CDP
  browser control, voice wake words, ClawHub marketplace) and where
  Hermes differs (self-improving skills system, Python/ML ecosystem,
  web UI, multi-profile, sub-agent orchestration)
- Category 4 framework updated: now lists both Hermes and OpenClaw,
  with the key architectural distinction called out
- Quick reference table expanded to include OpenClaw column (now 8 tools)
- New rows added: self-improving skills, browser/computer control,
  Python/ML ecosystem
- README Why Hermes table updated: OpenClaw replaces OpenCode column,
  self-improving skills row replaces generic skills row, callout line
  at bottom addresses OpenClaw head-on

* docs: major accuracy pass -- OpenClaw deep-dive, Claude Code corrections, drop Open Interpreter

OpenClaw:
- Expanded comparison from a table to a full prose section with
  'Where OpenClaw wins' / 'Where Hermes wins' structure
- Honest about OpenClaw strengths: 15+ messaging platforms, native
  Chrome CDP browser control, voice wake words, 13k+ ClawHub skills
- Hermes advantages called out clearly: self-improving skills as a
  first-class automatic loop (vs marketplace-install model), stability
  (documented OpenClaw update regressions, Telegram breakage in early
  2026, WhatsApp protocol instability), security (156 CVEs and 1,184
  malicious skills found in ClawHub audit vs Hermes's no marketplace
  attack surface), Python/ML ecosystem, full web UI vs dashboard-only,
  and first-class multi-profile support
- Category 4 framework updated to name both Hermes and OpenClaw
- Table updated: added stability/security rows, corrected web UI row
  (OpenClaw has a gateway dashboard but not a full chat UI)

Claude Code corrections (researched against official docs at code.claude.com):
- Skills/Hooks: changed from No to Yes -- has a full Hooks system (13
  event types, 4 handler types) and a Plugin/Skills marketplace since
  v2.0.12; unified with slash commands in v2.1.0
- Messaging: changed from No to Partial -- Channels feature (Telegram,
  Discord, iMessage, Webhooks) in research preview since v2.1.80; deep
  Slack integration that triggers cloud sessions and creates PRs
- Added Claude Cowork row: separate product with 38+ connectors
  (Slack, Gmail, Teams, Notion, Jira, Salesforce, etc.)
- Scheduling footnote updated: cloud-managed has 1-hour minimum interval
- Provider-agnostic clarified: routes through Bedrock/Vertex but always
  Claude models; cannot swap to GPT or Gemini

Open Interpreter removed:
- Less relevant comparison than OpenClaw for the 'always-on agent' frame
- Kept coverage focused on the tools people actually compare Hermes to

Quick reference table:
- Now 7 tools wide (added OpenClaw, kept Claude Code, Codex, OpenCode,
  Cursor, Claude.ai, Hermes)
- New rows: self-improving skills, browser/computer control, stability
- Updated: Claude Code messaging to Partial, OpenClaw web UI to
  'Dashboard only', skills rows differentiated by type

* docs: apply full editorial pass from hermes-edit-list.md

Writing patterns fixed:
- Em dashes reduced by ~80%; replaced with commas, periods, parens
- All 'Not X, it's Y' negative parallelism rewritten as positive
  statements; 'What Hermes Is Not' section renamed 'Scope and Limits'
  and reframed positively throughout
- 'It compounds.' standalone flourish removed
- 'meaningfully' removed everywhere (was appearing 3+ times)
- 'leverages' -> 'uses' in README
- 'remembers everything' softened to 'retains context across sessions'
- Bolded Hermes column in Quick Reference table un-bolded (only genuine
  differentiator cells kept bold: self-improving skills, always-on,
  orchestrates other agents)
- 'The honest summary' framing removed from OpenClaw section
- 'Hermes is different.' cliche transition cut from README
- Rule-of-three slogans trimmed (e.g. 'Same agent, same memory...')
- 'tired of re-explaining' -> 'don't want to re-explaining'

Duplicate content removed:
- 'day one / day one hundred' comparison kept only in Compounding
  Advantage section; removed from Pillar 1

Factual accuracy fixes:
- Claude.ai comparison updated: memory now auto-generated from history
  (not just user-curated); code execution and file read/write noted
  as sandboxed (Artifacts), not flat No
- Category 2: Windsurf framed as 'earliest' on memory, Copilot
  'catching up'; removed overconfident 'most mature' claim
- Category 4 qualifier: 'as of early 2026' added
- '1-hour minimum' for Claude Code cloud scheduling softened to
  'minimum interval applies' (specific claim unverified)
- Claude Code scheduling table note: 'cloud or desktop-app only'
  (was just 'cloud-managed or session-scoped')
- README claim 'No other open-source tool combines...' removed;
  was false because OpenClaw does combine all three
- OpenClaw self-improving skills: 'No' -> 'Partial' with clarification
- README OpenClaw callout: 'relies on a marketplace' softened to
  'skill system centers on a community marketplace'
- 'meaningfully more stable' -> 'more stable'; 'supply chain issues'
  -> 'security incidents involving malicious skills'
- OpenClaw star count: '347k+' -> '~347k' (moving fast)
- Stability row added to OpenClaw table; bold removed from table

---------

Co-authored-by: Hermes <hermes@localhost>
2026-04-03 22:03:19 -07:00
Nathan Esquenazi
c1320b4712 Merge pull request #62 from nesquena/docs/v0.30.1-release
Some checks failed
Release & Docker / release (push) Has been cancelled
docs: v0.30.1 release — CLI bridge fixes + README update
2026-04-03 21:12:15 -07:00
Nathan Esquenazi
d3b693524f docs: v0.30.1 release — CLI bridge fixes, README update
CHANGELOG: add v0.30.1 entry covering PRs #57-#61 (CLI session bridge
fixes: sidebar rendering, profile-aware state.db path, silent SQL error,
show/hide toggle in Settings.

README: add CLI session bridge, token/cost display, subagent cards,
/usage command, skills linked files, show CLI sessions toggle.

Version label: v0.30 -> v0.30.1 in index.html, SPRINTS, CHANGELOG footer.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
EOF
)
2026-04-03 21:11:52 -07:00
nesquena-hermes
66f95e08c2 feat: 'Show CLI sessions' toggle in Settings (#61)
Adds a server-side boolean setting (default: false) that controls whether
CLI sessions from state.db appear in the sidebar. Off by default so the
sidebar is clean until the user explicitly opts in.

- api/config.py: add show_cli_sessions to _SETTINGS_DEFAULTS and _SETTINGS_BOOL_KEYS
- api/routes.py: gate get_cli_sessions() call on the setting at request time
- static/index.html: checkbox in settings panel with description
- static/panels.js: load/save checkbox, refresh session list on save
- static/boot.js: load on startup alongside send_key and show_token_usage

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 21:06:23 -07:00
nesquena-hermes
1a4d56c215 fix: CLI DB has no profile column, and silent SQL error swallowed results (#60)
The sessions table in the CLI state.db does not have a 'profile' column --
selecting s.profile caused an OperationalError which was silently caught by
'except Exception: return []', making get_cli_sessions() always return empty.

Fix: remove s.profile from the SELECT (it doesn't exist in the CLI schema)
and derive the profile from get_active_profile_name() instead, which is the
right value anyway since the CLI DB has no profile concept.

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 21:02:01 -07:00
nesquena-hermes
b2c2f32584 fix: CLI session bridge reads active profile's state.db not server launch profile (#59)
get_cli_sessions() and get_cli_session_messages() were using HERMES_HOME
(the profile the server was launched under) to find state.db. This meant
a server launched under the webui profile would read webui's state.db
(full of cron runs) instead of the user's actual CLI sessions.

Fix: use get_active_hermes_home() which tracks whichever profile the user
has selected in the UI. This means:
  - default profile active -> reads ~/.hermes/state.db (interactive CLI)
  - camanji profile active -> reads ~/.hermes/profiles/camanji/state.db

Falls back to HERMES_HOME env var if profiles module unavailable.

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 21:00:04 -07:00
nesquena-hermes
15fde033c3 fix: wire up CLI session display in sidebar (3 frontend gaps) (#58)
The backend CLI session bridge (PR #56) was complete but the frontend
never connected to it:

1. css class never applied -- el.className never included 'cli-session'
   so the gold border and 'cli' badge CSS was dead code. Fixed: append
   ' cli-session' when s.is_cli_session is true.

2. import never triggered -- click handler always called loadSession()
   directly, never POST /api/session/import_cli. Fixed: for CLI sessions,
   call import_cli first (idempotent -- safe to call on every click),
   then fall through to loadSession() which now finds the imported copy.

3. profile filter silently hid CLI sessions -- filter required
   s.profile === S.activeProfile, but CLI sessions may have profile=null
   if the SQLite DB has no profile column. Fixed: CLI sessions always
   pass the filter (s.is_cli_session || s.profile === S.activeProfile).

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 20:55:29 -07:00
nesquena-hermes
10a1e57c9b docs: fix test count in v0.30 CHANGELOG (424 not 426) (#57)
Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 20:44:58 -07:00
Nathan Esquenazi
4f10080501 Merge pull request #56 from thadreber-web/feat/cli-session-bridge
Some checks failed
Release & Docker / release (push) Has been cancelled
feat: CLI session bridge - read CLI sessions from agent SQLite store
2026-04-03 20:42:21 -07:00
Nathan Esquenazi
f8ea02c14d merge: resolve conflicts with master (v0.29), bump to v0.30
Resolved CHANGELOG.md and SPRINTS.md conflicts: master added v0.29
(Sprint 23: Agentic Transparency), CLI bridge becomes v0.30.
Updated all version references to v0.30.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 20:42:11 -07:00
Nathan Esquenazi
122fe955b6 docs: v0.29 release notes for CLI session bridge, version bump
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 20:39:27 -07:00
Nathan Esquenazi
017d7f1eca fix: add missing HOME import to models.py (NameError crash)
get_cli_sessions() and get_cli_session_messages() reference HOME but
it was not imported from api.config. This caused /api/sessions to 500
on every request, breaking the entire session list.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 20:37:34 -07:00
Thad Reber
cabda6b77a feat: CLI session bridge - read CLI sessions from agent SQLite store
Read CLI sessions from the agent's state.db and surface them in the
WebUI sidebar alongside local sessions, with read-only display and
import-on-click to avoid data duplication.

Key changes:
- get_cli_sessions(): reads sessions list via parameterized SQL,
  wrapped in sqlite3 context manager (no connection leaks)
- get_cli_session_messages(): reads messages for a CLI session
  via parameterized SQL, also context-managed
- GET /api/sessions: merges WebUI + CLI sessions with dedup
  (WebUI takes priority on same session_id)
- GET /api/session: falls back to CLI store if not a WebUI session
- POST /api/session/import_cli: imports a CLI session into the
  WebUI store (idempotent, no duplicates on re-import)
- Imported sessions use get_last_workspace() for the workspace field
  (not a hardcoded string) and carry the active profile tag
- CSS: .cli-session with ::after 'cli' indicator (no theme changes)

Fixes review feedback:
- SQLite connections use 'with' context managers (no leaks)
- Workspace uses real path via get_last_workspace()
- Profile awareness via api.profiles.get_active_profile_name()
- Parameterized SQL queries throughout (no injection risk)
- Graceful fallback when sqlite3 or state.db is missing
2026-04-03 19:54:54 -07:00
nesquena-hermes
33fca2383c docs: v0.29 release notes + roadmap/sprint plan updates
- CHANGELOG.md: add v0.29 entry covering all Sprint 23 deliverables
  (token/cost display, subagent cards, skill picker, linked files viewer,
  workspace tree persistence, timestamp fixes, XSS + security fixes)
- ROADMAP.md: update to v0.29, add Sprint 23 to history table, check off
  token/cost, skill linked files, skill picker in cron (3 items closed)
- TESTING.md: update automated test count 415 -> 424
- SPRINTS.md: add Sprint 24 (web polish bug fix pass) and Sprint 25
  (macOS native desktop app) forward plans; remove stale stub entries

Co-authored-by: Nathan Esquenazi <nesquena@gmail.com>
2026-04-03 19:36:18 -07:00
Nathan Esquenazi
be951a4d1d Merge pull request #54 from nesquena/fix/stricter-docker-regex
fix(ci): stricter semver regex for Docker tags
2026-04-03 19:33:14 -07:00
Nathan Esquenazi
bba9a236c3 fix(ci): use stricter semver regex for Docker tag extraction
Use v(\d+\.\d+(?:\.\d+)?) instead of v(.*) to only match real
version numbers (v0.29, v0.29.1), not arbitrary strings.
Keep latest unconditional since all tag pushes are releases.

Based on review of PR #52 approach vs #53.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 19:32:50 -07:00
Nathan Esquenazi
846565484b Merge pull request #53 from nesquena/fix/release-docker-tags
Some checks failed
Release & Docker / release (push) Has been cancelled
fix(ci): Docker tag extraction for 2-part versions (v0.29)
2026-04-03 19:28:18 -07:00
Nathan Esquenazi
1a579ef9cf fix(ci): use match pattern for Docker tags to support 2-part versions
The semver pattern in docker/metadata-action requires 3-part versions
(e.g. v0.29.0). Our tags use 2-part (v0.29), causing the metadata
step to produce empty tags, which made build-push-action fail.

Fix: use type=match with regex to extract the version string directly,
plus type=raw for the latest tag unconditionally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 19:27:41 -07:00
Nathan Esquenazi
1605d65226 Merge pull request #51 from nesquena/sprint-23-agentic-transparency
Sprint 23: Agentic transparency — token costs, subagent cards, skill picker, linked files
2026-04-03 19:16:42 -07:00
Nathan Esquenazi
3d4d7f2b53 fix: test hardening for sprint 23 — handle missing cron/skills modules in test env
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 19:16:17 -07:00
Nathan Esquenazi
2fb2ddeaaa feat: token usage toggle (setting + /usage command) + timestamp fixes
Token usage display:
- Add 'show_token_usage' boolean to settings (default: false, off by default)
- Settings panel: checkbox 'Show token usage after responses'
- /usage slash command: instant toggle with toast feedback, persists to
  server, updates checkbox if settings panel is open, re-renders messages
- Boot: load show_token_usage alongside send_key on startup
- ui.js: gate usage badge on window._showTokenUsage flag

Timestamps:
- streaming.py: stamp 'timestamp' on every message that lacks one at
  conversation completion; old messages (no timestamp field) now get a
  wall-clock time the first time they're touched by a new turn
- messages.js: stamp _ts on the last assistant message at done-event time
  so the time shows immediately on the current turn before next reload
- Timestamps already render in the UI (Sprint 14): faint time on each
  role header line, full opacity on hover, full date in title tooltip
2026-04-03 19:11:36 -07:00
Nathan Esquenazi
b1d687ba22 feat: persist workspace tree expanded state across refreshes
Store expanded directory paths in localStorage keyed by workspace path
(key: 'hermes-webui-expanded:{workspacePath}'). On root load (loadDir('.')),
restore the saved set for the current workspace and pre-fetch dir contents
for any restored expanded directories so the tree renders fully on first
paint without requiring a second click to expand.

Saves on every expand/collapse toggle. Switching workspaces automatically
picks up that workspace's own saved state. Per-workspace (not per-session)
so the same tree state is shared across sessions using the same workspace,
which is the natural expectation.
2026-04-03 19:11:36 -07:00
Nathan Esquenazi
c1dcd73502 fix: security, correctness, and test hardening from review
- routes.py: reject glob wildcards (* ? [ ]) in skill name param to
  prevent rglob wildcard injection when serving linked files
- panels.js: replace inline onclick+esc() with data-* attributes and
  addEventListener for skill tag removal and linked-file clicks;
  esc() is HTML-safe but not JS-safe -- apostrophes in names caused
  JS syntax errors and _cronSelectedSkills array corruption
- ui.js: fix _fmtTokens(null/undefined) returning 'null'/'undefined'
  by guarding with (!n||n<0) -> '0'; add data-role attribute to msg-row
  elements so usage badge correctly targets the last assistant row
  instead of the last row regardless of speaker
- tests: rename test_sprint24.py -> test_sprint23.py (wrong sprint #);
  add 3 new tests: path traversal rejection, wildcard name rejection,
  cron create with skills; strengthen existing tests to assert field
  presence explicitly (was using .get(field, 0)==0 which never caught
  a missing field)
2026-04-03 19:11:36 -07:00
Nathan Esquenazi
df06c1cdca feat: Sprint 23 — agentic transparency + polish
Track A: Token/cost display
- Read agent usage attrs (session_prompt_tokens, session_completion_tokens,
  session_estimated_cost_usd) after run_conversation in streaming.py
- Add input_tokens, output_tokens, estimated_cost fields to Session model
- Include usage in done SSE event payload
- Store usage on S.lastUsage in messages.js done handler
- Render usage badge below last assistant message (input/output/cost)

Track B: Subagent delegation cards
- Add subagent_progress to toolIcon map with shuffle emoji
- Special-case subagent_progress in buildToolCard: "Subagent" label,
  strip double emoji from preview, add tool-card-subagent CSS class
- Indented border-left styling for subagent cards
- Clean delegate_task display name

Track C: Skill picker in cron create form
- Add skill search input + tag chips to cron create form HTML
- Skill picker JS in panels.js: search/filter, click-to-add tags,
  remove tag chips, pre-fetch skill list on form open
- submitCronCreate sends skills array in POST body
- Skill picker dropdown + tag CSS

Track D: Skill linked files viewer
- Add file query param to /api/skills/content endpoint
- Serve linked files from skill directory with path traversal protection
- Ensure linked_files key always present in skill content response
- Render linked files section below SKILL.md content in preview panel
- openSkillFile function for viewing individual linked files

Track E: Bug fixes and code quality
- Expand Session.__init__ and compact() to readable multi-line format
- Remove inline import json as _j2 inside loop in streaming.py
- Fix tool_calls: capture args from assistant messages, skip unresolved names
- Store args snapshot in persisted tool_calls for reload display

6 new tests. Total: 421 (409 passing).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 18:33:49 -07:00
Nathan Esquenazi
2c0f6e80b6 Merge pull request #49 from nesquena/docs/update-all-markdown-v0.28
docs: update all markdown to v0.28.1 state
2026-04-03 14:20:29 -07:00
Nathan Esquenazi
4a4af209ad docs: update all markdown to v0.28.1 state
- README: add GHCR pre-built images to Docker section, update line counts
  and test count (426 tests, 22 files), add CI/CD to architecture tree
- ROADMAP: update header to v0.28.1/426 tests, mark all user-requested
  features as shipped, collapse completed Waves 3-7 into summary table,
  update architecture line counts, add CI/CD row
- CHANGELOG: add v0.28.1 entry for CI pipeline + multi-arch Docker builds,
  update footer version
- SPRINTS: update header and footer to v0.28.1

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 14:18:50 -07:00
Nathan Esquenazi
279690e4c1 Merge pull request #48 from nesquena/fix/ci-action-versions
Some checks failed
Release & Docker / release (push) Has been cancelled
fix(ci): use standard version tags for GitHub Actions
2026-04-03 14:10:39 -07:00
Nathan Esquenazi
2766314e81 fix(ci): use standard version tags for GitHub Actions
The SHA-pinned versions from the security hardening commit referenced
non-existent commit hashes, causing the workflow to fail with 'unable
to resolve action'. Switch to standard major version tags (v4, v3, v2,
v6, v5) which are the recommended approach for GitHub-maintained and
well-known actions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 14:09:36 -07:00
nesquena-hermes
9d69408610 ci: add GitHub Actions workflow for multi-arch Docker + releases (#47)
Some checks failed
Release & Docker / release (push) Has been cancelled
ci: multi-arch Docker builds + GitHub Releases on tag push
2026-04-03 14:02:52 -07:00
Nathan Esquenazi
4a3b9571f1 fix(ci): pin all GitHub Actions to full commit SHAs for supply chain security
Pinned all 7 third-party actions from mutable version tags to immutable
commit SHAs. Mutable tags (e.g. @v4) can be force-pushed by the action
author (or a compromised account) to inject malicious code into the workflow,
which runs with write access to the repo and GHCR registry.

Also moved 'permissions' from workflow level to job level (best practice:
scope permissions as narrowly as possible).

Pin mapping:
  actions/checkout@v4               -> @11bd71901bbe...  (v4.2.2)
  softprops/action-gh-release@v2    -> @c062e08bd532...  (v2.2.1)
  docker/setup-qemu-action@v3       -> @49b3bc8e6bdd...  (v3.2.0)
  docker/setup-buildx-action@v3     -> @c47758b77c97...  (v3.7.1)
  docker/login-action@v3            -> @9780b0c442fb...  (v3.3.0)
  docker/metadata-action@v5         -> @369eb591f429...  (v5.6.1)
  docker/build-push-action@v6       -> @ca877d9245fe...  (v6.10.0)
2026-04-03 21:02:08 +00:00
Nathan Esquenazi
c488031fe3 Merge pull request #45 from nesquena/fix/profile-creation-docker-fallback
fix: profile creation fallback for Docker (#44)
2026-04-03 14:01:04 -07:00
Nathan Esquenazi
94b080fa1e docs: v0.27 release notes, version bump for profile creation fallback
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 14:00:46 -07:00
Nathan Esquenazi
e6663596ce fix(review): 4 issues found in agent review of PR #45
BUG-1 (medium): _validate_profile_name() used re.match() with a $ anchor.
re.match() with $ is truthy for 'name\n' because match() allows trailing
content after the $ in multiline mode. Changed to re.fullmatch() which
requires the entire string to match — trailing newlines now correctly rejected.

BUG-2 (medium/defense-in-depth): create_profile_api() validated 'name' via
_validate_profile_name() but passed clone_from directly to hermes_cli and
_create_profile_fallback() without validation. Added clone_from validation
inside create_profile_api() (skipping 'default' which is a valid clone source).
routes.py already validates it at the HTTP layer; this adds API-layer defense.

BUG-3 (low): When hermes_cli is not importable (the exact Docker case this PR
targets), list_profiles_api() also returns only the stub default dict and
can't find the newly created profile by name. The fallback return was a
2-key dict {name, path} — incomplete vs the 9-key schema everywhere else.
Expanded to the full profile dict with all fields so API clients get
consistent data regardless of hermes_cli availability.

OBS-4 (low/TOCTOU): _create_profile_fallback() checked profile_dir.exists()
then called mkdir(exist_ok=True). If a concurrent request created the dir
between those two calls, mkdir silently succeeded — defeating the
FileExistsError guard. Changed to mkdir(exist_ok=False) so the OS raises
FileExistsError atomically if the dir appears in the race window.

Tests: 423 passed, 0 failed.
2026-04-03 13:58:43 -07:00
Nathan Esquenazi
16553be59d fix: profile creation fallback when hermes_cli unavailable (Docker)
When hermes-agent is not discoverable (common in Docker), create_profile_api()
raised a hard RuntimeError while list and delete already had manual fallbacks.

Changes:
- Add _create_profile_fallback() that bootstraps profile directory structure
  directly (matching upstream hermes_cli.profiles: 8 subdirs + config clone)
- Extract _validate_profile_name() so validation works without hermes_cli
- Add constants _PROFILE_ID_RE, _PROFILE_DIRS, _CLONE_CONFIG_FILES matching
  upstream hermes-agent
- Remove :ro from docker-compose.yml hermes home mount so profiles dir is
  writable inside the container

Closes #44

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 13:58:43 -07:00
Nathan Esquenazi
6a61f36280 ci: add GitHub Actions workflow for multi-arch Docker + releases
On tag push (v*):
- Creates a GitHub Release with auto-generated release notes
- Builds multi-arch Docker image (linux/amd64, linux/arm64)
- Pushes to ghcr.io/nesquena/hermes-webui with semver tags
- Uses GitHub Actions cache for faster builds

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 13:55:41 -07:00
Nathan Esquenazi
b03ddf78c9 Merge pull request #46 from nesquena/fix/profile-switch-default-home
fix: Profile system polish — 10 post-Sprint-23 fixes (v0.26)
2026-04-03 13:44:16 -07:00
Nathan Esquenazi
5c9edfc7bf docs: v0.26 release notes, remove planning artifact, update versions
- Add v0.26 CHANGELOG entry (10 post-Sprint-23 fixes)
- Remove SPRINT_23_PLAN.md (planning artifact, not runtime docs)
- Bump version label to v0.26 in index.html
- Update SPRINTS header and footer to v0.26 / 426 tests
- Update CHANGELOG footer to v0.26 / 426 tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 13:44:06 -07:00
Nathan Esquenazi
733957cea1 docs: add Sprint 23 planning document (profile/workspace/model coherence spec) 2026-04-03 20:37:48 +00:00
Nathan Esquenazi
e61382ef71 fix: pass fallback_model to AIAgent; show rate-limit error inline instead of 'Connection lost'
Two fixes for Camanji rate limit UX:

1. api/streaming.py — pass fallback_model from profile config to AIAgent
   The agent already supports fallback_model (a dict with provider/model/base_url)
   for automatic rate-limit recovery, but streaming.py never read it from config
   or passed it to AIAgent.  Now reads get_config().get('fallback_model') at
   call time (not module-level snapshot) and passes it through.
   Also reads platform_toolsets.cli from the active profile's config at call
   time so profiles with custom toolset lists use the right tools.

   Camanji has fallback_model: {provider: openrouter, model: anthropic/claude-sonnet-4.6}
   so hitting the direct-Anthropic rate limit will now automatically retry via
   OpenRouter before giving up.

2. api/streaming.py + static/messages.js — show error inline, not 'Connection lost'
   Previously: agent threw -> put('error', msg) -> SSE connection closed ->
   browser's network-level 'error' event fired -> generic 'Connection lost'.
   The actual error message was invisible to the user.

   Fix: renamed server-side error event to 'apperror' (distinct from the SSE
   spec's network error event).  Added source.addEventListener('apperror', ...)
   in messages.js that renders the error as a styled assistant message:
     ⏱️ Rate limit reached: <full message>
     *Rate limit reached. Fallback model exhausted. Try again in a moment.*
   Also added source.addEventListener('warning', ...) for non-fatal notices
   (future use: fallback-activated status bar update).

Tests: 426 passed, 0 failed.
2026-04-03 20:34:52 +00:00
Nathan Esquenazi
da43a6a09a fix: switching profiles mid-conversation starts a new session instead of cross-tagging
A session with messages belongs to the profile it was created under. Switching
profiles while a conversation is in progress should not retag that session or
update its workspace/model in place — that would corrupt the session's context.

New behavior:
- Session has NO messages (empty): profile switch updates it in place (model,
  workspace). Works exactly as before — nothing was started yet.
- Session HAS messages (in progress): profile switch calls newSession() to
  start a fresh session tagged to the new profile. The old session is left
  untouched. Toast: 'Switched to profile: X — new conversation started'.
- Agent busy: blocked as before, no change.

Also: S._profileDefaultWorkspace is now consumed (set to null) inside
newSession() after the first use, so it doesn't keep forcing the same
workspace on every subsequent new session after a switch.
2026-04-03 20:27:50 +00:00
Nathan Esquenazi
4eae6c98f9 fix: cross-provider model pick causes Connection lost on non-OpenRouter profiles
Root cause: resolve_model_provider() had a branch:
  if config_provider and config_provider != 'openrouter' and prefix in _PROVIDER_MODELS:
      return bare, prefix, None

When Camanji profile (config_provider='anthropic') picked openai/gpt-5.4-mini
from the OpenRouter dropdown, prefix='openai' matched _PROVIDER_MODELS and
config_provider was not 'openrouter', so it returned ('gpt-5.4-mini', 'openai', None).
The agent then demanded OPENAI_API_KEY directly -- not found -- RuntimeError --
stream crashed -- 'Connection lost'.

Fix: if prefix != config_provider (cross-provider selection), always route through
openrouter with the full provider/model string. Only strip the prefix and call a
direct provider API when the config_provider EXACTLY matches the model prefix.

Cases verified:
  openrouter + openai/gpt-5.4-mini     -> (openai/gpt-5.4-mini, openrouter)  ✓
  anthropic  + openai/gpt-5.4-mini     -> (openai/gpt-5.4-mini, openrouter)  ✓ FIXED
  anthropic  + anthropic/claude-...    -> (claude-..., anthropic)             ✓
  anthropic  + claude-sonnet-4-6 bare  -> (claude-sonnet-4-6, anthropic)      ✓
  openrouter + anthropic/claude-...    -> (anthropic/claude-..., openrouter)  ✓

Tests: 426 passed, 0 failed.
2026-04-03 20:23:25 +00:00
Nathan Esquenazi
c71439d8ab fix: model picker correctly updates on profile switch without flicker or raw injection
Root cause: three interacting bugs caused the model picker to show the wrong
model or flicker after a profile switch.

Bug 1 — syncTopbar() fought switchToProfile().
After switchToProfile() set the picker to the profile's model, syncTopbar()
was called (via renderSessionList -> loadSession, then explicitly at the end)
and overwrote it with S.session.model -- the old session's model.
Fix: added S._pendingProfileModel flag. switchToProfile() sets it;
syncTopbar() checks it first, applies the override, then clears it.
S.session.model is also updated to the resolved value so subsequent
syncTopbar() calls are consistent.

Bug 2 — Raw option injected at top of list for mismatched model IDs.
Profile configs store model IDs like 'claude-sonnet-4-6' (hermes-agent
format: hyphens, no namespace prefix) but the dropdown has
'anthropic/claude-sonnet-4.6' (OpenRouter format: dots, with prefix).
The old code did sel.value = id, found no match, then injected a new
<option> at the top of the list -- creating a lowercase duplicate that
didn't match any real provider group entry.
Fix: _findModelInDropdown() normalises both sides (strip prefix, hyphens->dots,
lowercase) and finds the best matching existing option. No new options are ever
injected for profile switching.

Bug 3 — populateModelDropdown() injected raw option on cold load.
Same issue: if default_model from /api/models didn't exactly match a dropdown
value, an extra option was added. Fixed by using _applyModelToDropdown()
which only selects existing options.

New helpers in ui.js:
  _findModelInDropdown(modelId, sel) -- smart fuzzy match, returns matched value
  _applyModelToDropdown(modelId, sel) -- sets picker, returns resolved value

Tests: 426 passed, 0 failed.
2026-04-03 20:10:47 +00:00
Nathan Esquenazi
ad755e49e5 fix: workspace isolation, session filtering, and clean migration path
Three interrelated fixes:

1. api/workspace.py — clean workspace isolation with auto-migration
   _clean_workspace_list(): sanitizes any workspace list by:
   - Removing test artifacts (webui-mvp-test, test-workspace paths)
   - Removing paths that no longer exist on disk
   - Removing cross-profile leaks (paths under ~/.hermes/profiles/*)
   - Renaming 'default' workspace label to 'Home' (avoids confusion
     with the 'default' profile name)

   _migrate_global_workspaces(): one-time migration for upgrading users.
   Reads the legacy global workspaces.json, runs _clean_workspace_list,
   rewrites it cleaned. This runs automatically on first load after upgrade
   for the default profile only.

   load_workspaces(): now cleans every read and persists cleaned version
   if anything changed. Named profiles always start fresh (no global leak).
   Empty results fall back to 'Home' entry pointing at profile's workspace.
   Default label for auto-generated single-entry lists is 'Home', not 'default'.

2. api/models.py — legacy session profile backfill (already committed,
   this commit adds the sessions.js filter tightening counterpart)

3. static/sessions.js — strict profile filter
   Removed the '!s.profile' escape hatch from the profile filter.
   Server now backfills profile='default' on legacy sessions, so every
   session has an explicit tag. Filter is now exact:
     s.profile === S.activeProfile
   Named profiles see zero legacy clutter. Default profile sees its own
   sessions. 'All profiles' toggle still shows everything.

Migration story for users pulling this update:
- Existing sessions (profile=null) -> attributed to 'default' at read time
- Global workspaces.json -> cleaned of test artifacts and cross-profile paths
  on first server start after upgrade
- Named profile workspace files -> cleaned on first read, persisted clean
- No manual intervention needed

Tests: 426 passed, 0 failed.
2026-04-03 20:01:12 +00:00
Nathan Esquenazi
f75e17c912 fix: legacy sessions (profile=null) leak into all profiles' session lists
Root cause: sessions created before Sprint 22 have no profile tag (profile=None).
The client filter was '!s.profile || s.profile === S.activeProfile' -- the
'!s.profile' guard made ALL 33 legacy sessions visible under every profile,
so switching to Camanji still showed the entire default session history.

Fix:
- api/models.py all_sessions(): backfill profile='default' on sessions with
  no profile tag before returning. This is in-memory only (no disk writes) --
  legacy sessions just get attributed to the default profile at read time.
  Applied to both the index-path and the full-scan fallback path.
- static/sessions.js: tighten the client filter to s.profile === S.activeProfile
  (remove the '!s.profile' escape hatch -- now redundant since server fills it).
  Every session now has an explicit profile, so the filter is precise.

Result: switching to Camanji shows only Camanji sessions. Default profile shows
legacy + default-tagged sessions. 'All profiles' toggle still shows everything.
S.activeProfile defaults to 'default' in the S object so first render is safe.

Tests: 426 passed, 0 failed.
2026-04-03 19:50:08 +00:00
Nathan Esquenazi
3d8cf85ef2 fix: profile default workspace reads terminal.cwd; dropdown opens upward
1. _profile_default_workspace() now checks terminal.cwd
   Profile config.yaml files don't have a 'workspace' or 'default_workspace' key
   — they store the working directory as terminal.cwd (the hermes-agent CLI
   setting). Added it as the third fallback after 'workspace' and
   'default_workspace', so switching to camanji correctly resolves
   ~/Camanji, webui resolves ~/webui-mvp, etc.

2. Workspace dropdown opens upward (bottom: calc(100% + 4px))
   The dropdown is now anchored at the bottom of the sidebar. Opening it
   downward (top: 100%) caused it to clip off screen. Flipped to open upward
   with an upward shadow so it expands into the session list area instead.

Tests: 426 passed, 0 failed.
2026-04-03 19:47:38 +00:00
Nathan Esquenazi
d4ab01c152 fix: workspace updates on profile switch; remove redundant topbar workspace chip
Two changes:

1. Workspace updates correctly on profile switch
   switchToProfile() now applies data.default_workspace from the switch
   response to the current session via /api/session/update, updates
   S.session.workspace in-memory, and stores S._profileDefaultWorkspace
   so the next new session also inherits the profile's workspace.
   newSession() in sessions.js picks up S._profileDefaultWorkspace when
   creating a new session after a profile switch.

2. Workspace chip removed from topbar
   The workspace was shown in two places: the topbar chip (wsChip) AND
   the sidebar bottom display (sidebarWsDisplay with name + full path).
   The topbar chip was redundant, cluttered the topbar, and pushed other
   chips (profile, model, clear, settings) off screen.
   Removed wsChip from the topbar entirely. The sidebar display is now
   the sole workspace UI, consistent and unambiguous.
   Moved wsDropdown to live inside the sidebar position:relative wrapper
   so it opens downward from sidebarWsDisplay. Updated the click-outside
   listener to close on clicks outside sidebarWsDisplay/wsDropdown.
   Removed stale wsChip update code from syncTopbar() in ui.js.

Tests: 426 passed, 0 failed.
2026-04-03 19:38:33 +00:00
Nathan Esquenazi
c778c1eb0c fix: profile switch fails with 'does not exist' when server starts on non-default profile
Root cause: _DEFAULT_HERMES_HOME was evaluated at module import time from
os.getenv('HERMES_HOME'). HERMES_HOME is a MUTABLE env var -- init_profile_state()
at server startup calls _set_hermes_home() which writes to os.environ['HERMES_HOME'].
If the sticky active_profile file pointed to e.g. 'webui', HERMES_HOME was set to
~/.hermes/profiles/webui BEFORE api/profiles.py imported. So _DEFAULT_HERMES_HOME
resolved to ~/.hermes/profiles/webui. Then switch_profile('webui') computed:
  home = ~/.hermes/profiles/webui / 'profiles' / 'webui'
       = ~/.hermes/profiles/webui/profiles/webui  -- doesn't exist -> 404 ValueError

Fix: replace the one-liner assignment with _resolve_base_hermes_home() which:
  1. Checks HERMES_BASE_HOME env var (explicit override)
  2. Checks HERMES_HOME -- but if it looks like a profiles/ subdir (parent.name ==
     'profiles'), walks up two levels to the actual base
  3. Falls back to Path.home() / '.hermes'

This means the server can start with HERMES_HOME pointing to any profile and
_DEFAULT_HERMES_HOME will still correctly point to ~/.hermes.

Also fix: api() helper in workspace.js was throwing new Error(await res.text())
which surfaced raw JSON to the UI: 'Switch failed: {"error":"Profile X does not exist."}'
Now parses the JSON and extracts j.error so the toast shows clean human-readable text.

Regression tests added in test_sprint23.py:
- test_profile_switch_base_home_not_subdir: static analysis verifying the resolver
- test_api_helper_returns_clean_error_message: verifies api() parses JSON errors
- test_profile_switch_resolve_base_home_logic: verifies the profiles/ subdir detection

Tests: 426 passed, 0 failed.
2026-04-03 19:29:24 +00:00
Nathan Esquenazi
ca01845643 Merge pull request #43 from nesquena/feat/sprint23-profile-coherence
feat: Sprint 23 -- Profile/Workspace/Model Coherence
2026-04-03 12:10:39 -07:00
Nathan Esquenazi
30529e0002 docs: fix SPRINTS header and CHANGELOG footer to v0.25
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 12:10:29 -07:00
Nathan Esquenazi
7ef203cd41 fix(review): 5 issues found in agent review of PR #43
BUG-1 (critical): api/profiles.py _DEFAULT_HERMES_HOME used Path.home()/.hermes
hardcoded, ignoring the HERMES_HOME env var. conftest.py sets HERMES_HOME to a
test-isolated state dir -- but profiles.py bypassed it and read/wrote real ~/.hermes
during every test run (active_profile file, .env loading). Fixed by reading
os.getenv('HERMES_HOME', ...) at module load time.

BUG-7 (medium): api/workspace.py load_workspaces() fell back to the global
workspaces.json for ALL profiles when their profile-local file didn't exist yet.
New named profiles silently inherited the default profile's workspace list instead
of starting clean. Fixed: the global file fallback now only applies to the default
profile (migration path); named profiles start with a fresh default entry.

BUG-4 (high): test_sessions_list_includes_profile had a vacuous 'if matching:'
guard -- if the session wasn't found the assert was silently skipped and the test
passed. Fixed with hard assert. Also changed to use /api/session?session_id=
directly instead of scanning /api/sessions (which filters out empty Untitled
sessions with 0 messages, causing the test to always see an empty match list).

BUG-5 / test ordering regression: test_profile_switch_returns_default_model_and_workspace
failed with 409 because test_chat_stream_opens_successfully (runs earlier in the
suite) starts a real LLM stream that stays alive in STREAMS. Added a wait loop
(up to 30s) polling /health active_streams before attempting the profile switch.

BUG-8 (low): Removed dead import _profile_default_workspace in switch_profile()
-- was imported but never used (get_last_workspace() already delegates to it).

Also: test_profile_active_endpoint hardcoded assert data['name'] == 'default'
which fails if a prior run left a non-default active_profile on disk. Changed
to assert name is a non-empty string (the endpoint contract), not a specific value.

Tests: 423 passed, 0 failed.
2026-04-03 19:03:16 +00:00
Nathan Esquenazi
3520fa5643 feat: Sprint 23 -- profile/workspace/model coherence
Fix five coherence bugs in profile switching:
1. Model picker ignored profile default (localStorage stale key)
2. Workspace list was global (not profile-scoped)
3. DEFAULT_WORKSPACE was a boot-time singleton
4. Session list showed all profiles (no filtering)
5. switchToProfile() didn't refresh workspaces or sessions

Backend: workspace storage is now profile-local for named profiles,
switch_profile() returns default_model and default_workspace.
Frontend: switchToProfile() clears stale model pref, refreshes
workspace list and session list, sessions.js filters by active profile
with 'Show N from other profiles' toggle.

8 new tests. 400 pass / 23 fail (identical to baseline).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 11:46:15 -07:00
Nathan Esquenazi
0480bbf34c Merge pull request #42 from nesquena/docs/comprehensive-markdown-update
docs: comprehensive markdown update for v0.24
2026-04-03 11:25:30 -07:00
Nathan Esquenazi
28ac04da7d docs: comprehensive markdown update for v0.24
README.md:
- Features section rewritten: added voice input, profiles, auth/security,
  slash commands, mobile responsive, thinking display, session projects,
  workspace tree, code copy, safe HTML rendering sections
- Architecture tree updated with all current files and line counts
- Env var table: added HERMES_WEBUI_PASSWORD
- Test section: updated count (415 tests), corrected pytest command
- Docs section: added SPRINTS.md reference

ARCHITECTURE.md:
- File inventory: added profiles.py, Dockerfile, docker-compose.yml,
  .dockerignore; updated all line counts to current values
- Env vars: added HERMES_HOME to both server-level and per-request sections
- Test files: 21 files, 415 functions (was 17 files, 327)

ROADMAP.md:
- Header: v0.21 -> v0.24, 328 -> 415 tests
- Sprint history table: added Sprints 20-22
- Architecture table: updated line counts and added Docker row
- Feature checklist: marked voice, mobile, profiles as done; reorganized

TESTING.md:
- Header: Sprint 19/v0.21 -> Sprint 22/v0.24, updated test counts
- Footer: same updates
- Added manual test sections for Sprints 20 (voice + send button),
  21 (mobile + Docker), 22 (multi-profile)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 11:20:43 -07:00
Nathan Esquenazi
f21b088a14 Merge pull request #41 from nesquena/feat/multi-profile-support
feat: Multi-Profile Support (Issue #28)
2026-04-03 11:10:43 -07:00
Nathan Esquenazi
4bec7c082e docs: fix SPRINTS header and CHANGELOG footer to v0.24
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 11:10:28 -07:00
Nathan Esquenazi
571a5a40f1 fix(review): 3 issues found in agent review of PR #41
BUG-3 (high): /api/profile/delete missing RuntimeError catch. When
deleting the active profile while an agent was running, delete_profile_api()
called switch_profile('default') which raises RuntimeError('Cannot switch
profiles while agent is running'). This propagated to the 500 handler
giving the user 'Internal server error' with no context. Added the same
except RuntimeError -> 409 pattern that /api/profile/switch already uses.

INFO-1 (defense-in-depth): /api/profile/create had no server-side name
validation before delegating to hermes_cli.validate_profile_name. Added
server-side ^[a-z0-9][a-z0-9_-]{0,63}$ check, consistent with client-side
regex in submitProfileCreate(). Prevents path-traversal-ish names from
reaching hermes_cli even if the client-side guard is bypassed.

INFO-2 (defense-in-depth): clone_from parameter was passed directly to
hermes_cli with no validation. Applied the same name regex check to
clone_from before delegating.

BUG-11 (low): toggleProfileDropdown() and toggleWsDropdown() could both
be open simultaneously. Added cross-dropdown close calls: opening the
profile dropdown now closes the workspace dropdown, and vice versa.

Tests: 415 passed, 0 failed.
2026-04-03 18:06:18 +00:00
Nathan Esquenazi
d2b27f6f1e feat: multi-profile support -- create, switch, delete profiles from web UI (Issue #28)
Add full profile management to the web UI, matching the hermes-agent CLI
profile system. Profiles are isolated HERMES_HOME instances with their own
config, skills, memory, cron, and API keys.

Backend: new api/profiles.py wrapping hermes_cli.profiles, dynamic config
reloading, 5 new API endpoints, profile-aware path resolution, HERMES_HOME
env save/restore in streaming, module-level cache patching for skills_tool
and cron/jobs.

Frontend: profile chip in topbar with dropdown, Profiles sidebar panel with
CRUD UI, boot-time profile fetch, cascade refresh on switch.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:50:21 -07:00
Nathan Esquenazi
af73a5d8fd Merge pull request #40 from nesquena/sprint-21-mobile-docker
Sprint 21: Mobile responsive layout + Docker support (Issues #21, #7)
2026-04-03 10:29:04 -07:00
Nathan Esquenazi
a92c251ef8 docs: Sprint 21 release notes, version v0.23, Docker localhost binding
- CHANGELOG: add v0.23 Sprint 21 entry (mobile + Docker)
- SPRINTS: Sprint 21 marked COMPLETED, footer updated
- index.html: version label v0.22 -> v0.23
- docker-compose.yml: bind to 127.0.0.1 by default (SEC-1 fix)
- README: add security note about Docker port binding

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:28:47 -07:00
Nathan Esquenazi
574cd2cf70 fix(review): 5 issues found in agent review of PR #40
BUG-1 (critical): CSS cascade — .sidebar{position:relative} and
.rightpanel{position:relative} at line 528/530 appeared after the
@media(max-width:640px) block and silently overrode the position:fixed
overlay behavior needed for the mobile slide-in. Wrapped both in
@media(min-width:641px) so they only apply on desktop.

BUG-2 (medium): mobileSwitchPanel() in boot.js always reopened the
sidebar overlay after closing it, with a stale comment saying 'close
after a moment' but no actual auto-close. For the 'chat' panel, the
content lives in the main area — reopening the sidebar obstructs it.
Fixed: only open sidebar for non-chat panels; chat tap closes sidebar.

BUG-3 (medium): Dockerfile was missing 'pip install -r requirements.txt'.
pyyaml (required by api/config.py) is not in the python:3.12-slim base
image — the container would fail at startup with ImportError.

SEC-2 (medium): No .dockerignore — COPY . /app included .git/, tests/,
and .env* in every image. Added .dockerignore excluding these.

NIT-3: docker-compose.yml used ${HERMES_HOME:-~/.hermes} but Docker
Compose does not shell-expand ~ in default values. Changed to
${HERMES_HOME:-${HOME}/.hermes}.

Tests: 415 passed, 0 failed (same as pre-fix).
2026-04-03 17:21:42 +00:00
Nathan Esquenazi
d278563e00 feat: Sprint 21 — mobile responsive layout + Docker support
Mobile responsive (Issue #21):
- Hamburger sidebar: slide-in overlay on mobile (<640px) with backdrop.
  Tap hamburger in topbar to open, tap outside to close. Full session
  list, project chips, all panel content accessible.
- Bottom navigation bar: 5-tab fixed bar (Chat, Tasks, Skills, Memory,
  Spaces) replaces sidebar nav tabs on mobile. iOS-style layout.
  Tapping a tab opens the sidebar overlay with that panel active.
- Right panel slide-over: Files button in topbar chips opens workspace
  panel as a slide-over from the right on mobile/tablet.
- Touch targets: all interactive elements get min 44x44px touch areas.
  Session items, approval buttons, composer buttons all sized for fingers.
- Composer positioned above bottom nav bar with proper spacing.
- Sidebar nav tabs and bottom section hidden on mobile (replaced by
  bottom nav + topbar chips).
- Clicking a session auto-closes the sidebar overlay.
- Desktop layout completely unchanged — all mobile elements are
  display:none by default, only shown inside @media(max-width:640px).

Docker (Issue #7):
- Dockerfile: python:3.12-slim, HERMES_WEBUI_HOST=0.0.0.0, port 8787.
- docker-compose.yml: named volume for state persistence, optional
  ~/.hermes mount for agent features, password env var documented.
- README: Docker quick start section with compose and manual commands.

Tests: 392 passed, 23 pre-existing failures, 0 regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 10:09:36 -07:00
Nathan Esquenazi
8cd07d3774 Merge pull request #39 from nesquena/fix/test-keyframe-parser
fix: test_send_pop_in keyframe parser found wrong @keyframes block
2026-04-03 07:25:22 -07:00
Nathan Esquenazi
959c386d8d fix: test_send_pop_in keyframe parser hit wrong @keyframes block
rfind('@keyframes') searched backward from 'send-pop-in' but with both
keyframes on the same CSS line, it landed on mic-pulse instead.
Fix: use find('@keyframes send-pop-in') directly (forward search) via
a shared _extract_keyframe() helper. Same fix applied to both
test_send_pop_in_uses_scale and test_send_pop_in_uses_opacity.
2026-04-03 14:23:56 +00:00
Nathan Esquenazi
690f04bff0 Merge pull request #38 from nesquena/feat/send-button-polish
feat: polish send button — hidden until content, icon-circle, pop-in animation
2026-04-03 07:22:30 -07:00
Nathan Esquenazi
f5c9f218c4 docs: rename test_sprint21 to test_sprint20b, update test counts to 415
Sprint 20 combines voice input (20a) and send button polish (20b).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 07:22:13 -07:00
Nathan Esquenazi
dcb21dfd37 feat: polish send button — hidden until content, icon-circle, pop-in animation
- index.html: btnSend hidden by default (display:none), icon-only (upward
  arrow SVG, no text label), title attribute for accessibility

- style.css: new send-btn design — 34px circle, blue fill (#7cb9ff),
  subtle glow box-shadow, scale() hover/active for tactile feel,
  .send-btn.visible with @keyframes send-pop-in (scale+opacity spring
  using cubic-bezier(.34,1.56,.64,1) for a satisfying pop). Mobile
  override updated to preserve circle dimensions.

- ui.js: updateSendBtn() — shows button with pop-in animation when
  textarea has content OR files are attached and agent is not busy;
  hides instantly when content is cleared. Hooked into setBusy() and
  renderTray() so button state tracks all content sources correctly.

- boot.js: input event listener calls updateSendBtn() on every keystroke.

- messages.js: autoResize() calls updateSendBtn() so button disappears
  immediately after send clears the textarea.

- tests/test_sprint21.py: 33 tests covering HTML structure, CSS design
  (circle shape, colors, animations, keyframes), JS logic (updateSendBtn,
  setBusy, renderTray, autoResize integration), and regressions
  (363 total, all pass).
2026-04-03 07:20:16 -07:00
Nathan Esquenazi
59a92e03d8 Merge pull request #37 from nesquena/feat/voice-input-mic-button
feat: voice input mic button via Web Speech API
2026-04-03 07:19:38 -07:00
Nathan Esquenazi
df3de7a543 docs: Sprint 20 release notes, version v0.22, SPRINTS update
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 07:19:26 -07:00
Nathan Esquenazi
46fdf3513f fix: mic appends to existing textarea text instead of replacing it
Previously, tapping the mic button would reset the textarea each time,
clobbering anything the user had already typed or previously dictated.

Fix:
- Capture _prefix = ta.value when recording starts (btn.onclick)
- onresult writes _prefix + (final || interim) so live interim text
  appears after the existing content, not replacing it
- onend commits _prefix + _finalText with smart space insertion:
  if the prefix doesn't end with a space or newline, a space is added
  before the new transcript so words don't run together
- _prefix is reset to '' in _setRecording(false) so each new recording
  session starts with a fresh snapshot

Behaviour now: tap mic, speak, tap again (or wait for auto-stop) ->
transcript is appended to whatever was in the textarea. Tap mic again
-> continues appending further. Text stays fully editable before send.

tests/test_sprint20.py: 6 new tests covering prefix capture, onresult
prepend, onend commit, reset, and smart spacing (52 total, 382 overall).
2026-04-03 14:13:29 +00:00
Nathan Esquenazi
efb7293ae8 feat: add voice input mic button via Web Speech API
- index.html: add #btnMic (hidden by default, shown if browser supports
  SpeechRecognition) and #micStatus listening indicator inside .composer-box

- boot.js: IIFE-scoped mic handler wired to Web Speech API
  * recognition.continuous=false (auto-stops after ~2s silence)
  * recognition.interimResults=true (live transcript preview in textarea)
  * Toggles .recording class + shows #micStatus while active
  * Handles 'not-allowed', 'no-speech', 'network' errors via showToast()
  * btnSend.onclick stops active recognition before sending
  * Entire feature disabled/hidden gracefully when API unavailable

- style.css: .mic-btn, .mic-btn.recording (red pulse animation),
  .mic-status, .mic-dot, @keyframes mic-pulse

- tests/test_sprint20.py: 46 tests covering HTML structure, CSS rules,
  JS logic, error handling, and regression checks (376 total, all pass)

No API keys, no external libraries, no server changes. Browser-only.
Works in Chrome, Edge, Safari (partial). Firefox unsupported (hides button).
2026-04-03 14:04:03 +00:00
nesquena-hermes
44aa538b7c fix: stop leaking stack traces to clients in 500 responses
fix: stop leaking stack traces to clients in 500 responses
2026-04-03 06:46:34 -07:00
Nathan Esquenazi
1b1cd124f6 fix: stop leaking stack traces to clients in HTTP 500 responses
Tracebacks exposed file paths, module names, and potentially secret
values from local variables. Now logged server-side only; clients
receive a generic error message.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 06:41:32 -07:00
Nathan Esquenazi
3f9d1da0e2 Merge pull request #35 from nesquena/docs/fix-test-count-v021
docs: fix test count 327->328 (Sprint 19 added 10 tests, all passing)
2026-04-03 06:37:53 -07:00
Nathan Esquenazi
9363d967ed docs: fix stale test count in SPRINTS.md (327->328)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 06:37:45 -07:00
Nathan Esquenazi
2dda99082f docs: fix test count 327->328 in CHANGELOG, TESTING.md, ROADMAP.md
Sprint 19 added 10 new tests (not 9), bringing the total to 328 (not 327).
All 328 tests pass with 0 failures -- the "304 passing, 23 pre-existing
failures" note was stale from an earlier state of the test suite.

Files updated:
- CHANGELOG.md: v0.21 header, tests line, footer
- TESTING.md: automated tests header, footer
- ROADMAP.md: header note, Sprint History table
2026-04-03 13:34:21 +00:00
Nathan Esquenazi
51bcf8fead Merge pull request #34 from nesquena/sprint-19-auth-security
Sprint 19: Password auth, security headers, login page (Issue #23)
2026-04-03 06:22:44 -07:00
Nathan Esquenazi
56526ce502 chore: update UI version to v0.21, CHANGELOG footer
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 06:22:29 -07:00
Nathan Esquenazi
e0a1ab8e03 fix(auth): blank password field no longer clears auth; add Disable Auth button
The previous logic treated a blank password field as intent to clear auth,
which meant saving any other setting (model, send key, etc.) would silently
disable password protection.

New behavior:
- Blank password field + Save Settings = no change to auth (do nothing)
- Password field with content + Save = set/change password (unchanged)
- 'Disable Auth' button = explicit confirmation-gated clear (new)

UI changes:
- index.html: updated description text to 'Leave blank to keep current
  setting'; added 'Disable Auth' button (amber, shown only when auth active)
- panels.js: saveSettings() skips password logic entirely when field is blank;
  loadSettingsPanel() shows/hides both btnDisableAuth and btnSignOut based on
  auth_enabled; new disableAuth() function sends _clear_password:true after
  confirm() prompt and hides both auth buttons on success

Server: no logic changes needed; _clear_password handling in save_settings()
is now only triggered by the explicit Disable Auth action.
2026-04-03 06:21:04 -07:00
Nathan Esquenazi
d88419ccfb fix(auth): redirect to /login when auth is enabled and accessing root
'/' and '/index.html' were in PUBLIC_PATHS, so setting a password
and refreshing the root URL would show the app blank (JS loaded
but all API calls returned 401) instead of redirecting to /login.

Root and index.html must be protected paths so the browser gets a
302 -> /login when auth is active and no valid session cookie exists.
2026-04-03 06:21:04 -07:00
Nathan Esquenazi
3c95502979 fix(auth): harden password_hash handling in settings API
Three security issues found during review:

1. password_hash exposed via GET /api/settings
   load_settings() returned all fields including the stored hash.
   Fix: strip password_hash from the response in routes.py.

2. password_hash directly settable via POST /api/settings
   'password_hash' was in _SETTINGS_ALLOWED_KEYS, so an attacker
   could POST {password_hash: 'X'} to hijack auth without knowing
   the current password.
   Fix: exclude password_hash from _SETTINGS_ALLOWED_KEYS.
   (Use _set_password for the legitimate hash-and-store path.)

3. Security headers missing from /api/auth/login and /api/auth/logout
   These endpoints built their responses manually (bypassing j()),
   so they omitted X-Content-Type-Options etc.
   Fix: call _security_headers() before end_headers() on both.

Tests updated: renamed test to assert key absent (not just None),
added new test verifying direct password_hash POST is blocked.
2026-04-03 06:21:04 -07:00
Nathan Esquenazi
66bd84accb docs: comprehensive update of all markdown files for v0.21
ARCHITECTURE.md:
- 6→7 JS modules (added commands.js), updated all line counts
- Added api/auth.py to file inventory
- Added HERMES_WEBUI_PASSWORD env var
- Added projects.json to state directory listing
- Replaced PORTABILITY.md ref with BUGS.md
- Updated test file references (test_sprint1-19, 327 functions)

ROADMAP.md:
- Version Sprint 17/v0.19 → Sprint 19/v0.21, test count 294→327
- Added Sprint 18 + 19 rows to sprint history table
- Updated architecture table (api/ 2491 lines, JS 3148 lines)
- Added sections: Workspace, Slash Commands, Security, Thinking
- Added Sprint 20-24 to Advanced/Future (voice, mobile, multi-profile,
  desktop, extended commands)

SPRINTS.md:
- Header v0.20→v0.21, 318→327 tests
- "Where we are now" updated from v0.18 to v0.21
- Removed two stale/duplicate "Sprint 18" sections (Voice + Subagent)
- Added completed Sprint 18 (thinking + tree + preview fix)
- Added completed Sprint 19 (auth + security)
- Added planned Sprints 20-24 (voice, mobile, multi-profile, desktop, commands)
- Parity tables fully updated with current Done/Deferred status

CHANGELOG.md:
- Added v0.21 Sprint 19 entry (auth, security headers, 20MB limit)

TESTING.md:
- Header "through Sprint 2" → "through Sprint 19 (v0.21)"
- Added test count and pytest command to header
- Added 9 new manual test sections covering Sprints 11-19
- Updated footer with current stats

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 06:06:00 -07:00
Nathan Esquenazi
b8b62722ec feat: Sprint 19 — password auth, security headers, login page
Auth system (off by default, zero friction for localhost):
- New api/auth.py module: password hashing (SHA-256 + STATE_DIR salt),
  signed HMAC session cookies (24h TTL), auth middleware
- Enable via HERMES_WEBUI_PASSWORD env var or Settings panel
- Minimal dark-themed login page at /login (self-contained HTML)
- POST /api/auth/login, /api/auth/logout, GET /api/auth/status
- Settings panel: "Access Password" field + "Sign Out" button
- password_hash added to settings.json (null = auth disabled)

Security hardening:
- Security headers on all responses: X-Content-Type-Options: nosniff,
  X-Frame-Options: DENY, Referrer-Policy: same-origin
- POST body size limit: 20MB cap in read_body() to prevent DoS

Closes #23. 9 new tests. Total: 304 passed, 0 regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 05:53:26 -07:00
37 changed files with 5329 additions and 419 deletions

7
.dockerignore Normal file
View File

@@ -0,0 +1,7 @@
.git
.pytest_cache
__pycache__
*.pyc
*.pyo
tests/
.env*

56
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,56 @@
name: Release & Docker
on:
push:
tags:
- 'v*'
jobs:
release:
runs-on: ubuntu-latest
permissions:
contents: write # required: create GitHub Release
packages: write # required: push to ghcr.io
steps:
- uses: actions/checkout@v4
# Create GitHub Release from tag with auto-generated notes
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
generate_release_notes: true
# Set up multi-arch build (QEMU + Buildx)
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
# Log in to GitHub Container Registry
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
# Extract tags from the git ref (supports vX.Y and vX.Y.Z formats)
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=match,pattern=v(\d+\.\d+(?:\.\d+)?),group=1
type=raw,value=latest
# Build and push multi-arch image (amd64 + arm64)
- name: Build and push Docker image
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@@ -18,7 +18,7 @@ a central chat area, and a right panel for workspace file browsing.
The design philosophy is deliberately minimal. There is no build step, no bundler, no
frontend framework. The Python server is split into a routing shell (server.py) and
business logic modules (api/). The frontend is six vanilla JS modules loaded from static/.
business logic modules (api/). The frontend is seven vanilla JS modules loaded from static/.
This makes the code easy to modify from a terminal or by an agent.
---
@@ -26,38 +26,44 @@ This makes the code easy to modify from a terminal or by an agent.
## 2. File Inventory
<repo>/
server.py Thin routing shell + HTTP Handler. ~76 lines. Pure Python.
server.py Thin routing shell + HTTP Handler + auth middleware. ~81 lines.
Delegates all route handling to api/routes.py.
start.sh Discovery script: finds agent dir, Python, starts server.
Dockerfile python:3.12-slim container image (~23 lines)
docker-compose.yml Compose config with named volume and optional auth (~22 lines)
.dockerignore Excludes .git, tests/, .env* from Docker builds
api/
__init__.py Package marker
routes.py All GET + POST route handlers (~1016 lines)
config.py Shared configuration, constants, global state, model discovery (~640 lines)
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve() (~57 lines)
models.py Session model + CRUD (~132 lines)
auth.py Optional password authentication, signed cookies (~149 lines)
config.py Discovery, globals, model detection, reloadable config (~701 lines)
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve(), security headers (~71 lines)
models.py Session model + CRUD, per-session profile tracking (~137 lines)
profiles.py Profile state management, hermes_cli wrapper (~246 lines)
routes.py All GET + POST route handlers (~1180 lines)
streaming.py SSE engine, run_agent, cancel, HERMES_HOME save/restore (~236 lines)
upload.py Multipart parser, file upload handler (~78 lines)
workspace.py File ops: list_dir, read_file_content, workspace helpers (~77 lines)
upload.py Multipart parser, file upload handler (~77 lines)
streaming.py SSE engine, run_agent integration, cancel support (~222 lines)
static/
index.html HTML template (served from disk)
style.css All CSS
ui.js DOM helpers, renderMd, tool cards, model dropdown (~846 lines)
workspace.js File tree, preview, file ops (~169 lines)
sessions.js Session CRUD, list rendering, search, SVG icons, overlay actions (~532 lines)
messages.js send(), SSE event handlers, approval, transcript (~293 lines)
panels.js Cron, skills, memory, workspace, todo, switchPanel (~771 lines)
boot.js Event wiring + boot IIFE (~175 lines)
index.html HTML template (~364 lines)
style.css All CSS incl. mobile responsive (~670 lines)
ui.js DOM helpers, renderMd, tool cards, model dropdown, file tree (~977 lines)
workspace.js File preview, file ops, loadDir, clearPreview (~185 lines)
sessions.js Session CRUD, list rendering, search, SVG icons, overlay actions (~533 lines)
messages.js send(), SSE event handlers, approval, transcript (~297 lines)
panels.js Cron, skills, memory, workspace, profiles, todo, settings (~974 lines)
commands.js Slash command registry, parser, autocomplete dropdown (~156 lines)
boot.js Event wiring, mobile nav, voice input, boot IIFE (~338 lines)
tests/
conftest.py Isolated test server (port 8788, separate HERMES_HOME) (~240 lines)
test_sprint1-16.py Feature tests per sprint (14 files, Sprints 1-11 + 16)
test_regressions.py Permanent regression gate
test_sprint{1-20b}.py Feature tests per sprint (21 files, 415 test functions)
test_regressions.py Permanent regression gate (23 tests)
AGENTS.md Instruction file for agents working in this directory.
ROADMAP.md Feature and product roadmap document.
SPRINTS.md Forward sprint plan with CLI + Claude parity targets.
ARCHITECTURE.md THIS FILE.
TESTING.md Manual browser test plan and automated coverage reference.
CHANGELOG.md Release notes per sprint.
PORTABILITY.md Portability design spec for download-and-run installs.
BUGS.md Bug backlog and fixed items tracker.
requirements.txt Python dependencies.
.env.example Sample environment variable overrides.
@@ -67,7 +73,8 @@ State directory (runtime data, separate from source):
sessions/ One JSON file per session: {session_id}.json
workspaces.json Registered workspaces list
last_workspace.txt Last-used workspace path
settings.json (future) User settings
settings.json User settings (default model, workspace, send key, password hash)
projects.json Session project groups (name, color, id)
Log file:
@@ -91,6 +98,8 @@ Environment variables controlling behavior:
HERMES_WEBUI_STATE_DIR Where sessions/ folder lives
HERMES_CONFIG_PATH Path to ~/.hermes/config.yaml
HERMES_WEBUI_DEFAULT_MODEL Default LLM model string
HERMES_WEBUI_PASSWORD Optional: enable password auth (off by default)
HERMES_HOME Base directory for Hermes state (~/.hermes by default)
Test isolation environment variables (set by conftest.py):
@@ -109,6 +118,8 @@ Per-request environment variables (set by chat handler, restored after):
HERMES_EXEC_ASK Set to "1" to enable approval gate for dangerous commands.
HERMES_SESSION_KEY Set to session_id. The approval tool keys pending entries
by this value, enabling per-session approval state.
HERMES_HOME Set to the active profile's directory before running agent.
Saved and restored around each agent run.
WARNING: These env vars are process-global. Two concurrent chat requests will clobber
each other. This is safe only for single-user, single-concurrent-request use.

View File

@@ -5,6 +5,425 @@
---
## [v0.30.1] CLI Session Bridge Fixes
*April 4, 2026 | 424 tests*
### Bug Fixes
- **CLI sessions not appearing in sidebar.** Three frontend gaps: `sessions.js`
wasn't rendering CLI sessions (missing `is_cli_session` check in render loop),
sidebar click handler didn't trigger import, and the "cli" badge CSS selector
wasn't matching the rendered DOM structure. (#58)
- **CLI bridge read wrong profile's state.db.** `get_cli_sessions()` resolved
`HERMES_HOME` at server launch time, not at call time. After a profile switch,
it kept reading the original profile's database. Now resolves dynamically via
`get_active_hermes_home()`. (#59)
- **Silent SQL error swallowed all CLI sessions.** The `sessions` table in
`state.db` has no `profile` column — the query referenced `s.profile` which
caused a silent `OperationalError`. The `except Exception: return []` handler
swallowed it, returning zero CLI sessions. Removed the column reference and
added explicit column-existence checks. (#60)
### Features
- **"Show CLI sessions" toggle in Settings.** New checkbox in the Settings panel
to show/hide CLI sessions in the sidebar. Persisted server-side in
`settings.json` (`show_cli_sessions`, default `true`). When disabled, CLI
sessions are excluded from `/api/sessions` responses. (#61)
---
## [v0.30] CLI Session Bridge (Community: @thadreber-web)
*April 4, 2026 | 424 tests*
### Features
- **CLI session bridge.** The WebUI now reads sessions from the hermes-agent's
SQLite store (`state.db`). CLI sessions appear in the sidebar with a gold
"cli" indicator badge. Click to import into the WebUI store with full message
history — replies then work through the normal agent pipeline.
- **`/api/session/import_cli` endpoint.** Imports a CLI session into the WebUI
JSON store. Idempotent — returns existing session if already imported.
Derives title from first message, inherits active profile and workspace.
- **`/api/sessions` merges CLI sessions.** Sidebar shows both WebUI and CLI
sessions sorted by last activity. Deduplication ensures WebUI sessions take
priority when the same session_id exists in both stores.
- **CLI session fallback on `/api/session`.** If a session_id isn't found in
the WebUI store, falls back to reading from the CLI SQLite store.
### Architecture
- `api/models.py`: `get_cli_sessions()`, `get_cli_session_messages()`,
`import_cli_session()`. All use parameterized SQL queries and `with` for
connection management. Graceful fallback on missing sqlite3 or state.db.
- `api/routes.py`: CLI fallback in GET `/api/session`, merged list in
GET `/api/sessions`, POST `/api/session/import_cli`.
- `static/style.css`: `.cli-session` indicator styles (gold border + badge).
---
## [v0.29] Sprint 23: Agentic Transparency + Polish
*April 4, 2026 | 424 tests*
### Features
- **Token/cost display.** Agent usage (input tokens, output tokens, estimated
cost) is now read after each conversation and persisted on the session.
A muted badge appears below the last assistant message when enabled.
Off by default — toggle via the Settings panel checkbox or `/usage` slash
command. Persists server-side across refreshes.
- **Subagent delegation cards.** `subagent_progress` events now render with
a 🔀 icon and a blue indented left border to visually distinguish child
tool activity from parent tool calls. `delegate_task` cards display as
"Delegate task" with cleaner formatting.
- **Skill picker in cron create form.** The "New Job" form now has a search
input + tag chip picker for attaching skills to cron jobs. Skills fetched
from `/api/skills`, filtered on keyup, added/removed as tag chips.
`submitCronCreate()` sends `skills` array in the POST body. Backend already
supported the field — this was a pure frontend gap.
- **Skill linked files viewer.** Skill preview panel now renders a "Linked
Files" section below SKILL.md content when a skill has `references/`,
`templates/`, `scripts/`, or `assets/` subdirectories. Clicking a file
loads it in the preview panel with syntax highlighting.
New `file` query param on `GET /api/skills/content` serves linked files
with path traversal protection.
- **Workspace tree state persists across refreshes.** Expanded directory
paths are saved to `localStorage` keyed by workspace path
(`hermes-webui-expanded:{path}`). On every root load (page refresh,
session switch), the saved state is restored and previously-expanded
directories are pre-fetched so the tree renders fully on first paint.
- **Timestamps fixed.** `api/streaming.py` now stamps `timestamp` on every
message that lacks one at conversation completion. The `done` SSE event
also stamps `_ts` on the last assistant message immediately. Timestamps
were already rendered in the UI (Sprint 14, hover-to-reveal) but most
messages had no timestamp field, so nothing ever showed.
- **`/usage` slash command.** Instant toggle for token usage display.
Shows a toast, persists to server, updates the Settings checkbox if open,
re-renders immediately.
### Bug Fixes
- **XSS via inline onclick + esc().** Skill names and file paths embedded in
`onclick` HTML attributes used `esc()` for encoding. `esc()` converts `'`
to `&#39;` (HTML-safe) but browsers decode it back before executing JS,
allowing skill names with apostrophes to break out of string literals.
Fixed by switching to `data-*` attributes + `addEventListener`.
- **rglob wildcard injection.** The `name` query param for
`/api/skills/content?file=` was passed directly to `SKILLS_DIR.rglob()`,
which accepts glob patterns. `name=*` would match an arbitrary directory
and use it as the trust base for path traversal checking.
Fixed by rejecting names containing `* ? [ ]` metacharacters with 400.
- **`_fmtTokens(null)` returned "null".** `String(null)` = `"null"` would
appear in the usage badge for sessions missing fields. Fixed with a
`!n || n < 0` guard returning `'0'`.
- **Usage badge on wrong row.** Badge used `:last-child` which could target
a user message row. Fixed by adding `data-role` to message rows and
scanning backwards for the last `assistant` row.
- **Tool name resolution.** Tool call entries in session JSON sometimes
stored the literal string `"tool"` as the name when the call ID couldn't
be resolved. Fixed: defaults to empty string and skips unresolvable entries.
- **Inline import inside loop.** `import json as _j2` inside the done-handler
loop in `streaming.py` moved to module-level.
### Session Model
- Added `input_tokens`, `output_tokens`, `estimated_cost` fields to Session
(defaults: 0, 0, None). Included in `compact()`, session JSON, and all
API responses. Backward-compatible via `**kwargs`.
- Added `args` capture to `tool_calls` session JSON entries (truncated
snapshot of tool inputs, up to 6 keys / 120 chars each).
### Settings
- New `show_token_usage` boolean setting (default: `false`). Stored in
`settings.json`, loaded on boot alongside `send_key`.
### Tests
- Renamed `test_sprint24.py``test_sprint23.py`.
- Strengthened session usage assertions (explicit field presence checks).
- Added: path traversal rejection test, wildcard name rejection test,
cron create with skills array test.
- Total: 424 tests (up from 415).
---
## [v0.28.1] CI Pipeline + Multi-Arch Docker Builds
*April 3, 2026 | 426 tests*
### Features
- **GitHub Actions CI.** New workflow triggers on tag push (`v*`). Builds
multi-arch Docker images (linux/amd64 + linux/arm64), pushes to
`ghcr.io/nesquena/hermes-webui`, and creates a GitHub Release with
auto-generated release notes. Uses GHA layer caching for fast rebuilds.
- **Pre-built container images.** Users can now `docker pull ghcr.io/nesquena/hermes-webui:latest`
instead of building locally.
---
## [v0.27] Profile Creation Fallback for Docker (Issue #44)
*April 3, 2026 | 426 tests*
### Bug Fixes
- **Profile creation works without hermes-agent.** In Docker containers where
`hermes_cli` is not importable, profile creation now falls back to a local
implementation that creates the directory structure and optionally clones
config files. Previously returned `RuntimeError` with "hermes-agent required".
- **Name validation uses `fullmatch()`.** Prevents trailing-newline bypass of
the `$` anchor in `re.match()`. Not reachable from the web UI (name is
stripped), but fixed for defense-in-depth.
- **`clone_from` validated in `create_profile_api()`.** Defense-in-depth:
prevents path traversal if called by a non-HTTP client.
- **Fallback return uses full 9-key schema.** Previously returned only 2 keys
(`name`, `path`), inconsistent with the normal response shape.
- **Atomic directory creation.** `mkdir(exist_ok=False)` prevents TOCTOU race
on concurrent profile creates.
### Architecture
- `api/profiles.py`: `_validate_profile_name()`, `_create_profile_fallback()`,
`_PROFILE_ID_RE`, `_PROFILE_DIRS`, `_CLONE_CONFIG_FILES` constants matching
upstream `hermes_cli.profiles`.
- `docker-compose.yml`: Removed `:ro` from `~/.hermes` mount (required for
profile writes). Localhost-only binding preserved.
---
## [v0.26] Profile System Polish -- 10 Post-Sprint-23 Fixes
*April 3, 2026 | 426 tests*
### Bug Fixes
- **Profile switch base dir bug.** When `HERMES_HOME` was mutated to a
`profiles/` subdir at startup, `switch_profile()` doubled the path
(e.g. `~/.hermes/profiles/X/profiles/X`). New `_resolve_base_hermes_home()`
detects profile subdirs and walks up to the actual base.
- **Cross-provider model routing.** Picking a model from a different provider
than the config's default now routes through OpenRouter instead of trying
a direct API call to a provider whose key may not exist.
- **Legacy sessions missing profile tag.** `all_sessions()` now backfills
`profile='default'` for pre-Sprint-22 sessions so the profile filter works.
- **Workspace list cleanup.** Stale paths, test artifacts, and cross-profile
entries are now cleaned on load. Legacy global workspace file migrated
once for the default profile.
- **API error messages.** `api()` helper now parses JSON error bodies and
surfaces the human-readable message instead of raw JSON.
- **Workspace dropdown moved to sidebar.** The workspace picker now opens
upward from the sidebar bottom instead of clipping behind the topbar.
### Features
- **Rate limit error display.** Rate limit errors (429) now show a distinct
card with a rate limit icon and hint, instead of the generic error message.
- **SSE `apperror`/`warning` events.** Server can send typed error events
that the frontend handles with appropriate UX (rate limit card, fallback
notice, etc.).
- **Smart model resolver.** `_findModelInDropdown()` handles name mismatches
between config model IDs and dropdown values (e.g. `claude-sonnet-4-6` vs
`anthropic/claude-sonnet-4.6`).
- **Profile switch starts new session.** When the current session has messages,
switching profiles automatically starts a fresh session to prevent
cross-profile tagging.
- **Per-profile toolsets.** Agent now reads `platform_toolsets.cli` from the
active profile's config at call time, not the boot-time snapshot.
- **Per-profile fallback model.** `fallback_model` config is read from the
active profile and passed to AIAgent.
### Architecture
- `api/profiles.py`: `_resolve_base_hermes_home()` replaces naive env var read.
- `api/workspace.py`: `_clean_workspace_list()`, `_migrate_global_workspaces()`.
- `api/streaming.py`: Per-profile toolsets and fallback model at call time.
- `api/models.py`: `all_sessions()` backfills `profile='default'`.
- `static/ui.js`: `_findModelInDropdown()`, `_applyModelToDropdown()`.
- `static/messages.js`: `apperror` and `warning` SSE event handlers.
---
## [v0.25] Sprint 23 -- Profile/Workspace/Model Coherence
*April 3, 2026 | 423 tests*
### Features
- **Profile-local workspace storage.** Each named profile now stores its own
`workspaces.json` and `last_workspace.txt` under `{profile_home}/webui_state/`.
Default profile continues using the global STATE_DIR for backward compat.
- **Profile switch returns defaults.** `POST /api/profile/switch` response now
includes `default_model` and `default_workspace` from the new profile's
config.yaml, enabling one-round-trip state sync.
- **Session profile filter.** Session sidebar filters to the active profile by
default. "Show N from other profiles" toggle reveals sessions from all
profiles, modeled on the existing archived toggle. Resets on profile switch.
### Bug Fixes
- **Model picker ignores profile on switch.** `switchToProfile()` now clears
the `hermes-webui-model` localStorage key so the profile's default model
applies instead of a stale preference from another profile.
- **Workspace list was global.** Switching profiles no longer shows the wrong
profile's workspaces.
- **`DEFAULT_WORKSPACE` was a boot-time singleton.** Now resolved dynamically
through `_profile_default_workspace()`.
- **Session list showed all profiles.** Now filtered to active profile.
- **`switchToProfile()` didn't refresh workspaces or sessions.** Now refreshes
workspace list, session list, and resets profile filter on switch.
### Architecture
- `api/workspace.py` rewritten with profile-aware path resolution.
- `api/profiles.py`: `switch_profile()` returns `default_model` and
`default_workspace`.
- `static/sessions.js`: Profile filter with toggle UI.
- `static/panels.js`: Full cascade refresh on profile switch.
- 8 new tests in `test_sprint23.py`.
---
## [v0.24] Sprint 22 -- Multi-Profile Support (Issue #28)
*April 3, 2026 | 415 tests*
### Features
- **Profile picker (topbar).** Purple-accented chip with SVG user icon. Click
to open dropdown listing all profiles with gateway status dots (green =
running), model info, and skill count. Click any profile to switch; "Manage
profiles" link opens the sidebar panel.
- **Profiles management panel.** New sidebar tab with full CRUD UI. Profile
cards show name, model/provider, skill count, API key status, and gateway
status badge. "Use" button switches profile, delete button removes non-default
profiles (with confirmation).
- **Profile creation.** "+ New profile" form with name validation (`[a-z0-9_-]`),
optional "clone config from active" checkbox. Wraps the CLI's
`hermes_cli.profiles.create_profile()`.
- **Profile deletion.** Confirm dialog. Auto-switches to default if deleting
the active profile. Blocked while agent is running.
- **Seamless profile switching.** No server restart. Profile switch updates
`HERMES_HOME`, patches module-level caches in hermes-agent's `skills_tool`
and `cron/jobs`, reloads `.env` API keys and `config.yaml`, refreshes the
model dropdown, skills, memory, and cron panels.
- **Per-session profile tracking.** `profile` field on Session records which
profile was active at creation. Backward-compatible (`null` for old sessions).
### Bug Fixes
- **Hardcoded `~/.hermes` paths.** Memory read/write and model discovery used
hardcoded paths. Now resolved through `get_active_hermes_home()`.
- **Module-level path caching.** hermes-agent modules snapshot `HERMES_HOME`
at import time. Profile switch now monkey-patches `SKILLS_DIR`, `CRON_DIR`,
`JOBS_FILE`, `OUTPUT_DIR` so they track the active profile.
### Architecture
- New `api/profiles.py`: profile state management wrapping `hermes_cli.profiles`.
Thread-safe (`_profile_lock`). Lazy imports avoid circular deps.
- `api/config.py`: module-level `cfg` replaced with reloadable `get_config()`
/ `reload_config()`. Dynamic `_get_config_path()` resolves through profile.
- `api/streaming.py`: `HERMES_HOME` added to env save/restore block.
- Profile switch blocked while agent streams are active.
- 5 new API endpoints: `GET /api/profiles`, `GET /api/profile/active`,
`POST /api/profile/switch`, `POST /api/profile/create`,
`POST /api/profile/delete`.
- Zero modifications to hermes-agent code.
---
## [v0.23] Sprint 21 -- Mobile Responsive + Docker
*April 3, 2026 | 415 tests*
### Features
- **Mobile responsive layout (Issue #21).** Full mobile experience with
hamburger sidebar (slide-in overlay), bottom navigation bar (5-tab iOS
pattern), and files slide-over panel. Touch targets minimum 44px. Composer
positioned above bottom nav. Session clicks auto-close sidebar. Desktop
layout completely unchanged — all mobile elements hidden via `@media`.
- **Docker support (Issue #7).** Dockerfile (`python:3.12-slim`), docker-compose.yml
with named volume for state persistence, optional `~/.hermes` mount for
agent features. Binds to `127.0.0.1` by default for security.
### Bug Fixes (from review)
- **CSS cascade broke mobile slide-in.** `position:relative` rules after the
media query overrode `position:fixed` on mobile. Wrapped in `@media(min-width:641px)`.
- **mobileSwitchPanel() always reopened sidebar.** Chat tab now closes sidebar
instead of reopening it over the main chat area.
- **Dockerfile missing pip install.** Added `pip install -r requirements.txt`.
- **No .dockerignore.** Added exclusions for `.git`, `tests/`, `.env*`.
- **docker-compose tilde expansion.** Changed `~/.hermes` default to
`${HOME}/.hermes` (Docker Compose doesn't shell-expand `~`).
### Architecture
- Mobile navigation functions in `boot.js`: `toggleMobileSidebar()`,
`closeMobileSidebar()`, `toggleMobileFiles()`, `mobileSwitchPanel()`.
- `sessions.js`: `closeMobileSidebar()` called after session click.
- 69 new CSS lines in `@media(max-width:640px)` block.
- New files: `Dockerfile`, `docker-compose.yml`, `.dockerignore`.
---
## [v0.22] Sprint 20 -- Voice Input + Send Button Polish
*April 3, 2026 | 415 tests*
### Features
- **Voice input via Web Speech API.** Microphone button in the composer.
Tap to start recording, tap again (or send) to stop. Live interim
transcription appears in the textarea. Auto-stops after ~2s of silence.
Final text stays editable before sending. Appends to existing textarea
content rather than replacing it. Button hidden when browser doesn't
support Web Speech API. No API keys, no external libraries, no server
changes. Works in Chrome, Edge, Safari (partial). Firefox unsupported
(button stays hidden).
- **Send button polish.** Send button redesigned as a 34px icon-only circle
with upward arrow SVG. Hidden by default — appears with pop-in spring
animation when textarea has content or files are attached. Disappears
on send or when content is cleared. Hidden while agent is responding.
Blue fill (#7cb9ff) with glow, scale hover/active for tactile feedback.
### Architecture
- Voice input IIFE in `boot.js`: SpeechRecognition lifecycle with
`continuous=false`, `interimResults=true`, error handling via `showToast()`.
- `_prefix` variable snapshots existing textarea content on recording start
so dictation appends rather than overwrites.
- `btnSend.onclick` stops active recognition before sending (send guard).
- CSS: `.mic-btn`, `.mic-btn.recording` (red pulse), `.mic-status`,
`.mic-dot`, `@keyframes mic-pulse`.
- `updateSendBtn()` in `ui.js` tracks textarea content, pending files,
and busy state. Hooked into `setBusy()`, `renderTray()`, `autoResize()`,
and input event listener.
- CSS: `.send-btn` redesigned (circle, glow), `.send-btn.visible` +
`@keyframes send-pop-in` (spring animation).
### Tests
- 52 new tests in `test_sprint20.py`: voice input HTML, CSS, JS, append
behaviour, error handling, regressions.
- 33 new tests in `test_sprint20b.py`: send button HTML, CSS, JS,
animation, visibility logic, regressions. Total: **415 tests**.
---
## [v0.21] Sprint 19 -- Auth + Security Hardening
*April 3, 2026 | 328 tests*
### Features
- **Password authentication (Issue #23).** Optional password auth, off by default.
Enable via `HERMES_WEBUI_PASSWORD` env var or Settings panel. Password-only
(single-user app). Signed HMAC HTTP-only cookie with 24h TTL. Minimal dark-themed
login page at `/login`. API calls without auth return 401; page loads redirect.
New `api/auth.py` module with hashing, verification, session management.
- **Security headers.** All responses now include `X-Content-Type-Options: nosniff`,
`X-Frame-Options: DENY`, `Referrer-Policy: same-origin`.
- **POST body size limit.** Non-upload POST bodies capped at 20MB via `read_body()`.
- **Settings panel additions.** "Access Password" field and "Sign Out" button
(only visible when auth is active).
### Architecture
- New `api/auth.py`: password hashing (SHA-256 + STATE_DIR salt), signed cookies,
auth middleware, public path allowlist.
- Auth check in `server.py` do_GET/do_POST before routing.
- `password_hash` added to `_SETTINGS_DEFAULTS`.
### Tests
- 10 new tests in `test_sprint19.py`: auth status, login flow, security headers,
cache-control, settings password field, request size limit. Total: **328 tests (328 passing)**.
---
## [v0.20] Sprint 18 -- File Preview Auto-Close + Thinking Display + Workspace Tree
*April 3, 2026 | 318 tests*
@@ -649,4 +1068,4 @@ Three-panel layout: sessions sidebar, chat area, workspace panel.
---
*Last updated: v0.20, April 3, 2026 | Tests: 318*
*Last updated: v0.30.1, April 4, 2026 | Tests: 424*

23
Dockerfile Normal file
View File

@@ -0,0 +1,23 @@
FROM python:3.12-slim
LABEL maintainer="nesquena"
LABEL description="Hermes Web UI — browser interface for Hermes Agent"
WORKDIR /app
# Copy source
COPY . /app
# Install Python dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Default to binding all interfaces (required for container networking)
ENV HERMES_WEBUI_HOST=0.0.0.0
ENV HERMES_WEBUI_PORT=8787
# State directory (mount as volume for persistence)
ENV HERMES_WEBUI_STATE_DIR=/data
EXPOSE 8787
CMD ["python", "server.py"]

375
HERMES.md Normal file
View File

@@ -0,0 +1,375 @@
# Why Hermes
Hermes is a persistent, autonomous AI agent that lives on your server. It remembers everything,
schedules work while you sleep, and gets more capable the longer it runs. This document explains
the mental model, why that matters, and how Hermes compares to every major AI tool available today.
---
## The Core Idea: Assistants Forget. Agents Don't.
Every time you open Claude Code, Codex, or a chat window, the tool starts from zero. It does not
know who you are, what you worked on yesterday, how your repo is structured, or what bugs you
already fixed. You re-explain yourself every single session. The tool is powerful in the moment
and useless the next day.
Hermes fills that gap. It runs on your server, retains context across every session, and acts
on your behalf whether or not you are at a keyboard.
```
Assistant model: You -> [Tool] -> Answer -> Done
(tool forgets everything when the window closes)
Agent model: You <-> [Hermes] <-> (memory, skills, schedule, tools)
(persistent, learns your stack, acts on your behalf, runs while you're offline)
```
---
## The Three Pillars
### 1. Memory That Compounds
Hermes has layered memory that survives every session, every reboot, every model swap:
- **User profile** -- who you are, your preferences, your communication style, things you've
corrected Hermes on
- **Agent memory** -- facts about your environment, your toolchain, your project conventions
- **Skills** -- reusable procedures Hermes discovers and saves; it never has to relearn how to
deploy your app, run your tests, or review a PR
- **Session history** -- every past conversation is searchable; Hermes can recall what you
worked on last Tuesday
When you correct Hermes, it remembers. When it solves a tricky problem, it saves the approach.
When it learns your stack, that knowledge carries into every future session.
### 2. Autonomous Scheduling
Hermes can run jobs without you present -- every hour, every morning, on any cron schedule.
It fires up a fresh session, runs the task, and delivers the result to wherever you want it:
Telegram, Discord, Slack, Signal, WhatsApp, SMS, email, and more.
Things Hermes can do while you sleep:
- Review new pull requests on your GitHub repo and post a full verdict comment
- Send you a morning briefing of news, markets, or anything else you care about
- Run your test suite and alert you if something breaks
- Watch a competitor's blog for new posts and summarize them
- Monitor a datasource and notify you when a threshold is crossed
### 3. Reach It From Anywhere
Hermes runs on your server and is reachable from every surface: terminal over SSH, the web UI
(this project), and messaging apps including Telegram, Discord, Slack, WhatsApp, Signal, and
Matrix. Start a task from your phone, check it from the browser on your laptop, continue it in
a terminal on a remote server. The same agent, memory, and history follow you everywhere.
---
## A Framework for AI Tools
There are four distinct categories of AI tool. Understanding the category tells you what a tool
can and cannot do.
### Category 1: Chat Assistants
*Claude.ai, ChatGPT, Gemini*
You open a window, ask something, get an answer. No persistent memory beyond the conversation,
no ability to run code or touch files, no way to act on your behalf. Excellent for Q&A,
drafting, and brainstorming. You re-explain your context every session.
### Category 2: IDE Integrations
*GitHub Copilot, Cursor, Windsurf, Zed AI*
Deep inside your editor. Autocomplete, inline diffs, refactors -- all excellent. Windsurf was
earliest with workspace-scoped memory (Cascade Memories); Copilot has been shipping repo-level
memory since late 2025 and is catching up. Cursor has no native memory as of early 2026. None
have scheduling or messaging access. Tied to one machine and one editor.
### Category 3: Agentic CLI Tools
*Claude Code, Codex CLI, OpenCode, Aider*
The current frontier for most developers. Can use real tools -- run shell commands, read and
write files, search the web, call APIs. Great for deep, multi-step tasks in a single terminal
session. All are adding memory and scheduling features to varying degrees (see comparisons below),
but the core model is still session-scoped: you invoke it, it works, it stops.
### Category 4: Persistent Autonomous Agents
*Hermes, OpenClaw (as of early 2026)*
All the tool use of Category 3, plus memory that accumulates across sessions, plus always-on
scheduling, plus multi-modal access from any device or messaging app. Gets more useful over time
rather than resetting to zero. Hermes and OpenClaw are the two primary open-source, self-hosted
tools in this category. OpenClaw is a gateway-centric automation platform; Hermes is a
self-improving agent that writes and reuses its own procedures from experience.
---
## How Hermes Compares
### vs. OpenClaw
OpenClaw is the most direct comparison to Hermes and the question most people ask first.
Both are open-source, self-hosted, always-on agents with persistent memory, cron scheduling,
and messaging app integration. If you're evaluating Hermes, you should evaluate OpenClaw too.
OpenClaw (MIT, ~347k GitHub stars) is built around a **Gateway** control plane written in
Node.js/TypeScript. It excels at broad personal automation: native Chrome/Chromium control for
browser automation, the widest messaging platform support in the space (WhatsApp, Telegram,
Signal, iMessage, LINE, WeChat, Slack, Discord, Teams, Matrix, and more), voice wake words,
and a ClawHub skill marketplace where users share pre-built automations. The community is large
and the ecosystem is growing fast.
Hermes takes a different approach. It is built in Python and centers on a **self-improving
agent loop** rather than a gateway control plane. The core difference is in how skills work:
OpenClaw skills are primarily human-authored plugins installed from a marketplace; Hermes
**writes and saves its own skills automatically** as part of every session. When Hermes solves
a problem a new way, it saves the procedure and reuses it going forward without any user effort.
Beyond the skills architecture, there are two other practical differences worth knowing:
**Stability.** OpenClaw's community forums and GitHub issues document a recurring pattern of
update-breaking regressions -- for example, Telegram integration was broken across multiple
releases in early 2026. The unofficial WhatsApp Web protocol OpenClaw uses is known to
disconnect and requires periodic re-pairing (this is documented in OpenClaw's own FAQ).
Hermes has had no equivalent release breakages.
**Security.** ClawHub's open publishing model has been exploited repeatedly. A community audit
identified over a thousand malicious skills in the marketplace including prompt injections and
tool-poisoning payloads; the community-maintained awesome-openclaw-skills list tracks confirmed
removals and flags known bad actors. Hermes has no third-party marketplace and a correspondingly
smaller attack surface.
**OpenClaw's genuine strengths** are worth stating plainly: it has broader messaging coverage
(iMessage, LINE, WeChat, Teams -- platforms Hermes does not support), native browser and
computer control via Chrome CDP, voice wake words on macOS and iOS, a larger community, and
more third-party integrations than Hermes. If those capabilities matter most to you, OpenClaw
is worth a serious look.
Where Hermes is the better fit: you want an agent that self-improves from experience without
manual plugin authoring, you work in Python and want access to the ML/data science ecosystem,
you want a stable deployment that does not break between updates, or you want a full web chat
UI rather than a monitoring dashboard.
| | OpenClaw | Hermes |
|---|---|---|
| Persistent memory | Yes | Yes |
| Scheduled jobs (cron) | Yes | Yes |
| Messaging app access | Yes (15+ platforms, incl. iMessage/WeChat) | Yes (10+ platforms) |
| Web UI | Gateway dashboard (monitoring only) | Full three-panel chat UI |
| Self-hosted | Yes | Yes |
| Open source | Yes (MIT) | Yes |
| Self-improving skills | Partial (AI can generate skills; not the default loop) | Yes (automatic, first-class) |
| Browser / computer control | Yes (native Chrome CDP) | Via shell / tools |
| Voice wake words | Yes (macOS/iOS) | No |
| Python / ML ecosystem | No (Node.js) | Yes |
| Orchestrates Claude Code / Codex | No | Yes |
| Multi-profile support | Via binding-rule routing | Yes (first-class named profiles) |
| Provider-agnostic | Yes | Yes |
| Update reliability | Moderate (documented regressions) | High |
### vs. Claude Code (Anthropic)
Claude Code is Anthropic's official agentic CLI and one of the best tools in Category 3.
In a single focused session it is capable -- deep code understanding, shell access, file
editing, multi-step reasoning.
Claude Code has been adding features rapidly and the gap is narrowing:
- **Hooks system** -- 13 event types (SessionStart, PreToolUse, PostToolUse, Stop, etc.) with
4 handler types (shell command, HTTP endpoint, LLM prompt, sub-agent); deterministic
non-LLM control over the agent lifecycle
- **Plugins / Skills** -- installable via `/plugin install`, hot-reloaded from `~/.claude/skills`,
with a marketplace; skills and slash commands unified as of v2.1.0
- **Scheduling** -- `/loop` (session-scoped), cloud-managed cron via `claude.ai/code/scheduled`
(Anthropic infrastructure, minimum interval applies), and desktop app automations
- **Messaging channels** -- Telegram, Discord, iMessage, and webhooks via the Channels feature
(research preview, v2.1.80+); deep Slack integration that triggers cloud sessions and creates PRs
- **Claude Cowork** -- a separate product for knowledge workers; connects to 38+
services via MCP including Slack, Gmail, Microsoft Teams, Notion, Jira, Salesforce, and more
- **Memory** -- CLAUDE.md and MEMORY.md for project-level context; auto-memory rolling out
These are real features. The key differences that remain:
- Claude Code's scheduling runs on **Anthropic's cloud** (or requires the desktop app open),
not a self-hosted server; cloud jobs have a minimum interval and your data leaves your hardware
- Memory is **project-file-based** (CLAUDE.md / MEMORY.md), not a knowledge graph that
accumulates automatically across all your work; auto-memory is still rolling out
- **Not provider-agnostic** -- routes through Bedrock or Vertex but always hits a Claude model;
you cannot switch to GPT, Gemini, or a local model
- **Not open source** -- proprietary; the CLI ships obfuscated JavaScript
- Messaging channels are a **research preview** requiring Bun runtime; not yet production-grade
Hermes can use Claude Code as a sub-agent. For large implementation tasks, Hermes can spawn
Claude Code to handle the heavy lifting and fold the result back into its own memory and history.
| | Claude Code | Hermes |
|---|---|---|
| Persistent memory (automatic) | Partial (CLAUDE.md / MEMORY.md, rolling out) | Yes |
| Skills / hooks system | Yes (Hooks + Plugin/Skills marketplace) | Yes (auto-generated from experience) |
| Scheduled jobs (self-hosted) | No (cloud or desktop-app only) | Yes |
| Messaging access | Partial (Telegram/Discord/iMessage via research preview; Slack native) | Yes (10+ platforms, production) |
| Cowork connectors (Slack, Gmail, etc.) | Yes (via Claude Cowork, separate product) | Via agent tool use |
| Web UI | Yes (claude.ai/code, Anthropic-hosted) | Yes (self-hosted) |
| Provider-agnostic | No (Claude models only, via Bedrock/Vertex) | Yes (any provider) |
| Self-hosted scheduling | No | Yes |
| Open source | No | Yes |
| Runs as sub-agent of Hermes | Yes | N/A |
### vs. Codex CLI (OpenAI)
Codex CLI is OpenAI's open-source agentic terminal tool (Apache 2.0, ~73k GitHub stars). It
supports 10+ providers including Anthropic, Google, Mistral, Groq, and local models via Ollama.
It added persistent session memory in v0.100.0 with `codex resume`. The desktop app has an
Automations feature for scheduled local tasks.
The CLI itself has no native scheduling (open feature request as of early 2026). Memory is
session-history-based rather than a living knowledge graph. No messaging app access. A strong
tool for single-session coding; Hermes adds the always-on layer on top.
| | Codex CLI | Hermes |
|---|---|---|
| Persistent memory | Partial (session history + AGENTS.md) | Yes (automatic, layered) |
| Scheduled jobs | Partial (desktop app only; CLI has none) | Yes |
| Messaging app access | No | Yes |
| Web UI | No | Yes (self-hosted) |
| Provider-agnostic | Yes (10+ providers) | Yes (10+ providers) |
| Self-hosted | Yes | Yes |
| Open source | Yes (Apache 2.0) | Yes |
### vs. OpenCode
OpenCode is an open-source TUI agentic coding assistant, provider-agnostic across 75+ providers.
It has a WebUI embedded in its binary and an official desktop app. It uses SQLite for session
history and AGENTS.md for project context.
No native scheduled jobs (a community background plugin exists), no first-party messaging
integration (community Telegram bots exist but require manual setup), and no automatic
cross-session semantic memory. Good for interactive terminal coding sessions.
| | OpenCode | Hermes |
|---|---|---|
| Persistent memory | Partial (session history + AGENTS.md) | Yes (automatic, layered) |
| Scheduled jobs | No (community plugin only) | Yes |
| Messaging app access | No (community Telegram bot only) | Yes (first-party, 10+ platforms) |
| Web UI | Yes (embedded + desktop app) | Yes (self-hosted) |
| Mobile access | No | Yes |
| Skills system | No | Yes |
| Provider-agnostic | Yes (75+ providers) | Yes |
| Open source | Yes | Yes |
### vs. Cursor / Windsurf / Copilot
Category 2 tools -- exceptional at in-editor autocomplete, inline diffs, and code review.
Not competing for the same job as Hermes, and they work well alongside it.
Windsurf was earliest with workspace-scoped memory (Cascade Memories); Copilot has been
shipping repo-level memory since late 2025. Cursor has no native cross-session memory as of
early 2026. None have scheduling or messaging access.
| | Cursor | Windsurf | Copilot | Hermes |
|---|---|---|---|---|
| In-editor autocomplete | Excellent | Excellent | Excellent | No |
| Inline diff / refactor | Yes | Yes | Yes | Via shell |
| Cross-session memory | No | Yes (workspace) | Partial (repo, early access) | Yes |
| Scheduled background jobs | No | No | No | Yes |
| Messaging app / mobile | No | No | No | Yes |
| Terminal tool use | Limited | Limited | Limited | Full |
| Self-hosted | No | No | No | Yes |
| Provider-agnostic | Partial | Partial | No | Yes |
| Open source | No | No | No | Yes |
### vs. Claude.ai / ChatGPT
Category 1. For drafting, Q&A, and brainstorming in the moment, both are excellent.
Claude.ai memory has been improving -- it now generates memory from chat history, not just
user-curated entries. Claude.ai can also execute code and read/write files in a sandboxed
environment via Artifacts. These are real capabilities, just not the same as direct filesystem
or shell access on your own server.
| | Claude.ai / ChatGPT | Hermes |
|---|---|---|
| Memory across conversations | Yes (improving; auto-generated from history) | Yes (deep, automatic) |
| Runs shell commands | No | Yes |
| Code execution | Sandboxed (Artifacts) | Yes (full shell) |
| Reads / writes files | Sandboxed (Artifacts) | Yes (full filesystem) |
| Schedules background jobs | No | Yes |
| Web UI | Yes | Yes |
| Messaging apps | No | Yes |
| Self-hosted | No | Yes |
| Provider-agnostic | No | Yes |
| Open source | No | Yes |
---
## The Compounding Advantage
What matters most about Hermes is that it improves over time. That is the point.
Every time Hermes encounters a new environment, it saves facts to memory. Every time it solves
a problem a new way, it saves the approach as a skill. Every time you correct it, it updates its
profile of you. Every session, every scheduled job, every tool call, the agent gets more
calibrated to you and your workflow.
A Claude Code session on day one and day one hundred are identical. A Hermes agent on day one
and day one hundred is smarter about you -- it knows your stack, your conventions, your
preferences, and the solutions that have worked before.
---
## Who Hermes Is For
**Solo developers and power users** who don't want to re-explain their stack every session and
want an AI that actually knows their environment.
**Teams on a shared server** where multiple people want Claude-quality AI access without each
paying for a separate subscription or running local tooling.
**Automation-heavy workflows** where you want an AI running tasks on a schedule, delivering
results to your phone, without babysitting it.
**Privacy-conscious users** who want their conversations, memory, and files on their own
hardware.
**Multi-model users** who want to switch between OpenAI, Anthropic, Google, DeepSeek, and
others based on cost, capability, or rate limits, without rebuilding their workflow each time.
---
## Scope and Limits
**Hermes lives in the terminal, browser, and messaging apps.** For in-editor autocomplete and
inline diffs, use Cursor or Windsurf alongside it -- they do that job better.
**You run Hermes on your own server.** That means initial setup, but your data stays on your
hardware and you control the schedule, the models, and the costs.
**Hermes is an orchestration and memory layer.** It makes whatever model you point it at more
useful over time. The models do the reasoning; Hermes makes sure that reasoning accumulates into
something durable.
---
## Quick Reference
| | OpenClaw | Claude Code | Codex CLI | OpenCode | Cursor | Claude.ai | Hermes |
|---|---|---|---|---|---|---|---|
| Persistent memory (auto) | Yes | Partial† | Partial | Partial | No | Yes (improving) | **Yes** |
| Scheduled / background jobs | Yes | Partial‡ | Partial§ | No | No | No | **Yes (self-hosted)** |
| Messaging app access | Yes (15+ platforms) | Partial (Telegram/Discord preview; Slack native) | No | No | No | No | **Yes (10+ platforms)** |
| Web UI | Dashboard only | Yes (Anthropic cloud) | No | Yes | No | Yes | **Yes (self-hosted)** |
| Skills system | Yes (marketplace) | Yes (Hooks + Plugins) | No | No | No | No | **Yes** |
| Self-improving skills | Partial | No | No | No | No | No | **Yes** |
| Browser / computer control | Yes (Chrome CDP) | No | No | No | No | No | Via shell |
| Python / ML ecosystem | No (Node.js) | No | No | No | No | No | **Yes** |
| In-editor autocomplete | No | No | No | No | Yes | No | No |
| Orchestrates other agents | No | No | No | No | No | No | **Yes** |
| Provider-agnostic | Yes | No (Claude only) | Yes | Yes | Partial | No | **Yes** |
| Self-hosted | Yes | No | Yes | Yes | No | No | **Yes** |
| Open source | Yes (MIT) | No | Yes | Yes | No | No | **Yes** |
| Always-on / autonomous | Yes | No | No | No | No | No | **Yes** |
† Claude Code has CLAUDE.md / MEMORY.md project context and rolling auto-memory, but not full automatic cross-session recall
‡ Claude Code scheduling: cloud-managed (Anthropic infrastructure) or desktop-app only; no self-hosted cron
§ Codex scheduling: desktop app Automations only; CLI has no native scheduling

233
README.md
View File

@@ -10,9 +10,70 @@ and vanilla JS.
Layout: three-panel Claude-style. Left sidebar for sessions and tools,
center for chat, right for workspace file browsing.
<img width="1392" height="854" alt="image" src="https://github.com/user-attachments/assets/79cd3c0d-3167-42ed-9434-447a742c25c3" />
<img width="1392" alt="Hermes Web UI — three-panel layout" src="https://github.com/user-attachments/assets/79cd3c0d-3167-42ed-9434-447a742c25c3" />
This gives you nearly **1:1 parity with Hermes CLI from a convenient web UI** which you can access securely through an SSH tunnel from your Hermes setup. Single command to start this up, and a single command to SSH tunnel for access on your computer. Every single part of the web UI leverages your existing Hermes agent, existing models, without requiring any setup.
<table>
<tr>
<td width="50%" align="center">
<img alt="Workspace file browser with inline preview" src="docs/images/ui-workspace.png" />
<br /><sub>Workspace file browser with inline preview</sub>
</td>
<td width="50%" align="center">
<img alt="Session projects, tags, and tool call cards" src="docs/images/ui-sessions.png" />
<br /><sub>Session projects, tags, and tool call cards</sub>
</td>
</tr>
</table>
This gives you nearly **1:1 parity with Hermes CLI from a convenient web UI** which you can access securely through an SSH tunnel from your Hermes setup. Single command to start this up, and a single command to SSH tunnel for access on your computer. Every single part of the web UI uses your existing Hermes agent and existing models, without requiring any additional setup.
---
## Why Hermes
Most AI tools reset every session. They don't know who you are, what you worked on, or what
conventions your project follows. You re-explain yourself every time.
Hermes retains context across sessions, runs scheduled jobs while you're offline, and gets
smarter about your environment the longer it runs. It uses your existing Hermes agent setup,
your existing models, and requires no additional configuration to start.
What makes it different from other agentic tools:
- **Persistent memory** — user profile, agent notes, and a skills system that saves reusable
procedures; Hermes learns your environment and does not have to relearn it
- **Self-hosted scheduling** — cron jobs that fire while you're offline and deliver results to
Telegram, Discord, Slack, Signal, email, and more
- **10+ messaging platforms** — the same agent available in the terminal is reachable from your phone
- **Self-improving skills** — Hermes writes and saves its own skills automatically from experience;
no marketplace to browse, no plugins to install
- **Provider-agnostic** — OpenAI, Anthropic, Google, DeepSeek, OpenRouter, and more
- **Orchestrates other agents** — can spawn Claude Code or Codex for heavy coding tasks and bring
the results back into its own memory
- **Self-hosted** — your conversations, your memory, your hardware
**vs. the field** *(landscape is actively shifting — see [HERMES.md](HERMES.md) for the full breakdown)*:
| | OpenClaw | Claude Code | Codex CLI | OpenCode | Hermes |
|---|---|---|---|---|---|
| Persistent memory (auto) | Yes | Partial† | Partial | Partial | Yes |
| Scheduled jobs (self-hosted) | Yes | No‡ | No | No | Yes |
| Messaging app access | Yes (15+ platforms) | Partial (Telegram/Discord preview) | No | No | Yes (10+) |
| Web UI (self-hosted) | Dashboard only | No | No | Yes | Yes |
| Self-improving skills | Partial | No | No | No | Yes |
| Python / ML ecosystem | No (Node.js) | No | No | No | Yes |
| Provider-agnostic | Yes | No (Claude only) | Yes | Yes | Yes |
| Open source | Yes (MIT) | No | Yes | Yes | Yes |
† Claude Code has CLAUDE.md / MEMORY.md project context and rolling auto-memory, but not full automatic cross-session recall
‡ Claude Code has cloud-managed scheduling (Anthropic infrastructure) and session-scoped `/loop`; no self-hosted cron
**The closest competitor is OpenClaw** — both are always-on, self-hosted, open-source agents
with memory, cron, and messaging. The key differences: Hermes writes and saves its own skills
automatically as a core behavior (OpenClaw's skill system centers on a community marketplace);
Hermes is more stable across updates (OpenClaw has documented release regressions and ClawHub
has had security incidents involving malicious skills); and Hermes runs natively in the Python
ecosystem. See [HERMES.md](HERMES.md) for the full side-by-side.
---
@@ -35,6 +96,44 @@ That is it. The script will:
---
## Docker
**Pre-built images** (amd64 + arm64) are published to GHCR on every release:
```bash
docker pull ghcr.io/nesquena/hermes-webui:latest
docker run -d -p 8787:8787 -v ~/.hermes:/root/.hermes ghcr.io/nesquena/hermes-webui:latest
```
Or run with Docker Compose (recommended):
```bash
docker compose up -d
```
Or build locally:
```bash
docker build -t hermes-webui .
docker run -d -p 8787:8787 -v ~/.hermes:/root/.hermes hermes-webui
```
Open http://localhost:8787 in your browser.
To enable password protection:
```bash
docker run -d -p 8787:8787 -e HERMES_WEBUI_PASSWORD=your-secret -v ~/.hermes:/root/.hermes ghcr.io/nesquena/hermes-webui:latest
```
Session data persists in a named volume (`hermes-data`) across restarts.
> **Note:** By default, Docker Compose binds to `127.0.0.1` (localhost only).
> To expose on a network, change the port to `"8787:8787"` in `docker-compose.yml`
> and set `HERMES_WEBUI_PASSWORD` to enable authentication.
---
## What start.sh discovers automatically
| Thing | How it finds it |
@@ -75,7 +174,8 @@ Full list of environment variables:
| `HERMES_WEBUI_STATE_DIR` | `~/.hermes/webui-mvp` | Where sessions and state are stored |
| `HERMES_WEBUI_DEFAULT_WORKSPACE` | `~/workspace` | Default workspace |
| `HERMES_WEBUI_DEFAULT_MODEL` | `openai/gpt-5.4-mini` | Default model |
| `HERMES_HOME` | `~/.hermes` | Base directory for Hermes state (affects all paths above) |
| `HERMES_WEBUI_PASSWORD` | *(unset)* | Set to enable password authentication |
| `HERMES_HOME` | `~/.hermes` | Base directory for Hermes state (affects all paths) |
| `HERMES_CONFIG_PATH` | `~/.hermes/config.yaml` | Path to Hermes config file |
---
@@ -127,17 +227,18 @@ Tests discover the repo and the Hermes agent dynamically -- no hardcoded paths.
```bash
cd hermes-webui
python -m pytest tests/ -v
pytest tests/ -v --timeout=60
```
Or using the agent venv explicitly:
```bash
/path/to/hermes-agent/venv/bin/python -m pytest tests/ -v # or any Python with deps installed
/path/to/hermes-agent/venv/bin/python -m pytest tests/ -v
```
Tests run against an isolated server on port 8788 with a separate state directory.
Production data and real cron jobs are never touched.
Production data and real cron jobs are never touched. Current count: **424 tests**
across 22 test files.
---
@@ -145,88 +246,150 @@ Production data and real cron jobs are never touched.
### Chat and agent
- Streaming responses via SSE (tokens appear as they are generated)
- Multi-provider model support -- any Hermes API provider (OpenAI, Anthropic, Google, DeepSeek, Nous Portal, OpenRouter); dynamic model dropdown populated from configured keys
- Multi-provider model support -- any Hermes API provider (OpenAI, Anthropic, Google, DeepSeek, Nous Portal, OpenRouter, MiniMax, Z.AI); dynamic model dropdown populated from configured keys
- Send a message while one is processing -- it queues automatically
- Edit any past user message inline and regenerate from that point
- Retry the last assistant response with one click
- Cancel a running task from the activity bar
- Tool call cards inline -- each shows the tool name, args, and result snippet
- Tool call cards inline -- each shows the tool name, args, and result snippet; expand/collapse all toggle for multi-tool turns
- Subagent delegation cards -- child agent activity shown with distinct icon and indented border
- Mermaid diagram rendering inline (flowcharts, sequence diagrams, gantt charts)
- Thinking/reasoning display -- collapsible gold-themed cards for Claude extended thinking and o3 reasoning blocks
- Approval card for dangerous shell commands (allow once / session / always / deny)
- SSE auto-reconnect on network blips (SSH tunnel resilience)
- File attachments persist across page reloads
- Message timestamps (HH:MM next to each message, full date on hover)
- Code block copy button with "Copied!" feedback
- Syntax highlighting via Prism.js (Python, JS, bash, JSON, SQL, and more)
- Safe HTML rendering in AI responses (bold, italic, code converted to markdown)
### Sessions
- Create, rename, duplicate, delete, search by title and message content
- Pin/star sessions to the top of the sidebar
- Pin/star sessions to the top of the sidebar (gold indicator)
- Archive sessions (hide without deleting, toggle to show)
- Session projects -- named groups with colors for organizing sessions
- Session tags -- add #tag to titles for colored chips and click-to-filter
- Grouped by Today / Yesterday / Earlier in the sidebar
- Download as Markdown transcript, full JSON export, or import from JSON
- Sessions persist across page reloads and SSH tunnel reconnects
- Browser tab title reflects the active session name
- CLI session bridge -- CLI sessions from hermes-agent's SQLite store appear in the sidebar with a gold "cli" badge; click to import with full history and reply normally
- Token/cost display -- input tokens, output tokens, estimated cost shown per conversation (toggle in Settings or `/usage` command)
### Workspace file browser
- Browse directory tree with type icons
- Directory tree with expand/collapse (single-click toggles, double-click navigates)
- Breadcrumb navigation with clickable path segments
- Preview text, code, Markdown (rendered), and images inline
- Edit, create, delete, and rename files; create folders
- Binary file download (auto-detected from server)
- File preview auto-closes on directory navigation (with unsaved-edit guard)
- Right panel is drag-resizable
- Syntax highlighted code preview (Prism.js)
### Voice input
- Microphone button in the composer (Web Speech API)
- Tap to record, tap again or send to stop
- Live interim transcription appears in the textarea
- Auto-stops after ~2s of silence
- Appends to existing textarea content (doesn't replace)
- Hidden when browser doesn't support Web Speech API (Chrome, Edge, Safari)
### Profiles
- Profile picker in the topbar -- purple chip with dropdown showing all profiles
- Gateway status dots (green = running), model info, skill count per profile
- Profiles management panel -- create, switch, and delete profiles from the sidebar
- Clone config from active profile on create
- Seamless switching -- no server restart; reloads config, skills, memory, cron, models
- Per-session profile tracking (records which profile was active at creation)
### Authentication and security
- Optional password auth -- off by default, zero friction for localhost
- Enable via `HERMES_WEBUI_PASSWORD` env var or Settings panel
- Signed HMAC HTTP-only cookie with 24h TTL
- Minimal dark-themed login page at `/login`
- Security headers on all responses (X-Content-Type-Options, X-Frame-Options, Referrer-Policy)
- 20MB POST body size limit
- CDN resources pinned with SRI integrity hashes
### Settings and configuration
- Settings panel (gear icon in topbar) -- persist default model and default workspace server-side
- Settings panel (gear icon) -- default model, default workspace, send key preference
- Send key: Enter (default) or Ctrl/Cmd+Enter
- Show/hide CLI sessions toggle (enabled by default)
- Token usage display toggle (off by default, also via `/usage` command)
- Cron completion alerts -- toast notifications and unread badge on Tasks tab
- Background agent error alerts -- banner when a non-active session encounters an error
### Slash commands
- Type `/` in the composer for autocomplete dropdown
- Built-in: `/help`, `/clear`, `/model <name>`, `/workspace <name>`, `/new`, `/usage`
- Arrow keys navigate, Tab/Enter select, Escape closes
- Unrecognized commands pass through to the agent
### Panels
- **Chat** -- session list, search, pin, archive, new conversation
- **Tasks** -- view, create, edit, run, pause/resume, delete cron jobs; completion alerts
- **Skills** -- list all skills by category, search, preview, create/edit/delete
- **Chat** -- session list, search, pin, archive, projects, new conversation
- **Tasks** -- view, create, edit, run, pause/resume, delete cron jobs; run history; completion alerts
- **Skills** -- list all skills by category, search, preview, create/edit/delete; linked files viewer
- **Memory** -- view and edit MEMORY.md and USER.md inline
- **Profiles** -- create, switch, delete agent profiles; clone config
- **Todos** -- live task list from the current session
- **Spaces** -- add, rename, remove workspaces; quick-switch from topbar
### Mobile responsive
- Hamburger sidebar -- slide-in overlay on mobile (<640px)
- Bottom navigation bar -- 5-tab iOS-style fixed bar
- Files slide-over panel from right edge
- Touch targets minimum 44px on all interactive elements
- Composer positioned above bottom nav
- Desktop layout completely unchanged
---
## Architecture
```
server.py HTTP routing shell (~76 lines)
server.py HTTP routing shell + auth middleware (~81 lines)
api/
routes.py All GET + POST route handlers
config.py Discovery + globals + model provider detection
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve()
models.py Session model + CRUD
workspace.py File ops: list_dir, read_file_content, workspace helpers
upload.py Multipart parser, file upload handler
streaming.py SSE engine, run_agent integration, cancel support
auth.py Optional password authentication, signed cookies (~149 lines)
config.py Discovery, globals, model detection, reloadable config (~702 lines)
helpers.py HTTP helpers, security headers (~71 lines)
models.py Session model + CRUD (~146 lines)
profiles.py Profile state management, hermes_cli wrapper (~366 lines)
routes.py All GET + POST route handlers (~1180 lines)
streaming.py SSE engine, run_agent, cancel support (~272 lines)
upload.py Multipart parser, file upload handler (~78 lines)
workspace.py File ops, workspace helpers (~245 lines)
static/
index.html HTML template
style.css All CSS
ui.js DOM helpers, renderMd, Mermaid, tool cards, file tree
workspace.js File tree, preview, file ops
sessions.js Session CRUD, list rendering, search, tags, archive
messages.js send(), SSE event handlers, approval, transcript
panels.js Cron, skills, memory, workspace, todo, switchPanel, alerts
boot.js Event wiring + boot IIFE
index.html HTML template (~364 lines)
style.css All CSS incl. mobile responsive (~670 lines)
ui.js DOM helpers, renderMd, tool cards, file tree (~1002 lines)
workspace.js File preview, file ops (~191 lines)
sessions.js Session CRUD, list rendering, search (~556 lines)
messages.js send(), SSE handlers, approval, transcript (~337 lines)
panels.js Cron, skills, memory, profiles, settings (~1030 lines)
commands.js Slash command autocomplete (~156 lines)
boot.js Mobile nav, voice input, boot IIFE (~338 lines)
tests/
conftest.py Isolated test server (port 8788, separate HERMES_HOME)
test_sprint1-14.py Feature tests per sprint
test_regressions.py Permanent regression gate
conftest.py Isolated test server (port 8788)
test_sprint{1-23}.py 22 test files, 426 test functions
test_regressions.py Permanent regression gate (23 tests)
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
```
State lives outside the repo at `~/.hermes/webui-mvp/` by default
(sessions, workspaces, settings, last_workspace). Override with `HERMES_WEBUI_STATE_DIR`.
(sessions, workspaces, settings, projects, last_workspace). Override with `HERMES_WEBUI_STATE_DIR`.
---
## Docs
- `HERMES.md` -- why Hermes, mental model, and detailed comparison to Claude Code / Codex / OpenCode / Cursor
- `ROADMAP.md` -- feature roadmap and sprint history
- `ARCHITECTURE.md` -- system design, all API endpoints, implementation notes
- `TESTING.md` -- manual browser test plan and automated coverage reference
- `CHANGELOG.md` -- release notes
- `CHANGELOG.md` -- release notes per sprint
- `SPRINTS.md` -- forward sprint plan with CLI + Claude parity targets
## Repo

View File

@@ -3,8 +3,8 @@
> 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: Sprint 17 / v0.19 (April 3, 2026)
> Tests: 294 passing
> Last updated: v0.29 (April 4, 2026)
> Tests: 424 total (401 passing, 23 pre-existing failures)
> Source: <repo>/
---
@@ -32,8 +32,14 @@
| Sprint 13 | Alerts + polish | Cron completion alerts (polling + badge), background error banner, session duplicate, browser tab title | 221 |
| Sprint 14 | Visual polish + workspace ops | Mermaid diagrams, message timestamps, file rename, folder create, session tags, session archive | 233 |
| Sprint 15 | Session projects + code copy | Session projects/folders, code block copy button, tool card expand/collapse toggle | 237 |
| Sprint 16 | Session sidebar visual polish | SVG action icons, overlay hover actions, pin indicator, project border, custom model discovery, GLM-5.1 | 237 |
| Sprint 17 | Workspace polish + slash commands + settings | Breadcrumb navigation, slash command autocomplete, send key setting (#26) | 294 |
| Sprint 16 | Session sidebar visual polish | SVG action icons, overlay hover actions, pin indicator, project border, safe HTML rendering | 289 |
| Sprint 17 | Workspace polish + slash commands + settings | Breadcrumb navigation, slash command autocomplete, send key setting (#26) | 318 |
| Sprint 18 | Thinking display + workspace tree | File preview auto-close, thinking/reasoning cards, expandable directory tree (#22) | 318 |
| Sprint 19 | Auth + security hardening | Password auth (off by default), login page, security headers, 20MB body limit (#23) | 328 |
| Sprint 20 | Voice input + send button | Voice input (Web Speech API), send button icon-circle with pop-in animation | 415 |
| Sprint 21 | Mobile responsive + Docker | Hamburger sidebar, bottom nav, files slide-over, Docker support (#21, #7) | 415 |
| Sprint 22 | Multi-profile support | Profile picker, management panel, seamless switching, per-session tracking (#28) | 415 |
| Sprint 23 | Agentic transparency | Token/cost display, subagent cards, skill picker in cron, skill linked files, workspace tree persistence, timestamp fixes | 424 |
---
@@ -41,10 +47,12 @@
| Layer | Location | Status |
|-------|----------|--------|
| Python server | <repo>/server.py (~76 lines) + api/ modules (~2145 lines) | Thin shell + business logic in api/ |
| HTML template | <repo>/static/index.html | Served from disk |
| CSS | <repo>/static/style.css (~560 lines) | Served from disk |
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands}.js | 7 modules, ~2990 lines total |
| 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 |
| 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 |
| Production server | Port 8787 | SSH tunnel from Mac |
@@ -69,7 +77,7 @@
- [x] Copy message to clipboard (hover icon on each bubble)
- [x] Edit last user message and regenerate
- [ ] Branch/fork conversation (Wave 3)
- [ ] Token/cost estimate per message (Wave 3)
- [x] Token/cost estimate per message (Sprint 23)
### Tool Visibility
- [x] Tool progress in activity bar (moved out of composer footer)
@@ -130,7 +138,7 @@
- [x] Edit existing cron job
- [x] Delete cron job
- [x] View full cron run history (expandable per job)
- [ ] Skill picker in cron create form (Wave 3)
- [x] Skill picker in cron create form (Sprint 23)
### Skills
- [x] List all skills grouped by category (Skills sidebar tab)
@@ -139,7 +147,7 @@
- [x] Create skill
- [x] Edit skill
- [x] Delete skill
- [ ] View skill linked files (Wave 3)
- [x] View skill linked files (Sprint 23)
### Memory
- [x] View personal notes (MEMORY.md) rendered as markdown (Memory tab)
@@ -149,22 +157,48 @@
### Configuration
- [x] Settings panel (default model, default workspace) (Sprint 12)
- [x] Send key preference (Enter or Ctrl+Enter) (Sprint 17)
- [x] Password authentication (Sprint 19)
- [ ] Enable/disable toolsets per session (deferred)
### Notifications
- [x] Cron job completion alerts (Sprint 13)
- [x] Background agent error alerts (Sprint 13)
### Workspace
- [x] Breadcrumb navigation in subdirectories (Sprint 17)
- [x] Workspace tree view with expand/collapse (Sprint 18, Issue #22)
- [x] File preview auto-close on directory navigation (Sprint 18)
### Slash Commands
- [x] Command registry + autocomplete dropdown (Sprint 17)
- [x] Built-in: /help, /clear, /model, /workspace, /new (Sprint 17)
### Security
- [x] Password auth with signed cookies (Sprint 19, Issue #23)
- [x] Security headers (X-Content-Type-Options, X-Frame-Options) (Sprint 19)
- [x] POST body size limit (20MB) (Sprint 19)
### Thinking / Reasoning
- [x] Collapsible thinking cards for extended-thinking models (Sprint 18)
### Voice
- [x] Voice input via Web Speech API (Sprint 20)
### Mobile
- [x] Mobile responsive layout — hamburger sidebar, bottom nav, files slide-over (Sprint 21)
### Profiles
- [x] Multi-profile support — create, switch, delete profiles (Sprint 22, Issue #28)
### Advanced / Future
- [ ] Voice input via Whisper (Wave 6)
- [ ] TTS playback of responses (Wave 6)
- [ ] Subagent delegation cards (Wave 6)
- [ ] TTS playback of responses (deferred)
- [ ] Subagent delegation cards (deferred)
- [x] Background task cancel (activity bar Cancel button)
- [ ] Code execution cell (Wave 6)
- [ ] Password authentication (Wave 7)
- [ ] HTTPS / reverse proxy (Wave 7)
- [ ] Mobile responsive layout (Wave 7)
- [ ] Virtual scroll for large lists (Wave 7)
- [ ] Code execution cell (deferred)
- [ ] Desktop application (deferred)
- [ ] Extended slash command / skill integration (deferred)
- [ ] Virtual scroll for large lists (deferred)
---
@@ -241,96 +275,29 @@ Enter saves, Escape cancels. Topbar updates immediately.
---
## Wave 3: Power Features and Developer Experience
## Completed Waves (Summary)
### Sprint 3.1: Tool Call Visibility Inline
Show tool calls as collapsible cards in the conversation.
Collapsed: tool name badge + one-line preview. Expanded: full args + result.
### Sprint 3.2: Multi-Model Expansion
Add more models. Group by provider. Model info tooltip on hover.
(Partially done: 10 models in dropdown from Sprint 1.)
### Sprint 3.2b: Resizable Panel Widths (COMPLETE Sprint 6)
Both sidebar and workspace panel are drag-resizable with localStorage persistence.
### Sprint 3.3: Workspace File Actions
- [x] Rename file (inline, double-click) (Sprint 14)
- [x] Create folder (Sprint 14)
- [x] Syntax highlighted code preview (Prism.js)
### Sprint 3.4: Conversation Controls
- [x] Copy message (Sprint 5)
- [x] Edit last user message + regenerate
- [x] Regenerate last assistant response
- [x] Clear conversation (wipe messages, keep session)
---
## Wave 4: Settings, Configuration, Notifications
### Sprint 4.1: Settings Panel
Full settings overlay: default model, default workspace, enabled toolsets, config viewer.
### Sprint 4.2: Notification Panel
Bell icon with unread count. SSE endpoint for cron completions and errors. Toast pop-ups.
### Sprint 4.3: Delivery Target Config
Configure and test-ping delivery targets (Discord, Telegram, Slack, email) for cron jobs.
---
## Wave 5: Honcho Integration and Long-term Memory
### Sprint 5.1: Honcho Memory Panel
User representation panel, cross-session context, Honcho search, memory write.
### Sprint 5.2: Session Continuity Features
"What were we working on?" button, session tags, session archive.
---
## Wave 6: Realtime and Agentic Features
### Sprint 6.1: Background Task Monitor
Live list of running agent threads. Cancel button. Queue visibility.
### Sprint 6.2: Subagent Delegation Cards
When delegate_task fires, show subagent progress inline in chat.
### Sprint 6.3: Code Execution Panel
Jupyter-style inline code cell. Stateful kernel per session.
### Sprint 6.4: Voice Mode
Push-to-talk mic button. Whisper transcription. Optional TTS playback.
---
## Wave 7: Production Hardening and Mobile
### Sprint 7.1: Authentication
HERMES_WEBUI_PASSWORD env var gate. Signed cookie. Login page.
### Sprint 7.2: HTTPS and Reverse Proxy
Nginx + Let's Encrypt. CORS headers for external domain.
### Sprint 7.3: Mobile Responsive Layout
Collapsible sidebar hamburger. Touch-friendly controls. Swipe gestures.
### Sprint 7.4: Performance and Scale
Virtual scroll for session/message lists. Incremental message loading.
| Wave | Theme | Key Deliverables |
|------|-------|-----------------|
| Wave 2 | Full CRUD + Interaction | Cron/skill/memory CRUD, session search, workspace management, session rename |
| Wave 3 | Power Features | Tool call cards, multi-model dropdown, resizable panels, file actions, conversation controls |
| Wave 4 | Settings + Notifications | Settings panel, cron alerts, background error banner |
| Wave 5 | Session Continuity | Session tags, archive, projects/folders |
| Wave 6 | Agentic Features | Background task cancel, voice input (Web Speech API) |
| Wave 7 | Production Hardening | Password auth, security headers, mobile responsive, Docker + GHCR CI |
---
## User Requested Features
Community-requested enhancements tracked from GitHub issues.
Community-requested enhancements tracked from GitHub issues. All shipped.
| Feature | Issue | Description | Complexity |
|---------|-------|-------------|-----------|
| Workspace tree view | #22 | Accordion/tree view for workspace file browser instead of flat list. Lazy-load subdirectories on expand, no backend changes needed. | Medium |
| Docker container | #7 | Docker Compose setup with separate hermes-agent and hermes-webui containers, multi-arch (amd64 + arm64), volume mounts for config. | Medium-High |
| Authentication | #23 | Password gate via `HERMES_WEBUI_PASSWORD` env var, login page, signed cookie. Already planned in Sprint 7.1. | Low-Medium |
| Send key / personalization | #26 | Toggle send key (Enter vs Ctrl/Cmd+Enter) and queue vs interrupt mode as global settings. | Low |
| Multi-profile support | #28 | Profile management UI: create, delete, switch, configure agent profiles. | Medium |
| Mobile responsive UI | #21 | Hamburger menu, slide-out sidebar drawer, touch-friendly controls. Already planned in Sprint 7.3. | Medium-High |
| Feature | Issue | Shipped | Sprint |
|---------|-------|---------|--------|
| Workspace tree view | #22 | Done | Sprint 18 |
| Docker container + GHCR images | #7 | Done | Sprint 21 + v0.28.1 CI |
| Authentication | #23 | Done | Sprint 19 |
| Send key / personalization | #26 | Done | Sprint 17 |
| Multi-profile support | #28 | Done | Sprint 22 |
| Mobile responsive UI | #21 | Done | Sprint 21 |
| Profile creation in Docker | #44 | Done | v0.27 |

View File

@@ -1,6 +1,6 @@
# Hermes Web UI -- Forward Sprint Plan
> Current state: v0.20 | 318 tests | Daily driver ready
> Current state: v0.30.1 | 424 tests | Daily driver ready
> This document plans the path from here to two targets:
>
> Target A: 1:1 feature parity with the Hermes CLI (everything you can do from the
@@ -14,17 +14,19 @@
---
## Where we are now (v0.18)
## Where we are now (v0.21)
**CLI parity: ~85% complete.** Core agent loop, all tools visible, workspace
file ops, cron/skills/memory CRUD, session management, streaming, cancel,
multi-provider models, custom endpoint discovery -- all solid. Gaps are
subagent visibility, toolset control, and code execution.
**CLI parity: ~90% complete.** Core agent loop, all tools visible, workspace
file ops with tree view, cron/skills/memory CRUD, session management, streaming,
cancel, multi-provider models, custom endpoint discovery, slash commands,
thinking/reasoning display, password auth -- all solid. Gaps are subagent
visibility, toolset control, and code execution.
**Claude parity: ~65% complete.** Chat, streaming, file browser, session
**Claude parity: ~70% complete.** Chat, streaming, file browser, session
management, tool cards, syntax highlighting, model switching, projects,
settings, Mermaid diagrams, mobile layout -- all present. Gaps are
artifacts, voice, reasoning display, sharing.
settings, Mermaid diagrams, mobile layout, breadcrumb workspace nav, slash
commands, thinking display, auth -- all present. Gaps are artifacts, voice,
TTS, sharing, mobile-optimized layout.
---
@@ -323,122 +325,508 @@ handler for slash command autocomplete.
---
## Sprint 18 -- Voice + Multimodal Input
## Sprint 18 -- Thinking Display + Workspace Tree + Preview Fix (COMPLETED)
**Theme:** Input beyond the keyboard.
**Theme:** Show the model's reasoning, improve workspace navigation, fix UX bug.
**Why now:** Voice is a meaningful quality-of-life feature for longer sessions
and is achievable with Whisper. Image input closes the last modality gap with
Claude (Claude accepts image paste natively -- we do too, but only as
file uploads, not clipboard screenshots into the conversation directly).
**Why now:** Thinking/reasoning display was deferred twice (Sprint 16 → 17 → 18).
Workspace tree view was the #1 community request (Issue #22). File preview
staying open on directory navigation was a daily-driver annoyance.
### Track A: Bugs
- Image paste currently requires a click-to-attach flow. Direct paste into the
message textarea should embed the image inline (as a preview chip) and queue
it for upload on Send. (Partially works -- clean up edge cases.)
- Large image uploads (>5MB) time out the upload step silently.
- **File preview auto-close.** When viewing a file in the right panel and
navigating directories (breadcrumbs, up button, folder clicks), the preview
stayed visible with stale content. Fix: extracted `clearPreview()` as a named
function in boot.js and call it from `loadDir()` in workspace.js.
### Track B: Features
- **Voice input (Whisper):** A microphone icon in the composer. Hold to record,
release to transcribe via `POST /api/transcribe` (calls local Whisper or
OpenAI Whisper API). Transcribed text appears in the message input, editable
before send. Supports the full "voice -> text -> Hermes response" loop.
- **TTS playback:** A speaker icon on assistant messages. Calls a TTS endpoint
(ElevenLabs or OpenAI TTS) and plays the audio. Toggle per-message. Optional
auto-play mode in settings.
- **Vision input improvements:** Paste a screenshot directly from clipboard into
the conversation (not just the tray). Shows as an inline preview chip with
the image thumbnail. On Send, uploads and includes in the message.
- **Thinking/reasoning display.** Assistant messages with structured content
arrays containing `type:'thinking'` or `type:'reasoning'` blocks now render
as collapsible gold-themed cards above the response text. Collapsed by
default, click header to expand. Works with Claude extended thinking and
o3 reasoning tokens when preserved in the message array.
- **Workspace tree view (Issue #22).** Directories expand/collapse in-place
with toggle arrows. Single-click toggles, double-click navigates (breadcrumb
view). Subdirectory contents fetched lazily and cached in `S._dirCache`.
Nesting depth shown via indentation. Empty directories show "(empty)".
**Tests:** 0 new (pure CSS/DOM changes). Total: 318.
**Hermes CLI parity impact:** Low
**Claude parity impact:** High (reasoning display matches Claude's UI)
---
## Sprint 19 -- Auth + Security Hardening (COMPLETED)
**Theme:** Make this safe to leave running beyond localhost.
**Why now:** Issue #23 requested authentication. Auth is the last production
hardening feature before the app is safe to expose to a network.
### Track A: Bugs
- **No request size limit.** POST bodies were unbounded (DoS risk). Added 20MB
cap in `read_body()`.
### Track B: Features
- **Password authentication (Issue #23).** Off by default — zero friction for
localhost. Enable via `HERMES_WEBUI_PASSWORD` env var or Settings panel.
Password-only (no username — single-user app). Signed HMAC HTTP-only cookie
with 24h TTL. Minimal dark-themed login page at `/login`. API calls without
auth return 401; page loads redirect to `/login`. Settings panel gains
"Access Password" field and "Sign Out" button.
- **Security headers.** All responses now include `X-Content-Type-Options: nosniff`,
`X-Frame-Options: DENY`, `Referrer-Policy: same-origin`.
### Track C: Architecture
- Audio pipeline: `POST /api/transcribe` streams audio bytes, returns transcript.
`GET /api/tts?text=...` returns audio/mpeg. Both use lazy import of Whisper
and TTS libraries to keep cold start fast.
- New `api/auth.py` module: password hashing (SHA-256 + STATE_DIR salt), signed
session cookies, auth middleware, public path allowlist.
- Auth check in `server.py` do_GET/do_POST before routing.
- `password_hash` added to `_SETTINGS_DEFAULTS` in config.py.
- `_set_password` special field in save_settings for secure password updates.
**Tests:** ~12 new. Total: ~271.
**Tests:** 10 new. Total: 328.
**Hermes CLI parity impact:** Low (CLI has no auth concerns)
**Claude parity impact:** High (Claude is authenticated)
---
## Sprint 20 -- Voice Input + Send Button Polish (COMPLETED)
**Theme:** Input refinements — voice and visual polish.
**Why now:** Voice input was the next feature on the roadmap. The send button
UX was a low-effort high-impact polish opportunity that pairs naturally.
### Track A: Bugs
- **Send button always visible.** The old pill-shaped "Send" button was always
visible even with an empty textarea, wasting space. Now hidden by default,
appears only when there is content to send.
### Track B: Features
- **Voice input (Web Speech API).** Microphone button in composer. Tap to
record, tap again to stop. Live interim transcription in textarea. Auto-stops
after ~2s of silence. Appends to existing text. Hidden when browser doesn't
support Web Speech API. No API keys, no server changes.
- **Send button polish.** Icon-only 34px circle with upward arrow SVG. Pop-in
spring animation on appear. Scale hover/active for tactile feedback. Hidden
while agent is responding.
### Track C: Architecture
- Voice input IIFE in `boot.js` with SpeechRecognition lifecycle.
- `updateSendBtn()` in `ui.js` hooked into setBusy, renderTray, autoResize.
**Tests:** 52 new (voice) + 33 new (send button). Total: 415.
**Hermes CLI parity impact:** Medium (voice not in CLI, but adds capability)
**Claude parity impact:** High (Claude has native voice mode)
---
## Sprint 18 -- Subagent Visibility + Agentic Transparency
## Sprint 21 -- Mobile Responsive + Docker (COMPLETED)
**Theme:** Watch Hermes think, not just respond.
**Theme:** Mobile experience + containerized deployment.
**Why now:** When Hermes delegates to subagents (delegate_task, spawns parallel
workstreams), the UI shows nothing. On long multi-agent tasks you have no idea
what's happening. This is the last major "CLI feels better" gap for power users.
**Why now:** Issue #21 (mobile) was the most-requested UX gap. Issue #7 (Docker)
enables deployment beyond localhost. Both were achievable without new dependencies.
### Track A: Bugs
- Tool cards for delegate_task show no information about what the subagent was
asked to do or what it returned.
- The activity bar text truncates at 55 chars -- tool previews for long terminal
commands show nothing useful.
### Track A: Bugs (from review)
- **CSS cascade broke mobile slide-in.** `position:relative` after the media query
overrode `position:fixed`. Wrapped in `@media(min-width:641px)`.
- **mobileSwitchPanel() always reopened sidebar.** Chat tab now closes it.
- **Dockerfile missing pip install.** Container failed on startup.
- **No .dockerignore.** `.git`, `tests/`, `.env*` leaked into images.
- **docker-compose tilde expansion.** `~` doesn't expand in Compose defaults.
### Track B: Features
- **Subagent delegation cards:** When `delegate_task` fires, show an expandable
card with the subagent's goal, status (pending/running/done), and result
summary. Multiple subagents from one call appear as a card group. Uses the
existing tool card infrastructure.
- **Background task monitor:** A "Tasks" indicator in the topbar (separate from
the cron Tasks panel). Shows count of active agent threads. Click opens a
popover listing all in-flight streams with session names and elapsed times.
Cancel any individual thread. This is the full job queue visibility the CLI
implicitly has via `ps aux`.
- **Thinking/reasoning display:** When the model emits reasoning tokens (o3,
Claude extended thinking), show them in a collapsible "Reasoning" card above
the response. Collapsed by default. This matches Claude's reasoning display.
- **Hamburger sidebar.** Slide-in overlay on mobile, tap outside to close.
- **Bottom navigation bar.** 5-tab iOS-style bar replaces sidebar tabs.
- **Files slide-over.** Right panel opens as slide-over from right edge.
- **Touch targets.** Minimum 44px on all interactive elements.
- **Docker support.** Dockerfile, docker-compose.yml, .dockerignore.
### Track C: Architecture
- Task registry: extend STREAMS to include session name, start time, and task
description. New `GET /api/tasks/active` endpoint returns all running streams
with metadata.
- Mobile nav functions in `boot.js`. Session click auto-closes sidebar.
- 69 new CSS lines scoped to `@media(max-width:640px)`.
- Desktop layout untouched — all mobile elements `display:none` by default.
**Tests:** ~14 new. Total: ~285.
**Hermes CLI parity impact:** Very High (subagent and task visibility is the
last major CLI gap)
**Claude parity impact:** High (Claude shows reasoning, tool use visibly)
**Tests:** 0 new (CSS/DOM changes). Total: 415.
**Hermes CLI parity impact:** Low
**Claude parity impact:** High (Claude has mobile layout)
---
## Sprint 19 -- Auth, HTTPS, and Production Hardening
## Sprint 22 -- Multi-Profile Support (COMPLETED, Issue #28)
**Theme:** Make this safe to leave running.
**Theme:** Switch between Hermes agent profiles seamlessly from the web UI.
**Why now:** Everything else is done. This is the sprint you run when you want
to expose the UI beyond localhost -- to a team, a mobile device, or a public
address.
**Why now:** Issue #28 requested full profile management in the UI. The CLI has
had comprehensive profile support since v0.6.0 — isolated instances with their
own config, skills, memory, cron, and API keys. The web UI was locked to a
single default profile, blocking multi-persona workflows.
### Track A: Bugs
- Server has no request size limit on non-upload endpoints (potential DoS).
- Session JSON files have no size cap (a runaway agent could write GBs).
- **Hardcoded `~/.hermes` paths.** Memory read/write in routes.py and model
discovery in config.py used hardcoded paths instead of the active profile's
directory. Fixed to resolve through `get_active_hermes_home()`.
- **Module-level cached paths.** hermes-agent's `skills_tool.py` and `cron/jobs.py`
snapshot `HERMES_HOME` at import time. Profile switch now monkey-patches these
cached variables (`SKILLS_DIR`, `CRON_DIR`, `JOBS_FILE`, `OUTPUT_DIR`).
### Track B: Features
- **Password authentication:** A login page with a configurable password
(HERMES_WEBUI_PASSWORD env var). Signed cookie session (24h expiry).
Single-user model -- no accounts, no registration.
- **HTTPS / reverse proxy guide:** A one-page `DEPLOY.md` with instructions
for running behind nginx + Let's Encrypt on a VPS. Configuration snippets
for systemd service, nginx config, certbot.
- **Mobile responsive layout:** Collapsible sidebar (hamburger). Touch-friendly
session list (swipe to delete, tap to navigate). Composer expands on focus.
Right panel hidden by default on mobile, accessible via a Files tab.
- **Rate limiting:** Simple per-IP token bucket on the chat/start endpoint
(configurable, default 10 req/min) to prevent accidental hammering.
- **Profile picker (topbar).** Purple-accented chip with SVG user icon in the
topbar. Click opens a dropdown listing all profiles with gateway status dots,
model info, and skill count. Click to switch; "Manage profiles" link opens
the management panel.
- **Profiles sidebar panel.** New nav tab with full management UI. Cards show
each profile with model, provider, skill count, API key status, and gateway
badge. "Use" button to switch, delete button for non-default profiles.
- **Profile creation.** "+ New profile" form with name validation (lowercase
alphanumeric + hyphens), optional "clone config from active" checkbox. Wraps
`hermes_cli.profiles.create_profile()`.
- **Profile deletion.** Confirm dialog, auto-switches to default if deleting
the active profile. Blocked while agent is running.
- **Seamless switching.** No server restart required. Profile switch updates
`HERMES_HOME` env var, patches module-level caches, reloads `.env` API keys,
reloads `config.yaml`, and refreshes the model dropdown, skills, memory, and
cron panels.
- **Per-session profile tracking.** New `profile` field on Session records which
profile was active when the session was created. Backward-compatible (defaults
to `null` for old sessions).
### Track C: Architecture
- Helmet headers: X-Content-Type-Options, X-Frame-Options, HSTS (when served
over HTTPS). Simple middleware in the Handler.
- New `api/profiles.py` module (~200 lines): profile state management wrapping
`hermes_cli.profiles`. Thread-safe with `_profile_lock`. Lazy imports to
avoid circular dependencies.
- `api/config.py`: Replaced module-level `cfg` dict with reloadable
`get_config()`/`reload_config()`. Dynamic `_get_config_path()` resolves
through active profile.
- `api/streaming.py`: `HERMES_HOME` added to env save/restore block around
agent runs (alongside `TERMINAL_CWD`, `HERMES_EXEC_ASK`).
- Profile switch blocked while any agent stream is active (process-global
`HERMES_HOME` cannot be changed mid-run).
- Zero modifications to hermes-agent code required.
**Tests:** ~12 new. Total: ~297.
**Hermes CLI parity impact:** Low (CLI has no auth/HTTPS concerns)
**Claude parity impact:** Very High (Claude is authenticated, HTTPS only)
**Tests:** 0 new (profile management requires hermes-agent integration). Total: 415.
**Hermes CLI parity impact:** Very High (profile support is a major CLI feature)
**Claude parity impact:** Low (Claude has no profile concept)
---
## Sprint 23 -- Profile/Workspace/Model Coherence (COMPLETED)
**Theme:** Make profiles, workspaces, models, and sessions coherent across
profile switches.
**Why now:** Sprint 22 added profile switching but five coherence bugs remained:
the model picker ignored the profile's default, workspaces were a global file,
DEFAULT_WORKSPACE was a startup singleton, the session list showed all profiles,
and switchToProfile() didn't refresh workspaces or sessions.
### Track A: Bugs
- **Model picker ignores profile on switch.** `populateModelDropdown()` skipped
the profile's default model if `localStorage` had a saved preference. Fixed:
`switchToProfile()` now clears `hermes-webui-model` from localStorage and
applies the profile's default model from the switch response.
- **Workspace list is a global file.** `workspaces.json` was process-global.
Fixed: workspace storage is now profile-local at `{profile_home}/webui_state/`.
Default profile uses global STATE_DIR for backward compatibility.
- **`DEFAULT_WORKSPACE` is a startup singleton.** Frozen at boot. Fixed:
`get_last_workspace()` and `_profile_default_workspace()` now resolve
dynamically through the active profile's config.
- **Session list shows all profiles.** Fixed: `renderSessionListFromCache()`
filters to `S.activeProfile` by default, with "Show N from other profiles"
toggle (modeled on the archived toggle).
- **`switchToProfile()` doesn't refresh workspace list or sessions.** Fixed:
now calls `loadWorkspaceList()`, `renderSessionList()`, resets profile filter.
### Track B: Features
- **Profile-local workspace storage.** Each named profile stores its own
`workspaces.json` and `last_workspace.txt` under `{profile_home}/webui_state/`.
Falls back to global STATE_DIR for the default profile (preserves test
isolation and backward compat).
- **Profile switch returns defaults.** `POST /api/profile/switch` response now
includes `default_model` and `default_workspace` so the frontend can apply
both in one round-trip.
- **Session profile filter.** Session sidebar filters to active profile by
default. "Show N from other profiles" toggle reveals sessions from all
profiles. Resets on profile switch.
### Track C: Architecture
- `api/workspace.py`: Rewritten with `_profile_state_dir()`, `_workspaces_file()`,
`_last_workspace_file()`, `_profile_default_workspace()`. All lazy imports to
avoid circular deps.
- `api/profiles.py`: `switch_profile()` returns `default_model` and
`default_workspace` from the new profile's config.yaml.
- `static/panels.js`: `switchToProfile()` clears localStorage model key,
refreshes workspace list and session list, resets profile filter.
- `static/sessions.js`: `_showAllProfiles` state variable, profile filter in
`renderSessionListFromCache()`, toggle UI.
**Tests:** 8 new (test_sprint23.py). Total: 423.
**Hermes CLI parity impact:** High (coherent profile behavior)
**Claude parity impact:** Low
---
## Sprint 24 -- Web Polish + Bug Fix Pass (PLANNED)
**Theme:** Stabilize, harden, and close the last meaningful web UI gaps before
shifting focus to distribution. Goal is a release that's genuinely ready for
wider user adoption -- no rough edges, no obvious missing pieces.
**Why now:** Sprint 23 completed the core agentic transparency features. The
remaining web roadmap items are diminishing-returns polish. Rather than
grinding through marginal features, this sprint cleans up what's there, fixes
bugs users will actually hit, and closes a few real gaps before recommending
the app to others.
### Track A: Bug Fixes
- **Cron edit form has no skill picker.** Sprint 23 added skill picker to the
create form but not the edit form. cronEditSave() doesn't include skills in
the update body, so existing skills survive an edit but can't be changed.
Fix: add the same skill picker UI to the inline edit form and include
`skills` in the update POST body.
- **S.lastUsage dead code.** messages.js sets `S.lastUsage` from `d.usage` at
done-time, but nothing reads it. The usage badge reads cumulative session
totals from `S.session.input_tokens` instead. Either wire `S.lastUsage` into
a per-turn display or remove the dead assignment.
- **_cronSkillsCache never invalidated.** Skills picker shows stale data if
skills are added/removed mid-session. Add a cache-bust when the skills panel
is opened or a skill is saved/deleted.
- **Tool args not shown on session reload.** Tool call cards in history show
name and result snippet but not the args (args only exist in the live SSE
event). Sprint 23 added args to the session JSON -- verify they're actually
rendering in the settled history cards.
### Track B: Features
- **Cron edit: skill picker parity.** As above -- make create and edit forms
identical in capability.
- **Per-turn cost display.** The current usage badge shows cumulative session
totals attached to the last message, which is misleading. Either: (a) show
per-turn cost from `S.lastUsage` immediately after each response instead of
cumulative, or (b) show cumulative in the session topbar/header instead of
attached to a message bubble. Pick the cleaner UX.
- **Virtual scroll for long session/skill lists.** When session count or skill
count gets large (100+), the sidebar becomes sluggish. Add a simple virtual
scroll or windowed render -- only render visible items + a buffer above/below.
CSS `contain: strict` + IntersectionObserver approach, no library needed.
### Track C: Code Quality
- **SPRINTS.md + ROADMAP.md + CHANGELOG.md updated** to reflect Sprint 23
completion (agentic transparency) and correct test counts.
- **Remove stale Sprint 23 description** from SPRINTS.md (the "Profile/Workspace
coherence" text is from an older plan; Sprint 23 actually shipped agentic
transparency features).
- **CHANGELOG entry for v0.29** covering Sprint 23 deliverables.
**Estimated tests:** ~10 new. Target total: ~435.
**Hermes CLI parity impact:** Low
**Claude parity impact:** Low
**User-facing value:** Medium -- removes rough edges that would bother new users
---
## Sprint 25 -- macOS Desktop Application (PLANNED)
**Theme:** Native Mac desktop app. Single download, runs entirely offline,
feels like a real application -- not a browser tab.
**Why this matters:** The web UI requires an SSH tunnel or a server setup to
use. A .app bundle that a user can double-click and immediately have a working
Hermes interface is genuinely differentiating. No other open-source Hermes
interface ships as a native Mac app. This is the highest-leverage remaining
investment for user adoption.
**Approach: Swift + WKWebView (not Electron)**
The right architecture is a thin native Swift shell (~300-500 lines) that:
1. Bundles the existing Python server and all api/ modules inside the .app
2. Spawns the server as a subprocess on a random local port at launch
3. Opens a WKWebView window pointed at that localhost port
4. Handles Mac app lifecycle natively (dock icon, cmd+Q, window management,
app menu, about box)
5. Bridges a small set of native Mac capabilities that WKWebView can't do
**Why not Electron:** WKWebView is Safari's engine -- dramatically lighter than
Chromium. No 200MB node_modules. No separate update daemon. The .app is ~30MB
including the Python runtime, vs 150MB+ for Electron.
**Why not full native Swift UI:** Would require rewriting the entire frontend
from scratch. The web UI is already fast, dark-themed, and feature-complete.
The thin shell approach gets 95% of the benefit at 5% of the cost.
### Track A: Swift App Shell
**Files to create:**
```
desktop/
HermesApp.swift -- @main entry point, NSApp delegate
AppDelegate.swift -- lifecycle: start server on launch, stop on quit
WindowController.swift -- NSWindow + WKWebView setup, cmd shortcuts
ServerManager.swift -- spawn/monitor Python subprocess, pick free port
MenuBuilder.swift -- native app menu (File, Edit, View, Window, Help)
Info.plist -- bundle ID, display name, version, icon
Assets.xcassets/ -- app icon (1024x1024 + all required sizes)
HermesApp.xcodeproj/ -- Xcode project file
```
**ServerManager.swift responsibilities:**
- Find Python: check bundled runtime first, fall back to system python3
- Pick a free port (bind to :0, read assigned port, close, use it)
- Spawn: `python3 server.py --port {port}` as a child Process
- Monitor: if server crashes, show an error sheet and offer restart
- Shutdown: SIGTERM on app quit, wait up to 3s, then SIGKILL
**WKWebView configuration:**
- `allowsBackForwardNavigationGestures = false` (it's a single-page app)
- `WKUserContentController` for JS bridge (native notifications, file picker)
- Wait for server health check before loading (poll /health, show loading
spinner in the native window while waiting, typically <1s)
- `userAgent` override so the server can detect desktop app context
**Native menu items (beyond defaults):**
- File > New Session (Cmd+N) -- calls JS `newSession()`
- File > New Window (Cmd+Shift+N) -- opens second window with its own WKWebView
- View > Toggle Sidebar (Cmd+Shift+S)
- Window > Zoom, Minimize (standard)
- Help > About Hermes, Check for Updates (links to GitHub releases page)
### Track B: Python Bundling
Two options, in order of preference:
**Option A: Require system Python (simpler, recommended for v1)**
- Check for `python3` at known paths: `/usr/bin/python3`, homebrew paths,
pyenv paths
- If not found: show a one-time setup sheet with instructions
- Pros: tiny download (~5MB for the Swift app + web assets), no bundling complexity
- Cons: user needs Python installed (most developers do; target audience does too)
**Option B: Bundle python-standalone (self-contained, larger)**
- Use `python-build-standalone` (from Astral/uv project): pre-built Python
3.11 binaries, ~30MB compressed, no Xcode toolchain needed to build
- Extract to `~/Library/Application Support/Hermes/python/` on first launch
- Install `requirements.txt` via bundled pip into a local venv
- Pros: zero dependencies, works on a clean Mac
- Cons: first launch takes ~10-20s for extraction + pip install; ~30MB download
**Recommendation:** Ship v1 with Option A. Add Option B as an optional
"standalone" download for non-developers.
### Track C: Distribution
**GitHub Releases (primary):**
- Build with `xcodebuild -scheme HermesApp -configuration Release -archivePath`
- `xcodebuild -exportArchive` to produce a .app bundle
- `hdiutil create` to produce a .dmg with drag-to-Applications installer UI
- Upload .dmg as a GitHub Release asset via `gh release create`
- CI: add `.github/workflows/mac-release.yml` -- trigger on `vX.Y.Z-mac` tag
**Code signing:**
- Without an Apple Developer account: distribute as unsigned, users must
right-click > Open on first launch (standard for open-source Mac apps)
- With a free Apple Developer account: ad-hoc signing removes the Gatekeeper
warning without paying $99/year (no notarization, but much better UX)
- With paid account ($99/year): full notarization, no warnings, direct download
**Recommended for v1:** ad-hoc signing (free, good enough for early adopters).
Document the right-click > Open workaround in the README for unsigned builds.
**Universal binary (Intel + Apple Silicon):**
```bash
xcodebuild archive -scheme HermesApp -destination "generic/platform=macOS"
```
Both architectures in one .app. No separate downloads needed.
### Track D: Native Integrations (v1 scope)
**System notifications for cron completion:**
- The web UI polls `/api/cron/alerts` and shows in-page banners
- The Mac app can additionally post `UNUserNotificationCenter` notifications
- JS bridge: `window.webkit.messageHandlers.notify.postMessage({title, body})`
- Swift handler: posts a native notification with the cron job name and output
summary -- appears in Notification Center, works even when app is in background
**File picker for workspace add:**
- Currently: user types a path string into the workspace add form
- Mac app: intercept workspace-add form submission, open `NSOpenPanel` instead,
return the selected path to the JS via `evaluateJavaScript`
- Much better UX -- standard Mac folder picker, no typing paths
**Dock badge for pending approvals:**
- When an agent approval is waiting, set `NSApp.dockTile.badgeLabel = "1"`
- Clear badge when approval is resolved
- JS bridge fires when approval card appears/disappears
**Menu bar mode (optional, v2):**
- A small status bar item (⚗️ icon in menu bar) that opens a compact popover
- Popover shows current session status, last message, quick-compose field
- Useful for running Hermes in the background without a full window
### Track E: Testing
Since the Swift app is thin glue, most testing remains in the existing pytest
suite (server still runs identically). New Swift-specific tests:
- `ServerManagerTests.swift`: verify port picking, process spawn, health wait
- UI tests via `XCUITest`: launch app, wait for WKWebView to load, verify
title bar shows "Hermes", verify /health responds
- Smoke test in CI: `xcodebuild test -scheme HermesApp`
### Implementation Order
1. `ServerManager.swift` + basic `AppDelegate` -- get Python server spawning
and health-check working from Swift
2. `WindowController.swift` -- WKWebView loading, loading spinner while
server starts
3. App icon + Info.plist -- make it look like a real app
4. `MenuBuilder.swift` -- native menus + keyboard shortcuts
5. JS bridge for notifications -- most impactful native integration
6. DMG build script + GitHub Actions CI
7. (Optional) File picker bridge, dock badge
### What to NOT do in v1
- Windows or Linux wrapper (different toolchain; do Mac first, assess demand)
- Full Swift/SwiftUI rewrite of the frontend (months of work, wrong tradeoff)
- App Store submission (sandboxing breaks local server; not worth the effort)
- Auto-update mechanism (GitHub releases + manual download is fine for v1)
- Menu bar mode (cool but not v1 scope)
### Files to create in the repo
```
desktop/mac/
HermesApp/
HermesApp.swift
AppDelegate.swift
WindowController.swift
ServerManager.swift
MenuBuilder.swift
Assets.xcassets/
Info.plist
HermesApp.xcodeproj/
README.md -- build instructions, requirements, signing notes
.github/workflows/
mac-release.yml -- build + sign + upload DMG on tag push
```
The server code (`server.py`, `api/`, `static/`, `requirements.txt`) is
referenced from the repo root -- no duplication. The .app bundle copies them
at build time.
**Estimated effort:** 2-3x a typical web sprint (new language, new toolchain,
bundling complexity). Realistic for a focused weekend or a dedicated agent run
with clear instructions.
**Hermes CLI parity impact:** N/A (different distribution channel)
**Claude parity impact:** Medium (Claude.app is a native Mac app)
**User-facing value:** Very high -- lowers barrier to entry dramatically,
genuinely differentiating for an open-source project
---
## Feature Parity Summary
### After Sprint 18 (Hermes CLI parity: complete)
### Hermes CLI Parity (as of Sprint 19)
| CLI Feature | Status |
|-------------|--------|
@@ -454,15 +842,19 @@ address.
| Workspace switching | Done (v0.7) |
| Model selection | Done (v0.3) |
| Multi-provider model support | Done (Sprint 11) |
| Toolset control | Sprint 12 |
| Settings persistence | Done (Sprint 12) |
| Subagent visibility | Sprint 18 |
| Background task monitor | Sprint 18 |
| Code execution (Jupyter) | Sprint 17+ |
| Cron completion alerts | Done (Sprint 13) |
| Slash commands | Done (Sprint 17) |
| Thinking/reasoning display | Done (Sprint 18) |
| Auth / login | Done (Sprint 19) |
| Voice input | Done (Sprint 20) |
| Multi-profile support | Done (Sprint 22) |
| Subagent visibility | Deferred |
| Code execution (Jupyter) | Deferred |
| Toolset control | Deferred |
| Virtual scroll (perf) | Deferred |
### After Sprint 19 (Claude parity: ~90% complete)
### Claude Parity (as of Sprint 19)
| Claude Feature | Status |
|----------------|--------|
@@ -474,19 +866,21 @@ address.
| Tool use visibility | Done (v0.11) |
| Edit/regenerate messages | Done (v0.10) |
| Session management | Done (v0.6) |
| Artifacts (HTML/SVG preview) | Sprint 17+ |
| Code execution inline | Sprint 17+ |
| Mermaid diagrams | Done (Sprint 14) |
| Projects / folders | Done (Sprint 15) |
| Pinned/starred sessions | Done (Sprint 12) |
| Reasoning display | Sprint 18 |
| Voice input | Sprint 17 |
| TTS playback | Sprint 17 |
| Notifications | Done (Sprint 13) |
| Settings panel | Done (Sprint 12) |
| Auth / login | Sprint 19 |
| HTTPS | Sprint 19 |
| Mobile layout | Done (v0.16.1) |
| Reasoning display | Done (Sprint 18) |
| Auth / login | Done (Sprint 19) |
| Mobile layout (basic) | Done (v0.16.1) |
| Workspace tree view | Done (Sprint 18) |
| Slash commands | Done (Sprint 17) |
| Voice input | Done (Sprint 20) |
| TTS playback | Deferred |
| Artifacts (HTML/SVG preview) | Deferred |
| Code execution inline | Deferred |
| Mobile-optimized layout | Done (Sprint 21) |
| Sharing / public URLs | Not planned (requires server infra) |
| Claude-specific features | Not replicable (Projects AI, artifacts sync) |
@@ -503,6 +897,6 @@ address.
---
*Last updated: April 3, 2026*
*Current version: v0.19 | 318 tests*
*Next sprint: Sprint 18 (Voice + Multimodal Input)*
*Last updated: April 4, 2026*
*Current version: v0.30.1 | 424 tests*
*Next sprint: Sprint 24 (Web Polish + Bug Fix Pass)*

View File

@@ -1,12 +1,15 @@
# Hermes Web UI: Browser Testing Plan
> This document is for manual browser testing by you or by a Claude browser agent.
> It covers every user-facing feature of the UI through Sprint 2.
> It covers user-facing features of the UI through Sprint 22 (v0.24).
> 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 8787. Open http://localhost:8787 in browser.
> Server health check: curl http://127.0.0.1:8787/health should return {"status":"ok"}.
>
> Automated tests: 424 total (401 passing, 23 pre-existing failures).
> Run: `pytest tests/ -v --timeout=60`
---
@@ -1593,8 +1596,120 @@ FAIL: User message gone, blank chat, response lands in wrong session.
---
*Last updated: Post-Sprint 10 concurrency sweeps, March 31, 2026*
*Total automated tests: 190/190*
*Regression gate: tests/test_regressions.py (23 tests, one per introduced bug)*
*Run: python -m pytest tests/ -v*
---
## Sections Added Post-Sprint 10 (Sprints 11-19)
The following features were added in Sprints 11-19 and need manual browser testing.
Each has automated API-level tests in `tests/test_sprint{N}.py`.
### Sprint 11: Multi-Provider Models
- Open model dropdown. Verify models grouped by provider (OpenAI, Anthropic, Google, etc.)
- If custom `base_url` configured in config.yaml, verify local models appear in dropdown.
- Switch model. Send a message. Verify response uses selected model.
### Sprint 12: Settings + Pin + Import
- Click gear icon. Settings overlay opens.
- Change default model, save. Restart server. Verify setting persisted.
- Pin a session (star icon in hover overlay). Verify it floats to top of list.
- Export session as JSON. Import it back. Verify messages restored.
### Sprint 13: Alerts + Session QoL
- Duplicate a session (copy icon in hover overlay). Verify "(copy)" title.
- Browser tab title updates to active session name. Switch sessions — title changes.
### Sprint 14: Visual Polish + Workspace Ops
- Create a mermaid code block in a response. Verify diagram renders inline.
- Message timestamps visible next to role labels (hover for full date).
- Double-click a file in workspace panel to rename. Enter saves, Escape cancels.
- Create a folder via folder icon in workspace header.
- Add `#tag` to session title. Verify tag chip appears in sidebar. Click to filter.
- Archive a session. Verify it disappears. Toggle "Show archived" to see it.
### Sprint 15: Session Projects
- Click "+" in project bar to create a project. Type name, Enter.
- Click a project chip to filter sessions.
- Hover a session → click folder icon → assign to project via picker.
- Verify colored left border appears on assigned session.
- Double-click project chip to rename. Right-click to delete.
- Code blocks have a "Copy" button. Click → "Copied!" feedback.
- Messages with 2+ tool cards show "Expand all / Collapse all" toggle.
### Sprint 16: Sidebar Visual Polish
- Session titles use full sidebar width (no truncated space for hidden icons).
- Hover a session → action buttons appear from right with gradient fade.
- All icons are monochrome SVGs (not emoji). Consistent across platforms.
- Pinned sessions show small gold star inline. Unpinned = no star, full title width.
- Active session has gold highlight (not blue). Overlay gradient matches.
- Double-click to rename → overlay hides during rename.
### Sprint 17: Workspace + Slash Commands + Send Key
- Navigate into a subdirectory. Breadcrumb bar appears with clickable segments.
- Up button in panel header navigates to parent. Hidden at root.
- Type `/` in composer → autocomplete dropdown appears. Arrow keys navigate.
- Type `/help` → lists all commands. `/clear` clears conversation. `/model` switches.
- Settings panel: change send key to Ctrl+Enter. Verify Enter inserts newline.
### Sprint 18: Thinking + Tree View + Preview Fix
- View a file in workspace. Click a breadcrumb or folder → preview closes automatically.
- Click a directory toggle arrow (▸) → expands in-place showing children.
- Click again (▾) → collapses. Double-click navigates into it (breadcrumb view).
- If model returns thinking blocks (Claude extended thinking), verify collapsible gold card appears above response.
### Sprint 19: Auth + Security
- No password set: everything works as normal. No login page.
- Set `HERMES_WEBUI_PASSWORD=test` env var. Restart. All pages redirect to `/login`.
- Login page: minimal card, password field, "Sign in" button.
- Enter correct password → redirected to `/`. Cookie set (24h).
- Enter wrong password → error message, stay on login page.
- Settings panel: set password via "Access Password" field. Auth activates.
- "Sign Out" button visible when auth active. Click → redirected to /login.
- API calls without auth cookie → 401 JSON response.
- Check response headers: `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`.
### Sprint 20: Voice Input + Send Button
- Mic button visible in composer (Chrome/Edge). Hidden in Firefox.
- Tap mic → button turns red with pulse, "Listening..." indicator appears.
- Speak → live transcription appears in textarea.
- Stop speaking → auto-stops after ~2s silence. Text stays editable.
- Tap mic again or Send → stops recording, sends text.
- Type text, then tap mic → spoken text appends to existing text (doesn't replace).
- Send button hidden when textarea is empty. Appears with pop-in animation when typing.
- Send button is icon-only circle (no "Send" text label). Blue with glow.
- Attach a file with no text → send button appears.
- Send message → button disappears after textarea clears.
- While agent is responding → send button hidden.
### Sprint 21: Mobile Responsive + Docker
- Open on mobile viewport (<640px): hamburger icon visible in topbar.
- Tap hamburger → sidebar slides in from left with backdrop overlay.
- Tap outside sidebar → closes. Tap a session → closes and loads session.
- Bottom navigation bar: 5 tabs (Chat, Tasks, Skills, Memory, Spaces).
- Tap "Tasks" in bottom nav → sidebar opens showing Tasks panel.
- Tap "Chat" in bottom nav → sidebar closes (chat is in main area).
- Files button in topbar → right panel slides in from right.
- All touch targets are at least 44px (session items, buttons, icons).
- Desktop viewport (>640px): no hamburger, no bottom nav, no mobile elements.
- Docker: `docker compose up -d` starts server on port 8787.
- Docker: session data persists across container restarts (named volume).
### Sprint 22: Multi-Profile Support
- Profile chip in topbar (purple accent). Click → dropdown with all profiles.
- Dropdown shows gateway status dots, model info, skill count per profile.
- Click a profile → switches; model dropdown, skills, memory, cron refresh.
- "Manage profiles" link opens Profiles sidebar panel.
- Profiles panel: cards with name, model, provider, skill count, API key status.
- "Use" button switches profile. Delete button removes non-default profiles.
- "+ New profile" form: name validation (lowercase + hyphens), clone config checkbox.
- Create profile → appears in list and dropdown.
- Delete profile → confirm dialog. Auto-switches to default if deleting active.
- Attempt switch while agent busy → blocked with toast message.
- With hermes-agent not installed → only default profile shown, graceful fallback.
---
*Last updated: Sprint 22 / v0.24, April 3, 2026*
*Total automated tests: 415 (392 passing, 23 pre-existing failures)*
*Regression gate: tests/test_regressions.py (23 tests)*
*Run: pytest tests/ -v --timeout=60*
*Source: <repo>/*

149
api/auth.py Normal file
View File

@@ -0,0 +1,149 @@
"""
Hermes Web UI -- Optional password authentication.
Off by default. Enable by setting HERMES_WEBUI_PASSWORD env var
or configuring a password in the Settings panel.
"""
import hashlib
import hmac
import http.cookies
import os
import secrets
import time
from api.config import STATE_DIR, load_settings
# ── Public paths (no auth required) ─────────────────────────────────────────
PUBLIC_PATHS = frozenset({
'/login', '/health', '/favicon.ico',
'/api/auth/login', '/api/auth/status',
})
COOKIE_NAME = 'hermes_session'
SESSION_TTL = 86400 # 24 hours
# Active sessions: token -> expiry timestamp
_sessions = {}
def _signing_key():
"""Derive a stable signing key from STATE_DIR."""
return hashlib.sha256(str(STATE_DIR).encode()).digest()
def _hash_password(password):
"""SHA-256 hash with a salt derived from STATE_DIR."""
salt = str(STATE_DIR).encode()
return hashlib.sha256(salt + password.encode()).hexdigest()
def get_password_hash():
"""Return the active password hash, or None if auth is disabled.
Priority: env var > settings.json."""
env_pw = os.getenv('HERMES_WEBUI_PASSWORD', '').strip()
if env_pw:
return _hash_password(env_pw)
settings = load_settings()
return settings.get('password_hash') or None
def is_auth_enabled():
"""True if a password is configured (env var or settings)."""
return get_password_hash() is not None
def verify_password(plain):
"""Verify a plaintext password against the stored hash."""
expected = get_password_hash()
if not expected:
return False
return hmac.compare_digest(_hash_password(plain), expected)
def create_session():
"""Create a new auth session. Returns signed cookie value."""
token = secrets.token_hex(32)
_sessions[token] = time.time() + SESSION_TTL
sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:16]
return f"{token}.{sig}"
def verify_session(cookie_value):
"""Verify a signed session cookie. Returns True if valid and not expired."""
if not cookie_value or '.' not in cookie_value:
return False
token, sig = cookie_value.rsplit('.', 1)
expected_sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:16]
if not hmac.compare_digest(sig, expected_sig):
return False
expiry = _sessions.get(token)
if not expiry or time.time() > expiry:
_sessions.pop(token, None)
return False
return True
def invalidate_session(cookie_value):
"""Remove a session token."""
if cookie_value and '.' in cookie_value:
token = cookie_value.rsplit('.', 1)[0]
_sessions.pop(token, None)
def parse_cookie(handler):
"""Extract the auth cookie from the request headers."""
cookie_header = handler.headers.get('Cookie', '')
if not cookie_header:
return None
cookie = http.cookies.SimpleCookie()
try:
cookie.load(cookie_header)
except http.cookies.CookieError:
return None
morsel = cookie.get(COOKIE_NAME)
return morsel.value if morsel else None
def check_auth(handler, parsed):
"""Check if request is authorized. Returns True if OK.
If not authorized, sends 401 (API) or 302 redirect (page) and returns False."""
if not is_auth_enabled():
return True
# Public paths don't require auth
if parsed.path in PUBLIC_PATHS or parsed.path.startswith('/static/'):
return True
# Check session cookie
cookie_val = parse_cookie(handler)
if cookie_val and verify_session(cookie_val):
return True
# Not authorized
if parsed.path.startswith('/api/'):
handler.send_response(401)
handler.send_header('Content-Type', 'application/json')
handler.end_headers()
handler.wfile.write(b'{"error":"Authentication required"}')
else:
handler.send_response(302)
handler.send_header('Location', '/login')
handler.end_headers()
return False
def set_auth_cookie(handler, cookie_value):
"""Set the auth cookie on the response."""
cookie = http.cookies.SimpleCookie()
cookie[COOKIE_NAME] = cookie_value
cookie[COOKIE_NAME]['httponly'] = True
cookie[COOKIE_NAME]['samesite'] = 'Lax'
cookie[COOKIE_NAME]['path'] = '/'
cookie[COOKIE_NAME]['max-age'] = str(SESSION_TTL)
handler.send_header('Set-Cookie', cookie[COOKIE_NAME].OutputString())
def clear_auth_cookie(handler):
"""Clear the auth cookie on the response."""
cookie = http.cookies.SimpleCookie()
cookie[COOKIE_NAME] = ''
cookie[COOKIE_NAME]['httponly'] = True
cookie[COOKIE_NAME]['path'] = '/'
cookie[COOKIE_NAME]['max-age'] = '0'
handler.send_header('Set-Cookie', cookie[COOKIE_NAME].OutputString())

View File

@@ -134,17 +134,44 @@ if _AGENT_DIR is not None:
else:
_HERMES_FOUND = False
# ── Config file (optional YAML) ──────────────────────────────────────────────
CONFIG_PATH = Path(os.getenv(
'HERMES_CONFIG_PATH',
str(HOME / '.hermes' / 'config.yaml')
)).expanduser()
# ── Config file (reloadable -- supports profile switching) ──────────────────
_cfg_cache = {}
_cfg_lock = threading.Lock()
try:
import yaml as _yaml
cfg = _yaml.safe_load(CONFIG_PATH.read_text()) if CONFIG_PATH.exists() else {}
except Exception:
cfg = {}
def _get_config_path() -> Path:
"""Return config.yaml path for the active profile."""
env_override = os.getenv('HERMES_CONFIG_PATH')
if env_override:
return Path(env_override).expanduser()
try:
from api.profiles import get_active_hermes_home
return get_active_hermes_home() / 'config.yaml'
except ImportError:
return HOME / '.hermes' / 'config.yaml'
def get_config() -> dict:
"""Return the cached config dict, loading from disk if needed."""
if not _cfg_cache:
reload_config()
return _cfg_cache
def reload_config():
"""Reload config.yaml from the active profile's directory."""
with _cfg_lock:
_cfg_cache.clear()
config_path = _get_config_path()
try:
import yaml as _yaml
if config_path.exists():
loaded = _yaml.safe_load(config_path.read_text())
if isinstance(loaded, dict):
_cfg_cache.update(loaded)
except Exception:
pass
# Initial load
reload_config()
cfg = _cfg_cache # alias for backward compat with existing references
# ── Default workspace discovery ───────────────────────────────────────────────
def _discover_default_workspace() -> Path:
@@ -183,7 +210,7 @@ def print_startup_config():
f' state dir : {STATE_DIR}',
f' workspace : {DEFAULT_WORKSPACE}',
f' host:port : {HOST}:{PORT}',
f' config file : {CONFIG_PATH} {"(found)" if CONFIG_PATH.exists() else "(not found, using defaults)"}',
f' config file : {_get_config_path()} {"(found)" if _get_config_path().exists() else "(not found, using defaults)"}',
'',
]
print('\n'.join(lines), flush=True)
@@ -234,11 +261,12 @@ MIME_MAP = {
}
# ── Toolsets (from config.yaml or hardcoded default) ─────────────────────────
CLI_TOOLSETS = cfg.get('platform_toolsets', {}).get('cli', [
_DEFAULT_TOOLSETS = [
'browser', 'clarify', 'code_execution', 'cronjob', 'delegation', 'file',
'image_gen', 'memory', 'session_search', 'skills', 'terminal', 'todo',
'web', 'webhook',
])
]
CLI_TOOLSETS = get_config().get('platform_toolsets', {}).get('cli', _DEFAULT_TOOLSETS)
# ── Model / provider discovery ───────────────────────────────────────────────
@@ -345,15 +373,16 @@ def resolve_model_provider(model_id: str):
if '/' in model_id:
prefix, bare = model_id.split('/', 1)
# If prefix matches config provider, strip it and use that provider directly
# If prefix matches config provider exactly, strip it and use that provider directly.
# e.g. config=anthropic, model=anthropic/claude-... → bare name to anthropic API
if config_provider and prefix == config_provider:
return bare, config_provider, config_base_url
# If the config provider is openrouter (or unset/None), pass the full
# provider/model string through -- OpenRouter uses this as its model ID.
# Only strip the prefix and switch to a direct-API provider when the
# config is explicitly set to that direct provider.
if config_provider and config_provider != 'openrouter' and prefix in _PROVIDER_MODELS:
return bare, prefix, None
# If prefix does NOT match config provider, the user picked a cross-provider model
# from the OpenRouter dropdown (e.g. config=anthropic but picked openai/gpt-5.4-mini).
# In this case always route through openrouter with the full provider/model string.
# Never strip the prefix and try a direct-API call to a provider whose key may not exist.
if prefix in _PROVIDER_MODELS and prefix != config_provider:
return model_id, 'openrouter', None
return model_id, config_provider, config_base_url
@@ -396,7 +425,11 @@ def get_available_models() -> dict:
# 3. Try to read auth store for active provider (if hermes is installed)
if not active_provider:
auth_store_path = HOME / '.hermes' / 'auth.json'
try:
from api.profiles import get_active_hermes_home as _gah
auth_store_path = _gah() / 'auth.json'
except ImportError:
auth_store_path = HOME / '.hermes' / 'auth.json'
if auth_store_path.exists():
try:
import json as _j
@@ -406,7 +439,11 @@ def get_available_models() -> dict:
pass
# 4. Check for API keys that imply available providers
hermes_env_path = HOME / '.hermes' / '.env'
try:
from api.profiles import get_active_hermes_home as _gah2
hermes_env_path = _gah2() / '.env'
except ImportError:
hermes_env_path = HOME / '.hermes' / '.env'
env_keys = {}
if hermes_env_path.exists():
try:
@@ -595,6 +632,9 @@ _SETTINGS_DEFAULTS = {
'default_model': DEFAULT_MODEL,
'default_workspace': str(DEFAULT_WORKSPACE),
'send_key': 'enter', # 'enter' or 'ctrl+enter'
'show_token_usage': False, # show input/output token badge below assistant messages
'show_cli_sessions': False, # merge CLI sessions from state.db into the sidebar
'password_hash': None, # SHA-256 hash; None = auth disabled
}
def load_settings() -> dict:
@@ -609,19 +649,32 @@ def load_settings() -> dict:
pass
return settings
_SETTINGS_ALLOWED_KEYS = set(_SETTINGS_DEFAULTS.keys())
_SETTINGS_ALLOWED_KEYS = set(_SETTINGS_DEFAULTS.keys()) - {'password_hash'}
_SETTINGS_ENUM_VALUES = {
'send_key': {'enter', 'ctrl+enter'},
}
_SETTINGS_BOOL_KEYS = {'show_token_usage', 'show_cli_sessions'}
def save_settings(settings: dict) -> dict:
"""Save settings to disk. Returns the merged settings. Ignores unknown keys."""
import hashlib as _hl
current = load_settings()
# Handle _set_password: hash and store as password_hash
raw_pw = settings.pop('_set_password', None)
if raw_pw and isinstance(raw_pw, str) and raw_pw.strip():
salt = str(STATE_DIR).encode()
current['password_hash'] = _hl.sha256(salt + raw_pw.strip().encode()).hexdigest()
# Handle _clear_password: explicitly disable auth
if settings.pop('_clear_password', False):
current['password_hash'] = None
for k, v in settings.items():
if k in _SETTINGS_ALLOWED_KEYS:
# Validate enum-constrained keys
if k in _SETTINGS_ENUM_VALUES and v not in _SETTINGS_ENUM_VALUES[k]:
continue
# Coerce bool keys
if k in _SETTINGS_BOOL_KEYS:
v = bool(v)
current[k] = v
SETTINGS_FILE.write_text(
json.dumps(current, ensure_ascii=False, indent=2),
@@ -645,3 +698,11 @@ if SETTINGS_FILE.exists():
# ── SESSIONS in-memory cache (LRU OrderedDict) ───────────────────────────────
SESSIONS: collections.OrderedDict = collections.OrderedDict()
# ── Profile state initialisation ────────────────────────────────────────────
# Must run after all imports are resolved to correctly patch module-level caches
try:
from api.profiles import init_profile_state
init_profile_state()
except ImportError:
pass # hermes_cli not available -- default profile only

View File

@@ -25,6 +25,13 @@ def safe_resolve(root: Path, requested: str) -> Path:
return resolved
def _security_headers(handler):
"""Add security headers to every response."""
handler.send_header('X-Content-Type-Options', 'nosniff')
handler.send_header('X-Frame-Options', 'DENY')
handler.send_header('Referrer-Policy', 'same-origin')
def j(handler, payload, status=200):
"""Send a JSON response."""
body = _json.dumps(payload, ensure_ascii=False, indent=2).encode('utf-8')
@@ -32,6 +39,7 @@ def j(handler, payload, status=200):
handler.send_header('Content-Type', 'application/json; charset=utf-8')
handler.send_header('Content-Length', str(len(body)))
handler.send_header('Cache-Control', 'no-store')
_security_headers(handler)
handler.end_headers()
handler.wfile.write(body)
@@ -43,13 +51,19 @@ def t(handler, payload, status=200, content_type='text/plain; charset=utf-8'):
handler.send_header('Content-Type', content_type)
handler.send_header('Content-Length', str(len(body)))
handler.send_header('Cache-Control', 'no-store')
_security_headers(handler)
handler.end_headers()
handler.wfile.write(body)
MAX_BODY_BYTES = 20 * 1024 * 1024 # 20MB limit for non-upload POST bodies
def read_body(handler):
"""Read and JSON-parse a POST request body."""
"""Read and JSON-parse a POST request body (capped at 20MB)."""
length = int(handler.headers.get('Content-Length', 0))
if length > MAX_BODY_BYTES:
raise ValueError(f'Request body too large ({length} bytes, max {MAX_BODY_BYTES})')
raw = handler.rfile.read(length) if length else b'{}'
try:
return _json.loads(raw)

View File

@@ -10,7 +10,7 @@ from pathlib import Path
import api.config as _cfg
from api.config import (
SESSION_DIR, SESSION_INDEX_FILE, SESSIONS, SESSIONS_MAX,
LOCK, DEFAULT_WORKSPACE, DEFAULT_MODEL, PROJECTS_FILE
LOCK, DEFAULT_WORKSPACE, DEFAULT_MODEL, PROJECTS_FILE, HOME
)
from api.workspace import get_last_workspace
@@ -34,17 +34,65 @@ def _write_session_index():
class Session:
def __init__(self, session_id=None, title='Untitled', workspace=str(DEFAULT_WORKSPACE), model=DEFAULT_MODEL, messages=None, created_at=None, updated_at=None, tool_calls=None, pinned=False, archived=False, project_id=None, **kwargs):
self.session_id = session_id or uuid.uuid4().hex[:12]; self.title = title; self.workspace = str(Path(workspace).expanduser().resolve()); self.model = model; self.messages = messages or []; self.tool_calls = tool_calls or []; self.created_at = created_at or time.time(); self.updated_at = updated_at or time.time(); self.pinned = bool(pinned); self.archived = bool(archived); self.project_id = project_id or None
def __init__(self, session_id=None, title='Untitled',
workspace=str(DEFAULT_WORKSPACE), model=DEFAULT_MODEL,
messages=None, created_at=None, updated_at=None,
tool_calls=None, pinned=False, archived=False,
project_id=None, profile=None,
input_tokens=0, output_tokens=0, estimated_cost=None,
**kwargs):
self.session_id = session_id or uuid.uuid4().hex[:12]
self.title = title
self.workspace = str(Path(workspace).expanduser().resolve())
self.model = model
self.messages = messages or []
self.tool_calls = tool_calls or []
self.created_at = created_at or time.time()
self.updated_at = updated_at or time.time()
self.pinned = bool(pinned)
self.archived = bool(archived)
self.project_id = project_id or None
self.profile = profile
self.input_tokens = input_tokens or 0
self.output_tokens = output_tokens or 0
self.estimated_cost = estimated_cost
@property
def path(self): return SESSION_DIR / f'{self.session_id}.json'
def save(self): self.updated_at = time.time(); self.path.write_text(json.dumps(self.__dict__, ensure_ascii=False, indent=2), encoding='utf-8'); _write_session_index()
def path(self):
return SESSION_DIR / f'{self.session_id}.json'
def save(self):
self.updated_at = time.time()
self.path.write_text(
json.dumps(self.__dict__, ensure_ascii=False, indent=2),
encoding='utf-8',
)
_write_session_index()
@classmethod
def load(cls, sid):
p = SESSION_DIR / f'{sid}.json'
if not p.exists(): return None
if not p.exists():
return None
return cls(**json.loads(p.read_text(encoding='utf-8')))
def compact(self): return {'session_id': self.session_id, 'title': self.title, 'workspace': self.workspace, 'model': self.model, 'message_count': len(self.messages), 'created_at': self.created_at, 'updated_at': self.updated_at, 'pinned': self.pinned, 'archived': self.archived, 'project_id': self.project_id}
def compact(self):
return {
'session_id': self.session_id,
'title': self.title,
'workspace': self.workspace,
'model': self.model,
'message_count': len(self.messages),
'created_at': self.created_at,
'updated_at': self.updated_at,
'pinned': self.pinned,
'archived': self.archived,
'project_id': self.project_id,
'profile': self.profile,
'input_tokens': self.input_tokens,
'output_tokens': self.output_tokens,
'estimated_cost': self.estimated_cost,
}
def get_session(sid):
with LOCK:
@@ -63,7 +111,12 @@ def get_session(sid):
def new_session(workspace=None, model=None):
# Use _cfg.DEFAULT_MODEL (not the import-time snapshot) so save_settings() changes take effect
s = Session(workspace=workspace or get_last_workspace(), model=model or _cfg.DEFAULT_MODEL)
try:
from api.profiles import get_active_profile_name
_profile = get_active_profile_name()
except ImportError:
_profile = None
s = Session(workspace=workspace or get_last_workspace(), model=model or _cfg.DEFAULT_MODEL, profile=_profile)
with LOCK:
SESSIONS[s.session_id] = s
SESSIONS.move_to_end(s.session_id)
@@ -85,6 +138,11 @@ def all_sessions():
result = sorted(index_map.values(), key=lambda s: (s.get('pinned', False), s['updated_at']), reverse=True)
# Hide empty Untitled sessions from the UI (created by tests, page refreshes, etc.)
result = [s for s in result if not (s.get('title','Untitled')=='Untitled' and s.get('message_count',0)==0)]
# Backfill: sessions created before Sprint 22 have no profile tag.
# Attribute them to 'default' so the client profile filter works correctly.
for s in result:
if not s.get('profile'):
s['profile'] = 'default'
return result
except Exception:
pass # fall through to full scan
@@ -100,7 +158,11 @@ def all_sessions():
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)
return [s.compact() for s in out if not (s.title=='Untitled' and len(s.messages)==0)]
result = [s.compact() for s in out if not (s.title=='Untitled' and len(s.messages)==0)]
for s in result:
if not s.get('profile'):
s['profile'] = 'default'
return result
def title_from(messages, fallback='Untitled'):
@@ -130,3 +192,147 @@ def load_projects():
def save_projects(projects):
"""Write project list to disk."""
PROJECTS_FILE.write_text(json.dumps(projects, ensure_ascii=False, indent=2), encoding='utf-8')
def import_cli_session(session_id, title, messages, model='unknown', profile=None):
"""Create a new WebUI session populated with CLI messages.
Returns the Session object.
"""
s = Session(
session_id=session_id,
title=title,
workspace=get_last_workspace(),
model=model,
messages=messages,
profile=profile,
)
s.save()
return s
# ── CLI session bridge ──────────────────────────────────────────────────────
def get_cli_sessions():
"""Read CLI sessions from the agent's SQLite store and return them as
dicts in a format the WebUI sidebar can render alongside local sessions.
Returns empty list if the SQLite DB is missing, the sqlite3 module is
unavailable, or any error occurs -- the bridge is purely additive and never
crashes the WebUI.
"""
import os
cli_sessions = []
try:
import sqlite3
except ImportError:
return cli_sessions
# Use the active WebUI profile's HERMES_HOME to find state.db.
# The active profile is determined by what the user has selected in the UI
# (stored in the server's runtime config). This means:
# - default profile -> ~/.hermes/state.db
# - named profile X -> ~/.hermes/profiles/X/state.db
# We resolve the active profile's home directory rather than just using
# HERMES_HOME (which is the server's launch profile, not necessarily the
# active one after a profile switch).
try:
from api.profiles import get_active_hermes_home
hermes_home = Path(get_active_hermes_home()).expanduser().resolve()
except Exception:
hermes_home = Path(os.getenv('HERMES_HOME', str(HOME / '.hermes'))).expanduser().resolve()
db_path = hermes_home / 'state.db'
if not db_path.exists():
return cli_sessions
# Try to resolve the active CLI profile so imported sessions integrate
# with the WebUI profile filter (available since Sprint 22).
try:
from api.profiles import get_active_profile_name
_cli_profile = get_active_profile_name()
except ImportError:
_cli_profile = None # older agent -- fall back to no profile
try:
with sqlite3.connect(str(db_path)) as conn:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("""
SELECT s.id, s.title, s.model, s.message_count,
s.started_at, s.source,
MAX(m.timestamp) AS last_activity
FROM sessions s
LEFT JOIN messages m ON m.session_id = s.id
GROUP BY s.id
ORDER BY COALESCE(MAX(m.timestamp), s.started_at) DESC
LIMIT 200
""")
for row in cur.fetchall():
sid = row['id']
raw_ts = row['last_activity'] or row['started_at']
# Prefer the CLI session's own profile from the DB; fall back to
# the active CLI profile so sidebar filtering works either way.
profile = _cli_profile # CLI DB has no profile column; use active profile
cli_sessions.append({
'session_id': sid,
'title': row['title'] or 'CLI Session',
'workspace': str(get_last_workspace()),
'model': row['model'] or 'unknown',
'message_count': row['message_count'] or 0,
'created_at': row['started_at'],
'updated_at': raw_ts,
'pinned': False,
'archived': False,
'project_id': None,
'profile': profile,
'source_tag': 'cli',
'is_cli_session': True,
})
except Exception:
# DB schema changed, locked, or corrupted -- silently degrade
return []
return cli_sessions
def get_cli_session_messages(sid):
"""Read messages for a single CLI session from the SQLite store.
Returns a list of {role, content, timestamp} dicts.
Returns empty list on any error.
"""
import os
try:
import sqlite3
except ImportError:
return []
try:
from api.profiles import get_active_hermes_home
hermes_home = Path(get_active_hermes_home()).expanduser().resolve()
except Exception:
hermes_home = Path(os.getenv('HERMES_HOME', str(HOME / '.hermes'))).expanduser().resolve()
db_path = hermes_home / 'state.db'
if not db_path.exists():
return []
try:
with sqlite3.connect(str(db_path)) as conn:
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("""
SELECT role, content, timestamp
FROM messages
WHERE session_id = ?
ORDER BY timestamp ASC
""", (sid,))
msgs = []
for row in cur.fetchall():
msgs.append({
'role': row['role'],
'content': row['content'],
'timestamp': row['timestamp'],
})
except Exception:
return []
return msgs

366
api/profiles.py Normal file
View File

@@ -0,0 +1,366 @@
"""
Hermes Web UI -- Profile state management.
Wraps hermes_cli.profiles to provide profile switching for the web UI.
The web UI maintains a process-level "active profile" that determines which
HERMES_HOME directory is used for config, skills, memory, cron, and API keys.
Profile switches update os.environ['HERMES_HOME'] and monkey-patch module-level
cached paths in hermes-agent modules (skills_tool, cron/jobs) that snapshot
HERMES_HOME at import time.
"""
import json
import os
import re
import shutil
import threading
from pathlib import Path
# ── Constants (match hermes_cli.profiles upstream) ─────────────────────────
_PROFILE_ID_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{0,63}$')
_PROFILE_DIRS = [
'memories', 'sessions', 'skills', 'skins',
'logs', 'plans', 'workspace', 'cron',
]
_CLONE_CONFIG_FILES = ['config.yaml', '.env', 'SOUL.md']
# ── Module state ────────────────────────────────────────────────────────────
_active_profile = 'default'
_profile_lock = threading.Lock()
def _resolve_base_hermes_home() -> Path:
"""Return the BASE ~/.hermes directory — the root that contains profiles/.
This is intentionally distinct from HERMES_HOME, which tracks the *active
profile's* home and changes on every profile switch. The base dir must
always point to the top-level .hermes regardless of which profile is active.
Resolution order:
1. HERMES_BASE_HOME env var (set explicitly, highest priority)
2. HERMES_HOME env var — but only if it does NOT look like a profile subdir
(i.e. its parent is not named 'profiles'). This handles test isolation
where HERMES_HOME is set to an isolated test state dir.
3. ~/.hermes (always-correct default)
The bug this prevents: if HERMES_HOME has already been mutated to
/home/user/.hermes/profiles/webui (by init_profile_state at startup),
reading it here would make _DEFAULT_HERMES_HOME point to that subdir,
causing switch_profile('webui') to look for
/home/user/.hermes/profiles/webui/profiles/webui — which doesn't exist.
"""
# Explicit override for tests or unusual setups
base_override = os.getenv('HERMES_BASE_HOME', '').strip()
if base_override:
return Path(base_override).expanduser()
hermes_home = os.getenv('HERMES_HOME', '').strip()
if hermes_home:
p = Path(hermes_home).expanduser()
# If HERMES_HOME points to a profiles/ subdir, walk up two levels to the base
if p.parent.name == 'profiles':
return p.parent.parent
# Otherwise trust it (e.g. test isolation sets HERMES_HOME to TEST_STATE_DIR)
return p
return Path.home() / '.hermes'
_DEFAULT_HERMES_HOME = _resolve_base_hermes_home()
def _read_active_profile_file() -> str:
"""Read the sticky active profile from ~/.hermes/active_profile."""
ap_file = _DEFAULT_HERMES_HOME / 'active_profile'
if ap_file.exists():
try:
name = ap_file.read_text().strip()
if name:
return name
except Exception:
pass
return 'default'
# ── Public API ──────────────────────────────────────────────────────────────
def get_active_profile_name() -> str:
"""Return the currently active profile name."""
return _active_profile
def get_active_hermes_home() -> Path:
"""Return the HERMES_HOME path for the currently active profile."""
if _active_profile == 'default':
return _DEFAULT_HERMES_HOME
profile_dir = _DEFAULT_HERMES_HOME / 'profiles' / _active_profile
if profile_dir.is_dir():
return profile_dir
return _DEFAULT_HERMES_HOME
def _set_hermes_home(home: Path):
"""Set HERMES_HOME env var and monkey-patch cached module-level paths."""
os.environ['HERMES_HOME'] = str(home)
# Patch skills_tool module-level cache (snapshots HERMES_HOME at import)
try:
import tools.skills_tool as _sk
_sk.HERMES_HOME = home
_sk.SKILLS_DIR = home / 'skills'
except (ImportError, AttributeError):
pass
# Patch cron/jobs module-level cache
try:
import cron.jobs as _cj
_cj.HERMES_DIR = home
_cj.CRON_DIR = home / 'cron'
_cj.JOBS_FILE = _cj.CRON_DIR / 'jobs.json'
_cj.OUTPUT_DIR = _cj.CRON_DIR / 'output'
except (ImportError, AttributeError):
pass
def _reload_dotenv(home: Path):
"""Load .env from the profile dir into os.environ (additive)."""
env_path = home / '.env'
if not env_path.exists():
return
try:
for line in env_path.read_text().splitlines():
line = line.strip()
if line and not line.startswith('#') and '=' in line:
k, v = line.split('=', 1)
k = k.strip()
v = v.strip().strip('"').strip("'")
if k and v:
os.environ[k] = v
except Exception:
pass
def init_profile_state():
"""Initialize profile state at server startup.
Reads ~/.hermes/active_profile, sets HERMES_HOME env var, patches
module-level cached paths. Called once from config.py after imports.
"""
global _active_profile
_active_profile = _read_active_profile_file()
home = get_active_hermes_home()
_set_hermes_home(home)
_reload_dotenv(home)
def switch_profile(name: str) -> dict:
"""Switch the active profile.
Validates the profile exists, updates process state, patches module caches,
reloads .env, and reloads config.yaml.
Returns: {'profiles': [...], 'active': name}
Raises ValueError if profile doesn't exist or agent is busy.
"""
global _active_profile
# Import here to avoid circular import at module load
from api.config import STREAMS, STREAMS_LOCK, reload_config
# Block if agent is running
with STREAMS_LOCK:
if len(STREAMS) > 0:
raise RuntimeError(
'Cannot switch profiles while an agent is running. '
'Cancel or wait for it to finish.'
)
# Resolve profile directory
if name == 'default':
home = _DEFAULT_HERMES_HOME
else:
home = _DEFAULT_HERMES_HOME / 'profiles' / name
if not home.is_dir():
raise ValueError(f"Profile '{name}' does not exist.")
with _profile_lock:
_active_profile = name
_set_hermes_home(home)
_reload_dotenv(home)
# Write sticky default for CLI consistency
try:
ap_file = _DEFAULT_HERMES_HOME / 'active_profile'
ap_file.write_text(name if name != 'default' else '')
except Exception:
pass
# Reload config.yaml from the new profile
reload_config()
# Return profile-specific defaults so frontend can apply them
from api.workspace import get_last_workspace
from api.config import get_config
cfg = get_config()
model_cfg = cfg.get('model', {})
default_model = None
if isinstance(model_cfg, str):
default_model = model_cfg
elif isinstance(model_cfg, dict):
default_model = model_cfg.get('default')
return {
'profiles': list_profiles_api(),
'active': name,
'default_model': default_model,
'default_workspace': get_last_workspace(),
}
def list_profiles_api() -> list:
"""List all profiles with metadata, serialized for JSON response."""
try:
from hermes_cli.profiles import list_profiles
infos = list_profiles()
except ImportError:
# hermes_cli not available -- return just the default
return [_default_profile_dict()]
active = _active_profile
result = []
for p in infos:
result.append({
'name': p.name,
'path': str(p.path),
'is_default': p.is_default,
'is_active': p.name == active,
'gateway_running': p.gateway_running,
'model': p.model,
'provider': p.provider,
'has_env': p.has_env,
'skill_count': p.skill_count,
})
return result
def _default_profile_dict() -> dict:
"""Fallback profile dict when hermes_cli is not importable."""
return {
'name': 'default',
'path': str(_DEFAULT_HERMES_HOME),
'is_default': True,
'is_active': True,
'gateway_running': False,
'model': None,
'provider': None,
'has_env': (_DEFAULT_HERMES_HOME / '.env').exists(),
'skill_count': 0,
}
def _validate_profile_name(name: str):
"""Validate profile name format (matches hermes_cli.profiles upstream)."""
if name == 'default':
raise ValueError("Cannot create a profile named 'default' -- it is the built-in profile.")
# Use fullmatch (not match) so a trailing newline can't sneak past the $ anchor
if not _PROFILE_ID_RE.fullmatch(name):
raise ValueError(
f"Invalid profile name {name!r}. "
"Must match [a-z0-9][a-z0-9_-]{0,63}"
)
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)."""
profile_dir = _DEFAULT_HERMES_HOME / 'profiles' / name
if profile_dir.exists():
raise FileExistsError(f"Profile '{name}' already exists.")
# Bootstrap directory structure (exist_ok=False so a concurrent create raises)
profile_dir.mkdir(parents=True, exist_ok=False)
for subdir in _PROFILE_DIRS:
(profile_dir / subdir).mkdir(parents=True, exist_ok=True)
# Clone config files from source profile if requested
if clone_config and clone_from:
if clone_from == 'default':
source_dir = _DEFAULT_HERMES_HOME
else:
source_dir = _DEFAULT_HERMES_HOME / 'profiles' / clone_from
if source_dir.is_dir():
for filename in _CLONE_CONFIG_FILES:
src = source_dir / filename
if src.exists():
shutil.copy2(src, profile_dir / filename)
return profile_dir
def create_profile_api(name: str, clone_from: str = None,
clone_config: bool = False) -> dict:
"""Create a new profile. Returns the new profile info dict."""
_validate_profile_name(name)
# Defense-in-depth: validate clone_from here too, even though routes.py
# also validates it. Any caller that bypasses the HTTP layer gets protection.
if clone_from is not None and clone_from != 'default':
_validate_profile_name(clone_from)
try:
from hermes_cli.profiles import create_profile
create_profile(
name,
clone_from=clone_from,
clone_config=clone_config,
clone_all=False,
no_alias=True,
)
except ImportError:
_create_profile_fallback(name, clone_from, clone_config)
# Find and return the newly created profile info.
# When hermes_cli is not importable, list_profiles_api() also falls back
# to the stub default-only list and won't find the new profile by name.
# In that case, return a complete profile dict directly.
profile_path = _DEFAULT_HERMES_HOME / 'profiles' / name
for p in list_profiles_api():
if p['name'] == name:
return p
return {
'name': name,
'path': str(profile_path),
'is_default': False,
'is_active': _active_profile == name,
'gateway_running': False,
'model': None,
'provider': None,
'has_env': (profile_path / '.env').exists(),
'skill_count': 0,
}
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.")
# If deleting the active profile, switch to default first
if _active_profile == name:
try:
switch_profile('default')
except RuntimeError:
raise RuntimeError(
f"Cannot delete active profile '{name}' while an agent is running. "
"Cancel or wait for it to finish."
)
try:
from hermes_cli.profiles import delete_profile
delete_profile(name, yes=True)
except ImportError:
# Manual fallback: just remove the directory
import shutil
profile_dir = _DEFAULT_HERMES_HOME / 'profiles' / name
if profile_dir.is_dir():
shutil.rmtree(str(profile_dir))
else:
raise ValueError(f"Profile '{name}' does not exist.")
return {'ok': True, 'name': name}

View File

@@ -19,11 +19,12 @@ from api.config import (
IMAGE_EXTS, MD_EXTS, MIME_MAP, MAX_FILE_BYTES, MAX_UPLOAD_BYTES,
CHAT_LOCK, load_settings, save_settings,
)
from api.helpers import require, bad, safe_resolve, j, t, read_body
from api.helpers import require, bad, safe_resolve, j, t, read_body, _security_headers
from api.models import (
Session, get_session, new_session, all_sessions, title_from,
_write_session_index, SESSION_INDEX_FILE,
load_projects, save_projects,
load_projects, save_projects, import_cli_session,
get_cli_sessions, get_cli_session_messages,
)
from api.workspace import (
load_workspaces, save_workspaces, get_last_workspace, set_last_workspace,
@@ -52,6 +53,58 @@ except ImportError:
_permanent_approved = set()
# ── Login page (self-contained, no external deps) ────────────────────────────
_LOGIN_PAGE_HTML = '''<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Hermes — Sign in</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#1a1a2e;color:#e8e8f0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;
height:100vh;display:flex;align-items:center;justify-content:center}
.card{background:#16213e;border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:36px 32px;
width:320px;text-align:center;box-shadow:0 8px 32px rgba(0,0,0,.3)}
.logo{width:48px;height:48px;border-radius:12px;background:linear-gradient(145deg,#e8a030,#e94560);
display:flex;align-items:center;justify-content:center;font-weight:800;font-size:20px;color:#fff;
margin:0 auto 12px;box-shadow:0 2px 12px rgba(233,69,96,.3)}
h1{font-size:18px;font-weight:600;margin-bottom:4px}
.sub{font-size:12px;color:#8888aa;margin-bottom:24px}
input{width:100%;padding:10px 14px;border-radius:10px;border:1px solid rgba(255,255,255,.1);
background:rgba(255,255,255,.04);color:#e8e8f0;font-size:14px;outline:none;margin-bottom:14px;
transition:border-color .15s}
input:focus{border-color:rgba(124,185,255,.5);box-shadow:0 0 0 3px rgba(124,185,255,.1)}
button{width:100%;padding:10px;border-radius:10px;border:none;background:rgba(124,185,255,.15);
border:1px solid rgba(124,185,255,.3);color:#7cb9ff;font-size:14px;font-weight:600;cursor:pointer;
transition:all .15s}
button:hover{background:rgba(124,185,255,.25)}
.err{color:#e94560;font-size:12px;margin-top:10px;display:none}
</style></head><body>
<div class="card">
<div class="logo">H</div>
<h1>Hermes</h1>
<p class="sub">Enter your password to continue</p>
<form onsubmit="return doLogin(event)">
<input type="password" id="pw" placeholder="Password" autofocus>
<button type="submit">Sign in</button>
</form>
<div class="err" id="err"></div>
</div>
<script>
async function doLogin(e){
e.preventDefault();
const pw=document.getElementById('pw').value;
const err=document.getElementById('err');
err.style.display='none';
try{
const res=await fetch('/api/auth/login',{method:'POST',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({password:pw}),credentials:'include'});
const data=await res.json();
if(res.ok&&data.ok){window.location.href='/';}
else{err.textContent=data.error||'Invalid password';err.style.display='block';}
}catch(ex){err.textContent='Connection failed';err.style.display='block';}
}
</script></body></html>'''
# ── GET routes ────────────────────────────────────────────────────────────────
def handle_get(handler, parsed):
@@ -61,6 +114,17 @@ def handle_get(handler, parsed):
return t(handler, _INDEX_HTML_PATH.read_text(encoding='utf-8'),
content_type='text/html; charset=utf-8')
if parsed.path == '/login':
return t(handler, _LOGIN_PAGE_HTML, content_type='text/html; charset=utf-8')
if parsed.path == '/api/auth/status':
from api.auth import is_auth_enabled, parse_cookie, verify_session
logged_in = False
if is_auth_enabled():
cv = parse_cookie(handler)
logged_in = bool(cv and verify_session(cv))
return j(handler, {'auth_enabled': is_auth_enabled(), 'logged_in': logged_in})
if parsed.path == '/favicon.ico':
handler.send_response(204); handler.end_headers(); return True
@@ -76,7 +140,10 @@ def handle_get(handler, parsed):
return j(handler, get_available_models())
if parsed.path == '/api/settings':
return j(handler, load_settings())
settings = load_settings()
# Never expose the stored password hash to clients
settings.pop('password_hash', None)
return j(handler, settings)
if parsed.path.startswith('/static/'):
return _serve_static(handler, parsed)
@@ -85,14 +152,52 @@ def handle_get(handler, parsed):
sid = parse_qs(parsed.query).get('session_id', [''])[0]
if not sid:
return j(handler, {'error': 'session_id is required'}, status=400)
s = get_session(sid)
return j(handler, {'session': s.compact() | {
'messages': s.messages,
'tool_calls': getattr(s, 'tool_calls', []),
}})
try:
s = get_session(sid)
return j(handler, {'session': s.compact() | {
'messages': s.messages,
'tool_calls': getattr(s, 'tool_calls', []),
}})
except KeyError:
# Not a WebUI session -- try CLI store
msgs = get_cli_session_messages(sid)
if msgs:
cli_meta = None
for cs in get_cli_sessions():
if cs['session_id'] == sid:
cli_meta = cs
break
sess = {
'session_id': sid,
'title': (cli_meta or {}).get('title', 'CLI Session'),
'workspace': (cli_meta or {}).get('workspace', ''),
'model': (cli_meta or {}).get('model', 'unknown'),
'message_count': len(msgs),
'created_at': (cli_meta or {}).get('created_at', 0),
'updated_at': (cli_meta or {}).get('updated_at', 0),
'pinned': False,
'archived': False,
'project_id': None,
'profile': (cli_meta or {}).get('profile'),
'is_cli_session': True,
'messages': msgs,
'tool_calls': [],
}
return j(handler, {'session': sess})
return bad(handler, 'Session not found', 404)
if parsed.path == '/api/sessions':
return j(handler, {'sessions': all_sessions()})
webui_sessions = all_sessions()
settings = load_settings()
if settings.get('show_cli_sessions'):
cli = get_cli_sessions()
webui_ids = {s['session_id'] for s in webui_sessions}
deduped_cli = [s for s in cli if s['session_id'] not in webui_ids]
else:
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)})
if parsed.path == '/api/projects':
return j(handler, {'projects': load_projects()})
@@ -157,17 +262,44 @@ def handle_get(handler, parsed):
return j(handler, {'skills': data.get('skills', [])})
if parsed.path == '/api/skills/content':
from tools.skills_tool import skill_view as _skill_view
name = parse_qs(parsed.query).get('name', [''])[0]
from tools.skills_tool import skill_view as _skill_view, SKILLS_DIR
qs = parse_qs(parsed.query)
name = qs.get('name', [''])[0]
if not name: return j(handler, {'error': 'name required'}, status=400)
file_path = qs.get('file', [''])[0]
if file_path:
# Serve a linked file from the skill directory
import re as _re
if _re.search(r'[*?\[\]]', name):
return bad(handler, 'Invalid skill name', 400)
skill_dir = None
for p in SKILLS_DIR.rglob(name):
if p.is_dir(): skill_dir = p; break
if not skill_dir: return bad(handler, 'Skill not found', 404)
target = (skill_dir / file_path).resolve()
try: target.relative_to(skill_dir.resolve())
except ValueError: return bad(handler, 'Invalid file path', 400)
if not target.exists() or not target.is_file():
return bad(handler, 'File not found', 404)
return j(handler, {'content': target.read_text(encoding='utf-8'), 'path': file_path})
raw = _skill_view(name)
data = json.loads(raw) if isinstance(raw, str) else raw
if 'linked_files' not in data: data['linked_files'] = {}
return j(handler, data)
# ── Memory API (GET) ──
if parsed.path == '/api/memory':
return _handle_memory_read(handler)
# ── Profile API (GET) ──
if parsed.path == '/api/profiles':
from api.profiles import list_profiles_api, get_active_profile_name
return j(handler, {'profiles': list_profiles_api(), 'active': get_active_profile_name()})
if parsed.path == '/api/profile/active':
from api.profiles import get_active_profile_name, get_active_hermes_home
return j(handler, {'name': get_active_profile_name(), 'path': str(get_active_hermes_home())})
return False # 404
@@ -306,9 +438,58 @@ def handle_post(handler, parsed):
if parsed.path == '/api/memory/write':
return _handle_memory_write(handler, body)
# ── Profile API (POST) ──
if parsed.path == '/api/profile/switch':
name = body.get('name', '').strip()
if not name: return bad(handler, 'name is required')
try:
from api.profiles import switch_profile
result = switch_profile(name)
return j(handler, result)
except (ValueError, FileNotFoundError) as e:
return bad(handler, str(e), 404)
except RuntimeError as e:
return bad(handler, str(e), 409)
if parsed.path == '/api/profile/create':
name = body.get('name', '').strip()
if not name: return bad(handler, 'name is required')
import re as _re
if not _re.match(r'^[a-z0-9][a-z0-9_-]{0,63}$', name):
return bad(handler, 'Invalid profile name: lowercase letters, numbers, hyphens, underscores only')
clone_from = body.get('clone_from')
if clone_from is not None:
clone_from = str(clone_from).strip()
if not _re.match(r'^[a-z0-9][a-z0-9_-]{0,63}$', clone_from):
return bad(handler, 'Invalid clone_from name')
try:
from api.profiles import create_profile_api
result = create_profile_api(
name,
clone_from=clone_from,
clone_config=bool(body.get('clone_config', False)),
)
return j(handler, {'ok': True, 'profile': result})
except (ValueError, FileExistsError, RuntimeError) as e:
return bad(handler, str(e))
if parsed.path == '/api/profile/delete':
name = body.get('name', '').strip()
if not name: return bad(handler, 'name is required')
try:
from api.profiles import delete_profile_api
result = delete_profile_api(name)
return j(handler, result)
except (ValueError, FileNotFoundError) as e:
return bad(handler, str(e))
except RuntimeError as e:
return bad(handler, str(e), 409)
# ── Settings (POST) ──
if parsed.path == '/api/settings':
return j(handler, save_settings(body))
saved = save_settings(body)
saved.pop('password_hash', None) # never expose hash to client
return j(handler, saved)
# ── Session pin (POST) ──
if parsed.path == '/api/session/pin':
@@ -400,6 +581,42 @@ def handle_post(handler, parsed):
if parsed.path == '/api/session/import':
return _handle_session_import(handler, body)
# ── CLI session import (POST) ──
if parsed.path == '/api/session/import_cli':
return _handle_session_import_cli(handler, body)
# ── Auth endpoints (POST) ──
if parsed.path == '/api/auth/login':
from api.auth import verify_password, create_session, set_auth_cookie, is_auth_enabled
if not is_auth_enabled():
return j(handler, {'ok': True, 'message': 'Auth not enabled'})
password = body.get('password', '')
if not verify_password(password):
return bad(handler, 'Invalid password', 401)
cookie_val = create_session()
handler.send_response(200)
handler.send_header('Content-Type', 'application/json')
handler.send_header('Cache-Control', 'no-store')
_security_headers(handler)
set_auth_cookie(handler, cookie_val)
handler.end_headers()
handler.wfile.write(json.dumps({'ok': True}).encode())
return True
if parsed.path == '/api/auth/logout':
from api.auth import clear_auth_cookie, invalidate_session, parse_cookie
cookie_val = parse_cookie(handler)
if cookie_val:
invalidate_session(cookie_val)
handler.send_response(200)
handler.send_header('Content-Type', 'application/json')
handler.send_header('Cache-Control', 'no-store')
_security_headers(handler)
clear_auth_cookie(handler)
handler.end_headers()
handler.wfile.write(json.dumps({'ok': True}).encode())
return True
return False # 404
@@ -631,7 +848,11 @@ def _handle_cron_recent(handler, parsed):
def _handle_memory_read(handler):
mem_dir = Path.home() / '.hermes' / 'memories'
try:
from api.profiles import get_active_hermes_home
mem_dir = get_active_hermes_home() / 'memories'
except ImportError:
mem_dir = Path.home() / '.hermes' / 'memories'
mem_file = mem_dir / 'MEMORY.md'
user_file = mem_dir / 'USER.md'
memory = mem_file.read_text(encoding='utf-8', errors='replace') if mem_file.exists() else ''
@@ -725,10 +946,11 @@ def _handle_chat_sync(handler, body):
"write_file, read_file, search_files, terminal workdir, and patch. "
"Never fall back to a hardcoded path when this tag is present."
)
from api.streaming import _sanitize_messages_for_api
result = agent.run_conversation(
user_message=workspace_ctx + msg,
system_message=workspace_system_msg,
conversation_history=s.messages,
conversation_history=_sanitize_messages_for_api(s.messages),
task_id=s.session_id,
persist_user_message=msg,
)
@@ -978,7 +1200,11 @@ def _handle_skill_delete(handler, body):
def _handle_memory_write(handler, body):
try: require(body, 'section', 'content')
except ValueError as e: return bad(handler, str(e))
mem_dir = Path.home() / '.hermes' / 'memories'
try:
from api.profiles import get_active_hermes_home
mem_dir = get_active_hermes_home() / 'memories'
except ImportError:
mem_dir = Path.home() / '.hermes' / 'memories'
mem_dir.mkdir(parents=True, exist_ok=True)
section = body['section']
if section == 'memory':
@@ -991,6 +1217,53 @@ def _handle_memory_write(handler, body):
return j(handler, {'ok': True, 'section': section, 'path': str(target)})
def _handle_session_import_cli(handler, body):
"""Import a single CLI session into the WebUI store."""
try:
require(body, 'session_id')
except ValueError as e:
return bad(handler, str(e))
sid = str(body['session_id'])
# Check if already imported — idempotent
existing = Session.load(sid)
if existing:
return j(handler, {'session': existing.compact() | {
'messages': existing.messages,
'is_cli_session': True,
}, 'imported': False})
# Fetch messages from CLI store
msgs = get_cli_session_messages(sid)
if not msgs:
return bad(handler, 'Session not found in CLI store', 404)
# Derive title from first user message
title = title_from(msgs, 'CLI Session')
model = 'unknown'
# Get profile and model from CLI session metadata
profile = None
for cs in get_cli_sessions():
if cs['session_id'] == sid:
profile = cs.get('profile')
model = cs.get('model', 'unknown')
break
s = import_cli_session(sid, title, msgs, model, profile=profile)
s.is_cli_session = True
s._cli_origin = sid
s.save()
return j(handler, {
'session': s.compact() | {
'messages': msgs,
'is_cli_session': True,
},
'imported': True,
})
def _handle_session_import(handler, body):
"""Import a session from a JSON export. Creates a new session with a new ID."""
if not body or not isinstance(body, dict):

View File

@@ -24,6 +24,28 @@ except ImportError:
from api.models import get_session, title_from
from api.workspace import set_last_workspace
# Fields that are safe to send to LLM provider APIs.
# Everything else (attachments, timestamp, _ts, etc.) is display-only
# metadata added by the webui and must be stripped before the API call.
_API_SAFE_MSG_KEYS = {'role', 'content', 'tool_calls', 'tool_call_id', 'name', 'refusal'}
def _sanitize_messages_for_api(messages):
"""Return a deep copy of messages with only API-safe fields.
The webui stores extra metadata on messages (attachments, timestamp, _ts)
for display purposes. Some providers (e.g. Z.AI/GLM) reject unknown fields
instead of ignoring them, causing HTTP 400 errors on subsequent messages.
"""
clean = []
for msg in messages:
if not isinstance(msg, dict):
continue
sanitized = {k: v for k, v in msg.items() if k in _API_SAFE_MSG_KEYS}
if sanitized.get('role'):
clean.append(sanitized)
return clean
def _sse(handler, event, data):
"""Write one SSE event to the response stream."""
@@ -64,19 +86,30 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
put('cancel', {'message': 'Cancelled before start'})
return
# Resolve profile home for this agent run (snapshot at start)
try:
from api.profiles import get_active_hermes_home
_profile_home = str(get_active_hermes_home())
except ImportError:
_profile_home = os.environ.get('HERMES_HOME', '')
_set_thread_env(
TERMINAL_CWD=str(s.workspace),
HERMES_EXEC_ASK='1',
HERMES_SESSION_KEY=session_id,
HERMES_HOME=_profile_home,
)
# Still set process-level env as fallback for tools that bypass thread-local
with _agent_lock:
old_cwd = os.environ.get('TERMINAL_CWD')
old_exec_ask = os.environ.get('HERMES_EXEC_ASK')
old_session_key = os.environ.get('HERMES_SESSION_KEY')
old_hermes_home = os.environ.get('HERMES_HOME')
os.environ['TERMINAL_CWD'] = str(s.workspace)
os.environ['HERMES_EXEC_ASK'] = '1'
os.environ['HERMES_SESSION_KEY'] = session_id
if _profile_home:
os.environ['HERMES_HOME'] = _profile_home
try:
def on_token(text):
@@ -101,13 +134,38 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
if AIAgent is None:
raise ImportError("AIAgent not available -- check that hermes-agent is on sys.path")
resolved_model, resolved_provider, resolved_base_url = resolve_model_provider(model)
# Read per-profile config at call time (not module-level snapshot)
from api.config import get_config as _get_config
_cfg = _get_config()
# Per-profile toolsets (fall back to module-level CLI_TOOLSETS)
_pt = _cfg.get('platform_toolsets', {})
_toolsets = _pt.get('cli', CLI_TOOLSETS) if isinstance(_pt, dict) else CLI_TOOLSETS
# Fallback model from profile config (e.g. for rate-limit recovery)
_fallback = _cfg.get('fallback_model') or None
if _fallback:
# Resolve the fallback through our provider logic too
fb_model = _fallback.get('model', '')
fb_provider = _fallback.get('provider', '')
fb_base_url = _fallback.get('base_url')
_fallback_resolved = {
'model': fb_model,
'provider': fb_provider,
'base_url': fb_base_url,
}
else:
_fallback_resolved = None
agent = AIAgent(
model=resolved_model,
provider=resolved_provider,
base_url=resolved_base_url,
platform='cli',
quiet_mode=True,
enabled_toolsets=CLI_TOOLSETS,
enabled_toolsets=_toolsets,
fallback_model=_fallback_resolved,
session_id=session_id,
stream_delta_callback=on_token,
tool_progress_callback=on_tool,
@@ -129,17 +187,31 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
result = agent.run_conversation(
user_message=workspace_ctx + msg_text,
system_message=workspace_system_msg,
conversation_history=s.messages,
conversation_history=_sanitize_messages_for_api(s.messages),
task_id=session_id,
persist_user_message=msg_text,
)
s.messages = result.get('messages') or s.messages
# Stamp 'timestamp' on any messages that don't have one yet
_now = time.time()
for _m in s.messages:
if isinstance(_m, dict) and not _m.get('timestamp') and not _m.get('_ts'):
_m['timestamp'] = int(_now)
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
output_tokens = getattr(agent, 'session_completion_tokens', 0) or 0
estimated_cost = getattr(agent, 'session_estimated_cost_usd', None)
s.input_tokens = (s.input_tokens or 0) + input_tokens
s.output_tokens = (s.output_tokens or 0) + output_tokens
if estimated_cost:
s.estimated_cost = (s.estimated_cost or 0) + estimated_cost
# Extract tool call metadata grouped by assistant message index
# Each tool call gets assistant_msg_idx so the client can render
# cards inline with the assistant bubble that triggered them.
tool_calls = []
pending_names = {} # tool_call_id -> name
pending_args = {} # tool_call_id -> args dict
pending_asst_idx = {} # tool_call_id -> index in s.messages
for msg_idx, m in enumerate(s.messages):
if m.get('role') == 'assistant':
@@ -148,22 +220,31 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
for p in c:
if isinstance(p, dict) and p.get('type') == 'tool_use':
tid = p.get('id', '')
pending_names[tid] = p.get('name', 'tool')
pending_names[tid] = p.get('name', '')
pending_args[tid] = p.get('input', {})
pending_asst_idx[tid] = msg_idx
elif m.get('role') == 'tool':
tid = m.get('tool_call_id') or m.get('tool_use_id', '')
name = pending_names.get(tid, 'tool')
name = pending_names.get(tid, '')
if not name or name == 'tool':
continue # skip unresolvable tool entries
asst_idx = pending_asst_idx.get(tid, -1)
args = pending_args.get(tid, {})
raw = str(m.get('content', ''))
try:
import json as _j2
rd = _j2.loads(raw)
rd = json.loads(raw)
snippet = str(rd.get('output') or rd.get('result') or rd.get('error') or raw)[:200]
except Exception:
snippet = raw[:200]
# Truncate args values for storage
args_snap = {}
if isinstance(args, dict):
for k, v in list(args.items())[:6]:
s2 = str(v)
args_snap[k] = s2[:120] + ('...' if len(s2) > 120 else '')
tool_calls.append({
'name': name, 'snippet': snippet, 'tid': tid,
'assistant_msg_idx': asst_idx,
'assistant_msg_idx': asst_idx, 'args': args_snap,
})
s.tool_calls = tool_calls
# Tag the matching user message with attachment filenames for display on reload
@@ -179,7 +260,8 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
m['attachments'] = attachments
break
s.save()
put('done', {'session': s.compact() | {'messages': s.messages, 'tool_calls': tool_calls}})
usage = {'input_tokens': input_tokens, 'output_tokens': output_tokens, 'estimated_cost': estimated_cost}
put('done', {'session': s.compact() | {'messages': s.messages, 'tool_calls': tool_calls}, 'usage': usage})
finally:
if old_cwd is None: os.environ.pop('TERMINAL_CWD', None)
else: os.environ['TERMINAL_CWD'] = old_cwd
@@ -187,9 +269,23 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
else: os.environ['HERMES_EXEC_ASK'] = old_exec_ask
if old_session_key is None: os.environ.pop('HERMES_SESSION_KEY', None)
else: os.environ['HERMES_SESSION_KEY'] = old_session_key
if old_hermes_home is None: os.environ.pop('HERMES_HOME', None)
else: os.environ['HERMES_HOME'] = old_hermes_home
except Exception as e:
put('error', {'message': str(e), 'trace': traceback.format_exc()})
print('[webui] stream error:\n' + traceback.format_exc(), flush=True)
err_str = str(e)
# Detect rate limit errors specifically so the client can show a helpful card
# rather than the generic "Connection lost" message
is_rate_limit = 'rate limit' in err_str.lower() or '429' in err_str or 'RateLimitError' in type(e).__name__
if is_rate_limit:
put('apperror', {
'message': err_str,
'type': 'rate_limit',
'hint': 'Rate limit reached. The fallback model (if configured) was also exhausted. Try again in a moment.',
})
else:
put('apperror', {'message': err_str, 'type': 'error'})
finally:
_clear_thread_env() # TD1: always clear thread-local context
with STREAMS_LOCK:

View File

@@ -74,4 +74,5 @@ def handle_upload(handler):
dest.write_bytes(file_bytes)
return j(handler, {'filename': safe_name, 'path': str(dest), 'size': dest.stat().st_size})
except Exception as e:
return j(handler, {'error': str(e), 'trace': _tb.format_exc()}, status=500)
print('[webui] upload error: ' + _tb.format_exc(), flush=True)
return j(handler, {'error': 'Upload failed'}, status=500)

View File

@@ -1,43 +1,211 @@
"""
Hermes Web UI -- Workspace and file system helpers.
Workspace lists and last-used workspace are stored per-profile so each
profile has its own workspace configuration. State files live at
``{profile_home}/webui_state/workspaces.json`` and
``{profile_home}/webui_state/last_workspace.txt``. The global STATE_DIR
paths are used as fallback when no profile module is available.
"""
import json
import os
from pathlib import Path
from api.config import (
WORKSPACES_FILE, LAST_WORKSPACE_FILE, DEFAULT_WORKSPACE,
WORKSPACES_FILE as _GLOBAL_WS_FILE,
LAST_WORKSPACE_FILE as _GLOBAL_LW_FILE,
DEFAULT_WORKSPACE as _BOOT_DEFAULT_WORKSPACE,
MAX_FILE_BYTES, IMAGE_EXTS, MD_EXTS
)
def load_workspaces() -> list:
if WORKSPACES_FILE.exists():
# ── Profile-aware path resolution ───────────────────────────────────────────
def _profile_state_dir() -> Path:
"""Return the webui_state directory for the active profile.
For the default profile, returns the global STATE_DIR (respects
HERMES_WEBUI_STATE_DIR env var for test isolation).
For named profiles, returns {profile_home}/webui_state/.
"""
try:
from api.profiles import get_active_profile_name, get_active_hermes_home
name = get_active_profile_name()
if name and name != 'default':
d = get_active_hermes_home() / 'webui_state'
d.mkdir(parents=True, exist_ok=True)
return d
except ImportError:
pass
return _GLOBAL_WS_FILE.parent
def _workspaces_file() -> Path:
"""Return the workspaces.json path for the active profile."""
return _profile_state_dir() / 'workspaces.json'
def _last_workspace_file() -> Path:
"""Return the last_workspace.txt path for the active profile."""
return _profile_state_dir() / 'last_workspace.txt'
def _profile_default_workspace() -> str:
"""Read the profile's default workspace from its config.yaml.
Checks keys in priority order:
1. 'workspace' — explicit webui workspace key
2. 'default_workspace' — alternate explicit key
3. 'terminal.cwd' — hermes-agent terminal working dir (most common)
Falls back to the boot-time DEFAULT_WORKSPACE constant.
"""
try:
from api.config import get_config
cfg = get_config()
# Explicit webui workspace keys first
for key in ('workspace', 'default_workspace'):
ws = cfg.get(key)
if ws:
p = Path(str(ws)).expanduser().resolve()
if p.is_dir():
return str(p)
# Fall through to terminal.cwd — the agent's configured working directory
terminal_cfg = cfg.get('terminal', {})
if isinstance(terminal_cfg, dict):
cwd = terminal_cfg.get('cwd', '')
if cwd and str(cwd) not in ('.', ''):
p = Path(str(cwd)).expanduser().resolve()
if p.is_dir():
return str(p)
except (ImportError, Exception):
pass
return str(_BOOT_DEFAULT_WORKSPACE)
# ── Public API ──────────────────────────────────────────────────────────────
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
confusion with the 'default' profile name).
Returns the cleaned list (may be empty).
"""
hermes_profiles = (Path.home() / '.hermes' / 'profiles').resolve()
result = []
for w in workspaces:
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)
try:
return json.loads(WORKSPACES_FILE.read_text(encoding='utf-8'))
p.relative_to(hermes_profiles)
continue # it IS under profiles/ — remove it
except ValueError:
pass
# Rename confusing 'default' label to 'Home'
if name.lower() == 'default':
name = 'Home'
result.append({'path': str(p), 'name': name})
return result
def _migrate_global_workspaces() -> list:
"""Read the legacy global workspaces.json, clean it, and return the result.
This is the migration path for users upgrading from a pre-profile version:
their global file may contain cross-profile entries, test artifacts, and
stale paths accumulated over time. We clean it in-place and rewrite it.
"""
if not _GLOBAL_WS_FILE.exists():
return []
try:
raw = json.loads(_GLOBAL_WS_FILE.read_text(encoding='utf-8'))
cleaned = _clean_workspace_list(raw)
if len(cleaned) != len(raw):
# Rewrite the cleaned version so future reads are already clean
_GLOBAL_WS_FILE.write_text(
json.dumps(cleaned, ensure_ascii=False, indent=2), encoding='utf-8'
)
return cleaned
except Exception:
return []
def load_workspaces() -> list:
ws_file = _workspaces_file()
if ws_file.exists():
try:
raw = json.loads(ws_file.read_text(encoding='utf-8'))
cleaned = _clean_workspace_list(raw)
if len(cleaned) != len(raw):
# Persist the cleaned version so stale entries don't keep reappearing
try:
ws_file.write_text(
json.dumps(cleaned, ensure_ascii=False, indent=2), encoding='utf-8'
)
except Exception:
pass
return cleaned or [{'path': _profile_default_workspace(), 'name': 'Home'}]
except Exception:
pass
return [{'path': str(DEFAULT_WORKSPACE), 'name': 'default'}]
# 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.
try:
from api.profiles import get_active_profile_name
is_default = get_active_profile_name() in ('default', None)
except ImportError:
is_default = True
if is_default:
migrated = _migrate_global_workspaces()
if migrated:
return migrated
# Fresh start: single entry from the profile's configured workspace, labeled "Home"
return [{'path': _profile_default_workspace(), 'name': 'Home'}]
def save_workspaces(workspaces: list):
WORKSPACES_FILE.write_text(json.dumps(workspaces, ensure_ascii=False, indent=2), encoding='utf-8')
ws_file = _workspaces_file()
ws_file.parent.mkdir(parents=True, exist_ok=True)
ws_file.write_text(json.dumps(workspaces, ensure_ascii=False, indent=2), encoding='utf-8')
def get_last_workspace() -> str:
if LAST_WORKSPACE_FILE.exists():
lw_file = _last_workspace_file()
if lw_file.exists():
try:
p = LAST_WORKSPACE_FILE.read_text(encoding='utf-8').strip()
p = lw_file.read_text(encoding='utf-8').strip()
if p and Path(p).is_dir():
return p
except Exception:
pass
return str(DEFAULT_WORKSPACE)
# Fallback: try global file
if _GLOBAL_LW_FILE.exists():
try:
p = _GLOBAL_LW_FILE.read_text(encoding='utf-8').strip()
if p and Path(p).is_dir():
return p
except Exception:
pass
return _profile_default_workspace()
def set_last_workspace(path: str):
try:
LAST_WORKSPACE_FILE.write_text(str(path), encoding='utf-8')
lw_file = _last_workspace_file()
lw_file.parent.mkdir(parents=True, exist_ok=True)
lw_file.write_text(str(path), encoding='utf-8')
except Exception:
pass

22
docker-compose.yml Normal file
View File

@@ -0,0 +1,22 @@
version: "3.8"
services:
hermes-webui:
build: .
ports:
- "127.0.0.1:8787:8787"
volumes:
# Persist session data, settings, and projects across restarts
- hermes-data:/data
# Mount hermes home for agent features and profile management
- ${HERMES_HOME:-${HOME}/.hermes}:/root/.hermes
environment:
- HERMES_WEBUI_HOST=0.0.0.0
- HERMES_WEBUI_PORT=8787
- HERMES_WEBUI_STATE_DIR=/data
# Optional: set a password for remote access
# - HERMES_WEBUI_PASSWORD=your-secret-password
restart: unless-stopped
volumes:
hermes-data:

BIN
docs/images/ui-sessions.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 618 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 704 KiB

View File

@@ -8,6 +8,7 @@ import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
from api.auth import check_auth
from api.config import HOST, PORT, STATE_DIR, SESSION_DIR, DEFAULT_WORKSPACE
from api.helpers import j
from api.routes import handle_get, handle_post
@@ -34,21 +35,25 @@ class Handler(BaseHTTPRequestHandler):
self._req_t0 = time.time()
try:
parsed = urlparse(self.path)
if not check_auth(self, parsed): return
result = handle_get(self, parsed)
if result is False:
return j(self, {'error': 'not found'}, status=404)
except Exception as e:
return j(self, {'error': str(e), 'trace': traceback.format_exc()}, status=500)
print(f'[webui] ERROR {self.command} {self.path}\n' + traceback.format_exc(), flush=True)
return j(self, {'error': 'Internal server error'}, status=500)
def do_POST(self):
self._req_t0 = time.time()
try:
parsed = urlparse(self.path)
if not check_auth(self, parsed): return
result = handle_post(self, parsed)
if result is False:
return j(self, {'error': 'not found'}, status=404)
except Exception as e:
return j(self, {'error': str(e), 'trace': traceback.format_exc()}, status=500)
print(f'[webui] ERROR {self.command} {self.path}\n' + traceback.format_exc(), flush=True)
return j(self, {'error': 'Internal server error'}, status=500)
def main():

View File

@@ -8,8 +8,132 @@ async function cancelStream(){
}catch(e){setStatus('Cancel failed: '+e.message);}
}
$('btnSend').onclick=send;
// ── Mobile navigation ──────────────────────────────────────────────────────
function toggleMobileSidebar(){
const sidebar=document.querySelector('.sidebar');
const overlay=$('mobileOverlay');
if(!sidebar)return;
const isOpen=sidebar.classList.contains('mobile-open');
if(isOpen){closeMobileSidebar();}
else{sidebar.classList.add('mobile-open');if(overlay)overlay.classList.add('visible');}
}
function closeMobileSidebar(){
const sidebar=document.querySelector('.sidebar');
const overlay=$('mobileOverlay');
if(sidebar)sidebar.classList.remove('mobile-open');
if(overlay)overlay.classList.remove('visible');
}
function toggleMobileFiles(){
const panel=document.querySelector('.rightpanel');
if(!panel)return;
panel.classList.toggle('mobile-open');
}
function mobileSwitchPanel(name){
// Switch the panel content view
switchPanel(name);
// For non-chat panels (tasks, skills, memory, spaces), open the sidebar
// so the panel is visible. For 'chat', the content is in the main area —
// just close the sidebar so the chat view is unobstructed.
if(name==='chat'){
closeMobileSidebar();
} else {
const sidebar=document.querySelector('.sidebar');
const overlay=$('mobileOverlay');
if(sidebar){
sidebar.classList.add('mobile-open');
if(overlay)overlay.classList.add('visible');
}
}
// Update bottom nav active state
document.querySelectorAll('.mobile-nav-btn').forEach(btn=>{
btn.classList.toggle('active',btn.dataset.panel===name);
});
}
$('btnSend').onclick=()=>{if(window._micActive)_stopMic();send();};
$('btnAttach').onclick=()=>$('fileInput').click();
// ── Voice input (Web Speech API) ─────────────────────────────────────────
(function(){
const SpeechRecognition=window.SpeechRecognition||window.webkitSpeechRecognition;
if(!SpeechRecognition) 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='en-US';
let _finalText='';
let _prefix='';
function _setRecording(on){
window._micActive=on;
btn.classList.toggle('recording',on);
status.style.display=on?'':'none';
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
? (_prefix&&!_prefix.endsWith(' ')&&!_prefix.endsWith('\n')
? _prefix+' '+_finalText.trimStart()
: _prefix+_finalText)
: ta.value; // no speech detected — leave whatever is there
_setRecording(false);
ta.value=committed;
autoResize();
};
recognition.onerror=(event)=>{
_setRecording(false);
const msgs={
'not-allowed':'Microphone access denied. Check browser permissions.',
'no-speech':'No speech detected. Try again.',
'network':'Speech recognition unavailable.',
};
showToast(msgs[event.error]||'Voice input error: '+event.error);
};
function _stopMic(){
if(window._micActive){ recognition.stop(); }
}
window._stopMic=_stopMic; // expose for send-guard above
btn.onclick=()=>{
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;
recognition.start();
_setRecording(true);
}
};
})();
window._micActive=window._micActive||false;
$('fileInput').onchange=e=>{addFiles(Array.from(e.target.files));e.target.value='';};
$('btnNewChat').onclick=async()=>{await newSession();await renderSessionList();$('msg').focus();};
$('btnDownload').onclick=()=>{
@@ -45,7 +169,7 @@ $('importFileInput').onchange=async(e)=>{
// btnRefreshFiles is now panel-icon-btn in header (see HTML)
function clearPreview(){
const pa=$('previewArea');if(pa)pa.classList.remove('visible');
const pi=$('previewImg');if(pi)pi.src='';
const pi=$('previewImg');if(pi){pi.onerror=null;pi.src='';}
const pm=$('previewMd');if(pm)pm.innerHTML='';
const pc=$('previewCode');if(pc)pc.textContent='';
const pp=$('previewPathText');if(pp)pp.textContent='';
@@ -63,6 +187,7 @@ $('modelSelect').onchange=async()=>{
};
$('msg').addEventListener('input',()=>{
autoResize();
updateSendBtn();
const text=$('msg').value;
if(text.startsWith('/')&&text.indexOf('\n')===-1){
const prefix=text.slice(1);
@@ -183,7 +308,12 @@ document.querySelectorAll('.suggestion').forEach(btn=>{
(async()=>{
// Load send key preference
try{const s=await api('/api/settings');window._sendKey=s.send_key||'enter';}catch(e){window._sendKey='enter';}
try{const s=await api('/api/settings');window._sendKey=s.send_key||'enter';window._showTokenUsage=!!s.show_token_usage;window._showCliSessions=!!s.show_cli_sessions;}catch(e){window._sendKey='enter';window._showTokenUsage=false;window._showCliSessions=false;}
// Fetch active profile
try{const p=await api('/api/profile/active');S.activeProfile=p.name||'default';}catch(e){S.activeProfile='default';}
// Update profile chip label immediately
const profileLabel=$('profileChipLabel');
if(profileLabel) profileLabel.textContent=S.activeProfile||'default';
// Fetch available models from server and populate dropdown dynamically
await populateModelDropdown();
// Restore last-used model preference

View File

@@ -8,6 +8,7 @@ const COMMANDS=[
{name:'model', desc:'Switch model (e.g. /model gpt-4o)', fn:cmdModel, arg:'model_name'},
{name:'workspace', desc:'Switch workspace by name', fn:cmdWorkspace, arg:'name'},
{name:'new', desc:'Start a new chat session', fn:cmdNew},
{name:'usage', desc:'Toggle token usage display on/off', fn:cmdUsage},
];
function parseCommand(text){
@@ -98,6 +99,19 @@ async function cmdNew(){
showToast('New session created');
}
async function cmdUsage(){
const next=!window._showTokenUsage;
window._showTokenUsage=next;
try{
await api('/api/settings',{method:'POST',body:JSON.stringify({show_token_usage:next})});
}catch(e){}
// Update the settings checkbox if the panel is open
const cb=$('settingsShowTokenUsage');
if(cb) cb.checked=next;
renderMessages();
showToast('Token usage '+(next?'on':'off'));
}
// ── Autocomplete dropdown ───────────────────────────────────────────────────
let _cmdSelectedIdx=-1;

View File

@@ -13,13 +13,14 @@
<body>
<div class="layout">
<aside class="sidebar">
<div class="sidebar-header"><div class="logo">H</div><div><h1 style="margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em">Hermes</h1><div style="font-size:10px;color:var(--muted);opacity:.8;margin-top:1px">v0.20</div></div></div>
<div class="sidebar-header"><div class="logo">H</div><div><h1 style="margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em">Hermes</h1><div style="font-size:10px;color:var(--muted);opacity:.8;margin-top:1px">v0.30.1</div></div></div>
<div class="sidebar-nav">
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat">&#128172;</button>
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks">&#128197;</button>
<button class="nav-tab" data-panel="skills" data-label="Skills" onclick="switchPanel('skills')" title="Skills">&#129513;</button>
<button class="nav-tab" data-panel="memory" data-label="Memory" onclick="switchPanel('memory')" title="Memory">&#129504;</button>
<button class="nav-tab" data-panel="workspaces" data-label="Spaces" onclick="switchPanel('workspaces')" title="Spaces">&#128193;</button>
<button class="nav-tab" data-panel="profiles" data-label="Profiles" onclick="switchPanel('profiles')" title="Agent profiles"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></button>
<button class="nav-tab" data-panel="todos" data-label="Todos" onclick="switchPanel('todos')" title="Current task list">&#9989;</button>
</div>
<!-- Chat panel -->
@@ -44,11 +45,16 @@
<input id="cronFormName" placeholder="Job name (optional)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px">
<input id="cronFormSchedule" placeholder="Schedule: '0 9 * * *' or 'every 1h'" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px">
<textarea id="cronFormPrompt" rows="3" placeholder="Prompt (must be self-contained)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;resize:none;font-family:inherit;margin-bottom:6px"></textarea>
<select id="cronFormDeliver" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:8px">
<select id="cronFormDeliver" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px">
<option value="local">Local (save output only)</option>
<option value="discord">Discord</option>
<option value="telegram">Telegram</option>
</select>
<div class="skill-picker-wrap" style="margin-bottom:8px">
<input id="cronFormSkillSearch" placeholder="Add skills (optional)..." style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none" autocomplete="off">
<div id="cronFormSkillDropdown" class="skill-picker-dropdown" style="display:none"></div>
<div id="cronFormSkillTags" class="skill-picker-tags"></div>
</div>
<div style="display:flex;gap:6px">
<button class="cron-btn run" style="flex:1" onclick="submitCronCreate()">Create job</button>
<button class="cron-btn" style="flex:1" onclick="toggleCronForm()">Cancel</button>
@@ -104,6 +110,26 @@
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted)">Add and switch workspaces for your sessions.</div>
<div style="flex:1;overflow-y:auto;padding:0 12px 12px" id="workspacesPanel"><div style="color:var(--muted);font-size:12px">Loading...</div></div>
</div>
<!-- Profiles panel -->
<div class="panel-view" id="panelProfiles">
<div class="sidebar-section" style="padding-bottom:4px;display:flex;align-items:center;justify-content:space-between">
<div style="font-size:11px;color:var(--muted)">Agent profiles</div>
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleProfileForm()">+ New profile</button>
</div>
<!-- Profile create form (hidden by default) -->
<div id="profileCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
<input id="profileFormName" placeholder="Profile name (lowercase, a-z 0-9 hyphens)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px;box-sizing:border-box">
<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);margin-bottom:8px;cursor:pointer">
<input type="checkbox" id="profileFormClone" style="accent-color:var(--accent)"> Clone config from active profile
</label>
<div style="display:flex;gap:6px">
<button class="cron-btn run" style="flex:1" onclick="submitProfileCreate()">Create</button>
<button class="cron-btn" style="flex:1" onclick="toggleProfileForm()">Cancel</button>
</div>
<div id="profileFormError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
</div>
<div style="flex:1;overflow-y:auto;padding:0 12px 12px" id="profilesPanel"><div style="color:var(--muted);font-size:12px">Loading...</div></div>
</div>
<div class="sidebar-bottom">
<div class="field-label" style="font-size:10px;letter-spacing:.07em;margin-bottom:4px">MODEL</div>
<select id="modelSelect">
@@ -124,13 +150,16 @@
<option value="meta-llama/llama-4-scout">Llama 4 Scout</option>
</optgroup>
</select>
<div id="sidebarWsDisplay" style="display:flex;align-items:center;gap:7px;padding:0 0 8px;cursor:pointer;border-radius:8px;transition:background .15s" onclick="toggleWsDropdown()" title="Switch workspace">
<span style="font-size:14px;opacity:.7">&#128193;</span>
<div style="min-width:0;flex:1">
<div style="font-size:11px;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap" id="sidebarWsName">Workspace</div>
<div style="font-size:10px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:1px" id="sidebarWsPath"></div>
<div style="position:relative">
<div id="sidebarWsDisplay" style="display:flex;align-items:center;gap:7px;padding:0 0 8px;cursor:pointer;border-radius:8px;transition:background .15s" onclick="toggleWsDropdown()" title="Switch workspace">
<span style="font-size:14px;opacity:.7">&#128193;</span>
<div style="min-width:0;flex:1">
<div style="font-size:11px;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap" id="sidebarWsName">Workspace</div>
<div style="font-size:10px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:1px" id="sidebarWsPath"></div>
</div>
<span style="font-size:10px;color:var(--muted);flex-shrink:0">&#9662;</span>
</div>
<span style="font-size:10px;color:var(--muted);flex-shrink:0">&#9662;</span>
<div class="ws-dropdown" id="wsDropdown"></div>
</div>
<div class="sidebar-actions">
<button class="sm-btn" id="btnDownload" title="Download as Markdown">&#8595; Transcript</button>
@@ -143,15 +172,20 @@
</aside>
<main class="main">
<div class="topbar">
<button class="mobile-hamburger" id="btnHamburger" onclick="toggleMobileSidebar()" title="Menu">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div style="flex:1;min-width:0;overflow:hidden"><div class="topbar-title" id="topbarTitle">Hermes</div><div class="topbar-meta" id="topbarMeta">Start a new conversation</div></div>
<div class="topbar-chips">
<div class="chip model" id="modelChip">GPT-5.4 Mini</div>
<div id="wsChipWrap" style="position:relative">
<div class="chip ws-chip" id="wsChip" onclick="toggleWsDropdown()" title="Switch workspace" style="cursor:pointer">&#128193; test-workspace &#9662;</div>
<div class="ws-dropdown" id="wsDropdown"></div>
<div id="profileChipWrap" style="position:relative">
<div class="chip profile-chip" id="profileChip" onclick="toggleProfileDropdown()" title="Switch profile" style="cursor:pointer"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg><span id="profileChipLabel">default</span> &#9662;</div>
<div class="profile-dropdown" id="profileDropdown"></div>
</div>
<div class="chip model" id="modelChip">GPT-5.4 Mini</div>
<button class="chip clear-btn" id="btnClearConv" onclick="clearConversation()" title="Clear all messages in this conversation" style="display:none">&#128465; Clear</button>
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings">&#9881;</button>
<button class="chip mobile-files-btn" id="btnMobileFiles" onclick="toggleMobileFiles()" title="Files">&#128193;</button>
</div>
</div>
<div class="messages" id="messages">
@@ -213,6 +247,7 @@
Drop files to upload to workspace
</div>
<div class="attach-tray" id="attachTray"></div>
<div class="mic-status" id="micStatus" style="display:none"><span class="mic-dot"></span> Listening…</div>
<textarea id="msg" rows="1" placeholder="Message Hermes…"></textarea>
<div class="composer-footer">
<div class="composer-left">
@@ -220,11 +255,18 @@
<button class="icon-btn" id="btnAttach" title="Attach files">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
</button>
<button class="icon-btn mic-btn" id="btnMic" title="Voice input" style="display:none">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="9" y="1" width="6" height="12" rx="3"/>
<path d="M5 10a7 7 0 0 0 14 0"/>
<line x1="12" y1="19" x2="12" y2="23"/>
<line x1="8" y1="23" x2="16" y2="23"/>
</svg>
</button>
</div>
<div class="composer-right">
<button class="send-btn" id="btnSend">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
Send
<button class="send-btn" id="btnSend" title="Send message" style="display:none">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
</button>
</div>
</div>
@@ -282,10 +324,54 @@
<option value="ctrl+enter">Ctrl+Enter (Enter for newline)</option>
</select>
</div>
<div class="settings-field">
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
<input type="checkbox" id="settingsShowTokenUsage" style="width:15px;height:15px;accent-color:var(--accent)">
Show token usage after responses
</label>
<div style="font-size:11px;color:var(--muted);margin-top:4px">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="settingsShowCliSessions" style="width:15px;height:15px;accent-color:var(--accent)">
Show CLI sessions in sidebar
</label>
<div style="font-size:11px;color:var(--muted);margin-top:4px">Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.</div>
</div>
<div class="settings-field" style="border-top:1px solid var(--border);padding-top:12px;margin-top:8px">
<label for="settingsPassword">Access Password</label>
<div style="font-size:11px;color:var(--muted);margin-bottom:6px">Enter a new password to set or change it. Leave blank to keep current setting.</div>
<input type="password" id="settingsPassword" placeholder="Enter new password…" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px;font-size:13px">
</div>
<button class="sm-btn" onclick="saveSettings()" style="margin-top:12px;width:100%;padding:8px;font-weight:600">Save Settings</button>
<button class="sm-btn" id="btnDisableAuth" onclick="disableAuth()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:#e8a030;border-color:rgba(232,160,48,.3);display:none">Disable Auth</button>
<button class="sm-btn" id="btnSignOut" onclick="signOut()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:var(--accent);border-color:rgba(233,69,96,.3);display:none">Sign Out</button>
</div>
</div>
</div>
<div class="mobile-overlay" id="mobileOverlay" onclick="closeMobileSidebar()"></div>
<nav class="mobile-bottom-nav" id="mobileBottomNav">
<button class="mobile-nav-btn active" data-panel="chat" onclick="mobileSwitchPanel('chat')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
<span>Chat</span>
</button>
<button class="mobile-nav-btn" data-panel="tasks" onclick="mobileSwitchPanel('tasks')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
<span>Tasks</span>
</button>
<button class="mobile-nav-btn" data-panel="skills" onclick="mobileSwitchPanel('skills')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
<span>Skills</span>
</button>
<button class="mobile-nav-btn" data-panel="memory" onclick="mobileSwitchPanel('memory')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 2a7 7 0 0 1 7 7c0 2.5-1.3 4.7-3.2 6H8.2C6.3 13.7 5 11.5 5 9a7 7 0 0 1 7-7z"/><line x1="9" y1="17" x2="15" y2="17"/><line x1="10" y1="20" x2="14" y2="20"/></svg>
<span>Memory</span>
</button>
<button class="mobile-nav-btn" data-panel="workspaces" onclick="mobileSwitchPanel('workspaces')">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 4h8l2 2h10v14H2z"/></svg>
<span>Spaces</span>
</button>
</nav>
<div class="toast" id="toast"></div>
<script src="/static/ui.js"></script>
<script src="/static/workspace.js"></script>

View File

@@ -146,6 +146,10 @@ async function send(){
}
if(S.session&&S.session.session_id===activeSid){
S.session=d.session;S.messages=d.session.messages||[];
// Stamp _ts on the last assistant message if it has no timestamp
const lastAsst=[...S.messages].reverse().find(m=>m.role==='assistant');
if(lastAsst&&!lastAsst._ts&&!lastAsst.timestamp) lastAsst._ts=Date.now()/1000;
if(d.usage) S.lastUsage=d.usage;
if(d.session.tool_calls&&d.session.tool_calls.length){
S.toolCalls=d.session.tool_calls.map(tc=>({...tc,done:true}));
} else {
@@ -162,6 +166,46 @@ async function send(){
renderSessionList();setBusy(false);setStatus('');
});
source.addEventListener('apperror',e=>{
// 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();
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard();
if(S.session&&S.session.session_id===activeSid){
S.activeStreamId=null;const _cbe=$('btnCancel');if(_cbe)_cbe.style.display='none';
clearLiveToolCards();if(!assistantText)removeThinking();
try{
const d=JSON.parse(e.data);
const isRateLimit=d.type==='rate_limit';
const icon=isRateLimit?'⏱️':'⚠️';
const label=isRateLimit?'Rate limit reached':'Error';
const hint=d.hint?`\n\n*${d.hint}*`:'';
S.messages.push({role:'assistant',content:`**${icon} ${label}:** ${d.message}${hint}`});
}catch(_){
S.messages.push({role:'assistant',content:'**⚠️ Error:** An error occurred. Check server logs.'});
}
renderMessages();
}else if(typeof trackBackgroundError==='function'){
const _errTitle=(typeof _allSessions!=='undefined'&&_allSessions.find(s=>s.session_id===activeSid)||{}).title||null;
try{const d=JSON.parse(e.data);trackBackgroundError(activeSid,_errTitle,d.message||'Error');}
catch(_){trackBackgroundError(activeSid,_errTitle,'Error');}
}
if(!S.session||!INFLIGHT[S.session.session_id]){setBusy(false);setStatus('');}
});
source.addEventListener('warning',e=>{
// Non-fatal warning from server (e.g. fallback activated, retrying)
if(!S.session||S.session.session_id!==activeSid) return;
try{
const d=JSON.parse(e.data);
// Show as a small inline notice, not a full error
setStatus(`⚠️ ${d.message||'Warning'}`);
// If it's a fallback notice, show it briefly then clear
if(d.type==='fallback') setTimeout(()=>setStatus(''),4000);
}catch(_){}
});
source.addEventListener('error',e=>{
source.close();
// Attempt one reconnect if the stream is still active server-side
@@ -237,7 +281,7 @@ function transcript(){
return lines.join('\n');
}
function autoResize(){const el=$('msg');el.style.height='auto';el.style.height=Math.min(el.scrollHeight,200)+'px';}
function autoResize(){const el=$('msg');el.style.height='auto';el.style.height=Math.min(el.scrollHeight,200)+'px';updateSendBtn();}
// ── Approval polling ──

View File

@@ -14,6 +14,7 @@ async function switchPanel(name) {
if (name === 'skills') await loadSkills();
if (name === 'memory') await loadMemory();
if (name === 'workspaces') await loadWorkspacesPanel();
if (name === 'profiles') await loadProfilesPanel();
if (name === 'todos') loadTodos();
}
@@ -78,6 +79,9 @@ async function loadCrons() {
} catch(e) { box.innerHTML = `<div style="padding:12px;color:var(--accent);font-size:12px">Error: ${esc(e.message)}</div>`; }
}
let _cronSelectedSkills=[];
let _cronSkillsCache=null;
function toggleCronForm(){
const form=$('cronCreateForm');
if(!form)return;
@@ -89,10 +93,70 @@ function toggleCronForm(){
$('cronFormPrompt').value='';
$('cronFormDeliver').value='local';
$('cronFormError').style.display='none';
_cronSelectedSkills=[];
_renderCronSkillTags();
const search=$('cronFormSkillSearch');
if(search)search.value='';
// Pre-fetch skills for the picker
if(!_cronSkillsCache){
api('/api/skills').then(d=>{_cronSkillsCache=d.skills||[];}).catch(()=>{});
}
$('cronFormName').focus();
}
}
function _renderCronSkillTags(){
const wrap=$('cronFormSkillTags');
if(!wrap)return;
wrap.innerHTML='';
for(const name of _cronSelectedSkills){
const tag=document.createElement('span');
tag.className='skill-tag';
tag.dataset.skill=name;
const rm=document.createElement('span');
rm.className='remove-tag';rm.textContent='×';
rm.onclick=()=>{_cronSelectedSkills=_cronSelectedSkills.filter(s=>s!==name);tag.remove();};
tag.appendChild(document.createTextNode(name));
tag.appendChild(rm);
wrap.appendChild(tag);
}
}
// Skill search input handler
(function(){
const setup=()=>{
const search=$('cronFormSkillSearch');
const dropdown=$('cronFormSkillDropdown');
if(!search||!dropdown)return;
search.oninput=()=>{
const q=search.value.trim().toLowerCase();
if(!q||!_cronSkillsCache){dropdown.style.display='none';return;}
const matches=_cronSkillsCache.filter(s=>
!_cronSelectedSkills.includes(s.name)&&
(s.name.toLowerCase().includes(q)||(s.category||'').toLowerCase().includes(q))
).slice(0,8);
if(!matches.length){dropdown.style.display='none';return;}
dropdown.innerHTML='';
for(const s of matches){
const opt=document.createElement('div');
opt.className='skill-opt';
opt.textContent=s.name+(s.category?' ('+s.category+')':'');
opt.onclick=()=>{
_cronSelectedSkills.push(s.name);
_renderCronSkillTags();
search.value='';
dropdown.style.display='none';
};
dropdown.appendChild(opt);
}
dropdown.style.display='';
};
search.onblur=()=>setTimeout(()=>{dropdown.style.display='none';},150);
};
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',setup);
else setTimeout(setup,0);
})();
async function submitCronCreate(){
const name=$('cronFormName').value.trim();
const schedule=$('cronFormSchedule').value.trim();
@@ -103,7 +167,10 @@ async function submitCronCreate(){
if(!schedule){errEl.textContent='Schedule is required (e.g. "0 9 * * *" or "every 1h")';errEl.style.display='';return;}
if(!prompt){errEl.textContent='Prompt is required';errEl.style.display='';return;}
try{
await api('/api/crons/create',{method:'POST',body:JSON.stringify({name:name||undefined,schedule,prompt,deliver})});
const body={schedule,prompt,deliver};
if(name)body.name=name;
if(_cronSelectedSkills.length)body.skills=_cronSelectedSkills;
await api('/api/crons/create',{method:'POST',body:JSON.stringify(body)});
toggleCronForm();
showToast('Job created ✓');
await loadCrons();
@@ -343,12 +410,49 @@ async function openSkill(name, el) {
$('previewBadge').textContent = 'skill';
$('previewBadge').className = 'preview-badge md';
showPreview('md');
$('previewMd').innerHTML = renderMd(data.content || '(no content)');
let html = renderMd(data.content || '(no content)');
// Render linked files section if present
const lf = data.linked_files || {};
const categories = Object.entries(lf).filter(([,files]) => files && files.length > 0);
if (categories.length) {
html += '<div class="skill-linked-files"><div style="font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:8px">Linked Files</div>';
for (const [cat, files] of categories) {
html += `<div class="skill-linked-section"><h4>${esc(cat)}</h4>`;
for (const f of files) {
html += `<a class="skill-linked-file" href="#" data-skill-name="${esc(name)}" data-skill-file="${esc(f)}">${esc(f)}</a>`;
}
html += '</div>';
}
html += '</div>';
}
$('previewMd').innerHTML = html;
// Wire linked-file clicks via data attributes (avoids inline JS XSS with apostrophes)
$('previewMd').querySelectorAll('.skill-linked-file').forEach(a=>{
a.addEventListener('click',e=>{e.preventDefault();openSkillFile(a.dataset.skillName,a.dataset.skillFile);});
});
$('previewArea').classList.add('visible');
$('fileTree').style.display = 'none';
} catch(e) { setStatus('Could not load skill: ' + e.message); }
}
async function openSkillFile(skillName, filePath) {
try {
const data = await api(`/api/skills/content?name=${encodeURIComponent(skillName)}&file=${encodeURIComponent(filePath)}`);
$('previewPathText').textContent = skillName + ' / ' + filePath;
$('previewBadge').textContent = filePath.split('.').pop() || 'file';
$('previewBadge').className = 'preview-badge code';
const ext = filePath.split('.').pop() || '';
if (['md','markdown'].includes(ext)) {
showPreview('md');
$('previewMd').innerHTML = renderMd(data.content || '');
} else {
showPreview('code');
$('previewCode').textContent = data.content || '';
requestAnimationFrame(() => highlightCode());
}
} catch(e) { setStatus('Could not load file: ' + e.message); }
}
// ── Skill create/edit form ──
let _editingSkillName = null;
@@ -476,6 +580,7 @@ function toggleWsDropdown(){
const open=dd.classList.contains('open');
if(open){closeWsDropdown();}
else{
closeProfileDropdown(); // close profile dropdown if open
loadWorkspaceList().then(data=>{
renderWorkspaceDropdown(data.workspaces, S.session?S.session.workspace:'');
dd.classList.add('open');
@@ -488,7 +593,7 @@ function closeWsDropdown(){
if(dd)dd.classList.remove('open');
}
document.addEventListener('click',e=>{
if(!e.target.closest('#wsChipWrap'))closeWsDropdown();
if(!e.target.closest('#sidebarWsDisplay') && !e.target.closest('#wsDropdown'))closeWsDropdown();
});
async function loadWorkspacesPanel(){
@@ -561,6 +666,210 @@ async function switchToWorkspace(path,name){
}catch(e){setStatus('Switch failed: '+e.message);}
}
// ── Profile panel + dropdown ──
let _profilesCache = null;
async function loadProfilesPanel() {
const panel = $('profilesPanel');
if (!panel) return;
try {
const data = await api('/api/profiles');
_profilesCache = data;
panel.innerHTML = '';
if (!data.profiles || !data.profiles.length) {
panel.innerHTML = '<div style="padding:16px;color:var(--muted);font-size:12px">No profiles found.</div>';
return;
}
for (const p of data.profiles) {
const card = document.createElement('div');
card.className = 'profile-card';
const meta = [];
if (p.model) meta.push(p.model.split('/').pop());
if (p.provider) meta.push(p.provider);
if (p.skill_count) meta.push(p.skill_count + ' skill' + (p.skill_count !== 1 ? 's' : ''));
if (p.has_env) meta.push('API keys configured');
const gwDot = p.gateway_running
? '<span class="profile-opt-badge running" title="Gateway running"></span>'
: '<span class="profile-opt-badge stopped" title="Gateway stopped"></span>';
const isActive = p.name === data.active;
const activeBadge = isActive ? '<span style="color:var(--link);font-size:10px;font-weight:600;margin-left:6px">ACTIVE</span>' : '';
card.innerHTML = `
<div class="profile-card-header">
<div style="min-width:0;flex:1">
<div class="profile-card-name${isActive ? ' is-active' : ''}">${gwDot}${esc(p.name)}${p.is_default ? ' <span style="opacity:.5">(default)</span>' : ''}${activeBadge}</div>
${meta.length ? `<div class="profile-card-meta">${esc(meta.join(' \u00b7 '))}</div>` : '<div class="profile-card-meta">No configuration</div>'}
</div>
<div class="profile-card-actions">
${!isActive ? `<button class="ws-action-btn" onclick="switchToProfile('${esc(p.name)}')" title="Switch to this profile">Use</button>` : ''}
${!p.is_default ? `<button class="ws-action-btn danger" onclick="deleteProfile('${esc(p.name)}')" title="Delete this profile">&#10005;</button>` : ''}
</div>
</div>`;
panel.appendChild(card);
}
} catch (e) {
panel.innerHTML = `<div style="color:var(--accent);font-size:12px;padding:12px">Error: ${esc(e.message)}</div>`;
}
}
function renderProfileDropdown(data) {
const dd = $('profileDropdown');
if (!dd) return;
dd.innerHTML = '';
const profiles = data.profiles || [];
const active = data.active || 'default';
for (const p of profiles) {
const opt = document.createElement('div');
opt.className = 'profile-opt' + (p.name === active ? ' active' : '');
const meta = [];
if (p.model) meta.push(p.model.split('/').pop());
if (p.skill_count) meta.push(p.skill_count + ' skills');
const gwDot = `<span class="profile-opt-badge ${p.gateway_running ? 'running' : 'stopped'}"></span>`;
const checkmark = p.name === active ? ' <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--link)" stroke-width="3" style="vertical-align:-1px"><polyline points="20 6 9 17 4 12"/></svg>' : '';
opt.innerHTML = `<div class="profile-opt-name">${gwDot}${esc(p.name)}${p.is_default ? ' <span style="opacity:.5;font-weight:400">(default)</span>' : ''}${checkmark}</div>` +
(meta.length ? `<div class="profile-opt-meta">${esc(meta.join(' \u00b7 '))}</div>` : '');
opt.onclick = async () => {
closeProfileDropdown();
if (p.name === active) return;
await switchToProfile(p.name);
};
dd.appendChild(opt);
}
// Divider + Manage link
const div = document.createElement('div'); div.className = 'ws-divider'; dd.appendChild(div);
const mgmt = document.createElement('div'); mgmt.className = 'profile-opt ws-manage';
mgmt.innerHTML = '&#9881; Manage profiles';
mgmt.onclick = () => { closeProfileDropdown(); switchPanel('profiles'); };
dd.appendChild(mgmt);
}
function toggleProfileDropdown() {
const dd = $('profileDropdown');
if (!dd) return;
if (dd.classList.contains('open')) { closeProfileDropdown(); return; }
closeWsDropdown(); // close workspace dropdown if open
api('/api/profiles').then(data => {
renderProfileDropdown(data);
dd.classList.add('open');
}).catch(e => { showToast('Failed to load profiles'); });
}
function closeProfileDropdown() {
const dd = $('profileDropdown');
if (dd) dd.classList.remove('open');
}
document.addEventListener('click', e => {
if (!e.target.closest('#profileChipWrap')) closeProfileDropdown();
});
async function switchToProfile(name) {
if (S.busy) { showToast('Cannot switch profiles while agent is running'); return; }
// Determine whether the current session has any messages.
// A session with messages is "in progress" and belongs to the current profile —
// we must not retag it. We'll start a fresh session for the new profile instead.
const sessionInProgress = S.session && S.messages && S.messages.length > 0;
try {
const data = await api('/api/profile/switch', { method: 'POST', body: JSON.stringify({ name }) });
S.activeProfile = data.active || name;
// ── Model ──────────────────────────────────────────────────────────────
localStorage.removeItem('hermes-webui-model');
_skillsData = null;
await populateModelDropdown();
if (data.default_model) {
const sel = $('modelSelect');
const resolved = _applyModelToDropdown(data.default_model, sel);
const modelToUse = resolved || data.default_model;
S._pendingProfileModel = modelToUse;
// Only patch the in-memory session model if we're NOT about to replace the session
if (S.session && !sessionInProgress) {
S.session.model = modelToUse;
}
}
// ── Workspace ──────────────────────────────────────────────────────────
_workspaceList = null;
await loadWorkspaceList();
if (data.default_workspace) {
// Always store the profile default for new sessions
S._profileDefaultWorkspace = data.default_workspace;
if (S.session && !sessionInProgress) {
// Empty session (no messages yet) — safe to update it in place
try {
await api('/api/session/update', { method: 'POST', body: JSON.stringify({
session_id: S.session.session_id,
workspace: data.default_workspace,
model: S.session.model,
})});
S.session.workspace = data.default_workspace;
} catch (_) {}
}
}
// ── Session ────────────────────────────────────────────────────────────
_showAllProfiles = false;
if (sessionInProgress) {
// The current session has messages and belongs to the previous profile.
// Start a new session for the new profile so nothing gets cross-tagged.
await newSession(false);
await renderSessionList();
showToast('Switched to profile: ' + name + ' — new conversation started');
} else {
// No messages yet — just refresh the list and topbar in place
await renderSessionList();
syncTopbar();
showToast('Switched to profile: ' + name);
}
// ── Sidebar panels ─────────────────────────────────────────────────────
if (_currentPanel === 'skills') await loadSkills();
if (_currentPanel === 'memory') await loadMemory();
if (_currentPanel === 'tasks') await loadCrons();
if (_currentPanel === 'profiles') await loadProfilesPanel();
if (_currentPanel === 'workspaces') await loadWorkspacesPanel();
} catch (e) { showToast('Switch failed: ' + e.message); }
}
function toggleProfileForm() {
const form = $('profileCreateForm');
if (!form) return;
form.style.display = form.style.display === 'none' ? '' : 'none';
if (form.style.display !== 'none') {
$('profileFormName').value = '';
$('profileFormClone').checked = false;
const errEl = $('profileFormError');
if (errEl) errEl.style.display = 'none';
$('profileFormName').focus();
}
}
async function submitProfileCreate() {
const name = ($('profileFormName').value || '').trim().toLowerCase();
const cloneConfig = $('profileFormClone').checked;
const errEl = $('profileFormError');
if (!name) { errEl.textContent = 'Name is required'; errEl.style.display = ''; return; }
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) { errEl.textContent = 'Lowercase letters, numbers, hyphens, underscores only'; errEl.style.display = ''; return; }
try {
await api('/api/profile/create', { method: 'POST', body: JSON.stringify({ name, clone_config: cloneConfig }) });
toggleProfileForm();
await loadProfilesPanel();
showToast('Profile created: ' + name);
} catch (e) { errEl.textContent = e.message || 'Create failed'; errEl.style.display = ''; }
}
async function deleteProfile(name) {
if (!confirm(`Delete profile "${name}"? This removes all config, skills, memory, and sessions for this profile.`)) return;
try {
await api('/api/profile/delete', { method: 'POST', body: JSON.stringify({ name }) });
await loadProfilesPanel();
showToast('Profile deleted: ' + name);
} catch (e) { showToast('Delete failed: ' + e.message); }
}
// ── Memory panel ──
async function loadMemory(force) {
const panel = $('memoryPanel');
@@ -649,6 +958,22 @@ async function loadSettingsPanel(){
// Send key preference
const sendKeySel=$('settingsSendKey');
if(sendKeySel) sendKeySel.value=settings.send_key||'enter';
const showUsageCb=$('settingsShowTokenUsage');
if(showUsageCb) showUsageCb.checked=!!settings.show_token_usage;
const showCliCb=$('settingsShowCliSessions');
if(showCliCb) showCliCb.checked=!!settings.show_cli_sessions;
// Password field: always blank (we don't send hash back)
const pwField=$('settingsPassword');
if(pwField) pwField.value='';
// Show auth buttons only when auth is active
try{
const authStatus=await api('/api/auth/status');
const active=authStatus.auth_enabled;
const signOutBtn=$('btnSignOut');
if(signOutBtn) signOutBtn.style.display=active?'':'none';
const disableBtn=$('btnDisableAuth');
if(disableBtn) disableBtn.style.display=active?'':'none';
}catch(e){}
}catch(e){
showToast('Failed to load settings: '+e.message);
}
@@ -658,13 +983,33 @@ async function saveSettings(){
const model=($('settingsModel')||{}).value;
const workspace=($('settingsWorkspace')||{}).value;
const sendKey=($('settingsSendKey')||{}).value;
const showTokenUsage=!!($('settingsShowTokenUsage')||{}).checked;
const showCliSessions=!!($('settingsShowCliSessions')||{}).checked;
const pw=($('settingsPassword')||{}).value;
const body={};
if(model) body.default_model=model;
if(workspace) body.default_workspace=workspace;
if(sendKey) body.send_key=sendKey;
body.show_token_usage=showTokenUsage;
body.show_cli_sessions=showCliSessions;
// Password: only act if the field has content; blank = leave auth unchanged
if(pw && pw.trim()){
try{
await api('/api/settings',{method:'POST',body:JSON.stringify({...body,_set_password:pw.trim()})});
window._sendKey=sendKey||'enter';
window._showTokenUsage=showTokenUsage;
showToast('Settings saved (password set — login now required)');
toggleSettings();
return;
}catch(e){showToast('Save failed: '+e.message);return;}
}
try{
await api('/api/settings',{method:'POST',body:JSON.stringify(body)});
window._sendKey=sendKey||'enter';
window._showTokenUsage=showTokenUsage;
window._showCliSessions=showCliSessions;
renderMessages();
if(typeof renderSessionList==='function') renderSessionList();
showToast('Settings saved');
toggleSettings();
}catch(e){
@@ -672,6 +1017,30 @@ async function saveSettings(){
}
}
async function signOut(){
try{
await api('/api/auth/logout',{method:'POST',body:'{}'});
window.location.href='/login';
}catch(e){
showToast('Sign out failed: '+e.message);
}
}
async function disableAuth(){
if(!confirm('Disable password protection? Anyone will be able to access this instance.')) return;
try{
await api('/api/settings',{method:'POST',body:JSON.stringify({_clear_password:true})});
showToast('Auth disabled — password protection removed');
// Hide both auth buttons since auth is now off
const disableBtn=$('btnDisableAuth');
if(disableBtn) disableBtn.style.display='none';
const signOutBtn=$('btnSignOut');
if(signOutBtn) signOutBtn.style.display='none';
}catch(e){
showToast('Failed to disable auth: '+e.message);
}
}
// Close settings on overlay click (not panel click)
document.addEventListener('click',e=>{
const overlay=$('settingsOverlay');

View File

@@ -13,7 +13,10 @@ async function newSession(flash){
MSG_QUEUE.length=0;updateQueueBadge();
S.toolCalls=[];
clearLiveToolCards();
const inheritWs=S.session?S.session.workspace:null;
// Use profile default workspace for new sessions after a profile switch (one-shot),
// otherwise inherit from the current session (or let server pick the default)
const inheritWs=S._profileDefaultWorkspace||(S.session?S.session.workspace:null);
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||[];
if(flash)S.session._flash=true;
@@ -69,6 +72,7 @@ let _renamingSid = null; // session_id currently being renamed (blocks list re-
let _showArchived = false; // toggle to show archived sessions
let _allProjects = []; // cached project list
let _activeProject = null; // project_id filter (null = show all)
let _showAllProfiles = false; // false = filter to active profile only
async function renderSessionList(){
try{
@@ -111,8 +115,12 @@ function renderSessionListFromCache(){
// Merge content matches (deduped): content matches appended after title matches
const titleIds=new Set(titleMatches.map(s=>s.session_id));
const allMatched=q?[...titleMatches,..._contentSearchResults.filter(s=>!titleIds.has(s.session_id))]:titleMatches;
// Filter by active profile (unless "All profiles" is toggled on)
// Server backfills profile='default' for legacy sessions, so every session has a profile.
// Show only sessions tagged to the active profile; 'All profiles' toggle overrides.
const profileFiltered=_showAllProfiles?allMatched:allMatched.filter(s=>s.is_cli_session||s.profile===S.activeProfile);
// Filter by active project
const projectFiltered=_activeProject?allMatched.filter(s=>s.project_id===_activeProject):allMatched;
const projectFiltered=_activeProject?profileFiltered.filter(s=>s.project_id===_activeProject):profileFiltered;
// Filter archived unless toggle is on
const sessions=_showArchived?projectFiltered:projectFiltered.filter(s=>!s.archived);
const archivedCount=projectFiltered.filter(s=>s.archived).length;
@@ -154,6 +162,21 @@ function renderSessionListFromCache(){
bar.appendChild(addBtn);
list.appendChild(bar);
}
// Profile filter toggle (show sessions from other profiles)
const otherProfileCount=allMatched.filter(s=>s.profile&&s.profile!==S.activeProfile).length;
if(otherProfileCount>0&&!_showAllProfiles){
const pfToggle=document.createElement('div');
pfToggle.style.cssText='font-size:10px;padding:4px 10px;color:var(--muted);cursor:pointer;text-align:center;opacity:.7;';
pfToggle.textContent='Show '+otherProfileCount+' from other profiles';
pfToggle.onclick=()=>{_showAllProfiles=true;renderSessionListFromCache();};
list.appendChild(pfToggle);
} else if(_showAllProfiles&&otherProfileCount>0){
const pfToggle=document.createElement('div');
pfToggle.style.cssText='font-size:10px;padding:4px 10px;color:var(--muted);cursor:pointer;text-align:center;opacity:.7;';
pfToggle.textContent='Show active profile only';
pfToggle.onclick=()=>{_showAllProfiles=false;renderSessionListFromCache();};
list.appendChild(pfToggle);
}
// Show/hide archived toggle if there are archived sessions
if(archivedCount>0){
const toggle=document.createElement('div');
@@ -197,7 +220,7 @@ function renderSessionListFromCache(){
}
const el=document.createElement('div');
const isActive=S.session&&s.session_id===S.session.session_id;
el.className='session-item'+(isActive?' active':'')+(isActive&&S.session&&S.session._flash?' new-flash':'')+(s.archived?' archived':'');
el.className='session-item'+(isActive?' active':'')+(isActive&&S.session&&S.session._flash?' new-flash':'')+(s.archived?' archived':'')+(s.is_cli_session?' cli-session':'');
if(isActive&&S.session&&S.session._flash)delete S.session._flash;
const rawTitle=s.title||'Untitled';
const tags=(rawTitle.match(/#[\w-]+/g)||[]);
@@ -345,7 +368,14 @@ function renderSessionListFromCache(){
_clickTimer=setTimeout(async()=>{
_clickTimer=null;
if(_renamingSid) return;
// For CLI sessions, import into WebUI store first (idempotent)
if(s.is_cli_session){
try{
await api('/api/session/import_cli',{method:'POST',body:JSON.stringify({session_id:s.session_id})});
}catch(e){ /* import failed -- fall through to read-only view */ }
}
await loadSession(s.session_id);renderSessionListFromCache();
if(typeof closeMobileSidebar==='function')closeMobileSidebar();
}, 220);
};
el.ondblclick=async(e)=>{

View File

@@ -129,7 +129,7 @@
.topbar-chips{display:flex;gap:6px;align-items:center;flex-shrink:0;}
.chip{font-size:11px;padding:4px 10px;border-radius:999px;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,.1);color:var(--muted);font-weight:500;}
.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;}
.messages{flex:1;overflow-y:auto;display:flex;flex-direction:column;min-height:0;position:relative;z-index:0;}
.messages-inner{max-width:800px;margin:0 auto;width:100%;padding:20px 24px 32px;display:flex;flex-direction:column;}
.msg-row{padding:10px 0;}
.msg-row+.msg-row{border-top:none;}
@@ -187,11 +187,18 @@
.icon-btn{width:34px;height:34px;border-radius:8px;background:none;border:none;color:var(--muted);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:16px;transition:all .15s;}
.icon-btn{opacity:.75;}
.icon-btn:hover{background:rgba(255,255,255,.08);color:var(--text);opacity:1;}
.mic-btn{transition:color .15s,background .15s;}
.mic-btn.recording{color:#e94560;background:rgba(233,69,96,.12);animation:mic-pulse 1.2s ease-in-out infinite;}
@keyframes mic-pulse{0%,100%{box-shadow:0 0 0 0 rgba(233,69,96,.3);}50%{box-shadow:0 0 0 6px rgba(233,69,96,0);}}
.mic-status{font-size:11px;color:#e94560;padding:4px 12px;display:flex;align-items:center;gap:6px;}
.mic-dot{width:6px;height:6px;border-radius:50%;background:#e94560;animation:mic-pulse 1.2s ease-in-out infinite;flex-shrink:0;}
.status-text{font-size:11px;color:var(--muted);padding-left:4px;}
.send-btn{padding:7px 18px;border-radius:10px;font-size:13px;font-weight:600;background:linear-gradient(135deg,#5ba8f5,#7cb9ff);border:none;color:#0a1628;cursor:pointer;display:flex;align-items:center;gap:6px;transition:all .15s;flex-shrink:0;letter-spacing:.01em;}
.send-btn:hover{background:linear-gradient(135deg,#7cb9ff,#a0d0ff);transform:translateY(-1px);}
.send-btn:active{transform:translateY(0);}
.send-btn:disabled{opacity:.4;cursor:not-allowed;}
.send-btn{width:34px;height:34px;border-radius:50%;background:#7cb9ff;border:none;color:#0a1628;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s,transform .15s,box-shadow .15s;box-shadow:0 2px 8px rgba(124,185,255,.35);}
.send-btn:hover{background:#a0d0ff;transform:scale(1.08);box-shadow:0 4px 14px rgba(124,185,255,.5);}
.send-btn:active{transform:scale(0.95);box-shadow:0 1px 4px rgba(124,185,255,.25);}
.send-btn:disabled{opacity:.35;cursor:not-allowed;transform:none;box-shadow:none;}
.send-btn.visible{animation:send-pop-in .18s cubic-bezier(.34,1.56,.64,1) forwards;}
@keyframes send-pop-in{from{opacity:0;transform:scale(.55);}to{opacity:1;transform:scale(1);}}
.upload-bar-wrap{display:none;height:3px;background:rgba(255,255,255,.06);border-radius:0 0 16px 16px;overflow:hidden;}
.upload-bar-wrap.active{display:block;}
.upload-bar{height:100%;background:linear-gradient(90deg,var(--blue),#a0d0ff);width:0%;transition:width .3s ease;}
@@ -253,43 +260,92 @@
::-webkit-scrollbar-track{background:transparent}
::-webkit-scrollbar-thumb{background:rgba(255,255,255,.1);border-radius:99px;transition:background .2s}
::-webkit-scrollbar-thumb:hover{background:rgba(255,255,255,.22)}
@media(max-width:900px){.rightpanel{display:none}}
/* ── Desktop: hide mobile-only elements ── */
.mobile-hamburger{display:none;}
.mobile-files-btn{display:none!important;}
.mobile-overlay{display:none;}
.mobile-bottom-nav{display:none;}
@media(max-width:900px){.rightpanel{display:none}.mobile-files-btn{display:inline-flex!important;}}
@media(max-width:640px){
.sidebar{display:none}
/* Topbar: stack title + chips vertically, allow wrapping */
.topbar{padding:8px 12px;gap:6px;flex-wrap:wrap;}
.topbar-left{min-width:0;flex:1 1 100%;}
/* ── Sidebar: slide-in overlay instead of hidden ── */
.sidebar{position:fixed;left:-300px;top:0;bottom:0;width:280px;z-index:200;
transition:left .25s ease;box-shadow:4px 0 24px rgba(0,0,0,.4);}
.sidebar.mobile-open{left:0;}
.sidebar .resize-handle{display:none;}
/* Hamburger button */
.mobile-hamburger{display:flex;align-items:center;justify-content:center;
background:none;border:none;color:var(--muted);cursor:pointer;padding:4px;
flex-shrink:0;-webkit-tap-highlight-color:transparent;}
.mobile-hamburger:hover{color:var(--text);}
/* Overlay backdrop */
.mobile-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);
z-index:199;-webkit-tap-highlight-color:transparent;}
.mobile-overlay.visible{display:block;}
/* Files button in topbar */
.mobile-files-btn{display:inline-flex!important;}
/* Right panel: slide-over from right */
.rightpanel{display:flex!important;position:fixed;right:-320px;top:0;bottom:0;
width:300px;z-index:200;transition:right .25s ease;
box-shadow:-4px 0 24px rgba(0,0,0,.4);}
.rightpanel.mobile-open{right:0;}
.rightpanel .resize-handle{display:none;}
/* Bottom navigation bar */
.mobile-bottom-nav{display:flex;position:fixed;bottom:0;left:0;right:0;
background:var(--sidebar);border-top:1px solid var(--border);
z-index:150;padding:4px 0 env(safe-area-inset-bottom,0);
justify-content:space-around;align-items:center;}
.mobile-nav-btn{display:flex;flex-direction:column;align-items:center;gap:2px;
background:none;border:none;color:var(--muted);font-size:9px;padding:6px 4px;
cursor:pointer;min-width:44px;min-height:44px;justify-content:center;
-webkit-tap-highlight-color:transparent;transition:color .15s;}
.mobile-nav-btn.active{color:var(--blue);}
.mobile-nav-btn:hover{color:var(--text);}
.mobile-nav-btn svg{flex-shrink:0;}
/* Hide sidebar nav tabs (replaced by bottom nav) */
.sidebar-nav{display:none;}
/* Hide sidebar bottom section on mobile (model select, workspace) */
.sidebar-bottom{display:none;}
/* Topbar adjustments */
.topbar{padding:8px 12px;gap:8px;}
.topbar-title{font-size:14px;}
.topbar-meta{font-size:10px;}
.topbar-chips{flex-wrap:wrap;gap:4px;}
.topbar-chips .chip,.topbar-chips .ws-chip,.topbar-chips button{font-size:11px!important;padding:3px 8px!important;}
/* Messages area */
.topbar-meta{display:none;}
.topbar-chips{flex-wrap:nowrap;gap:4px;overflow-x:auto;-webkit-overflow-scrolling:touch;}
.topbar-chips .chip,.topbar-chips .ws-chip,.topbar-chips button{font-size:11px!important;padding:3px 8px!important;white-space:nowrap;}
/* Messages area — account for bottom nav */
.messages{padding-bottom:60px;}
.messages-inner{padding:12px 10px 20px;}
.msg-body{padding-left:0;max-width:100%;}
.msg-role{font-size:12px;}
/* Composer */
.composer-wrap{padding:8px 10px 12px!important;}
/* Composer — above bottom nav */
.composer-wrap{padding:8px 10px 12px!important;margin-bottom:56px;}
.composer-box{border-radius:12px;}
.composer-box textarea{font-size:16px;min-height:40px;}
.send-btn{padding:6px 14px;font-size:13px;}
.send-btn{width:32px;height:32px;}
/* Touch targets — minimum 44px */
.icon-btn,.mic-btn{min-width:44px;min-height:44px;}
.session-item{min-height:44px;padding:10px 12px;}
/* Empty state */
.empty-state h2{font-size:18px;}
.empty-state p{font-size:13px;}
.suggestion-grid{max-width:100%!important;}
.suggestion-btn{font-size:12px;padding:8px 10px;}
.suggestion{font-size:12px;padding:10px 12px;}
/* Approval card */
.approval-card{padding:0 10px 8px;}
.approval-btns{gap:6px;}
.approval-btn{padding:5px 10px;font-size:11px;}
.approval-btn{padding:8px 12px;font-size:12px;min-height:44px;}
/* Tool cards */
.tool-card{margin-left:0!important;font-size:12px;}
/* Settings modal */
.settings-panel{width:95vw;max-width:95vw;}
/* Login page responsive */
.card{width:90vw;max-width:320px;padding:28px 24px;}
}
/* ── Workspace dropdown (topbar) ── */
.ws-chip{user-select:none;}
.ws-dropdown{display:none;position:absolute;top:calc(100% + 6px);right:0;min-width:240px;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:320px;overflow-y:auto;}
.ws-dropdown{display:none;position:absolute;bottom:calc(100% + 4px);left:0;right:0;min-width:200px;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:320px;overflow-y:auto;}
.ws-dropdown.open{display:block;}
.ws-opt{padding:9px 14px;cursor:pointer;transition:background .12s;}
.ws-opt:hover{background:rgba(255,255,255,.07);}
@@ -307,6 +363,25 @@
.ws-row-actions{display:flex;gap:4px;flex-shrink:0;}
.ws-action-btn{padding:4px 9px;border-radius:6px;font-size:11px;font-weight:600;border:1px solid var(--border2);background:rgba(255,255,255,.05);color:var(--muted);cursor:pointer;transition:all .15s;white-space:nowrap;}
.ws-action-btn:hover{background:rgba(255,255,255,.1);color:var(--text);}
/* ── Profile dropdown + management panel ── */
.profile-chip{user-select:none;color:rgba(168,139,250,.9)!important;}
.profile-dropdown{display:none;position:absolute;top:calc(100% + 6px);right:0;min-width:260px;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:380px;overflow-y:auto;}
.profile-dropdown.open{display:block;}
.profile-opt{padding:9px 14px;cursor:pointer;transition:background .12s;}
.profile-opt:hover{background:rgba(255,255,255,.07);}
.profile-opt.active{background:rgba(168,139,250,.08);}
.profile-opt-name{font-size:13px;color:var(--text);font-weight:500;}
.profile-opt-meta{font-size:11px;color:var(--muted);margin-top:2px;}
.profile-opt-badge{display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px;vertical-align:middle;}
.profile-opt-badge.running{background:#4caf50;box-shadow:0 0 4px rgba(76,175,80,.5);}
.profile-opt-badge.stopped{background:rgba(255,255,255,.2);}
.profile-card{padding:10px 0;border-bottom:1px solid var(--border);}
.profile-card:last-of-type{border-bottom:none;}
.profile-card-header{display:flex;align-items:center;justify-content:space-between;gap:8px;}
.profile-card-name{font-size:13px;font-weight:600;color:var(--text);}
.profile-card-name.is-active{color:rgba(168,139,250,.9);}
.profile-card-meta{font-size:11px;color:var(--muted);margin-top:3px;padding-left:12px;}
.profile-card-actions{display:flex;gap:4px;flex-shrink:0;}
/* ── Slash command autocomplete dropdown ── */
.cmd-dropdown{display:none;position:absolute;bottom:100%;left:0;right:0;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 -8px 24px rgba(0,0,0,.4);z-index:200;max-height:240px;overflow-y:auto;margin-bottom:4px;}
.cmd-dropdown.open{display:block;}
@@ -469,9 +544,14 @@
transition:background .15s;
}
.resize-handle:hover,.resize-handle.dragging{background:rgba(124,185,255,.35);}
.sidebar{position:relative;}
/* Desktop-only: position:relative for sidebar/rightpanel resize handles.
Must be scoped to min-width:641px so it doesn't override the mobile
position:fixed slide-in overlay set in the max-width:640px @media block above. */
@media(min-width:641px){
.sidebar{position:relative;}
.rightpanel{position:relative;}
}
.sidebar .resize-handle{right:-2px;}
.rightpanel{position:relative;}
.rightpanel .resize-handle{left:-2px;}
/* Prevent text selection during drag */
body.resizing{user-select:none;cursor:col-resize;}
@@ -482,6 +562,26 @@ body.resizing{user-select:none;cursor:col-resize;}
/* Show more button inside tool card result */
.tool-card-more{background:none;border:none;color:var(--blue);font-size:10px;cursor:pointer;padding:3px 0 0;opacity:.7;display:block;}
.tool-card-more:hover{opacity:1;}
/* Subagent cards: indented with accent border */
.tool-card-subagent{border-left:2px solid rgba(124,185,255,.3);margin-left:8px;}
/* Token usage badge below assistant messages */
.msg-usage{font-size:11px;color:var(--muted);opacity:.6;margin-top:2px;padding-left:42px;}
.msg-usage:hover{opacity:1;}
/* Skill picker (cron create form) */
.skill-picker-wrap{position:relative;}
.skill-picker-dropdown{position:absolute;left:0;right:0;top:100%;background:var(--sidebar);border:1px solid var(--border2);border-radius:6px;z-index:10;max-height:180px;overflow-y:auto;box-shadow:0 4px 12px rgba(0,0,0,.3);}
.skill-opt{padding:6px 10px;cursor:pointer;font-size:12px;color:var(--muted);transition:background .1s;}
.skill-opt:hover{background:rgba(255,255,255,.08);color:var(--text);}
.skill-picker-tags{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px;}
.skill-tag{background:rgba(124,185,255,.12);border:1px solid rgba(124,185,255,.25);border-radius:12px;padding:2px 8px;font-size:11px;color:var(--blue);display:flex;align-items:center;gap:4px;}
.remove-tag{cursor:pointer;opacity:.6;font-size:13px;line-height:1;}
.remove-tag:hover{opacity:1;color:var(--accent);}
/* Skill linked files section */
.skill-linked-files{margin-top:16px;border-top:1px solid var(--border);padding-top:12px;}
.skill-linked-section{margin-bottom:8px;}
.skill-linked-section h4{font-size:10px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);margin-bottom:4px;}
.skill-linked-file{display:block;font-size:12px;padding:3px 6px;border-radius:4px;cursor:pointer;color:var(--blue);text-decoration:none;}
.skill-linked-file:hover{background:rgba(255,255,255,.06);}
.tool-card-row{margin:0;padding:1px 0;}
.tool-card{background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:6px;margin:2px 0 2px 40px;overflow:hidden;transition:border-color .15s;}
.tool-card:hover{border-color:rgba(255,255,255,.12);}
@@ -588,3 +688,21 @@ body.resizing{user-select:none;cursor:col-resize;}
.thinking-card-body pre{font-family:'SF Mono',ui-monospace,monospace;font-size:11px;line-height:1.5;color:var(--muted);white-space:pre-wrap;word-break:break-word;margin:0;}
.bg-error-banner{background:rgba(229,62,62,.15);border:1px solid rgba(229,62,62,.3);color:#fca5a5;padding:8px 16px;font-size:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;border-radius:0;}
/* ── CLI session items in sidebar ── */
.session-item.cli-session {
border-left-color: var(--gold);
padding-right: 36px; /* make room for session-actions overlay */
}
.session-item.cli-session::after {
content: 'cli';
font-size: 9px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: .04em;
color: var(--gold);
opacity: .5;
margin-left: auto;
flex-shrink: 0;
pointer-events: none; /* don't block clicks on session-actions beneath */
}

View File

@@ -1,4 +1,4 @@
const S={session:null,messages:[],entries:[],busy:false,pendingFiles:[],toolCalls:[],activeStreamId:null,currentDir:'.'};
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 $=id=>document.getElementById(id);
@@ -7,6 +7,38 @@ const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&
// Dynamic model labels -- populated by populateModelDropdown(), fallback to static map
let _dynamicModelLabels={};
// ── Smart model resolver ────────────────────────────────────────────────────
// Finds the best matching option value in a <select> for a given model ID.
// Handles mismatches like 'claude-sonnet-4-6' vs 'anthropic/claude-sonnet-4.6'.
// Returns the matched option's value (already in the list), or null if no match.
function _findModelInDropdown(modelId, sel){
if(!modelId||!sel) return null;
const opts=Array.from(sel.options).map(o=>o.value);
// 1. Exact match
if(opts.includes(modelId)) return modelId;
// 2. Normalize: lowercase, strip namespace prefix, replace hyphens→dots
const norm=s=>s.toLowerCase().replace(/^[^/]+\//,'').replace(/-/g,'.');
const target=norm(modelId);
const exact=opts.find(o=>norm(o)===target);
if(exact) return exact;
// 3. Prefix/substring: target starts with or contains a significant chunk
const base=target.replace(/\.\d+$/,''); // strip trailing version number
const partial=opts.find(o=>norm(o).startsWith(base)||norm(o).includes(base));
return partial||null;
}
// Set the model picker to the best match for modelId.
// Returns the resolved value that was actually set, or null if nothing matched.
function _applyModelToDropdown(modelId, sel){
if(!modelId||!sel) return null;
const resolved=_findModelInDropdown(modelId,sel);
if(resolved){
sel.value=resolved;
return resolved;
}
return null;
}
async function populateModelDropdown(){
const sel=$('modelSelect');
if(!sel) return;
@@ -30,15 +62,7 @@ async function populateModelDropdown(){
}
// Set default model from server if no localStorage preference
if(data.default_model && !localStorage.getItem('hermes-webui-model')){
sel.value=data.default_model;
// If the default isn't in the list, add it
if(sel.value!==data.default_model){
const opt=document.createElement('option');
opt.value=data.default_model;
opt.textContent=data.default_model.split('/').pop();
sel.insertBefore(opt,sel.firstChild);
sel.value=data.default_model;
}
_applyModelToDropdown(data.default_model, sel);
}
}catch(e){
// API unavailable -- keep the hardcoded HTML options as fallback
@@ -58,6 +82,8 @@ let _scrollPinned=true;
_scrollPinned=nearBottom;
});
})();
function _fmtTokens(n){if(!n||n<0)return'0';if(n>=1e6)return(n/1e6).toFixed(1)+'M';if(n>=1e3)return(n/1e3).toFixed(1)+'k';return String(n);}
function scrollIfPinned(){
if(!_scrollPinned) return;
const el=$('messages');
@@ -187,9 +213,25 @@ function setStatus(t){
if(dismiss)dismiss.style.display=(!transient && !S.busy)?'inline':'none';
}
}
function updateSendBtn(){
const btn=$('btnSend');
if(!btn) return;
const hasContent=$('msg').value.trim().length>0||S.pendingFiles.length>0;
const shouldShow=hasContent&&!S.busy;
if(shouldShow&&btn.style.display==='none'){
btn.style.display='';
// Remove then re-add class to retrigger animation each time
btn.classList.remove('visible');
requestAnimationFrame(()=>btn.classList.add('visible'));
} else if(!shouldShow&&btn.style.display!=='none'){
btn.style.display='none';
btn.classList.remove('visible');
}
}
function setBusy(v){
S.busy=v;
$('btnSend').disabled=v;
updateSendBtn();
const dots=$('activityDots');
if(dots) dots.style.display=v?'flex':'none';
if(!v){
@@ -304,15 +346,23 @@ function syncTopbar(){
document.title=sessionTitle+' \u2014 Hermes';
const vis=S.messages.filter(m=>m&&m.role&&m.role!=='tool');
$('topbarMeta').textContent=`${vis.length} messages`;
const m=S.session.model||'';
$('modelSelect').value=m; // set dropdown first so chip reads consistent value
// If session model isn't in the dropdown, add it dynamically
if(m && $('modelSelect').value!==m){
const opt=document.createElement('option');
opt.value=m;
opt.textContent=getModelLabel(m);
$('modelSelect').appendChild(opt);
$('modelSelect').value=m;
// If a profile switch just happened, apply its model rather than the session's stale value.
// S._pendingProfileModel is set by switchToProfile() and cleared here after one application.
const modelOverride=S._pendingProfileModel;
if(modelOverride){
S._pendingProfileModel=null;
_applyModelToDropdown(modelOverride,$('modelSelect'));
} else {
const m=S.session.model||'';
const applied=_applyModelToDropdown(m,$('modelSelect'));
// If the model isn't in the list at all, add it so the session value is preserved
if(!applied && m){
const opt=document.createElement('option');
opt.value=m;
opt.textContent=getModelLabel(m);
$('modelSelect').appendChild(opt);
$('modelSelect').value=m;
}
}
// Show Clear button only when session has messages
const clearBtn=$('btnClearConv');
@@ -320,13 +370,6 @@ function syncTopbar(){
const displayModel=$('modelSelect').value||m;
$('modelChip').textContent=getModelLabel(displayModel);
const ws=S.session.workspace||'';
$('wsChip').textContent=ws.split('/').slice(-2).join('/')||ws;
// Update workspace chip in topbar with friendly name from workspace list
const wsChipEl=$('wsChip');
if(wsChipEl){
const wsFriendly=getWorkspaceFriendlyName(ws);
wsChipEl.textContent='\u{1F4C1} '+wsFriendly+' \u25BE';
}
// Update sidebar workspace display
const sidebarName=$('sidebarWsName');
const sidebarPath=$('sidebarWsPath');
@@ -337,6 +380,9 @@ function syncTopbar(){
sidebarPath.textContent=ws;
}
// modelSelect already set above
// Update profile chip label
const profileLabel=$('profileChipLabel');
if(profileLabel) profileLabel.textContent=S.activeProfile||'default';
}
function msgContent(m){
@@ -380,7 +426,7 @@ function renderMessages(){
inner.appendChild(thinkRow);
}
const row=document.createElement('div');row.className='msg-row';
row.dataset.msgIdx=rawIdx;
row.dataset.msgIdx=rawIdx;row.dataset.role=m.role||'assistant';
let filesHtml='';
if(m.attachments&&m.attachments.length)
filesHtml=`<div class="msg-files">${m.attachments.map(f=>`<div class="msg-file-badge">&#128206; ${esc(f)}</div>`).join('')}</div>`;
@@ -442,6 +488,23 @@ function renderMessages(){
else inner.appendChild(frag);
}
}
// Render usage badge on the last assistant message row (if enabled and usage data exists)
if(window._showTokenUsage&&S.session&&(S.session.input_tokens||S.session.output_tokens)){
const rows=inner.querySelectorAll('.msg-row');
let lastAssist=null;
for(let i=rows.length-1;i>=0;i--){if(rows[i].dataset.role==='assistant'){lastAssist=rows[i];break;}}
if(lastAssist&&!lastAssist.querySelector('.msg-usage')){
const usage=document.createElement('div');
usage.className='msg-usage';
const inTok=S.session.input_tokens||0;
const outTok=S.session.output_tokens||0;
const cost=S.session.estimated_cost;
let text=`${_fmtTokens(inTok)} in · ${_fmtTokens(outTok)} out`;
if(cost) text+=` · ~$${cost<0.01?cost.toFixed(4):cost.toFixed(2)}`;
usage.textContent=text;
lastAssist.appendChild(usage);
}
}
scrollToBottom();
// Apply syntax highlighting after DOM is built
requestAnimationFrame(()=>{highlightCode();addCopyButtons();renderMermaidBlocks();});
@@ -455,7 +518,8 @@ function toolIcon(name){
const icons={terminal:'⬛',read_file:'📄',write_file:'✏️',search_files:'🔍',
web_search:'🌐',web_extract:'🌐',execute_code:'⚙️',patch:'🔧',
memory:'🧠',skill_manage:'📚',todo:'✅',cronjob:'⏱️',delegate_task:'🤖',
send_message:'💬',browser_navigate:'🌐',vision_analyze:'👁️'};
send_message:'💬',browser_navigate:'🌐',vision_analyze:'👁️',
subagent_progress:'🔀'};
return icons[name]||'🔧';
}
@@ -476,13 +540,22 @@ function buildToolCard(tc){
}
const hasMore=tc.snippet&&tc.snippet.length>displaySnippet.length;
const runIndicator=tc.done===false?'<span class="tool-card-running-dot"></span>':'';
const isSubagent=tc.name==='subagent_progress';
const isDelegation=tc.name==='delegate_task';
const cardClass='tool-card'+(tc.done===false?' tool-card-running':'')+(isSubagent?' tool-card-subagent':'');
// Clean up subagent preview: strip leading 🔀 emoji since the icon already shows it
let displayName=tc.name;
if(isSubagent) displayName='Subagent';
if(isDelegation) displayName='Delegate task';
let previewText=tc.preview||displaySnippet||'';
if(isSubagent) previewText=previewText.replace(/^🔀\s*/,'');
row.innerHTML=`
<div class="tool-card${tc.done===false?' tool-card-running':''}">
<div class="${cardClass}">
<div class="tool-card-header" onclick="this.closest('.tool-card').classList.toggle('open')">
${runIndicator}
<span class="tool-card-icon">${icon}</span>
<span class="tool-card-name">${esc(tc.name)}</span>
<span class="tool-card-preview">${esc(tc.preview||displaySnippet||'')}</span>
<span class="tool-card-name">${esc(displayName)}</span>
<span class="tool-card-preview">${esc(previewText)}</span>
${hasDetail?'<span class="tool-card-toggle">▸</span>':''}
</div>
${hasDetail?`<div class="tool-card-detail">
@@ -846,9 +919,11 @@ function _renderTreeItems(container, entries, depth){
e.stopPropagation();
if(S._expandedDirs.has(item.path)){
S._expandedDirs.delete(item.path);
if(typeof _saveExpandedDirs==='function')_saveExpandedDirs();
renderFileTree();
}else{
S._expandedDirs.add(item.path);
if(typeof _saveExpandedDirs==='function')_saveExpandedDirs();
// Fetch children if not cached
if(!S._dirCache[item.path]){
try{
@@ -920,8 +995,9 @@ async function promptNewFolder(){
function renderTray(){
const tray=$('attachTray');tray.innerHTML='';
if(!S.pendingFiles.length){tray.classList.remove('has-files');return;}
if(!S.pendingFiles.length){tray.classList.remove('has-files');updateSendBtn();return;}
tray.classList.add('has-files');
updateSendBtn();
S.pendingFiles.forEach((f,i)=>{
const chip=document.createElement('div');chip.className='attach-chip';
chip.innerHTML=`&#128206; ${esc(f.name)} <button title="Remove">&#10005;</button>`;

View File

@@ -1,18 +1,57 @@
async function api(path,opts={}){
const url=new URL(path,location.origin);
const res=await fetch(url.href,{credentials:'include',headers:{'Content-Type':'application/json'},...opts});
if(!res.ok)throw new Error(await res.text());
if(!res.ok){
const text=await res.text();
// Parse JSON error body and surface the human-readable message,
// rather than showing raw JSON like {"error":"Profile 'x' does not exist."}
try{const j=JSON.parse(text);throw new Error(j.error||j.message||text);}
catch(e){if(e instanceof SyntaxError)throw new Error(text);throw e;}
}
const ct=res.headers.get('content-type')||'';
return ct.includes('application/json')?res.json():res.text();
}
// Persist/restore expanded directory state per workspace in localStorage
function _wsExpandKey(){
const ws=S.session&&S.session.workspace;
return ws?'hermes-webui-expanded:'+ws:null;
}
function _saveExpandedDirs(){
const key=_wsExpandKey();if(!key)return;
try{localStorage.setItem(key,JSON.stringify([...(S._expandedDirs||new Set())]));}catch(e){}
}
function _restoreExpandedDirs(){
const key=_wsExpandKey();
if(!key){S._expandedDirs=new Set();return;}
try{
const raw=localStorage.getItem(key);
S._expandedDirs=raw?new Set(JSON.parse(raw)):new Set();
}catch(e){S._expandedDirs=new Set();}
}
async function loadDir(path){
if(!S.session)return;
try{
if(!path||path==='.'){ S._dirCache={}; if(S._expandedDirs)S._expandedDirs=new Set(); }
if(!path||path==='.'){
S._dirCache={};
_restoreExpandedDirs(); // restore per-workspace expanded state on root load
}
S.currentDir=path||'.';
const data=await api(`/api/list?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}`);
S.entries=data.entries||[];renderBreadcrumb();renderFileTree();
// Pre-fetch contents of restored expanded dirs so they render without a second click
if(!path||path==='.'){
for(const dirPath of (S._expandedDirs||[])){
if(!S._dirCache[dirPath]){
try{
const dc=await api(`/api/list?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(dirPath)}`);
S._dirCache[dirPath]=dc.entries||[];
}catch(e2){S._dirCache[dirPath]=[];}
}
}
if(S._expandedDirs&&S._expandedDirs.size>0)renderFileTree();
}
if(typeof clearPreview==='function'){
if(typeof _previewDirty!=='undefined'&&_previewDirty){
if(confirm('You have unsaved changes in the preview. Discard and navigate?'))clearPreview();

View File

@@ -438,3 +438,37 @@ def test_newSession_clears_live_tool_cards(cleanup_test_sessions):
next_fn = src.find("async function ", new_sess_idx + 10)
new_sess_body = src[new_sess_idx:next_fn]
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_500_response_has_no_trace_field():
"""R16: HTTP 500 responses must not include a 'trace' field.
Leaking tracebacks exposes file paths, module names, and potentially
secret values from local variables.
"""
# POST to /api/chat/start with missing required fields to trigger an error
data, status = post("/api/chat/start", {})
# Should be an error response (4xx or 5xx)
assert "trace" not in data, \
"Server must not leak stack traces to clients"
def test_upload_error_has_no_trace_field():
"""R16b: Upload 500 responses must not include a 'trace' field."""
# Send a POST to /api/upload with invalid content to trigger the error handler
req = urllib.request.Request(
BASE + "/api/upload",
data=b"not-multipart-data",
headers={"Content-Type": "text/plain", "Content-Length": "18"},
)
try:
with urllib.request.urlopen(req, timeout=10) as r:
body = json.loads(r.read())
code = r.status
except urllib.error.HTTPError as e:
body = json.loads(e.read())
code = e.code
assert code >= 400, "Invalid upload should return an error status"
assert "trace" not in body, \
"Upload errors must not leak stack traces to clients"
assert "error" in body, "Error responses must include an 'error' key"

118
tests/test_sprint19.py Normal file
View File

@@ -0,0 +1,118 @@
"""
Sprint 19 Tests: auth/login, security headers, request size limit.
"""
import json, urllib.error, urllib.request
BASE = "http://127.0.0.1:8788"
def get(path, headers=None):
req = urllib.request.Request(BASE + path)
if headers:
for k, v in headers.items():
req.add_header(k, v)
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read()), r.status, dict(r.headers)
def post(path, body=None, headers=None):
data = json.dumps(body or {}).encode()
req = urllib.request.Request(BASE + path, data=data,
headers={"Content-Type": "application/json"})
if headers:
for k, v in headers.items():
req.add_header(k, v)
try:
with urllib.request.urlopen(req, timeout=10) as r:
return json.loads(r.read()), r.status, dict(r.headers)
except urllib.error.HTTPError as e:
return json.loads(e.read()), e.code, dict(e.headers)
# ── Auth status (no password configured in test env) ──────────────────────
def test_auth_status_disabled():
"""Auth should be disabled by default (no password set)."""
d, status, _ = get("/api/auth/status")
assert status == 200
assert d["auth_enabled"] is False
def test_login_when_auth_disabled():
"""Login should succeed trivially when auth is not enabled."""
d, status, _ = post("/api/auth/login", {"password": "anything"})
assert status == 200
assert d["ok"] is True
def test_all_routes_accessible_without_auth():
"""When auth is disabled, all routes should work without cookies."""
d, status, _ = get("/api/sessions")
assert status == 200
assert "sessions" in d
def test_login_page_served():
"""GET /login should return the login page HTML."""
req = urllib.request.Request(BASE + "/login")
with urllib.request.urlopen(req, timeout=10) as r:
html = r.read().decode()
assert r.status == 200
assert "Sign in" in html
assert "Hermes" in html
# ── Security headers ─────────────────────────────────────────────────────
def test_security_headers_on_json():
"""JSON responses should include security headers."""
d, status, headers = get("/api/auth/status")
assert status == 200
assert headers.get("X-Content-Type-Options") == "nosniff"
assert headers.get("X-Frame-Options") == "DENY"
assert headers.get("Referrer-Policy") == "same-origin"
def test_security_headers_on_health():
"""Health endpoint should include security headers."""
d, status, headers = get("/health")
assert status == 200
assert headers.get("X-Content-Type-Options") == "nosniff"
def test_cache_control_no_store():
"""API responses should have Cache-Control: no-store."""
d, status, headers = get("/api/sessions")
assert headers.get("Cache-Control") == "no-store"
# ── Settings password field ──────────────────────────────────────────────
def test_settings_password_hash_not_exposed():
"""GET /api/settings must never expose the stored password hash."""
d, status, _ = get("/api/settings")
assert status == 200
assert "password_hash" not in d # security: never send hash to client
def test_settings_save_preserves_other_fields():
"""Saving settings should not break existing fields."""
# Get current settings
current, _, _ = get("/api/settings")
# Save with just send_key
d, status, _ = post("/api/settings", {"send_key": "enter"})
assert status == 200
# Verify other fields still present
updated, _, _ = get("/api/settings")
assert "default_model" in updated
assert "default_workspace" in updated
def test_settings_password_hash_not_directly_settable():
"""POST /api/settings with password_hash must not overwrite the stored hash."""
# Attempt to set a raw hash directly (attack vector)
post("/api/settings", {"password_hash": "deadbeef" * 8})
# Settings response must not expose it regardless
updated, status, _ = get("/api/settings")
assert status == 200
assert "password_hash" not in updated

422
tests/test_sprint20.py Normal file
View File

@@ -0,0 +1,422 @@
"""
Sprint 20 Tests: Voice input (mic button) via Web Speech API.
These tests verify the static assets contain the correct HTML structure,
CSS rules, and JS logic for the mic feature — all of which runs purely in
the browser with no server-side component.
"""
import re
import urllib.request
import json
BASE = "http://127.0.0.1:8788"
def get_text(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return r.read().decode(), r.status
# ── index.html ────────────────────────────────────────────────────────────
def test_mic_button_present_in_html():
"""index.html must contain the mic button with id='btnMic'."""
html, status = get_text("/")
assert status == 200
assert 'id="btnMic"' in html
def test_mic_button_has_mic_btn_class():
"""btnMic must carry the mic-btn CSS class for styling hooks."""
html, _ = get_text("/")
assert 'class="icon-btn mic-btn"' in html
def test_mic_button_hidden_by_default():
"""btnMic starts hidden (display:none) — JS shows it only if supported."""
html, _ = get_text("/")
# The button element should have display:none in its style attribute
assert 'id="btnMic"' in html
btn_match = re.search(r'id="btnMic"[^>]*>', html)
assert btn_match, "btnMic element not found"
assert 'display:none' in btn_match.group(0)
def test_mic_button_has_title():
"""btnMic should have a descriptive title for accessibility."""
html, _ = get_text("/")
btn_match = re.search(r'id="btnMic"[^>]*>', html)
assert btn_match
assert 'title=' in btn_match.group(0)
def test_mic_status_div_present():
"""index.html must contain the #micStatus listening indicator."""
html, _ = get_text("/")
assert 'id="micStatus"' in html
def test_mic_status_hidden_by_default():
"""#micStatus starts hidden — only shown during active recording."""
html, _ = get_text("/")
status_match = re.search(r'id="micStatus"[^>]*>', html)
assert status_match, "#micStatus element not found"
assert 'display:none' in status_match.group(0)
def test_mic_status_has_mic_dot():
"""#micStatus must contain a .mic-dot element for the pulse animation."""
html, _ = get_text("/")
# mic-dot should appear after micStatus
idx_status = html.find('id="micStatus"')
idx_dot = html.find('mic-dot', idx_status)
assert idx_status != -1 and idx_dot != -1
assert idx_dot > idx_status
def test_mic_status_has_listening_text():
"""#micStatus should display a 'Listening' label."""
html, _ = get_text("/")
assert 'Listening' in html
def test_mic_button_svg_microphone_shape():
"""btnMic SVG must include the rect (mic body) and path (mic arc)."""
html, _ = get_text("/")
# Find mic button section
btn_start = html.find('id="btnMic"')
btn_end = html.find('</button>', btn_start) + len('</button>')
btn_html = html[btn_start:btn_end]
assert '<rect' in btn_html, "mic SVG missing rect (mic body)"
assert '<path' in btn_html, "mic SVG missing path (arc)"
assert '<line' in btn_html, "mic SVG missing line (stand)"
def test_mic_button_inside_composer_left():
"""btnMic must be inside .composer-left, next to the attach button."""
html, _ = get_text("/")
composer_left_start = html.find('class="composer-left"')
composer_left_end = html.find('</div>', composer_left_start)
section = html[composer_left_start:composer_left_end]
assert 'btnAttach' in section
assert 'btnMic' in section
# ── style.css ────────────────────────────────────────────────────────────
def test_mic_btn_css_rule_exists():
"""style.css must define .mic-btn rule."""
css, status = get_text("/static/style.css")
assert status == 200
assert '.mic-btn' in css
def test_mic_btn_recording_state_css():
""".mic-btn.recording must be defined for active recording visual state."""
css, _ = get_text("/static/style.css")
assert '.mic-btn.recording' in css
def test_mic_recording_color_red():
""".mic-btn.recording must use the red accent color #e94560."""
css, _ = get_text("/static/style.css")
recording_idx = css.find('.mic-btn.recording')
# Find the rule block after the selector
brace_open = css.find('{', recording_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert '#e94560' in rule or 'e94560' in rule
def test_mic_recording_has_animation():
""".mic-btn.recording must use an animation for the pulse effect."""
css, _ = get_text("/static/style.css")
recording_idx = css.find('.mic-btn.recording')
brace_open = css.find('{', recording_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'animation' in rule
def test_mic_pulse_keyframes_defined():
"""@keyframes mic-pulse must be defined for the pulsing animation."""
css, _ = get_text("/static/style.css")
assert 'mic-pulse' in css
assert '@keyframes' in css
def test_mic_status_css_rule_exists():
"""style.css must define .mic-status rule."""
css, _ = get_text("/static/style.css")
assert '.mic-status' in css
def test_mic_dot_css_rule_exists():
"""style.css must define .mic-dot rule with animation."""
css, _ = get_text("/static/style.css")
assert '.mic-dot' in css
dot_idx = css.find('.mic-dot')
brace_open = css.find('{', dot_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'animation' in rule
def test_mic_btn_has_transition():
""".mic-btn must define a transition for smooth state changes."""
css, _ = get_text("/static/style.css")
mic_btn_idx = css.find('.mic-btn{')
if mic_btn_idx == -1:
mic_btn_idx = css.find('.mic-btn ')
brace_open = css.find('{', mic_btn_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'transition' in rule
# ── boot.js ──────────────────────────────────────────────────────────────
def test_boot_js_serves_ok():
"""boot.js must be served successfully."""
_, status = get_text("/static/boot.js")
assert status == 200
def test_boot_js_speech_recognition_check():
"""boot.js must check for SpeechRecognition (with webkit fallback)."""
js, _ = get_text("/static/boot.js")
assert 'SpeechRecognition' in js
assert 'webkitSpeechRecognition' in js
def test_boot_js_recognition_config():
"""boot.js must configure recognition.continuous, interimResults, and lang."""
js, _ = get_text("/static/boot.js")
assert 'recognition.continuous' in js
assert 'recognition.interimResults' in js
assert 'recognition.lang' in js
def test_boot_js_recognition_not_continuous():
"""recognition.continuous must be false (auto-stop after silence)."""
js, _ = get_text("/static/boot.js")
assert 'recognition.continuous=false' in js or 'recognition.continuous = false' in js
def test_boot_js_recognition_interim_results():
"""recognition.interimResults must be true (live transcription preview)."""
js, _ = get_text("/static/boot.js")
assert 'recognition.interimResults=true' in js or 'recognition.interimResults = true' in js
def test_boot_js_recognition_lang_en():
"""recognition.lang must be set to en-US."""
js, _ = get_text("/static/boot.js")
assert "recognition.lang='en-US'" in js or 'recognition.lang = "en-US"' in js or "recognition.lang='en-US'" in js
def test_boot_js_onresult_handler():
"""boot.js must define recognition.onresult to handle transcription."""
js, _ = get_text("/static/boot.js")
assert 'recognition.onresult' in js
def test_boot_js_onend_handler():
"""boot.js must define recognition.onend to reset state when recording stops."""
js, _ = get_text("/static/boot.js")
assert 'recognition.onend' in js
def test_boot_js_onerror_handler():
"""boot.js must define recognition.onerror for graceful error handling."""
js, _ = get_text("/static/boot.js")
assert 'recognition.onerror' in js
def test_boot_js_not_allowed_error_message():
"""onerror must handle 'not-allowed' with a user-friendly message."""
js, _ = get_text("/static/boot.js")
assert 'not-allowed' in js
assert 'permission' in js.lower() or 'denied' in js.lower() or 'access' in js.lower()
def test_boot_js_no_speech_error_message():
"""onerror must handle 'no-speech' with a user-friendly message."""
js, _ = get_text("/static/boot.js")
assert 'no-speech' in js
def test_boot_js_network_error_message():
"""onerror must handle 'network' error."""
js, _ = get_text("/static/boot.js")
assert "'network'" in js or '"network"' in js
def test_boot_js_mic_active_flag():
"""boot.js must track recording state via _micActive flag."""
js, _ = get_text("/static/boot.js")
assert '_micActive' in js
def test_boot_js_mic_recording_class_toggle():
"""boot.js must toggle 'recording' CSS class on the mic button."""
js, _ = get_text("/static/boot.js")
assert "'recording'" in js or '"recording"' in js
def test_boot_js_mic_status_toggle():
"""boot.js must show/hide #micStatus during recording."""
js, _ = get_text("/static/boot.js")
assert 'micStatus' in js
def test_boot_js_send_stops_mic():
"""btnSend onclick must stop mic before sending (send guard)."""
js, _ = get_text("/static/boot.js")
# The send button onclick should check _micActive and stop recording
send_onclick_idx = js.find("$('btnSend').onclick")
assert send_onclick_idx != -1
# Find the handler code — check that _micActive check appears near send assignment
handler_end = js.find(';', send_onclick_idx)
handler = js[send_onclick_idx:handler_end + 1]
assert '_micActive' in handler or 'stopMic' in handler.lower()
def test_boot_js_btn_mic_onclick():
"""boot.js must attach an onclick handler to btnMic."""
js, _ = get_text("/static/boot.js")
assert 'btn.onclick' in js or "btnMic.onclick" in js or "$('btnMic').onclick" in js
def test_boot_js_recognition_start():
"""boot.js must call recognition.start() to begin recording."""
js, _ = get_text("/static/boot.js")
assert 'recognition.start()' in js
def test_boot_js_recognition_stop():
"""boot.js must call recognition.stop() to end recording."""
js, _ = get_text("/static/boot.js")
assert 'recognition.stop()' in js
def test_boot_js_iife_guard():
"""Mic logic must be wrapped in an IIFE so it doesn't pollute global scope."""
js, _ = get_text("/static/boot.js")
# IIFE pattern: (function(){...})() or (() => {...})()
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."""
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
def test_boot_js_shows_mic_button_when_supported():
"""boot.js must set display='' on btnMic when SpeechRecognition is available."""
js, _ = get_text("/static/boot.js")
assert "btn.style.display=''" in js or 'btn.style.display = ""' in js
def test_boot_js_show_toast_on_error():
"""boot.js must call showToast() for mic errors."""
js, _ = get_text("/static/boot.js")
assert 'showToast' in js
def test_boot_js_autoresize_called():
"""boot.js must call autoResize() after updating textarea from transcript."""
js, _ = get_text("/static/boot.js")
assert 'autoResize()' in js
# ── Append behaviour (fix: mic appends to existing text, not replace) ────
def test_boot_js_prefix_variable_declared():
"""boot.js must declare _prefix variable to snapshot pre-existing textarea content."""
js, _ = get_text("/static/boot.js")
assert "_prefix" in js
def test_boot_js_prefix_captured_on_start():
"""_prefix must be set from ta.value when the user starts recording."""
js, _ = get_text("/static/boot.js")
# _prefix assignment must happen in the btn.onclick else branch (before recognition.start)
btn_onclick_idx = js.find("btn.onclick")
btn_onclick_end = js.find("};", btn_onclick_idx)
onclick_body = js[btn_onclick_idx:btn_onclick_end]
assert "_prefix=ta.value" in onclick_body or "_prefix = ta.value" in onclick_body
def test_boot_js_onresult_prepends_prefix():
"""onresult must include _prefix when writing to textarea (append, not replace)."""
js, _ = get_text("/static/boot.js")
onresult_idx = js.find("recognition.onresult")
onresult_end = js.find("};", onresult_idx)
onresult_body = js[onresult_idx:onresult_end]
# ta.value must be set to _prefix + something, not just the transcript alone
assert "_prefix" in onresult_body
def test_boot_js_onend_commits_with_prefix():
"""onend must commit _prefix + _finalText so appended text survives after recognition ends."""
js, _ = get_text("/static/boot.js")
onend_idx = js.find("recognition.onend")
onend_end = js.find("};", onend_idx)
onend_body = js[onend_idx:onend_end]
assert "_prefix" in onend_body
def test_boot_js_prefix_reset_on_stop():
"""_prefix must be reset when recording stops so next session starts clean."""
js, _ = get_text("/static/boot.js")
# _setRecording(false) clears both _finalText and _prefix
set_rec_idx = js.find("function _setRecording")
set_rec_end = js.find("}", set_rec_idx) + 1
fn_body = js[set_rec_idx:set_rec_end]
assert "_prefix" in fn_body
def test_boot_js_auto_space_between_prefix_and_transcript():
"""onend must insert a space between existing text and new transcript when needed."""
js, _ = get_text("/static/boot.js")
onend_idx = js.find("recognition.onend")
onend_end = js.find("};", onend_idx)
onend_body = js[onend_idx:onend_end]
# Should handle spacing — look for trimStart or endsWith(' ') check
has_spacing = ("trimStart" in onend_body or "endsWith(' ')" in onend_body
or "endsWith(\" \")" in onend_body or "endsWith('\\n')" in onend_body)
assert has_spacing, "onend should handle spacing between prefix and new transcript"
# ── Regression: existing behaviour unchanged ──────────────────────────────
def test_attach_button_still_wired():
"""btnAttach onclick must still be wired up (no regression)."""
js, _ = get_text("/static/boot.js")
assert "$('btnAttach').onclick" in js
def test_file_input_onchange_still_wired():
"""fileInput onchange must still be wired up (no regression)."""
js, _ = get_text("/static/boot.js")
assert "$('fileInput').onchange" in js
def test_index_html_still_has_send_button():
"""btnSend must still be present in index.html (no regression)."""
html, _ = get_text("/")
assert 'id="btnSend"' in html
def test_index_html_still_has_attach_button():
"""btnAttach must still be present in index.html (no regression)."""
html, _ = get_text("/")
assert 'id="btnAttach"' in html

343
tests/test_sprint20b.py Normal file
View File

@@ -0,0 +1,343 @@
"""
Sprint 21 Tests: Send button polish — hidden until content, pop-in animation,
icon-only circle design.
"""
import re
import urllib.request
BASE = "http://127.0.0.1:8788"
def get_text(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return r.read().decode(), r.status
# ── index.html ────────────────────────────────────────────────────────────
def test_send_button_present():
"""btnSend must still exist in the DOM."""
html, status = get_text("/")
assert status == 200
assert 'id="btnSend"' in html
def test_send_button_hidden_by_default():
"""btnSend must start hidden (display:none) — only shown when there is content."""
html, _ = get_text("/")
btn_match = re.search(r'id="btnSend"[^>]*>', html)
assert btn_match, "btnSend element not found"
assert 'display:none' in btn_match.group(0)
def test_send_button_no_text_label():
"""Send button must be icon-only — no visible 'Send' text label."""
html, _ = get_text("/")
# Find the full button element (from opening tag to closing tag)
btn_open_end = html.find('>', html.find('id="btnSend"')) + 1
btn_end = html.find('</button>', btn_open_end) + len('</button>')
btn_inner = html[btn_open_end:btn_end]
# Strip SVG content and any remaining tags; check visible text
no_svg = re.sub(r'<svg[^>]*>.*?</svg>', '', btn_inner, flags=re.DOTALL)
visible_text = re.sub(r'<[^>]+>', '', no_svg).strip()
assert visible_text == '', f"Send button has visible text: {visible_text!r}"
def test_send_button_has_svg_icon():
"""Send button must have an SVG icon."""
html, _ = get_text("/")
btn_start = html.find('id="btnSend"')
btn_end = html.find('</button>', btn_start) + len('</button>')
btn_html = html[btn_start:btn_end]
assert '<svg' in btn_html
def test_send_button_has_title_attribute():
"""btnSend must have a title attribute for accessibility (replaces text label)."""
html, _ = get_text("/")
btn_match = re.search(r'id="btnSend"[^>]*>', html)
assert btn_match
assert 'title=' in btn_match.group(0)
def test_send_button_svg_arrow_up():
"""Send button SVG should use an upward arrow (line + polyline or path)."""
html, _ = get_text("/")
btn_start = html.find('id="btnSend"')
btn_end = html.find('</button>', btn_start) + len('</button>')
btn_html = html[btn_start:btn_end]
# Must have some directional shape element
has_shape = ('<line' in btn_html or '<polyline' in btn_html or
'<polygon' in btn_html or '<path' in btn_html)
assert has_shape, "Send button SVG missing directional shape"
# ── style.css ────────────────────────────────────────────────────────────
def test_send_btn_is_circle():
"""send-btn must use border-radius:50% for the circle shape."""
css, status = get_text("/static/style.css")
assert status == 200
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'border-radius:50%' in rule or 'border-radius: 50%' in rule
def test_send_btn_fixed_dimensions():
"""send-btn must have explicit width and height (icon-circle, not text-padded)."""
css, _ = get_text("/static/style.css")
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'width:' in rule or 'width :' in rule
assert 'height:' in rule or 'height :' in rule
def test_send_btn_no_old_padding():
"""send-btn must not use text padding layout (old pill style removed)."""
css, _ = get_text("/static/style.css")
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
# Old style used padding:7px 18px — should be gone
assert 'padding:7px' not in rule and 'padding: 7px' not in rule
def test_send_btn_blue_background():
"""send-btn background must use the blue accent (#7cb9ff or similar)."""
css, _ = get_text("/static/style.css")
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert '7cb9ff' in rule or '5ba8f5' in rule or 'var(--blue)' in rule
def test_send_btn_has_transition():
"""send-btn must have transition for smooth hover/active states."""
css, _ = get_text("/static/style.css")
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'transition' in rule
def test_send_btn_has_box_shadow():
"""send-btn must have a box-shadow glow effect."""
css, _ = get_text("/static/style.css")
send_idx = css.find('.send-btn{')
brace_open = css.find('{', send_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'box-shadow' in rule
def test_send_btn_hover_has_scale():
"""send-btn:hover must use transform:scale for a satisfying hover effect."""
css, _ = get_text("/static/style.css")
hover_idx = css.find('.send-btn:hover{')
brace_open = css.find('{', hover_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'scale' in rule
def test_send_btn_active_shrinks():
"""send-btn:active must scale down slightly for tactile press feedback."""
css, _ = get_text("/static/style.css")
active_idx = css.find('.send-btn:active{')
brace_open = css.find('{', active_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'scale' in rule
def test_send_btn_disabled_rule_exists():
"""send-btn:disabled must still be styled."""
css, _ = get_text("/static/style.css")
assert '.send-btn:disabled' in css
def test_send_btn_visible_class_defined():
""".send-btn.visible class must be defined for the pop-in animation."""
css, _ = get_text("/static/style.css")
assert '.send-btn.visible' in css
def test_send_pop_in_keyframes_defined():
"""@keyframes send-pop-in must be defined."""
css, _ = get_text("/static/style.css")
assert 'send-pop-in' in css
assert '@keyframes' in css
def _extract_keyframe(css, name):
"""Extract the full @keyframes block for the given animation name."""
# Find '@keyframes <name>' directly (forward search) to avoid hitting
# an earlier keyframe when multiple are defined on the same line.
kf_start = css.find('@keyframes ' + name)
assert kf_start != -1, f"@keyframes {name} not found in CSS"
depth = 0
kf_end = kf_start
for i, ch in enumerate(css[kf_start:], kf_start):
if ch == '{':
depth += 1
elif ch == '}':
depth -= 1
if depth == 0:
kf_end = i
break
return css[kf_start:kf_end]
def test_send_pop_in_uses_scale():
"""send-pop-in keyframe must animate from a scaled-down state."""
css, _ = get_text("/static/style.css")
kf_rule = _extract_keyframe(css, 'send-pop-in')
assert 'scale' in kf_rule
def test_send_pop_in_uses_opacity():
"""send-pop-in keyframe must fade in (opacity transition)."""
css, _ = get_text("/static/style.css")
kf_rule = _extract_keyframe(css, 'send-pop-in')
assert 'opacity' in kf_rule
def test_send_btn_mobile_override_no_padding():
"""Mobile override for send-btn must not add text padding (keeps circle shape)."""
css, _ = get_text("/static/style.css")
# Find the @media block
media_idx = css.find('@media')
send_mobile_idx = css.find('.send-btn', media_idx)
if send_mobile_idx == -1:
return # No mobile override, fine
brace_open = css.find('{', send_mobile_idx)
brace_close = css.find('}', brace_open)
rule = css[brace_open:brace_close]
assert 'padding:' not in rule and 'font-size' not in rule
# ── ui.js ─────────────────────────────────────────────────────────────────
def test_ui_js_update_send_btn_function():
"""ui.js must define updateSendBtn() function."""
js, status = get_text("/static/ui.js")
assert status == 200
assert 'function updateSendBtn' in js
def test_update_send_btn_checks_content():
"""updateSendBtn must check textarea value length."""
js, _ = get_text("/static/ui.js")
fn_idx = js.find('function updateSendBtn')
fn_end = js.find('\n}', fn_idx) + 2
fn_body = js[fn_idx:fn_end]
assert 'msg' in fn_body
assert '.value' in fn_body
assert '.length' in fn_body or '.trim()' in fn_body
def test_update_send_btn_checks_pending_files():
"""updateSendBtn must also show send button when files are attached."""
js, _ = get_text("/static/ui.js")
fn_idx = js.find('function updateSendBtn')
fn_end = js.find('\n}', fn_idx) + 2
fn_body = js[fn_idx:fn_end]
assert 'pendingFiles' in fn_body
def test_update_send_btn_uses_visible_class():
"""updateSendBtn must add .visible class to trigger the pop-in animation."""
js, _ = get_text("/static/ui.js")
fn_idx = js.find('function updateSendBtn')
fn_end = js.find('\n}', fn_idx) + 2
fn_body = js[fn_idx:fn_end]
assert 'visible' in fn_body
def test_update_send_btn_uses_display_none():
"""updateSendBtn must hide the button with display:none when no content."""
js, _ = get_text("/static/ui.js")
fn_idx = js.find('function updateSendBtn')
fn_end = js.find('\n}', fn_idx) + 2
fn_body = js[fn_idx:fn_end]
assert 'display' in fn_body
assert 'none' in fn_body
def test_set_busy_calls_update_send_btn():
"""setBusy must call updateSendBtn() so button hides while agent is responding."""
js, _ = get_text("/static/ui.js")
busy_idx = js.find('function setBusy')
busy_end = js.find('\n}', busy_idx) + 2
busy_body = js[busy_idx:busy_end]
assert 'updateSendBtn' in busy_body
def test_render_tray_calls_update_send_btn():
"""renderTray must call updateSendBtn() so button appears when files are attached."""
js, _ = get_text("/static/ui.js")
tray_idx = js.find('function renderTray')
tray_end = js.find('\n}', tray_idx) + 2
tray_body = js[tray_idx:tray_end]
assert 'updateSendBtn' in tray_body
# ── boot.js ──────────────────────────────────────────────────────────────
def test_boot_js_input_calls_update_send_btn():
"""boot.js input event listener must call updateSendBtn()."""
js, status = get_text("/static/boot.js")
assert status == 200
assert 'updateSendBtn' in js
# ── messages.js ───────────────────────────────────────────────────────────
def test_auto_resize_calls_update_send_btn():
"""autoResize() must call updateSendBtn() so button hides after send clears textarea."""
js, status = get_text("/static/messages.js")
assert status == 200
assert 'updateSendBtn' in js
# ── Regression: existing behaviour unchanged ──────────────────────────────
def test_send_button_still_has_send_btn_class():
"""btnSend must still carry class='send-btn' for CSS targeting."""
html, _ = get_text("/")
assert 'class="send-btn"' in html
def test_ui_js_set_busy_still_disables_btn():
"""setBusy must still set btnSend.disabled (not just hide it)."""
js, _ = get_text("/static/ui.js")
busy_idx = js.find('function setBusy')
busy_end = js.find('\n}', busy_idx) + 2
busy_body = js[busy_idx:busy_end]
assert "btnSend" in busy_body
assert 'disabled' in busy_body
def test_index_html_attach_button_unchanged():
"""btnAttach must still be present (no regression)."""
html, _ = get_text("/")
assert 'id="btnAttach"' in html
def test_send_function_still_exists():
"""send() function must still be defined in messages.js."""
js, _ = get_text("/static/messages.js")
assert 'async function send()' in js

196
tests/test_sprint23.py Normal file
View File

@@ -0,0 +1,196 @@
"""
Sprint 23 Tests: agentic transparency — token/cost display, session usage fields,
subagent card names, skill picker in cron, skill linked files.
"""
import json, urllib.error, urllib.request
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
def make_session(created_list):
d, _ = post("/api/session/new", {})
sid = d["session"]["session_id"]
created_list.append(sid)
return sid, d["session"]
# ── Session usage fields ─────────────────────────────────────────────────
def test_new_session_has_usage_fields():
"""New session should include input_tokens, output_tokens, estimated_cost."""
created = []
try:
sid, sess = make_session(created)
post("/api/session/rename", {"session_id": sid, "title": "Usage Test"})
d, status = get(f"/api/session?session_id={sid}")
assert status == 200
sess = d["session"]
assert "input_tokens" in sess, "input_tokens field missing from session"
assert "output_tokens" in sess, "output_tokens field missing from session"
assert "estimated_cost" in sess, "estimated_cost field missing from session"
assert sess["input_tokens"] == 0
assert sess["output_tokens"] == 0
finally:
for s in created:
post("/api/session/delete", {"session_id": s})
def test_session_compact_has_usage_fields():
"""Session list should include usage fields in compact form."""
created = []
try:
sid, _ = make_session(created)
post("/api/session/rename", {"session_id": sid, "title": "Compact Usage"})
d, status = get("/api/sessions")
assert status == 200
match = [s for s in d["sessions"] if s["session_id"] == sid]
assert len(match) == 1
assert "input_tokens" in match[0], "input_tokens missing from session list"
assert "output_tokens" in match[0], "output_tokens missing from session list"
assert match[0]["input_tokens"] == 0
assert match[0]["output_tokens"] == 0
finally:
for s in created:
post("/api/session/delete", {"session_id": s})
def test_session_usage_defaults_zero():
"""New session usage fields should default to 0/None in creation response."""
created = []
try:
sid, sess = make_session(created)
assert "input_tokens" in sess, "input_tokens missing from new session response"
assert "output_tokens" in sess, "output_tokens missing from new session response"
assert sess["input_tokens"] == 0
assert sess["output_tokens"] == 0
finally:
for s in created:
post("/api/session/delete", {"session_id": s})
# ── Skills content linked_files ──────────────────────────────────────────
def test_skills_content_requires_name():
"""GET /api/skills/content without name should return 400 (or 500 if skills module unavailable)."""
try:
d, status = get("/api/skills/content")
assert status in (400, 500), f"Expected 400/500 for missing name, got {status}"
except urllib.error.HTTPError as e:
assert e.code in (400, 500), f"Expected 400/500 for missing name, got {e.code}"
def test_skills_content_has_linked_files_key():
"""GET /api/skills/content should always return a linked_files key."""
try:
d, status = get("/api/skills")
if not d.get("skills"):
return # no skills in test env, skip
name = d["skills"][0]["name"]
d2, status2 = get(f"/api/skills/content?name={name}")
assert status2 == 200
assert "linked_files" in d2, "linked_files key missing from skills/content response"
# linked_files must be a dict (possibly empty), not None
assert isinstance(d2["linked_files"], dict), "linked_files must be a dict"
except urllib.error.HTTPError:
pass # skills module unavailable in this env
def test_skills_content_file_path_traversal_rejected():
"""GET /api/skills/content with traversal path should be rejected."""
from urllib.parse import quote as _quote
try:
d, status = get("/api/skills")
if not d.get("skills"):
return # no skills in test env, skip
name = d["skills"][0]["name"]
traversal = _quote("../../etc/passwd", safe="")
try:
d2, status2 = get(f"/api/skills/content?name={name}&file={traversal}")
assert status2 in (400, 404, 500), f"Path traversal should be rejected, got {status2}"
except urllib.error.HTTPError as e:
assert e.code in (400, 404, 500), f"Path traversal should be rejected, got {e.code}"
except urllib.error.HTTPError:
pass # skills module unavailable in test env
def test_skills_content_wildcard_name_rejected():
"""GET /api/skills/content with glob wildcard in name should be rejected when file param present."""
try:
try:
d2, status2 = get("/api/skills/content?name=*&file=SKILL.md")
assert status2 == 400, f"Wildcard name should return 400, got {status2}"
except urllib.error.HTTPError as e:
assert e.code in (400, 404), f"Wildcard name should be rejected, got {e.code}"
except Exception:
pass
# ── Cron create with skills ───────────────────────────────────────────────
def test_cron_create_accepts_skills():
"""POST /api/crons/create should accept and store a skills array (or 500 if cron module unavailable)."""
created_jobs = []
try:
body = {
"name": "test-sprint23-skills",
"schedule": "0 9 * * *",
"prompt": "test prompt",
"deliver": "local",
"skills": ["some-skill"]
}
d, status = post("/api/crons/create", body)
if status in (400, 500) and ('module' in str(d.get('error','')) or 'cron' in str(d.get('error',''))):
return # cron module not available in test env
assert status == 200, f"Expected 200 from cron create, got {status}: {d}"
assert d.get("ok"), f"Cron create did not return ok: {d}"
job_id = d.get("job", {}).get("id") or d.get("id")
if job_id:
created_jobs.append(job_id)
# Verify job appears in list
jobs_d, _ = get("/api/crons")
job = next((j for j in jobs_d.get("jobs", []) if j.get("name") == "test-sprint23-skills"), None)
assert job is not None, "Created cron job not found in job list"
assert job.get("skills") == ["some-skill"] or job.get("skill") == "some-skill", \
f"skills not stored on job: {job}"
finally:
try:
for jid in created_jobs:
post("/api/crons/delete", {"id": jid})
jobs_d, _ = get("/api/crons")
for j in jobs_d.get("jobs", []):
if j.get("name") == "test-sprint23-skills":
post("/api/crons/delete", {"id": j["id"]})
except Exception:
pass # cron module may not be available
# ── Tool call integrity ──────────────────────────────────────────────────
def test_tool_calls_have_real_names():
"""Tool calls in session JSON should not have unresolved 'tool' name."""
created = []
try:
sid, _ = make_session(created)
d, status = get(f"/api/session?session_id={sid}")
assert status == 200
for tc in d["session"].get("tool_calls", []):
assert tc.get("name") not in ("tool", "", None), f"Unresolved tool name: {tc}"
finally:
for s in created:
post("/api/session/delete", {"session_id": s})