Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
279690e4c1 | ||
|
|
2766314e81 | ||
|
|
9d69408610 | ||
|
|
4a3b9571f1 | ||
|
|
c488031fe3 | ||
|
|
94b080fa1e | ||
|
|
e6663596ce | ||
|
|
16553be59d | ||
|
|
6a61f36280 | ||
|
|
b03ddf78c9 | ||
|
|
5c9edfc7bf | ||
|
|
733957cea1 | ||
|
|
e61382ef71 | ||
|
|
da43a6a09a | ||
|
|
4eae6c98f9 | ||
|
|
c71439d8ab | ||
|
|
ad755e49e5 | ||
|
|
f75e17c912 | ||
|
|
3d8cf85ef2 | ||
|
|
d4ab01c152 | ||
|
|
c778c1eb0c | ||
|
|
ca01845643 | ||
|
|
30529e0002 | ||
|
|
7ef203cd41 | ||
|
|
3520fa5643 | ||
|
|
0480bbf34c | ||
|
|
28ac04da7d |
57
.github/workflows/release.yml
vendored
Normal file
57
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
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 semver tags: e.g. v0.28 -> 0.28, latest
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
# 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
|
||||
@@ -26,32 +26,36 @@ 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 + auth middleware. ~79 lines.
|
||||
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
|
||||
auth.py Optional password authentication, signed cookies (~149 lines)
|
||||
routes.py All GET + POST route handlers (~1109 lines)
|
||||
config.py Shared configuration, constants, global state, model discovery (~654 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 (~132 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 (~590 lines)
|
||||
ui.js DOM helpers, renderMd, tool cards, model dropdown, file tree (~957 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 (~532 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, todo, switchPanel, settings (~813 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, keydown handlers, boot IIFE (~208 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_sprint{1-19}.py Feature tests per sprint (17 files, 327 test functions)
|
||||
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.
|
||||
@@ -95,6 +99,7 @@ Environment variables controlling behavior:
|
||||
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):
|
||||
|
||||
@@ -113,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.
|
||||
|
||||
113
CHANGELOG.md
113
CHANGELOG.md
@@ -5,6 +5,117 @@
|
||||
|
||||
---
|
||||
|
||||
## [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*
|
||||
|
||||
@@ -793,4 +904,4 @@ Three-panel layout: sessions sidebar, chat area, workspace panel.
|
||||
|
||||
---
|
||||
|
||||
*Last updated: v0.24, April 3, 2026 | Tests: 415*
|
||||
*Last updated: v0.27, April 3, 2026 | Tests: 426*
|
||||
|
||||
121
README.md
121
README.md
@@ -106,7 +106,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 |
|
||||
|
||||
---
|
||||
@@ -158,17 +159,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: **415 tests**
|
||||
across 21 test files.
|
||||
|
||||
---
|
||||
|
||||
@@ -176,22 +178,27 @@ 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
|
||||
- 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
|
||||
@@ -199,56 +206,105 @@ Production data and real cron jobs are never touched.
|
||||
- Browser tab title reflects the active session name
|
||||
|
||||
### 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
|
||||
- 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`
|
||||
- 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
|
||||
- **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
|
||||
- **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 (~701 lines)
|
||||
helpers.py HTTP helpers, security headers (~71 lines)
|
||||
models.py Session model + CRUD (~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 support (~236 lines)
|
||||
upload.py Multipart parser, file upload handler (~78 lines)
|
||||
workspace.py File ops, workspace helpers (~77 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 (~977 lines)
|
||||
workspace.js File preview, file ops (~185 lines)
|
||||
sessions.js Session CRUD, list rendering, search (~533 lines)
|
||||
messages.js send(), SSE handlers, approval, transcript (~297 lines)
|
||||
panels.js Cron, skills, memory, profiles, settings (~974 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-20b}.py 21 test files, 415 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
|
||||
```
|
||||
|
||||
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`.
|
||||
|
||||
---
|
||||
|
||||
@@ -257,7 +313,8 @@ State lives outside the repo at `~/.hermes/webui-mvp/` by default
|
||||
- `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
|
||||
|
||||
|
||||
34
ROADMAP.md
34
ROADMAP.md
@@ -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 19 / v0.21 (April 3, 2026)
|
||||
> Tests: 328 total (328 passing, 0 failures)
|
||||
> Last updated: Sprint 22 / v0.24 (April 3, 2026)
|
||||
> Tests: 415 total (392 passing, 23 pre-existing failures)
|
||||
> Source: <repo>/
|
||||
|
||||
---
|
||||
@@ -36,6 +36,9 @@
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -43,10 +46,11 @@
|
||||
|
||||
| Layer | Location | Status |
|
||||
|-------|----------|--------|
|
||||
| Python server | <repo>/server.py (~79 lines) + api/ modules (~2491 lines) | Thin shell + auth middleware + business logic in api/ |
|
||||
| HTML template | <repo>/static/index.html | Served from disk |
|
||||
| CSS | <repo>/static/style.css (~590 lines) | Served from disk |
|
||||
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands}.js | 7 modules, ~3148 lines total |
|
||||
| Python server | <repo>/server.py (~81 lines) + api/ modules (~2876 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, ~3460 lines total |
|
||||
| Docker | Dockerfile, docker-compose.yml, .dockerignore | python:3.12-slim, named volume |
|
||||
| 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 |
|
||||
@@ -176,16 +180,22 @@
|
||||
### 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 (Sprint 20)
|
||||
- [ ] TTS playback of responses (Sprint 20)
|
||||
- [ ] TTS playback of responses (deferred)
|
||||
- [ ] Subagent delegation cards (deferred)
|
||||
- [x] Background task cancel (activity bar Cancel button)
|
||||
- [ ] Code execution cell (deferred)
|
||||
- [ ] Mobile responsive layout (Sprint 21)
|
||||
- [ ] Multi-profile support (Sprint 22, Issue #28)
|
||||
- [ ] Desktop application (Sprint 23)
|
||||
- [ ] Extended slash command / skill integration (Sprint 24)
|
||||
- [ ] Desktop application (deferred)
|
||||
- [ ] Extended slash command / skill integration (deferred)
|
||||
- [ ] Virtual scroll for large lists (deferred)
|
||||
|
||||
---
|
||||
|
||||
64
SPRINTS.md
64
SPRINTS.md
@@ -1,6 +1,6 @@
|
||||
# Hermes Web UI -- Forward Sprint Plan
|
||||
|
||||
> Current state: v0.24 | 415 tests | Daily driver ready
|
||||
> Current state: v0.27 | 426 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
|
||||
@@ -511,7 +511,63 @@ single default profile, blocking multi-persona workflows.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 23 -- Desktop Application (PLANNED)
|
||||
## 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 -- Desktop Application (PLANNED)
|
||||
|
||||
**Theme:** Native desktop experience.
|
||||
|
||||
@@ -607,5 +663,5 @@ single default profile, blocking multi-persona workflows.
|
||||
---
|
||||
|
||||
*Last updated: April 3, 2026*
|
||||
*Current version: v0.24 | 415 tests*
|
||||
*Next sprint: Sprint 23 (Desktop Application)*
|
||||
*Current version: v0.27 | 426 tests*
|
||||
*Next sprint: Sprint 24 (Desktop Application)*
|
||||
|
||||
47
TESTING.md
47
TESTING.md
@@ -1,14 +1,14 @@
|
||||
# Hermes Web UI: Browser Testing Plan
|
||||
|
||||
> This document is for manual browser testing by you or by a Claude browser agent.
|
||||
> It covers user-facing features of the UI through Sprint 19 (v0.21).
|
||||
> 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: 328 total (328 passing, 0 failures).
|
||||
> Automated tests: 415 total (392 passing, 23 pre-existing failures).
|
||||
> Run: `pytest tests/ -v --timeout=60`
|
||||
|
||||
---
|
||||
@@ -1667,10 +1667,49 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
- 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 19 / v0.21, April 3, 2026*
|
||||
*Total automated tests: 328 (328 passing, 0 failures)*
|
||||
*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>/*
|
||||
|
||||
@@ -373,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
|
||||
|
||||
|
||||
@@ -90,6 +90,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
|
||||
@@ -105,7 +110,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'):
|
||||
|
||||
150
api/profiles.py
150
api/profiles.py
@@ -10,13 +10,60 @@ 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()
|
||||
_DEFAULT_HERMES_HOME = Path.home() / '.hermes'
|
||||
|
||||
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:
|
||||
@@ -148,7 +195,23 @@ def switch_profile(name: str) -> dict:
|
||||
# Reload config.yaml from the new profile
|
||||
reload_config()
|
||||
|
||||
return {'profiles': list_profiles_api(), 'active': name}
|
||||
# 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:
|
||||
@@ -192,28 +255,85 @@ def _default_profile_dict() -> dict:
|
||||
}
|
||||
|
||||
|
||||
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, validate_profile_name
|
||||
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:
|
||||
raise RuntimeError('Profile management requires hermes-agent to be installed.')
|
||||
_create_profile_fallback(name, clone_from, clone_config)
|
||||
|
||||
validate_profile_name(name)
|
||||
create_profile(
|
||||
name,
|
||||
clone_from=clone_from,
|
||||
clone_config=clone_config,
|
||||
clone_all=False,
|
||||
no_alias=True,
|
||||
)
|
||||
|
||||
# Find and return the newly created profile info
|
||||
# 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(_DEFAULT_HERMES_HOME / 'profiles' / name)}
|
||||
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:
|
||||
|
||||
@@ -112,13 +112,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,
|
||||
@@ -203,7 +228,18 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
|
||||
except Exception as e:
|
||||
print('[webui] stream error:\n' + traceback.format_exc(), flush=True)
|
||||
put('error', {'message': str(e)})
|
||||
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:
|
||||
|
||||
188
api/workspace.py
188
api/workspace.py
@@ -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
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ services:
|
||||
volumes:
|
||||
# Persist session data, settings, and projects across restarts
|
||||
- hermes-data:/data
|
||||
# Mount hermes-agent for full agent features (optional)
|
||||
- ${HERMES_HOME:-${HOME}/.hermes}:/root/.hermes:ro
|
||||
# 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
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<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.24</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.27</div></div></div>
|
||||
<div class="sidebar-nav">
|
||||
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat">💬</button>
|
||||
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks">📅</button>
|
||||
@@ -145,13 +145,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">📁</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">📁</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">▾</span>
|
||||
</div>
|
||||
<span style="font-size:10px;color:var(--muted);flex-shrink:0">▾</span>
|
||||
<div class="ws-dropdown" id="wsDropdown"></div>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<button class="sm-btn" id="btnDownload" title="Download as Markdown">↓ Transcript</button>
|
||||
@@ -174,10 +177,7 @@
|
||||
<div class="profile-dropdown" id="profileDropdown"></div>
|
||||
</div>
|
||||
<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">📁 test-workspace ▾</div>
|
||||
<div class="ws-dropdown" id="wsDropdown"></div>
|
||||
</div>
|
||||
|
||||
<button class="chip clear-btn" id="btnClearConv" onclick="clearConversation()" title="Clear all messages in this conversation" style="display:none">🗑 Clear</button>
|
||||
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings">⚙</button>
|
||||
<button class="chip mobile-files-btn" id="btnMobileFiles" onclick="toggleMobileFiles()" title="Files">📁</button>
|
||||
|
||||
@@ -162,6 +162,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
|
||||
|
||||
@@ -490,7 +490,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(){
|
||||
@@ -660,18 +660,74 @@ document.addEventListener('click', e => {
|
||||
|
||||
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;
|
||||
syncTopbar();
|
||||
// Refresh dependent panels
|
||||
|
||||
// ── 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();
|
||||
showToast('Switched to profile: ' + name);
|
||||
if (_currentPanel === 'workspaces') await loadWorkspacesPanel();
|
||||
|
||||
} catch (e) { showToast('Switch failed: ' + e.message); }
|
||||
}
|
||||
|
||||
|
||||
@@ -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.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');
|
||||
|
||||
@@ -345,7 +345,7 @@
|
||||
|
||||
/* ── 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);}
|
||||
|
||||
75
static/ui.js
75
static/ui.js
@@ -7,6 +7,38 @@ const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'&
|
||||
// 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
|
||||
@@ -320,15 +344,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');
|
||||
@@ -336,13 +368,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');
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
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();
|
||||
}
|
||||
|
||||
193
tests/test_sprint23.py
Normal file
193
tests/test_sprint23.py
Normal file
@@ -0,0 +1,193 @@
|
||||
"""Sprint 23 tests: profile/workspace/model coherence."""
|
||||
import json, pathlib, re, urllib.request, urllib.error
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ── Workspace profile-locality ──────────────────────────────────────────────
|
||||
|
||||
def test_workspace_list_returns_data():
|
||||
"""Workspace list endpoint works after profile-local refactor."""
|
||||
data, status = get("/api/workspaces")
|
||||
assert status == 200
|
||||
assert "workspaces" in data
|
||||
assert isinstance(data["workspaces"], list)
|
||||
assert "last" in data
|
||||
|
||||
|
||||
def test_workspace_add_remove_roundtrip():
|
||||
"""Workspace add/remove still works with profile-local storage."""
|
||||
import os
|
||||
# Use a path that won't resolve differently (macOS /tmp -> /private/tmp)
|
||||
resolved_tmp = str(pathlib.Path("/tmp").resolve())
|
||||
# Clean slate
|
||||
post("/api/workspaces/remove", {"path": resolved_tmp})
|
||||
# Add
|
||||
data, status = post("/api/workspaces/add", {"path": "/tmp", "name": "Temp"})
|
||||
assert status == 200
|
||||
assert any(w["path"] == resolved_tmp for w in data.get("workspaces", []))
|
||||
# Remove
|
||||
data, status = post("/api/workspaces/remove", {"path": resolved_tmp})
|
||||
assert status == 200
|
||||
assert not any(w["path"] == resolved_tmp for w in data.get("workspaces", []))
|
||||
|
||||
|
||||
# ── Profile switch response fields ─────────────────────────────────────────
|
||||
|
||||
def test_profile_switch_returns_default_model_and_workspace():
|
||||
"""switch_profile() response includes default_model and default_workspace."""
|
||||
# Prior tests (test_chat_stream_opens_successfully) may leave a live LLM stream in
|
||||
# STREAMS. The server-side thread keeps running until the LLM response completes.
|
||||
# Wait up to 30 seconds for it to drain before attempting the profile switch.
|
||||
import time
|
||||
for _ in range(60):
|
||||
health, _ = get("/health")
|
||||
if health.get("active_streams", 0) == 0:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
data, status = post("/api/profile/switch", {"name": "default"})
|
||||
assert status == 200, f"Profile switch returned {status}: {data}"
|
||||
assert "active" in data
|
||||
assert data["active"] == "default"
|
||||
# default_workspace should always be present (may be null for model)
|
||||
assert "default_workspace" in data
|
||||
assert isinstance(data["default_workspace"], str)
|
||||
assert "default_model" in data # can be None
|
||||
|
||||
|
||||
def test_profile_active_endpoint():
|
||||
"""GET /api/profile/active returns name and path."""
|
||||
data, status = get("/api/profile/active")
|
||||
assert status == 200
|
||||
assert "name" in data, "Response missing 'name' field"
|
||||
assert isinstance(data["name"], str) and data["name"], "Profile name should be a non-empty string"
|
||||
assert "path" in data
|
||||
|
||||
|
||||
# ── Session profile tagging ────────────────────────────────────────────────
|
||||
|
||||
def test_new_session_has_profile_field():
|
||||
"""Sessions created after Sprint 22 should have a profile field."""
|
||||
data, status = post("/api/session/new", {})
|
||||
assert status == 200
|
||||
session = data["session"]
|
||||
assert "profile" in session
|
||||
# Clean up
|
||||
post("/api/session/delete", {"session_id": session["session_id"]})
|
||||
|
||||
|
||||
def test_sessions_list_includes_profile():
|
||||
"""Sessions created after Sprint 22 expose a profile field."""
|
||||
# Create a session and check via the direct session endpoint
|
||||
# (/api/sessions filters out empty Untitled sessions; use /api/session instead)
|
||||
create_data, _ = post("/api/session/new", {})
|
||||
sid = create_data["session"]["session_id"]
|
||||
try:
|
||||
data, status = get(f"/api/session?session_id={sid}")
|
||||
assert status == 200
|
||||
session = data.get("session", data)
|
||||
assert "profile" in session, f"'profile' field missing from session: {list(session.keys())}"
|
||||
finally:
|
||||
post("/api/session/delete", {"session_id": sid})
|
||||
|
||||
|
||||
# ── Static JS analysis ─────────────────────────────────────────────────────
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
|
||||
def test_sessions_js_has_profile_filter():
|
||||
"""sessions.js should filter sessions by active profile."""
|
||||
content = (REPO_ROOT / "static" / "sessions.js").read_text()
|
||||
assert "_showAllProfiles" in content
|
||||
assert "profileFiltered" in content
|
||||
assert "S.activeProfile" in content
|
||||
|
||||
|
||||
def test_panels_js_clears_model_on_switch():
|
||||
"""switchToProfile() must clear localStorage model key."""
|
||||
content = (REPO_ROOT / "static" / "panels.js").read_text()
|
||||
assert "localStorage.removeItem('hermes-webui-model')" in content
|
||||
assert "loadWorkspaceList" in content
|
||||
assert "renderSessionList" in content
|
||||
|
||||
|
||||
# ── Regression: profile switch base dir bug (PR #44) ──────────────────────
|
||||
|
||||
def test_profile_switch_base_home_not_subdir():
|
||||
"""_DEFAULT_HERMES_HOME must always be the base ~/.hermes root, not a
|
||||
profile subdir. Regression: if HERMES_HOME was mutated to a profiles/
|
||||
subdir at server startup, switch_profile() looked for
|
||||
~/.hermes/profiles/X/profiles/X which never exists — returning 404.
|
||||
|
||||
We verify the fix is present via static analysis of profiles.py.
|
||||
The live-switch variant is in test_profile_switch_returns_default_model_and_workspace.
|
||||
"""
|
||||
content = (REPO_ROOT / "api" / "profiles.py").read_text()
|
||||
|
||||
# The fix must define a resolver function that handles the profiles/ subdir case
|
||||
assert "_resolve_base_hermes_home" in content, (
|
||||
"profiles.py must define _resolve_base_hermes_home() to safely resolve "
|
||||
"the base HERMES_HOME regardless of HERMES_HOME env var mutation"
|
||||
)
|
||||
assert "p.parent.name == 'profiles'" in content, (
|
||||
"_resolve_base_hermes_home must detect when HERMES_HOME points to a "
|
||||
"profiles/ subdir (e.g. ~/.hermes/profiles/webui) and walk up to base"
|
||||
)
|
||||
assert "p.parent.parent" in content, (
|
||||
"_resolve_base_hermes_home must return p.parent.parent when HERMES_HOME "
|
||||
"is a profiles/ subdir, giving back the actual ~/.hermes base"
|
||||
)
|
||||
# _DEFAULT_HERMES_HOME must be set from the resolver, not directly from env
|
||||
assert "_DEFAULT_HERMES_HOME = _resolve_base_hermes_home()" in content, (
|
||||
"_DEFAULT_HERMES_HOME must be assigned from _resolve_base_hermes_home(), "
|
||||
"not directly from os.getenv('HERMES_HOME')"
|
||||
)
|
||||
|
||||
|
||||
def test_api_helper_returns_clean_error_message():
|
||||
"""workspace.js api() helper must parse JSON error bodies and surface
|
||||
the human-readable 'error' field, not raw JSON like
|
||||
{'error': 'Profile X does not exist.'}.
|
||||
|
||||
Regression: api() did `throw new Error(await res.text())` which made
|
||||
showToast display 'Switch failed: {"error":"Profile X does not exist."}' --
|
||||
JSON noise the user shouldn't see.
|
||||
"""
|
||||
content = (REPO_ROOT / "static" / "workspace.js").read_text()
|
||||
# Must parse the JSON error body
|
||||
assert "JSON.parse(text)" in content, (
|
||||
"api() must parse JSON error bodies -- raw res.text() leaks JSON to the UI"
|
||||
)
|
||||
# Must extract the .error field
|
||||
assert "j.error" in content, (
|
||||
"api() must extract j.error from parsed JSON error response"
|
||||
)
|
||||
|
||||
|
||||
def test_profile_switch_resolve_base_home_logic():
|
||||
"""Static analysis: _resolve_base_hermes_home() must handle the case
|
||||
where HERMES_HOME points to a profiles/ subdir by walking up to the base.
|
||||
"""
|
||||
content = (REPO_ROOT / "api" / "profiles.py").read_text()
|
||||
assert "_resolve_base_hermes_home" in content, (
|
||||
"profiles.py must define _resolve_base_hermes_home()"
|
||||
)
|
||||
assert "p.parent.name == 'profiles'" in content, (
|
||||
"_resolve_base_hermes_home must detect and unwrap profiles/ subdir paths"
|
||||
)
|
||||
assert "p.parent.parent" in content, (
|
||||
"_resolve_base_hermes_home must walk up two levels from a profiles/ subdir"
|
||||
)
|
||||
Reference in New Issue
Block a user