Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3c85624d9 | ||
|
|
ed9023a431 | ||
|
|
e59fedd351 | ||
|
|
9a5435176d | ||
|
|
31281a6025 | ||
|
|
cc8cbc4d3f | ||
|
|
0e5e465ea0 | ||
|
|
a92e21553d | ||
|
|
06f46439c0 | ||
|
|
e68c1b92a4 | ||
|
|
fb19c7ea1f | ||
|
|
cb069794dd | ||
|
|
be92e59bdb | ||
|
|
f90be60e31 | ||
|
|
011034dc71 | ||
|
|
392bc5df6e | ||
|
|
fdf6ebfbe6 | ||
|
|
04678b7b6e |
@@ -40,6 +40,7 @@ This makes the code easy to modify from a terminal or by an agent.
|
||||
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)
|
||||
startup.py Startup helpers: auto_install_agent_deps() (~50 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)
|
||||
|
||||
58
CHANGELOG.md
58
CHANGELOG.md
@@ -6,6 +6,64 @@
|
||||
---
|
||||
|
||||
|
||||
## [v0.43.0] — 2026-04-10
|
||||
|
||||
### Features
|
||||
- **Auto-install agent dependencies on startup** (PRs #215 + #216): When `hermes-agent` is found on disk but its Python dependencies are missing (common in Docker deployments where the agent is volume-mounted post-build), `server.py` now calls `api/startup.auto_install_agent_deps()` to install from `requirements.txt` or `pyproject.toml`. Falls back gracefully — failures are logged and never fatal.
|
||||
|
||||
### Bug Fixes
|
||||
- **Session ID validator broadened** (PR #212): `Session.load()` rejected any session ID containing non-hex characters, breaking sessions created by the new hermes-agent format (`YYYYMMDD_HHMMSS_xxxxxx`). Validator now accepts `[0-9a-z_]` while rejecting path traversal patterns (null bytes, slashes, backslashes, dot-extensions).
|
||||
- **Test suite isolation** (PR #216): `conftest.py` now kills any stale process on the test port (8788) before starting the fixture server. Stale QA harness servers (8792/8793) could occupy 8788 and cause non-deterministic test failures across the full suite.
|
||||
|
||||
## [v0.42.2] — 2026-04-10
|
||||
|
||||
### Bug Fixes
|
||||
- **CSP blocking inline event handlers** (PR #209): `script-src 'self'` blocked all 55+ inline `onclick=` handlers in `index.html`, making the settings panel, sidebar navigation, and most interactive controls non-functional. Added `'unsafe-inline'` to `script-src`. Also restores `https://cdn.jsdelivr.net` to `script-src` and `style-src` for Mermaid.js and Prism.js (dropped in v0.42.1).
|
||||
|
||||
## [v0.42.1] — 2026-04-11
|
||||
|
||||
### Bug Fixes
|
||||
- **i18n button text stripping** (post-review): Three sidebar buttons (`+ New job`, `+ New skill`, `+ New profile`) and three suggestion buttons had `data-i18n` on the outer element, which caused `applyLocaleToDOM` to replace the entire `textContent` — stripping the `+` prefix and emoji characters on locale switch. Fixed by wrapping only the translatable label text in a `<span data-i18n="...">`.
|
||||
- **German translation corrections** (post-review): Fixed `cancelling` (imperative → progressive `"Wird abgebrochen…"`), `editing` (first-person verb → noun `"Bearbeitung"`), and completed truncated descriptions for `empty_subtitle`, `settings_desc_check_updates`, and `settings_desc_cli_sessions`.
|
||||
|
||||
## [v0.42.0] — 2026-04-10
|
||||
|
||||
### Features
|
||||
- **German translation** (PR #190 by @DavidSchuchert): Complete `de` locale covering all UI strings — settings, commands, sidebar, approval cards. Also extends the i18n system with `data-i18n-title` and `data-i18n-placeholder` attribute support so tooltip text and input placeholders are now translatable. German speech recognition uses `de-DE`.
|
||||
|
||||
### Bug Fixes
|
||||
- **Custom slash-model routing** (PR #189 by @smurmann): Model IDs like `google/gemma-4-26b-a4b` from custom providers (LM Studio, Ollama) were silently misrouted to OpenRouter because of the slash-heuristic. Custom providers now win: entries in `config.yaml → custom_providers` are checked first, so their model IDs route to the correct local endpoint regardless of format.
|
||||
- **Phantom Custom group in model picker** (PR #191 by @mbac): When `model.provider` was a named provider (e.g. `openai-codex`) and `model.base_url` was set, `hermes_cli` reported `'custom'` as authenticated, producing a duplicate "Custom" group in the dropdown. The real provider's group was missing the configured default model. Fixed by discarding the phantom `custom` entry when a real named provider is active.
|
||||
- **Hyphen/space model group injection** (PR #191): The "ensure default_model appears" post-pass used `active_provider.lower() in group_name.lower()`, which fails for `openai-codex` vs display name `OpenAI Codex` (hyphen vs space). Now uses `_PROVIDER_DISPLAY` for exact display-name matching.
|
||||
|
||||
## [v0.41.0] — 2026-04-10
|
||||
|
||||
### Features
|
||||
- **Optional HTTPS/TLS support** (PR #199): Set `HERMES_WEBUI_TLS_CERT` and
|
||||
`HERMES_WEBUI_TLS_KEY` env vars to enable HTTPS natively. Uses
|
||||
`ssl.PROTOCOL_TLS_SERVER` with TLS 1.2 minimum. Gracefully falls back to HTTP
|
||||
if cert loading fails. No reverse proxy required for LAN/VPN deployments.
|
||||
|
||||
### Bug Fixes
|
||||
- **CSP blocking Mermaid and Prism** (PR #197): Added Content-Security-Policy and
|
||||
Permissions-Policy headers to every response. CSP allows `cdn.jsdelivr.net` in
|
||||
`script-src` and `style-src` for Mermaid.js (dynamically loaded) and Prism.js
|
||||
(statically loaded with SRI integrity hashes). All other external origins blocked.
|
||||
- **Session memory leak** (PR #196): `api/auth.py` accumulated expired session tokens
|
||||
indefinitely. Added `_prune_expired_sessions()` called lazily on every
|
||||
`verify_session()` call. No background thread, no lock contention.
|
||||
- **Slow-client thread exhaustion** (PR #198): Added `Handler.timeout = 30` to kill
|
||||
idle/stalled connections before they exhaust the thread pool.
|
||||
- **False update alerts on feature branches** (PR #201): Update checker compared
|
||||
`HEAD..origin/master` even when on a feature branch, counting unrelated master
|
||||
commits as missing updates. Now uses `git rev-parse --abbrev-ref @{upstream}` to
|
||||
track the current branch's upstream. Falls back to default branch when no upstream
|
||||
is set.
|
||||
- **CLI session file browser returning 404** (PR #204): `/api/list` only checked
|
||||
the WebUI in-memory session dict, so CLI sessions shown in the sidebar always
|
||||
returned 404 for file browsing. Now falls back to `get_cli_sessions()` — the same
|
||||
pattern used by `/api/session` GET and `/api/sessions` list.
|
||||
|
||||
## [v0.40.2] — 2026-04-09
|
||||
|
||||
### Features
|
||||
|
||||
@@ -108,10 +108,18 @@ def create_session() -> str:
|
||||
return f"{token}.{sig}"
|
||||
|
||||
|
||||
def _prune_expired_sessions():
|
||||
"""Remove all expired session entries to prevent unbounded memory growth."""
|
||||
now = time.time()
|
||||
for token in [t for t, exp in _sessions.items() if now > exp]:
|
||||
_sessions.pop(token, None)
|
||||
|
||||
|
||||
def verify_session(cookie_value) -> bool:
|
||||
"""Verify a signed session cookie. Returns True if valid and not expired."""
|
||||
if not cookie_value or '.' not in cookie_value:
|
||||
return False
|
||||
_prune_expired_sessions() # lazy cleanup on every verification attempt
|
||||
token, sig = cookie_value.rsplit('.', 1)
|
||||
expected_sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
if not hmac.compare_digest(sig, expected_sig):
|
||||
|
||||
@@ -28,6 +28,11 @@ REPO_ROOT = Path(__file__).parent.parent.resolve()
|
||||
HOST = os.getenv('HERMES_WEBUI_HOST', '127.0.0.1')
|
||||
PORT = int(os.getenv('HERMES_WEBUI_PORT', '8787'))
|
||||
|
||||
# ── TLS/HTTPS config (optional, env-overridable) ────────────────────────────
|
||||
TLS_CERT = os.getenv('HERMES_WEBUI_TLS_CERT', '').strip() or None
|
||||
TLS_KEY = os.getenv('HERMES_WEBUI_TLS_KEY', '').strip() or None
|
||||
TLS_ENABLED = TLS_CERT is not None and TLS_KEY is not None
|
||||
|
||||
# ── State directory (env-overridable, never inside repo) ──────────────────────
|
||||
STATE_DIR = Path(os.getenv(
|
||||
'HERMES_WEBUI_STATE_DIR',
|
||||
@@ -384,14 +389,21 @@ def resolve_model_provider(model_id: str) -> tuple:
|
||||
"""Resolve model name, provider, and base_url for AIAgent.
|
||||
|
||||
Model IDs from the dropdown can be in several formats:
|
||||
- 'claude-sonnet-4.6' (bare name, uses config default provider)
|
||||
- 'anthropic/claude-sonnet-4.6' (OpenRouter format, provider/model)
|
||||
- '@minimax:MiniMax-M2.7' (explicit provider hint from dropdown)
|
||||
- 'claude-sonnet-4.6' (bare name, uses config default provider)
|
||||
- 'anthropic/claude-sonnet-4.6' (OpenRouter-style provider/model)
|
||||
- '@minimax:MiniMax-M2.7' (explicit provider hint from dropdown)
|
||||
|
||||
The @provider:model format is used for models from non-default provider
|
||||
groups in the dropdown, so we can route them through the correct provider
|
||||
via resolve_runtime_provider(requested=provider) instead of the default.
|
||||
|
||||
Custom OpenAI-compatible endpoints are special: their model IDs often look
|
||||
like provider/model (for example ``google/gemma-4-26b-a4b``), which would be
|
||||
mistaken for an OpenRouter model if we only looked at the slash. To avoid
|
||||
that, first check whether the selected model matches an entry in
|
||||
config.yaml -> custom_providers and route it through that named custom
|
||||
provider.
|
||||
|
||||
Returns (model, provider, base_url) where provider and base_url may be None.
|
||||
"""
|
||||
config_provider = None
|
||||
@@ -405,6 +417,20 @@ def resolve_model_provider(model_id: str) -> tuple:
|
||||
if not model_id:
|
||||
return model_id, config_provider, config_base_url
|
||||
|
||||
# Custom providers declared in config.yaml should win over slash-based
|
||||
# OpenRouter heuristics. Their model IDs commonly contain '/' too.
|
||||
custom_providers = cfg.get('custom_providers', [])
|
||||
if isinstance(custom_providers, list):
|
||||
for entry in custom_providers:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
entry_model = (entry.get('model') or '').strip()
|
||||
entry_name = (entry.get('name') or '').strip()
|
||||
entry_base_url = (entry.get('base_url') or '').strip()
|
||||
if entry_model and entry_name and model_id == entry_model:
|
||||
provider_hint = 'custom:' + entry_name.lower().replace(' ', '-')
|
||||
return model_id, provider_hint, entry_base_url or None
|
||||
|
||||
# @provider:model format — explicit provider hint from the dropdown.
|
||||
# Route through that provider directly (resolve_runtime_provider will
|
||||
# resolve credentials in streaming.py).
|
||||
@@ -654,6 +680,14 @@ def get_available_models() -> dict:
|
||||
_seen_custom_ids.add(_cp_model)
|
||||
detected_providers.add('custom')
|
||||
|
||||
# If the user configured a real model.provider, the base_url belongs to
|
||||
# THAT provider, not to a separate "Custom" group. hermes_cli reports
|
||||
# 'custom' as authenticated whenever base_url is set, which would otherwise
|
||||
# build a phantom "Custom" bucket next to the real provider's group. Drop
|
||||
# it unless the user explicitly chose 'custom' as their active provider.
|
||||
if active_provider and active_provider != 'custom':
|
||||
detected_providers.discard('custom')
|
||||
|
||||
# 5. Build model groups
|
||||
if detected_providers:
|
||||
for pid in sorted(detected_providers):
|
||||
@@ -715,11 +749,21 @@ def get_available_models() -> dict:
|
||||
_norm = lambda mid: mid.split('/', 1)[-1] if '/' in mid else mid
|
||||
all_ids_norm = {_norm(m['id']) for g in groups for m in g.get('models', [])}
|
||||
if _norm(default_model) not in all_ids_norm:
|
||||
# Determine which group to inject into
|
||||
# Determine which group to inject into. Compare against the
|
||||
# provider's display name from _PROVIDER_DISPLAY rather than
|
||||
# doing a substring match on active_provider — substring
|
||||
# matching breaks on hyphenated provider IDs like 'openai-codex'
|
||||
# vs display name 'OpenAI Codex' (hyphen vs. space), which
|
||||
# silently falls through to groups[0] and lands the model in
|
||||
# the wrong group.
|
||||
label = default_model.split('/')[-1] if '/' in default_model else default_model
|
||||
target_display = (
|
||||
_PROVIDER_DISPLAY.get(active_provider, active_provider or '').lower()
|
||||
if active_provider else ''
|
||||
)
|
||||
injected = False
|
||||
for g in groups:
|
||||
if active_provider and active_provider.lower() in g.get('provider', '').lower():
|
||||
if target_display and g.get('provider', '').lower() == target_display:
|
||||
g['models'].insert(0, {'id': default_model, 'label': label})
|
||||
injected = True
|
||||
break
|
||||
|
||||
@@ -39,6 +39,18 @@ def _security_headers(handler):
|
||||
handler.send_header('X-Content-Type-Options', 'nosniff')
|
||||
handler.send_header('X-Frame-Options', 'DENY')
|
||||
handler.send_header('Referrer-Policy', 'same-origin')
|
||||
handler.send_header(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; "
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
|
||||
"img-src 'self' data:; font-src 'self' data:; connect-src 'self'; "
|
||||
"base-uri 'self'; form-action 'self'"
|
||||
)
|
||||
handler.send_header(
|
||||
'Permissions-Policy',
|
||||
'camera=(), microphone=(), geolocation=()'
|
||||
)
|
||||
|
||||
|
||||
def j(handler, payload, status: int=200) -> None:
|
||||
|
||||
@@ -74,7 +74,7 @@ class Session:
|
||||
@classmethod
|
||||
def load(cls, sid):
|
||||
# Validate session ID format to prevent path traversal
|
||||
if not sid or not all(c in '0123456789abcdef' for c in sid):
|
||||
if not sid or not all(c in '0123456789abcdefghijklmnopqrstuvwxyz_' for c in sid):
|
||||
return None
|
||||
p = SESSION_DIR / f'{sid}.json'
|
||||
if not p.exists():
|
||||
|
||||
@@ -862,11 +862,25 @@ def _handle_list_dir(handler, parsed):
|
||||
qs = parse_qs(parsed.query)
|
||||
sid = qs.get('session_id', [''])[0]
|
||||
if not sid: return bad(handler, 'session_id is required')
|
||||
try: s = get_session(sid)
|
||||
except KeyError: return bad(handler, 'Session not found', 404)
|
||||
try:
|
||||
s = get_session(sid)
|
||||
workspace = s.workspace
|
||||
except KeyError:
|
||||
# Fallback for CLI sessions not loaded in WebUI memory
|
||||
try:
|
||||
cli_meta = None
|
||||
for cs in get_cli_sessions():
|
||||
if cs['session_id'] == sid:
|
||||
cli_meta = cs
|
||||
break
|
||||
if not cli_meta:
|
||||
return bad(handler, 'Session not found', 404)
|
||||
workspace = cli_meta.get('workspace', '')
|
||||
except Exception:
|
||||
return bad(handler, 'Session not found', 404)
|
||||
try:
|
||||
return j(handler, {
|
||||
'entries': list_dir(Path(s.workspace), qs.get('path', ['.'])[0]),
|
||||
'entries': list_dir(Path(workspace), qs.get('path', ['.'])[0]),
|
||||
'path': qs.get('path', ['.'])[0],
|
||||
})
|
||||
except (FileNotFoundError, ValueError) as e:
|
||||
|
||||
46
api/startup.py
Normal file
46
api/startup.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Hermes Web UI -- startup helpers."""
|
||||
from __future__ import annotations
|
||||
import os, subprocess, sys
|
||||
from pathlib import Path
|
||||
|
||||
def _agent_dir() -> Path | None:
|
||||
hermes_home = Path(os.environ.get('HERMES_HOME', str(Path.home() / '.hermes')))
|
||||
for raw in [os.environ.get('HERMES_WEBUI_AGENT_DIR', '').strip(), str(hermes_home / 'hermes-agent')]:
|
||||
if not raw:
|
||||
continue
|
||||
p = Path(raw).expanduser()
|
||||
if p.is_dir():
|
||||
return p.resolve()
|
||||
return None
|
||||
|
||||
def auto_install_agent_deps() -> bool:
|
||||
agent_dir = _agent_dir()
|
||||
if agent_dir is None:
|
||||
print('[!!] Auto-install skipped: agent directory not found.', flush=True)
|
||||
return False
|
||||
req_file = agent_dir / 'requirements.txt'
|
||||
pyproject = agent_dir / 'pyproject.toml'
|
||||
if req_file.exists():
|
||||
install_args = [sys.executable, '-m', 'pip', 'install', '--quiet', '-r', str(req_file)]
|
||||
print(f' Installing from {req_file} ...', flush=True)
|
||||
elif pyproject.exists():
|
||||
install_args = [sys.executable, '-m', 'pip', 'install', '--quiet', str(agent_dir)]
|
||||
print(f' Installing from {agent_dir} (pyproject.toml) ...', flush=True)
|
||||
else:
|
||||
print('[!!] Auto-install skipped: no requirements.txt or pyproject.toml in agent dir.', flush=True)
|
||||
return False
|
||||
try:
|
||||
result = subprocess.run(install_args, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
print(f'[!!] pip install failed (exit {result.returncode}):', flush=True)
|
||||
for line in (result.stderr or '').splitlines()[-10:]:
|
||||
print(f' {line}', flush=True)
|
||||
return False
|
||||
print('[ok] pip install completed.', flush=True)
|
||||
return True
|
||||
except subprocess.TimeoutExpired:
|
||||
print('[!!] Auto-install timed out after 120s.', flush=True)
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f'[!!] Auto-install error: {e}', flush=True)
|
||||
return False
|
||||
@@ -64,22 +64,32 @@ def _check_repo(path, name):
|
||||
if not fetch_ok:
|
||||
return {'name': name, 'behind': 0, 'error': 'fetch failed'}
|
||||
|
||||
branch = _detect_default_branch(path)
|
||||
# Use the current branch's upstream tracking branch, not the repo default.
|
||||
# This avoids false "N updates behind" alerts when the user is on a feature
|
||||
# branch and master/main has moved forward with unrelated commits.
|
||||
# If no upstream is set (brand-new local branch), fall back to the default branch.
|
||||
upstream, ok = _run_git(['rev-parse', '--abbrev-ref', '@{upstream}'], path)
|
||||
if ok and upstream:
|
||||
# upstream is like "origin/feat/foo" — use it directly in rev-list
|
||||
compare_ref = upstream
|
||||
else:
|
||||
branch = _detect_default_branch(path)
|
||||
compare_ref = f'origin/{branch}'
|
||||
|
||||
# Count commits behind
|
||||
out, ok = _run_git(['rev-list', '--count', f'HEAD..origin/{branch}'], path)
|
||||
out, ok = _run_git(['rev-list', '--count', f'HEAD..{compare_ref}'], path)
|
||||
behind = int(out) if ok and out.isdigit() else 0
|
||||
|
||||
# Get short SHAs for display
|
||||
current, _ = _run_git(['rev-parse', '--short', 'HEAD'], path)
|
||||
latest, _ = _run_git(['rev-parse', '--short', f'origin/{branch}'], path)
|
||||
latest, _ = _run_git(['rev-parse', '--short', compare_ref], path)
|
||||
|
||||
return {
|
||||
'name': name,
|
||||
'behind': behind,
|
||||
'current_sha': current,
|
||||
'latest_sha': latest,
|
||||
'branch': branch,
|
||||
'branch': compare_ref,
|
||||
}
|
||||
|
||||
|
||||
@@ -129,7 +139,14 @@ def _apply_update_inner(target):
|
||||
if path is None or not (path / '.git').exists():
|
||||
return {'ok': False, 'message': 'Not a git repository'}
|
||||
|
||||
branch = _detect_default_branch(path)
|
||||
# Use the current branch's upstream for pull, matching the behaviour
|
||||
# of _check_repo. Falls back to default branch if no upstream is set.
|
||||
upstream, ok = _run_git(['rev-parse', '--abbrev-ref', '@{upstream}'], path)
|
||||
if ok and upstream:
|
||||
compare_ref = upstream
|
||||
else:
|
||||
branch = _detect_default_branch(path)
|
||||
compare_ref = f'origin/{branch}'
|
||||
|
||||
# Check for dirty working tree
|
||||
status_out, _ = _run_git(['status', '--porcelain'], path)
|
||||
@@ -141,7 +158,7 @@ def _apply_update_inner(target):
|
||||
stashed = True
|
||||
|
||||
# Pull with ff-only (no merge commits)
|
||||
pull_out, pull_ok = _run_git(['pull', '--ff-only', 'origin', branch], path, timeout=30)
|
||||
pull_out, pull_ok = _run_git(['pull', '--ff-only', compare_ref], path, timeout=30)
|
||||
if not pull_ok:
|
||||
if stashed:
|
||||
_run_git(['stash', 'pop'], path)
|
||||
|
||||
33
server.py
33
server.py
@@ -12,9 +12,11 @@ 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
|
||||
from api.startup import auto_install_agent_deps
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 30 # seconds — kills idle/incomplete connections to prevent thread exhaustion
|
||||
server_version = 'HermesWebUI/0.2'
|
||||
def log_message(self, fmt, *args): pass # suppress default Apache-style log
|
||||
|
||||
@@ -74,16 +76,41 @@ def main() -> None:
|
||||
print(f'[!!] Warning: Hermes agent found but missing modules: {missing}', flush=True)
|
||||
for mod, err in errors.items():
|
||||
print(f' {mod}: {err}', flush=True)
|
||||
print(' Agent features may not work correctly.', flush=True)
|
||||
print(' Attempting to install missing dependencies from agent requirements.txt...', flush=True)
|
||||
auto_install_agent_deps()
|
||||
ok, missing, errors = verify_hermes_imports()
|
||||
if not ok:
|
||||
print(f'[!!] Still missing after install attempt: {missing}', flush=True)
|
||||
for mod, err in errors.items():
|
||||
print(f' {mod}: {err}', flush=True)
|
||||
print(' Agent features may not work correctly.', flush=True)
|
||||
else:
|
||||
print('[ok] Agent dependencies installed successfully.', flush=True)
|
||||
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
||||
DEFAULT_WORKSPACE.mkdir(parents=True, exist_ok=True)
|
||||
httpd = ThreadingHTTPServer((HOST, PORT), Handler)
|
||||
print(f' Hermes Web UI listening on http://{HOST}:{PORT}', flush=True)
|
||||
|
||||
# ── TLS/HTTPS setup (optional) ─────────────────────────────────────────
|
||||
from api.config import TLS_ENABLED, TLS_CERT, TLS_KEY
|
||||
scheme = 'https' if TLS_ENABLED else 'http'
|
||||
if TLS_ENABLED:
|
||||
try:
|
||||
import ssl
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ctx.load_cert_chain(TLS_CERT, TLS_KEY)
|
||||
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
|
||||
print(f' TLS enabled: cert={TLS_CERT}, key={TLS_KEY}', flush=True)
|
||||
except Exception as e:
|
||||
print(f'[!!] WARNING: TLS setup failed ({e}), falling back to HTTP', flush=True)
|
||||
scheme = 'http'
|
||||
|
||||
print(f' Hermes Web UI listening on {scheme}://{HOST}:{PORT}', flush=True)
|
||||
if HOST == '127.0.0.1':
|
||||
print(f' Remote access: ssh -N -L {PORT}:127.0.0.1:{PORT} <user>@<your-server>', flush=True)
|
||||
print(f' Then open: http://localhost:{PORT}', flush=True)
|
||||
print(f' Then open: {scheme}://localhost:{PORT}', flush=True)
|
||||
print('', flush=True)
|
||||
httpd.serve_forever()
|
||||
|
||||
|
||||
236
static/i18n.js
236
static/i18n.js
@@ -136,6 +136,232 @@ const LOCALES = {
|
||||
login_btn: 'Sign in',
|
||||
login_invalid_pw: 'Invalid password',
|
||||
login_conn_failed: 'Connection failed',
|
||||
// Sidebar & Tabs
|
||||
tab_chat: 'Chat',
|
||||
tab_tasks: 'Tasks',
|
||||
tab_skills: 'Skills',
|
||||
tab_memory: 'Memory',
|
||||
tab_workspaces: 'Spaces',
|
||||
tab_profiles: 'Profiles',
|
||||
tab_todos: 'Todos',
|
||||
new_conversation: 'New conversation',
|
||||
filter_conversations: 'Filter conversations...',
|
||||
scheduled_jobs: 'Scheduled jobs',
|
||||
new_job: 'New job',
|
||||
loading: 'Loading...',
|
||||
search_skills: 'Search skills...',
|
||||
new_skill: 'New skill',
|
||||
personal_memory: 'Personal memory',
|
||||
current_task_list: 'Current task list',
|
||||
workspace_desc: 'Add and switch workspaces for your sessions.',
|
||||
new_profile: 'New profile',
|
||||
transcript: 'Transcript',
|
||||
download_transcript: 'Download as Markdown',
|
||||
import: 'Import',
|
||||
// Settings detail
|
||||
settings_label_sound: 'Notification sound',
|
||||
settings_desc_sound: 'Play a sound when the assistant finishes a response.',
|
||||
settings_label_notifications: 'Browser notifications',
|
||||
settings_desc_notifications: 'Show a system notification when a response completes while the tab is in the background.',
|
||||
settings_desc_token_usage: 'Displays input/output token count below each assistant reply. Also toggled with /usage.',
|
||||
settings_desc_cli_sessions: 'Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.',
|
||||
settings_desc_sync_insights: 'Mirrors WebUI token usage to state.db so hermes /insights includes browser session data. Off by default.',
|
||||
settings_desc_check_updates: 'Show a banner when newer versions of the WebUI or Agent are available. Runs a background git fetch periodically.',
|
||||
settings_desc_bot_name: 'Display name for the assistant throughout the UI. Defaults to Hermes.',
|
||||
settings_desc_password: 'Enter a new password to set or change it. Leave blank to keep current setting.',
|
||||
password_placeholder: 'Enter new password…',
|
||||
disable_auth: 'Disable Auth',
|
||||
sign_out: 'Sign Out',
|
||||
cancel: 'Cancel',
|
||||
create_job: 'Create job',
|
||||
save_skill: 'Save skill',
|
||||
editing: 'Editing',
|
||||
// Empty state
|
||||
empty_title: 'What can I help with?',
|
||||
empty_subtitle: 'Ask anything, run commands, explore files, or manage your scheduled tasks.',
|
||||
suggest_files: 'What files are in this workspace?',
|
||||
suggest_schedule: "What's on my schedule today?",
|
||||
suggest_plan: 'Help me plan a small project.',
|
||||
},
|
||||
|
||||
de: {
|
||||
_lang: 'de',
|
||||
_label: 'Deutsch',
|
||||
_speech: 'de-DE',
|
||||
// boot.js
|
||||
cancelling: 'Wird abgebrochen\u2026',
|
||||
cancel_failed: 'Abbrechen fehlgeschlagen: ',
|
||||
mic_denied: 'Mikrofonzugriff verweigert. Überprüfen Sie die Browserberechtigungen.',
|
||||
mic_no_speech: 'Keine Sprache erkannt. Versuchen Sie es erneut.',
|
||||
mic_network: 'Spracherkennung nicht verfügbar.',
|
||||
mic_error: 'Spracheingabefehler: ',
|
||||
session_imported: 'Sitzung importiert',
|
||||
import_failed: 'Import fehlgeschlagen: ',
|
||||
import_invalid_json: 'Ungültiges JSON',
|
||||
image_pasted: 'Bild eingefügt: ',
|
||||
// messages.js
|
||||
edit_message: 'Nachricht bearbeiten',
|
||||
regenerate: 'Antwort regenerieren',
|
||||
copy: 'Kopieren',
|
||||
copied: 'Kopiert!',
|
||||
you: 'Du',
|
||||
thinking: 'Nachdenken',
|
||||
expand_all: 'Alle ausklappen',
|
||||
collapse_all: 'Alle einklappen',
|
||||
edit_failed: 'Bearbeiten fehlgeschlagen: ',
|
||||
regen_failed: 'Regeneration fehlgeschlagen: ',
|
||||
reconnect_active: 'Eine Antwort wird noch generiert. Neu laden, wenn bereit?',
|
||||
reconnect_finished: 'Eine Antwort war in Arbeit, als Sie zuletzt gegangen sind. Nachrichten könnten aktualisiert worden sein.',
|
||||
// approval card
|
||||
approval_heading: 'Genehmigung erforderlich',
|
||||
approval_desc_prefix: 'Gefährlicher Befehl erkannt',
|
||||
approval_btn_once: 'Einmal zulassen',
|
||||
approval_btn_once_title: 'Diesen einen Befehl zulassen (Enter)',
|
||||
approval_btn_session: 'Sitzung zulassen',
|
||||
approval_btn_session_title: 'Für diese Konversationssitzung zulassen',
|
||||
approval_btn_always: 'Immer zulassen',
|
||||
approval_btn_always_title: 'Dieses Befehlsmuster immer zulassen',
|
||||
approval_btn_deny: 'Ablehnen',
|
||||
approval_btn_deny_title: 'Ablehnen \u2014 diesen Befehl nicht ausführen',
|
||||
approval_responding: 'Antwortet\u2026',
|
||||
untitled: 'Unbenannt',
|
||||
n_messages: (n) => `${n} Nachrichten`,
|
||||
model_unavailable: ' (nicht verfügbar)',
|
||||
model_unavailable_title: 'Dieses Modell ist nicht mehr in Ihrer aktuellen Provider-Liste',
|
||||
// commands.js
|
||||
cmd_help: 'Verfügbare Befehle auflisten',
|
||||
cmd_clear: 'Konversationsverlauf löschen',
|
||||
cmd_compact: 'Kontext komprimieren',
|
||||
cmd_model: 'Modell wechseln (z.B. /model gpt-4o)',
|
||||
cmd_workspace: 'Workspace nach Namen wechseln',
|
||||
cmd_new: 'Neue Chat-Sitzung starten',
|
||||
cmd_usage: 'Token-Verbrauchsanzeige umschalten',
|
||||
cmd_theme: 'Theme wechseln (dark/light/slate/solarized/monokai/nord/oled)',
|
||||
cmd_personality: 'Agenten-Persönlichkeit wechseln',
|
||||
available_commands: 'Verfügbare Befehle:',
|
||||
type_slash: 'Tippe / für Befehle',
|
||||
conversation_cleared: 'Konversation gelöscht',
|
||||
model_usage: 'Nutzung: /model <name>',
|
||||
no_model_match: 'Kein Modell gefunden für "',
|
||||
switched_to: 'Gewechselt zu ',
|
||||
workspace_usage: 'Nutzung: /workspace <name>',
|
||||
no_workspace_match: 'Kein Workspace gefunden für "',
|
||||
switched_workspace: 'Gewechselt zu Workspace: ',
|
||||
workspace_switch_failed: 'Workspace-Wechsel fehlgeschlagen: ',
|
||||
new_session: 'Neue Sitzung erstellt',
|
||||
compressing: 'Kontext-Komprimierung wird angefordert...',
|
||||
token_usage_on: 'Token-Verbrauch an',
|
||||
token_usage_off: 'Token-Verbrauch aus',
|
||||
theme_usage: 'Nutzung: /theme ',
|
||||
theme_set: 'Theme: ',
|
||||
no_active_session: 'Keine aktive Sitzung',
|
||||
no_personalities: 'Keine Persönlichkeiten gefunden (füge sie in ~/.hermes/personalities/ hinzu)',
|
||||
available_personalities: 'Verfügbare Persönlichkeiten:',
|
||||
personality_switch_hint: '\n\nNutze `/personality <name>` zum Wechseln, oder `/personality none` zum Löschen.',
|
||||
personalities_load_failed: 'Fehler beim Laden der Persönlichkeiten',
|
||||
personality_cleared: 'Persönlichkeit gelöscht',
|
||||
personality_set: 'Persönlichkeit: ',
|
||||
failed_colon: 'Fehlgeschlagen: ',
|
||||
// ui.js
|
||||
no_workspace: 'Kein Workspace',
|
||||
// workspace.js
|
||||
unsaved_confirm: 'Sie haben ungespeicherte Änderungen in der Vorschau. Verwerfen und fortfahren?',
|
||||
save: 'Speichern',
|
||||
edit: 'Bearbeiten',
|
||||
save_title: 'Änderungen speichern',
|
||||
edit_title: 'Diese Datei bearbeiten',
|
||||
saved: 'Gespeichert',
|
||||
save_failed: 'Speichern fehlgeschlagen: ',
|
||||
image_load_failed: 'Bild konnte nicht geladen werden',
|
||||
file_open_failed: 'Datei konnte nicht geöffnet werden',
|
||||
downloading: (name) => `Lade ${name} herunter\u2026`,
|
||||
double_click_rename: 'Doppelklick zum Umbenennen',
|
||||
renamed_to: 'Umbenannt in ',
|
||||
rename_failed: 'Umbenennen fehlgeschlagen: ',
|
||||
delete_title: 'Löschen',
|
||||
delete_confirm: (name) => `${name} löschen?`,
|
||||
deleted: 'Gelöscht ',
|
||||
delete_failed: 'Löschen fehlgeschlagen: ',
|
||||
new_file_prompt: 'Neuer Dateiname (z.B. notes.md):',
|
||||
created: 'Erstellt ',
|
||||
create_failed: 'Erstellen fehlgeschlagen: ',
|
||||
new_folder_prompt: 'Neuer Ordnername:',
|
||||
folder_created: 'Ordner erstellt ',
|
||||
folder_create_failed: 'Ordner erstellen fehlgeschlagen: ',
|
||||
remove_title: 'Entfernen',
|
||||
empty_dir: '(leer)',
|
||||
upload_failed: 'Upload fehlgeschlagen: ',
|
||||
all_uploads_failed: (n) => `Alle ${n} Upload(s) fehlgeschlagen`,
|
||||
// settings panel
|
||||
settings_title: 'Einstellungen',
|
||||
settings_save_btn: 'Einstellungen speichern',
|
||||
settings_label_model: 'Standard-Modell',
|
||||
settings_label_send_key: 'Sende-Taste',
|
||||
settings_label_theme: 'Theme',
|
||||
settings_label_language: 'Sprache',
|
||||
settings_label_token_usage: 'Token-Verbrauch anzeigen',
|
||||
settings_label_cli_sessions: 'CLI-Sitzungen anzeigen',
|
||||
settings_label_sync_insights: 'Mit Insights synchronisieren',
|
||||
settings_label_check_updates: 'Nach Updates suchen',
|
||||
settings_label_bot_name: 'Assistenten-Name',
|
||||
settings_label_password: 'Zugangspasswort',
|
||||
settings_saved: 'Einstellungen gespeichert',
|
||||
settings_save_failed: 'Speichern fehlgeschlagen: ',
|
||||
settings_load_failed: 'Laden der Einstellungen fehlgeschlagen: ',
|
||||
settings_saved_pw: 'Einstellungen gespeichert (Passwort gesetzt \u2014 Login jetzt erforderlich)',
|
||||
// login page
|
||||
login_title: 'Anmelden',
|
||||
login_subtitle: 'Geben Sie Ihr Passwort ein, um fortzufahren',
|
||||
login_placeholder: 'Passwort',
|
||||
login_btn: 'Anmelden',
|
||||
login_invalid_pw: 'Ungültiges Passwort',
|
||||
login_conn_failed: 'Verbindung fehlgeschlagen',
|
||||
// Sidebar & Tabs
|
||||
tab_chat: 'Chat',
|
||||
tab_tasks: 'Aufgaben',
|
||||
tab_skills: 'Skills',
|
||||
tab_memory: 'Gedächtnis',
|
||||
tab_workspaces: 'Spaces',
|
||||
tab_profiles: 'Profile',
|
||||
tab_todos: 'Todos',
|
||||
new_conversation: 'Neuer Chat',
|
||||
filter_conversations: 'Chats filtern...',
|
||||
scheduled_jobs: 'Geplante Aufgaben',
|
||||
new_job: 'Neuer Job',
|
||||
loading: 'Lädt...',
|
||||
search_skills: 'Skills suchen...',
|
||||
new_skill: 'Neuer Skill',
|
||||
personal_memory: 'Persönliches Gedächtnis',
|
||||
current_task_list: 'Aktuelle Aufgabenliste',
|
||||
workspace_desc: 'Workspaces hinzufügen und wechseln.',
|
||||
new_profile: 'Neues Profil',
|
||||
transcript: 'Protokoll',
|
||||
download_transcript: 'Als Markdown herunterladen',
|
||||
import: 'Importieren',
|
||||
// Settings detail
|
||||
settings_label_sound: 'Benachrichtigungston',
|
||||
settings_desc_sound: 'Spielt einen Ton ab, wenn der Assistent eine Antwort beendet.',
|
||||
settings_label_notifications: 'Browser-Benachrichtigungen',
|
||||
settings_desc_notifications: 'Zeigt eine Systembenachrichtigung an, wenn eine Antwort fertiggestellt wird, während der Tab im Hintergrund ist.',
|
||||
settings_desc_token_usage: 'Zeigt die Anzahl der Input/Output-Token unter jeder Antwort des Assistenten an. Auch umschaltbar mit /usage.',
|
||||
settings_desc_cli_sessions: 'Fügt Sitzungen aus der Hermes CLI (state.db) in die Sitzungsliste ein. Klicken Sie auf eine CLI-Sitzung, um sie zu importieren und das Gespräch fortzusetzen.',
|
||||
settings_desc_sync_insights: 'Spiegelt den WebUI-Token-Verbrauch in die state.db, sodass hermes /insights Browser-Sitzungsdaten enthält. Standardmäßig aus.',
|
||||
settings_desc_check_updates: 'Zeigt ein Banner an, wenn neuere Versionen der WebUI oder des Agenten verfügbar sind. Führt regelmäßig einen Git-Fetch im Hintergrund aus.',
|
||||
settings_desc_bot_name: 'Anzeigename für den Assistenten in der UI. Standardmäßig Hermes.',
|
||||
settings_desc_password: 'Geben Sie ein neues Passwort ein, um es zu setzen oder zu ändern. Leer lassen, um die aktuelle Einstellung beizubehalten.',
|
||||
password_placeholder: 'Neues Passwort eingeben…',
|
||||
disable_auth: 'Authentifizierung deaktivieren',
|
||||
sign_out: 'Abmelden',
|
||||
cancel: 'Abbrechen',
|
||||
create_job: 'Job erstellen',
|
||||
save_skill: 'Skill speichern',
|
||||
editing: 'Bearbeitung',
|
||||
// Empty state
|
||||
empty_title: 'Wie kann ich helfen?',
|
||||
empty_subtitle: 'Frage mich alles, führe Befehle aus, erkunde Dateien oder verwalte deine Aufgaben.',
|
||||
suggest_files: 'Welche Dateien sind in diesem Workspace?',
|
||||
suggest_schedule: 'Was steht heute auf meinem Plan?',
|
||||
suggest_plan: 'Hilf mir, ein kleines Projekt zu planen.',
|
||||
},
|
||||
|
||||
zh: {
|
||||
@@ -321,6 +547,16 @@ function applyLocaleToDOM() {
|
||||
const val = t(key);
|
||||
if (val && val !== key) el.textContent = val;
|
||||
});
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n-title');
|
||||
const val = t(key);
|
||||
if (val && val !== key) el.title = val;
|
||||
});
|
||||
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
|
||||
const key = el.getAttribute('data-i18n-placeholder');
|
||||
const val = t(key);
|
||||
if (val && val !== key) el.placeholder = val;
|
||||
});
|
||||
}
|
||||
|
||||
// Apply saved locale immediately so there's no flash of English on reload.
|
||||
|
||||
@@ -14,32 +14,32 @@
|
||||
<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.40.2</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.43.0</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>
|
||||
<button class="nav-tab" data-panel="skills" data-label="Skills" onclick="switchPanel('skills')" title="Skills">🧩</button>
|
||||
<button class="nav-tab" data-panel="memory" data-label="Memory" onclick="switchPanel('memory')" title="Memory">🧠</button>
|
||||
<button class="nav-tab" data-panel="workspaces" data-label="Spaces" onclick="switchPanel('workspaces')" title="Spaces">📁</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">✅</button>
|
||||
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat" data-i18n-title="tab_chat">💬</button>
|
||||
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks" data-i18n-title="tab_tasks">📅</button>
|
||||
<button class="nav-tab" data-panel="skills" data-label="Skills" onclick="switchPanel('skills')" title="Skills" data-i18n-title="tab_skills">🧩</button>
|
||||
<button class="nav-tab" data-panel="memory" data-label="Memory" onclick="switchPanel('memory')" title="Memory" data-i18n-title="tab_memory">🧠</button>
|
||||
<button class="nav-tab" data-panel="workspaces" data-label="Spaces" onclick="switchPanel('workspaces')" title="Spaces" data-i18n-title="tab_workspaces">📁</button>
|
||||
<button class="nav-tab" data-panel="profiles" data-label="Profiles" onclick="switchPanel('profiles')" title="Agent profiles" data-i18n-title="tab_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" data-i18n-title="tab_todos">✅</button>
|
||||
</div>
|
||||
<!-- Chat panel -->
|
||||
<div class="panel-view active" id="panelChat">
|
||||
<div class="sidebar-section">
|
||||
<button class="new-chat-btn" id="btnNewChat">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
New conversation <span style="font-size:10px;opacity:.5;margin-left:4px">⌘K</span>
|
||||
<span data-i18n="new_conversation">New conversation</span> <span style="font-size:10px;opacity:.5;margin-left:4px">⌘K</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="session-search"><input id="sessionSearch" placeholder="Filter conversations..." oninput="filterSessions()"></div>
|
||||
<div class="session-search"><input id="sessionSearch" placeholder="Filter conversations..." data-i18n-placeholder="filter_conversations" oninput="filterSessions()"></div>
|
||||
<div class="session-list" id="sessionList"></div>
|
||||
</div>
|
||||
<!-- Tasks (cron) panel -->
|
||||
<div class="panel-view" id="panelTasks">
|
||||
<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)">Scheduled jobs</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleCronForm()">+ New job</button>
|
||||
<div style="font-size:11px;color:var(--muted)" data-i18n="scheduled_jobs">Scheduled jobs</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleCronForm()">+ <span data-i18n="new_job">New job</span></button>
|
||||
</div>
|
||||
<!-- Create job form (hidden by default) -->
|
||||
<div id="cronCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
|
||||
@@ -57,18 +57,18 @@
|
||||
<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>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitCronCreate()" data-i18n="create_job">Create job</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleCronForm()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="cronFormError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
<div class="cron-list" id="cronList"><div style="padding:12px;color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div class="cron-list" id="cronList"><div style="padding:12px;color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
</div>
|
||||
<!-- Skills panel -->
|
||||
<div class="panel-view" id="panelSkills">
|
||||
<div class="sidebar-section" style="padding-bottom:4px;display:flex;align-items:center;justify-content:space-between">
|
||||
<div class="skills-search" style="flex:1;padding:0"><input id="skillsSearch" placeholder="Search skills..." oninput="filterSkills()"></div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px;flex-shrink:0;margin-left:6px" onclick="toggleSkillForm()">+ New skill</button>
|
||||
<div class="skills-search" style="flex:1;padding:0"><input id="skillsSearch" placeholder="Search skills..." data-i18n-placeholder="search_skills" oninput="filterSkills()"></div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px;flex-shrink:0;margin-left:6px" onclick="toggleSkillForm()">+ <span data-i18n="new_skill">New skill</span></button>
|
||||
</div>
|
||||
<!-- Skill create/edit form (hidden by default) -->
|
||||
<div id="skillCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
|
||||
@@ -76,46 +76,46 @@
|
||||
<input id="skillFormCategory" placeholder="Category (optional, e.g. devops)" 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">
|
||||
<textarea id="skillFormContent" rows="6" placeholder="SKILL.md content (YAML frontmatter + markdown body)" 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:vertical;font-family:'SF Mono',ui-monospace,monospace;margin-bottom:6px;box-sizing:border-box"></textarea>
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitSkillSave()">Save skill</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleSkillForm()">Cancel</button>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitSkillSave()" data-i18n="save_skill">Save skill</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleSkillForm()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="skillFormError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
<div class="skills-list" id="skillsList"><div style="padding:12px;color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div class="skills-list" id="skillsList"><div style="padding:12px;color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
</div>
|
||||
<!-- Memory panel -->
|
||||
<div class="panel-view" id="panelMemory">
|
||||
<div style="padding:8px 12px 4px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0">
|
||||
<span style="font-size:11px;color:var(--muted)">Personal memory</span>
|
||||
<button class="cron-btn run" id="memEditBtn" style="padding:3px 8px;font-size:10px" onclick="toggleMemoryEdit()">✎ Edit</button>
|
||||
<span style="font-size:11px;color:var(--muted)" data-i18n="personal_memory">Personal memory</span>
|
||||
<button class="cron-btn run" id="memEditBtn" style="padding:3px 8px;font-size:10px" onclick="toggleMemoryEdit()">✎ <span data-i18n="edit">Edit</span></button>
|
||||
</div>
|
||||
<div class="memory-panel" id="memoryPanel"><div style="color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div class="memory-panel" id="memoryPanel"><div style="color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
<!-- Memory edit form (hidden by default) -->
|
||||
<div id="memoryEditForm" style="display:none;padding:8px 12px;border-top:1px solid var(--border);flex-shrink:0">
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:4px">Editing: <span id="memEditSection">memory</span></div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:4px"><span data-i18n="editing">Editing</span>: <span id="memEditSection">memory</span></div>
|
||||
<textarea id="memEditContent" rows="10" 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:11px;outline:none;resize:vertical;font-family:'SF Mono',ui-monospace,monospace;box-sizing:border-box;margin-bottom:6px;line-height:1.5"></textarea>
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitMemorySave()">Save</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="closeMemoryEdit()">Cancel</button>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitMemorySave()" data-i18n="save">Save</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="closeMemoryEdit()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="memEditError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Todo panel -->
|
||||
<div class="panel-view" id="panelTodos">
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted);flex-shrink:0">Current task list</div>
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted);flex-shrink:0" data-i18n="current_task_list">Current task list</div>
|
||||
<div id="todoPanel" style="flex:1;overflow-y:auto;padding:8px 12px"></div>
|
||||
</div>
|
||||
<!-- Workspaces panel -->
|
||||
<div class="panel-view" id="panelWorkspaces">
|
||||
<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 style="padding:10px 12px 4px;font-size:11px;color:var(--muted)" data-i18n="workspace_desc">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" data-i18n="loading">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 style="font-size:11px;color:var(--muted)" data-i18n="tab_profiles">Agent profiles</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleProfileForm()">+ <span data-i18n="new_profile">New profile</span></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">
|
||||
@@ -163,9 +163,9 @@
|
||||
<div class="ws-dropdown" id="wsDropdown"></div>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<button class="sm-btn" id="btnDownload" title="Download as Markdown">↓ Transcript</button>
|
||||
<button class="sm-btn" id="btnDownload" title="Download as Markdown" data-i18n-title="download_transcript">↓ <span data-i18n="transcript">Transcript</span></button>
|
||||
<button class="sm-btn" id="btnExportJSON" title="Export full session as JSON">❬/❭ JSON</button>
|
||||
<button class="sm-btn" id="btnImportJSON" title="Import session from JSON">↑ Import</button>
|
||||
<button class="sm-btn" id="btnImportJSON" title="Import session from JSON">↑ <span data-i18n="import">Import</span></button>
|
||||
<input type="file" id="importFileInput" accept=".json" style="display:none">
|
||||
</div>
|
||||
</div>
|
||||
@@ -176,7 +176,7 @@
|
||||
<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 style="flex:1;min-width:0;overflow:hidden"><div class="topbar-title" id="topbarTitle">Hermes</div><div class="topbar-meta" id="topbarMeta" data-i18n="new_conversation">Start a new conversation</div></div>
|
||||
<div class="topbar-chips">
|
||||
<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> ▾</div>
|
||||
@@ -184,20 +184,20 @@
|
||||
</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">🗑 Clear</button>
|
||||
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings">⚙</button>
|
||||
<button class="chip clear-btn" id="btnClearConv" onclick="clearConversation()" title="Clear all messages in this conversation" style="display:none">🗑 <span data-i18n="copy">Clear</span></button>
|
||||
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings" data-i18n-title="settings_title">⚙</button>
|
||||
<button class="chip mobile-files-btn" id="btnMobileFiles" onclick="toggleMobileFiles()" title="Files">📁</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="messages" id="messages">
|
||||
<div class="empty-state" id="emptyState">
|
||||
<div class="empty-logo">🦉</div>
|
||||
<h2>What can I help with?</h2>
|
||||
<p>Ask anything, run commands, explore files, or manage your scheduled tasks.</p>
|
||||
<h2 data-i18n="empty_title">What can I help with?</h2>
|
||||
<p data-i18n="empty_subtitle">Ask anything, run commands, explore files, or manage your scheduled tasks.</p>
|
||||
<div class="suggestion-grid">
|
||||
<button class="suggestion" data-msg="What files are in this workspace?">📁 What files are in this workspace?</button>
|
||||
<button class="suggestion" data-msg="What's on my schedule today?">📋 What's on my schedule today?</button>
|
||||
<button class="suggestion" data-msg="Help me plan a small project.">🗺 Help me plan a small project.</button>
|
||||
<button class="suggestion" data-msg="What files are in this workspace?">📁 <span data-i18n="suggest_files">What files are in this workspace?</span></button>
|
||||
<button class="suggestion" data-msg="What's on my schedule today?">📋 <span data-i18n="suggest_schedule">What's on my schedule today?</span></button>
|
||||
<button class="suggestion" data-msg="Help me plan a small project.">🗺 <span data-i18n="suggest_plan">Help me plan a small project.</span></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="messages-inner" id="msgInner"></div>
|
||||
@@ -365,58 +365,58 @@
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsSoundEnabled" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
Notification sound
|
||||
<span data-i18n="settings_label_sound">Notification sound</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Play a sound when the assistant finishes a response.</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_sound">Play a sound when the assistant finishes a response.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsNotificationsEnabled" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
Browser notifications
|
||||
<span data-i18n="settings_label_notifications">Browser notifications</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Show a system notification when a response completes while the tab is in the background.</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_notifications">Show a system notification when a response completes while the tab is in the background.</div>
|
||||
</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)">
|
||||
<span data-i18n="settings_label_token_usage">Show token usage after responses</span>
|
||||
</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 style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_token_usage">Displays input/output token count below each assistant reply. Also toggled with <code>/usage</code>.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsShowCliSessions" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_cli_sessions">Show CLI sessions in sidebar</span>
|
||||
</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 style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_cli_sessions">Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsSyncInsights" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_sync_insights">Sync usage to /insights</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Mirrors WebUI token usage to state.db so <code>hermes /insights</code> includes browser session data. Off by default.</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_sync_insights">Mirrors WebUI token usage to state.db so <code>hermes /insights</code> includes browser session data. Off by default.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsCheckUpdates" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_check_updates">Check for updates</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Show a banner when newer versions of the WebUI or Agent are available. Runs a background git fetch periodically.</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_check_updates">Show a banner when newer versions of the WebUI or Agent are available. Runs a background git fetch periodically.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsBotName" data-i18n="settings_label_bot_name">Assistant Name</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px">Display name for the assistant throughout the UI. Defaults to Hermes.</div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px" data-i18n="settings_desc_bot_name">Display name for the assistant throughout the UI. Defaults to Hermes.</div>
|
||||
<input type="text" id="settingsBotName" placeholder="Hermes" maxlength="64" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px;font-size:13px">
|
||||
</div>
|
||||
<div class="settings-field" style="border-top:1px solid var(--border);padding-top:12px;margin-top:8px">
|
||||
<label for="settingsPassword" data-i18n="settings_label_password">Access Password</label>
|
||||
<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 style="font-size:11px;color:var(--muted);margin-bottom:6px" data-i18n="settings_desc_password">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…" data-i18n-placeholder="password_placeholder" 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" data-i18n="settings_save_btn">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>
|
||||
<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" data-i18n="disable_auth">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" data-i18n="sign_out">Sign Out</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -424,23 +424,23 @@
|
||||
<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>
|
||||
<span data-i18n="tab_chat">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>
|
||||
<span data-i18n="tab_tasks">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>
|
||||
<span data-i18n="tab_skills">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>
|
||||
<span data-i18n="tab_memory">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>
|
||||
<span data-i18n="tab_workspaces">Spaces</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
@@ -210,6 +210,18 @@ def test_server():
|
||||
Start an isolated test server on TEST_PORT with a clean state directory.
|
||||
Paths are discovered dynamically -- no hardcoded absolute path assumptions.
|
||||
"""
|
||||
# Kill any leftover process on the test port before starting.
|
||||
# Stale servers from QA harness runs or prior test sessions cause
|
||||
# conftest to think the server is already up, producing false failures.
|
||||
try:
|
||||
import subprocess as _sp
|
||||
_sp.run(['fuser', '-k', f'{TEST_PORT}/tcp'],
|
||||
capture_output=True, timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
import time as _time
|
||||
_time.sleep(0.5) # brief pause to let the port release
|
||||
|
||||
# Clean slate
|
||||
if TEST_STATE_DIR.exists():
|
||||
shutil.rmtree(TEST_STATE_DIR)
|
||||
|
||||
134
tests/test_auth_sessions.py
Normal file
134
tests/test_auth_sessions.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Tests for auth session lifecycle — session creation, verification, expiry,
|
||||
and lazy pruning of expired entries.
|
||||
"""
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Isolate state dir so we don't touch real sessions
|
||||
_TEST_STATE = Path(tempfile.mkdtemp())
|
||||
os.environ["HERMES_WEBUI_STATE_DIR"] = str(_TEST_STATE)
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
import importlib
|
||||
|
||||
# Force re-import of auth module so it picks up our TEST_STATE_DIR
|
||||
auth = importlib.import_module("api.auth")
|
||||
|
||||
|
||||
class TestSessionPruning(unittest.TestCase):
|
||||
"""Verify expired session cleanup works correctly."""
|
||||
|
||||
def setUp(self):
|
||||
# Clear any leftover sessions from other tests
|
||||
auth._sessions.clear()
|
||||
|
||||
def test_session_created_valid(self):
|
||||
"""A fresh session token should verify as valid."""
|
||||
token = auth.create_session()
|
||||
self.assertTrue(auth.verify_session(token))
|
||||
|
||||
def test_expired_session_pruned(self):
|
||||
"""Manually inserting an expired entry should be pruned on next verify_session call."""
|
||||
# Insert sessions that have already expired
|
||||
auth._sessions["fake_token"] = time.time() - 100
|
||||
auth._sessions["another_fake"] = time.time() - 50
|
||||
# Insert one valid session (far future)
|
||||
auth._sessions["good_token"] = time.time() + 3600
|
||||
|
||||
# _sessions has 3 entries, 2 expired
|
||||
self.assertEqual(len(auth._sessions), 3)
|
||||
|
||||
# Call verify_session — this triggers _prune_expired_sessions()
|
||||
# Cookie format is token.signature, so we need a dot to pass the early check
|
||||
auth.verify_session("fake_token.fake_sig")
|
||||
|
||||
# After verification, only the valid session should remain
|
||||
self.assertEqual(len(auth._sessions), 1)
|
||||
self.assertIn("good_token", auth._sessions)
|
||||
self.assertNotIn("fake_token", auth._sessions)
|
||||
self.assertNotIn("another_fake", auth._sessions)
|
||||
|
||||
def test_prune_does_not_remove_valid_sessions(self):
|
||||
"""_prune_expired_sessions should never remove sessions that are still active."""
|
||||
auth._sessions["active_1"] = time.time() + 86400 # 24 hours from now
|
||||
auth._sessions["active_2"] = time.time() + 7200 # 2 hours from now
|
||||
auth._sessions["expired_1"] = time.time() - 10
|
||||
|
||||
auth._prune_expired_sessions()
|
||||
|
||||
self.assertEqual(len(auth._sessions), 2)
|
||||
self.assertIn("active_1", auth._sessions)
|
||||
self.assertIn("active_2", auth._sessions)
|
||||
self.assertNotIn("expired_1", auth._sessions)
|
||||
|
||||
def test_verify_session_prunes_before_verification(self):
|
||||
"""verify_session should prune expired entries before checking the target token.
|
||||
|
||||
This ensures that _prune_expired_sessions() is called at the very top
|
||||
of verify_session(), so cleanup happens on every auth check.
|
||||
"""
|
||||
auth._sessions["expired_for_test"] = time.time() - 999
|
||||
|
||||
# verify_session with an invalid cookie triggers the full path:
|
||||
# _prune_expired_sessions -> signature check -> return False
|
||||
result = auth.verify_session("nonexistent.bad_sig")
|
||||
self.assertFalse(result)
|
||||
|
||||
# The expired entry should have been cleaned up
|
||||
self.assertNotIn("expired_for_test", auth._sessions)
|
||||
|
||||
def test_prune_handles_empty_dict(self):
|
||||
"""_prune_expired_sessions should be safe on an empty dict."""
|
||||
auth._sessions.clear()
|
||||
auth._prune_expired_sessions()
|
||||
self.assertEqual(len(auth._sessions), 0)
|
||||
|
||||
def test_session_ttl_is_24_hours(self):
|
||||
"""Newly created sessions should have the expected 24-hour TTL."""
|
||||
auth._sessions.clear()
|
||||
token_hex = auth.create_session().split(".")[0]
|
||||
# The _sessions dict stores token -> expiry_time
|
||||
# We can check the expiry is approximately SESSION_TTL seconds from now
|
||||
# by looking up the raw entry via the token
|
||||
from api.auth import _sessions, SESSION_TTL
|
||||
# find our entry
|
||||
for t, exp in _sessions.items():
|
||||
if t == token_hex:
|
||||
# expiry should be within 5 seconds of now + SESSION_TTL
|
||||
expected = time.time() + SESSION_TTL
|
||||
self.assertAlmostEqual(exp, expected, delta=5)
|
||||
break
|
||||
else:
|
||||
self.fail("Session token not found in _sessions")
|
||||
|
||||
|
||||
class TestSessionInvalidation(unittest.TestCase):
|
||||
"""Test session logout / invalidation."""
|
||||
|
||||
def setUp(self):
|
||||
auth._sessions.clear()
|
||||
|
||||
def test_invalidate_session_removes_token(self):
|
||||
"""Calling invalidate_session should remove the token from _sessions."""
|
||||
token = auth.create_session()
|
||||
self.assertTrue(auth.verify_session(token))
|
||||
|
||||
auth.invalidate_session(token)
|
||||
# Token should be gone
|
||||
self.assertFalse(auth.verify_session(token))
|
||||
|
||||
def test_invalidate_unknown_token_is_safe(self):
|
||||
"""Invalidating a non-existent token should not raise."""
|
||||
auth._sessions.clear()
|
||||
auth.invalidate_session("nonexistent_token")
|
||||
# Should not raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,8 +6,8 @@ tuples for different provider configurations.
|
||||
import api.config as config
|
||||
|
||||
|
||||
def _resolve_with_config(model_id, provider=None, base_url=None, default=None):
|
||||
"""Helper: temporarily set config.cfg model section, call resolve, restore."""
|
||||
def _resolve_with_config(model_id, provider=None, base_url=None, default=None, custom_providers=None):
|
||||
"""Helper: temporarily set config.cfg model/custom provider sections, call resolve, restore."""
|
||||
old_cfg = dict(config.cfg)
|
||||
model_cfg = {}
|
||||
if provider:
|
||||
@@ -17,6 +17,8 @@ def _resolve_with_config(model_id, provider=None, base_url=None, default=None):
|
||||
if default:
|
||||
model_cfg['default'] = default
|
||||
config.cfg['model'] = model_cfg if model_cfg else {}
|
||||
if custom_providers is not None:
|
||||
config.cfg['custom_providers'] = custom_providers
|
||||
try:
|
||||
return config.resolve_model_provider(model_id)
|
||||
finally:
|
||||
@@ -139,6 +141,23 @@ def test_slash_prefix_non_default_still_routes_openrouter():
|
||||
assert provider == 'openrouter'
|
||||
|
||||
|
||||
def test_custom_provider_model_with_slash_routes_to_named_custom_provider():
|
||||
"""Slash-containing custom endpoint model IDs must not be mistaken for OpenRouter models."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'google/gemma-4-26b-a4b',
|
||||
provider='openrouter',
|
||||
base_url='https://openrouter.ai/api/v1',
|
||||
custom_providers=[{
|
||||
'name': 'Local LM Studio',
|
||||
'base_url': 'http://lmstudio.local:1234/v1',
|
||||
'model': 'google/gemma-4-26b-a4b',
|
||||
}],
|
||||
)
|
||||
assert model == 'google/gemma-4-26b-a4b'
|
||||
assert provider == 'custom:local-lm-studio'
|
||||
assert base_url == 'http://lmstudio.local:1234/v1'
|
||||
|
||||
|
||||
# ── get_available_models() @provider: hint behaviour ──────────────────────
|
||||
|
||||
def _available_models_with_provider(provider):
|
||||
@@ -202,3 +221,108 @@ def test_default_provider_models_not_prefixed():
|
||||
assert bare_id in returned_ids, (
|
||||
f"_PROVIDER_MODELS entry '{bare_id}' is missing from the Anthropic group"
|
||||
)
|
||||
|
||||
|
||||
# ── get_available_models(): phantom "Custom" group regression ─────────────
|
||||
#
|
||||
# When the user has model.provider set to a real provider (e.g. openai-codex)
|
||||
# AND a model.base_url set, hermes_cli reports the 'custom' pseudo-provider as
|
||||
# authenticated. The WebUI picker must NOT build a separate "Custom" group in
|
||||
# that case — the base_url belongs to the active provider.
|
||||
|
||||
def _available_models_with_full_cfg(provider, default, base_url):
|
||||
"""Helper: set model.provider, model.default, model.base_url at once.
|
||||
|
||||
Clears model-override env vars (HERMES_MODEL, OPENAI_MODEL, LLM_MODEL)
|
||||
during the call so the real hermes profile environment doesn't leak into
|
||||
the test and override the fixture's default model.
|
||||
"""
|
||||
import os
|
||||
import api.config as _cfg
|
||||
old_cfg = dict(_cfg.cfg)
|
||||
_cfg.cfg['model'] = {
|
||||
'provider': provider,
|
||||
'default': default,
|
||||
'base_url': base_url,
|
||||
}
|
||||
# Clear model-override env vars to prevent the real profile from leaking in
|
||||
_model_env_keys = ('HERMES_MODEL', 'OPENAI_MODEL', 'LLM_MODEL')
|
||||
_saved_env = {k: os.environ.pop(k, None) for k in _model_env_keys}
|
||||
try:
|
||||
return _cfg.get_available_models()
|
||||
finally:
|
||||
_cfg.cfg.clear()
|
||||
_cfg.cfg.update(old_cfg)
|
||||
for k, v in _saved_env.items():
|
||||
if v is not None:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_no_phantom_custom_group_when_active_provider_is_set(monkeypatch):
|
||||
"""Issue: with provider=openai-codex + base_url set, gpt-5.4 was landing
|
||||
under a phantom "Custom" group instead of the "OpenAI Codex" group."""
|
||||
import sys, types
|
||||
|
||||
# Force hermes_cli to report both the real provider and the phantom
|
||||
# 'custom' as authenticated, simulating what list_available_providers()
|
||||
# returns when base_url is configured.
|
||||
fake_mod = types.ModuleType('hermes_cli.models')
|
||||
fake_mod.list_available_providers = lambda: [
|
||||
{'id': 'openai-codex', 'authenticated': True},
|
||||
{'id': 'custom', 'authenticated': True},
|
||||
]
|
||||
fake_auth = types.ModuleType('hermes_cli.auth')
|
||||
fake_auth.get_auth_status = lambda pid: {'key_source': 'env'}
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.models', fake_mod)
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.auth', fake_auth)
|
||||
|
||||
result = _available_models_with_full_cfg(
|
||||
provider='openai-codex',
|
||||
default='gpt-5.4',
|
||||
base_url='https://chatgpt.com/backend-api/codex',
|
||||
)
|
||||
group_names = [g['provider'] for g in result['groups']]
|
||||
assert 'Custom' not in group_names, (
|
||||
f"Phantom 'Custom' group present; full groups: {group_names}"
|
||||
)
|
||||
|
||||
|
||||
def test_default_model_lands_under_active_provider_group(monkeypatch):
|
||||
"""The configured default_model must appear under the active provider's
|
||||
display group, even when the model isn't in _PROVIDER_MODELS[provider]
|
||||
AND the active provider isn't the alphabetical first detected provider.
|
||||
|
||||
Regression guard for a hyphen-vs-space bug in the "ensure default_model
|
||||
appears" post-pass: the substring check `active_provider.lower() in
|
||||
g.get('provider', '').lower()` was failing for 'openai-codex' vs
|
||||
display name 'OpenAI Codex' (hyphen vs. space), silently falling back
|
||||
to groups[0] — which, when another provider sorted earlier
|
||||
alphabetically (e.g. 'anthropic'), placed gpt-5.4 in the WRONG group.
|
||||
"""
|
||||
import sys, types
|
||||
fake_mod = types.ModuleType('hermes_cli.models')
|
||||
fake_mod.list_available_providers = lambda: [
|
||||
{'id': 'anthropic', 'authenticated': True}, # sorts before openai-codex
|
||||
{'id': 'openai-codex', 'authenticated': True},
|
||||
{'id': 'custom', 'authenticated': True},
|
||||
]
|
||||
fake_auth = types.ModuleType('hermes_cli.auth')
|
||||
fake_auth.get_auth_status = lambda pid: {'key_source': 'env'}
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.models', fake_mod)
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.auth', fake_auth)
|
||||
|
||||
result = _available_models_with_full_cfg(
|
||||
provider='openai-codex',
|
||||
default='gpt-5.4',
|
||||
base_url='https://chatgpt.com/backend-api/codex',
|
||||
)
|
||||
groups = {g['provider']: [m['id'] for m in g['models']] for g in result['groups']}
|
||||
assert 'OpenAI Codex' in groups, f"OpenAI Codex group missing: {list(groups)}"
|
||||
assert 'gpt-5.4' in groups['OpenAI Codex'], (
|
||||
f"gpt-5.4 not in OpenAI Codex group; contents: {groups['OpenAI Codex']}"
|
||||
)
|
||||
# And crucially, it must NOT have landed in the alphabetically-first
|
||||
# group (Anthropic) via the fallback path.
|
||||
assert 'gpt-5.4' not in groups.get('Anthropic', []), (
|
||||
f"gpt-5.4 leaked into Anthropic group via fallback: {groups.get('Anthropic')}"
|
||||
)
|
||||
|
||||
@@ -154,8 +154,15 @@ class TestSessionIDValidation:
|
||||
result = Session.load(valid_hex)
|
||||
assert result is None # No file, but no error
|
||||
|
||||
def test_new_format_session_id_passes_validation(self):
|
||||
"""New hermes-agent session IDs (YYYYMMDD_HHMMSS_xxxxxx) must pass validation."""
|
||||
from api.models import Session
|
||||
# Should pass the validator (returns None only because the file doesn't exist)
|
||||
result = Session.load("20260406_164014_74b2d1")
|
||||
assert result is None # file doesn't exist, but validator passed
|
||||
|
||||
def test_non_hex_session_id_rejected(self):
|
||||
"""A session ID with non-hex chars must be rejected."""
|
||||
"""A session ID with dangerous chars must be rejected."""
|
||||
from api.models import Session
|
||||
evil_ids = [
|
||||
"../../../etc/passwd",
|
||||
@@ -163,11 +170,15 @@ class TestSessionIDValidation:
|
||||
"session; rm -rf /",
|
||||
"hello world",
|
||||
"ZZZZZZZZZZZZZZZZ",
|
||||
"session\x00evil",
|
||||
"..\\..\\windows\\system32",
|
||||
"session/../../etc/passwd",
|
||||
"valid_looking.json",
|
||||
]
|
||||
for sid in evil_ids:
|
||||
result = Session.load(sid)
|
||||
assert result is None, \
|
||||
f"Session.load should reject non-hex ID '{sid}', got {result}"
|
||||
f"Session.load should reject dangerous ID '{sid}', got {result}"
|
||||
|
||||
def test_empty_session_id_rejected(self):
|
||||
"""An empty session ID must be rejected."""
|
||||
|
||||
71
tests/test_sprint32.py
Normal file
71
tests/test_sprint32.py
Normal file
@@ -0,0 +1,71 @@
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
import subprocess
|
||||
from api.startup import auto_install_agent_deps
|
||||
|
||||
class TestAutoInstallAgentDeps:
|
||||
def test_installs_from_requirements_txt(self, tmp_path):
|
||||
agent_dir = tmp_path / 'hermes-agent'
|
||||
agent_dir.mkdir()
|
||||
req = agent_dir / 'requirements.txt'
|
||||
req.write_text('pyyaml\n')
|
||||
with patch.dict('os.environ', {'HERMES_WEBUI_AGENT_DIR': str(agent_dir)}, clear=False):
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stderr='')
|
||||
assert auto_install_agent_deps() is True
|
||||
args = mock_run.call_args[0][0]
|
||||
assert '-r' in args and str(req) in args
|
||||
|
||||
def test_falls_back_to_pyproject(self, tmp_path):
|
||||
agent_dir = tmp_path / 'hermes-agent'
|
||||
agent_dir.mkdir()
|
||||
(agent_dir / 'pyproject.toml').write_text('[project]\nname="hermes-agent"\n')
|
||||
with patch.dict('os.environ', {'HERMES_WEBUI_AGENT_DIR': str(agent_dir)}, clear=False):
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stderr='')
|
||||
assert auto_install_agent_deps() is True
|
||||
args = mock_run.call_args[0][0]
|
||||
assert str(agent_dir) in args and '-r' not in args
|
||||
|
||||
def test_skips_when_agent_dir_missing(self, tmp_path, capsys):
|
||||
missing = tmp_path / 'nonexistent-agent'
|
||||
# Patch both HERMES_WEBUI_AGENT_DIR and HERMES_HOME so the fallback
|
||||
# path (HERMES_HOME/hermes-agent) also resolves to a nonexistent dir,
|
||||
# preventing the real agent dir from being found in the test environment.
|
||||
env_overrides = {
|
||||
'HERMES_WEBUI_AGENT_DIR': str(missing),
|
||||
'HERMES_HOME': str(tmp_path / 'no-hermes-home'),
|
||||
}
|
||||
with patch.dict('os.environ', env_overrides, clear=False):
|
||||
with patch('subprocess.run') as mock_run:
|
||||
assert auto_install_agent_deps() is False
|
||||
assert not mock_run.called
|
||||
assert 'skipped' in capsys.readouterr().out.lower()
|
||||
|
||||
def test_skips_when_no_install_file(self, tmp_path, capsys):
|
||||
agent_dir = tmp_path / 'hermes-agent'
|
||||
agent_dir.mkdir()
|
||||
with patch.dict('os.environ', {'HERMES_WEBUI_AGENT_DIR': str(agent_dir)}, clear=False):
|
||||
with patch('subprocess.run') as mock_run:
|
||||
assert auto_install_agent_deps() is False
|
||||
assert not mock_run.called
|
||||
assert 'skipped' in capsys.readouterr().out.lower()
|
||||
|
||||
def test_tolerates_pip_failure(self, tmp_path, capsys):
|
||||
agent_dir = tmp_path / 'hermes-agent'
|
||||
agent_dir.mkdir()
|
||||
(agent_dir / 'requirements.txt').write_text('somepkg\n')
|
||||
with patch.dict('os.environ', {'HERMES_WEBUI_AGENT_DIR': str(agent_dir)}, clear=False):
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=1, stderr='ERROR: could not find package')
|
||||
assert auto_install_agent_deps() is False
|
||||
assert 'failed' in capsys.readouterr().out.lower() or 'pip' in capsys.readouterr().out.lower()
|
||||
|
||||
def test_tolerates_timeout(self, tmp_path, capsys):
|
||||
agent_dir = tmp_path / 'hermes-agent'
|
||||
agent_dir.mkdir()
|
||||
(agent_dir / 'requirements.txt').write_text('somepkg\n')
|
||||
with patch.dict('os.environ', {'HERMES_WEBUI_AGENT_DIR': str(agent_dir)}, clear=False):
|
||||
with patch('subprocess.run', side_effect=subprocess.TimeoutExpired('pip', 120)):
|
||||
assert auto_install_agent_deps() is False
|
||||
assert 'timed out' in capsys.readouterr().out.lower()
|
||||
214
tests/test_tls_support.py
Normal file
214
tests/test_tls_support.py
Normal file
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
Tests for optional TLS/HTTPS support (HERMES_WEBUI_TLS_CERT / TLS_KEY).
|
||||
|
||||
Tests use a self-signed certificate generated at test time via openssl.
|
||||
"""
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import textwrap
|
||||
import time
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).parent.parent
|
||||
|
||||
|
||||
def _gen_test_cert(tmpdir: Path) -> tuple[str, str]:
|
||||
"""Generate a self-signed cert and key pair for testing."""
|
||||
cert = str(tmpdir / "test_cert.pem")
|
||||
key = str(tmpdir / "test_key.pem")
|
||||
subprocess.run(
|
||||
["openssl", "req", "-x509", "-newkey", "rsa:2048",
|
||||
"-keyout", key, "-out", cert, "-days", "1", "-nodes",
|
||||
"-subj", "/CN=localhost"],
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
return cert, key
|
||||
|
||||
|
||||
def _find_free_port() -> int:
|
||||
import socket
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def _wait_for_server(host: str, port: int, use_ssl: bool = False,
|
||||
timeout: float = 8.0) -> bool:
|
||||
"""Poll until the server accepts a connection or times out."""
|
||||
ctx = None
|
||||
if use_ssl:
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if use_ssl:
|
||||
c = http.client.HTTPSConnection(host, port, timeout=2, context=ctx)
|
||||
else:
|
||||
c = http.client.HTTPConnection(host, port, timeout=2)
|
||||
c.request("GET", "/health")
|
||||
resp = c.getresponse()
|
||||
resp.read()
|
||||
c.close()
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def _start_server(port: int, cert: str = None, key: str = None) -> subprocess.Popen:
|
||||
"""Start server.py as a subprocess with the given TLS env vars."""
|
||||
env = {k: v for k, v in os.environ.items()}
|
||||
env["HERMES_WEBUI_HOST"] = "127.0.0.1"
|
||||
env["HERMES_WEBUI_PORT"] = str(port)
|
||||
env.pop("HERMES_WEBUI_TLS_CERT", None)
|
||||
env.pop("HERMES_WEBUI_TLS_KEY", None)
|
||||
if cert:
|
||||
env["HERMES_WEBUI_TLS_CERT"] = cert
|
||||
if key:
|
||||
env["HERMES_WEBUI_TLS_KEY"] = key
|
||||
env["HERMES_WEBUI_STATE_DIR"] = str(Path(tempfile.mkdtemp()))
|
||||
proc = subprocess.Popen(
|
||||
[os.sys.executable, str(ROOT / "server.py")],
|
||||
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
return proc
|
||||
|
||||
|
||||
# ── Test class ──────────────────────────────────────────────────────────────
|
||||
|
||||
class TestTLSConfigFlag(unittest.TestCase):
|
||||
|
||||
def test_tls_enabled_true_when_both_env_set(self):
|
||||
code = textwrap.dedent("""\
|
||||
import os
|
||||
os.environ['HERMES_WEBUI_TLS_CERT'] = '/tmp/cert.pem'
|
||||
os.environ['HERMES_WEBUI_TLS_KEY'] = '/tmp/key.pem'
|
||||
from api.config import TLS_ENABLED
|
||||
print(TLS_ENABLED)
|
||||
""")
|
||||
r = subprocess.run(
|
||||
[os.sys.executable, "-c", code],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
cwd=str(ROOT),
|
||||
)
|
||||
self.assertEqual(r.stdout.strip(), "True")
|
||||
|
||||
def test_tls_enabled_false_when_env_absent(self):
|
||||
env = {k: v for k, v in os.environ.items()
|
||||
if k not in ("HERMES_WEBUI_TLS_CERT", "HERMES_WEBUI_TLS_KEY")}
|
||||
code = textwrap.dedent("""\
|
||||
import os
|
||||
os.environ.pop('HERMES_WEBUI_TLS_CERT', None)
|
||||
os.environ.pop('HERMES_WEBUI_TLS_KEY', None)
|
||||
from api.config import TLS_ENABLED
|
||||
print(TLS_ENABLED)
|
||||
""")
|
||||
r = subprocess.run(
|
||||
[os.sys.executable, "-c", code],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
cwd=str(ROOT), env=env,
|
||||
)
|
||||
self.assertEqual(r.stdout.strip(), "False")
|
||||
|
||||
def test_tls_enabled_false_when_only_cert_set(self):
|
||||
env = {k: v for k, v in os.environ.items()
|
||||
if k not in ("HERMES_WEBUI_TLS_CERT", "HERMES_WEBUI_TLS_KEY")}
|
||||
env["HERMES_WEBUI_TLS_CERT"] = "/tmp/cert.pem"
|
||||
code = textwrap.dedent("""\
|
||||
from api.config import TLS_ENABLED
|
||||
print(TLS_ENABLED)
|
||||
""")
|
||||
r = subprocess.run(
|
||||
[os.sys.executable, "-c", code],
|
||||
capture_output=True, text=True, timeout=10,
|
||||
cwd=str(ROOT), env=env,
|
||||
)
|
||||
self.assertEqual(r.stdout.strip(), "False")
|
||||
|
||||
|
||||
class TestTLSEndToEnd(unittest.TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = Path(tempfile.mkdtemp())
|
||||
cls._cert, cls._key = _gen_test_cert(cls._tmpdir)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
with suppress(Exception):
|
||||
import shutil
|
||||
shutil.rmtree(cls._tmpdir, ignore_errors=True)
|
||||
|
||||
def tearDown(self):
|
||||
if hasattr(self, "_proc") and self._proc.poll() is None:
|
||||
self._proc.terminate()
|
||||
try:
|
||||
self._proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._proc.kill()
|
||||
|
||||
def test_https_server_responds_to_health(self):
|
||||
port = _find_free_port()
|
||||
self._proc = _start_server(port, cert=self._cert, key=self._key)
|
||||
self.assertTrue(
|
||||
_wait_for_server("127.0.0.1", port, use_ssl=True),
|
||||
"TLS server did not start in time",
|
||||
)
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
conn = http.client.HTTPSConnection("127.0.0.1", port, timeout=5, context=ctx)
|
||||
conn.request("GET", "/health")
|
||||
resp = conn.getresponse()
|
||||
self.assertEqual(resp.status, 200)
|
||||
data = json.loads(resp.read())
|
||||
self.assertEqual(data.get("status"), "ok")
|
||||
conn.close()
|
||||
|
||||
def test_http_without_tls_still_works(self):
|
||||
port = _find_free_port()
|
||||
self._proc = _start_server(port)
|
||||
self.assertTrue(
|
||||
_wait_for_server("127.0.0.1", port, use_ssl=False),
|
||||
)
|
||||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
||||
conn.request("GET", "/health")
|
||||
resp = conn.getresponse()
|
||||
self.assertEqual(resp.status, 200)
|
||||
data = json.loads(resp.read())
|
||||
self.assertEqual(data.get("status"), "ok")
|
||||
conn.close()
|
||||
|
||||
def test_tls_startup_failure_fallback_to_http(self):
|
||||
"""Bad cert paths should print a warning and start HTTP anyway."""
|
||||
port = _find_free_port()
|
||||
self._proc = _start_server(
|
||||
port, cert="/nonexistent/cert.pem", key="/nonexistent/key.pem",
|
||||
)
|
||||
# Server should be reachable over plain HTTP even though TLS setup failed
|
||||
self.assertTrue(
|
||||
_wait_for_server("127.0.0.1", port, use_ssl=False),
|
||||
"HTTP fallback server did not start after TLS failure",
|
||||
)
|
||||
# Confirm TLS warning was printed
|
||||
import fcntl
|
||||
os.set_blocking(self._proc.stdout.fileno(), False)
|
||||
output = ""
|
||||
try:
|
||||
output = self._proc.stdout.read(2000) or ""
|
||||
except BlockingIOError:
|
||||
output = ""
|
||||
self.assertIn("TLS setup failed", output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user