Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b12a682121 | ||
|
|
bc16545794 | ||
|
|
a13a1e0b9e | ||
|
|
fc43b897c5 | ||
|
|
d6a925cf11 | ||
|
|
5468b04550 | ||
|
|
7556ea0e04 | ||
|
|
92fbf2a793 | ||
|
|
0d98116b37 | ||
|
|
31a721417e | ||
|
|
f9663d2f1d | ||
|
|
cbc3c01604 | ||
|
|
42dd2b562d | ||
|
|
6b4ff53315 | ||
|
|
ce84d1bafa | ||
|
|
afa540a222 | ||
|
|
711bb5a6c9 | ||
|
|
c677893105 | ||
|
|
eca6f5efbd | ||
|
|
068836cf6b | ||
|
|
09325f1bdf | ||
|
|
1003fa410c | ||
|
|
a2ae953620 | ||
|
|
b86ace6ce3 | ||
|
|
c357ed9b74 | ||
|
|
27c2fd6c08 | ||
|
|
0e112455ec | ||
|
|
02e6e768e6 | ||
|
|
da160d675f | ||
|
|
1e27940535 | ||
|
|
2215aced19 | ||
|
|
4947a6b0c3 |
30
.github/workflows/tests.yml
vendored
Normal file
30
.github/workflows/tests.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master]
|
||||
push:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: ['3.11', '3.12', '3.13']
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install pyyaml>=6.0 pytest pytest-timeout
|
||||
|
||||
- name: Run tests
|
||||
run: pytest tests/ -v --timeout=60
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -25,3 +25,6 @@ full-UI.png
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local reference clones — never committed
|
||||
docs/
|
||||
|
||||
@@ -28,7 +28,8 @@ This makes the code easy to modify from a terminal or by an agent.
|
||||
<repo>/
|
||||
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.
|
||||
bootstrap.py One-shot launcher: optional agent install, deps, health wait, browser open.
|
||||
start.sh Thin wrapper around bootstrap.py for shell-based startup.
|
||||
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
|
||||
@@ -39,6 +40,7 @@ This makes the code easy to modify from a terminal or by an agent.
|
||||
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve(), security headers (~71 lines)
|
||||
models.py Session model + CRUD, per-session profile tracking (~137 lines)
|
||||
profiles.py Profile state management, hermes_cli wrapper (~246 lines)
|
||||
onboarding.py First-run onboarding status, real provider config writes, and readiness detection.
|
||||
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)
|
||||
@@ -53,6 +55,7 @@ This makes the code easy to modify from a terminal or by an agent.
|
||||
messages.js send(), SSE event handlers, approval, transcript (~297 lines)
|
||||
panels.js Cron, skills, memory, workspace, profiles, todo, settings (~974 lines)
|
||||
commands.js Slash command registry, parser, autocomplete dropdown (~156 lines)
|
||||
onboarding.js First-run wizard overlay, provider setup flow, and settings/workspace orchestration.
|
||||
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)
|
||||
|
||||
138
CHANGELOG.md
138
CHANGELOG.md
@@ -6,6 +6,144 @@
|
||||
---
|
||||
|
||||
|
||||
## [v0.49.2] OAuth provider support in onboarding (issues #303, #304)
|
||||
|
||||
- **OAuth provider bypass** (closes #303, #304): The first-run onboarding wizard now correctly recognizes OAuth-authenticated providers (GitHub Copilot, OpenAI Codex, Nous Portal, Qwen OAuth) as ready, instead of always demanding an API key.
|
||||
- New `_provider_oauth_authenticated()` helper in `api/onboarding.py` checks `hermes_cli.auth.get_auth_status()` first (authoritative), then falls back to parsing `~/.hermes/auth.json` directly for the known OAuth provider IDs (`openai-codex`, `copilot`, `copilot-acp`, `qwen-oauth`, `nous`).
|
||||
- `_status_from_runtime()` now has an `else` branch for providers not in `_SUPPORTED_PROVIDER_SETUPS`; OAuth-authenticated providers return `provider_ready=True` and `setup_state="ready"`.
|
||||
- The `provider_incomplete` status note no longer says "API key" for OAuth providers — it now says "Run 'hermes auth' or 'hermes model' in a terminal to complete setup."
|
||||
- 19 new tests in `tests/test_sprint34.py`; 738 tests total (up from 719)
|
||||
|
||||
## [v0.49.1] Docker docs + mobile Profiles button (PRs #291, #265)
|
||||
|
||||
- **Two-container Docker setup** (PR #291 / closes #288): New `docker-compose.two-container.yml` for running the Hermes Agent and WebUI as separate containers with shared volumes. Documents the architecture clearly; localhost-only port binding by default.
|
||||
- **Mobile Profiles button** (PR #265 @gabogabucho): Adds Profiles to the mobile bottom navigation bar (last position: Chat → Tasks → Skills → Memory → Spaces → Profiles). Uses `mobileSwitchPanel()` for correct active-highlight behaviour; `data-panel="profiles"` attribute set; SVG matches other nav icons; 3 new tests.
|
||||
- 700 tests total (up from 697)
|
||||
|
||||
## [v0.49.0] First-run onboarding wizard + self-update hardening (PRs #285, #287, #289)
|
||||
|
||||
- **One-shot bootstrap and first-run setup wizard** (PR #285): New users are greeted with a guided onboarding overlay on first load. The wizard checks system status, configures a provider (OpenRouter, Anthropic, OpenAI, or custom OpenAI-compatible endpoint), sets a workspace and optional password, and marks setup as complete — all without leaving the browser.
|
||||
- `bootstrap.py`: one-shot CLI bootstrap that writes `~/.hermes/config.yaml` and `~/.hermes/.env` from flags; idempotent and safe to re-run
|
||||
- `api/routes.py`: `/api/onboarding/status` (GET) and `/api/onboarding/complete` (POST) endpoints; real provider config persistence to `config.yaml` + `.env`
|
||||
- `static/onboarding.js`: full wizard JS module — step navigation, provider dropdown, model selector, API key input, Back/Continue flow, i18n support
|
||||
- `static/index.html`: onboarding overlay HTML shell + `<script src="/static/onboarding.js">` load
|
||||
- `static/i18n.js`: 40+ onboarding keys added to all 5 locales (en, es, de, zh-Hans, zh-Hant)
|
||||
- `static/boot.js`: on load, fetches `/api/onboarding/status` and opens wizard when `completed=false`
|
||||
- Wizard does NOT show when `onboarding_completed=true` in settings
|
||||
- 14 new tests in `tests/test_onboarding.py`; 693 tests total (up from 679)
|
||||
|
||||
- **Self-update git pull diagnostics** (PR #287): Fixes multiple failure modes in the WebUI self-update flow when the repo has a non-trivial git state.
|
||||
- `_run_git()` now returns stderr on failure (stdout fallback, then exit-code message) — users see actionable git errors instead of empty strings
|
||||
- New `_split_remote_ref()` helper splits `origin/master` into `('origin', 'master')` before `git pull --ff-only` — fixes silent failures where git misinterpreted the combined string as a repository name
|
||||
- `--untracked-files=no` added to `git status --porcelain` — prevents spurious stash failures in repos with untracked files
|
||||
- Early merge-conflict detection via porcelain status codes before attempting pull
|
||||
- 4 new unit tests in `tests/test_updates.py`
|
||||
|
||||
- **Skip flaky redaction test in agent-less environments** (PR #289): `test_api_sessions_list_redacts_titles` added to the CI skip list for environments without hermes-agent installed. Test still runs with the full agent; security coverage preserved by 6 pure-unit tests and 2 other API-level redaction tests.
|
||||
- 697 tests total (up from 693)
|
||||
|
||||
## [v0.48.2] Provider/model mismatch warning (PR #283, fixes #266)
|
||||
|
||||
- **Provider mismatch warning** (PR #283): WebUI now warns when you select a model from a provider different from the one Hermes is configured for, instead of silently failing with a 401 error.
|
||||
- `api/streaming.py`: 401/auth errors classified as `type='auth_mismatch'` with an actionable hint ("Run `hermes model` in your terminal to switch providers")
|
||||
- `static/ui.js`: `populateModelDropdown()` stores `active_provider` from `/api/models` as `window._activeProvider`; new `_checkProviderMismatch()` helper compares selected model's provider prefix against the configured provider
|
||||
- `static/boot.js`: `modelSelect.onchange` calls `_checkProviderMismatch()` and shows a toast warning immediately on selection
|
||||
- `static/messages.js`: `apperror` handler shows "Provider mismatch" label (via i18n) instead of "Error" for auth errors
|
||||
- `static/i18n.js`: `provider_mismatch_warning` and `provider_mismatch_label` keys added to all 5 locales (en, es, de, zh-Hans, zh-Hant)
|
||||
- Check skipped for `openrouter` and `custom` providers to avoid false positives
|
||||
- 21 new tests in `tests/test_provider_mismatch.py`; 679 tests total (up from 658)
|
||||
## [v0.48.1] Markdown table inline formatting (PR #278)
|
||||
|
||||
- **Inline formatting in table cells** (PR #278, @nesquena): Table header and data cells now render `**bold**`, `*italic*`, `` `code` ``, and `[links](url)` correctly. Previously `esc()` was used, which displayed raw HTML tags as text. Changed to `inlineMd()` consistent with list items and blockquotes. XSS-safe: `inlineMd()` escapes all interpolated values. Two-line change in `static/ui.js`. Fixes #273.
|
||||
## [v0.48.0] Real-time gateway session sync (PR #274)
|
||||
|
||||
- **Real-time gateway session sync** (PR #274, @bergeouss): Gateway sessions from Telegram, Discord, Slack, and other messaging platforms now appear in the WebUI sidebar and update in real time as new messages arrive. Enable via the "Show agent sessions" checkbox (renamed from "Show CLI sessions").
|
||||
- `api/gateway_watcher.py`: background daemon thread polling `state.db` every 5s using MD5 hash-based change detection
|
||||
- New SSE endpoint `/api/sessions/gateway/stream` for real-time push to browser
|
||||
- Dynamic source badges: telegram (blue), discord (purple), slack (dark purple), cli (green)
|
||||
- Zero changes to hermes-agent — WebUI reads the shared `state.db` that both components access
|
||||
- 10 new tests in `test_gateway_sync.py` covering metadata, filtering, SSE, and watcher lifecycle
|
||||
- 658 tests (up from 648)
|
||||
## [v0.47.1] Spanish locale (PR #275)
|
||||
|
||||
- **Spanish (es) locale** (PR #275, @gabogabucho): Full Spanish translation for all 175 UI strings. Exposed automatically in the language selector via existing `LOCALES` wiring. Includes regression tests verifying locale presence, representative translations, and key-parity with English. 648 tests (up from 645).
|
||||
## [v0.47.0] — 2026-04-11
|
||||
|
||||
### Features
|
||||
- **`/skills [query]` slash command** (PR #257): Fetches from `/api/skills`, groups results by category (alphabetically), renders as a formatted assistant message. Optional query filters by name, description, or category. Shows in the `/` autocomplete dropdown. i18n for en/de/zh/zh-Hant. 1 regression test added.
|
||||
- **Shared app dialogs replace native `confirm()`/`prompt()`** (PR #251, extracted from #242 by @aronprins): `showConfirmDialog()` and `showPromptDialog()` in `ui.js`, backed by `#appDialogOverlay`. Replaces all 11 native browser dialog call sites across panels.js, sessions.js, ui.js, workspace.js. Full keyboard focus trap (Tab/Escape/Enter), ARIA roles, danger mode, focus restore, mobile-responsive buttons. i18n for en/de/zh/zh-Hant. 5 new tests in `test_sprint33.py`.
|
||||
- **Session `⋯` action dropdown** (PR #252, extracted from #242 by @aronprins): Replaces 5 per-row hover buttons (pin/move/archive/duplicate/delete) with a single `⋯` trigger. Menu uses `position:fixed` to avoid sidebar clipping. Full close handling: click-outside, scroll, Escape, resize-reposition. `test_sprint16.py` updated to assert the new trigger exists and old button classes are gone.
|
||||
|
||||
### Bug Fixes
|
||||
- **Custom provider with slash model name no longer rerouted to OpenRouter** (PR #255): `resolve_model_provider()` now returns immediately with the configured `provider`/`base_url` when `base_url` is set, before the slash-based OpenRouter heuristic runs. Fixes `google/gemma-4-26b-a4b` with `provider: custom` being silently routed to OpenRouter (401 errors). 1 regression test added. Fixes #230.
|
||||
- **Android Chrome: workspace panel now closeable on mobile** (PR #256): `toggleMobileFiles()` now shows/hides the mobile overlay. New `closeMobileFiles()` helper closes the right panel with correct overlay tracking. Overlay tap-to-close calls both `closeMobileSidebar()` and `closeMobileFiles()`. Mobile-only `×` close button added to workspace panel header. Fix applied during review: `closeMobileSidebar()` now checks if the right panel is still open before hiding the overlay. Fixes #247.
|
||||
- **Android Chrome: profile dropdown no longer clipped on mobile** (PR #256): `.profile-dropdown` switches to `position:fixed; top:56px; right:8px` at `max-width:900px`, escaping the `overflow-x:auto` stacking context that was making it invisible. Fixes #246.
|
||||
|
||||
### Tests
|
||||
- **Mobile layout regression suite** (PR #254): 14 static tests in `tests/test_mobile_layout.py` that run on every QA pass. Covers: CSS breakpoints at 900px/640px, right panel slide-over, mobile overlay, bottom nav, files button, profile dropdown z-index, chip overflow, workspace close, `100dvh`, 44px touch targets, 16px textarea font. All pass against current and future master.
|
||||
|
||||
**CSS hotfix (commit a2ae953, post-tag):** session action menu — icon now displays inline-left of text. The `.ws-opt` base class (`flex-direction:column`) was causing SVG icons to stack above the label. Fixed with 3 CSS rule overrides on `.session-action-opt`.
|
||||
|
||||
**645 tests (up from 624 on v0.46.0 — +21 new tests)**
|
||||
|
||||
---
|
||||
|
||||
## [v0.46.0] — 2026-04-11
|
||||
|
||||
### Features
|
||||
- **Docker UID/GID matching** (PR #237 by @mmartial): New `docker_init.bash` entrypoint adds `hermeswebui`/`hermeswebuitoo` user pattern so container-created files match the host user UID/GID. Prevents `.hermes` volume mounts from being owned by root. Configure via `WANTED_UID` and `WANTED_GID` env vars (default 1000/1000). README updated with setup instructions.
|
||||
- `Dockerfile` — two-user pattern with passwordless sudo; `/.within_container` marker for in-container detection; starts as `hermeswebuitoo`, switches to correct UID/GID
|
||||
- `docker-compose.yml` — mounts `.hermes` at `/home/hermeswebui/.hermes`; uses `${UID:-1000}/${GID:-1000}` for UID/GID passthrough
|
||||
- `server.py` — detects `/.within_container` and prints a note when binding to 0.0.0.0
|
||||
|
||||
### Security
|
||||
- **Credential redaction in API responses** (PR #243 by @kcclaw001): All API endpoints now redact credentials from responses at the response layer. Session files on disk are unchanged; only the API output is masked.
|
||||
- `api/helpers.py` — `redact_session_data()` and `_redact_value()` apply pattern-based redaction to messages, tool_calls, and title; covers GitHub PATs, OpenAI/Anthropic keys, AWS keys, Slack tokens, HuggingFace tokens, Authorization Bearer headers, and PEM private key blocks
|
||||
- `api/routes.py` — `GET /api/session`, `GET /api/session/export`, `GET /api/memory` all wrapped with redaction
|
||||
- `api/streaming.py` — SSE `done` event payload redacted before broadcast
|
||||
- `api/startup.py` — new `fix_credential_permissions()` called at startup; `chmod 600` on `.env`, `google_token.json`, `auth.json`, `.signing_key` if they have group/other read bits set
|
||||
- `tests/test_security_redaction.py` — 13 new tests covering redaction functions and endpoint structural verification
|
||||
|
||||
### Bug Fixes
|
||||
- **Custom model list discovery with config API key** (PR #238 by @ccqqlo): `get_available_models()` now reads `api_key` from `config.yaml` before env vars when fetching `/v1/models` from custom endpoints (LM Studio, Ollama, etc.). Priority: `model.api_key` → `providers.<active>.api_key` → `providers.custom.api_key` → env vars. Also adds `OpenAI/Python 1.0` User-Agent header. Fixes model picker collapsing to single default model for config-only setups. 1 new regression test.
|
||||
- **HTML entity decode before markdown processing** (PR #239 by @Argonaut790): Adds `decode()` helper in `renderMd()` to fix double-escaping of HTML entities from LLM output (e.g. `<code>` becoming `&lt;code&gt;` instead of rendering). XSS-safe: decode runs before `esc()`, only 5 entity patterns (`<`, `>`, `&`, `"`, `'`).
|
||||
- **Simplified Chinese translations completed** (PR #239 by @Argonaut790): 40+ missing keys added to `zh` locale (123 → 164 keys). New `zh-Hant` (Traditional Chinese) locale with 163 keys.
|
||||
- **Cancel button now interrupts agent execution** (PR #244 by @huangzt): `cancel_stream()` now calls `agent.interrupt()` to stop backend tool execution, not just the SSE stream. `AGENT_INSTANCES` dict (protected by `STREAMS_LOCK`) tracks active agents. Race condition fixed: after storing agent, immediately checks if cancel was already requested. Frontend: removes stale "Cancelling..." status text; `setBusy(false)` always called on cancel. 6 new unit tests in `tests/test_cancel_interrupt.py`.
|
||||
|
||||
**624 tests (up from 604 on v0.45.0 — +20 new tests)**
|
||||
|
||||
---
|
||||
|
||||
## [v0.45.0] — 2026-04-10
|
||||
|
||||
### Features
|
||||
- **Custom endpoint fields in new profile form** (PR #233, fixes #170): The New Profile form now accepts optional Base URL and API key fields. When provided, both are written into the new profile's `config.yaml` under the `model` section, enabling local-endpoint setups (Ollama, LMStudio, etc.) to be configured in one step without editing YAML manually. The write is a no-op when both fields are left blank, so existing profile creation behavior is unchanged.
|
||||
- `api/profiles.py` — `_write_endpoint_to_config()` merges `base_url`/`api_key` into `config.yaml` using `yaml.safe_load` + `yaml.dump`, preserving any existing keys
|
||||
- `api/routes.py` — accepts `base_url` and `api_key` from POST body; validates that `base_url`, if provided, starts with `http://` or `https://` (returns 400 for invalid schemes)
|
||||
- `static/index.html` — two new inputs added to the New Profile form: Base URL (with `http://localhost:11434` placeholder) and API key (password type)
|
||||
- `static/panels.js` — `submitProfileCreate()` reads both fields, validates URL format client-side before sending, and includes them in the create payload; `toggleProfileForm()` clears them on cancel
|
||||
- 9 tests in `tests/test_sprint31.py` covering: config write (base_url, api_key, both, merge, no-op), route acceptance, profile path in response, and invalid-scheme rejection
|
||||
|
||||
**604 tests (up from 595)**
|
||||
|
||||
## [v0.44.1] — 2026-04-10
|
||||
|
||||
- **Unskip 16 approval tests** (PR #231): `test_approval_unblock.py` was importing `has_pending` and `pop_pending` from `tools.approval`, which the agent module had removed. The import failure tripped the `APPROVAL_AVAILABLE` guard and skipped all 16 tests in the file. Neither symbol was used in any test body. Removing the stale imports restores **595/595 passing, 0 skipped**.
|
||||
|
||||
## [v0.44.0] — 2026-04-10
|
||||
|
||||
### Features
|
||||
- **Lucide SVG icons** (PR #221): Replaces all emoji icons in the sidebar, workspace, and tool cards with self-hosted Lucide SVG paths via `static/icons.js`. No CDN dependency — icons are bundled directly. The `li(name)` renderer uses a hardcoded whitelist, so server-supplied tool names never inject arbitrary SVG. All 35 `onclick=` functions verified to exist in JS; all 21 icon references verified in `icons.js`.
|
||||
|
||||
### Bug Fixes
|
||||
- **Approval card hides immediately on respond/stream-end** (PR #225): `respondApproval()` and all stream-end SSE handlers (done, cancel, apperror, error, start-error) now call `hideApprovalCard(true)`. Previously the 30s minimum-visibility guard deferred the hide, leaving the card visible with disabled buttons for up to 30s after the user clicked Approve/Deny or the session completed. The poll-loop tick correctly keeps no-force so the guard still protects against transient polling gaps. Adds 11 structural tests for the timer logic.
|
||||
- **Login page CSP fix** (PR #226): Moves `doLogin()` and Enter key listener from inline `<script>`/`onsubmit`/`onkeydown` attributes into `static/login.js`. Inline handlers are blocked by strict `script-src` CSP, causing silent login failure. i18n error strings now passed via `data-*` attributes instead of injected JS literals. Also guards `res.json()` parse with try/catch so non-JSON server errors fall back to the password-error message. Fixes #222.
|
||||
- **Update error messages** (PR #227): `_apply_update_inner()` now fetches before pulling and surfaces three distinct failure modes with actionable recovery commands: network unreachable, diverged history (`git reset --hard`), and missing upstream tracking branch (`git branch --set-upstream-to`). Generic fallback truncates to 300 chars with a sentinel for empty output. Adds 13 tests covering all new diagnostic code paths. Fixes #223.
|
||||
- **Approval pending check** (PR #228): `GET /api/approval/pending` always returned `{pending: null}` after the agent module renamed `has_pending` to `has_blocking_approval`. The route now checks `_pending` directly under `_lock`, matching how `submit_pending` writes to it. Fixes `test_approval_submit_and_respond`.
|
||||
|
||||
### Tests
|
||||
- 579 passing, 16 skipped at this tag (595/595 after v0.44.1 unskip — +24 new tests across PRs #225, #227, #228)
|
||||
|
||||
## [v0.43.1] — 2026-04-10
|
||||
|
||||
- **CSRF fix for reverse proxies** (PR #219): The CSRF check now accepts `X-Forwarded-Host` and `X-Real-Host` headers in addition to `Host`, so deployments behind Caddy, nginx, and Traefik no longer reject POST requests with "Cross-origin request rejected". Security is preserved — requests with no matching proxy header are still rejected. Fixes #218.
|
||||
|
||||
76
Dockerfile
76
Dockerfile
@@ -3,21 +3,79 @@ FROM python:3.12-slim
|
||||
LABEL maintainer="nesquena"
|
||||
LABEL description="Hermes Web UI — browser interface for Hermes Agent"
|
||||
|
||||
WORKDIR /app
|
||||
# Install system packages
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
# Copy source
|
||||
COPY . /app
|
||||
# Make use of apt-cacher-ng if available
|
||||
RUN if [ "A${BUILD_APT_PROXY:-}" != "A" ]; then \
|
||||
echo "Using APT proxy: ${BUILD_APT_PROXY}"; \
|
||||
printf 'Acquire::http::Proxy "%s";\n' "$BUILD_APT_PROXY" > /etc/apt/apt.conf.d/01proxy; \
|
||||
fi \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates wget gnupg \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& apt-get clean
|
||||
|
||||
# Install Python dependencies
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN apt-get update -y --fix-missing --no-install-recommends \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
apt-utils \
|
||||
locales \
|
||||
ca-certificates \
|
||||
sudo \
|
||||
curl \
|
||||
rsync \
|
||||
&& apt-get upgrade -y \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# UTF-8
|
||||
RUN localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
|
||||
ENV LANG=en_US.utf8
|
||||
ENV LC_ALL=C
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONIOENCODING=utf-8
|
||||
|
||||
WORKDIR /apptoo
|
||||
|
||||
# Every sudo group user does not need a password
|
||||
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
|
||||
|
||||
# Create a new group for the hermeswebui and hermeswebuitoo users
|
||||
RUN groupadd -g 1024 hermeswebui \
|
||||
&& groupadd -g 1025 hermeswebuitoo
|
||||
|
||||
# The hermeswebui (resp. hermeswebuitoo) user will have UID 1024 (resp. 1025),
|
||||
# be part of the hermeswebui (resp. hermeswebuitoo) and users groups and be sudo capable (passwordless)
|
||||
RUN useradd -u 1024 -d /home/hermeswebui -g hermeswebui -s /bin/bash -m hermeswebui \
|
||||
&& usermod -G users hermeswebui \
|
||||
&& adduser hermeswebui sudo
|
||||
RUN useradd -u 1025 -d /home/hermeswebuitoo -g hermeswebuitoo -s /bin/bash -m hermeswebuitoo \
|
||||
&& usermod -G users hermeswebuitoo \
|
||||
&& adduser hermeswebuitoo sudo
|
||||
RUN chown -R hermeswebuitoo:hermeswebuitoo /apptoo
|
||||
|
||||
USER root
|
||||
|
||||
COPY --chmod=555 docker_init.bash /hermeswebui_init.bash
|
||||
|
||||
RUN touch /.within_container
|
||||
|
||||
# Remove APT proxy configuration and clean up APT downloaded files
|
||||
RUN rm -rf /var/lib/apt/lists/* /etc/apt/apt.conf.d/01proxy \
|
||||
&& apt-get clean
|
||||
|
||||
USER hermeswebuitoo
|
||||
|
||||
COPY . /apptoo
|
||||
|
||||
# Default to binding all interfaces (required for container networking)
|
||||
ENV HERMES_WEBUI_HOST=0.0.0.0
|
||||
ENV HERMES_WEBUI_PORT=8787
|
||||
|
||||
# State directory (mount as volume for persistence)
|
||||
ENV HERMES_WEBUI_STATE_DIR=/data
|
||||
|
||||
EXPOSE 8787
|
||||
|
||||
CMD ["python", "server.py"]
|
||||
CMD ["/hermeswebui_init.bash"]
|
||||
|
||||
|
||||
552
HERMES.md
552
HERMES.md
@@ -1,165 +1,176 @@
|
||||
# Why Hermes
|
||||
|
||||
Hermes is a persistent, autonomous AI agent that lives on your server. It remembers everything,
|
||||
schedules work while you sleep, and gets more capable the longer it runs. This document explains
|
||||
the mental model, why that matters, and how Hermes compares to every major AI tool available today.
|
||||
Hermes is a persistent, autonomous AI agent that runs on your server. It has layered memory that
|
||||
accumulates across sessions, a cron scheduler that fires jobs while you're offline, and a
|
||||
self-improving skills system that saves reusable procedures automatically. You reach it from a
|
||||
terminal, a browser, or a messaging app — and it's the same agent with the same history every time.
|
||||
|
||||
This document explains the mental model, how Hermes compares to other tools honestly, and where
|
||||
it is and is not the right choice.
|
||||
|
||||
---
|
||||
|
||||
## The Core Idea: Assistants Forget. Agents Don't.
|
||||
## The real problem: most tools are excellent in the moment and weak over time
|
||||
|
||||
Every time you open Claude Code, Codex, or a chat window, the tool starts from zero. It does not
|
||||
know who you are, what you worked on yesterday, how your repo is structured, or what bugs you
|
||||
already fixed. You re-explain yourself every single session. The tool is powerful in the moment
|
||||
and useless the next day.
|
||||
Memory is no longer a differentiator on its own. ChatGPT, Claude, Cursor, and GitHub Copilot all
|
||||
have some form of memory now. Anthropic, OpenAI, and Microsoft are all shipping scheduling and
|
||||
agent features. The category boundaries that existed twelve months ago are blurring fast.
|
||||
|
||||
Hermes fills that gap. It runs on your server, retains context across every session, and acts
|
||||
on your behalf whether or not you are at a keyboard.
|
||||
Hermes is not the only tool with memory or automation. It is the tool that makes those
|
||||
capabilities durable, self-hosted, cross-surface, and cumulative on your own server. The
|
||||
distinction that matters is not "has memory" vs. "has no memory" — it's whether context persists
|
||||
across sessions automatically, whether execution happens on hardware you control, whether you can
|
||||
reach the same agent identity from any device, and whether the system gets meaningfully better at
|
||||
your specific workflow over time without manual configuration.
|
||||
|
||||
```
|
||||
Assistant model: You -> [Tool] -> Answer -> Done
|
||||
(tool forgets everything when the window closes)
|
||||
Session-scoped: You -> [Tool] -> Answer -> Done
|
||||
(some tools now carry memory, but the execution is stateless)
|
||||
|
||||
Agent model: You <-> [Hermes] <-> (memory, skills, schedule, tools)
|
||||
(persistent, learns your stack, acts on your behalf, runs while you're offline)
|
||||
Persistent agent: You <-> [Hermes] <-> (memory, skills, schedule, tools, surfaces)
|
||||
(runs on your server, accumulates context, acts on your behalf offline)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## The Three Pillars
|
||||
## A note on convergence
|
||||
|
||||
### 1. Memory That Compounds
|
||||
The market is converging. Chat assistants are adding task scheduling and file connectors. IDE
|
||||
tools are launching cloud agent modes. CLI tools are adding skills systems and mobile surfaces.
|
||||
The lines between "assistant," "editor," and "agent" are dissolving.
|
||||
|
||||
Hermes has layered memory that survives every session, every reboot, every model swap:
|
||||
This makes comparisons harder but also makes the question sharper: what actually matters when
|
||||
every tool is claiming some version of every feature? For Hermes, the answer is synthesis. Any
|
||||
single feature — memory, scheduling, messaging — is available somewhere else. The value is
|
||||
having all of them in one self-hosted system, running continuously, with a persistent identity
|
||||
that accumulates real knowledge of your stack over time.
|
||||
|
||||
- **User profile** -- who you are, your preferences, your communication style, things you've
|
||||
corrected Hermes on
|
||||
- **Agent memory** -- facts about your environment, your toolchain, your project conventions
|
||||
- **Skills** -- reusable procedures Hermes discovers and saves; it never has to relearn how to
|
||||
deploy your app, run your tests, or review a PR
|
||||
- **Session history** -- every past conversation is searchable; Hermes can recall what you
|
||||
worked on last Tuesday
|
||||
---
|
||||
|
||||
## The three pillars
|
||||
|
||||
### 1. Memory that compounds
|
||||
|
||||
Hermes has layered memory that survives every session, every reboot, and every model swap:
|
||||
|
||||
- User profile — who you are, your preferences, your communication style, things you've corrected Hermes on
|
||||
- Agent memory — facts about your environment, your toolchain, your project conventions
|
||||
- Skills — reusable procedures Hermes discovers and saves automatically; it never has to relearn how to deploy your app, run your tests, or review a PR
|
||||
- Session history — every past conversation is searchable; Hermes can recall what you worked on last Tuesday
|
||||
|
||||
When you correct Hermes, it remembers. When it solves a tricky problem, it saves the approach.
|
||||
When it learns your stack, that knowledge carries into every future session.
|
||||
When it learns your stack, that knowledge carries into every future session. You never configure
|
||||
this manually — it happens in the background as a side effect of normal use.
|
||||
|
||||
### 2. Autonomous Scheduling
|
||||
### 2. Autonomous scheduling
|
||||
|
||||
Hermes can run jobs without you present -- every hour, every morning, on any cron schedule.
|
||||
It fires up a fresh session, runs the task, and delivers the result to wherever you want it:
|
||||
Telegram, Discord, Slack, Signal, WhatsApp, SMS, email, and more.
|
||||
Hermes can run jobs without you present — every hour, every morning, on any cron schedule. It
|
||||
fires up a fresh session with full access to your memory and skills, runs the task, and delivers
|
||||
the result wherever you want it: Telegram, Discord, Slack, Signal, WhatsApp, SMS, email, and more.
|
||||
|
||||
Things Hermes can do while you sleep:
|
||||
|
||||
- Review new pull requests on your GitHub repo and post a full verdict comment
|
||||
- Send you a morning briefing of news, markets, or anything else you care about
|
||||
- Send a morning briefing of news, markets, or anything else you track
|
||||
- Run your test suite and alert you if something breaks
|
||||
- Watch a competitor's blog for new posts and summarize them
|
||||
- Monitor a datasource and notify you when a threshold is crossed
|
||||
|
||||
### 3. Reach It From Anywhere
|
||||
The difference from cloud-scheduled alternatives is that the job runs on your server, with your
|
||||
memory and skills, and your data never leaves your hardware.
|
||||
|
||||
### 3. Reach it from anywhere
|
||||
|
||||
Hermes runs on your server and is reachable from every surface: terminal over SSH, the web UI
|
||||
(this project), and messaging apps including Telegram, Discord, Slack, WhatsApp, Signal, and
|
||||
Matrix. Start a task from your phone, check it from the browser on your laptop, continue it in
|
||||
a terminal on a remote server. The same agent, memory, and history follow you everywhere.
|
||||
a terminal on a remote server. The same agent, memory, and history follow you across all of them.
|
||||
|
||||
---
|
||||
|
||||
## A Framework for AI Tools
|
||||
## How AI tools are layered today
|
||||
|
||||
There are four distinct categories of AI tool. Understanding the category tells you what a tool
|
||||
can and cannot do.
|
||||
The old four-category model — chat, editor, CLI, agent — is too clean. These layers are actively
|
||||
collapsing into each other. Here is a more honest picture:
|
||||
|
||||
### Category 1: Chat Assistants
|
||||
*Claude.ai, ChatGPT, Gemini*
|
||||
Chat assistants (Claude.ai, ChatGPT) now have persistent memory, task scheduling, 50+ service
|
||||
connectors, and in some cases full agent modes with computer use. They are no longer "just chat."
|
||||
|
||||
You open a window, ask something, get an answer. No persistent memory beyond the conversation,
|
||||
no ability to run code or touch files, no way to act on your behalf. Excellent for Q&A,
|
||||
drafting, and brainstorming. You re-explain your context every session.
|
||||
IDE tools (Cursor, Windsurf, Copilot) have shipped or are shipping cross-session memory,
|
||||
cloud-based background agents, and in Cursor's case a full Automations platform with Slack
|
||||
integration. Cursor v3.0 (April 2026) is explicitly agent-first.
|
||||
|
||||
### Category 2: IDE Integrations
|
||||
*GitHub Copilot, Cursor, Windsurf, Zed AI*
|
||||
CLI tools (Claude Code, Codex, OpenCode) have added hooks, skills, desktop app automations,
|
||||
and multi-surface reach. Claude Code now spans terminal, IDE, desktop, and browser. Codex has
|
||||
become a product family: CLI, IDE extension, desktop app, and Codex Cloud.
|
||||
|
||||
Deep inside your editor. Autocomplete, inline diffs, refactors -- all excellent. Windsurf was
|
||||
earliest with workspace-scoped memory (Cascade Memories); Copilot has been shipping repo-level
|
||||
memory since late 2025 and is catching up. Cursor has no native memory as of early 2026. None
|
||||
have scheduling or messaging access. Tied to one machine and one editor.
|
||||
Persistent self-hosted agents (Hermes, OpenClaw) sit at the intersection: they combine the
|
||||
tool-use power of CLI agents, the memory of chat assistants, the scheduling of automation
|
||||
platforms, and the cross-surface reach of messaging integrations — running continuously on
|
||||
hardware you own.
|
||||
|
||||
### Category 3: Agentic CLI Tools
|
||||
*Claude Code, Codex CLI, OpenCode, Aider*
|
||||
|
||||
The current frontier for most developers. Can use real tools -- run shell commands, read and
|
||||
write files, search the web, call APIs. Great for deep, multi-step tasks in a single terminal
|
||||
session. All are adding memory and scheduling features to varying degrees (see comparisons below),
|
||||
but the core model is still session-scoped: you invoke it, it works, it stops.
|
||||
|
||||
### Category 4: Persistent Autonomous Agents
|
||||
*Hermes, OpenClaw (as of early 2026)*
|
||||
|
||||
All the tool use of Category 3, plus memory that accumulates across sessions, plus always-on
|
||||
scheduling, plus multi-modal access from any device or messaging app. Gets more useful over time
|
||||
rather than resetting to zero. Hermes and OpenClaw are the two primary open-source, self-hosted
|
||||
tools in this category. OpenClaw is a gateway-centric automation platform; Hermes is a
|
||||
self-improving agent that writes and reuses its own procedures from experience.
|
||||
The question is not which category a tool belongs to. The question is which combination of
|
||||
capabilities you actually need, where that execution lives, and whether the system gets better
|
||||
at your specific context over time.
|
||||
|
||||
---
|
||||
|
||||
## How Hermes Compares
|
||||
## How Hermes compares
|
||||
|
||||
### vs. OpenClaw
|
||||
|
||||
OpenClaw is the most direct comparison to Hermes and the question most people ask first.
|
||||
Both are open-source, self-hosted, always-on agents with persistent memory, cron scheduling,
|
||||
and messaging app integration. If you're evaluating Hermes, you should evaluate OpenClaw too.
|
||||
OpenClaw is the most direct comparison and the question most people ask first. Both are
|
||||
open-source, self-hosted, always-on agents with persistent memory, cron scheduling, and messaging
|
||||
app integration. If you're evaluating Hermes, evaluate OpenClaw too.
|
||||
|
||||
OpenClaw (MIT, ~347k GitHub stars) is built around a **Gateway** control plane written in
|
||||
Node.js/TypeScript. It excels at broad personal automation: native Chrome/Chromium control for
|
||||
browser automation, the widest messaging platform support in the space (WhatsApp, Telegram,
|
||||
Signal, iMessage, LINE, WeChat, Slack, Discord, Teams, Matrix, and more), voice wake words,
|
||||
and a ClawHub skill marketplace where users share pre-built automations. The community is large
|
||||
and the ecosystem is growing fast.
|
||||
OpenClaw (MIT) is built around a Gateway control plane written in Node.js/TypeScript. It has the
|
||||
widest messaging coverage in the space — 24+ channels including WhatsApp, Telegram, Signal,
|
||||
iMessage, LINE, WeChat, Slack, Discord, Teams, Matrix, Google Chat, Feishu, Mattermost, IRC,
|
||||
Nextcloud Talk, and more. It has native Chrome/Chromium control via CDP, voice wake words on
|
||||
macOS and iOS, and a ClawHub marketplace with 10,700+ skills. The community is large (350k+
|
||||
GitHub stars, 16,900+ commits) and growing.
|
||||
|
||||
Hermes takes a different approach. It is built in Python and centers on a **self-improving
|
||||
agent loop** rather than a gateway control plane. The core difference is in how skills work:
|
||||
OpenClaw skills are primarily human-authored plugins installed from a marketplace; Hermes
|
||||
**writes and saves its own skills automatically** as part of every session. When Hermes solves
|
||||
a problem a new way, it saves the procedure and reuses it going forward without any user effort.
|
||||
Hermes is built in Python and centers on a self-improving agent loop rather than a gateway
|
||||
control plane. The core architectural difference is in skills: OpenClaw skills are primarily
|
||||
human-authored plugins installed from a marketplace. Hermes writes and saves its own skills
|
||||
automatically as part of every session. When Hermes solves a problem a new way, it saves the
|
||||
procedure and reuses it without any user effort. That's not a subtle distinction — it's the
|
||||
reason Hermes gets meaningfully better at your workflow without you maintaining a plugin library.
|
||||
|
||||
Beyond the skills architecture, there are two other practical differences worth knowing:
|
||||
Two practical differences worth knowing directly:
|
||||
|
||||
**Stability.** OpenClaw's community forums and GitHub issues document a recurring pattern of
|
||||
update-breaking regressions -- for example, Telegram integration was broken across multiple
|
||||
releases in early 2026. The unofficial WhatsApp Web protocol OpenClaw uses is known to
|
||||
disconnect and requires periodic re-pairing (this is documented in OpenClaw's own FAQ).
|
||||
Hermes has had no equivalent release breakages.
|
||||
Stability. OpenClaw's GitHub issues and community forums document recurring update-breaking
|
||||
regressions. Telegram integration was broken across multiple releases from early 2026 through
|
||||
at least April 2026. The unofficial WhatsApp Web protocol OpenClaw relies on disconnects and
|
||||
requires periodic re-pairing — this is in OpenClaw's own FAQ.
|
||||
|
||||
**Security.** ClawHub's open publishing model has been exploited repeatedly. A community audit
|
||||
identified over a thousand malicious skills in the marketplace including prompt injections and
|
||||
tool-poisoning payloads; the community-maintained awesome-openclaw-skills list tracks confirmed
|
||||
removals and flags known bad actors. Hermes has no third-party marketplace and a correspondingly
|
||||
smaller attack surface.
|
||||
Security. ClawHub's open publishing model has been exploited at scale. Three separate audits in
|
||||
early 2026 found serious problems: Koi Security (January 2026) linked 335 skills to a campaign
|
||||
called "ClawHavoc" that delivered Atomic Stealer malware on macOS; Bitdefender found roughly
|
||||
900 malicious packages representing about 20% of the ecosystem at the time; Snyk's "ToxicSkills"
|
||||
report (February 2026) found malicious skills across roughly 4,000 scanned packages. China's
|
||||
CNCERT issued a national warning about ClawHub. Hermes has no third-party marketplace and a
|
||||
correspondingly smaller attack surface.
|
||||
|
||||
**OpenClaw's genuine strengths** are worth stating plainly: it has broader messaging coverage
|
||||
(iMessage, LINE, WeChat, Teams -- platforms Hermes does not support), native browser and
|
||||
computer control via Chrome CDP, voice wake words on macOS and iOS, a larger community, and
|
||||
more third-party integrations than Hermes. If those capabilities matter most to you, OpenClaw
|
||||
is worth a serious look.
|
||||
OpenClaw's genuine strengths are worth stating plainly: broader messaging coverage (iMessage,
|
||||
LINE, WeChat, Teams, Google Chat — platforms Hermes does not support), native browser and
|
||||
computer control via Chrome CDP, voice wake words, a larger community, and more third-party
|
||||
integrations than Hermes. If those capabilities matter most, OpenClaw is worth a serious look.
|
||||
|
||||
Where Hermes is the better fit: you want an agent that self-improves from experience without
|
||||
manual plugin authoring, you work in Python and want access to the ML/data science ecosystem,
|
||||
you want a stable deployment that does not break between updates, or you want a full web chat
|
||||
UI rather than a monitoring dashboard.
|
||||
Where Hermes fits better: you want an agent that self-improves from experience without managing
|
||||
a plugin library, you work in Python and want the ML/data science ecosystem, you want a stable
|
||||
deployment that doesn't break between updates, or you want a full web chat UI rather than a
|
||||
control dashboard.
|
||||
|
||||
| | OpenClaw | Hermes |
|
||||
|---|---|---|
|
||||
| Persistent memory | Yes | Yes |
|
||||
| Scheduled jobs (cron) | Yes | Yes |
|
||||
| Messaging app access | Yes (15+ platforms, incl. iMessage/WeChat) | Yes (10+ platforms) |
|
||||
| Web UI | Gateway dashboard (monitoring only) | Full three-panel chat UI |
|
||||
| Messaging app access | Yes (24+ platforms, incl. iMessage/WeChat/LINE) | Yes (many platforms) |
|
||||
| Web UI | Chat UI + control dashboard | Full three-panel chat UI |
|
||||
| Self-hosted | Yes | Yes |
|
||||
| Open source | Yes (MIT) | Yes |
|
||||
| Self-improving skills | Partial (AI can generate skills; not the default loop) | Yes (automatic, first-class) |
|
||||
| Self-improving skills | Partial (AI can generate; not the default loop) | Yes (automatic, first-class) |
|
||||
| Browser / computer control | Yes (native Chrome CDP) | Via shell / tools |
|
||||
| Voice wake words | Yes (macOS/iOS) | No |
|
||||
| Python / ML ecosystem | No (Node.js) | Yes |
|
||||
@@ -167,209 +178,312 @@ UI rather than a monitoring dashboard.
|
||||
| Multi-profile support | Via binding-rule routing | Yes (first-class named profiles) |
|
||||
| Provider-agnostic | Yes | Yes |
|
||||
| Update reliability | Moderate (documented regressions) | High |
|
||||
| Memory inspectability | Limited | Yes (markdown files, editable) |
|
||||
| Self-hosted autonomous execution | Yes | Yes |
|
||||
|
||||
### vs. Claude Code (Anthropic)
|
||||
|
||||
Claude Code is Anthropic's official agentic CLI and one of the best tools in Category 3.
|
||||
In a single focused session it is capable -- deep code understanding, shell access, file
|
||||
editing, multi-step reasoning.
|
||||
Claude Code is Anthropic's official agentic tool and one of the strongest options for focused
|
||||
coding sessions. It has deep code understanding, shell access, file editing, and multi-step
|
||||
reasoning. It has been expanding rapidly — it now spans terminal, IDE plugin, desktop app, and
|
||||
browser surfaces — and the gap is closing in several areas.
|
||||
|
||||
Claude Code has been adding features rapidly and the gap is narrowing:
|
||||
What Claude Code has that's worth knowing:
|
||||
|
||||
- **Hooks system** -- 13 event types (SessionStart, PreToolUse, PostToolUse, Stop, etc.) with
|
||||
4 handler types (shell command, HTTP endpoint, LLM prompt, sub-agent); deterministic
|
||||
- Hooks system — 26 event types (SessionStart, PreToolUse, PostToolUse, Stop, and more) with
|
||||
4 handler types (shell command, HTTP endpoint, LLM prompt, sub-agent); gives deterministic
|
||||
non-LLM control over the agent lifecycle
|
||||
- **Plugins / Skills** -- installable via `/plugin install`, hot-reloaded from `~/.claude/skills`,
|
||||
with a marketplace; skills and slash commands unified as of v2.1.0
|
||||
- **Scheduling** -- `/loop` (session-scoped), cloud-managed cron via `claude.ai/code/scheduled`
|
||||
(Anthropic infrastructure, minimum interval applies), and desktop app automations
|
||||
- **Messaging channels** -- Telegram, Discord, iMessage, and webhooks via the Channels feature
|
||||
(research preview, v2.1.80+); deep Slack integration that triggers cloud sessions and creates PRs
|
||||
- **Claude Cowork** -- a separate product for knowledge workers; connects to 38+
|
||||
services via MCP including Slack, Gmail, Microsoft Teams, Notion, Jira, Salesforce, and more
|
||||
- **Memory** -- CLAUDE.md and MEMORY.md for project-level context; auto-memory rolling out
|
||||
- Plugins / Skills — installable via `/plugin install`, hot-reloaded from `~/.claude/skills`,
|
||||
with a marketplace; includes the official ralph-wiggum plugin (`/ralph-loop`) for
|
||||
autonomous iteration toward a completion goal (distinct from `/loop`)
|
||||
- `/loop` — a native bundled skill, available in every session without any plugin, that runs
|
||||
a prompt on a repeating schedule within an active CLI session (polling/monitoring use case);
|
||||
session-scoped, dies when the terminal closes
|
||||
- Scheduling — cloud-managed cron (Anthropic infrastructure, minimum 1-hour interval) and
|
||||
desktop app scheduled tasks (run locally while the app is open, minimum 1-minute interval,
|
||||
full local file access); no self-hosted cron
|
||||
- Messaging channels — Telegram, Discord, and iMessage via the Channels feature (research
|
||||
preview, requires Bun runtime); Slack is the most-requested addition and has not yet shipped
|
||||
- Memory — CLAUDE.md and MEMORY.md for project-level context; auto-memory since v2.1.59+
|
||||
- Claude Cowork — a separate knowledge-worker product connecting 38+ services via MCP
|
||||
including Gmail, Microsoft Teams, Notion, Jira, Salesforce, and more
|
||||
|
||||
These are real features. The key differences that remain:
|
||||
Claude Code's source was briefly and accidentally made public in March 2026 before being taken
|
||||
down. The CLI ships as minified/bundled TypeScript compiled with Bun — it is not open source.
|
||||
|
||||
- Claude Code's scheduling runs on **Anthropic's cloud** (or requires the desktop app open),
|
||||
not a self-hosted server; cloud jobs have a minimum interval and your data leaves your hardware
|
||||
- Memory is **project-file-based** (CLAUDE.md / MEMORY.md), not a knowledge graph that
|
||||
accumulates automatically across all your work; auto-memory is still rolling out
|
||||
- **Not provider-agnostic** -- routes through Bedrock or Vertex but always hits a Claude model;
|
||||
you cannot switch to GPT, Gemini, or a local model
|
||||
- **Not open source** -- proprietary; the CLI ships obfuscated JavaScript
|
||||
- Messaging channels are a **research preview** requiring Bun runtime; not yet production-grade
|
||||
Key differences that remain:
|
||||
|
||||
- Scheduling requires cloud (Anthropic infrastructure, data off your hardware, 1-hour minimum)
|
||||
or the desktop app (runs locally, but the app must stay open — not a headless server process);
|
||||
neither runs as a server daemon the way Hermes cron does
|
||||
- Memory is project-file-based (CLAUDE.md / MEMORY.md plus rolling auto-memory); it doesn't
|
||||
automatically accumulate a cross-project knowledge graph the way Hermes does
|
||||
- Not provider-agnostic — routes through Anthropic, Bedrock, Vertex, or Foundry, but always
|
||||
a Claude model; you can't switch to GPT, Gemini, or a local model
|
||||
- Messaging channels are still a research preview, not production
|
||||
|
||||
Hermes can use Claude Code as a sub-agent. For large implementation tasks, Hermes can spawn
|
||||
Claude Code to handle the heavy lifting and fold the result back into its own memory and history.
|
||||
|
||||
| | Claude Code | Hermes |
|
||||
|---|---|---|
|
||||
| Persistent memory (automatic) | Partial (CLAUDE.md / MEMORY.md, rolling out) | Yes |
|
||||
| Skills / hooks system | Yes (Hooks + Plugin/Skills marketplace) | Yes (auto-generated from experience) |
|
||||
| Persistent memory (automatic) | Partial (CLAUDE.md / MEMORY.md + auto-memory v2.1.59+) | Yes |
|
||||
| Skills / hooks system | Yes (26-event Hooks + Plugin/Skills marketplace) | Yes (auto-generated from experience) |
|
||||
| Scheduled jobs (self-hosted) | No (cloud or desktop-app only) | Yes |
|
||||
| Messaging access | Partial (Telegram/Discord/iMessage via research preview; Slack native) | Yes (10+ platforms, production) |
|
||||
| Messaging access | Partial (Telegram/Discord/iMessage research preview; Slack not yet) | Yes (many platforms, production) |
|
||||
| Cowork connectors (Slack, Gmail, etc.) | Yes (via Claude Cowork, separate product) | Via agent tool use |
|
||||
| Web UI | Yes (claude.ai/code, Anthropic-hosted) | Yes (self-hosted) |
|
||||
| Provider-agnostic | No (Claude models only, via Bedrock/Vertex) | Yes (any provider) |
|
||||
| Provider-agnostic | No (Claude models only) | Yes (any provider) |
|
||||
| Self-hosted scheduling | No | Yes |
|
||||
| Open source | No | Yes |
|
||||
| Background/cloud agent mode | Yes (cloud-scheduled) | Yes (self-hosted cron) |
|
||||
| Runs as sub-agent of Hermes | Yes | N/A |
|
||||
| Memory inspectability | Partial (CLAUDE.md readable; auto-memory less so) | Yes (markdown files) |
|
||||
|
||||
### vs. Codex CLI (OpenAI)
|
||||
|
||||
Codex CLI is OpenAI's open-source agentic terminal tool (Apache 2.0, ~73k GitHub stars). It
|
||||
supports 10+ providers including Anthropic, Google, Mistral, Groq, and local models via Ollama.
|
||||
It added persistent session memory in v0.100.0 with `codex resume`. The desktop app has an
|
||||
Automations feature for scheduled local tasks.
|
||||
Codex CLI (Apache 2.0, ~60k GitHub stars) started as a straightforward terminal tool and has
|
||||
expanded into a product family. It was rewritten from TypeScript to Rust. It now includes an IDE
|
||||
extension, a desktop app with an Automations feature, and Codex Cloud for remote execution. A
|
||||
Skills system is shared across surfaces. It supports 12+ built-in providers: OpenAI, Anthropic,
|
||||
Google/Gemini, Mistral, Groq, Ollama, OpenRouter, LM Studio, Together AI, DeepSeek, xAI,
|
||||
Azure OpenAI, and custom endpoints.
|
||||
|
||||
The CLI itself has no native scheduling (open feature request as of early 2026). Memory is
|
||||
session-history-based rather than a living knowledge graph. No messaging app access. A strong
|
||||
tool for single-session coding; Hermes adds the always-on layer on top.
|
||||
The CLI itself has no native scheduling (open feature request). Session continuity is available
|
||||
via `codex resume`. Memory is session-history-based plus AGENTS.md project context — not a
|
||||
living knowledge graph that accumulates across all your projects. No first-party messaging
|
||||
integration. The Automations feature in the desktop app covers scheduled local tasks but doesn't
|
||||
reach the cross-session, cross-surface continuity Hermes has.
|
||||
|
||||
| | Codex CLI | Hermes |
|
||||
|---|---|---|
|
||||
| Persistent memory | Partial (session history + AGENTS.md) | Yes (automatic, layered) |
|
||||
| Scheduled jobs | Partial (desktop app only; CLI has none) | Yes |
|
||||
| Scheduled jobs | Partial (desktop app Automations; CLI has none) | Yes |
|
||||
| Messaging app access | No | Yes |
|
||||
| Web UI | No | Yes (self-hosted) |
|
||||
| Provider-agnostic | Yes (10+ providers) | Yes (10+ providers) |
|
||||
| Web UI | No (CLI + desktop app) | Yes (self-hosted) |
|
||||
| Provider-agnostic | Yes (12+ providers) | Yes |
|
||||
| Self-hosted | Yes | Yes |
|
||||
| Open source | Yes (Apache 2.0) | Yes |
|
||||
| Background/cloud agent mode | Yes (Codex Cloud) | Yes (self-hosted cron) |
|
||||
| Self-improving skills | No | Yes |
|
||||
|
||||
### vs. OpenCode
|
||||
|
||||
OpenCode is an open-source TUI agentic coding assistant, provider-agnostic across 75+ providers.
|
||||
It has a WebUI embedded in its binary and an official desktop app. It uses SQLite for session
|
||||
history and AGENTS.md for project context.
|
||||
OpenCode is an open-source TUI agentic coding assistant supporting 75+ providers. It has a WebUI
|
||||
embedded in its binary, an official desktop app, SQLite session history, and AGENTS.md project
|
||||
context. It supports CLAUDE.md as a fallback for users migrating from Claude Code. There are 30+
|
||||
community plugins, and community messaging integrations exist for Telegram, Slack, Discord, and
|
||||
Microsoft Teams — though none are first-party and all require manual setup.
|
||||
|
||||
No native scheduled jobs (a community background plugin exists), no first-party messaging
|
||||
integration (community Telegram bots exist but require manual setup), and no automatic
|
||||
cross-session semantic memory. Good for interactive terminal coding sessions.
|
||||
OpenCode Go ($10/month) and OpenCode Zen (curated model service) are subscription tiers. The
|
||||
GitHub Copilot official integration launched January 2026. There is no native scheduling; a
|
||||
community background plugin exists. No automatic cross-session semantic memory.
|
||||
|
||||
| | OpenCode | Hermes |
|
||||
|---|---|---|
|
||||
| Persistent memory | Partial (session history + AGENTS.md) | Yes (automatic, layered) |
|
||||
| Scheduled jobs | No (community plugin only) | Yes |
|
||||
| Messaging app access | No (community Telegram bot only) | Yes (first-party, 10+ platforms) |
|
||||
| Messaging app access | Community integrations only (Telegram/Slack/Discord/Teams) | Yes (first-party, many platforms) |
|
||||
| Web UI | Yes (embedded + desktop app) | Yes (self-hosted) |
|
||||
| Mobile access | No | Yes |
|
||||
| Skills system | No | Yes |
|
||||
| Skills / plugins | Yes (30+ community plugins) | Yes (auto-generated, first-party) |
|
||||
| Provider-agnostic | Yes (75+ providers) | Yes |
|
||||
| Open source | Yes | Yes |
|
||||
| Self-hosted autonomous execution | No | Yes |
|
||||
|
||||
### vs. Cursor / Windsurf / Copilot
|
||||
### vs. Cursor
|
||||
|
||||
Category 2 tools -- exceptional at in-editor autocomplete, inline diffs, and code review.
|
||||
Not competing for the same job as Hermes, and they work well alongside it.
|
||||
Cursor has changed substantially. The "no memory, no scheduling, no messaging" description was
|
||||
accurate in 2024 and is wrong now.
|
||||
|
||||
Windsurf was earliest with workspace-scoped memory (Cascade Memories); Copilot has been
|
||||
shipping repo-level memory since late 2025. Cursor has no native cross-session memory as of
|
||||
early 2026. None have scheduling or messaging access.
|
||||
Memories (per-project cross-session knowledge base) shipped in beta with v1.0 in June 2025.
|
||||
Automations launched March 5, 2026 — time-based, event-based (GitHub/Linear/PagerDuty), and
|
||||
communication-based (Slack) triggers that fire background agents on cloud VMs. The web app,
|
||||
mobile agent, and Slack bot give it multi-surface reach. Cursor v3.0 (April 2, 2026) is
|
||||
explicitly agent-first with Design Mode and 30+ marketplace plugins. Cursor acquired Supermaven
|
||||
for autocomplete. As of early 2026 it's valued at $29.3B with $2B ARR. It is not a narrow editor
|
||||
tool anymore.
|
||||
|
||||
Hermes still has a different profile: it's self-hosted and server-resident, the same persistent
|
||||
identity follows you across every surface without cloud intermediation, and it works with any
|
||||
model family rather than being cloud-VM-based. For workflows that require data sovereignty,
|
||||
self-hosted scheduling, or deep Python/ML tooling on your own hardware, Cursor's cloud-agent
|
||||
architecture is a fundamental mismatch. For teams that want editor-native agents with strong
|
||||
IDE integration, Cursor's recent evolution is significant.
|
||||
|
||||
| | Cursor | Windsurf | Copilot | Hermes |
|
||||
|---|---|---|---|---|
|
||||
| In-editor autocomplete | Excellent | Excellent | Excellent | No |
|
||||
| In-editor autocomplete | Excellent (Supermaven) | Excellent (Cascade) | Excellent | No |
|
||||
| Inline diff / refactor | Yes | Yes | Yes | Via shell |
|
||||
| Cross-session memory | No | Yes (workspace) | Partial (repo, early access) | Yes |
|
||||
| Scheduled background jobs | No | No | No | Yes |
|
||||
| Messaging app / mobile | No | No | No | Yes |
|
||||
| Cross-session memory | Yes (Memories, per-project) | Yes (Cascade Memories, workspace) | Yes (Agentic Memory, repo-scoped, 28-day expiry) | Yes (automatic, persistent) |
|
||||
| Scheduled background jobs | Yes (Automations, cloud VM) | No | Via Coding Agent (issue-driven) | Yes (self-hosted cron) |
|
||||
| Messaging app / multi-surface | Yes (Slack bot, web app, mobile) | No | Via Copilot CLI / fleet | Yes (many platforms) |
|
||||
| Background/cloud agent mode | Yes (Automations on cloud VMs) | No | Yes (Coding Agent, GA Mar 2026) | Yes (self-hosted) |
|
||||
| Terminal tool use | Limited | Limited | Limited | Full |
|
||||
| Self-hosted | No | No | No | Yes |
|
||||
| Provider-agnostic | Partial | Partial | No | Yes |
|
||||
| Self-hosted autonomous execution | No | No | No | Yes |
|
||||
| Provider-agnostic | Partial | Partial | No (GitHub models) | Yes |
|
||||
| Open source | No | No | No | Yes |
|
||||
| Memory inspectability | Partial | Yes (stored locally) | Limited | Yes (markdown files) |
|
||||
|
||||
### vs. Claude.ai / ChatGPT
|
||||
### vs. Claude.ai and ChatGPT
|
||||
|
||||
Category 1. For drafting, Q&A, and brainstorming in the moment, both are excellent.
|
||||
These are no longer simple chat tools. The description of "no memory, no scheduling, no
|
||||
messaging" is inaccurate for both.
|
||||
|
||||
Claude.ai memory has been improving -- it now generates memory from chat history, not just
|
||||
user-curated entries. Claude.ai can also execute code and read/write files in a sandboxed
|
||||
environment via Artifacts. These are real capabilities, just not the same as direct filesystem
|
||||
or shell access on your own server.
|
||||
Claude Cowork (in Claude Desktop) launched scheduled tasks on February 25, 2026 — hourly,
|
||||
daily, weekly, weekdays, and on-demand. It runs in an isolated VM with file and shell access.
|
||||
Claude has 50+ service connectors as of February 2026 including Slack (launched January 26,
|
||||
2026), Gmail, Google Calendar, Google Drive, Microsoft 365, Notion, Asana, Linear, and Jira.
|
||||
Memory auto-generates from chat history, not just user-curated entries. Code execution and
|
||||
file access in Artifacts is sandboxed, not the same as shell access on your own server.
|
||||
|
||||
| | Claude.ai / ChatGPT | Hermes |
|
||||
|---|---|---|
|
||||
| Memory across conversations | Yes (improving; auto-generated from history) | Yes (deep, automatic) |
|
||||
| Runs shell commands | No | Yes |
|
||||
| Code execution | Sandboxed (Artifacts) | Yes (full shell) |
|
||||
| Reads / writes files | Sandboxed (Artifacts) | Yes (full filesystem) |
|
||||
| Schedules background jobs | No | Yes |
|
||||
| Web UI | Yes | Yes |
|
||||
| Messaging apps | No | Yes |
|
||||
| Self-hosted | No | Yes |
|
||||
| Provider-agnostic | No | Yes |
|
||||
| Open source | No | Yes |
|
||||
ChatGPT has Agent Mode (launched July 17, 2025), Scheduled Tasks (January 2025, recurring
|
||||
automated prompts), a computer-using agent, Projects, 50+ connectors including Gmail, GitHub,
|
||||
and Google Drive, dual-mode memory (auto + manual), and ChatGPT Pulse for Pro users (daily
|
||||
research briefings). It is not a passive Q&A interface.
|
||||
|
||||
Where Claude.ai and ChatGPT differ from Hermes: neither is self-hosted, neither is
|
||||
provider-agnostic, and neither gives you execution on your own hardware. Connectors and
|
||||
scheduling exist, but they run on Anthropic's or OpenAI's infrastructure. Your memory, session
|
||||
history, and agent execution live on their servers, not yours. For many use cases that's fine
|
||||
— they are capable and well-supported. For privacy-conscious users, regulated environments, or
|
||||
workflows that require persistent server-side execution on controlled hardware, it's a
|
||||
disqualifying constraint.
|
||||
|
||||
| | Claude.ai | ChatGPT | Hermes |
|
||||
|---|---|---|---|
|
||||
| Memory across conversations | Yes (auto-generated from history) | Yes (dual-mode: auto + manual) | Yes (deep, automatic) |
|
||||
| Scheduled tasks | Yes (Cowork: hourly/daily/weekly) | Yes (since Jan 2025) | Yes (any cron, self-hosted) |
|
||||
| Service connectors / messaging | Yes (50+ via Cowork) | Yes (50+ connectors) | Yes (many platforms, direct) |
|
||||
| Runs shell commands | Sandboxed (Cowork VM) | Sandboxed | Yes (full shell) |
|
||||
| Code execution | Sandboxed | Sandboxed | Yes (full shell) |
|
||||
| Reads / writes files | Sandboxed | Sandboxed | Yes (full filesystem) |
|
||||
| Web UI | Yes (Anthropic-hosted) | Yes (OpenAI-hosted) | Yes (self-hosted) |
|
||||
| Self-hosted | No | No | Yes |
|
||||
| Provider-agnostic | No | No | Yes |
|
||||
| Open source | No | No | Yes |
|
||||
| Self-hosted autonomous execution | No | No | Yes |
|
||||
| Memory inspectability | Limited | Limited | Yes (markdown files) |
|
||||
|
||||
---
|
||||
|
||||
## The Compounding Advantage
|
||||
## The compounding advantage
|
||||
|
||||
What matters most about Hermes is that it improves over time. That is the point.
|
||||
What distinguishes Hermes from most of the tools above is that it gets meaningfully better at
|
||||
your specific workflow over time without manual configuration.
|
||||
|
||||
Every time Hermes encounters a new environment, it saves facts to memory. Every time it solves
|
||||
a problem a new way, it saves the approach as a skill. Every time you correct it, it updates its
|
||||
profile of you. Every session, every scheduled job, every tool call, the agent gets more
|
||||
calibrated to you and your workflow.
|
||||
profile of you. Every session, every scheduled job, every tool call adds to a body of knowledge
|
||||
that is specific to you, stored on your hardware, and available to every future interaction.
|
||||
|
||||
A Claude Code session on day one and day one hundred are identical. A Hermes agent on day one
|
||||
and day one hundred is smarter about you -- it knows your stack, your conventions, your
|
||||
preferences, and the solutions that have worked before.
|
||||
A Claude Code session on day one and day one hundred are identical — it starts fresh. A Hermes
|
||||
agent on day one and day one hundred knows your stack, your conventions, your preferences, and
|
||||
the solutions that have worked before. That's the actual compounding.
|
||||
|
||||
---
|
||||
|
||||
## Who Hermes Is For
|
||||
## Who Hermes is for
|
||||
|
||||
**Solo developers and power users** who don't want to re-explain their stack every session and
|
||||
want an AI that actually knows their environment.
|
||||
Solo developers and power users who don't want to re-explain their stack every session and want
|
||||
an AI that actually knows their environment.
|
||||
|
||||
**Teams on a shared server** where multiple people want Claude-quality AI access without each
|
||||
paying for a separate subscription or running local tooling.
|
||||
Teams on a shared server where multiple people want capable AI access without each paying for
|
||||
a separate subscription or running separate local tooling.
|
||||
|
||||
**Automation-heavy workflows** where you want an AI running tasks on a schedule, delivering
|
||||
results to your phone, without babysitting it.
|
||||
Automation-heavy workflows where you want an AI running tasks on a schedule, delivering results
|
||||
to your phone, without babysitting it.
|
||||
|
||||
**Privacy-conscious users** who want their conversations, memory, and files on their own
|
||||
hardware.
|
||||
Privacy-conscious users who want their conversations, memory, and files on their own hardware.
|
||||
|
||||
**Multi-model users** who want to switch between OpenAI, Anthropic, Google, DeepSeek, and
|
||||
others based on cost, capability, or rate limits, without rebuilding their workflow each time.
|
||||
Multi-model users who want to switch between OpenAI, Anthropic, Google, DeepSeek, and others
|
||||
based on cost, capability, or rate limits, without rebuilding their workflow each time.
|
||||
|
||||
---
|
||||
|
||||
## Scope and Limits
|
||||
## What Hermes is not
|
||||
|
||||
**Hermes lives in the terminal, browser, and messaging apps.** For in-editor autocomplete and
|
||||
inline diffs, use Cursor or Windsurf alongside it -- they do that job better.
|
||||
Hermes is not the best in-editor autocomplete tool. Cursor and Windsurf do that job better.
|
||||
Use one alongside Hermes.
|
||||
|
||||
**You run Hermes on your own server.** That means initial setup, but your data stays on your
|
||||
It is not zero-setup. You are running a server. That means initial configuration, and it means
|
||||
you're responsible for uptime, upgrades, and backups. The tradeoff is data sovereignty and
|
||||
control; that only makes sense if you actually want it.
|
||||
|
||||
It does not make weaker models magical. Memory and skills help, but the underlying model still
|
||||
determines reasoning quality. Hermes with a weak model is a well-organized weak model.
|
||||
|
||||
It still needs guardrails, approvals, and observability for high-stakes automations. Autonomous
|
||||
execution on a schedule with shell access is powerful and requires judgment about what to
|
||||
approve. Terminal commands can require confirmation before running; use that for anything
|
||||
consequential.
|
||||
|
||||
If you need the absolute lowest-friction path to a one-off answer or a quick edit, a chat
|
||||
interface or an in-editor tool is the right call. Hermes is for continuity and autonomy, not
|
||||
minimum-friction one-shots.
|
||||
|
||||
---
|
||||
|
||||
## Scope and limits
|
||||
|
||||
Hermes lives in the terminal, browser, and messaging apps. For in-editor autocomplete and inline
|
||||
diffs, use Cursor or Windsurf — they do that job better and work well alongside Hermes.
|
||||
|
||||
You run Hermes on your own server. That means initial setup, but your data stays on your
|
||||
hardware and you control the schedule, the models, and the costs.
|
||||
|
||||
**Hermes is an orchestration and memory layer.** It makes whatever model you point it at more
|
||||
useful over time. The models do the reasoning; Hermes makes sure that reasoning accumulates into
|
||||
Hermes is an orchestration and memory layer. It makes whatever model you point at it more useful
|
||||
over time. The models do the reasoning; Hermes makes sure that reasoning accumulates into
|
||||
something durable.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
## Security and control
|
||||
|
||||
| | OpenClaw | Claude Code | Codex CLI | OpenCode | Cursor | Claude.ai | Hermes |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| Persistent memory (auto) | Yes | Partial† | Partial | Partial | No | Yes (improving) | **Yes** |
|
||||
| Scheduled / background jobs | Yes | Partial‡ | Partial§ | No | No | No | **Yes (self-hosted)** |
|
||||
| Messaging app access | Yes (15+ platforms) | Partial (Telegram/Discord preview; Slack native) | No | No | No | No | **Yes (10+ platforms)** |
|
||||
| Web UI | Dashboard only | Yes (Anthropic cloud) | No | Yes | No | Yes | **Yes (self-hosted)** |
|
||||
| Skills system | Yes (marketplace) | Yes (Hooks + Plugins) | No | No | No | No | **Yes** |
|
||||
| Self-improving skills | Partial | No | No | No | No | No | **Yes** |
|
||||
| Browser / computer control | Yes (Chrome CDP) | No | No | No | No | No | Via shell |
|
||||
| Python / ML ecosystem | No (Node.js) | No | No | No | No | No | **Yes** |
|
||||
| In-editor autocomplete | No | No | No | No | Yes | No | No |
|
||||
| Orchestrates other agents | No | No | No | No | No | No | **Yes** |
|
||||
| Provider-agnostic | Yes | No (Claude only) | Yes | Yes | Partial | No | **Yes** |
|
||||
| Self-hosted | Yes | No | Yes | Yes | No | No | **Yes** |
|
||||
| Open source | Yes (MIT) | No | Yes | Yes | No | No | **Yes** |
|
||||
| Always-on / autonomous | Yes | No | No | No | No | No | **Yes** |
|
||||
Memory is stored locally on your server as readable, editable files: user profile, agent memory,
|
||||
and skills are all markdown. Session history is in SQLite on your machine. You can inspect,
|
||||
edit, or delete any of it directly.
|
||||
|
||||
† Claude Code has CLAUDE.md / MEMORY.md project context and rolling auto-memory, but not full automatic cross-session recall
|
||||
‡ Claude Code scheduling: cloud-managed (Anthropic infrastructure) or desktop-app only; no self-hosted cron
|
||||
§ Codex scheduling: desktop app Automations only; CLI has no native scheduling
|
||||
If you want external memory providers, eight are supported: Mem0, Honcho, Hindsight, RetainDB,
|
||||
ByteRover, Supermemory, Holographic, and others. These are optional and configurable.
|
||||
|
||||
Execution runs in configurable backends: local shell, Docker, SSH, Daytona, Singularity, or
|
||||
Modal. You choose what execution environment Hermes operates in and what it can reach.
|
||||
|
||||
Terminal commands can require confirmation before running. For any automation that touches
|
||||
production systems or makes external calls, enable approval controls.
|
||||
|
||||
Secrets stay on your hardware. Hermes does not phone home; it calls whatever model APIs you
|
||||
configure directly.
|
||||
|
||||
Multiple profiles give isolation between users or projects. A shared server can have separate
|
||||
profiles with separate memory, separate skills, and separate history.
|
||||
|
||||
---
|
||||
|
||||
## Quick reference
|
||||
|
||||
| | OpenClaw | Claude Code | Codex | OpenCode | Cursor | Copilot | Claude.ai | ChatGPT | Hermes |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| Persistent memory (auto) | Yes | Partial† | Partial | Partial | Yes (per-project) | Yes (repo-scoped‡) | Yes | Yes | Yes |
|
||||
| Scheduled / background jobs | Yes | Partial§ | Partial¶ | No | Yes (Automations) | Via Coding Agent | Yes (Cowork) | Yes | Yes (self-hosted) |
|
||||
| Messaging / multi-surface | Yes (24+ platforms) | Partial (preview) | No | Community only | Yes (Slack/web/mobile) | Via CLI/fleet | Yes (50+ connectors) | Yes (50+ connectors) | Yes (many platforms) |
|
||||
| Web UI | Chat UI + control dashboard | Anthropic-hosted | No | Yes | Yes + mobile | github.com | Yes (Claude Desktop) | Yes | Yes (self-hosted) |
|
||||
| Skills system | Yes (ClawHub marketplace) | Yes (Hooks + Plugins) | Partial (Skills) | Community plugins | Yes (marketplace) | No | No | No | Yes (auto-generated) |
|
||||
| Self-improving skills | Partial | No | No | No | No | No | No | No | Yes |
|
||||
| Browser / computer control | Yes (Chrome CDP) | No | No | No | No | No | No | Yes (CUA) | Via shell |
|
||||
| In-editor autocomplete | No | No | Via extension | No | Excellent | Excellent | No | No | No |
|
||||
| Orchestrates other agents | No | No | No | No | No | No | No | No | Yes |
|
||||
| Provider-agnostic | Yes | No (Claude only) | Yes | Yes | Partial | No | No | No | Yes |
|
||||
| Self-hosted | Yes | No | Yes (CLI) | Yes | No | No | No | No | Yes |
|
||||
| Self-hosted autonomous execution | Yes | No | No | No | No | No | No | No | Yes |
|
||||
| Background/cloud agent mode | Yes | Yes (cloud) | Yes (Codex Cloud) | No | Yes (cloud VMs) | Yes (Coding Agent) | Yes (Cowork VM) | Yes (Agent Mode) | Yes (self-hosted) |
|
||||
| Memory inspectability | Limited | Partial | Partial | Partial | Partial | Limited | Limited | Limited | Yes (markdown files) |
|
||||
| Open source | Yes (MIT) | No | Yes (Apache 2.0) | Yes | No | No | No | No | Yes |
|
||||
| Always-on autonomous execution | Yes | No | No | No | No | No | No | No | Yes |
|
||||
|
||||
† Claude Code: CLAUDE.md / MEMORY.md project context plus auto-memory since v2.1.59+; no automatic cross-project accumulation
|
||||
‡ Copilot Agentic Memory: public preview Jan 15, 2026; enabled by default Mar 4, 2026; repo-scoped, auto-expires after 28 days
|
||||
§ Claude Code scheduling: cloud-managed (Anthropic infrastructure) or desktop-app only; no self-hosted cron
|
||||
¶ Codex scheduling: desktop app Automations only; CLI has no native scheduling
|
||||
|
||||
84
README.md
84
README.md
@@ -92,29 +92,31 @@ ecosystem. See [HERMES.md](HERMES.md) for the full side-by-side.
|
||||
|
||||
## Quick start
|
||||
|
||||
First, you need to install and configure [Hermes Agent](https://hermes-agent.nousresearch.com/docs/getting-started/quickstart) on your computer or server. This includes the following steps to complete:
|
||||
|
||||
* [ ] Running the `curl` command to download and setup Hermes
|
||||
* [ ] Configure your [LLM provider](https://hermes-agent.nousresearch.com/docs/getting-started/quickstart#2-set-up-a-provider) with `hermes model`
|
||||
* [ ] Configure yout [messaging gateways](https://hermes-agent.nousresearch.com/docs/user-guide/messaging/) with `hermes gateway setup`
|
||||
* [ ] Can start chatting with hermes on command-line with `hermes`
|
||||
* [ ] Optional: [Configure your extended memory provider](https://hermes-agent.nousresearch.com/docs/user-guide/features/memory-providers)
|
||||
* [ ] Optional: [Configure your tools](https://hermes-agent.nousresearch.com/docs/user-guide/features/tools)
|
||||
|
||||
Once installed, you can now setup the web UI with:
|
||||
Run the repo bootstrap:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/nesquena/hermes-webui.git hermes-webui
|
||||
cd hermes-webui
|
||||
python3 bootstrap.py
|
||||
```
|
||||
|
||||
Or keep using the shell launcher:
|
||||
|
||||
```bash
|
||||
./start.sh
|
||||
```
|
||||
|
||||
That is it! The script will:
|
||||
The bootstrap will:
|
||||
|
||||
1. Locate your Hermes agent directory automatically.
|
||||
2. Find (or create) a Python environment with the required dependencies.
|
||||
3. Start the web server.
|
||||
4. Print the URL (and SSH tunnel command if you are on a remote machine).
|
||||
1. Detect Hermes Agent and, if missing, attempt the official installer (`curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash`).
|
||||
2. Find or create a Python environment with the WebUI dependencies.
|
||||
3. Start the web server and wait for `/health`.
|
||||
4. Open the browser unless you pass `--no-browser`.
|
||||
5. Drop you into a first-run onboarding wizard inside the WebUI.
|
||||
|
||||
> Native Windows is not supported for this bootstrap yet. Use Linux, macOS, or WSL2.
|
||||
|
||||
If provider setup is still incomplete after install, the onboarding wizard will point you to finish it with `hermes model` instead of trying to replicate the full CLI setup in-browser.
|
||||
|
||||
---
|
||||
|
||||
@@ -122,14 +124,23 @@ That is it! The script will:
|
||||
|
||||
**Pre-built images** (amd64 + arm64) are published to GHCR on every release:
|
||||
|
||||
Make sure the `HERMES_WEBUI_STATE_DIR` (by default `~/.hermes/webui-mvp`, as detailed in the `.env.example` file) folder exist with the UID/GID of the owner of the `.hermes` folder.
|
||||
The container will also mount your configured "workspace" (also from the example .env.example) as `/workspace`. adapt the location as needed.
|
||||
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/nesquena/hermes-webui:latest
|
||||
docker run -d -p 8787:8787 -v ~/.hermes:/root/.hermes ghcr.io/nesquena/hermes-webui:latest
|
||||
docker run -d \
|
||||
-e WANTED_UID=`id -u` -e WANTED_GID=`id -g` \
|
||||
-v ~/.hermes:/home/hermeswebui/.hermes -e HERMES_WEBUI_STATE_DIR=/home/hermeswebui/.hermes/webui-mvp \
|
||||
-v ~/workspace:/workspace \
|
||||
-p 8787:8787 ghcr.io/nesquena/hermes-webui:latest
|
||||
```
|
||||
|
||||
Or run with Docker Compose (recommended):
|
||||
|
||||
```bash
|
||||
# Check the docker-compose.yml and make sure to adapt as needed, at minimum WANTED_UID/WANTED_GID
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
@@ -137,7 +148,11 @@ Or build locally:
|
||||
|
||||
```bash
|
||||
docker build -t hermes-webui .
|
||||
docker run -d -p 8787:8787 -v ~/.hermes:/root/.hermes hermes-webui
|
||||
docker run -d \
|
||||
-e WANTED_UID=`id -u` -e WANTED_GID=`id -g` \
|
||||
-v ~/.hermes:/home/hermeswebui/.hermes -e HERMES_WEBUI_STATE_DIR=/home/hermeswebui/.hermes/webui-mvp \
|
||||
-v ~/workspace:/workspace \
|
||||
-p 8787:8787 hermes-webui
|
||||
```
|
||||
|
||||
Open http://localhost:8787 in your browser.
|
||||
@@ -145,15 +160,43 @@ Open http://localhost:8787 in your browser.
|
||||
To enable password protection:
|
||||
|
||||
```bash
|
||||
docker run -d -p 8787:8787 -e HERMES_WEBUI_PASSWORD=your-secret -v ~/.hermes:/root/.hermes ghcr.io/nesquena/hermes-webui:latest
|
||||
docker run -d \
|
||||
-e WANTED_UID=`id -u` -e WANTED_GID=`id -g` \
|
||||
-v ~/.hermes:/home/hermeswebui/.hermes -e HERMES_WEBUI_STATE_DIR=/home/hermeswebui/.hermes/webui-mvp \
|
||||
-v ~/workspace:/workspace \
|
||||
-p 8787:8787 -e HERMES_WEBUI_PASSWORD=your-secret ghcr.io/nesquena/hermes-webui:latest
|
||||
```
|
||||
|
||||
Session data persists in a named volume (`hermes-data`) across restarts.
|
||||
|
||||
> **Note:** By default, Docker Compose binds to `127.0.0.1` (localhost only).
|
||||
> To expose on a network, change the port to `"8787:8787"` in `docker-compose.yml`
|
||||
> and set `HERMES_WEBUI_PASSWORD` to enable authentication.
|
||||
|
||||
### Two-container setup (Agent + WebUI)
|
||||
|
||||
If you run the Hermes Agent in its own Docker container and want the WebUI
|
||||
in a separate container:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.two-container.yml up -d
|
||||
```
|
||||
|
||||
This starts both containers with shared volumes:
|
||||
|
||||
- **`hermes-home`** — shared `~/.hermes` for config, sessions, skills, memory
|
||||
- **`hermes-agent-src`** — the agent's source code, mounted into the WebUI
|
||||
container so it can install the agent's Python dependencies at startup
|
||||
|
||||
The WebUI's init script automatically installs hermes-agent and all its
|
||||
dependencies (openai, anthropic, etc.) into its own Python environment on
|
||||
first boot. Subsequent restarts reuse the installed packages.
|
||||
|
||||
> **How it works:** The WebUI imports hermes-agent's Python modules directly
|
||||
> (not via HTTP). The shared volume makes the agent source available, and
|
||||
> the init script runs `uv pip install` to set up the dependencies. Both
|
||||
> containers share the same `~/.hermes` directory for config and state.
|
||||
|
||||
See `docker-compose.two-container.yml` for the full configuration.
|
||||
|
||||
---
|
||||
|
||||
## What start.sh discovers automatically
|
||||
@@ -358,6 +401,7 @@ across 23 test files.
|
||||
- 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
|
||||
- Optional custom endpoint fields on create -- Base URL and API key written into the profile's `config.yaml` at creation time, so Ollama, LMStudio, and other local endpoints can be configured without editing files manually
|
||||
- Seamless switching -- no server restart; reloads config, skills, memory, cron, models
|
||||
- Per-session profile tracking (records which profile was active at creation)
|
||||
|
||||
|
||||
15
ROADMAP.md
15
ROADMAP.md
@@ -3,8 +3,9 @@
|
||||
> Goal: Full 1:1 parity with the Hermes CLI experience via a clean dark web UI.
|
||||
> Everything you can do from the CLI terminal, you can do from this UI.
|
||||
>
|
||||
> Last updated: v0.39.0 (April 8, 2026)
|
||||
> Tests: 499 total (499 passing, 0 failures)
|
||||
> Last updated: v0.49.1 (April 12, 2026) — 700 tests, 700 passing
|
||||
> Onboarding MVP now writes real Hermes provider config from the Web UI for OpenRouter, Anthropic, OpenAI, and custom OpenAI-compatible endpoints.
|
||||
> Tests: 700 total (700 passing, 0 failures)
|
||||
> Source: <repo>/
|
||||
|
||||
---
|
||||
@@ -40,6 +41,16 @@
|
||||
| Sprint 21 | Mobile responsive + Docker | Hamburger sidebar, bottom nav, files slide-over, Docker support (#21, #7) | 415 |
|
||||
| Sprint 22 | Multi-profile support | Profile picker, management panel, seamless switching, per-session tracking (#28) | 415 |
|
||||
| Sprint 23 | Agentic transparency | Token/cost display, subagent cards, skill picker in cron, skill linked files, workspace tree persistence, timestamp fixes | 424 |
|
||||
| v0.44.0 patch | Fix batch: approval card, login CSP, update diagnostics, Lucide icons | PRs #221 #225 #226 #227 #228 | 579 |
|
||||
| v0.45.0 | Custom endpoint in new profile form | Base URL + API key fields; server-side URL validation; config.yaml merge; 9 new tests (PR #233, fixes #170) | 604 |
|
||||
| v0.46.0 | Security, Docker UID/GID, model discovery, i18n, cancel fix | Credential redaction in API responses (PR #243); Docker UID/GID matching (PR #237); custom model API key discovery (PR #238); HTML entity decode + zh/zh-Hant i18n (PR #239); cancel interrupts agent (PR #244); +20 tests | 624 |
|
||||
| v0.47.0 | Dialogs, session menu, skills command, mobile fixes, mobile QA | Shared app dialogs (#251); session ⋯ menu (#252); mobile QA suite (#254); custom provider slash routing fix (#255); Android Chrome mobile fixes (#256); /skills command (#257); +21 tests | 645 |
|
||||
| v0.47.1 | Spanish locale | Full Spanish (es) locale, 175 keys, key-parity tests (#275 @gabogabucho); +3 tests | 648 |
|
||||
| v0.48.0 | Gateway session sync | Real-time Telegram/Discord/Slack sessions in sidebar via SSE + DB polling (#274 @bergeouss); +10 tests | 658 |
|
||||
| v0.48.1 | Table inline formatting | `inlineMd()` in table cells — **bold**, *italic*, `code`, links render correctly (PR #278); 0 new tests | 658 |
|
||||
| v0.48.2 | Provider mismatch warning | Toast warning + auth_mismatch error type for provider/model mismatches (#283, fixes #266); +21 tests | 679 |
|
||||
| v0.49.1 | Docker docs + mobile Profiles button | Two-container Docker compose (#291/#288); Profiles button in mobile bottom nav with mobileSwitchPanel, data-panel, correct SVG size and position (#297/#265 @gabogabucho); +3 tests | 700 |
|
||||
| v0.49.0 | First-run onboarding wizard + self-update hardening | One-shot bootstrap + guided setup wizard; provider config persisted to config.yaml + .env; OpenRouter/Anthropic/OpenAI/Custom; wizard hidden after completion (#285); self-update stderr/split-ref/conflict fixes (#287); skip flaky redaction test (#289); +18 tests | 697 |
|
||||
| v0.32 | Auto-compaction handling | Compression detection, /compact command, real context window indicator | 424 |
|
||||
| v0.33 | /insights sync | Opt-in state.db sync so `hermes /insights` includes WebUI sessions | 424 |
|
||||
| v0.34 | Sprint 26 — Pluggable themes | Dark, Light, Slate, Solarized, Monokai, Nord; settings unsaved-changes guard; /theme command | 433 |
|
||||
|
||||
@@ -1163,8 +1163,8 @@ New test cases in `tests/test_sprint26.py`:
|
||||
|
||||
---
|
||||
|
||||
*Last updated: April 8, 2026*
|
||||
*Current version: v0.39.0 | 499 tests*
|
||||
*Last updated: April 12, 2026*
|
||||
*Current version: v0.49.1 | 700 tests*
|
||||
*Next sprint: Sprint 24 (Web Polish + Bug Fix Pass)*
|
||||
*Horizon sprint: Sprint 25 (macOS Desktop Application)*
|
||||
*Docs sweep policy: update markdown proactively during PR reviews and after significant releases*
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
> Prerequisites: SSH tunnel is active on port 8786. Open http://localhost:8786 in browser.
|
||||
> Server health check: curl http://127.0.0.1:8786/health should return {"status":"ok"}.
|
||||
>
|
||||
> Automated tests: 547 total (547 passing, 0 known isolation failures)
|
||||
> Automated tests: 700 total (700 passing, 0 skipped, 0 known failures). Includes onboarding coverage for bootstrap/static wizard presence, real provider config persistence (`config.yaml` + `.env`), and the `/api/onboarding/*` backend.
|
||||
> Run: `pytest tests/ -v --timeout=60`
|
||||
|
||||
---
|
||||
@@ -1708,8 +1708,8 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
|
||||
---
|
||||
|
||||
*Last updated: Sprint 26 / v0.36, April 5, 2026*
|
||||
*Total automated tests: 440 (440 passing, 0 failures)*
|
||||
*Last updated: v0.47.0, April 11, 2026*
|
||||
*Total automated tests: 645 (645 passing, 0 failures)*
|
||||
*Regression gate: tests/test_regressions.py*
|
||||
*Run: pytest tests/ -v --timeout=60*
|
||||
*Source: <repo>/*
|
||||
|
||||
833
api/config.py
833
api/config.py
File diff suppressed because it is too large
Load Diff
225
api/gateway_watcher.py
Normal file
225
api/gateway_watcher.py
Normal file
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
Hermes Web UI -- Gateway session watcher.
|
||||
|
||||
Background daemon thread that polls state.db every 5 seconds for changes
|
||||
to gateway sessions (telegram, discord, slack, etc.). When changes are
|
||||
detected, it pushes notifications to all subscribed SSE clients.
|
||||
|
||||
This enables real-time session list updates in the sidebar without
|
||||
requiring any changes to hermes-agent.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from api.config import HOME
|
||||
|
||||
|
||||
# ── State hash tracking ─────────────────────────────────────────────────────
|
||||
|
||||
def _snapshot_hash(sessions: list) -> str:
|
||||
"""Create a lightweight hash of session IDs and timestamps for change detection."""
|
||||
key = '|'.join(
|
||||
f"{s['session_id']}:{s.get('updated_at', 0)}:{s.get('message_count', 0)}"
|
||||
for s in sorted(sessions, key=lambda x: x['session_id'])
|
||||
)
|
||||
return hashlib.md5(key.encode()).hexdigest()
|
||||
|
||||
|
||||
# ── DB resolution (shared pattern with state_sync.py) ──────────────────────
|
||||
|
||||
def _get_state_db_path() -> Path:
|
||||
"""Resolve state.db path for the active profile."""
|
||||
try:
|
||||
from api.profiles import get_active_hermes_home
|
||||
hermes_home = Path(get_active_hermes_home()).expanduser().resolve()
|
||||
except Exception:
|
||||
hermes_home = Path(os.getenv('HERMES_HOME', str(HOME / '.hermes'))).expanduser().resolve()
|
||||
return hermes_home / 'state.db'
|
||||
|
||||
|
||||
def _get_agent_sessions_from_db() -> list:
|
||||
"""Read all non-webui sessions from state.db.
|
||||
Returns list of session dicts, or empty list on any error.
|
||||
"""
|
||||
db_path = _get_state_db_path()
|
||||
if not db_path.exists():
|
||||
return []
|
||||
|
||||
try:
|
||||
with sqlite3.connect(str(db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
SELECT s.id, s.title, s.model, s.message_count,
|
||||
s.started_at, s.source,
|
||||
MAX(m.timestamp) AS last_activity
|
||||
FROM sessions s
|
||||
LEFT JOIN messages m ON m.session_id = s.id
|
||||
WHERE s.source IS NOT NULL AND s.source != 'webui'
|
||||
GROUP BY s.id
|
||||
ORDER BY COALESCE(MAX(m.timestamp), s.started_at) DESC
|
||||
LIMIT 200
|
||||
""")
|
||||
sessions = []
|
||||
for row in cur.fetchall():
|
||||
sessions.append({
|
||||
'session_id': row['id'],
|
||||
'title': row['title'] or 'Agent Session',
|
||||
'model': row['model'] or 'unknown',
|
||||
'message_count': row['message_count'] or 0,
|
||||
'created_at': row['started_at'],
|
||||
'updated_at': row['last_activity'] or row['started_at'],
|
||||
'source': row['source'] or 'cli',
|
||||
})
|
||||
return sessions
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
# ── GatewayWatcher ──────────────────────────────────────────────────────────
|
||||
|
||||
class GatewayWatcher:
|
||||
"""Background thread that polls state.db for agent session changes.
|
||||
|
||||
Usage:
|
||||
watcher = GatewayWatcher()
|
||||
watcher.start()
|
||||
q = watcher.subscribe()
|
||||
# ... receive change events via q.get() ...
|
||||
watcher.unsubscribe(q)
|
||||
watcher.stop()
|
||||
"""
|
||||
|
||||
POLL_INTERVAL = 5 # seconds between polls
|
||||
SUBSCRIBER_TIMEOUT = 30 # seconds before sending keepalive comment
|
||||
|
||||
def __init__(self):
|
||||
self._subscribers: list[queue.Queue] = []
|
||||
self._sub_lock = threading.Lock()
|
||||
self._stop_event = threading.Event()
|
||||
self._thread: threading.Thread | None = None
|
||||
self._last_hash: str = ''
|
||||
self._last_sessions: list = []
|
||||
|
||||
def start(self):
|
||||
"""Start the watcher daemon thread."""
|
||||
if self._thread and self._thread.is_alive():
|
||||
return
|
||||
self._stop_event.clear()
|
||||
self._thread = threading.Thread(target=self._poll_loop, daemon=True, name='gateway-watcher')
|
||||
self._thread.start()
|
||||
|
||||
def stop(self):
|
||||
"""Stop the watcher thread."""
|
||||
self._stop_event.set()
|
||||
# Wake up any subscribers
|
||||
with self._sub_lock:
|
||||
for q in self._subscribers:
|
||||
try:
|
||||
q.put(None) # sentinel
|
||||
except Exception:
|
||||
pass
|
||||
if self._thread:
|
||||
self._thread.join(timeout=3)
|
||||
self._thread = None
|
||||
|
||||
def subscribe(self) -> queue.Queue:
|
||||
"""Subscribe to change events. Returns a queue.Queue.
|
||||
Events are dicts: {'type': 'sessions_changed', 'sessions': [...]}
|
||||
A None sentinel means the watcher is stopping.
|
||||
"""
|
||||
q = queue.Queue(maxsize=10)
|
||||
with self._sub_lock:
|
||||
self._subscribers.append(q)
|
||||
return q
|
||||
|
||||
def unsubscribe(self, q: queue.Queue):
|
||||
"""Remove a subscriber queue."""
|
||||
with self._sub_lock:
|
||||
try:
|
||||
self._subscribers.remove(q)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def _notify_subscribers(self, sessions: list):
|
||||
"""Push change event to all subscribers."""
|
||||
event = {
|
||||
'type': 'sessions_changed',
|
||||
'sessions': sessions,
|
||||
}
|
||||
with self._sub_lock:
|
||||
dead = []
|
||||
for q in self._subscribers:
|
||||
try:
|
||||
q.put_nowait(event)
|
||||
except queue.Full:
|
||||
dead.append(q) # remove slow consumers
|
||||
except Exception:
|
||||
dead.append(q)
|
||||
for q in dead:
|
||||
try:
|
||||
self._subscribers.remove(q)
|
||||
except ValueError:
|
||||
pass
|
||||
# Send a None sentinel so the SSE handler unblocks, closes,
|
||||
# and lets the browser's EventSource auto-reconnect.
|
||||
try:
|
||||
q.put_nowait(None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _poll_loop(self):
|
||||
"""Main polling loop. Runs in a daemon thread."""
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
sessions = _get_agent_sessions_from_db()
|
||||
current_hash = _snapshot_hash(sessions)
|
||||
|
||||
if current_hash != self._last_hash:
|
||||
self._last_hash = current_hash
|
||||
self._last_sessions = sessions
|
||||
self._notify_subscribers(sessions)
|
||||
except Exception:
|
||||
pass # never crash the watcher
|
||||
|
||||
# Sleep in small increments so we can stop promptly
|
||||
for _ in range(self.POLL_INTERVAL * 10):
|
||||
if self._stop_event.is_set():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
# ── Module-level singleton ─────────────────────────────────────────────────
|
||||
|
||||
_watcher: GatewayWatcher | None = None
|
||||
_watcher_lock = threading.Lock()
|
||||
|
||||
|
||||
def start_watcher():
|
||||
"""Start the global gateway watcher (idempotent)."""
|
||||
global _watcher
|
||||
with _watcher_lock:
|
||||
if _watcher is None:
|
||||
_watcher = GatewayWatcher()
|
||||
_watcher.start()
|
||||
|
||||
|
||||
def stop_watcher():
|
||||
"""Stop the global gateway watcher."""
|
||||
global _watcher
|
||||
with _watcher_lock:
|
||||
if _watcher is not None:
|
||||
_watcher.stop()
|
||||
_watcher = None
|
||||
|
||||
|
||||
def get_watcher() -> GatewayWatcher | None:
|
||||
"""Get the global watcher instance (or None if not started)."""
|
||||
with _watcher_lock:
|
||||
return _watcher
|
||||
@@ -2,6 +2,7 @@
|
||||
Hermes Web UI -- HTTP helper functions.
|
||||
"""
|
||||
import json as _json
|
||||
import re as _re
|
||||
from pathlib import Path
|
||||
from api.config import IMAGE_EXTS, MD_EXTS
|
||||
|
||||
@@ -80,6 +81,88 @@ def t(handler, payload, status: int=200, content_type: str='text/plain; charset=
|
||||
MAX_BODY_BYTES = 20 * 1024 * 1024 # 20MB limit for non-upload POST bodies
|
||||
|
||||
|
||||
# ── Credential redaction ──────────────────────────────────────────────────────
|
||||
|
||||
def _build_redact_fn():
|
||||
"""Return redact_sensitive_text from hermes-agent if available, else a fallback."""
|
||||
try:
|
||||
from agent.redact import redact_sensitive_text
|
||||
return redact_sensitive_text
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Minimal fallback covering the most common credential prefixes
|
||||
_CRED_RE = _re.compile(
|
||||
r"(?<![A-Za-z0-9_-])("
|
||||
r"sk-[A-Za-z0-9_-]{10,}" # OpenAI / Anthropic / OpenRouter
|
||||
r"|ghp_[A-Za-z0-9]{10,}" # GitHub PAT (classic)
|
||||
r"|github_pat_[A-Za-z0-9_]{10,}" # GitHub PAT (fine-grained)
|
||||
r"|gho_[A-Za-z0-9]{10,}" # GitHub OAuth token
|
||||
r"|ghu_[A-Za-z0-9]{10,}" # GitHub user-to-server token
|
||||
r"|ghs_[A-Za-z0-9]{10,}" # GitHub server-to-server token
|
||||
r"|ghr_[A-Za-z0-9]{10,}" # GitHub refresh token
|
||||
r"|AKIA[A-Z0-9]{16}" # AWS Access Key ID
|
||||
r"|xox[baprs]-[A-Za-z0-9-]{10,}" # Slack tokens
|
||||
r"|hf_[A-Za-z0-9]{10,}" # HuggingFace token
|
||||
r"|SG\.[A-Za-z0-9_-]{10,}" # SendGrid API key
|
||||
r")(?![A-Za-z0-9_-])"
|
||||
)
|
||||
_AUTH_HDR_RE = _re.compile(r"(Authorization:\s*Bearer\s+)(\S+)", _re.IGNORECASE)
|
||||
_ENV_RE = _re.compile(
|
||||
r"([A-Z0-9_]{0,50}(?:API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)[A-Z0-9_]{0,50})"
|
||||
r"\s*=\s*(['\"]?)(\S+)\2"
|
||||
)
|
||||
_PRIVKEY_RE = _re.compile(
|
||||
r"-----BEGIN[A-Z ]*PRIVATE KEY-----[\s\S]*?-----END[A-Z ]*PRIVATE KEY-----"
|
||||
)
|
||||
|
||||
def _mask(token: str) -> str:
|
||||
return f"{token[:6]}...{token[-4:]}" if len(token) >= 18 else "***"
|
||||
|
||||
def _fallback_redact(text: str) -> str:
|
||||
if not isinstance(text, str) or not text:
|
||||
return text
|
||||
text = _CRED_RE.sub(lambda m: _mask(m.group(1)), text)
|
||||
text = _AUTH_HDR_RE.sub(lambda m: m.group(1) + _mask(m.group(2)), text)
|
||||
text = _ENV_RE.sub(
|
||||
lambda m: f"{m.group(1)}={m.group(2)}{_mask(m.group(3))}{m.group(2)}", text
|
||||
)
|
||||
text = _PRIVKEY_RE.sub("[REDACTED PRIVATE KEY]", text)
|
||||
return text
|
||||
|
||||
return _fallback_redact
|
||||
|
||||
|
||||
_redact_text = _build_redact_fn()
|
||||
|
||||
|
||||
def _redact_value(v):
|
||||
"""Recursively redact credentials from strings, dicts, and lists."""
|
||||
if isinstance(v, str):
|
||||
return _redact_text(v)
|
||||
if isinstance(v, dict):
|
||||
return {k: _redact_value(val) for k, val in v.items()}
|
||||
if isinstance(v, list):
|
||||
return [_redact_value(item) for item in v]
|
||||
return v
|
||||
|
||||
|
||||
def redact_session_data(session_dict: dict) -> dict:
|
||||
"""Redact credentials from message content and tool_call data before API response.
|
||||
|
||||
Applies to: messages[], tool_calls[], and title.
|
||||
The underlying session file is not modified; redaction is response-layer only.
|
||||
"""
|
||||
result = dict(session_dict)
|
||||
if isinstance(result.get('title'), str):
|
||||
result['title'] = _redact_text(result['title'])
|
||||
if 'messages' in result:
|
||||
result['messages'] = _redact_value(result['messages'])
|
||||
if 'tool_calls' in result:
|
||||
result['tool_calls'] = _redact_value(result['tool_calls'])
|
||||
return result
|
||||
|
||||
|
||||
def read_body(handler) -> dict:
|
||||
"""Read and JSON-parse a POST request body (capped at 20MB)."""
|
||||
length = int(handler.headers.get('Content-Length', 0))
|
||||
|
||||
@@ -269,6 +269,7 @@ def get_cli_sessions() -> list:
|
||||
MAX(m.timestamp) AS last_activity
|
||||
FROM sessions s
|
||||
LEFT JOIN messages m ON m.session_id = s.id
|
||||
WHERE s.source IS NOT NULL AND s.source != 'webui'
|
||||
GROUP BY s.id
|
||||
ORDER BY COALESCE(MAX(m.timestamp), s.started_at) DESC
|
||||
LIMIT 200
|
||||
@@ -280,9 +281,11 @@ def get_cli_sessions() -> list:
|
||||
# the active CLI profile so sidebar filtering works either way.
|
||||
profile = _cli_profile # CLI DB has no profile column; use active profile
|
||||
|
||||
_source = row['source'] or 'cli'
|
||||
_display_title = row['title'] or f'{_source.title()} Session'
|
||||
cli_sessions.append({
|
||||
'session_id': sid,
|
||||
'title': row['title'] or 'CLI Session',
|
||||
'title': _display_title,
|
||||
'workspace': str(get_last_workspace()),
|
||||
'model': row['model'] or 'unknown',
|
||||
'message_count': row['message_count'] or 0,
|
||||
@@ -292,7 +295,7 @@ def get_cli_sessions() -> list:
|
||||
'archived': False,
|
||||
'project_id': None,
|
||||
'profile': profile,
|
||||
'source_tag': 'cli',
|
||||
'source_tag': _source,
|
||||
'is_cli_session': True,
|
||||
})
|
||||
except Exception:
|
||||
|
||||
474
api/onboarding.py
Normal file
474
api/onboarding.py
Normal file
@@ -0,0 +1,474 @@
|
||||
"""Hermes Web UI -- first-run onboarding helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from api.auth import is_auth_enabled
|
||||
from api.config import (
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_WORKSPACE,
|
||||
_FALLBACK_MODELS,
|
||||
_HERMES_FOUND,
|
||||
_PROVIDER_DISPLAY,
|
||||
_PROVIDER_MODELS,
|
||||
_get_config_path,
|
||||
get_available_models,
|
||||
get_config,
|
||||
load_settings,
|
||||
reload_config,
|
||||
save_settings,
|
||||
verify_hermes_imports,
|
||||
)
|
||||
from api.workspace import get_last_workspace, load_workspaces
|
||||
|
||||
|
||||
_SUPPORTED_PROVIDER_SETUPS = {
|
||||
"openrouter": {
|
||||
"label": "OpenRouter",
|
||||
"env_var": "OPENROUTER_API_KEY",
|
||||
"default_model": "anthropic/claude-sonnet-4.6",
|
||||
"requires_base_url": False,
|
||||
"models": [
|
||||
{"id": model["id"], "label": model["label"]} for model in _FALLBACK_MODELS
|
||||
],
|
||||
},
|
||||
"anthropic": {
|
||||
"label": "Anthropic",
|
||||
"env_var": "ANTHROPIC_API_KEY",
|
||||
"default_model": "claude-sonnet-4.6",
|
||||
"requires_base_url": False,
|
||||
"models": list(_PROVIDER_MODELS.get("anthropic", [])),
|
||||
},
|
||||
"openai": {
|
||||
"label": "OpenAI",
|
||||
"env_var": "OPENAI_API_KEY",
|
||||
"default_model": "gpt-4o",
|
||||
"default_base_url": "https://api.openai.com/v1",
|
||||
"requires_base_url": False,
|
||||
"models": list(_PROVIDER_MODELS.get("openai", [])),
|
||||
},
|
||||
"custom": {
|
||||
"label": "Custom OpenAI-compatible",
|
||||
"env_var": "OPENAI_API_KEY",
|
||||
"default_model": "gpt-4o-mini",
|
||||
"requires_base_url": True,
|
||||
"models": [],
|
||||
},
|
||||
}
|
||||
|
||||
_UNSUPPORTED_PROVIDER_NOTE = (
|
||||
"OAuth and advanced provider flows such as Nous Portal, OpenAI Codex, and GitHub "
|
||||
"Copilot are still terminal-first. Use `hermes model` for those flows."
|
||||
)
|
||||
|
||||
|
||||
def _get_active_hermes_home() -> Path:
|
||||
try:
|
||||
from api.profiles import get_active_hermes_home
|
||||
|
||||
return get_active_hermes_home()
|
||||
except ImportError:
|
||||
return Path.home() / ".hermes"
|
||||
|
||||
|
||||
def _load_env_file(env_path: Path) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
if not env_path.exists():
|
||||
return values
|
||||
try:
|
||||
for raw in env_path.read_text(encoding="utf-8").splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip().strip('"').strip("'")
|
||||
except Exception:
|
||||
return {}
|
||||
return values
|
||||
|
||||
|
||||
def _write_env_file(env_path: Path, updates: dict[str, str]) -> None:
|
||||
current = _load_env_file(env_path)
|
||||
for key, value in updates.items():
|
||||
if value is None:
|
||||
current.pop(key, None)
|
||||
os.environ.pop(key, None)
|
||||
continue
|
||||
clean = str(value).strip()
|
||||
if not clean:
|
||||
continue
|
||||
# Reject embedded newlines/carriage returns to prevent .env injection
|
||||
if "\n" in clean or "\r" in clean:
|
||||
raise ValueError("API key must not contain newline characters.")
|
||||
current[key] = clean
|
||||
os.environ[key] = clean
|
||||
|
||||
env_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lines = [f"{key}={current[key]}" for key in sorted(current)]
|
||||
env_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
|
||||
|
||||
|
||||
def _load_yaml_config(config_path: Path) -> dict:
|
||||
try:
|
||||
import yaml as _yaml
|
||||
except ImportError:
|
||||
return {}
|
||||
|
||||
if not config_path.exists():
|
||||
return {}
|
||||
try:
|
||||
loaded = _yaml.safe_load(config_path.read_text(encoding="utf-8"))
|
||||
return loaded if isinstance(loaded, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_yaml_config(config_path: Path, config: dict) -> None:
|
||||
try:
|
||||
import yaml as _yaml
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("PyYAML is required to write Hermes config.yaml") from exc
|
||||
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
config_path.write_text(
|
||||
_yaml.safe_dump(config, sort_keys=False, allow_unicode=True),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_model_for_provider(provider: str, model: str) -> str:
|
||||
clean = (model or "").strip()
|
||||
if not clean:
|
||||
return ""
|
||||
if provider in {"anthropic", "openai"} and clean.startswith(provider + "/"):
|
||||
return clean.split("/", 1)[1]
|
||||
return clean
|
||||
|
||||
|
||||
def _normalize_base_url(base_url: str) -> str:
|
||||
return (base_url or "").strip().rstrip("/")
|
||||
|
||||
|
||||
def _extract_current_provider(cfg: dict) -> str:
|
||||
model_cfg = cfg.get("model", {})
|
||||
if isinstance(model_cfg, dict):
|
||||
provider = str(model_cfg.get("provider") or "").strip().lower()
|
||||
if provider:
|
||||
return provider
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_current_model(cfg: dict) -> str:
|
||||
model_cfg = cfg.get("model", {})
|
||||
if isinstance(model_cfg, str):
|
||||
return model_cfg.strip()
|
||||
if isinstance(model_cfg, dict):
|
||||
return str(model_cfg.get("default") or "").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_current_base_url(cfg: dict) -> str:
|
||||
model_cfg = cfg.get("model", {})
|
||||
if isinstance(model_cfg, dict):
|
||||
return _normalize_base_url(str(model_cfg.get("base_url") or ""))
|
||||
return ""
|
||||
|
||||
|
||||
def _provider_api_key_present(
|
||||
provider: str, cfg: dict, env_values: dict[str, str]
|
||||
) -> bool:
|
||||
provider = (provider or "").strip().lower()
|
||||
if not provider:
|
||||
return False
|
||||
|
||||
env_var = _SUPPORTED_PROVIDER_SETUPS.get(provider, {}).get("env_var")
|
||||
if env_var and env_values.get(env_var):
|
||||
return True
|
||||
|
||||
model_cfg = cfg.get("model", {})
|
||||
if isinstance(model_cfg, dict) and str(model_cfg.get("api_key") or "").strip():
|
||||
return True
|
||||
|
||||
providers_cfg = cfg.get("providers", {})
|
||||
if isinstance(providers_cfg, dict):
|
||||
provider_cfg = providers_cfg.get(provider, {})
|
||||
if (
|
||||
isinstance(provider_cfg, dict)
|
||||
and str(provider_cfg.get("api_key") or "").strip()
|
||||
):
|
||||
return True
|
||||
if provider == "custom":
|
||||
custom_cfg = providers_cfg.get("custom", {})
|
||||
if (
|
||||
isinstance(custom_cfg, dict)
|
||||
and str(custom_cfg.get("api_key") or "").strip()
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
|
||||
def _provider_oauth_authenticated(provider: str, hermes_home: "Path") -> bool:
|
||||
"""Return True if the provider has valid OAuth credentials.
|
||||
|
||||
Checks via hermes_cli.auth.get_auth_status() when available, then falls
|
||||
back to reading auth.json directly for the known OAuth provider IDs
|
||||
(openai-codex, copilot, copilot-acp, qwen-oauth, nous).
|
||||
|
||||
This covers users who authenticated via 'hermes auth' or 'hermes model'
|
||||
but whose provider is not in _SUPPORTED_PROVIDER_SETUPS because it does
|
||||
not use a plain API key.
|
||||
"""
|
||||
provider = (provider or "").strip().lower()
|
||||
if not provider:
|
||||
return False
|
||||
|
||||
# Fast path: ask hermes_cli directly — the authoritative source
|
||||
try:
|
||||
from hermes_cli.auth import get_auth_status as _gas
|
||||
|
||||
status = _gas(provider)
|
||||
if isinstance(status, dict) and status.get("logged_in"):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Fallback: parse auth.json ourselves for known OAuth provider IDs.
|
||||
# Covers deployments where hermes_cli is installed but the import above
|
||||
# fails for an unexpected reason (version mismatch, import cycle, etc.).
|
||||
_known_oauth_providers = {"openai-codex", "copilot", "copilot-acp", "qwen-oauth", "nous"}
|
||||
if provider not in _known_oauth_providers:
|
||||
return False
|
||||
|
||||
try:
|
||||
import json as _j
|
||||
|
||||
auth_path = hermes_home / "auth.json"
|
||||
if not auth_path.exists():
|
||||
return False
|
||||
store = _j.loads(auth_path.read_text(encoding="utf-8"))
|
||||
providers_store = store.get("providers")
|
||||
if not isinstance(providers_store, dict):
|
||||
return False
|
||||
state = providers_store.get(provider)
|
||||
if not isinstance(state, dict):
|
||||
return False
|
||||
# Any non-empty token is enough to confirm the user has credentials.
|
||||
# Token refresh happens at runtime inside the agent.
|
||||
has_token = bool(
|
||||
str(state.get("access_token") or "").strip()
|
||||
or str(state.get("api_key") or "").strip()
|
||||
or str(state.get("refresh_token") or "").strip()
|
||||
)
|
||||
return has_token
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _status_from_runtime(cfg: dict, imports_ok: bool) -> dict:
|
||||
provider = _extract_current_provider(cfg)
|
||||
model = _extract_current_model(cfg)
|
||||
base_url = _extract_current_base_url(cfg)
|
||||
env_values = _load_env_file(_get_active_hermes_home() / ".env")
|
||||
|
||||
provider_configured = bool(provider and model)
|
||||
provider_ready = False
|
||||
|
||||
if provider_configured:
|
||||
if provider == "custom":
|
||||
provider_ready = bool(
|
||||
base_url and _provider_api_key_present(provider, cfg, env_values)
|
||||
)
|
||||
elif provider in _SUPPORTED_PROVIDER_SETUPS:
|
||||
provider_ready = _provider_api_key_present(provider, cfg, env_values)
|
||||
else:
|
||||
# Unknown / OAuth provider (e.g. openai-codex, copilot, qwen-oauth).
|
||||
# These do not use a plain API key; auth lives in auth.json or a
|
||||
# credential pool managed by hermes_cli.
|
||||
provider_ready = _provider_oauth_authenticated(
|
||||
provider, _get_active_hermes_home()
|
||||
)
|
||||
|
||||
chat_ready = bool(_HERMES_FOUND and imports_ok and provider_ready)
|
||||
|
||||
if not _HERMES_FOUND or not imports_ok:
|
||||
state = "agent_unavailable"
|
||||
note = (
|
||||
"Hermes is not fully importable from the Web UI yet. Finish bootstrap or fix the "
|
||||
"agent install before provider setup will work."
|
||||
)
|
||||
elif chat_ready:
|
||||
state = "ready"
|
||||
provider_name = _PROVIDER_DISPLAY.get(
|
||||
provider, provider.title() if provider else "Hermes"
|
||||
)
|
||||
note = f"Hermes is minimally configured and ready to chat via {provider_name}."
|
||||
elif provider_configured:
|
||||
state = "provider_incomplete"
|
||||
if provider == "custom" and not base_url:
|
||||
note = (
|
||||
"Hermes has a saved provider/model selection but still needs the "
|
||||
"base URL and API key required to chat."
|
||||
)
|
||||
elif provider not in _SUPPORTED_PROVIDER_SETUPS:
|
||||
# OAuth / unsupported provider: avoid misleading "API key" wording.
|
||||
note = (
|
||||
f"Provider '{provider}' is configured but not yet authenticated. "
|
||||
"Run 'hermes auth' or 'hermes model' in a terminal to complete "
|
||||
"setup, then reload the Web UI."
|
||||
)
|
||||
else:
|
||||
note = (
|
||||
"Hermes has a saved provider/model selection but still needs the "
|
||||
"API key required to chat."
|
||||
)
|
||||
else:
|
||||
state = "needs_provider"
|
||||
note = "Hermes is installed, but you still need to choose a provider and save working credentials."
|
||||
|
||||
return {
|
||||
"provider_configured": provider_configured,
|
||||
"provider_ready": provider_ready,
|
||||
"chat_ready": chat_ready,
|
||||
"setup_state": state,
|
||||
"provider_note": note,
|
||||
"current_provider": provider or None,
|
||||
"current_model": model or None,
|
||||
"current_base_url": base_url or None,
|
||||
"env_path": str(_get_active_hermes_home() / ".env"),
|
||||
}
|
||||
|
||||
|
||||
def _build_setup_catalog(cfg: dict) -> dict:
|
||||
current_provider = _extract_current_provider(cfg) or "openrouter"
|
||||
current_model = _extract_current_model(cfg)
|
||||
current_base_url = _extract_current_base_url(cfg)
|
||||
|
||||
providers = []
|
||||
for provider_id, meta in _SUPPORTED_PROVIDER_SETUPS.items():
|
||||
providers.append(
|
||||
{
|
||||
"id": provider_id,
|
||||
"label": meta["label"],
|
||||
"env_var": meta["env_var"],
|
||||
"default_model": meta["default_model"],
|
||||
"default_base_url": meta.get("default_base_url") or "",
|
||||
"requires_base_url": bool(meta.get("requires_base_url")),
|
||||
"models": list(meta.get("models", [])),
|
||||
"quick": provider_id == "openrouter",
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"providers": providers,
|
||||
"unsupported_note": _UNSUPPORTED_PROVIDER_NOTE,
|
||||
"current": {
|
||||
"provider": current_provider,
|
||||
"model": current_model
|
||||
or _SUPPORTED_PROVIDER_SETUPS[current_provider]["default_model"],
|
||||
"base_url": current_base_url,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_onboarding_status() -> dict:
|
||||
settings = load_settings()
|
||||
cfg = get_config()
|
||||
imports_ok, missing, errors = verify_hermes_imports()
|
||||
runtime = _status_from_runtime(cfg, imports_ok)
|
||||
workspaces = load_workspaces()
|
||||
last_workspace = get_last_workspace()
|
||||
available_models = get_available_models()
|
||||
|
||||
return {
|
||||
"completed": bool(settings.get("onboarding_completed")),
|
||||
"settings": {
|
||||
"default_model": settings.get("default_model") or DEFAULT_MODEL,
|
||||
"default_workspace": settings.get("default_workspace")
|
||||
or str(DEFAULT_WORKSPACE),
|
||||
"password_enabled": is_auth_enabled(),
|
||||
"bot_name": settings.get("bot_name") or "Hermes",
|
||||
},
|
||||
"system": {
|
||||
"hermes_found": bool(_HERMES_FOUND),
|
||||
"imports_ok": bool(imports_ok),
|
||||
"missing_modules": missing,
|
||||
"import_errors": errors,
|
||||
"config_path": str(_get_config_path()),
|
||||
"config_exists": Path(_get_config_path()).exists(),
|
||||
**runtime,
|
||||
},
|
||||
"setup": _build_setup_catalog(cfg),
|
||||
"workspaces": {
|
||||
"items": workspaces,
|
||||
"last": last_workspace,
|
||||
},
|
||||
"models": available_models,
|
||||
}
|
||||
|
||||
|
||||
def apply_onboarding_setup(body: dict) -> dict:
|
||||
provider = str(body.get("provider") or "").strip().lower()
|
||||
model = str(body.get("model") or "").strip()
|
||||
api_key = str(body.get("api_key") or "").strip()
|
||||
base_url = _normalize_base_url(str(body.get("base_url") or ""))
|
||||
|
||||
if provider not in _SUPPORTED_PROVIDER_SETUPS:
|
||||
raise ValueError("Unsupported provider for WebUI onboarding.")
|
||||
if not model:
|
||||
raise ValueError("model is required")
|
||||
|
||||
provider_meta = _SUPPORTED_PROVIDER_SETUPS[provider]
|
||||
if provider_meta.get("requires_base_url"):
|
||||
if not base_url:
|
||||
raise ValueError("base_url is required for custom endpoints")
|
||||
parsed = urlparse(base_url)
|
||||
if parsed.scheme not in {"http", "https"}:
|
||||
raise ValueError("base_url must start with http:// or https://")
|
||||
|
||||
cfg = _load_yaml_config(_get_config_path())
|
||||
env_path = _get_active_hermes_home() / ".env"
|
||||
env_values = _load_env_file(env_path)
|
||||
|
||||
if not api_key and not _provider_api_key_present(provider, cfg, env_values):
|
||||
raise ValueError(f"{provider_meta['env_var']} is required")
|
||||
|
||||
model_cfg = cfg.get("model", {})
|
||||
if not isinstance(model_cfg, dict):
|
||||
model_cfg = {}
|
||||
|
||||
model_cfg["provider"] = provider
|
||||
model_cfg["default"] = _normalize_model_for_provider(provider, model)
|
||||
|
||||
if provider == "custom":
|
||||
model_cfg["base_url"] = base_url
|
||||
elif provider == "openai":
|
||||
model_cfg["base_url"] = (
|
||||
provider_meta.get("default_base_url") or "https://api.openai.com/v1"
|
||||
)
|
||||
else:
|
||||
model_cfg.pop("base_url", None)
|
||||
|
||||
cfg["model"] = model_cfg
|
||||
_save_yaml_config(_get_config_path(), cfg)
|
||||
|
||||
if api_key:
|
||||
_write_env_file(env_path, {provider_meta["env_var"]: api_key})
|
||||
|
||||
try:
|
||||
from api.profiles import _reload_dotenv
|
||||
|
||||
_reload_dotenv(_get_active_hermes_home())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
reload_config()
|
||||
return get_onboarding_status()
|
||||
|
||||
|
||||
def complete_onboarding() -> dict:
|
||||
save_settings({"onboarding_completed": True})
|
||||
return get_onboarding_status()
|
||||
@@ -294,8 +294,38 @@ def _create_profile_fallback(name: str, clone_from: str = None,
|
||||
return profile_dir
|
||||
|
||||
|
||||
def _write_endpoint_to_config(profile_dir: Path, base_url: str = None, api_key: str = None) -> None:
|
||||
"""Write custom endpoint fields into config.yaml for a profile."""
|
||||
if not base_url and not api_key:
|
||||
return
|
||||
config_path = profile_dir / 'config.yaml'
|
||||
try:
|
||||
import yaml as _yaml
|
||||
except ImportError:
|
||||
return
|
||||
cfg = {}
|
||||
if config_path.exists():
|
||||
try:
|
||||
loaded = _yaml.safe_load(config_path.read_text())
|
||||
if isinstance(loaded, dict):
|
||||
cfg = loaded
|
||||
except Exception:
|
||||
pass
|
||||
model_section = cfg.get('model', {})
|
||||
if not isinstance(model_section, dict):
|
||||
model_section = {}
|
||||
if base_url:
|
||||
model_section['base_url'] = base_url
|
||||
if api_key:
|
||||
model_section['api_key'] = api_key
|
||||
cfg['model'] = model_section
|
||||
config_path.write_text(_yaml.dump(cfg, default_flow_style=False, allow_unicode=True))
|
||||
|
||||
|
||||
def create_profile_api(name: str, clone_from: str = None,
|
||||
clone_config: bool = False) -> dict:
|
||||
clone_config: bool = False,
|
||||
base_url: str = None,
|
||||
api_key: str = None) -> 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
|
||||
@@ -315,11 +345,26 @@ def create_profile_api(name: str, clone_from: str = None,
|
||||
except ImportError:
|
||||
_create_profile_fallback(name, clone_from, clone_config)
|
||||
|
||||
# Resolve the profile directory from the profile list when possible.
|
||||
# hermes_cli and the webui runtime do not always agree on the exact root,
|
||||
# so we prefer the path returned by list_profiles_api() and fall back to the
|
||||
# standard profile location only if the profile cannot be found there yet.
|
||||
profile_path = _DEFAULT_HERMES_HOME / 'profiles' / name
|
||||
for p in list_profiles_api():
|
||||
if p['name'] == name:
|
||||
try:
|
||||
profile_path = Path(p.get('path') or profile_path)
|
||||
except Exception:
|
||||
pass
|
||||
break
|
||||
|
||||
profile_path.mkdir(parents=True, exist_ok=True)
|
||||
_write_endpoint_to_config(profile_path, base_url=base_url, api_key=api_key)
|
||||
|
||||
# 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
|
||||
|
||||
1877
api/routes.py
1877
api/routes.py
File diff suppressed because it is too large
Load Diff
@@ -1,8 +1,36 @@
|
||||
"""Hermes Web UI -- startup helpers."""
|
||||
from __future__ import annotations
|
||||
import os, subprocess, sys
|
||||
import os, stat, subprocess, sys
|
||||
from pathlib import Path
|
||||
|
||||
# Credential files that should never be world-readable
|
||||
_SENSITIVE_FILES = (
|
||||
'.env',
|
||||
'google_token.json',
|
||||
'google_client_secret.json',
|
||||
'.signing_key',
|
||||
'auth.json',
|
||||
)
|
||||
|
||||
|
||||
def fix_credential_permissions() -> None:
|
||||
"""Ensure sensitive files in HERMES_HOME are chmod 600 (owner-only)."""
|
||||
hermes_home = Path(os.environ.get('HERMES_HOME', str(Path.home() / '.hermes')))
|
||||
if not hermes_home.is_dir():
|
||||
return
|
||||
for name in _SENSITIVE_FILES:
|
||||
fpath = hermes_home / name
|
||||
if not fpath.exists():
|
||||
continue
|
||||
try:
|
||||
current = stat.S_IMODE(fpath.stat().st_mode)
|
||||
if current & 0o077: # group or other bits set
|
||||
fpath.chmod(0o600)
|
||||
print(f' [security] fixed permissions on {fpath.name} ({oct(current)} -> 0600)', flush=True)
|
||||
except OSError:
|
||||
pass # best-effort; don't abort startup
|
||||
|
||||
|
||||
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')]:
|
||||
|
||||
100
api/streaming.py
100
api/streaming.py
@@ -11,11 +11,12 @@ import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from api.config import (
|
||||
STREAMS, STREAMS_LOCK, CANCEL_FLAGS, CLI_TOOLSETS,
|
||||
STREAMS, STREAMS_LOCK, CANCEL_FLAGS, AGENT_INSTANCES, CLI_TOOLSETS,
|
||||
LOCK, SESSIONS, SESSION_DIR,
|
||||
_get_session_agent_lock, _set_thread_env, _clear_thread_env,
|
||||
resolve_model_provider,
|
||||
)
|
||||
from api.helpers import redact_session_data
|
||||
|
||||
# Global lock for os.environ writes. Per-session locks (_agent_lock) prevent
|
||||
# concurrent runs of the SAME session, but two DIFFERENT sessions can still
|
||||
@@ -28,6 +29,23 @@ try:
|
||||
from run_agent import AIAgent
|
||||
except ImportError:
|
||||
AIAgent = None
|
||||
|
||||
def _get_ai_agent():
|
||||
"""Return AIAgent class, retrying the import if the initial attempt failed.
|
||||
|
||||
auto_install_agent_deps() in server.py may install missing packages after
|
||||
this module is first imported (common in Docker with a volume-mounted agent).
|
||||
Re-attempting the import here picks up the newly installed packages without
|
||||
requiring a server restart.
|
||||
"""
|
||||
global AIAgent
|
||||
if AIAgent is None:
|
||||
try:
|
||||
from run_agent import AIAgent as _cls # noqa: PLC0415
|
||||
AIAgent = _cls
|
||||
except ImportError:
|
||||
pass
|
||||
return AIAgent
|
||||
from api.models import get_session, title_from
|
||||
from api.workspace import set_last_workspace
|
||||
|
||||
@@ -111,15 +129,15 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
# The finally block re-acquires to restore — keeping critical sections short
|
||||
# and preventing a deadlock where the restore would re-enter the same lock.
|
||||
with _ENV_LOCK:
|
||||
old_cwd = os.environ.get('TERMINAL_CWD')
|
||||
old_exec_ask = os.environ.get('HERMES_EXEC_ASK')
|
||||
old_session_key = os.environ.get('HERMES_SESSION_KEY')
|
||||
old_hermes_home = os.environ.get('HERMES_HOME')
|
||||
os.environ['TERMINAL_CWD'] = str(s.workspace)
|
||||
os.environ['HERMES_EXEC_ASK'] = '1'
|
||||
os.environ['HERMES_SESSION_KEY'] = session_id
|
||||
if _profile_home:
|
||||
os.environ['HERMES_HOME'] = _profile_home
|
||||
old_cwd = os.environ.get('TERMINAL_CWD')
|
||||
old_exec_ask = os.environ.get('HERMES_EXEC_ASK')
|
||||
old_session_key = os.environ.get('HERMES_SESSION_KEY')
|
||||
old_hermes_home = os.environ.get('HERMES_HOME')
|
||||
os.environ['TERMINAL_CWD'] = str(s.workspace)
|
||||
os.environ['HERMES_EXEC_ASK'] = '1'
|
||||
os.environ['HERMES_SESSION_KEY'] = session_id
|
||||
if _profile_home:
|
||||
os.environ['HERMES_HOME'] = _profile_home
|
||||
# Lock released — agent runs without holding it
|
||||
# Register a gateway-style notify callback so the approval system can
|
||||
# push the `approval` SSE event the moment a dangerous command is
|
||||
@@ -165,7 +183,8 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
if AIAgent is None:
|
||||
_AIAgent = _get_ai_agent()
|
||||
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)
|
||||
|
||||
@@ -206,7 +225,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
else:
|
||||
_fallback_resolved = None
|
||||
|
||||
agent = AIAgent(
|
||||
agent = _AIAgent(
|
||||
model=resolved_model,
|
||||
provider=resolved_provider,
|
||||
base_url=resolved_base_url,
|
||||
@@ -219,6 +238,20 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
stream_delta_callback=on_token,
|
||||
tool_progress_callback=on_tool,
|
||||
)
|
||||
|
||||
# Store agent instance for cancel/interrupt propagation
|
||||
with STREAMS_LOCK:
|
||||
AGENT_INSTANCES[stream_id] = agent
|
||||
# Check if cancel was requested during agent initialization
|
||||
if stream_id in CANCEL_FLAGS and CANCEL_FLAGS[stream_id].is_set():
|
||||
# Cancel arrived during agent creation - interrupt immediately
|
||||
try:
|
||||
agent.interrupt("Cancelled before start")
|
||||
except Exception:
|
||||
pass
|
||||
put('cancel', {'message': 'Cancelled by user'})
|
||||
return
|
||||
|
||||
# Prepend workspace context so the agent always knows which directory
|
||||
# to use for file operations, regardless of session age or AGENTS.md defaults.
|
||||
workspace_ctx = f"[Workspace: {s.workspace}]\n"
|
||||
@@ -404,7 +437,8 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
usage['context_length'] = getattr(_cc, 'context_length', 0) or 0
|
||||
usage['threshold_tokens'] = getattr(_cc, 'threshold_tokens', 0) or 0
|
||||
usage['last_prompt_tokens'] = getattr(_cc, 'last_prompt_tokens', 0) or 0
|
||||
put('done', {'session': s.compact() | {'messages': s.messages, 'tool_calls': tool_calls}, 'usage': usage})
|
||||
raw_session = s.compact() | {'messages': s.messages, 'tool_calls': tool_calls}
|
||||
put('done', {'session': redact_session_data(raw_session), 'usage': usage})
|
||||
finally:
|
||||
# Unregister the gateway approval callback and unblock any threads
|
||||
# still waiting on approval (e.g. stream cancelled mid-approval).
|
||||
@@ -429,12 +463,29 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
# 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__
|
||||
is_auth_error = (
|
||||
'401' in err_str
|
||||
or 'AuthenticationError' in type(e).__name__
|
||||
or 'authentication' in err_str.lower()
|
||||
or 'unauthorized' in err_str.lower()
|
||||
or 'invalid api key' in err_str.lower()
|
||||
or 'no cookie auth credentials' in err_str.lower()
|
||||
)
|
||||
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.',
|
||||
})
|
||||
elif is_auth_error:
|
||||
put('apperror', {
|
||||
'message': err_str,
|
||||
'type': 'auth_mismatch',
|
||||
'hint': (
|
||||
'The selected model may not be supported by your configured provider. '
|
||||
'Run `hermes model` in your terminal to switch providers, then restart the WebUI.'
|
||||
),
|
||||
})
|
||||
else:
|
||||
put('apperror', {'message': err_str, 'type': 'error'})
|
||||
finally:
|
||||
@@ -442,6 +493,7 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
with STREAMS_LOCK:
|
||||
STREAMS.pop(stream_id, None)
|
||||
CANCEL_FLAGS.pop(stream_id, None)
|
||||
AGENT_INSTANCES.pop(stream_id, None) # Clean up agent instance reference
|
||||
|
||||
# ============================================================
|
||||
# SECTION: HTTP Request Handler
|
||||
@@ -456,9 +508,31 @@ def cancel_stream(stream_id: str) -> bool:
|
||||
with STREAMS_LOCK:
|
||||
if stream_id not in STREAMS:
|
||||
return False
|
||||
|
||||
# Set WebUI layer cancel flag
|
||||
flag = CANCEL_FLAGS.get(stream_id)
|
||||
if flag:
|
||||
flag.set()
|
||||
|
||||
# Interrupt the AIAgent instance to stop tool execution
|
||||
agent = AGENT_INSTANCES.get(stream_id)
|
||||
if agent:
|
||||
try:
|
||||
agent.interrupt("Cancelled by user")
|
||||
except Exception as e:
|
||||
# Log but don't block the cancel flow
|
||||
import logging
|
||||
logging.getLogger(__name__).debug(
|
||||
f"Failed to interrupt agent for stream {stream_id}: {e}"
|
||||
)
|
||||
else:
|
||||
# Agent not yet stored - cancel_event flag will be checked by agent thread
|
||||
import logging
|
||||
logging.getLogger(__name__).debug(
|
||||
f"Cancel requested for stream {stream_id} before agent ready - "
|
||||
f"cancel_event flag set, will be checked on agent startup"
|
||||
)
|
||||
|
||||
# Put a cancel sentinel into the queue so the SSE handler wakes up
|
||||
q = STREAMS.get(stream_id)
|
||||
if q:
|
||||
|
||||
@@ -29,15 +29,39 @@ CACHE_TTL = 1800 # 30 minutes
|
||||
|
||||
|
||||
def _run_git(args, cwd, timeout=10):
|
||||
"""Run a git command and return (stdout, ok)."""
|
||||
"""Run a git command and return (useful output, ok).
|
||||
|
||||
On failure, returns stderr (or stdout as fallback) so callers can
|
||||
surface actionable git error messages instead of empty strings.
|
||||
"""
|
||||
try:
|
||||
r = subprocess.run(
|
||||
['git'] + args, cwd=str(cwd), capture_output=True,
|
||||
text=True, timeout=timeout,
|
||||
)
|
||||
return r.stdout.strip(), r.returncode == 0
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
|
||||
return '', False
|
||||
stdout = r.stdout.strip()
|
||||
stderr = r.stderr.strip()
|
||||
if r.returncode == 0:
|
||||
return stdout, True
|
||||
return stderr or stdout or f"git exited with status {r.returncode}", False
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
detail = (getattr(exc, 'stderr', None) or getattr(exc, 'stdout', None) or '').strip()
|
||||
return detail or f"git {' '.join(args)} timed out after {timeout}s", False
|
||||
except FileNotFoundError:
|
||||
return 'git executable not found', False
|
||||
except OSError as exc:
|
||||
return f'git failed to start: {exc}', False
|
||||
|
||||
|
||||
def _split_remote_ref(ref):
|
||||
"""Split 'origin/branch-name' into ('origin', 'branch-name').
|
||||
|
||||
Returns (None, ref) if ref contains no slash.
|
||||
"""
|
||||
if '/' not in ref:
|
||||
return None, ref
|
||||
remote, branch = ref.split('/', 1)
|
||||
return remote, branch
|
||||
|
||||
|
||||
def _detect_default_branch(path):
|
||||
@@ -148,8 +172,28 @@ def _apply_update_inner(target):
|
||||
branch = _detect_default_branch(path)
|
||||
compare_ref = f'origin/{branch}'
|
||||
|
||||
# Check for dirty working tree
|
||||
status_out, _ = _run_git(['status', '--porcelain'], path)
|
||||
# Fetch before attempting pull, so the remote ref is current.
|
||||
_, fetch_ok = _run_git(['fetch', 'origin', '--quiet'], path, timeout=15)
|
||||
if not fetch_ok:
|
||||
return {
|
||||
'ok': False,
|
||||
'message': (
|
||||
'Could not reach the remote repository. '
|
||||
'Check your internet connection and try again.'
|
||||
),
|
||||
}
|
||||
|
||||
# Check for dirty working tree (ignore untracked files — git stash
|
||||
# doesn't include them, so stashing on '??' alone leaves nothing to pop)
|
||||
status_out, status_ok = _run_git(
|
||||
['status', '--porcelain', '--untracked-files=no'], path
|
||||
)
|
||||
if not status_ok:
|
||||
return {'ok': False, 'message': f'Failed to inspect repo status: {status_out[:200]}'}
|
||||
# Fail early on unresolved merge conflicts
|
||||
if any(line[:2] in {'DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'}
|
||||
for line in status_out.splitlines()):
|
||||
return {'ok': False, 'message': 'Repository has unresolved merge conflicts'}
|
||||
stashed = False
|
||||
if status_out:
|
||||
_, ok = _run_git(['stash'], path)
|
||||
@@ -157,12 +201,44 @@ def _apply_update_inner(target):
|
||||
return {'ok': False, 'message': 'Failed to stash local changes'}
|
||||
stashed = True
|
||||
|
||||
# Pull with ff-only (no merge commits)
|
||||
pull_out, pull_ok = _run_git(['pull', '--ff-only', compare_ref], path, timeout=30)
|
||||
# Pull with ff-only (no merge commits).
|
||||
# Split tracking refs like 'origin/main' into separate remote + branch
|
||||
# arguments — git treats 'origin/main' as a repository name otherwise.
|
||||
remote, branch = _split_remote_ref(compare_ref)
|
||||
pull_args = ['pull', '--ff-only']
|
||||
if remote:
|
||||
pull_args.extend([remote, branch])
|
||||
else:
|
||||
pull_args.append(compare_ref)
|
||||
pull_out, pull_ok = _run_git(pull_args, path, timeout=30)
|
||||
if not pull_ok:
|
||||
if stashed:
|
||||
_run_git(['stash', 'pop'], path)
|
||||
return {'ok': False, 'message': f'Pull failed: {pull_out[:200]}'}
|
||||
|
||||
# Diagnose the most common failure modes and surface actionable messages.
|
||||
pull_lower = pull_out.lower()
|
||||
if 'not possible to fast-forward' in pull_lower or 'diverged' in pull_lower:
|
||||
return {
|
||||
'ok': False,
|
||||
'message': (
|
||||
f'The local {target} repo has commits that are not on the remote '
|
||||
'branch, so a fast-forward update is not possible. '
|
||||
'Run: git -C ' + str(path) + ' fetch origin && '
|
||||
'git -C ' + str(path) + ' reset --hard ' + compare_ref
|
||||
),
|
||||
'diverged': True,
|
||||
}
|
||||
if 'does not track' in pull_lower or 'no tracking information' in pull_lower:
|
||||
return {
|
||||
'ok': False,
|
||||
'message': (
|
||||
f'The local {target} branch has no upstream tracking branch configured. '
|
||||
'Run: git -C ' + str(path) + ' branch --set-upstream-to=' + compare_ref
|
||||
),
|
||||
}
|
||||
# Generic fallback — include the raw git output for debugging.
|
||||
detail = pull_out.strip()[:300] if pull_out.strip() else '(no output from git)'
|
||||
return {'ok': False, 'message': f'Pull failed: {detail}'}
|
||||
|
||||
# Pop stash if we stashed
|
||||
if stashed:
|
||||
|
||||
227
bootstrap.py
Normal file
227
bootstrap.py
Normal file
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot bootstrap launcher for Hermes Web UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import venv
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
INSTALLER_URL = "https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh"
|
||||
REPO_ROOT = Path(__file__).resolve().parent
|
||||
DEFAULT_HOST = os.getenv("HERMES_WEBUI_HOST", "127.0.0.1")
|
||||
DEFAULT_PORT = int(os.getenv("HERMES_WEBUI_PORT", "8787"))
|
||||
|
||||
|
||||
def info(msg: str) -> None:
|
||||
print(f"[bootstrap] {msg}", flush=True)
|
||||
|
||||
|
||||
def is_wsl() -> bool:
|
||||
if platform.system() != "Linux":
|
||||
return False
|
||||
release = platform.release().lower()
|
||||
return (
|
||||
"microsoft" in release or "wsl" in release or bool(os.getenv("WSL_DISTRO_NAME"))
|
||||
)
|
||||
|
||||
|
||||
def ensure_supported_platform() -> None:
|
||||
if platform.system() == "Windows" and not is_wsl():
|
||||
raise RuntimeError(
|
||||
"Native Windows is not supported for this bootstrap yet. "
|
||||
"Please run it from Linux, macOS, or inside WSL2."
|
||||
)
|
||||
|
||||
|
||||
def discover_agent_dir() -> Path | None:
|
||||
home = Path(os.getenv("HERMES_HOME", str(Path.home() / ".hermes"))).expanduser()
|
||||
candidates = [
|
||||
os.getenv("HERMES_WEBUI_AGENT_DIR", ""),
|
||||
str(home / "hermes-agent"),
|
||||
str(REPO_ROOT.parent / "hermes-agent"),
|
||||
str(Path.home() / ".hermes" / "hermes-agent"),
|
||||
str(Path.home() / "hermes-agent"),
|
||||
]
|
||||
for raw in candidates:
|
||||
if not raw:
|
||||
continue
|
||||
candidate = Path(raw).expanduser().resolve()
|
||||
if candidate.exists() and (candidate / "run_agent.py").exists():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def discover_launcher_python(agent_dir: Path | None) -> str:
|
||||
env_python = os.getenv("HERMES_WEBUI_PYTHON")
|
||||
if env_python:
|
||||
return env_python
|
||||
if agent_dir:
|
||||
for rel in ("venv/bin/python", "venv/Scripts/python.exe"):
|
||||
candidate = agent_dir / rel
|
||||
if candidate.exists():
|
||||
return str(candidate)
|
||||
for rel in (".venv/bin/python", ".venv/Scripts/python.exe"):
|
||||
candidate = REPO_ROOT / rel
|
||||
if candidate.exists():
|
||||
return str(candidate)
|
||||
return shutil.which("python3") or shutil.which("python") or sys.executable
|
||||
|
||||
|
||||
def ensure_python_has_webui_deps(python_exe: str) -> str:
|
||||
check = subprocess.run(
|
||||
[python_exe, "-c", "import yaml"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if check.returncode == 0:
|
||||
return python_exe
|
||||
|
||||
venv_dir = REPO_ROOT / ".venv"
|
||||
venv_python = venv_dir / (
|
||||
"Scripts/python.exe" if platform.system() == "Windows" else "bin/python"
|
||||
)
|
||||
if not venv_python.exists():
|
||||
info(f"Creating local virtualenv at {venv_dir}")
|
||||
venv.EnvBuilder(with_pip=True).create(venv_dir)
|
||||
|
||||
info("Installing WebUI dependencies into local virtualenv")
|
||||
subprocess.run(
|
||||
[str(venv_python), "-m", "pip", "install", "--quiet", "--upgrade", "pip"],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
str(venv_python),
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"--quiet",
|
||||
"-r",
|
||||
str(REPO_ROOT / "requirements.txt"),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
return str(venv_python)
|
||||
|
||||
|
||||
def hermes_command_exists() -> bool:
|
||||
return shutil.which("hermes") is not None
|
||||
|
||||
|
||||
def install_hermes_agent() -> None:
|
||||
info(f"Hermes Agent not found. Attempting install via {INSTALLER_URL}")
|
||||
subprocess.run(
|
||||
["/bin/bash", "-lc", f"curl -fsSL {INSTALLER_URL} | bash"], check=True
|
||||
)
|
||||
|
||||
|
||||
def wait_for_health(url: str, timeout: float = 25.0) -> bool:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as response:
|
||||
if b'"status": "ok"' in response.read():
|
||||
return True
|
||||
except Exception:
|
||||
time.sleep(0.4)
|
||||
return False
|
||||
|
||||
|
||||
def open_browser(url: str) -> None:
|
||||
try:
|
||||
webbrowser.open(url)
|
||||
except Exception as exc:
|
||||
info(f"Could not open browser automatically: {exc}")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Bootstrap Hermes Web UI onboarding.")
|
||||
parser.add_argument("port", nargs="?", type=int, default=DEFAULT_PORT)
|
||||
parser.add_argument("--host", default=DEFAULT_HOST)
|
||||
parser.add_argument(
|
||||
"--no-browser",
|
||||
action="store_true",
|
||||
help="Do not open a browser tab automatically.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-agent-install",
|
||||
action="store_true",
|
||||
help="Fail instead of attempting the official Hermes installer.",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
ensure_supported_platform()
|
||||
|
||||
agent_dir = discover_agent_dir()
|
||||
if not agent_dir and not hermes_command_exists():
|
||||
if args.skip_agent_install:
|
||||
raise RuntimeError(
|
||||
"Hermes Agent was not found and auto-install was disabled."
|
||||
)
|
||||
install_hermes_agent()
|
||||
agent_dir = discover_agent_dir()
|
||||
|
||||
python_exe = ensure_python_has_webui_deps(discover_launcher_python(agent_dir))
|
||||
state_dir = Path(
|
||||
os.getenv("HERMES_WEBUI_STATE_DIR", str(Path.home() / ".hermes" / "webui"))
|
||||
).expanduser()
|
||||
state_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_path = state_dir / f"bootstrap-{args.port}.log"
|
||||
|
||||
env = os.environ.copy()
|
||||
env["HERMES_WEBUI_HOST"] = args.host
|
||||
env["HERMES_WEBUI_PORT"] = str(args.port)
|
||||
env.setdefault("HERMES_WEBUI_STATE_DIR", str(state_dir))
|
||||
if agent_dir:
|
||||
env["HERMES_WEBUI_AGENT_DIR"] = str(agent_dir)
|
||||
|
||||
info(f"Starting Hermes Web UI on http://{args.host}:{args.port}")
|
||||
with log_path.open("ab") as log_file:
|
||||
proc = subprocess.Popen(
|
||||
[python_exe, str(REPO_ROOT / "server.py")],
|
||||
cwd=str(agent_dir or REPO_ROOT),
|
||||
env=env,
|
||||
stdout=log_file,
|
||||
stderr=subprocess.STDOUT,
|
||||
start_new_session=True,
|
||||
)
|
||||
|
||||
health_url = f"http://{args.host}:{args.port}/health"
|
||||
if not wait_for_health(health_url):
|
||||
raise RuntimeError(
|
||||
f"Web UI did not become healthy at {health_url}. "
|
||||
f"Check the log at {log_path}. Server PID: {proc.pid}"
|
||||
)
|
||||
|
||||
app_url = (
|
||||
f"http://localhost:{args.port}"
|
||||
if args.host in ("127.0.0.1", "localhost")
|
||||
else f"http://{args.host}:{args.port}"
|
||||
)
|
||||
info(f"Web UI is ready: {app_url}")
|
||||
info(f"Log file: {log_path}")
|
||||
if not args.no_browser:
|
||||
open_browser(app_url)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as exc:
|
||||
print(f"[bootstrap] ERROR: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
55
docker-compose.two-container.yml
Normal file
55
docker-compose.two-container.yml
Normal file
@@ -0,0 +1,55 @@
|
||||
# Two-container Docker Compose: Hermes Agent + Hermes WebUI
|
||||
#
|
||||
# This runs the agent and web UI in separate containers connected via
|
||||
# shared volumes. The WebUI installs the agent's Python dependencies
|
||||
# at startup from the shared agent source volume.
|
||||
#
|
||||
# Usage:
|
||||
# docker compose -f docker-compose.two-container.yml up -d
|
||||
#
|
||||
# The agent container runs the gateway (CLI, Telegram, cron, etc.).
|
||||
# The WebUI container serves the browser interface on port 8787.
|
||||
# Both share ~/.hermes for config, sessions, and state.
|
||||
|
||||
services:
|
||||
hermes-agent:
|
||||
image: nousresearch/hermes-agent:latest
|
||||
container_name: hermes-agent
|
||||
volumes:
|
||||
# Persist config, state, sessions, skills, memory across restarts
|
||||
- hermes-home:/root/.hermes
|
||||
# Expose agent source so the WebUI can install dependencies from it
|
||||
- hermes-agent-src:/opt/hermes
|
||||
environment:
|
||||
- HERMES_HOME=/root/.hermes
|
||||
restart: unless-stopped
|
||||
|
||||
hermes-webui:
|
||||
image: ghcr.io/nesquena/hermes-webui:latest
|
||||
container_name: hermes-webui
|
||||
depends_on:
|
||||
- hermes-agent
|
||||
ports:
|
||||
- "127.0.0.1:8787:8787"
|
||||
volumes:
|
||||
# Same hermes home as the agent — shares config, sessions, state
|
||||
- hermes-home:/home/hermeswebui/.hermes
|
||||
# Agent source mounted where docker_init.bash expects it.
|
||||
# At startup the init script runs:
|
||||
# uv pip install /home/hermeswebui/.hermes/hermes-agent
|
||||
# which installs the agent and all its Python dependencies.
|
||||
- hermes-agent-src:/home/hermeswebui/.hermes/hermes-agent
|
||||
environment:
|
||||
- HERMES_WEBUI_HOST=0.0.0.0
|
||||
- HERMES_WEBUI_PORT=8787
|
||||
- HERMES_WEBUI_STATE_DIR=/home/hermeswebui/.hermes/webui-mvp
|
||||
# Match your host user's UID/GID for correct file permissions
|
||||
- WANTED_UID=${UID:-1000}
|
||||
- WANTED_GID=${GID:-1000}
|
||||
# Optional: set a password for remote access
|
||||
# - HERMES_WEBUI_PASSWORD=your-secret-password
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
hermes-home:
|
||||
hermes-agent-src:
|
||||
@@ -4,19 +4,27 @@ services:
|
||||
hermes-webui:
|
||||
build: .
|
||||
ports:
|
||||
# select only one; use 127.0.0.1 version to expose to localhost only
|
||||
- "127.0.0.1:8787:8787"
|
||||
# - "8787:8787"
|
||||
volumes:
|
||||
# Persist session data, settings, and projects across restarts
|
||||
- hermes-data:/data
|
||||
# Within the containe the tool expects to find the .hermes location at /home/hermeswebui/.hermes, so we mount it there; this allows you to manage agent profiles and other features that rely on the .hermes directory from your host machine, make sure to adapt the path if your HERMES_HOME is different
|
||||
# Mount hermes home for agent features and profile management
|
||||
- ${HERMES_HOME:-${HOME}/.hermes}:/root/.hermes
|
||||
- ${HERMES_HOME:-${HOME}/.hermes}:/home/hermeswebui/.hermes
|
||||
# Your workspace directory shown on first launch (adapt if yours is different, the container will use the mounted /workspace)
|
||||
- ${HERMES_HOME:-${HOME}}/workspace:/workspace
|
||||
environment:
|
||||
# Modify the UID and GID to match your user; docker compose starts as root by default, but the container will drop privileges to the specified UID/GID
|
||||
- WANTED_UID=${UID:-1000}
|
||||
- WANTED_GID=${GID:-1000}
|
||||
# Required: bind address and port
|
||||
- HERMES_WEBUI_HOST=0.0.0.0
|
||||
- HERMES_WEBUI_PORT=8787
|
||||
- HERMES_WEBUI_STATE_DIR=/data
|
||||
# Where to store sessions, workspaces, and other state (default: ~/.hermes/webui-mvp)
|
||||
- HERMES_WEBUI_STATE_DIR=/home/hermeswebui/.hermes/webui-mvp
|
||||
# Default workspace directory shown on first launch
|
||||
# - HERMES_WEBUI_DEFAULT_WORKSPACE=/workspace
|
||||
# Optional: set a password for remote access
|
||||
# - HERMES_WEBUI_PASSWORD=your-secret-password
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
hermes-data:
|
||||
|
||||
228
docker_init.bash
Normal file
228
docker_init.bash
Normal file
@@ -0,0 +1,228 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
error_exit() {
|
||||
echo -n "!! ERROR: "
|
||||
echo $*
|
||||
echo "!! Exiting script (ID: $$)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
ok_exit() {
|
||||
echo $*
|
||||
echo "++ Exiting script (ID: $$)"
|
||||
exit 0
|
||||
}
|
||||
|
||||
## Environment variables loaded when passing environment variables from user to user
|
||||
# Ignore list: variables to ignore when loading environment variables from user to user
|
||||
export ENV_IGNORELIST="HOME PWD USER SHLVL TERM OLDPWD SHELL _ SUDO_COMMAND HOSTNAME LOGNAME MAIL SUDO_GID SUDO_UID SUDO_USER CHECK_NV_CUDNN_VERSION VIRTUAL_ENV VIRTUAL_ENV_PROMPT ENV_IGNORELIST ENV_OBFUSCATE_PART"
|
||||
# Obfuscate part: part of the key to obfuscate when loading environment variables from user to user, ex: HF_TOKEN, ...
|
||||
export ENV_OBFUSCATE_PART="TOKEN API KEY"
|
||||
|
||||
# Check for ENV_IGNORELIST and ENV_OBFUSCATE_PART
|
||||
if [ -z "${ENV_IGNORELIST+x}" ]; then error_exit "ENV_IGNORELIST not set"; fi
|
||||
if [ -z "${ENV_OBFUSCATE_PART+x}" ]; then error_exit "ENV_OBFUSCATE_PART not set"; fi
|
||||
|
||||
whoami=`whoami`
|
||||
script_dir=$(dirname $0)
|
||||
script_name=$(basename $0)
|
||||
echo ""; echo ""
|
||||
echo "======================================"
|
||||
echo "=================== Starting script (ID: $$)"
|
||||
echo "== Running ${script_name} in ${script_dir} as ${whoami}"
|
||||
script_fullname=$0
|
||||
echo " - script_fullname: ${script_fullname}"
|
||||
ignore_value="VALUE_TO_IGNORE"
|
||||
|
||||
# everyone can read our files by default
|
||||
umask 0022
|
||||
|
||||
# Write a world-writeable file (preferably inside /tmp -- ie within the container)
|
||||
write_worldtmpfile() {
|
||||
tmpfile=$1
|
||||
if [ -z "${tmpfile}" ]; then error_exit "write_worldfile: missing argument"; fi
|
||||
if [ -f $tmpfile ]; then rm -f $tmpfile; fi
|
||||
echo -n $2 > ${tmpfile}
|
||||
chmod 777 ${tmpfile}
|
||||
}
|
||||
|
||||
itdir=/tmp/hermeswebui_init
|
||||
if [ ! -d $itdir ]; then mkdir $itdir; chmod 777 $itdir; fi
|
||||
if [ ! -d $itdir ]; then error_exit "Failed to create $itdir"; fi
|
||||
|
||||
# Set user and group id
|
||||
# logic: if not set and file exists, use file value, else use default. Create file for persistence when the container is re-run
|
||||
# reasoning: needed when using docker compose as the file will exist in the stopped container, and changing the value from environment variables or configuration file must be propagated from hermeswebuitoo to hermeswebuitoo transition (those values are the only ones loaded before the environment variables dump file are loaded)
|
||||
it=$itdir/hermeswebui_user_uid
|
||||
if [ -z "${WANTED_UID+x}" ]; then
|
||||
if [ -f $it ]; then WANTED_UID=$(cat $it); fi
|
||||
fi
|
||||
WANTED_UID=${WANTED_UID:-1024}
|
||||
write_worldtmpfile $it "$WANTED_UID"
|
||||
echo "-- WANTED_UID: \"${WANTED_UID}\""
|
||||
|
||||
it=$itdir/hermeswebui_user_gid
|
||||
if [ -z "${WANTED_GID+x}" ]; then
|
||||
if [ -f $it ]; then WANTED_GID=$(cat $it); fi
|
||||
fi
|
||||
WANTED_GID=${WANTED_GID:-1024}
|
||||
write_worldtmpfile $it "$WANTED_GID"
|
||||
echo "-- WANTED_GID: \"${WANTED_GID}\""
|
||||
|
||||
echo "== Most Environment variables set"
|
||||
|
||||
# Check user id and group id
|
||||
new_gid=`id -g`
|
||||
new_uid=`id -u`
|
||||
echo "== user ($whoami)"
|
||||
echo " uid: $new_uid / WANTED_UID: $WANTED_UID"
|
||||
echo " gid: $new_gid / WANTED_GID: $WANTED_GID"
|
||||
|
||||
save_env() {
|
||||
tosave=$1
|
||||
echo "-- Saving environment variables to $tosave"
|
||||
env | sort > "$tosave"
|
||||
}
|
||||
|
||||
load_env() {
|
||||
tocheck=$1
|
||||
overwrite_if_different=$2
|
||||
ignore_list="${ENV_IGNORELIST}"
|
||||
obfuscate_part="${ENV_OBFUSCATE_PART}"
|
||||
if [ -f "$tocheck" ]; then
|
||||
echo "-- Loading environment variables from $tocheck (overwrite existing: $overwrite_if_different) (ignorelist: $ignore_list) (obfuscate: $obfuscate_part)"
|
||||
while IFS='=' read -r key value; do
|
||||
doit=false
|
||||
# checking if the key is in the ignorelist
|
||||
for i in $ignore_list; do
|
||||
if [[ "A$key" == "A$i" ]]; then doit=ignore; break; fi
|
||||
done
|
||||
if [[ "A$doit" == "Aignore" ]]; then continue; fi
|
||||
rvalue=$value
|
||||
# checking if part of the key is in the obfuscate list
|
||||
doobs=false
|
||||
for i in $obfuscate_part; do
|
||||
if [[ "A$key" == *"$i"* ]]; then doobs=obfuscate; break; fi
|
||||
done
|
||||
if [[ "A$doobs" == "Aobfuscate" ]]; then rvalue="**OBFUSCATED**"; fi
|
||||
|
||||
if [ -z "${!key}" ]; then
|
||||
echo " ++ Setting environment variable $key [$rvalue]"
|
||||
doit=true
|
||||
elif [ "A$overwrite_if_different" == "Atrue" ]; then
|
||||
cvalue="${!key}"
|
||||
if [[ "A${doobs}" == "Aobfuscate" ]]; then cvalue="**OBFUSCATED**"; fi
|
||||
if [[ "A${!key}" != "A${value}" ]]; then
|
||||
echo " @@ Overwriting environment variable $key [$cvalue] -> [$rvalue]"
|
||||
doit=true
|
||||
else
|
||||
echo " == Environment variable $key [$rvalue] already set and value is unchanged"
|
||||
fi
|
||||
fi
|
||||
if [[ "A$doit" == "Atrue" ]]; then
|
||||
export "$key=$value"
|
||||
fi
|
||||
done < "$tocheck"
|
||||
fi
|
||||
}
|
||||
|
||||
# hermeswebuitoo is a specfiic user not existing by default on ubuntu, we can check its whomai
|
||||
if [ "A${whoami}" == "Ahermeswebuitoo" ]; then
|
||||
echo "-- Running as hermeswebuitoo, will switch hermeswebui to the desired UID/GID"
|
||||
# The script is started as hermeswebuitoo -- UID/GID 1025/1025
|
||||
|
||||
# We are altering the UID/GID of the hermeswebui user to the desired ones and restarting as that user
|
||||
# using usermod for the already create hermeswebui user, knowing it is not already in use
|
||||
# per usermod manual: "You must make certain that the named user is not executing any processes when this command is being executed"
|
||||
sudo groupmod -o -g ${WANTED_GID} hermeswebui || error_exit "Failed to set GID of hermeswebui user"
|
||||
sudo usermod -o -u ${WANTED_UID} hermeswebui || error_exit "Failed to set UID of hermeswebui user"
|
||||
sudo chown -R ${WANTED_UID}:${WANTED_GID} /home/hermeswebui || error_exit "Failed to set owner of /home/hermeswebui"
|
||||
save_env /tmp/hermeswebuitoo_env.txt
|
||||
# restart the script as hermeswebui set with the correct UID/GID this time
|
||||
echo "-- Restarting as hermeswebui user with UID ${WANTED_UID} GID ${WANTED_GID}"
|
||||
sudo su hermeswebui $script_fullname || error_exit "subscript failed"
|
||||
ok_exit "Clean exit"
|
||||
fi
|
||||
|
||||
# If we are here, the script is started as another user than hermeswebuitoo
|
||||
# because the whoami value for the hermeswebui user can be any existing user, we can not check against it
|
||||
# instead we check if the UID/GID are the expected ones
|
||||
if [ "$WANTED_GID" != "$new_gid" ]; then error_exit "hermeswebui MUST be running as UID ${WANTED_UID} GID ${WANTED_GID}, current UID ${new_uid} GID ${new_gid}"; fi
|
||||
if [ "$WANTED_UID" != "$new_uid" ]; then error_exit "hermeswebui MUST be running as UID ${WANTED_UID} GID ${WANTED_GID}, current UID ${new_uid} GID ${new_gid}"; fi
|
||||
|
||||
########## 'hermeswebui' specific section below
|
||||
|
||||
# We are therefore running as hermeswebui
|
||||
echo ""; echo "== Running as hermeswebui"
|
||||
|
||||
# Load environment variables one by one if they do not exist from /tmp/hermeswebuitoo_env.txt
|
||||
it=/tmp/hermeswebuitoo_env.txt
|
||||
if [ -f $it ]; then
|
||||
echo "-- Loading not already set environment variables from $it"
|
||||
load_env $it true
|
||||
fi
|
||||
|
||||
##
|
||||
echo ""; echo "-- Making sure /app is owned by the hermeswebui user to avoid permission issues when running the server "
|
||||
sudo mkdir -p /app || error_exit "Failed to create /app directory"
|
||||
sudo chown hermeswebui:hermeswebui /app || error_exit "Failed to set owner of /app to hermeswebui user"
|
||||
sudo rsync -av --chown=hermeswebui:hermeswebui /apptoo/ /app/ || error_exit "Failed to sync /apptoo to /app with correct ownership"
|
||||
it=/app/.testfile; touch $it || error_exit "Failed to verify /app directory"
|
||||
rm -f $it || error_exit "Failed to delete test file in /app"
|
||||
|
||||
######## Environment variables (consume AFTER the load_env)
|
||||
|
||||
echo ""; echo "== Checking required environment variables for hermes-webui"
|
||||
|
||||
echo ""; echo "-- HERMES_WEBUI_VERSION: Where to store sessions, workspaces, and other state (default: ~/.hermes/webui-mvp)"
|
||||
if [ -z "${HERMES_WEBUI_STATE_DIR+x}" ]; then error_exit "HERMES_WEBUI_STATE_DIR not set"; fi;
|
||||
echo "-- HERMES_WEBUI_STATE_DIR: $HERMES_WEBUI_STATE_DIR"
|
||||
if [ ! -d "$HERMES_WEBUI_STATE_DIR" ]; then mkdir -p $HERMES_WEBUI_STATE_DIR || error_exit "Failed to create state directory at $HERMES_WEBUI_STATE_DIR"; fi
|
||||
if [ ! -d "$HERMES_WEBUI_STATE_DIR" ]; then error_exit "HERMES_WEBUI_STATE_DIR directory does not exist at $HERMES_WEBUI_STATE_DIR"; fi
|
||||
it="$HERMES_WEBUI_STATE_DIR/.testfile"; touch $it || error_exit "Failed to verify state directory at $HERMES_WEBUI_STATE_DIR"
|
||||
rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_STATE_DIR"
|
||||
|
||||
echo ""; echo "-- HERMES_WEBUI_DEFAULT_WORKSPACE: Default workspace directory shown on first launch"
|
||||
if [ -z "${HERMES_WEBUI_DEFAULT_WORKSPACE+x}" ]; then echo "HERMES_WEBUI_DEFAULT_WORKSPACE not set, setting to /workspace"; export HERMES_WEBUI_DEFAULT_WORKSPACE="/workspace"; fi;
|
||||
echo "-- HERMES_WEBUI_DEFAULT_WORKSPACE: $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
if [ ! -d "$HERMES_WEBUI_DEFAULT_WORKSPACE" ]; then mkdir -p $HERMES_WEBUI_DEFAULT_WORKSPACE || error_exit "Failed to create default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"; fi
|
||||
if [ ! -d "$HERMES_WEBUI_DEFAULT_WORKSPACE" ]; then error_exit "HERMES_WEBUI_DEFAULT_WORKSPACE directory does not exist at $HERMES_WEBUI_DEFAULT_WORKSPACE"; fi
|
||||
it="$HERMES_WEBUI_DEFAULT_WORKSPACE/.testfile"; touch $it || error_exit "Failed to verify default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
|
||||
echo ""; echo "==================="
|
||||
echo ""; echo "== Installing uv and creating a new virtual environment for hermes-webui"
|
||||
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
export PATH="/home/hermeswebui/.local/bin/:$PATH"
|
||||
export UV_PROJECT_ENVIRONMENT=venv
|
||||
|
||||
export UV_CACHE_DIR=/uv_cache
|
||||
sudo mkdir -p ${UV_CACHE_DIR} || error_exit "Failed to create /uv_cache directory"
|
||||
sudo chown hermeswebui:hermeswebui ${UV_CACHE_DIR} || error_exit "Failed to set owner of ${UV_CACHE_DIR} to hermeswebui user"
|
||||
|
||||
cd /app
|
||||
uv venv venv
|
||||
export VIRTUAL_ENV=/app/venv
|
||||
test -d /app/venv
|
||||
test -f /app/venv/bin/activate
|
||||
|
||||
echo "";echo "== Activating hermes webui's virtual environment"
|
||||
source /app/venv/bin/activate || error_exit "Failed to activate hermeswebui virtual environment"
|
||||
test -x /app/venv/bin/python3
|
||||
|
||||
echo ""; echo "== Installing hermes-webui dependencies"
|
||||
uv pip install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org
|
||||
uv pip install -U pip setuptools --trusted-host pypi.org --trusted-host files.pythonhosted.org
|
||||
test -x /app/venv/bin/pip
|
||||
|
||||
echo ""; echo "== Adding hermes-agent's pyproject.toml base dependencies to the virtual environment"
|
||||
uv pip install /home/hermeswebui/.hermes/hermes-agent --trusted-host pypi.org --trusted-host files.pythonhosted.org || error_exit "Failed to install hermes-agent's requirements"
|
||||
|
||||
echo ""; echo "== Running hermes-webui"
|
||||
cd /app; python server.py || error_exit "hermes-webui failed or exited with an error"
|
||||
|
||||
# we should never be here because the server should be running indefinitely, but if we are, we exit safely
|
||||
ok_exit "Clean exit"
|
||||
42
server.py
42
server.py
@@ -12,7 +12,7 @@ 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
|
||||
from api.startup import auto_install_agent_deps, fix_credential_permissions
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
@@ -63,6 +63,20 @@ def main() -> None:
|
||||
|
||||
print_startup_config()
|
||||
|
||||
# Fix sensitive file permissions before doing anything else
|
||||
fix_credential_permissions()
|
||||
|
||||
within_container = False
|
||||
# Check for the "/.within_container" file to determine if we're running inside a container; this file is created in the Dockerfile
|
||||
try:
|
||||
with open('/.within_container', 'r') as f:
|
||||
within_container = True
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
if within_container:
|
||||
print('[ok] Running within container.', flush=True)
|
||||
|
||||
# Security: warn if binding non-loopback without authentication
|
||||
from api.auth import is_auth_enabled
|
||||
if HOST not in ('127.0.0.1', '::1', 'localhost') and not is_auth_enabled():
|
||||
@@ -70,6 +84,12 @@ def main() -> None:
|
||||
print(f' Anyone on the network can access your filesystem and agent.', flush=True)
|
||||
print(f' Set a password via Settings or HERMES_WEBUI_PASSWORD env var.', flush=True)
|
||||
print(f' To suppress: bind to 127.0.0.1 or set a password.', flush=True)
|
||||
if within_container:
|
||||
print(f' Note: You are running within a container, must bind to 0.0.0.0 to publish the port.', flush=True)
|
||||
elif not is_auth_enabled():
|
||||
print(f' [tip] No password set. Any process on this machine can read sessions', flush=True)
|
||||
print(f' and memory via the local API. Set HERMES_WEBUI_PASSWORD to', flush=True)
|
||||
print(f' enable authentication.', flush=True)
|
||||
|
||||
ok, missing, errors = verify_hermes_imports()
|
||||
if not ok and _HERMES_FOUND:
|
||||
@@ -90,6 +110,14 @@ def main() -> None:
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
||||
DEFAULT_WORKSPACE.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Start the gateway session watcher for real-time SSE updates
|
||||
try:
|
||||
from api.gateway_watcher import start_watcher
|
||||
start_watcher()
|
||||
except Exception as e:
|
||||
print(f'[!!] WARNING: Gateway watcher failed to start: {e}', flush=True)
|
||||
|
||||
httpd = ThreadingHTTPServer((HOST, PORT), Handler)
|
||||
|
||||
# ── TLS/HTTPS setup (optional) ─────────────────────────────────────────
|
||||
@@ -108,11 +136,19 @@ def main() -> None:
|
||||
scheme = 'http'
|
||||
|
||||
print(f' Hermes Web UI listening on {scheme}://{HOST}:{PORT}', flush=True)
|
||||
if HOST == '127.0.0.1':
|
||||
if HOST == '127.0.0.1' or within_container:
|
||||
print(f' Remote access: ssh -N -L {PORT}:127.0.0.1:{PORT} <user>@<your-server>', flush=True)
|
||||
print(f' Then open: {scheme}://localhost:{PORT}', flush=True)
|
||||
print('', flush=True)
|
||||
httpd.serve_forever()
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
finally:
|
||||
# Stop the gateway watcher on shutdown
|
||||
try:
|
||||
from api.gateway_watcher import stop_watcher
|
||||
stop_watcher()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
265
start.sh
265
start.sh
@@ -1,260 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================
|
||||
# Hermes Web UI -- portable bootstrap
|
||||
# Usage: ./start.sh [port]
|
||||
#
|
||||
# One-command startup. Discovers your Hermes install, sets up
|
||||
# a local virtualenv if needed, installs dependencies, then
|
||||
# launches the server and prints everything you need to know.
|
||||
#
|
||||
# Override any step with environment variables:
|
||||
# HERMES_WEBUI_AGENT_DIR path to hermes-agent checkout
|
||||
# HERMES_WEBUI_PYTHON python executable to use
|
||||
# HERMES_WEBUI_PORT port to listen on (default: 8787)
|
||||
# HERMES_WEBUI_HOST bind address (default: 127.0.0.1)
|
||||
# HERMES_HOME override ~/.hermes base
|
||||
# HERMES_WEBUI_STATE_DIR override state directory
|
||||
# ============================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# ── Load .env if present (machine-local overrides, not committed) ─────────────
|
||||
_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
if [[ -f "${_SCRIPT_DIR}/.env" ]]; then
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source "${_SCRIPT_DIR}/.env"
|
||||
set +a
|
||||
fi
|
||||
|
||||
# ── Colours ──────────────────────────────────────────────────────────────────
|
||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
|
||||
CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'
|
||||
ok() { echo -e "${GREEN}[ok]${RESET} $*"; }
|
||||
warn() { echo -e "${YELLOW}[!!]${RESET} $*"; }
|
||||
die() { echo -e "${RED}[XX]${RESET} $*" >&2; exit 1; }
|
||||
info() { echo -e "${CYAN}[--]${RESET} $*"; }
|
||||
hdr() { echo -e "\n${BOLD}$*${RESET}"; }
|
||||
|
||||
# ── Resolve repo root (the directory this script lives in) ───────────────────
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
info "Repo root: ${REPO_ROOT}"
|
||||
|
||||
# ── Port ─────────────────────────────────────────────────────────────────────
|
||||
PORT="${1:-${HERMES_WEBUI_PORT:-8787}}"
|
||||
export HERMES_WEBUI_PORT="${PORT}"
|
||||
|
||||
# ── Python discovery ─────────────────────────────────────────────────────────
|
||||
hdr "Discovering Python..."
|
||||
|
||||
_find_python() {
|
||||
# 1. Explicit env var
|
||||
if [[ -n "${HERMES_WEBUI_PYTHON:-}" ]]; then
|
||||
echo "${HERMES_WEBUI_PYTHON}"; return
|
||||
fi
|
||||
|
||||
# 2. Agent venv (discovered below -- call again after agent dir found)
|
||||
# (handled after agent dir discovery)
|
||||
|
||||
# 3. Local .venv in repo
|
||||
if [[ -x "${REPO_ROOT}/.venv/bin/python" ]]; then
|
||||
echo "${REPO_ROOT}/.venv/bin/python"; return
|
||||
fi
|
||||
|
||||
# 4. System python3
|
||||
if command -v python3 &>/dev/null; then
|
||||
echo "$(command -v python3)"; return
|
||||
fi
|
||||
|
||||
echo ""
|
||||
}
|
||||
|
||||
PYTHON="$(_find_python)"
|
||||
|
||||
# ── Hermes agent discovery ────────────────────────────────────────────────────
|
||||
hdr "Discovering Hermes agent..."
|
||||
|
||||
HERMES_HOME="${HERMES_HOME:-${HOME}/.hermes}"
|
||||
AGENT_DIR=""
|
||||
|
||||
_find_agent() {
|
||||
local candidates=(
|
||||
"${HERMES_WEBUI_AGENT_DIR:-}"
|
||||
"${HERMES_HOME}/hermes-agent"
|
||||
"${REPO_ROOT}/../hermes-agent"
|
||||
"${HOME}/.hermes/hermes-agent"
|
||||
"${HOME}/hermes-agent"
|
||||
)
|
||||
|
||||
for d in "${candidates[@]}"; do
|
||||
[[ -z "$d" ]] && continue
|
||||
d="$(cd "${d}" 2>/dev/null && pwd || true)"
|
||||
if [[ -n "$d" && -f "${d}/run_agent.py" ]]; then
|
||||
echo "$d"; return
|
||||
fi
|
||||
done
|
||||
echo ""
|
||||
}
|
||||
|
||||
AGENT_DIR="$(_find_agent)"
|
||||
|
||||
if [[ -n "${AGENT_DIR}" ]]; then
|
||||
ok "Hermes agent: ${AGENT_DIR}"
|
||||
export HERMES_WEBUI_AGENT_DIR="${AGENT_DIR}"
|
||||
|
||||
# Now that we have agent dir, prefer its venv if we don't already have a python
|
||||
if [[ -z "${HERMES_WEBUI_PYTHON:-}" && -x "${AGENT_DIR}/venv/bin/python" ]]; then
|
||||
PYTHON="${AGENT_DIR}/venv/bin/python"
|
||||
fi
|
||||
else
|
||||
warn "Hermes agent not found. Agent features will not work."
|
||||
warn "Fix with: export HERMES_WEBUI_AGENT_DIR=/path/to/hermes-agent"
|
||||
if [[ -f "${REPO_ROOT}/.env" ]]; then
|
||||
set -a
|
||||
# shellcheck source=/dev/null
|
||||
source "${REPO_ROOT}/.env"
|
||||
set +a
|
||||
fi
|
||||
|
||||
if [[ -n "${PYTHON}" ]]; then
|
||||
ok "Python: ${PYTHON} ($(${PYTHON} --version 2>&1))"
|
||||
else
|
||||
warn "No Python found. Attempting to install..."
|
||||
if command -v apt-get &>/dev/null; then
|
||||
sudo apt-get install -y python3 python3-venv python3-pip
|
||||
elif command -v brew &>/dev/null; then
|
||||
brew install python3
|
||||
else
|
||||
die "Could not find or install Python. Please install Python 3.8+ and re-run."
|
||||
fi
|
||||
PYTHON="${HERMES_WEBUI_PYTHON:-}"
|
||||
if [[ -z "${PYTHON}" ]]; then
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
PYTHON="$(command -v python3)"
|
||||
ok "Python installed: ${PYTHON}"
|
||||
elif command -v python >/dev/null 2>&1; then
|
||||
PYTHON="$(command -v python)"
|
||||
else
|
||||
echo "[XX] Python 3 is required to run bootstrap.py" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── Minimum Python version check ─────────────────────────────────────────────
|
||||
PY_VER="$(${PYTHON} -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
|
||||
PY_MAJOR="$(echo "${PY_VER}" | cut -d. -f1)"
|
||||
PY_MINOR="$(echo "${PY_VER}" | cut -d. -f2)"
|
||||
if [[ "${PY_MAJOR}" -lt 3 || ( "${PY_MAJOR}" -eq 3 && "${PY_MINOR}" -lt 8 ) ]]; then
|
||||
die "Python 3.8+ required. Found: ${PY_VER}"
|
||||
fi
|
||||
|
||||
# ── Dependency check / local venv setup ──────────────────────────────────────
|
||||
hdr "Checking dependencies..."
|
||||
|
||||
VENV_NEEDED=false
|
||||
VENV_PATH="${REPO_ROOT}/.venv"
|
||||
|
||||
# If the chosen python is already the agent venv, its deps are already installed.
|
||||
# If it is a system python, check if we can import the webui deps, create a local
|
||||
# .venv if not.
|
||||
_check_deps() {
|
||||
"${PYTHON}" -c "import yaml" 2>/dev/null
|
||||
}
|
||||
|
||||
if ! _check_deps; then
|
||||
info "PyYAML not found in ${PYTHON}. Creating local .venv..."
|
||||
|
||||
if [[ ! -d "${VENV_PATH}" ]]; then
|
||||
"${PYTHON}" -m venv "${VENV_PATH}" || die "Failed to create virtualenv at ${VENV_PATH}"
|
||||
fi
|
||||
|
||||
VENV_PY="${VENV_PATH}/bin/python"
|
||||
"${VENV_PY}" -m pip install --quiet --upgrade pip
|
||||
|
||||
if [[ -f "${REPO_ROOT}/requirements.txt" ]]; then
|
||||
info "Installing from requirements.txt..."
|
||||
"${VENV_PY}" -m pip install --quiet -r "${REPO_ROOT}/requirements.txt"
|
||||
else
|
||||
info "Installing minimal deps (pyyaml)..."
|
||||
"${VENV_PY}" -m pip install --quiet pyyaml
|
||||
fi
|
||||
|
||||
PYTHON="${VENV_PY}"
|
||||
ok "Local venv ready: ${VENV_PATH}"
|
||||
else
|
||||
ok "Dependencies satisfied."
|
||||
fi
|
||||
|
||||
# ── Kill any stale instance on the same port ─────────────────────────────────
|
||||
hdr "Checking for existing instances..."
|
||||
|
||||
EXISTING=$(lsof -ti tcp:"${PORT}" 2>/dev/null || true)
|
||||
if [[ -n "${EXISTING}" ]]; then
|
||||
warn "Killing existing process on port ${PORT} (PID ${EXISTING})"
|
||||
kill "${EXISTING}" 2>/dev/null || true
|
||||
sleep 0.5
|
||||
fi
|
||||
|
||||
# Also kill any server.py process from this repo
|
||||
pkill -f "${REPO_ROOT}/server.py" 2>/dev/null || true
|
||||
|
||||
# ── Set up working directory for Hermes imports ───────────────────────────────
|
||||
# server.py / api/config.py inject agent dir into sys.path at import time,
|
||||
# but we also cd into the agent dir so relative imports in run_agent work.
|
||||
if [[ -n "${AGENT_DIR}" ]]; then
|
||||
WORKDIR="${AGENT_DIR}"
|
||||
else
|
||||
WORKDIR="${REPO_ROOT}"
|
||||
fi
|
||||
|
||||
# ── Launch ───────────────────────────────────────────────────────────────────
|
||||
hdr "Starting Hermes Web UI..."
|
||||
|
||||
LOG="/tmp/hermes-webui-${PORT}.log"
|
||||
export HERMES_WEBUI_HOST="${HERMES_WEBUI_HOST:-127.0.0.1}"
|
||||
export HERMES_WEBUI_STATE_DIR="${HERMES_WEBUI_STATE_DIR:-${HERMES_HOME}/webui}"
|
||||
|
||||
nohup "${PYTHON}" "${REPO_ROOT}/server.py" \
|
||||
> "${LOG}" 2>&1 &
|
||||
PID=$!
|
||||
|
||||
echo -e "\n${CYAN} PID ${PID} starting...${RESET}"
|
||||
sleep 1.5
|
||||
|
||||
# ── Health check ─────────────────────────────────────────────────────────────
|
||||
HEALTH_URL="http://${HERMES_WEBUI_HOST:-127.0.0.1}:${PORT}/health"
|
||||
MAX_WAIT=15
|
||||
ELAPSED=0
|
||||
while [[ $ELAPSED -lt $MAX_WAIT ]]; do
|
||||
if curl -sf "${HEALTH_URL}" | grep -q '"status"' 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
sleep 0.5
|
||||
ELAPSED=$((ELAPSED + 1))
|
||||
done
|
||||
|
||||
if ! curl -sf "${HEALTH_URL}" | grep -q '"status"' 2>/dev/null; then
|
||||
warn "Health check did not pass within ${MAX_WAIT}s. Check log:"
|
||||
tail -20 "${LOG}"
|
||||
echo ""
|
||||
warn "Server may still be starting. Try: curl ${HEALTH_URL}"
|
||||
else
|
||||
ok "Server is healthy."
|
||||
fi
|
||||
|
||||
# ── Print access instructions ─────────────────────────────────────────────────
|
||||
BIND_HOST="${HERMES_WEBUI_HOST:-127.0.0.1}"
|
||||
|
||||
echo ""
|
||||
echo -e "${BOLD}========================================${RESET}"
|
||||
echo -e "${GREEN} Hermes Web UI is running${RESET}"
|
||||
echo -e "${BOLD}========================================${RESET}"
|
||||
echo ""
|
||||
|
||||
if [[ "${BIND_HOST}" == "127.0.0.1" || "${BIND_HOST}" == "localhost" ]]; then
|
||||
# Server is bound to loopback -- detect if we are on a remote machine
|
||||
# by checking if $SSH_CLIENT or $SSH_TTY is set
|
||||
if [[ -n "${SSH_CLIENT:-}" || -n "${SSH_TTY:-}" ]]; then
|
||||
SERVER_IP="$(hostname -I 2>/dev/null | awk '{print $1}' || echo "<your-server-ip>")"
|
||||
echo -e " You are on a remote machine. To access from your local browser:"
|
||||
echo ""
|
||||
echo -e " ${CYAN}ssh -N -L ${PORT}:127.0.0.1:${PORT} \$(whoami)@${SERVER_IP}${RESET}"
|
||||
echo ""
|
||||
echo -e " Then open: ${BOLD}http://localhost:${PORT}${RESET}"
|
||||
else
|
||||
echo -e " Open: ${BOLD}http://localhost:${PORT}${RESET}"
|
||||
fi
|
||||
else
|
||||
echo -e " Open: ${BOLD}http://${BIND_HOST}:${PORT}${RESET}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo -e " Log: ${LOG}"
|
||||
echo -e " PID: ${PID}"
|
||||
echo ""
|
||||
exec "${PYTHON}" "${REPO_ROOT}/bootstrap.py" --no-browser "$@"
|
||||
|
||||
@@ -4,7 +4,7 @@ async function cancelStream(){
|
||||
try{
|
||||
await fetch(new URL(`/api/chat/cancel?stream_id=${encodeURIComponent(streamId)}`,location.origin).href,{credentials:'include'});
|
||||
const btn=$('btnCancel');if(btn)btn.style.display='none';
|
||||
setStatus(t('cancelling'));
|
||||
// Don't set status here - let the SSE cancel event handle UI cleanup
|
||||
}catch(e){setStatus(t('cancel_failed')+e.message);}
|
||||
}
|
||||
|
||||
@@ -21,12 +21,37 @@ function closeMobileSidebar(){
|
||||
const sidebar=document.querySelector('.sidebar');
|
||||
const overlay=$('mobileOverlay');
|
||||
if(sidebar)sidebar.classList.remove('mobile-open');
|
||||
if(overlay)overlay.classList.remove('visible');
|
||||
// only hide overlay if right panel is also closed
|
||||
const panel=document.querySelector('.rightpanel');
|
||||
if(!panel||!panel.classList.contains('mobile-open')){
|
||||
if(overlay)overlay.classList.remove('visible');
|
||||
}
|
||||
}
|
||||
function toggleMobileFiles(){
|
||||
const panel=document.querySelector('.rightpanel');
|
||||
const overlay=$('mobileOverlay');
|
||||
if(!panel)return;
|
||||
panel.classList.toggle('mobile-open');
|
||||
if(panel.classList.contains('mobile-open')){
|
||||
panel.classList.remove('mobile-open');
|
||||
// only hide overlay if left sidebar is also closed
|
||||
const sidebar=document.querySelector('.sidebar');
|
||||
if(!sidebar||!sidebar.classList.contains('mobile-open')){
|
||||
if(overlay)overlay.classList.remove('visible');
|
||||
}
|
||||
} else {
|
||||
panel.classList.add('mobile-open');
|
||||
if(overlay)overlay.classList.add('visible');
|
||||
}
|
||||
}
|
||||
function closeMobileFiles(){
|
||||
const panel=document.querySelector('.rightpanel');
|
||||
const overlay=$('mobileOverlay');
|
||||
if(panel)panel.classList.remove('mobile-open');
|
||||
// only hide overlay if left sidebar is also closed
|
||||
const sidebar=document.querySelector('.sidebar');
|
||||
if(!sidebar||!sidebar.classList.contains('mobile-open')){
|
||||
if(overlay)overlay.classList.remove('visible');
|
||||
}
|
||||
}
|
||||
function mobileSwitchPanel(name){
|
||||
// Switch the panel content view
|
||||
@@ -184,6 +209,11 @@ $('modelSelect').onchange=async()=>{
|
||||
localStorage.setItem('hermes-webui-model', selectedModel);
|
||||
await api('/api/session/update',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,workspace:S.session.workspace,model:selectedModel})});
|
||||
S.session.model=selectedModel;syncTopbar();
|
||||
// Warn if selected model belongs to a different provider than what Hermes is configured for
|
||||
if(typeof _checkProviderMismatch==='function'){
|
||||
const warn=_checkProviderMismatch(selectedModel);
|
||||
if(warn&&typeof showToast==='function') showToast(warn,4000);
|
||||
}
|
||||
};
|
||||
$('msg').addEventListener('input',()=>{
|
||||
autoResize();
|
||||
@@ -357,14 +387,17 @@ function applyBotName(){
|
||||
}
|
||||
// Pre-load workspace list so sidebar name is correct from first render
|
||||
await loadWorkspaceList();
|
||||
await loadOnboardingWizard();
|
||||
_initResizePanels();
|
||||
const saved=localStorage.getItem('hermes-webui-session');
|
||||
if(saved){
|
||||
try{await loadSession(saved);await renderSessionList();await checkInflightOnBoot(saved);return;}
|
||||
try{await loadSession(saved);await renderSessionList();if(typeof startGatewaySSE==='function')startGatewaySSE();await checkInflightOnBoot(saved);return;}
|
||||
catch(e){localStorage.removeItem('hermes-webui-session');}
|
||||
}
|
||||
// no saved session - show empty state, wait for user to hit +
|
||||
$('emptyState').style.display='';
|
||||
await renderSessionList();
|
||||
// Start real-time gateway session sync if setting is enabled
|
||||
if(typeof startGatewaySSE==='function') startGatewaySSE();
|
||||
})();
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ const COMMANDS=[
|
||||
{name:'usage', desc:t('cmd_usage'), fn:cmdUsage},
|
||||
{name:'theme', desc:t('cmd_theme'), fn:cmdTheme, arg:'name'},
|
||||
{name:'personality', desc:t('cmd_personality'), fn:cmdPersonality, arg:'name'},
|
||||
{name:'skills', desc:t('cmd_skills'), fn:cmdSkills, arg:'query'},
|
||||
];
|
||||
|
||||
function parseCommand(text){
|
||||
@@ -140,6 +141,49 @@ async function cmdTheme(args){
|
||||
showToast(t('theme_set')+themeName);
|
||||
}
|
||||
|
||||
async function cmdSkills(args){
|
||||
try{
|
||||
const data = await api('/api/skills');
|
||||
let skills = data.skills || [];
|
||||
if(args){
|
||||
const q = args.toLowerCase();
|
||||
skills = skills.filter(s =>
|
||||
(s.name||'').toLowerCase().includes(q) ||
|
||||
(s.description||'').toLowerCase().includes(q) ||
|
||||
(s.category||'').toLowerCase().includes(q)
|
||||
);
|
||||
}
|
||||
if(!skills.length){
|
||||
const msg = {role:'assistant', content: args ? `No skills matching "${args}".` : 'No skills found.'};
|
||||
S.messages.push(msg); renderMessages(); return;
|
||||
}
|
||||
// Group by category
|
||||
const byCategory = {};
|
||||
skills.forEach(s => {
|
||||
const cat = s.category || 'General';
|
||||
if(!byCategory[cat]) byCategory[cat] = [];
|
||||
byCategory[cat].push(s);
|
||||
});
|
||||
const lines = [];
|
||||
for(const [cat, items] of Object.entries(byCategory).sort()){
|
||||
lines.push(`**${cat}**`);
|
||||
items.forEach(s => {
|
||||
const desc = s.description ? ` — ${s.description.slice(0,80)}${s.description.length>80?'...':''}` : '';
|
||||
lines.push(` \`${s.name}\`${desc}`);
|
||||
});
|
||||
lines.push('');
|
||||
}
|
||||
const header = args
|
||||
? `Skills matching "${args}" (${skills.length}):\n\n`
|
||||
: `Available skills (${skills.length}):\n\n`;
|
||||
S.messages.push({role:'assistant', content: header + lines.join('\n')});
|
||||
renderMessages();
|
||||
showToast(t('type_slash'));
|
||||
}catch(e){
|
||||
showToast('Failed to load skills: '+e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdPersonality(args){
|
||||
if(!S.session){showToast(t('no_active_session'));return;}
|
||||
if(!args){
|
||||
|
||||
619
static/i18n.js
619
static/i18n.js
@@ -48,6 +48,8 @@ const LOCALES = {
|
||||
n_messages: (n) => `${n} messages`,
|
||||
model_unavailable: ' (unavailable)',
|
||||
model_unavailable_title: 'This model is no longer in your current provider list',
|
||||
provider_mismatch_warning: (m,p)=>`"${m}" may not work with your configured provider (${p}). Send anyway, or run \`hermes model\` in your terminal to switch.`,
|
||||
provider_mismatch_label: 'Provider mismatch',
|
||||
// commands.js
|
||||
cmd_help: 'List available commands',
|
||||
cmd_clear: 'Clear conversation messages',
|
||||
@@ -58,6 +60,7 @@ const LOCALES = {
|
||||
cmd_usage: 'Toggle token usage display on/off',
|
||||
cmd_theme: 'Switch theme (dark/light/slate/solarized/monokai/nord/oled)',
|
||||
cmd_personality: 'Switch agent personality',
|
||||
cmd_skills: 'List available Hermes skills',
|
||||
available_commands: 'Available commands:',
|
||||
type_slash: 'Type / to see commands',
|
||||
conversation_cleared: 'Conversation cleared',
|
||||
@@ -120,7 +123,7 @@ const LOCALES = {
|
||||
settings_label_theme: 'Theme',
|
||||
settings_label_language: 'Language',
|
||||
settings_label_token_usage: 'Show token usage',
|
||||
settings_label_cli_sessions: 'Show CLI sessions',
|
||||
settings_label_cli_sessions: 'Show agent sessions',
|
||||
settings_label_sync_insights: 'Sync to insights',
|
||||
settings_label_check_updates: 'Check for updates',
|
||||
settings_label_bot_name: 'Assistant Name',
|
||||
@@ -136,6 +139,14 @@ const LOCALES = {
|
||||
login_btn: 'Sign in',
|
||||
login_invalid_pw: 'Invalid password',
|
||||
login_conn_failed: 'Connection failed',
|
||||
dialog_confirm_title: 'Confirm action',
|
||||
dialog_prompt_title: 'Enter a value',
|
||||
dialog_confirm_btn: 'Confirm',
|
||||
discard: 'Discard',
|
||||
clear: 'Clear',
|
||||
create: 'Create',
|
||||
remove: 'Remove',
|
||||
project_name_prompt: 'Project name:',
|
||||
// Sidebar & Tabs
|
||||
tab_chat: 'Chat',
|
||||
tab_tasks: 'Tasks',
|
||||
@@ -182,6 +193,335 @@ const LOCALES = {
|
||||
suggest_files: 'What files are in this workspace?',
|
||||
suggest_schedule: "What's on my schedule today?",
|
||||
suggest_plan: 'Help me plan a small project.',
|
||||
// onboarding
|
||||
onboarding_badge: 'FIRST RUN',
|
||||
onboarding_title: 'Welcome to Hermes Web UI',
|
||||
onboarding_lead: 'A quick guided setup will verify Hermes, save a real provider configuration, choose a workspace and model, and optionally protect the app with a password.',
|
||||
onboarding_back: 'Back',
|
||||
onboarding_continue: 'Continue',
|
||||
onboarding_open: 'Open Hermes',
|
||||
onboarding_step_system_title: 'System check',
|
||||
onboarding_step_system_desc: 'Verify Hermes Agent and config visibility.',
|
||||
onboarding_step_setup_title: 'Provider setup',
|
||||
onboarding_step_setup_desc: 'Save the minimum Hermes provider config.',
|
||||
onboarding_step_workspace_title: 'Workspace + model',
|
||||
onboarding_step_workspace_desc: 'Pick defaults for new sessions and chat.',
|
||||
onboarding_step_password_title: 'Optional password',
|
||||
onboarding_step_password_desc: 'Protect the Web UI before sharing it.',
|
||||
onboarding_step_finish_title: 'Finish',
|
||||
onboarding_step_finish_desc: 'Review and enter the app.',
|
||||
onboarding_notice_system_ready: 'Hermes Agent looks reachable from the Web UI.',
|
||||
onboarding_notice_system_unavailable: 'Hermes Agent is not fully available yet. Bootstrap can install it, but provider setup may still require a terminal.',
|
||||
onboarding_check_agent: 'Hermes Agent',
|
||||
onboarding_check_agent_ready: 'Detected and importable',
|
||||
onboarding_check_agent_missing: 'Missing or partially importable',
|
||||
onboarding_check_password: 'Password',
|
||||
onboarding_check_password_enabled: 'Already enabled',
|
||||
onboarding_check_password_disabled: 'Not enabled yet',
|
||||
onboarding_check_provider: 'Provider config',
|
||||
onboarding_check_provider_ready: 'Ready to chat',
|
||||
onboarding_check_provider_partial: 'Saved but incomplete',
|
||||
onboarding_check_provider_pending: 'Needs verification',
|
||||
onboarding_config_file: 'Config file:',
|
||||
onboarding_env_file: '.env file:',
|
||||
onboarding_unknown: 'Unknown',
|
||||
onboarding_current_provider: 'Current setup:',
|
||||
onboarding_missing_imports: 'Missing imports:',
|
||||
onboarding_notice_setup_required: 'Choose a simple provider path here. Advanced OAuth flows still belong in the Hermes CLI for now.',
|
||||
onboarding_notice_setup_already_ready: 'A working Hermes provider setup is already detected. You can keep it or replace it here.',
|
||||
onboarding_notice_workspace: 'These values reuse the same settings APIs as the normal app.',
|
||||
onboarding_workspace_label: 'Workspace',
|
||||
onboarding_workspace_or_path: 'Or enter a workspace path',
|
||||
onboarding_workspace_placeholder: '/home/you/workspace',
|
||||
onboarding_provider_label: 'Setup mode',
|
||||
onboarding_quick_setup_badge: 'quick setup',
|
||||
onboarding_api_key_label: 'API key',
|
||||
onboarding_api_key_placeholder: 'Leave blank to keep an existing saved key',
|
||||
onboarding_api_key_help_prefix: 'Saved as a secret in your Hermes .env file using',
|
||||
onboarding_base_url_label: 'Base URL',
|
||||
onboarding_base_url_placeholder: 'https://your-endpoint.example/v1',
|
||||
onboarding_base_url_help: 'Use this for OpenAI-compatible routers, self-hosted servers, LiteLLM, Ollama, LM Studio, vLLM, or similar endpoints.',
|
||||
onboarding_model_label: 'Default model',
|
||||
onboarding_workspace_help: 'Pick the model Hermes should use for new chats after setup completes.',
|
||||
onboarding_custom_model_placeholder: 'your-model-name',
|
||||
onboarding_custom_model_help: 'For custom endpoints, enter the exact model ID your server expects.',
|
||||
onboarding_notice_password_enabled: 'A password is already configured. Enter a new one only if you want to replace it.',
|
||||
onboarding_notice_password_recommended: 'Optional but recommended if you will expose the UI beyond localhost.',
|
||||
onboarding_password_label: 'Password (optional)',
|
||||
onboarding_password_placeholder: 'Leave blank to skip',
|
||||
onboarding_password_help: 'Passwords are stored through the existing settings API and hashed server-side.',
|
||||
onboarding_notice_finish: 'You can reopen Settings later to change any of this.',
|
||||
onboarding_not_set: 'Not set',
|
||||
onboarding_password_will_enable: 'Will be enabled',
|
||||
onboarding_password_skipped: 'Skipped for now',
|
||||
onboarding_finish_help: 'Finishing stores <code>onboarding_completed</code> in settings and drops you into the normal app.',
|
||||
onboarding_error_choose_workspace: 'Choose a workspace before continuing.',
|
||||
onboarding_error_choose_model: 'Choose a model before continuing.',
|
||||
onboarding_error_provider_required: 'Choose a setup mode before continuing.',
|
||||
onboarding_error_base_url_required: 'Base URL is required for custom endpoints.',
|
||||
onboarding_error_workspace_required: 'Workspace is required.',
|
||||
onboarding_error_model_required: 'Model is required.',
|
||||
onboarding_complete: 'Onboarding complete',
|
||||
},
|
||||
|
||||
es: {
|
||||
_lang: 'es',
|
||||
_label: 'Español',
|
||||
_speech: 'es-ES',
|
||||
// boot.js
|
||||
cancelling: 'Cancelando…',
|
||||
cancel_failed: 'Error al cancelar: ',
|
||||
mic_denied: 'Acceso al micrófono denegado. Revisa los permisos del navegador.',
|
||||
mic_no_speech: 'No se detectó voz. Inténtalo de nuevo.',
|
||||
mic_network: 'El reconocimiento de voz no está disponible.',
|
||||
mic_error: 'Error de entrada por voz: ',
|
||||
session_imported: 'Sesión importada',
|
||||
import_failed: 'Error al importar: ',
|
||||
import_invalid_json: 'JSON inválido',
|
||||
image_pasted: 'Imagen pegada: ',
|
||||
// messages.js
|
||||
edit_message: 'Editar mensaje',
|
||||
regenerate: 'Regenerar respuesta',
|
||||
copy: 'Copiar',
|
||||
copied: '¡Copiado!',
|
||||
you: 'Tú',
|
||||
thinking: 'Pensando',
|
||||
expand_all: 'Expandir todo',
|
||||
collapse_all: 'Contraer todo',
|
||||
edit_failed: 'Error al editar: ',
|
||||
regen_failed: 'Error al regenerar: ',
|
||||
reconnect_active: 'Todavía se está generando una respuesta. ¿Recargar cuando termine?',
|
||||
reconnect_finished: 'Había una respuesta en curso cuando te fuiste. Puede que los mensajes se hayan actualizado.',
|
||||
// approval card
|
||||
approval_heading: 'Se requiere aprobación',
|
||||
approval_desc_prefix: 'Se detectó un comando peligroso',
|
||||
approval_btn_once: 'Permitir una vez',
|
||||
approval_btn_once_title: 'Permitir solo este comando (Enter)',
|
||||
approval_btn_session: 'Permitir en la sesión',
|
||||
approval_btn_session_title: 'Permitir durante esta sesión de conversación',
|
||||
approval_btn_always: 'Permitir siempre',
|
||||
approval_btn_always_title: 'Permitir siempre este patrón de comando',
|
||||
approval_btn_deny: 'Denegar',
|
||||
approval_btn_deny_title: 'Denegar — no ejecutar este comando',
|
||||
approval_responding: 'Respondiendo…',
|
||||
untitled: 'Sin título',
|
||||
n_messages: (n) => `${n} mensajes`,
|
||||
model_unavailable: ' (no disponible)',
|
||||
model_unavailable_title: 'Este modelo ya no está en tu lista actual de proveedores',
|
||||
provider_mismatch_warning: (m,p)=>`"${m}" puede no funcionar con tu proveedor configurado (${p}). Envía de todas formas, o ejecuta \`hermes model\` en la terminal para cambiar.`,
|
||||
provider_mismatch_label: 'Proveedor incompatible',
|
||||
// commands.js
|
||||
cmd_help: 'Listar los comandos disponibles',
|
||||
cmd_clear: 'Borrar los mensajes de la conversación',
|
||||
cmd_compact: 'Comprimir el contexto de la conversación',
|
||||
cmd_model: 'Cambiar de modelo (p. ej. /model gpt-4o)',
|
||||
cmd_workspace: 'Cambiar de espacio de trabajo por nombre',
|
||||
cmd_new: 'Iniciar una nueva sesión de chat',
|
||||
cmd_usage: 'Activar o desactivar el uso de tokens',
|
||||
cmd_theme: 'Cambiar tema (dark/light/slate/solarized/monokai/nord/oled)',
|
||||
cmd_personality: 'Cambiar la personalidad del agente',
|
||||
cmd_skills: 'Listar las skills de Hermes disponibles',
|
||||
available_commands: 'Comandos disponibles:',
|
||||
type_slash: 'Escribe / para ver los comandos',
|
||||
conversation_cleared: 'Conversación borrada',
|
||||
model_usage: 'Uso: /model <name>',
|
||||
no_model_match: 'No hay ningún modelo que coincida con "',
|
||||
switched_to: 'Se cambió a ',
|
||||
workspace_usage: 'Uso: /workspace <name>',
|
||||
no_workspace_match: 'No hay ningún espacio de trabajo que coincida con "',
|
||||
switched_workspace: 'Se cambió al espacio de trabajo: ',
|
||||
workspace_switch_failed: 'Error al cambiar de espacio de trabajo: ',
|
||||
new_session: 'Nueva sesión creada',
|
||||
compressing: 'Solicitando compresión del contexto...',
|
||||
token_usage_on: 'Uso de tokens activado',
|
||||
token_usage_off: 'Uso de tokens desactivado',
|
||||
theme_usage: 'Uso: /theme ',
|
||||
theme_set: 'Tema: ',
|
||||
no_active_session: 'No hay ninguna sesión activa',
|
||||
no_personalities: 'No se encontraron personalidades (añádelas a ~/.hermes/personalities/)',
|
||||
available_personalities: 'Personalidades disponibles:',
|
||||
personality_switch_hint: '\n\nUsa `/personality <name>` para cambiar, o `/personality none` para limpiar.',
|
||||
personalities_load_failed: 'No se pudieron cargar las personalidades',
|
||||
personality_cleared: 'Personalidad borrada',
|
||||
personality_set: 'Personalidad: ',
|
||||
failed_colon: 'Error: ',
|
||||
// ui.js
|
||||
no_workspace: 'Sin espacio de trabajo',
|
||||
// workspace.js
|
||||
unsaved_confirm: 'Tienes cambios sin guardar en la vista previa. ¿Descartar y navegar?',
|
||||
save: 'Guardar',
|
||||
edit: 'Editar',
|
||||
save_title: 'Guardar cambios',
|
||||
edit_title: 'Editar este archivo',
|
||||
saved: 'Guardado',
|
||||
save_failed: 'Error al guardar: ',
|
||||
image_load_failed: 'No se pudo cargar la imagen',
|
||||
file_open_failed: 'No se pudo abrir el archivo',
|
||||
downloading: (name) => `Descargando ${name}…`,
|
||||
double_click_rename: 'Haz doble clic para renombrar',
|
||||
renamed_to: 'Renombrado a ',
|
||||
rename_failed: 'Error al renombrar: ',
|
||||
delete_title: 'Eliminar',
|
||||
delete_confirm: (name) => `¿Eliminar ${name}?`,
|
||||
deleted: 'Eliminado ',
|
||||
delete_failed: 'Error al eliminar: ',
|
||||
new_file_prompt: 'Nombre del archivo nuevo (p. ej. notes.md):',
|
||||
created: 'Creado ',
|
||||
create_failed: 'Error al crear: ',
|
||||
new_folder_prompt: 'Nombre de la carpeta nueva:',
|
||||
folder_created: 'Carpeta creada ',
|
||||
folder_create_failed: 'Error al crear la carpeta: ',
|
||||
remove_title: 'Quitar',
|
||||
empty_dir: '(vacío)',
|
||||
upload_failed: 'Error al subir: ',
|
||||
all_uploads_failed: (n) => `Fallaron las ${n} subida(s)`,
|
||||
// settings panel
|
||||
settings_title: 'Configuración',
|
||||
settings_save_btn: 'Guardar configuración',
|
||||
settings_label_model: 'Modelo predeterminado',
|
||||
settings_label_send_key: 'Tecla de envío',
|
||||
settings_label_theme: 'Tema',
|
||||
settings_label_language: 'Idioma',
|
||||
settings_label_token_usage: 'Mostrar uso de tokens',
|
||||
settings_label_cli_sessions: 'Mostrar sesiones de CLI',
|
||||
settings_label_sync_insights: 'Sincronizar con insights',
|
||||
settings_label_check_updates: 'Buscar actualizaciones',
|
||||
settings_label_bot_name: 'Nombre del asistente',
|
||||
settings_label_password: 'Contraseña de acceso',
|
||||
settings_saved: 'Configuración guardada',
|
||||
settings_save_failed: 'Error al guardar: ',
|
||||
settings_load_failed: 'Error al cargar la configuración: ',
|
||||
settings_saved_pw: 'Configuración guardada (contraseña establecida — ahora se requiere iniciar sesión)',
|
||||
// login page (used server-side via /api/i18n/login endpoint)
|
||||
login_title: 'Iniciar sesión',
|
||||
login_subtitle: 'Introduce tu contraseña para continuar',
|
||||
login_placeholder: 'Contraseña',
|
||||
login_btn: 'Entrar',
|
||||
login_invalid_pw: 'Contraseña inválida',
|
||||
login_conn_failed: 'Error de conexión',
|
||||
dialog_confirm_title: 'Confirmar acción',
|
||||
dialog_prompt_title: 'Introduce un valor',
|
||||
dialog_confirm_btn: 'Confirmar',
|
||||
discard: 'Descartar',
|
||||
clear: 'Borrar',
|
||||
create: 'Crear',
|
||||
remove: 'Quitar',
|
||||
project_name_prompt: 'Nombre del proyecto:',
|
||||
// Sidebar & Tabs
|
||||
tab_chat: 'Chat',
|
||||
tab_tasks: 'Tareas',
|
||||
tab_skills: 'Habilidades',
|
||||
tab_memory: 'Memoria',
|
||||
tab_workspaces: 'Espacios',
|
||||
tab_profiles: 'Perfiles',
|
||||
tab_todos: 'Todos',
|
||||
new_conversation: 'Nueva conversación',
|
||||
filter_conversations: 'Filtrar conversaciones...',
|
||||
scheduled_jobs: 'Tareas programadas',
|
||||
new_job: 'Nueva tarea',
|
||||
loading: 'Cargando...',
|
||||
search_skills: 'Buscar skills...',
|
||||
new_skill: 'Nueva skill',
|
||||
personal_memory: 'Memoria personal',
|
||||
current_task_list: 'Lista de tareas actual',
|
||||
workspace_desc: 'Añade y cambia espacios de trabajo para tus sesiones.',
|
||||
new_profile: 'Nuevo perfil',
|
||||
transcript: 'Transcripción',
|
||||
download_transcript: 'Descargar como Markdown',
|
||||
import: 'Importar',
|
||||
// Settings detail
|
||||
settings_label_sound: 'Sonido de notificación',
|
||||
settings_desc_sound: 'Reproduce un sonido cuando el asistente termina una respuesta.',
|
||||
settings_label_notifications: 'Notificaciones del navegador',
|
||||
settings_desc_notifications: 'Muestra una notificación del sistema cuando una respuesta termina mientras la pestaña está en segundo plano.',
|
||||
settings_desc_token_usage: 'Muestra el conteo de tokens de entrada/salida debajo de cada respuesta del asistente. También se puede alternar con /usage.',
|
||||
settings_desc_cli_sessions: 'Fusiona las sesiones del CLI de Hermes (state.db) en la lista de sesiones. Haz clic en una sesión de CLI para importarla y continuar la conversación.',
|
||||
settings_desc_sync_insights: 'Refleja el uso de tokens de la WebUI en state.db para que hermes /insights incluya datos de sesiones del navegador. Desactivado por defecto.',
|
||||
settings_desc_check_updates: 'Muestra un banner cuando haya versiones más nuevas de la WebUI o del Agent. Ejecuta periódicamente un git fetch en segundo plano.',
|
||||
settings_desc_bot_name: 'Nombre visible del asistente en toda la UI. Por defecto es Hermes.',
|
||||
settings_desc_password: 'Introduce una nueva contraseña para establecerla o cambiarla. Déjalo en blanco para mantener la configuración actual.',
|
||||
password_placeholder: 'Introduce una contraseña nueva…',
|
||||
disable_auth: 'Desactivar autenticación',
|
||||
sign_out: 'Cerrar sesión',
|
||||
cancel: 'Cancelar',
|
||||
create_job: 'Crear tarea',
|
||||
save_skill: 'Guardar skill',
|
||||
editing: 'Editando',
|
||||
// Empty state
|
||||
empty_title: '¿En qué puedo ayudarte?',
|
||||
empty_subtitle: 'Pregunta lo que quieras, ejecuta comandos, explora archivos o gestiona tus tareas programadas.',
|
||||
suggest_files: '¿Qué archivos hay en este espacio de trabajo?',
|
||||
suggest_schedule: '¿Qué tengo hoy en mi agenda?',
|
||||
suggest_plan: 'Ayúdame a planificar un proyecto pequeño.',
|
||||
// onboarding
|
||||
onboarding_badge: 'PRIMER USO',
|
||||
onboarding_title: 'Bienvenido a Hermes Web UI',
|
||||
onboarding_lead: 'Una guía rápida verificará Hermes, guardará una configuración real del proveedor, elegirá un espacio de trabajo y un modelo, y opcionalmente protegerá la app con una contraseña.',
|
||||
onboarding_back: 'Atrás',
|
||||
onboarding_continue: 'Continuar',
|
||||
onboarding_open: 'Abrir Hermes',
|
||||
onboarding_step_system_title: 'Comprobación del sistema',
|
||||
onboarding_step_system_desc: 'Verifica Hermes Agent y la visibilidad de la configuración.',
|
||||
onboarding_step_setup_title: 'Configuración del proveedor',
|
||||
onboarding_step_setup_desc: 'Guarda la configuración mínima real de Hermes.',
|
||||
onboarding_step_workspace_title: 'Espacio de trabajo + modelo',
|
||||
onboarding_step_workspace_desc: 'Elige los valores predeterminados para nuevas sesiones y chats.',
|
||||
onboarding_step_password_title: 'Contraseña opcional',
|
||||
onboarding_step_password_desc: 'Protege la Web UI antes de compartirla.',
|
||||
onboarding_step_finish_title: 'Finalizar',
|
||||
onboarding_step_finish_desc: 'Revisa todo y entra en la app.',
|
||||
onboarding_notice_system_ready: 'Parece que Hermes Agent está accesible desde la Web UI.',
|
||||
onboarding_notice_system_unavailable: 'Hermes Agent todavía no está totalmente disponible. Bootstrap puede instalarlo, pero la configuración del proveedor quizá aún requiera una terminal.',
|
||||
onboarding_check_agent: 'Hermes Agent',
|
||||
onboarding_check_agent_ready: 'Detectado e importable',
|
||||
onboarding_check_agent_missing: 'Falta o solo es parcialmente importable',
|
||||
onboarding_check_password: 'Contraseña',
|
||||
onboarding_check_password_enabled: 'Ya está activada',
|
||||
onboarding_check_password_disabled: 'Todavía no está activada',
|
||||
onboarding_check_provider: 'Configuración del proveedor',
|
||||
onboarding_check_provider_ready: 'Listo para chatear',
|
||||
onboarding_check_provider_partial: 'Guardado pero incompleto',
|
||||
onboarding_check_provider_pending: 'Necesita verificación',
|
||||
onboarding_config_file: 'Archivo de configuración:',
|
||||
onboarding_env_file: 'Archivo .env:',
|
||||
onboarding_unknown: 'Desconocido',
|
||||
onboarding_current_provider: 'Configuración actual:',
|
||||
onboarding_missing_imports: 'Importaciones faltantes:',
|
||||
onboarding_notice_setup_required: 'Elige aquí una ruta simple de proveedor. Los flujos OAuth avanzados siguen siendo del CLI de Hermes por ahora.',
|
||||
onboarding_notice_setup_already_ready: 'Ya se detectó una configuración funcional del proveedor de Hermes. Puedes conservarla o reemplazarla aquí.',
|
||||
onboarding_notice_workspace: 'Estos valores reutilizan las mismas APIs de configuración que la app normal.',
|
||||
onboarding_workspace_label: 'Espacio de trabajo',
|
||||
onboarding_workspace_or_path: 'O introduce la ruta de un espacio de trabajo',
|
||||
onboarding_workspace_placeholder: '/home/you/workspace',
|
||||
onboarding_provider_label: 'Modo de configuración',
|
||||
onboarding_quick_setup_badge: 'configuración rápida',
|
||||
onboarding_api_key_label: 'API key',
|
||||
onboarding_api_key_placeholder: 'Déjala en blanco para conservar una key ya guardada',
|
||||
onboarding_api_key_help_prefix: 'Se guarda como secreto en tu archivo .env de Hermes usando',
|
||||
onboarding_base_url_label: 'Base URL',
|
||||
onboarding_base_url_placeholder: 'https://tu-endpoint.example/v1',
|
||||
onboarding_base_url_help: 'Úsalo para routers OpenAI-compatible, servidores autoalojados, LiteLLM, Ollama, LM Studio, vLLM o endpoints parecidos.',
|
||||
onboarding_model_label: 'Modelo predeterminado',
|
||||
onboarding_workspace_help: 'Elige el modelo que Hermes debe usar para nuevos chats cuando termine la configuración.',
|
||||
onboarding_custom_model_placeholder: 'tu-modelo',
|
||||
onboarding_custom_model_help: 'Para endpoints personalizados, introduce el identificador exacto del modelo que espera tu servidor.',
|
||||
onboarding_notice_password_enabled: 'Ya hay una contraseña configurada. Introduce una nueva solo si quieres reemplazarla.',
|
||||
onboarding_notice_password_recommended: 'Es opcional, pero recomendable si vas a exponer la UI más allá de localhost.',
|
||||
onboarding_password_label: 'Contraseña (opcional)',
|
||||
onboarding_password_placeholder: 'Déjala en blanco para omitirla',
|
||||
onboarding_password_help: 'Las contraseñas se guardan mediante la API de configuración existente y se hashean en el servidor.',
|
||||
onboarding_notice_finish: 'Puedes volver a abrir Configuración más tarde para cambiar cualquiera de estos valores.',
|
||||
onboarding_not_set: 'Sin definir',
|
||||
onboarding_password_will_enable: 'Se activará',
|
||||
onboarding_password_skipped: 'Se omitirá por ahora',
|
||||
onboarding_finish_help: 'Al finalizar se guarda <code>onboarding_completed</code> en la configuración y entras en la app normal.',
|
||||
onboarding_error_choose_workspace: 'Elige un espacio de trabajo antes de continuar.',
|
||||
onboarding_error_choose_model: 'Elige un modelo antes de continuar.',
|
||||
onboarding_error_provider_required: 'Elige un modo de configuración antes de continuar.',
|
||||
onboarding_error_base_url_required: 'La base URL es obligatoria para endpoints personalizados.',
|
||||
onboarding_error_workspace_required: 'El espacio de trabajo es obligatorio.',
|
||||
onboarding_error_model_required: 'El modelo es obligatorio.',
|
||||
onboarding_complete: 'Onboarding completado',
|
||||
},
|
||||
|
||||
de: {
|
||||
@@ -228,6 +568,8 @@ const LOCALES = {
|
||||
n_messages: (n) => `${n} Nachrichten`,
|
||||
model_unavailable: ' (nicht verfügbar)',
|
||||
model_unavailable_title: 'Dieses Modell ist nicht mehr in Ihrer aktuellen Provider-Liste',
|
||||
provider_mismatch_warning: (m,p)=>`"${m}" funktioniert möglicherweise nicht mit Ihrem konfigurierten Provider (${p}). Trotzdem senden, oder \`hermes model\` im Terminal ausführen.`,
|
||||
provider_mismatch_label: 'Provider-Konflikt',
|
||||
// commands.js
|
||||
cmd_help: 'Verfügbare Befehle auflisten',
|
||||
cmd_clear: 'Konversationsverlauf löschen',
|
||||
@@ -238,6 +580,7 @@ const LOCALES = {
|
||||
cmd_usage: 'Token-Verbrauchsanzeige umschalten',
|
||||
cmd_theme: 'Theme wechseln (dark/light/slate/solarized/monokai/nord/oled)',
|
||||
cmd_personality: 'Agenten-Persönlichkeit wechseln',
|
||||
cmd_skills: 'Verfügbare Hermes-Skills auflisten',
|
||||
available_commands: 'Verfügbare Befehle:',
|
||||
type_slash: 'Tippe / für Befehle',
|
||||
conversation_cleared: 'Konversation gelöscht',
|
||||
@@ -300,7 +643,7 @@ const LOCALES = {
|
||||
settings_label_theme: 'Theme',
|
||||
settings_label_language: 'Sprache',
|
||||
settings_label_token_usage: 'Token-Verbrauch anzeigen',
|
||||
settings_label_cli_sessions: 'CLI-Sitzungen anzeigen',
|
||||
settings_label_cli_sessions: 'Agent-Sitzungen anzeigen',
|
||||
settings_label_sync_insights: 'Mit Insights synchronisieren',
|
||||
settings_label_check_updates: 'Nach Updates suchen',
|
||||
settings_label_bot_name: 'Assistenten-Name',
|
||||
@@ -316,6 +659,14 @@ const LOCALES = {
|
||||
login_btn: 'Anmelden',
|
||||
login_invalid_pw: 'Ungültiges Passwort',
|
||||
login_conn_failed: 'Verbindung fehlgeschlagen',
|
||||
dialog_confirm_title: 'Aktion bestätigen',
|
||||
dialog_prompt_title: 'Wert eingeben',
|
||||
dialog_confirm_btn: 'Bestätigen',
|
||||
discard: 'Verwerfen',
|
||||
clear: 'Leeren',
|
||||
create: 'Erstellen',
|
||||
remove: 'Entfernen',
|
||||
project_name_prompt: 'Projektname:',
|
||||
// Sidebar & Tabs
|
||||
tab_chat: 'Chat',
|
||||
tab_tasks: 'Aufgaben',
|
||||
@@ -366,7 +717,7 @@ const LOCALES = {
|
||||
|
||||
zh: {
|
||||
_lang: 'zh',
|
||||
_label: '\u4e2d\u6587',
|
||||
_label: '\u7b80\u4f53\u4e2d\u6587',
|
||||
_speech: 'zh-CN',
|
||||
// boot.js
|
||||
cancelling: '\u6b63\u5728\u53d6\u6d88...',
|
||||
@@ -408,6 +759,8 @@ const LOCALES = {
|
||||
n_messages: (n) => `${n} \u6761\u6d88\u606f`,
|
||||
model_unavailable: '\uff08\u4e0d\u53ef\u7528\uff09',
|
||||
model_unavailable_title: '\u8fd9\u4e2a\u6a21\u578b\u5df2\u7ecf\u4e0d\u5728\u5f53\u524d provider \u5217\u8868\u4e2d',
|
||||
provider_mismatch_warning: (m,p)=>`\"${m}\" \u53ef\u80fd\u65e0\u6cd5\u5728\u5f53\u524d\u914d\u7f6e\u7684\u63d0\u4f9b\u5546 (${p}) \u4e0b\u5de5\u4f5c\u3002\u76f4\u63a5\u53d1\u9001\uff0c\u6216\u5728\u7ec8\u7aef\u8fd0\u884c \`hermes model\` \u5207\u6362\u3002`,
|
||||
provider_mismatch_label: '\u63d0\u4f9b\u5546\u4e0d\u5339\u914d',
|
||||
// commands.js
|
||||
cmd_help: '\u67e5\u770b\u53ef\u7528\u547d\u4ee4',
|
||||
cmd_clear: '\u6e05\u7a7a\u5f53\u524d\u5bf9\u8bdd\u6d88\u606f',
|
||||
@@ -418,6 +771,7 @@ const LOCALES = {
|
||||
cmd_usage: '\u5207\u6362 token \u7528\u91cf\u663e\u793a',
|
||||
cmd_theme: '\u5207\u6362\u4e3b\u9898\uff08dark/light/slate/solarized/monokai/nord/oled\uff09',
|
||||
cmd_personality: '\u5207\u6362 Agent \u4eba\u8bbe',
|
||||
cmd_skills: '\u5217\u51fa\u53ef\u7528\u7684 Hermes \u6280\u80fd',
|
||||
available_commands: '\u53ef\u7528\u547d\u4ee4\uff1a',
|
||||
type_slash: '\u8f93\u5165 / \u53ef\u67e5\u770b\u547d\u4ee4',
|
||||
conversation_cleared: '\u5bf9\u8bdd\u5df2\u6e05\u7a7a',
|
||||
@@ -496,6 +850,265 @@ const LOCALES = {
|
||||
login_btn: '\u767b\u5f55',
|
||||
login_invalid_pw: '\u5bc6\u7801\u9519\u8bef',
|
||||
login_conn_failed: '\u8fde\u63a5\u5931\u8d25',
|
||||
dialog_confirm_title: '确认操作',
|
||||
dialog_prompt_title: '输入内容',
|
||||
dialog_confirm_btn: '确认',
|
||||
discard: '放弃',
|
||||
clear: '清空',
|
||||
create: '创建',
|
||||
remove: '移除',
|
||||
project_name_prompt: '项目名称:',
|
||||
// missing keys from English
|
||||
tab_chat: '\u804a\u5929',
|
||||
tab_memory: '\u8a18\u61b6',
|
||||
tab_skills: '\u6280\u80fd',
|
||||
tab_tasks: '\u4efb\u52d9',
|
||||
tab_todos: '\u5f85\u8e29',
|
||||
tab_workspaces: '\u5de5\u4f5c\u5340',
|
||||
new_conversation: '\u65b0\u5b58\u5c0d\u8a71',
|
||||
filter_conversations: '\u7b5c\u9078\u5b58\u5c0d\u8a71',
|
||||
scheduled_jobs: '\u5b58\u5287\u4efb\u52d9',
|
||||
new_job: '\u65b0\u4efb\u52d9',
|
||||
search_skills: '\u641c\u5c0b\u6280\u80fd',
|
||||
new_skill: '\u65b0\u6280\u80fd',
|
||||
save_skill: '\u5132\u5b58\u6280\u80fd',
|
||||
personal_memory: '\u500b\u4eba\u8a18\u61b6',
|
||||
current_task_list: '\u76ee\u524d\u4efb\u52d9\u6e05\u55ae',
|
||||
new_profile: '\u65b0\u914d\u7f6e\u6a94',
|
||||
transcript: '\u8a18\u9304',
|
||||
download_transcript: '\u4e0b\u8f09\u8a18\u9304',
|
||||
import: '\u5c0e\u5165',
|
||||
editing: '\u7de8\u8f2f\u4e2d',
|
||||
empty_title: '\u7a7a\u767c\u5b58\u7a7a\u9593',
|
||||
empty_subtitle: '\u9ede\u64ca\u4e0a\u65b9\u6309\u9215\u958b\u59cb\u5c0d\u8a71',
|
||||
cancel: '\u53d6\u6d88',
|
||||
loading: '\u52a0\u8f09\u4e2d',
|
||||
create_job: '\u5efa\u7acb\u4efb\u52d9',
|
||||
suggest_plan: '\u5efa\u8b70\u8a08\u5287',
|
||||
suggest_schedule: '\u5efa\u8b70\u6642\u7a0b',
|
||||
suggest_files: '\u5efa\u8b70\u6a94\u6848',
|
||||
sign_out: '\u767b\u51fa',
|
||||
password_placeholder: '\u5bc6\u7801',
|
||||
disable_auth: '\u505c\u7528\u9a57\u8b49',
|
||||
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
|
||||
settings_label_notifications: '\u700f\u89bd\u901a\u77e5',
|
||||
settings_desc_sound: '\u52a9\u624b\u5b8c\u6210\u56de\u7b54\u6642\u64a9\u653e\u8072\u97f3\u3002',
|
||||
settings_desc_notifications: '\u7576\u5206\u9801\u5728\u5f8c\u53f0\u6642\uff0c\u6709\u56de\u7b54\u5b8c\u6210\u6e05\u55ae\u6703\u986f\u793a\u7cfb\u7d71\u901a\u77e5\u3002',
|
||||
settings_desc_token_usage: '\u5728\u52a9\u624b\u6bcf\u6b21\u56de\u7b54\u4e0b\u65b9\u986f\u793a Input/Output token \u6578\u91cf\u3002\u4e5f\u53ef\u4ee5\u7528 /usage \u5207\u63db\u3002',
|
||||
settings_desc_cli_sessions: '\u5c07 Hermes CLI (\u7684 state.db) \u4e2d\u7684\u4f1a\u8a71\u6dfb\u52a0\u5230\u4f1a\u8a71\u6e05\u55ae\u3002\u9ede\u64ca\u4e00\u500b CLI \u4f1a\u8a71\u5c07\u5c0e\u5165\u5b83\u7a0b\u5f0f\u4e26\u7e7c\u7e8c\u5b58\u5c0d\u8a71\u3002',
|
||||
settings_desc_sync_insights: '\u5c07 WebUI token \u4f7f\u7528\u60c5\u6cc1\u540c\u6b65\u5230 state.db\uff0c\u8a93 hermes /insights \u5305\u542b\u700f\u89bd\u5668\u4f1a\u8a71\u6578\u64da\u3002\u9810\u8a2d\u70b8\u555f\u7528\u3002',
|
||||
settings_desc_check_updates: '\u7576\u6709\u66f4\u65b0\u7684 WebUI \u6216\u52a9\u624b\u7248\u672c\u6642\u986f\u793a\u6a19\u8a18\u3002\u5c07\u5728\u5f8c\u81ea\u6b63\u5e38\u57f7\u884c Git-Fetch\u3002',
|
||||
settings_desc_bot_name: '\u52a9\u624b\u5728 UI \u4e2d\u7684\u986f\u793a\u540d\u7a31\u3002\u9810\u8a2d\u70b8\u7528\u6539\u3002',
|
||||
settings_desc_password: '\u8a2d\u5b9a WebUI \u767b\u5165\u5bc6\u7801\u3002\u5047\u5982\u5df2\u8a2d\u7f6e\uff0c\u6bcf\u6b21\u52a0\u8f09\u90fd\u9700\u8981\u767b\u5165\u3002',
|
||||
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
|
||||
},
|
||||
|
||||
// Traditional Chinese (zh-Hant)
|
||||
'zh-Hant': {
|
||||
_lang: 'zh-Hant',
|
||||
_label: '\u7e41\u9ad4\u4e2d\u6587',
|
||||
_speech: 'zh-TW',
|
||||
// boot.js
|
||||
cancelling: '\u6b63\u5728\u53d6\u6d88...',
|
||||
cancel_failed: '\u53d6\u6d88\u5931\u6557\uff1a',
|
||||
mic_denied: '\u9ea6\u514b\u98a8\u8a2a\u554f\u88ab\u62d2\u7d75\uff0c\u8acb\u6aa2\u67e5\u700f\u89bd\u5668\u6b0a\u9650\u3002',
|
||||
mic_no_speech: '\u6c92\u6709\u6aa2\u6e2c\u5230\u8a71\u97f3\uff0c\u8acb\u518d\u5617\u4e00\u6b21\u3002',
|
||||
mic_network: '\u8a71\u97f3\u8b58\u5225\u76ee\u524d\u4e0d\u53ef\u7528\u3002',
|
||||
mic_error: '\u8a71\u97f3\u8f38\u5165\u51fa\u932f\uff1a',
|
||||
session_imported: '\u6703\u8a71\u5df2\u5c0e\u5165',
|
||||
import_failed: '\u5c0e\u5165\u5931\u6557\uff1a',
|
||||
import_invalid_json: 'JSON \u7121\u6548',
|
||||
image_pasted: '\u5df2\u7c98\u8cbc\u5716\u7247\uff1a',
|
||||
// messages.js
|
||||
edit_message: '\u7de8\u8f2f\u8a0a\u606f',
|
||||
regenerate: '\u91cd\u65b0\u751f\u6210\u56de\u8986',
|
||||
copy: '\u8907\u88fd',
|
||||
copied: '\u5df2\u8907\u88fd',
|
||||
you: '\u4f60',
|
||||
thinking: '\u601d\u8003\u904e\u7a0b',
|
||||
expand_all: '\u5168\u90e8\u5c55\u958b',
|
||||
collapse_all: '\u5168\u90e8\u6298\u758a',
|
||||
edit_failed: '\u7de8\u8f2f\u5931\u6557\uff1a',
|
||||
regen_failed: '\u91cd\u65b0\u751f\u6210\u5931\u6557\uff1a',
|
||||
reconnect_active: '\u56de\u8986\u4ecd\u5728\u751f\u6210\u4e2d\uff0c\u6e96\u5099\u597d\u5f8c\u8981\u91cd\u65b0\u52a0\u8f09\u55ce\uff1f',
|
||||
reconnect_finished: '\u4f60\u96e2\u958b\u6642\u6709\u56de\u8986\u6b63\u5728\u751f\u6210\uff0c\u8a0a\u606f\u5167\u5bb9\u53ef\u80fd\u5df2\u7d93\u66f4\u65b0\u3002',
|
||||
// approval card
|
||||
approval_heading: '\u9700\u8981\u5ba1\u6838',
|
||||
approval_desc_prefix: '\u6aa2\u6e2c\u5230\u5371\u96aa\u547d\u4ee4',
|
||||
approval_btn_once: '\u5141\u8a31\u4e00\u6b21',
|
||||
approval_btn_once_title: '\u5141\u8a31\u57f7\u884c\u6b64\u547d\u4ee4\u4e00\u6b21\uff08Enter\uff09',
|
||||
approval_btn_session: '\u672c\u6b21\u5141\u8a31',
|
||||
approval_btn_session_title: '\u672c\u6b21\u6703\u8a71\u671f\u9593\u5141\u8a31',
|
||||
approval_btn_always: '\u59c4\u59b9\u5141\u8a31',
|
||||
approval_btn_always_title: '\u59c4\u59b9\u5141\u8a31\u6b64\u547d\u4ee4\u6a21\u5f0f',
|
||||
approval_btn_deny: '\u62d2\u7edd',
|
||||
approval_btn_deny_title: '\u62d2\u7edd — \u4e0d\u57f7\u884c\u6b64\u547d\u4ee4',
|
||||
approval_responding: '\u8655\u7406\u4e2d\u2026',
|
||||
untitled: '\u672a\u547d\u540d',
|
||||
n_messages: (n) => `${n} \u689d\u8a0a\u606f`,
|
||||
model_unavailable: '\uff08\u4e0d\u53ef\u7528\uff09',
|
||||
model_unavailable_title: '\u6b64\u6a21\u578b\u5df2\u7d93\u4e0d\u5728\u7576\u524d provider \u5217\u8868\u4e2d',
|
||||
provider_mismatch_warning: (m,p)=>`\"${m}\" \u53ef\u80fd\u7121\u6cd5\u5728\u7576\u524d\u914d\u7f6e\u7684\u63d0\u4f9b\u8005 (${p}) \u4e0b\u904b\u4f5c\u3002\u5c1a\u9001\uff0c\u6216\u5728\u7d42\u7aef\u57f7\u884c \`hermes model\` \u5207\u63db\u3002`,
|
||||
provider_mismatch_label: '\u63d0\u4f9b\u8005\u4e0d\u76f8\u7b26',
|
||||
// commands.js
|
||||
cmd_help: '\u67e5\u770b\u53ef\u7528\u547d\u4ee4',
|
||||
cmd_clear: '\u6e05\u7a7a\u7576\u524d\u5c0d\u8a71\u8a0a\u606f',
|
||||
cmd_compact: '\u58d3\u7e2e\u5c0d\u8a71\u4e0a\u4e0b\u6587',
|
||||
cmd_model: '\u5207\u63db\u6a21\u578b\uff08\u4f8b\u5982 /model gpt-4o\uff09',
|
||||
cmd_workspace: '\u6309\u540d\u7a31\u5207\u63db\u5de5\u4f5c\u5340',
|
||||
cmd_new: '\u65b0\u5efa\u804a\u5929\u6703\u8a71',
|
||||
cmd_usage: '\u5207\u63db token \u7528\u91cf\u986f\u793a',
|
||||
cmd_theme: '\u5207\u63db\u4e3b\u984c\uff08dark/light/slate/solarized/monokai/nord/oled\uff09',
|
||||
cmd_personality: '\u5207\u63db Agent \u4eba\u8a2d',
|
||||
cmd_skills: '\u5217\u51fa\u53ef\u7528\u7684 Hermes \u6280\u80fd',
|
||||
available_commands: '\u53ef\u7528\u547d\u4ee4\uff1a',
|
||||
type_slash: '\u8f38\u5165 / \u53ef\u67e5\u770b\u547d\u4ee4',
|
||||
conversation_cleared: '\u5c0d\u8a71\u5df2\u6e05\u7a7a',
|
||||
model_usage: '\u7528\u6cd5\uff1a/model <name>',
|
||||
no_model_match: '\u6c92\u6709\u5339\u914d\u201c',
|
||||
switched_to: '\u5df2\u5207\u63db\u5230 ',
|
||||
workspace_usage: '\u7528\u6cd5\uff1a/workspace <name>',
|
||||
no_workspace_match: '\u6c92\u6709\u5339\u914d\u201c',
|
||||
switched_workspace: '\u5df2\u5207\u63db\u5de5\u4f5c\u5340\uff1a',
|
||||
workspace_switch_failed: '\u5de5\u4f5c\u5340\u5207\u63db\u5931\u6557\uff1a',
|
||||
new_session: '\u5df2\u65b0\u5efa\u6703\u8a71',
|
||||
compressing: '\u6b63\u5728\u8981\u6c42\u58d3\u7e2e\u4e0a\u4e0b\u6587...',
|
||||
token_usage_on: 'Token \u7528\u91cf\u986f\u793a\u5df2\u958b\u555f',
|
||||
token_usage_off: 'Token \u7528\u91cf\u986f\u793a\u5df2\u95dc\u9589',
|
||||
theme_usage: '\u7528\u6cd5\uff1a/theme ',
|
||||
theme_set: '\u4e3b\u984c\uff1a',
|
||||
no_active_session: '\u7576\u524d\u6c92\u6709\u6d3b\u52d5\u6703\u8a71',
|
||||
no_personalities: '\u6c92\u6709\u627e\u5230\u4eba\u8a2d\uff08\u53ef\u6dfb\u52a0\u5230 ~/.hermes/personalities/\uff09',
|
||||
available_personalities: '\u53ef\u7528\u4eba\u8a2d\uff1a',
|
||||
personality_switch_hint: '\n\n\u4f7f\u7528 `/personality <name>` \u5207\u63db\uff0c\u6216\u7528 `/personality none` \u6e05\u7a7a\u3002',
|
||||
personalities_load_failed: '\u52a0\u8f7d\u4eba\u8a2d\u5931\u6557',
|
||||
personality_cleared: '\u4eba\u8a2d\u5df2\u6e05\u7a7a',
|
||||
personality_set: '\u7576\u524d\u4eba\u8a2d\uff1a',
|
||||
failed_colon: '\u5931\u6557\uff1a',
|
||||
// ui.js
|
||||
no_workspace: '\u672a\u9078\u64c7\u5de5\u4f5c\u5340',
|
||||
// workspace.js
|
||||
unsaved_confirm: '\u9810\u89bd\u5340\u6709\u672a\u5132\u5b58\u4fee\u6539\uff0c\u8981\u653e\u68c4\u66f4\u6539\u5e76\u7e7c\u7e8c\u8df3\u8ee2\u55ce\uff1f',
|
||||
save: '\u5132\u5b58',
|
||||
edit: '\u7de8\u8f2f',
|
||||
save_title: '\u5132\u5b58\u4fee\u6539',
|
||||
edit_title: '\u7de8\u8f2f\u6b64\u6587\u4ef6',
|
||||
saved: '\u5df2\u5132\u5b58',
|
||||
save_failed: '\u5132\u5b58\u5931\u6557\uff1a',
|
||||
image_load_failed: '\u5716\u7247\u52a0\u8f09\u5931\u6557',
|
||||
file_open_failed: '\u7121\u6cd5\u6253\u958b\u6587\u4ef6',
|
||||
downloading: (name) => `\u6b63\u5728\u4e0b\u8f09 ${name}...`,
|
||||
double_click_rename: '\u96d9\u64ca\u91cd\u547d\u540d',
|
||||
renamed_to: '\u5df2\u91cd\u547d\u540d\u70ba ',
|
||||
rename_failed: '\u91cd\u547d\u540d\u5931\u6557\uff1a',
|
||||
delete_title: '\u522a\u9664',
|
||||
delete_confirm: (name) => `\u8981\u522a\u9664 ${name} \u55ce\uff1f`,
|
||||
deleted: '\u5df2\u522a\u9664 ',
|
||||
delete_failed: '\u522a\u9664\u5931\u6557\uff1a',
|
||||
new_file_prompt: '\u65b0\u6587\u4ef6\u540d\uff08\u4f8b\u5982 notes.md\uff09\uff1a',
|
||||
created: '\u5df2\u5275\u5efa ',
|
||||
create_failed: '\u5275\u5efa\u5931\u6557\uff1a',
|
||||
new_folder_prompt: '\u65b0\u6587\u4ef6\u593e\u540d\u7a31\uff1a',
|
||||
folder_created: '\u5df2\u5275\u5efa\u6587\u4ef6\u593e ',
|
||||
folder_create_failed: '\u5275\u5efa\u6587\u4ef6\u593e\u5931\u6557\uff1a',
|
||||
remove_title: '\u79fb\u9664',
|
||||
empty_dir: '(\u7a7a)',
|
||||
upload_failed: '\u4e0a\u50b3\u5931\u6557\uff1a',
|
||||
all_uploads_failed: (n) => `${n} \u500b\u6587\u4ef6\u5168\u90e8\u4e0a\u50b3\u5931\u6557`,
|
||||
// settings panel
|
||||
settings_title: '\u8a2d\u5b9a',
|
||||
settings_save_btn: '\u5132\u5b58\u8a2d\u5b9a',
|
||||
settings_label_model: '\u9ed8\u8a8d\u6a21\u578b',
|
||||
settings_label_send_key: '\u767c\u9001\u5feb\u6377\u9375',
|
||||
settings_label_theme: '\u4e3b\u984c',
|
||||
settings_label_language: '\u8a9d\u8a00',
|
||||
settings_label_token_usage: '\u986f\u793a token \u7528\u91cf',
|
||||
settings_label_cli_sessions: '\u986f\u793a CLI \u6703\u8a71',
|
||||
settings_label_sync_insights: '\u540c\u6b65\u5230 insights',
|
||||
settings_label_check_updates: '\u6aa2\u67e5\u66f4\u65b0',
|
||||
settings_label_bot_name: '\u52a9\u624b\u540d\u7a31',
|
||||
settings_label_password: '\u8a2a\u8aad\u5bc6\u78bc',
|
||||
settings_saved: '\u8a2d\u5b9a\u5df2\u5132\u5b58',
|
||||
settings_save_failed: '\u5132\u5b58\u5931\u6557\uff1a',
|
||||
settings_load_failed: '\u8a2d\u5b9a\u52a0\u8f09\u5931\u6557\uff1a',
|
||||
settings_saved_pw: '\u8a2d\u5b9a\u5df2\u5132\u5b58\uff08\u5bc6\u78bc\u5df2\u8a2d\u5b9a\u2014\u73fe\u5728\u9700\u8981\u767b\u5f55\uff09',
|
||||
// login page
|
||||
login_title: '\u767b\u5f55',
|
||||
login_subtitle: '\u8f38\u5165\u5bc6\u78bc\u7e7c\u7e8c\u4f7f\u7528',
|
||||
login_placeholder: '\u5bc6\u78bc',
|
||||
login_btn: '\u767b\u5f55',
|
||||
login_invalid_pw: '\u5bc6\u78bc\u932f\u8aa4',
|
||||
login_conn_failed: '\u9023\u63a5\u5931\u6557',
|
||||
// missing keys from English
|
||||
dialog_confirm_title: '確認操作',
|
||||
dialog_prompt_title: '輸入內容',
|
||||
dialog_confirm_btn: '確認',
|
||||
discard: '放棄',
|
||||
clear: '清空',
|
||||
create: '建立',
|
||||
remove: '移除',
|
||||
project_name_prompt: '專案名稱:',
|
||||
tab_chat: '\u804a\u5929',
|
||||
tab_memory: '\u8a18\u61b6',
|
||||
tab_skills: '\u6280\u80fd',
|
||||
tab_tasks: '\u4efb\u52d9',
|
||||
tab_todos: '\u5f85\u8e29',
|
||||
tab_workspaces: '\u5de5\u4f5c\u5340',
|
||||
new_conversation: '\u65b0\u5b58\u5c0d\u8a71',
|
||||
filter_conversations: '\u7b5c\u9078\u5b58\u5c0d\u8a71',
|
||||
scheduled_jobs: '\u5b58\u5287\u4efb\u52d9',
|
||||
new_job: '\u65b0\u4efb\u52d9',
|
||||
search_skills: '\u641c\u5c0b\u6280\u80fd',
|
||||
new_skill: '\u65b0\u6280\u80fd',
|
||||
save_skill: '\u5132\u5b58\u6280\u80fd',
|
||||
personal_memory: '\u500b\u4eba\u8a18\u61b6',
|
||||
current_task_list: '\u76ee\u524d\u4efb\u52d9\u6e05\u55ae',
|
||||
new_profile: '\u65b0\u914d\u7f6e\u6a94',
|
||||
transcript: '\u8a18\u9304',
|
||||
download_transcript: '\u4e0b\u8f09\u8a18\u9304',
|
||||
import: '\u5c0e\u5165',
|
||||
editing: '\u7de8\u8f2f\u4e2d',
|
||||
empty_title: '\u7a7a\u767c\u5b58\u7a7a\u9593',
|
||||
empty_subtitle: '\u9ede\u64ca\u4e0a\u65b9\u6309\u9215\u958b\u59cb\u5c0d\u8a71',
|
||||
cancel: '\u53d6\u6d88',
|
||||
loading: '\u52a0\u8f09\u4e2d',
|
||||
create_job: '\u5efa\u7acb\u4efb\u52d9',
|
||||
suggest_plan: '\u5efa\u8b70\u8a08\u5287',
|
||||
suggest_schedule: '\u5efa\u8b70\u6642\u7a0b',
|
||||
suggest_files: '\u5efa\u8b70\u6a94\u6848',
|
||||
sign_out: '\u767b\u51fa',
|
||||
password_placeholder: '\u5bc6\u78bc',
|
||||
disable_auth: '\u505c\u7528\u9a57\u8b49',
|
||||
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
|
||||
settings_label_notifications: '\u700f\u89bd\u901a\u77e5',
|
||||
settings_desc_sound: '\u52a9\u624b\u5b8c\u6210\u56de\u7b54\u6642\u64a9\u653e\u8072\u97f3\u3002',
|
||||
settings_desc_notifications: '\u7576\u5206\u9801\u5728\u5f8c\u81ea\u6642\uff0c\u6709\u56de\u7b54\u5b8c\u6210\u6e05\u55ae\u6703\u986f\u793a\u7cfb\u7d71\u901a\u77e5\u3002',
|
||||
settings_desc_token_usage: '\u5728\u52a9\u624b\u6bcf\u6b21\u56de\u7b54\u4e0b\u65b9\u986f\u793a Input/Output token \u6578\u91cf\u3002\u4e5f\u53ef\u4ee5\u7528 /usage \u5207\u63db\u3002',
|
||||
settings_desc_cli_sessions: '\u5c07 Hermes CLI (\u7684 state.db) \u4e2d\u7684\u6703\u8a71\u6dfb\u52a0\u5230\u6703\u8a71\u6e05\u55ae\u3002\u9ede\u64ca\u4e00\u500b CLI \u6703\u8a71\u5c07\u5c0e\u5165\u5b83\u7a0b\u5f0f\u4e26\u7e7c\u7e8c\u5b58\u5c0d\u8a71\u3002',
|
||||
settings_desc_sync_insights: '\u5c07 WebUI token \u4f7f\u7528\u60c5\u6cc1\u540c\u6b65\u5230 state.db\uff0c\u8a93 hermes /insights \u5305\u542b\u700f\u89bd\u5668\u6703\u8a71\u6578\u64da\u3002\u9810\u8a2d\u70b8\u555f\u7528\u3002',
|
||||
settings_desc_check_updates: '\u7576\u6709\u66f4\u65b0\u7684 WebUI \u6216\u52a9\u624b\u7248\u672c\u6642\u986f\u793a\u6a19\u8a18\u3002\u5c07\u5728\u5f8c\u81ea\u6b63\u5e38\u57f7\u884c Git-Fetch\u3002',
|
||||
settings_desc_bot_name: '\u52a9\u624b\u5728 UI \u4e2d\u7684\u986f\u793a\u540d\u7a31\u3002\u9810\u8a2d\u70b8\u7528\u6539\u3002',
|
||||
settings_desc_password: '\u8a2d\u5b9a WebUI \u767b\u5165\u5bc6\u78bc\u3002\u5047\u5982\u5df2\u8a2d\u7f6e\uff0c\u6bcf\u6b21\u52a0\u8f09\u90fd\u9700\u8981\u767b\u5165\u3002',
|
||||
settings_label_sound: '\u901a\u77e5\u8072\u97f3',
|
||||
// boot.js
|
||||
cancelling: '\u6b63\u5728\u53d6\u6d88...',
|
||||
cancel_failed: '\u53d6\u6d88\u5931\u6557\uff1a',
|
||||
mic_denied: '\u9ea6\u514b\u98a8\u8a2a\u554f\u88ab\u62d2\u7d75\uff0c\u8acb\u6aa2\u67e5\u700f\u89bd\u5668\u6b0a\u9650\u3002',
|
||||
mic_no_speech: '\u6c92\u6709\u6aa2\u6e2c\u5230\u8a71\u97f3\uff0c\u8acb\u518d\u5617\u4e00\u6b21\u3002',
|
||||
mic_network: '\u8a71\u97f3\u8b58\u5225\u76ee\u524d\u4e0d\u53ef\u7528\u3002',
|
||||
mic_error: '\u8a71\u97f3\u8f38\u5165\u51fa\u932f\uff1a',
|
||||
session_imported: '\u6703\u8a71\u5df2\u5c0e\u5165',
|
||||
import_failed: '\u5c0e\u5165\u5931\u6557\uff1a',
|
||||
import_invalid_json: 'JSON \u7121\u6548',
|
||||
image_pasted: '\u5df2\u7c98\u8cbc\u5716\u7247\uff1a',
|
||||
// messages.js
|
||||
edit_message: '\u7de8\u8f2f\u8a0a\u606f',
|
||||
regenerate: '\u91cd\u65b0\u751f\u6210\u56de\u8986',
|
||||
copy: '\u8907\u88fd',
|
||||
copied: '\u5df2\u8907\u88fd',
|
||||
// ui.js
|
||||
workspace_desc: '\u8acb\u9078\u64c7\u5de5\u4f5c\u5340\uff0c\u6216\u8f09\u5165\u65b0\u540d\u7a31\u5beb\u4e00\u500b',
|
||||
tab_profiles: '\u914d\u7f6e',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
69
static/icons.js
Normal file
69
static/icons.js
Normal file
@@ -0,0 +1,69 @@
|
||||
// ── Lucide icon library (self-hosted SVG paths, no CDN dependency) ──────────
|
||||
// All icons are 24×24 viewBox, stroke-based, currentColor.
|
||||
// Usage: li('folder') → returns a ready-to-embed SVG string
|
||||
// The returned SVG uses display:inline-block + vertical-align so it sits
|
||||
// neatly beside text in both HTML templates and innerHTML assignments.
|
||||
|
||||
const LI_PATHS = {
|
||||
// Navigation tabs
|
||||
'message-square': '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
|
||||
'calendar': '<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"/>',
|
||||
'layers': '<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>',
|
||||
'lightbulb': '<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"/>',
|
||||
'folder': '<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>',
|
||||
'list-todo': '<rect x="3" y="5" width="6" height="6" rx="1"/><path d="m3 17 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/>',
|
||||
// Editing / actions
|
||||
'pencil': '<path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>',
|
||||
'chevron-down': '<polyline points="6 9 12 15 18 9"/>',
|
||||
'download': '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/>',
|
||||
'upload': '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/>',
|
||||
'braces': '<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 3h1a2 2 0 0 1 2 2v5a2 2 0 0 0 2 2 2 2 0 0 0-2 2v5a2 2 0 0 1-2 2h-1"/>',
|
||||
'trash-2': '<path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/>',
|
||||
'settings': '<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>',
|
||||
'alert-triangle': '<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
|
||||
'refresh-cw': '<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>',
|
||||
'check': '<polyline points="20 6 9 17 4 12"/>',
|
||||
'lock': '<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>',
|
||||
'star': '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
|
||||
'x': '<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',
|
||||
'square': '<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/>',
|
||||
'plus': '<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>',
|
||||
'arrow-up': '<line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/>',
|
||||
'loader': '<line x1="12" y1="2" x2="12" y2="6"/><line x1="12" y1="18" x2="12" y2="22"/><line x1="4.93" y1="4.93" x2="7.76" y2="7.76"/><line x1="16.24" y1="16.24" x2="19.07" y2="19.07"/><line x1="2" y1="12" x2="6" y2="12"/><line x1="18" y1="12" x2="22" y2="12"/><line x1="4.93" y1="19.07" x2="7.76" y2="16.24"/><line x1="16.24" y1="7.76" x2="19.07" y2="4.93"/>',
|
||||
// Tool icons
|
||||
'terminal': '<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>',
|
||||
'file-text': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/>',
|
||||
'file-pen': '<path d="M12 22h6a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v10"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10.4 19.4 14 16l-4-1 .4 4.4z"/><path d="m14 16 1.5-1.5a2.12 2.12 0 0 1 3 3L17 19"/>',
|
||||
'search': '<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>',
|
||||
'globe': '<circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>',
|
||||
'play': '<polygon points="5 3 19 12 5 21 5 3"/>',
|
||||
'wrench': '<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>',
|
||||
'brain': '<path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24 2.5 2.5 0 0 1 1.98-3A2.5 2.5 0 0 1 9.5 2z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24 2.5 2.5 0 0 0-1.98-3A2.5 2.5 0 0 0 14.5 2z"/>',
|
||||
'book-open': '<path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/>',
|
||||
'clock': '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
|
||||
'bot': '<rect x="3" y="11" width="18" height="10" rx="2"/><circle cx="12" cy="5" r="2"/><path d="M12 7v4"/><line x1="8" y1="16" x2="8" y2="16"/><line x1="16" y1="16" x2="16" y2="16"/>',
|
||||
'eye': '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>',
|
||||
'shuffle': '<polyline points="16 3 21 3 21 8"/><line x1="4" y1="20" x2="21" y2="3"/><polyline points="21 16 21 21 16 21"/><line x1="15" y1="15" x2="21" y2="21"/><line x1="4" y1="4" x2="9" y2="9"/>',
|
||||
// File-type icons
|
||||
'image': '<rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>',
|
||||
'file-code': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><polyline points="10 13 8 15 10 17"/><polyline points="14 13 16 15 14 17"/>',
|
||||
'zap': '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
|
||||
// Suggestion buttons
|
||||
'clipboard-list': '<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="12" y2="16"/>',
|
||||
'map': '<polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/>',
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Lucide SVG string for the given icon name.
|
||||
* @param {string} name – key in LI_PATHS (e.g. 'folder', 'trash-2')
|
||||
* @param {number} size – width/height in px (default 16)
|
||||
* @returns {string} SVG element string ready for innerHTML
|
||||
*/
|
||||
function li(name, size = 16) {
|
||||
const p = LI_PATHS[name];
|
||||
if (!p) { console.warn('li(): unknown icon', name); return ''; }
|
||||
return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" `
|
||||
+ `stroke="currentColor" stroke-width="2" stroke-linecap="round" `
|
||||
+ `stroke-linejoin="round" aria-hidden="true" `
|
||||
+ `style="display:inline-block;vertical-align:-0.15em;flex-shrink:0">${p}</svg>`;
|
||||
}
|
||||
@@ -14,15 +14,15 @@
|
||||
<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.43.1</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.49.2</div></div></div>
|
||||
<div class="sidebar-nav">
|
||||
<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 active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat" data-i18n-title="tab_chat"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><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></button>
|
||||
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks" data-i18n-title="tab_tasks"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><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></button>
|
||||
<button class="nav-tab" data-panel="skills" data-label="Skills" onclick="switchPanel('skills')" title="Skills" data-i18n-title="tab_skills"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><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></button>
|
||||
<button class="nav-tab" data-panel="memory" data-label="Memory" onclick="switchPanel('memory')" title="Memory" data-i18n-title="tab_memory"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><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></button>
|
||||
<button class="nav-tab" data-panel="workspaces" data-label="Spaces" onclick="switchPanel('workspaces')" title="Spaces" data-i18n-title="tab_workspaces"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></button>
|
||||
<button class="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>
|
||||
<button class="nav-tab" data-panel="todos" data-label="Todos" onclick="switchPanel('todos')" title="Current task list" data-i18n-title="tab_todos"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="5" width="6" height="6" rx="1"/><path d="m3 17 2 2 4-4"/><path d="M13 6h8"/><path d="M13 12h8"/><path d="M13 18h8"/></svg></button>
|
||||
</div>
|
||||
<!-- Chat panel -->
|
||||
<div class="panel-view active" id="panelChat">
|
||||
@@ -87,7 +87,7 @@
|
||||
<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)" 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>
|
||||
<button class="cron-btn run" id="memEditBtn" style="padding:3px 8px;font-size:10px" onclick="toggleMemoryEdit()"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg> <span data-i18n="edit">Edit</span></button>
|
||||
</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) -->
|
||||
@@ -123,6 +123,8 @@
|
||||
<label style="display:flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);margin-bottom:8px;cursor:pointer">
|
||||
<input type="checkbox" id="profileFormClone" style="accent-color:var(--accent)"> Clone config from active profile
|
||||
</label>
|
||||
<input id="profileFormBaseUrl" placeholder="Base URL (optional, e.g. http://localhost:11434)" 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">
|
||||
<input id="profileFormApiKey" type="password" placeholder="API key (optional)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px;box-sizing:border-box">
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitProfileCreate()">Create</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleProfileForm()">Cancel</button>
|
||||
@@ -153,19 +155,19 @@
|
||||
</select>
|
||||
<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>
|
||||
<span style="opacity:.7;line-height:1"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></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>
|
||||
<span style="color:var(--muted);flex-shrink:0;line-height:1"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg></span>
|
||||
</div>
|
||||
<div class="ws-dropdown" id="wsDropdown"></div>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<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">↑ <span data-i18n="import">Import</span></button>
|
||||
<button class="sm-btn" id="btnDownload" title="Download as Markdown" data-i18n-title="download_transcript"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> <span data-i18n="transcript">Transcript</span></button>
|
||||
<button class="sm-btn" id="btnExportJSON" title="Export full session as JSON"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 3h1a2 2 0 0 1 2 2v5a2 2 0 0 0 2 2 2 2 0 0 0-2 2v5a2 2 0 0 1-2 2h-1"/></svg> JSON</button>
|
||||
<button class="sm-btn" id="btnImportJSON" title="Import session from JSON"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg> <span data-i18n="import">Import</span></button>
|
||||
<input type="file" id="importFileInput" accept=".json" style="display:none">
|
||||
</div>
|
||||
</div>
|
||||
@@ -179,25 +181,41 @@
|
||||
<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>
|
||||
<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> <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg></div>
|
||||
<div class="profile-dropdown" id="profileDropdown"></div>
|
||||
</div>
|
||||
<div class="chip model" id="modelChip">GPT-5.4 Mini</div>
|
||||
|
||||
<button class="chip clear-btn" id="btnClearConv" onclick="clearConversation()" title="Clear all messages in this conversation" style="display:none">🗑 <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>
|
||||
<button class="chip clear-btn" id="btnClearConv" onclick="clearConversation()" title="Clear all messages in this conversation" style="display:none"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg> <span data-i18n="copy">Clear</span></button>
|
||||
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings" data-i18n-title="settings_title"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg></button>
|
||||
<button class="chip mobile-files-btn" id="btnMobileFiles" onclick="toggleMobileFiles()" title="Files"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="messages" id="messages">
|
||||
<div class="empty-state" id="emptyState">
|
||||
<div class="empty-logo">🦉</div>
|
||||
<div class="empty-logo"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="80" height="80" aria-label="Hermes caduceus">
|
||||
<defs>
|
||||
<linearGradient id="hermes-gold" x1="0%" y1="0%" x2="0%" y2="100%">
|
||||
<stop offset="0%" style="stop-color:#F5C542;stop-opacity:1"/>
|
||||
<stop offset="100%" style="stop-color:#D4961C;stop-opacity:1"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="30" y="10" width="4" height="46" rx="2" fill="url(#hermes-gold)"/>
|
||||
<path d="M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20" fill="#F5C542" opacity="0.9"/>
|
||||
<path d="M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24" fill="#D4961C" opacity="0.8"/>
|
||||
<path d="M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20" fill="#F5C542" opacity="0.9"/>
|
||||
<path d="M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24" fill="#D4961C" opacity="0.8"/>
|
||||
<path d="M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42" fill="none" stroke="#F5C542" stroke-width="2.5" stroke-linecap="round"/>
|
||||
<path d="M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42" fill="none" stroke="#D4961C" stroke-width="2.5" stroke-linecap="round"/>
|
||||
<circle cx="32" cy="10" r="4" fill="#F5C542"/>
|
||||
<circle cx="32" cy="10" r="2" fill="#FFF8E1" opacity="0.7"/>
|
||||
</svg></div>
|
||||
<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?">📁 <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>
|
||||
<button class="suggestion" data-msg="What files are in this workspace?"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> <span data-i18n="suggest_files">What files are in this workspace?</span></button>
|
||||
<button class="suggestion" data-msg="What's on my schedule today?"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><line x1="9" y1="12" x2="15" y2="12"/><line x1="9" y1="16" x2="12" y2="16"/></svg> <span data-i18n="suggest_schedule">What's on my schedule today?</span></button>
|
||||
<button class="suggestion" data-msg="Help me plan a small project."><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/><line x1="8" y1="2" x2="8" y2="18"/><line x1="16" y1="6" x2="16" y2="22"/></svg> <span data-i18n="suggest_plan">Help me plan a small project.</span></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="messages-inner" id="msgInner"></div>
|
||||
@@ -211,10 +229,10 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="reconnect-banner" id="reconnectBanner">
|
||||
<span id="reconnectMsg">⚠ A response may have been in progress when you last left. Reload messages?</span>
|
||||
<span id="reconnectMsg"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="vertical-align:-1px"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg> A response may have been in progress when you last left. Reload messages?</span>
|
||||
<div style="display:flex;gap:8px;flex-shrink:0">
|
||||
<button class="reconnect-btn" onclick="dismissReconnect()">Dismiss</button>
|
||||
<button class="reconnect-btn" onclick="refreshSession()">↻ Reload</button>
|
||||
<button class="reconnect-btn" onclick="refreshSession()"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="vertical-align:-1px"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg> Reload</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="approval-card" id="approvalCard" role="alertdialog" aria-labelledby="approvalHeading" aria-describedby="approvalDesc">
|
||||
@@ -227,20 +245,20 @@
|
||||
<div class="approval-cmd" id="approvalCmd"></div>
|
||||
<div class="approval-btns">
|
||||
<button class="approval-btn once" id="approvalBtnOnce" onclick="respondApproval('once')" title="Allow this one command (Enter)" data-i18n-title="approval_btn_once_title">
|
||||
<span class="approval-btn-icon">✓</span>
|
||||
<span class="approval-btn-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg></span>
|
||||
<span class="approval-btn-label" data-i18n="approval_btn_once">Allow once</span>
|
||||
<kbd class="approval-kbd">↵</kbd>
|
||||
</button>
|
||||
<button class="approval-btn session" id="approvalBtnSession" onclick="respondApproval('session')" title="Allow for this session">
|
||||
<span class="approval-btn-icon">🔒</span>
|
||||
<span class="approval-btn-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg></span>
|
||||
<span class="approval-btn-label" data-i18n="approval_btn_session">Allow session</span>
|
||||
</button>
|
||||
<button class="approval-btn always" id="approvalBtnAlways" onclick="respondApproval('always')" title="Always allow this command pattern">
|
||||
<span class="approval-btn-icon">☆</span>
|
||||
<span class="approval-btn-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg></span>
|
||||
<span class="approval-btn-label" data-i18n="approval_btn_always">Always allow</span>
|
||||
</button>
|
||||
<button class="approval-btn deny" id="approvalBtnDeny" onclick="respondApproval('deny')" title="Deny — do not run this command">
|
||||
<span class="approval-btn-icon">✕</span>
|
||||
<span class="approval-btn-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span>
|
||||
<span class="approval-btn-label" data-i18n="approval_btn_deny">Deny</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -249,10 +267,10 @@
|
||||
<!-- Activity bar: shows tool progress / status above composer (not inside input) -->
|
||||
<div id="activityBar" style="display:none;max-width:800px;margin:0 auto;width:100%;padding:0 24px;">
|
||||
<div id="activityBarInner" style="display:flex;align-items:center;gap:8px;padding:6px 12px;border-radius:8px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);font-size:12px;color:var(--muted);animation:fadeIn .15s ease;">
|
||||
<span id="activityIcon" style="font-size:13px;opacity:.6">⚙</span>
|
||||
<span id="activityIcon" style="opacity:.6;line-height:1"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="12" y1="2" x2="12" y2="6"/><line x1="12" y1="18" x2="12" y2="22"/><line x1="4.93" y1="4.93" x2="7.76" y2="7.76"/><line x1="16.24" y1="16.24" x2="19.07" y2="19.07"/><line x1="2" y1="12" x2="6" y2="12"/><line x1="18" y1="12" x2="22" y2="12"/><line x1="4.93" y1="19.07" x2="7.76" y2="16.24"/><line x1="16.24" y1="7.76" x2="19.07" y2="4.93"/></svg></span>
|
||||
<span id="activityText" style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"></span>
|
||||
<button id="btnCancel" onclick="cancelStream()" style="display:none;background:rgba(233,69,96,.12);border:1px solid rgba(233,69,96,.35);color:#e94560;font-size:11px;font-weight:600;padding:3px 10px;border-radius:6px;cursor:pointer;flex-shrink:0;transition:background .15s" title="Cancel this task">■ Cancel</button>
|
||||
<button id="btnDismissStatus" onclick="setStatus('')" style="display:none;background:none;border:none;color:var(--muted);font-size:14px;line-height:1;cursor:pointer;padding:0 2px;opacity:.5;flex-shrink:0" title="Dismiss">✕</button>
|
||||
<button id="btnCancel" onclick="cancelStream()" style="display:none;background:rgba(233,69,96,.12);border:1px solid rgba(233,69,96,.35);color:#e94560;font-size:11px;font-weight:600;padding:3px 10px;border-radius:6px;cursor:pointer;flex-shrink:0;transition:background .15s;align-items:center;gap:4px" title="Cancel this task"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/></svg> Cancel</button>
|
||||
<button id="btnDismissStatus" onclick="setStatus('')" style="display:none;background:none;border:none;color:var(--muted);line-height:1;cursor:pointer;padding:0 2px;opacity:.5;flex-shrink:0" title="Dismiss"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
|
||||
<span id="activityDots" style="display:flex;gap:3px;align-items:center">
|
||||
<span style="width:4px;height:4px;border-radius:50%;background:var(--blue);opacity:.3;animation:pulse 1.4s ease-in-out infinite"></span>
|
||||
<span style="width:4px;height:4px;border-radius:50%;background:var(--blue);opacity:.3;animation:pulse 1.4s ease-in-out .22s infinite"></span>
|
||||
@@ -305,11 +323,12 @@
|
||||
<span>Workspace</span>
|
||||
<span class="git-badge" id="gitBadge" style="display:none"></span>
|
||||
<div class="panel-actions">
|
||||
<button class="panel-icon-btn" id="btnUpDir" title="Parent directory" onclick="navigateUp()" style="display:none">↑</button>
|
||||
<button class="panel-icon-btn" id="btnNewFile" title="New file" onclick="promptNewFile()">+</button>
|
||||
<button class="panel-icon-btn" id="btnNewFolder" title="New folder" onclick="promptNewFolder()">📁</button>
|
||||
<button class="panel-icon-btn" id="btnRefreshPanel" title="Refresh" onclick="if(S.session)loadDir(S.currentDir)">↻</button>
|
||||
<button class="panel-icon-btn close-preview" id="btnClearPreview" title="Close preview">✕</button>
|
||||
<button class="panel-icon-btn" id="btnUpDir" title="Parent directory" onclick="navigateUp()" style="display:none"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg></button>
|
||||
<button class="panel-icon-btn" id="btnNewFile" title="New file" onclick="promptNewFile()"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg></button>
|
||||
<button class="panel-icon-btn" id="btnNewFolder" title="New folder" onclick="promptNewFolder()"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg></button>
|
||||
<button class="panel-icon-btn" id="btnRefreshPanel" title="Refresh" onclick="if(S.session)loadDir(S.currentDir)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></button>
|
||||
<button class="panel-icon-btn close-preview" id="btnClearPreview" title="Close preview"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
|
||||
<button class="panel-icon-btn mobile-close-btn" onclick="closeMobileFiles()" title="Close" aria-label="Close workspace panel">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="breadcrumb-bar" id="breadcrumbBar" style="display:none"></div>
|
||||
@@ -318,8 +337,8 @@
|
||||
<div class="preview-path" id="previewPath">
|
||||
<span id="previewPathText"></span>
|
||||
<span class="preview-badge" id="previewBadge"></span>
|
||||
<button id="btnDownloadFile" class="panel-icon-btn" style="margin-left:auto;font-size:12px;width:auto;padding:2px 8px" onclick="downloadFile(_previewCurrentPath)" title="Download file to your computer">⇩ Download</button>
|
||||
<button id="btnEditFile" class="panel-icon-btn" style="font-size:12px;width:auto;padding:2px 8px;display:none" onclick="toggleEditMode()">✎ Edit</button>
|
||||
<button id="btnDownloadFile" class="panel-icon-btn" style="margin-left:auto;font-size:12px;width:auto;padding:2px 8px;display:inline-flex;align-items:center;gap:4px" onclick="downloadFile(_previewCurrentPath)" title="Download file to your computer"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg> Download</button>
|
||||
<button id="btnEditFile" class="panel-icon-btn" style="font-size:12px;width:auto;padding:2px 8px;display:none;align-items:center;gap:4px" onclick="toggleEditMode()"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/></svg> Edit</button>
|
||||
</div>
|
||||
<pre class="preview-code" id="previewCode"></pre>
|
||||
<div class="preview-img-wrap" id="previewImgWrap" style="display:none"><img class="preview-img" id="previewImg" src="" alt=""></div>
|
||||
@@ -328,11 +347,31 @@
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<div class="onboarding-overlay" id="onboardingOverlay" style="display:none" role="dialog" aria-modal="true" aria-labelledby="onboardingTitle">
|
||||
<div class="onboarding-card">
|
||||
<div class="onboarding-shell">
|
||||
<div class="onboarding-sidebar">
|
||||
<div class="onboarding-badge" data-i18n="onboarding_badge">FIRST RUN</div>
|
||||
<h2 id="onboardingTitle" data-i18n="onboarding_title">Welcome to Hermes Web UI</h2>
|
||||
<p id="onboardingLead" data-i18n="onboarding_lead">A quick guided setup will check your Hermes install, choose a workspace and model, and optionally protect the app with a password.</p>
|
||||
<div class="onboarding-steps" id="onboardingSteps"></div>
|
||||
</div>
|
||||
<div class="onboarding-main">
|
||||
<div class="onboarding-status" id="onboardingNotice"></div>
|
||||
<div class="onboarding-body" id="onboardingBody"></div>
|
||||
<div class="onboarding-actions">
|
||||
<button class="sm-btn" id="onboardingBackBtn" onclick="prevOnboardingStep()" style="display:none" data-i18n="onboarding_back">Back</button>
|
||||
<button class="sm-btn" id="onboardingNextBtn" onclick="nextOnboardingStep()" style="font-weight:700;color:var(--blue);border-color:rgba(124,185,255,.32)" data-i18n="onboarding_continue">Continue</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-overlay" id="settingsOverlay" style="display:none">
|
||||
<div class="settings-panel">
|
||||
<div class="settings-header">
|
||||
<h3 style="margin:0;font-size:16px" data-i18n="settings_title">Settings</h3>
|
||||
<button class="panel-icon-btn" onclick="_closeSettingsPanel()" title="Close">✕</button>
|
||||
<button class="panel-icon-btn" onclick="_closeSettingsPanel()" title="Close"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
|
||||
</div>
|
||||
<div class="settings-body">
|
||||
<div class="settings-field">
|
||||
@@ -386,9 +425,9 @@
|
||||
<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>
|
||||
<span data-i18n="settings_label_cli_sessions">Show agent sessions in sidebar</span>
|
||||
</label>
|
||||
<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 style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_cli_sessions">Merges sessions from Hermes agent platforms (CLI, Telegram, Discord, Slack, etc.) into the session list. Agent sessions are view-only.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
@@ -420,7 +459,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-overlay" id="mobileOverlay" onclick="closeMobileSidebar()"></div>
|
||||
<div class="mobile-overlay" id="mobileOverlay" onclick="closeMobileSidebar();closeMobileFiles()"></div>
|
||||
<nav class="mobile-bottom-nav" id="mobileBottomNav">
|
||||
<button class="mobile-nav-btn active" data-panel="chat" onclick="mobileSwitchPanel('chat')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
@@ -442,15 +481,37 @@
|
||||
<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 data-i18n="tab_workspaces">Spaces</span>
|
||||
</button>
|
||||
<button class="mobile-nav-btn" data-panel="profiles" onclick="mobileSwitchPanel('profiles')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><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 data-i18n="tab_profiles">Profiles</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script src="/static/i18n.js"></script>
|
||||
<script src="/static/icons.js"></script>
|
||||
<script src="/static/ui.js"></script>
|
||||
<script src="/static/workspace.js"></script>
|
||||
<script src="/static/sessions.js"></script>
|
||||
<script src="/static/commands.js"></script>
|
||||
<script src="/static/messages.js"></script>
|
||||
<script src="/static/panels.js"></script>
|
||||
<script src="/static/onboarding.js"></script>
|
||||
<script src="/static/boot.js"></script>
|
||||
<div class="app-dialog-overlay" id="appDialogOverlay" style="display:none" aria-hidden="true">
|
||||
<div class="app-dialog" id="appDialog" role="dialog" aria-modal="true" aria-labelledby="appDialogTitle" aria-describedby="appDialogDesc">
|
||||
<div class="app-dialog-header">
|
||||
<div class="app-dialog-title" id="appDialogTitle">Confirm action</div>
|
||||
<button class="app-dialog-close" id="appDialogClose" type="button" aria-label="Close dialog">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="app-dialog-desc" id="appDialogDesc"></div>
|
||||
<input class="app-dialog-input" id="appDialogInput" type="text" style="display:none">
|
||||
<div class="app-dialog-actions">
|
||||
<button class="app-dialog-btn" id="appDialogCancel" type="button" data-i18n="cancel">Cancel</button>
|
||||
<button class="app-dialog-btn confirm" id="appDialogConfirm" type="button">Confirm</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
55
static/login.js
Normal file
55
static/login.js
Normal file
@@ -0,0 +1,55 @@
|
||||
/* Login page — external script, no inline handlers.
|
||||
* Loaded by the /login route. Reads data attributes from the form for
|
||||
* i18n strings so the server does not need to inject JS literals.
|
||||
*/
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var form = document.getElementById('login-form');
|
||||
var input = document.getElementById('pw');
|
||||
|
||||
if (!form || !input) return;
|
||||
|
||||
var invalidPw = form.getAttribute('data-invalid-pw') || 'Invalid password';
|
||||
var connFailed = form.getAttribute('data-conn-failed') || 'Connection failed';
|
||||
|
||||
function showErr(msg) {
|
||||
var err = document.getElementById('err');
|
||||
if (err) { err.textContent = msg; err.style.display = 'block'; }
|
||||
}
|
||||
|
||||
function hideErr() {
|
||||
var err = document.getElementById('err');
|
||||
if (err) { err.style.display = 'none'; }
|
||||
}
|
||||
|
||||
async function doLogin(e) {
|
||||
e.preventDefault();
|
||||
var pw = input.value;
|
||||
hideErr();
|
||||
try {
|
||||
var res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password: pw }),
|
||||
credentials: 'include',
|
||||
});
|
||||
var data = {};
|
||||
try { data = await res.json(); } catch (_) {}
|
||||
if (res.ok && data.ok) {
|
||||
window.location.href = '/';
|
||||
} else {
|
||||
showErr(data.error || invalidPw);
|
||||
}
|
||||
} catch (ex) {
|
||||
showErr(connFailed);
|
||||
}
|
||||
}
|
||||
|
||||
form.addEventListener('submit', doLogin);
|
||||
|
||||
input.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
doLogin(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ async function send(){
|
||||
setStatus(S.pendingFiles&&S.pendingFiles.length?'Uploading…':'Sending…');
|
||||
let uploaded=[];
|
||||
try{uploaded=await uploadPendingFiles();}
|
||||
catch(e){if(!text){setStatus(`❌ ${e.message}`);return;}}
|
||||
catch(e){if(!text){setStatus(`Upload error: ${e.message}`);return;}}
|
||||
|
||||
let msgText=text;
|
||||
if(uploaded.length&&!msgText)msgText=`I've uploaded ${uploaded.length} file(s): ${uploaded.join(', ')}`;
|
||||
@@ -69,12 +69,12 @@ async function send(){
|
||||
markInflight(activeSid, streamId);
|
||||
// Show Cancel button
|
||||
const cancelBtn=$('btnCancel');
|
||||
if(cancelBtn) cancelBtn.style.display='';
|
||||
if(cancelBtn) cancelBtn.style.display='inline-flex';
|
||||
}catch(e){
|
||||
delete INFLIGHT[activeSid];
|
||||
stopApprovalPolling();
|
||||
// Only hide approval card if it belongs to the session that just finished
|
||||
if(!_approvalSessionId || _approvalSessionId===activeSid) hideApprovalCard();removeThinking();
|
||||
if(!_approvalSessionId || _approvalSessionId===activeSid) hideApprovalCard(true);removeThinking();
|
||||
S.messages.push({role:'assistant',content:`**Error:** ${e.message}`});
|
||||
renderMessages();setBusy(false);setStatus('Error: '+e.message);
|
||||
return;
|
||||
@@ -182,7 +182,7 @@ async function send(){
|
||||
delete INFLIGHT[activeSid];
|
||||
clearInflight();
|
||||
stopApprovalPolling();
|
||||
if(!_approvalSessionId || _approvalSessionId===activeSid) hideApprovalCard();
|
||||
if(!_approvalSessionId || _approvalSessionId===activeSid) hideApprovalCard(true);
|
||||
if(S.session&&S.session.session_id===activeSid){
|
||||
S.activeStreamId=null;
|
||||
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
|
||||
@@ -227,19 +227,19 @@ async function send(){
|
||||
// This is distinct from the SSE network 'error' event below.
|
||||
source.close();
|
||||
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
|
||||
if(S.session&&S.session.session_id===activeSid){
|
||||
S.activeStreamId=null;const _cbe=$('btnCancel');if(_cbe)_cbe.style.display='none';
|
||||
clearLiveToolCards();if(!assistantText)removeThinking();
|
||||
try{
|
||||
const d=JSON.parse(e.data);
|
||||
const isRateLimit=d.type==='rate_limit';
|
||||
const icon=isRateLimit?'⏱️':'⚠️';
|
||||
const label=isRateLimit?'Rate limit reached':'Error';
|
||||
const isAuthMismatch=d.type==='auth_mismatch';
|
||||
const label=isRateLimit?'Rate limit reached':isAuthMismatch?(typeof t==='function'?t('provider_mismatch_label'):'Provider mismatch'):'Error';
|
||||
const hint=d.hint?`\n\n*${d.hint}*`:'';
|
||||
S.messages.push({role:'assistant',content:`**${icon} ${label}:** ${d.message}${hint}`});
|
||||
S.messages.push({role:'assistant',content:`**${label}:** ${d.message}${hint}`});
|
||||
}catch(_){
|
||||
S.messages.push({role:'assistant',content:'**⚠️ Error:** An error occurred. Check server logs.'});
|
||||
S.messages.push({role:'assistant',content:'**Error:** An error occurred. Check server logs.'});
|
||||
}
|
||||
renderMessages();
|
||||
}else if(typeof trackBackgroundError==='function'){
|
||||
@@ -256,7 +256,7 @@ async function send(){
|
||||
try{
|
||||
const d=JSON.parse(e.data);
|
||||
// Show as a small inline notice, not a full error
|
||||
setStatus(`⚠️ ${d.message||'Warning'}`);
|
||||
setStatus(`${d.message||'Warning'}`);
|
||||
// If it's a fallback notice, show it briefly then clear
|
||||
if(d.type==='fallback') setTimeout(()=>setStatus(''),4000);
|
||||
}catch(_){}
|
||||
@@ -287,7 +287,7 @@ async function send(){
|
||||
source.addEventListener('cancel',e=>{
|
||||
source.close();
|
||||
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
|
||||
if(S.session&&S.session.session_id===activeSid){
|
||||
S.activeStreamId=null;const _cbc=$('btnCancel');if(_cbc)_cbc.style.display='none';
|
||||
}
|
||||
@@ -296,13 +296,14 @@ async function send(){
|
||||
S.messages.push({role:'assistant',content:'*Task cancelled.*'});renderMessages();
|
||||
}
|
||||
renderSessionList();
|
||||
if(!S.session||!INFLIGHT[S.session.session_id]){setBusy(false);setStatus('');}
|
||||
// Always clear busy state and status when cancel event is received
|
||||
setBusy(false);setStatus('');
|
||||
});
|
||||
}
|
||||
|
||||
function _handleStreamError(){
|
||||
delete INFLIGHT[activeSid];clearInflight();stopApprovalPolling();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard();
|
||||
if(!_approvalSessionId||_approvalSessionId===activeSid) hideApprovalCard(true);
|
||||
if(S.session&&S.session.session_id===activeSid){
|
||||
S.activeStreamId=null;const _cbe=$('btnCancel');if(_cbe)_cbe.style.display='none';
|
||||
clearLiveToolCards();if(!assistantText)removeThinking();
|
||||
@@ -342,11 +343,45 @@ function autoResize(){const el=$('msg');el.style.height='auto';el.style.height=M
|
||||
|
||||
// ── Approval polling ──
|
||||
let _approvalPollTimer = null;
|
||||
let _approvalHideTimer = null;
|
||||
let _approvalVisibleSince = 0;
|
||||
let _approvalSignature = '';
|
||||
const APPROVAL_MIN_VISIBLE_MS = 30000;
|
||||
|
||||
// showApprovalCard moved above respondApproval
|
||||
|
||||
function hideApprovalCard() {
|
||||
$("approvalCard").classList.remove("visible");
|
||||
function _clearApprovalHideTimer() {
|
||||
if (_approvalHideTimer) {
|
||||
clearTimeout(_approvalHideTimer);
|
||||
_approvalHideTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function _resetApprovalCardState() {
|
||||
_clearApprovalHideTimer();
|
||||
_approvalVisibleSince = 0;
|
||||
_approvalSignature = '';
|
||||
}
|
||||
|
||||
function hideApprovalCard(force=false) {
|
||||
const card = $("approvalCard");
|
||||
if (!card) return;
|
||||
if (!force && _approvalVisibleSince) {
|
||||
const remaining = APPROVAL_MIN_VISIBLE_MS - (Date.now() - _approvalVisibleSince);
|
||||
if (remaining > 0) {
|
||||
const scheduledSignature = _approvalSignature;
|
||||
_clearApprovalHideTimer();
|
||||
_approvalHideTimer = setTimeout(() => {
|
||||
_approvalHideTimer = null;
|
||||
if (_approvalSignature !== scheduledSignature) return;
|
||||
hideApprovalCard(true);
|
||||
}, remaining);
|
||||
return;
|
||||
}
|
||||
}
|
||||
_approvalSessionId = null;
|
||||
_resetApprovalCardState();
|
||||
card.classList.remove("visible");
|
||||
$("approvalCmd").textContent = "";
|
||||
$("approvalDesc").textContent = "";
|
||||
}
|
||||
@@ -357,15 +392,24 @@ let _approvalSessionId = null;
|
||||
function showApprovalCard(pending) {
|
||||
const keys = pending.pattern_keys || (pending.pattern_key ? [pending.pattern_key] : []);
|
||||
const desc = (pending.description || "") + (keys.length ? " [" + keys.join(", ") + "]" : "");
|
||||
const cmd = pending.command || "";
|
||||
const sig = JSON.stringify({desc, cmd, sid: pending._session_id || (S.session && S.session.session_id) || null});
|
||||
const card = $("approvalCard");
|
||||
const sameApproval = card.classList.contains("visible") && _approvalSignature === sig;
|
||||
$("approvalDesc").textContent = desc;
|
||||
$("approvalCmd").textContent = pending.command || "";
|
||||
$("approvalCmd").textContent = cmd;
|
||||
_approvalSessionId = pending._session_id || (S.session && S.session.session_id) || null;
|
||||
_approvalSignature = sig;
|
||||
if (!sameApproval) {
|
||||
_approvalVisibleSince = Date.now();
|
||||
_clearApprovalHideTimer();
|
||||
}
|
||||
// Re-enable buttons in case a previous approval disabled them
|
||||
["approvalBtnOnce","approvalBtnSession","approvalBtnAlways","approvalBtnDeny"].forEach(id => {
|
||||
const b = $(id); if (b) { b.disabled = false; b.classList.remove("loading"); }
|
||||
});
|
||||
const card = $("approvalCard");
|
||||
card.classList.add("visible");
|
||||
if (!sameApproval) card.scrollIntoView({block:"nearest", behavior:"smooth"});
|
||||
// Apply current locale to data-i18n elements inside the card
|
||||
if (typeof applyLocaleToDOM === "function") applyLocaleToDOM();
|
||||
// Focus Allow once button so Enter works immediately
|
||||
@@ -382,7 +426,7 @@ async function respondApproval(choice) {
|
||||
if (b) { b.disabled = true; if (b.id === "approvalBtn" + choice.charAt(0).toUpperCase() + choice.slice(1)) b.classList.add("loading"); }
|
||||
});
|
||||
_approvalSessionId = null;
|
||||
hideApprovalCard();
|
||||
hideApprovalCard(true);
|
||||
try {
|
||||
await api("/api/approval/respond", {
|
||||
method: "POST",
|
||||
@@ -395,7 +439,7 @@ function startApprovalPolling(sid) {
|
||||
stopApprovalPolling();
|
||||
_approvalPollTimer = setInterval(async () => {
|
||||
if (!S.busy || !S.session || S.session.session_id !== sid) {
|
||||
stopApprovalPolling(); hideApprovalCard(); return;
|
||||
stopApprovalPolling(); hideApprovalCard(true); return;
|
||||
}
|
||||
try {
|
||||
const data = await api("/api/approval/pending?session_id=" + encodeURIComponent(sid));
|
||||
@@ -441,4 +485,3 @@ function sendBrowserNotification(title,body){
|
||||
}
|
||||
|
||||
// ── Panel navigation (Chat / Tasks / Skills / Memory) ──
|
||||
|
||||
|
||||
306
static/onboarding.js
Normal file
306
static/onboarding.js
Normal file
@@ -0,0 +1,306 @@
|
||||
const ONBOARDING={status:null,step:0,steps:['system','setup','workspace','password','finish'],form:{provider:'openrouter',workspace:'',model:'',password:'',apiKey:'',baseUrl:''},active:false};
|
||||
|
||||
function _getOnboardingSetupProviders(){
|
||||
return (((ONBOARDING.status||{}).setup||{}).providers)||[];
|
||||
}
|
||||
|
||||
function _getOnboardingSetupProvider(id){
|
||||
return _getOnboardingSetupProviders().find(p=>p.id===id)||null;
|
||||
}
|
||||
|
||||
function _getOnboardingCurrentSetup(){
|
||||
return (((ONBOARDING.status||{}).setup||{}).current)||{};
|
||||
}
|
||||
|
||||
function _onboardingStepMeta(key){
|
||||
return ({
|
||||
system:{title:t('onboarding_step_system_title'),desc:t('onboarding_step_system_desc')},
|
||||
setup:{title:t('onboarding_step_setup_title'),desc:t('onboarding_step_setup_desc')},
|
||||
workspace:{title:t('onboarding_step_workspace_title'),desc:t('onboarding_step_workspace_desc')},
|
||||
password:{title:t('onboarding_step_password_title'),desc:t('onboarding_step_password_desc')},
|
||||
finish:{title:t('onboarding_step_finish_title'),desc:t('onboarding_step_finish_desc')}
|
||||
})[key];
|
||||
}
|
||||
|
||||
function _renderOnboardingSteps(){
|
||||
const wrap=$('onboardingSteps');
|
||||
if(!wrap)return;
|
||||
wrap.innerHTML='';
|
||||
ONBOARDING.steps.forEach((key,idx)=>{
|
||||
const meta=_onboardingStepMeta(key);
|
||||
const item=document.createElement('div');
|
||||
item.className='onboarding-step'+(idx===ONBOARDING.step?' active':idx<ONBOARDING.step?' done':'');
|
||||
item.innerHTML=`<div class="onboarding-step-index">${idx+1}</div><div><div class="onboarding-step-title">${meta.title}</div><div class="onboarding-step-desc">${meta.desc}</div></div>`;
|
||||
wrap.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function _setOnboardingNotice(msg,kind='info'){
|
||||
const el=$('onboardingNotice');
|
||||
if(!el)return;
|
||||
if(!msg){el.style.display='none';el.textContent='';el.className='onboarding-status';return;}
|
||||
el.style.display='block';
|
||||
el.className='onboarding-status '+kind;
|
||||
el.textContent=msg;
|
||||
}
|
||||
|
||||
function _getOnboardingWorkspaceChoices(){
|
||||
const items=((ONBOARDING.status||{}).workspaces||{}).items||[];
|
||||
return items.length?items:[{name:'Home',path:ONBOARDING.form.workspace||''}];
|
||||
}
|
||||
|
||||
function _getOnboardingProviderModelChoices(){
|
||||
const provider=_getOnboardingSetupProvider(ONBOARDING.form.provider);
|
||||
return provider?(provider.models||[]):[];
|
||||
}
|
||||
|
||||
function _getOnboardingSelectedModel(){
|
||||
return ONBOARDING.form.model||'';
|
||||
}
|
||||
|
||||
function _renderOnboardingModelField(){
|
||||
const choices=_getOnboardingProviderModelChoices();
|
||||
if(ONBOARDING.form.provider==='custom'){
|
||||
return `<label class="onboarding-field"><span>${t('onboarding_model_label')}</span><input id="onboardingModelInput" value="${esc(_getOnboardingSelectedModel())}" placeholder="${t('onboarding_custom_model_placeholder')}" oninput="ONBOARDING.form.model=this.value"></label><p class="onboarding-copy">${t('onboarding_custom_model_help')}</p>`;
|
||||
}
|
||||
const options=choices.map(m=>`<option value="${esc(m.id)}">${esc(m.label)}</option>`).join('');
|
||||
return `<label class="onboarding-field"><span>${t('onboarding_model_label')}</span><select id="onboardingModelSelect" onchange="ONBOARDING.form.model=this.value">${options}</select></label><p class="onboarding-copy">${t('onboarding_workspace_help')}</p>`;
|
||||
}
|
||||
|
||||
function _providerStatusLabel(system){
|
||||
if(system.chat_ready) return t('onboarding_check_provider_ready');
|
||||
if(system.provider_configured) return t('onboarding_check_provider_partial');
|
||||
return t('onboarding_check_provider_pending');
|
||||
}
|
||||
|
||||
function _renderOnboardingBody(){
|
||||
const body=$('onboardingBody');
|
||||
if(!body||!ONBOARDING.status)return;
|
||||
const key=ONBOARDING.steps[ONBOARDING.step];
|
||||
const system=ONBOARDING.status.system||{};
|
||||
const settings=ONBOARDING.status.settings||{};
|
||||
const setup=ONBOARDING.status.setup||{};
|
||||
const nextBtn=$('onboardingNextBtn');
|
||||
const backBtn=$('onboardingBackBtn');
|
||||
if(backBtn) backBtn.style.display=ONBOARDING.step>0?'':'none';
|
||||
if(nextBtn) nextBtn.textContent=key==='finish'?t('onboarding_open'):t('onboarding_continue');
|
||||
|
||||
if(key==='system'){
|
||||
const hermesOk=system.hermes_found&&system.imports_ok;
|
||||
const setupOk=!!system.chat_ready;
|
||||
_setOnboardingNotice(system.provider_note|| (setupOk?t('onboarding_notice_system_ready'):t('onboarding_notice_system_unavailable')),setupOk?'success':(hermesOk?'info':'warn'));
|
||||
body.innerHTML=`
|
||||
<div class="onboarding-panel-grid">
|
||||
<div class="onboarding-check ${hermesOk?'ok':'warn'}"><strong>${t('onboarding_check_agent')}</strong><span>${hermesOk?t('onboarding_check_agent_ready'):t('onboarding_check_agent_missing')}</span></div>
|
||||
<div class="onboarding-check ${(setupOk?'ok':system.provider_configured?'warn':'muted')}"><strong>${t('onboarding_check_provider')}</strong><span>${_providerStatusLabel(system)}</span></div>
|
||||
<div class="onboarding-check ${(settings.password_enabled?'ok':'muted')}"><strong>${t('onboarding_check_password')}</strong><span>${settings.password_enabled?t('onboarding_check_password_enabled'):t('onboarding_check_password_disabled')}</span></div>
|
||||
</div>
|
||||
<div class="onboarding-copy">
|
||||
<p><strong>${t('onboarding_config_file')}</strong> ${esc(system.config_path||t('onboarding_unknown'))}</p>
|
||||
<p><strong>${t('onboarding_env_file')}</strong> ${esc(system.env_path||t('onboarding_unknown'))}</p>
|
||||
<p>${esc(system.provider_note||'')}</p>
|
||||
${system.current_provider?`<p><strong>${t('onboarding_current_provider')}</strong> ${esc(system.current_provider)}${system.current_model?` — ${esc(system.current_model)}`:''}</p>`:''}
|
||||
${system.current_base_url?`<p><strong>${t('onboarding_base_url_label')}</strong> ${esc(system.current_base_url)}</p>`:''}
|
||||
${system.missing_modules&&system.missing_modules.length?`<p><strong>${t('onboarding_missing_imports')}</strong> ${esc(system.missing_modules.join(', '))}</p>`:''}
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
if(key==='setup'){
|
||||
const providers=_getOnboardingSetupProviders();
|
||||
const options=providers.map(p=>`<option value="${esc(p.id)}">${esc(p.label)}${p.quick?' — '+esc(t('onboarding_quick_setup_badge')):''}</option>`).join('');
|
||||
const provider=_getOnboardingSetupProvider(ONBOARDING.form.provider)||providers[0]||null;
|
||||
const showBaseUrl=provider&&provider.requires_base_url;
|
||||
const keyHelp=provider?`${t('onboarding_api_key_help_prefix')} ${esc(provider.env_var)}.`:'';
|
||||
_setOnboardingNotice(system.chat_ready?t('onboarding_notice_setup_already_ready'):t('onboarding_notice_setup_required'),system.chat_ready?'success':'info');
|
||||
body.innerHTML=`
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_provider_label')}</span>
|
||||
<select id="onboardingProviderSelect" onchange="syncOnboardingProvider(this.value)">${options}</select>
|
||||
</label>
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_api_key_label')}</span>
|
||||
<input id="onboardingApiKeyInput" type="password" value="${esc(ONBOARDING.form.apiKey||'')}" placeholder="${t('onboarding_api_key_placeholder')}" oninput="ONBOARDING.form.apiKey=this.value">
|
||||
</label>
|
||||
${showBaseUrl?`<label class="onboarding-field"><span>${t('onboarding_base_url_label')}</span><input id="onboardingBaseUrlInput" value="${esc(ONBOARDING.form.baseUrl||'')}" placeholder="${t('onboarding_base_url_placeholder')}" oninput="ONBOARDING.form.baseUrl=this.value"></label>`:''}
|
||||
<p class="onboarding-copy">${keyHelp}</p>
|
||||
${showBaseUrl?`<p class="onboarding-copy">${t('onboarding_base_url_help')}</p>`:''}
|
||||
<p class="onboarding-copy">${esc(setup.unsupported_note||'')||''}</p>`;
|
||||
const providerSel=$('onboardingProviderSelect');
|
||||
if(providerSel) providerSel.value=ONBOARDING.form.provider;
|
||||
return;
|
||||
}
|
||||
|
||||
if(key==='workspace'){
|
||||
const workspaceOptions=_getOnboardingWorkspaceChoices().map(ws=>`<option value="${esc(ws.path)}">${esc(ws.name||ws.path)} — ${esc(ws.path)}</option>`).join('');
|
||||
_setOnboardingNotice(t('onboarding_notice_workspace'), 'info');
|
||||
body.innerHTML=`
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_workspace_label')}</span>
|
||||
<select id="onboardingWorkspaceSelect" onchange="syncOnboardingWorkspaceSelect(this.value)">${workspaceOptions}</select>
|
||||
</label>
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_workspace_or_path')}</span>
|
||||
<input id="onboardingWorkspaceInput" value="${esc(ONBOARDING.form.workspace||'')}" placeholder="${t('onboarding_workspace_placeholder')}" oninput="ONBOARDING.form.workspace=this.value">
|
||||
</label>
|
||||
${_renderOnboardingModelField()}`;
|
||||
const wsSel=$('onboardingWorkspaceSelect');
|
||||
if(wsSel && ONBOARDING.form.workspace) wsSel.value=ONBOARDING.form.workspace;
|
||||
const modelSel=$('onboardingModelSelect');
|
||||
if(modelSel && ONBOARDING.form.model) modelSel.value=ONBOARDING.form.model;
|
||||
return;
|
||||
}
|
||||
|
||||
if(key==='password'){
|
||||
_setOnboardingNotice(settings.password_enabled?t('onboarding_notice_password_enabled'):t('onboarding_notice_password_recommended'), settings.password_enabled?'success':'info');
|
||||
body.innerHTML=`
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_password_label')}</span>
|
||||
<input id="onboardingPasswordInput" type="password" value="${esc(ONBOARDING.form.password||'')}" placeholder="${t('onboarding_password_placeholder')}" oninput="ONBOARDING.form.password=this.value">
|
||||
</label>
|
||||
<p class="onboarding-copy">${t('onboarding_password_help')}</p>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const provider=_getOnboardingSetupProvider(ONBOARDING.form.provider);
|
||||
_setOnboardingNotice(t('onboarding_notice_finish'), 'success');
|
||||
body.innerHTML=`
|
||||
<div class="onboarding-summary">
|
||||
<div><strong>${t('onboarding_provider_label')}</strong><span>${esc((provider&&provider.label)||ONBOARDING.form.provider||t('onboarding_not_set'))}</span></div>
|
||||
<div><strong>${t('onboarding_model_label')}</strong><span>${esc(_getOnboardingSelectedModel()||t('onboarding_not_set'))}</span></div>
|
||||
<div><strong>${t('onboarding_workspace_label')}</strong><span>${esc(ONBOARDING.form.workspace||t('onboarding_not_set'))}</span></div>
|
||||
<div><strong>${t('onboarding_check_password')}</strong><span>${ONBOARDING.form.password?t('onboarding_password_will_enable'):t('onboarding_password_skipped')}</span></div>
|
||||
</div>
|
||||
${ONBOARDING.form.baseUrl?`<p class="onboarding-copy"><strong>${t('onboarding_base_url_label')}</strong> ${esc(ONBOARDING.form.baseUrl)}</p>`:''}
|
||||
<p class="onboarding-copy">${t('onboarding_finish_help')}</p>`;
|
||||
}
|
||||
|
||||
function syncOnboardingWorkspaceSelect(value){
|
||||
ONBOARDING.form.workspace=value;
|
||||
const input=$('onboardingWorkspaceInput');
|
||||
if(input) input.value=value;
|
||||
}
|
||||
|
||||
function syncOnboardingProvider(value){
|
||||
const provider=_getOnboardingSetupProvider(value);
|
||||
ONBOARDING.form.provider=value;
|
||||
if(provider){
|
||||
if(!ONBOARDING.form.model || !_getOnboardingProviderModelChoices().some(m=>m.id===ONBOARDING.form.model) || value==='custom'){
|
||||
ONBOARDING.form.model=provider.default_model||'';
|
||||
}
|
||||
if(provider.requires_base_url){
|
||||
ONBOARDING.form.baseUrl=ONBOARDING.form.baseUrl||provider.default_base_url||'';
|
||||
}else{
|
||||
ONBOARDING.form.baseUrl=provider.default_base_url||'';
|
||||
}
|
||||
}
|
||||
_renderOnboardingBody();
|
||||
}
|
||||
|
||||
async function loadOnboardingWizard(){
|
||||
try{
|
||||
const status=await api('/api/onboarding/status');
|
||||
ONBOARDING.status=status;
|
||||
const current=((status.setup||{}).current)||{};
|
||||
ONBOARDING.form.provider=current.provider||'openrouter';
|
||||
ONBOARDING.form.workspace=(status.workspaces&&status.workspaces.last)||status.settings.default_workspace||'';
|
||||
ONBOARDING.form.model=status.settings.default_model||current.model||'openai/gpt-5.4-mini';
|
||||
ONBOARDING.form.password='';
|
||||
ONBOARDING.form.apiKey='';
|
||||
ONBOARDING.form.baseUrl=current.base_url||'';
|
||||
ONBOARDING.active=!status.completed;
|
||||
if(!ONBOARDING.active) return false;
|
||||
$('onboardingOverlay').style.display='flex';
|
||||
_renderOnboardingSteps();
|
||||
_renderOnboardingBody();
|
||||
return true;
|
||||
}catch(e){
|
||||
console.warn('onboarding status failed',e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function prevOnboardingStep(){
|
||||
if(ONBOARDING.step===0)return;
|
||||
ONBOARDING.step--;
|
||||
_renderOnboardingSteps();
|
||||
_renderOnboardingBody();
|
||||
}
|
||||
|
||||
async function _saveOnboardingProviderSetup(){
|
||||
const provider=(ONBOARDING.form.provider||'').trim();
|
||||
const model=(ONBOARDING.form.model||'').trim();
|
||||
const apiKey=(ONBOARDING.form.apiKey||'').trim();
|
||||
const baseUrl=(ONBOARDING.form.baseUrl||'').trim();
|
||||
const current=_getOnboardingCurrentSetup();
|
||||
const isUnchanged=current.provider===provider&&((current.model||'')===model)&&((current.base_url||'')===baseUrl);
|
||||
if(isUnchanged && !apiKey && (ONBOARDING.status.system||{}).chat_ready) return;
|
||||
const body={provider,model};
|
||||
if(apiKey) body.api_key=apiKey;
|
||||
if(baseUrl) body.base_url=baseUrl;
|
||||
const status=await api('/api/onboarding/setup',{method:'POST',body:JSON.stringify(body)});
|
||||
ONBOARDING.status=status;
|
||||
}
|
||||
|
||||
async function _saveOnboardingDefaults(){
|
||||
const workspace=(ONBOARDING.form.workspace||'').trim();
|
||||
const model=(ONBOARDING.form.model||'').trim();
|
||||
const password=(ONBOARDING.form.password||'').trim();
|
||||
if(!workspace) throw new Error(t('onboarding_error_choose_workspace'));
|
||||
if(!model) throw new Error(t('onboarding_error_choose_model'));
|
||||
const known=_getOnboardingWorkspaceChoices().some(ws=>ws.path===workspace);
|
||||
if(!known){
|
||||
await api('/api/workspaces/add',{method:'POST',body:JSON.stringify({path:workspace})});
|
||||
}
|
||||
const body={default_workspace:workspace,default_model:model};
|
||||
if(password) body._set_password=password;
|
||||
await api('/api/settings',{method:'POST',body:JSON.stringify(body)});
|
||||
localStorage.setItem('hermes-webui-model',model);
|
||||
if($('modelSelect')) _applyModelToDropdown(model,$('modelSelect'));
|
||||
}
|
||||
|
||||
async function _finishOnboarding(){
|
||||
await _saveOnboardingProviderSetup();
|
||||
await _saveOnboardingDefaults();
|
||||
const done=await api('/api/onboarding/complete',{method:'POST',body:'{}'});
|
||||
ONBOARDING.status=done;
|
||||
ONBOARDING.active=false;
|
||||
$('onboardingOverlay').style.display='none';
|
||||
showToast(t('onboarding_complete'));
|
||||
await loadWorkspaceList();
|
||||
if(typeof renderSessionList==='function') await renderSessionList();
|
||||
if(!S.session && typeof newSession==='function'){
|
||||
await newSession(true);
|
||||
await renderSessionList();
|
||||
}
|
||||
}
|
||||
|
||||
async function nextOnboardingStep(){
|
||||
try{
|
||||
if(ONBOARDING.steps[ONBOARDING.step]==='setup'){
|
||||
ONBOARDING.form.provider=(($('onboardingProviderSelect')||{}).value||ONBOARDING.form.provider||'').trim();
|
||||
ONBOARDING.form.apiKey=(($('onboardingApiKeyInput')||{}).value||'').trim();
|
||||
ONBOARDING.form.baseUrl=(($('onboardingBaseUrlInput')||{}).value||ONBOARDING.form.baseUrl||'').trim();
|
||||
if(!ONBOARDING.form.provider) throw new Error(t('onboarding_error_provider_required'));
|
||||
if(ONBOARDING.form.provider==='custom' && !ONBOARDING.form.baseUrl) throw new Error(t('onboarding_error_base_url_required'));
|
||||
}
|
||||
if(ONBOARDING.steps[ONBOARDING.step]==='workspace'){
|
||||
ONBOARDING.form.workspace=(($('onboardingWorkspaceInput')||{}).value||ONBOARDING.form.workspace||'').trim();
|
||||
ONBOARDING.form.model=(($('onboardingModelInput')||{}).value||($('onboardingModelSelect')||{}).value||ONBOARDING.form.model||'').trim();
|
||||
if(!ONBOARDING.form.workspace) throw new Error(t('onboarding_error_workspace_required'));
|
||||
if(!ONBOARDING.form.model) throw new Error(t('onboarding_error_model_required'));
|
||||
}
|
||||
if(ONBOARDING.steps[ONBOARDING.step]==='password'){
|
||||
ONBOARDING.form.password=(($('onboardingPasswordInput')||{}).value||'').trim();
|
||||
}
|
||||
if(ONBOARDING.step===ONBOARDING.steps.length-1){
|
||||
await _finishOnboarding();
|
||||
return;
|
||||
}
|
||||
ONBOARDING.step++;
|
||||
_renderOnboardingSteps();
|
||||
_renderOnboardingBody();
|
||||
}catch(e){
|
||||
_setOnboardingNotice(e.message||String(e),'warn');
|
||||
}
|
||||
}
|
||||
@@ -296,7 +296,8 @@ async function cronEditSave(id) {
|
||||
}
|
||||
|
||||
async function cronDelete(id) {
|
||||
if (!confirm('Delete this cron job? This cannot be undone.')) return;
|
||||
const _delCron=await showConfirmDialog({title:'Delete cron job',message:'This cannot be undone.',confirmLabel:'Delete',danger:true,focusCancel:true});
|
||||
if(!_delCron) return;
|
||||
try {
|
||||
await api('/api/crons/delete', {method:'POST', body: JSON.stringify({job_id: id})});
|
||||
showToast('Job deleted');
|
||||
@@ -339,7 +340,8 @@ function loadTodos() {
|
||||
|
||||
async function clearConversation() {
|
||||
if(!S.session) return;
|
||||
if(!confirm('Clear all messages in this conversation? This cannot be undone.')) return;
|
||||
const _clrMsg=await showConfirmDialog({title:'Clear conversation',message:'Clear all messages? This cannot be undone.',confirmLabel:'Clear',danger:true,focusCancel:true});
|
||||
if(!_clrMsg) return;
|
||||
try {
|
||||
const data = await api('/api/session/clear', {method:'POST',
|
||||
body: JSON.stringify({session_id: S.session.session_id})});
|
||||
@@ -644,7 +646,8 @@ async function addWorkspace(){
|
||||
}
|
||||
|
||||
async function removeWorkspace(path){
|
||||
if(!confirm(`Remove workspace "${path}"?`))return;
|
||||
const _rmWs=await showConfirmDialog({title:'Remove workspace',message:`Remove "${path}"?`,confirmLabel:'Remove',danger:true,focusCancel:true});
|
||||
if(!_rmWs) return;
|
||||
try{
|
||||
const data=await api('/api/workspaces/remove',{method:'POST',body:JSON.stringify({path})});
|
||||
_workspaceList=data.workspaces;
|
||||
@@ -841,6 +844,8 @@ function toggleProfileForm() {
|
||||
if (form.style.display !== 'none') {
|
||||
$('profileFormName').value = '';
|
||||
$('profileFormClone').checked = false;
|
||||
if ($('profileFormBaseUrl')) $('profileFormBaseUrl').value = '';
|
||||
if ($('profileFormApiKey')) $('profileFormApiKey').value = '';
|
||||
const errEl = $('profileFormError');
|
||||
if (errEl) errEl.style.display = 'none';
|
||||
$('profileFormName').focus();
|
||||
@@ -854,7 +859,15 @@ async function submitProfileCreate() {
|
||||
if (!name) { errEl.textContent = 'Name is required'; errEl.style.display = ''; return; }
|
||||
if (!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(name)) { errEl.textContent = 'Lowercase letters, numbers, hyphens, underscores only'; errEl.style.display = ''; return; }
|
||||
try {
|
||||
await api('/api/profile/create', { method: 'POST', body: JSON.stringify({ name, clone_config: cloneConfig }) });
|
||||
const baseUrl = (($('profileFormBaseUrl') && $('profileFormBaseUrl').value) || '').trim();
|
||||
const apiKey = (($('profileFormApiKey') && $('profileFormApiKey').value) || '').trim();
|
||||
if (baseUrl && !/^https?:\/\//.test(baseUrl)) {
|
||||
errEl.textContent = 'Base URL must start with http:// or https://'; errEl.style.display = ''; return;
|
||||
}
|
||||
const payload = { name, clone_config: cloneConfig };
|
||||
if (baseUrl) payload.base_url = baseUrl;
|
||||
if (apiKey) payload.api_key = apiKey;
|
||||
await api('/api/profile/create', { method: 'POST', body: JSON.stringify(payload) });
|
||||
toggleProfileForm();
|
||||
await loadProfilesPanel();
|
||||
showToast('Profile created: ' + name);
|
||||
@@ -862,7 +875,8 @@ async function submitProfileCreate() {
|
||||
}
|
||||
|
||||
async function deleteProfile(name) {
|
||||
if (!confirm(`Delete profile "${name}"? This removes all config, skills, memory, and sessions for this profile.`)) return;
|
||||
const _delProf=await showConfirmDialog({title:`Delete profile "${name}"?`,message:'This removes all config, skills, memory, and sessions for this profile.',confirmLabel:'Delete',danger:true,focusCancel:true});
|
||||
if(!_delProf) return;
|
||||
try {
|
||||
await api('/api/profile/delete', { method: 'POST', body: JSON.stringify({ name }) });
|
||||
await loadProfilesPanel();
|
||||
@@ -1099,6 +1113,8 @@ async function saveSettings(andClose){
|
||||
if(typeof applyBotName==='function') applyBotName();
|
||||
if(typeof setLocale==='function') setLocale(language);
|
||||
if(typeof applyLocaleToDOM==='function') applyLocaleToDOM();
|
||||
// Restart gateway SSE when agent session setting changes
|
||||
if(typeof startGatewaySSE==='function'){if(showCliSessions)startGatewaySSE();else if(typeof stopGatewaySSE==='function')stopGatewaySSE();}
|
||||
_settingsDirty=false; _settingsThemeOnOpen=theme;
|
||||
const bar=$('settingsUnsavedBar'); if(bar) bar.style.display='none';
|
||||
renderMessages();
|
||||
@@ -1121,7 +1137,8 @@ async function signOut(){
|
||||
}
|
||||
|
||||
async function disableAuth(){
|
||||
if(!confirm('Disable password protection? Anyone will be able to access this instance.')) return;
|
||||
const _disAuth=await showConfirmDialog({title:'Disable password protection',message:'Anyone will be able to access this instance.',confirmLabel:'Disable',danger:true,focusCancel:true});
|
||||
if(!_disAuth) return;
|
||||
try{
|
||||
await api('/api/settings',{method:'POST',body:JSON.stringify({_clear_password:true})});
|
||||
showToast('Auth disabled — password protection removed');
|
||||
|
||||
@@ -7,8 +7,169 @@ const ICONS={
|
||||
unarchive:'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><rect x="1.5" y="2" width="13" height="3" rx="1"/><path d="M2.5 5v8h11V5"/><polyline points="6.5,7 8,5.5 9.5,7"/></svg>',
|
||||
dup:'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><rect x="4.5" y="4.5" width="8.5" height="8.5" rx="1.5"/><path d="M3 11.5V3h8.5"/></svg>',
|
||||
trash:'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><path d="M3.5 4.5h9M6.5 4.5V3h3v1.5M4.5 4.5v8.5h7v-8.5"/><line x1="7" y1="7" x2="7" y2="11"/><line x1="9" y1="7" x2="9" y2="11"/></svg>',
|
||||
more:'<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" stroke="none"><circle cx="8" cy="3" r="1.25"/><circle cx="8" cy="8" r="1.25"/><circle cx="8" cy="13" r="1.25"/></svg>',
|
||||
};
|
||||
|
||||
|
||||
let _sessionActionMenu = null;
|
||||
let _sessionActionAnchor = null;
|
||||
let _sessionActionSessionId = null;
|
||||
|
||||
function closeSessionActionMenu(){
|
||||
if(_sessionActionMenu){
|
||||
_sessionActionMenu.remove();
|
||||
_sessionActionMenu = null;
|
||||
}
|
||||
if(_sessionActionAnchor){
|
||||
_sessionActionAnchor.classList.remove('active');
|
||||
const row=_sessionActionAnchor.closest('.session-item');
|
||||
if(row) row.classList.remove('menu-open');
|
||||
_sessionActionAnchor = null;
|
||||
}
|
||||
_sessionActionSessionId = null;
|
||||
}
|
||||
|
||||
function _positionSessionActionMenu(anchorEl){
|
||||
if(!_sessionActionMenu || !anchorEl) return;
|
||||
const rect=anchorEl.getBoundingClientRect();
|
||||
const menuW=Math.min(280, Math.max(220, _sessionActionMenu.scrollWidth || 220));
|
||||
let left=rect.right-menuW;
|
||||
if(left<8) left=8;
|
||||
if(left+menuW>window.innerWidth-8) left=window.innerWidth-menuW-8;
|
||||
_sessionActionMenu.style.left=left+'px';
|
||||
_sessionActionMenu.style.top='8px';
|
||||
const menuH=_sessionActionMenu.offsetHeight || 0;
|
||||
let top=rect.bottom+6;
|
||||
if(top+menuH>window.innerHeight-8 && rect.top>menuH+12){
|
||||
top=rect.top-menuH-6;
|
||||
}
|
||||
if(top<8) top=8;
|
||||
_sessionActionMenu.style.top=top+'px';
|
||||
}
|
||||
|
||||
function _buildSessionAction(label, meta, icon, onSelect, extraClass=''){
|
||||
const opt=document.createElement('button');
|
||||
opt.type='button';
|
||||
opt.className='ws-opt session-action-opt'+(extraClass?` ${extraClass}`:'');
|
||||
opt.innerHTML=
|
||||
`<span class="ws-opt-action">`
|
||||
+ `<span class="ws-opt-icon">${icon}</span>`
|
||||
+ `<span class="session-action-copy">`
|
||||
+ `<span class="ws-opt-name">${esc(label)}</span>`
|
||||
+ (meta?`<span class="session-action-meta">${esc(meta)}</span>`:'')
|
||||
+ `</span>`
|
||||
+ `</span>`;
|
||||
opt.onclick=async(e)=>{
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
await onSelect();
|
||||
};
|
||||
return opt;
|
||||
}
|
||||
|
||||
function _openSessionActionMenu(session, anchorEl){
|
||||
if(_sessionActionMenu && _sessionActionSessionId===session.session_id && _sessionActionAnchor===anchorEl){
|
||||
closeSessionActionMenu();
|
||||
return;
|
||||
}
|
||||
closeSessionActionMenu();
|
||||
const menu=document.createElement('div');
|
||||
menu.className='session-action-menu open';
|
||||
menu.appendChild(_buildSessionAction(
|
||||
session.pinned?'Unpin conversation':'Pin conversation',
|
||||
session.pinned?'Remove from the pinned section':'Keep this conversation at the top',
|
||||
session.pinned?ICONS.pin:ICONS.unpin,
|
||||
async()=>{
|
||||
closeSessionActionMenu();
|
||||
const newPinned=!session.pinned;
|
||||
try{
|
||||
await api('/api/session/pin',{method:'POST',body:JSON.stringify({session_id:session.session_id,pinned:newPinned})});
|
||||
session.pinned=newPinned;
|
||||
if(S.session&&S.session.session_id===session.session_id) S.session.pinned=newPinned;
|
||||
renderSessionList();
|
||||
}catch(err){showToast('Pin failed: '+err.message);}
|
||||
},
|
||||
session.pinned?'is-active':''
|
||||
));
|
||||
menu.appendChild(_buildSessionAction(
|
||||
'Move to project',
|
||||
session.project_id?'Change which project this conversation belongs to':'Assign this conversation to a project',
|
||||
ICONS.folder,
|
||||
async()=>{
|
||||
closeSessionActionMenu();
|
||||
_showProjectPicker(session, anchorEl);
|
||||
}
|
||||
));
|
||||
menu.appendChild(_buildSessionAction(
|
||||
session.archived?'Restore conversation':'Archive conversation',
|
||||
session.archived?'Bring this conversation back into the main list':'Hide this conversation until archived is shown',
|
||||
session.archived?ICONS.unarchive:ICONS.archive,
|
||||
async()=>{
|
||||
closeSessionActionMenu();
|
||||
try{
|
||||
await api('/api/session/archive',{method:'POST',body:JSON.stringify({session_id:session.session_id,archived:!session.archived})});
|
||||
session.archived=!session.archived;
|
||||
if(S.session&&S.session.session_id===session.session_id) S.session.archived=session.archived;
|
||||
await renderSessionList();
|
||||
showToast(session.archived?'Session archived':'Session restored');
|
||||
}catch(err){showToast('Archive failed: '+err.message);}
|
||||
}
|
||||
));
|
||||
menu.appendChild(_buildSessionAction(
|
||||
'Duplicate conversation',
|
||||
'Create a copy with the same workspace and model',
|
||||
ICONS.dup,
|
||||
async()=>{
|
||||
closeSessionActionMenu();
|
||||
try{
|
||||
const res=await api('/api/session/new',{method:'POST',body:JSON.stringify({workspace:session.workspace,model:session.model})});
|
||||
if(res.session){
|
||||
await api('/api/session/rename',{method:'POST',body:JSON.stringify({session_id:res.session.session_id,title:(session.title||'Untitled')+' (copy)'})});
|
||||
await loadSession(res.session.session_id);
|
||||
await renderSessionList();
|
||||
showToast('Session duplicated');
|
||||
}
|
||||
}catch(err){showToast('Duplicate failed: '+err.message);}
|
||||
}
|
||||
));
|
||||
menu.appendChild(_buildSessionAction(
|
||||
'Delete conversation',
|
||||
'Permanently remove this conversation',
|
||||
ICONS.trash,
|
||||
async()=>{
|
||||
closeSessionActionMenu();
|
||||
await deleteSession(session.session_id);
|
||||
},
|
||||
'danger'
|
||||
));
|
||||
document.body.appendChild(menu);
|
||||
_sessionActionMenu = menu;
|
||||
_sessionActionAnchor = anchorEl;
|
||||
_sessionActionSessionId = session.session_id;
|
||||
anchorEl.classList.add('active');
|
||||
const row=anchorEl.closest('.session-item');
|
||||
if(row) row.classList.add('menu-open');
|
||||
_positionSessionActionMenu(anchorEl);
|
||||
}
|
||||
|
||||
document.addEventListener('click',e=>{
|
||||
if(!_sessionActionMenu) return;
|
||||
if(_sessionActionMenu.contains(e.target)) return;
|
||||
if(_sessionActionAnchor && _sessionActionAnchor.contains(e.target)) return;
|
||||
closeSessionActionMenu();
|
||||
});
|
||||
document.addEventListener('scroll',e=>{
|
||||
if(!_sessionActionMenu) return;
|
||||
if(_sessionActionMenu.contains(e.target)) return;
|
||||
closeSessionActionMenu();
|
||||
}, true);
|
||||
document.addEventListener('keydown',e=>{
|
||||
if(e.key==='Escape' && _sessionActionMenu) closeSessionActionMenu();
|
||||
});
|
||||
window.addEventListener('resize',()=>{
|
||||
if(_sessionActionMenu && _sessionActionAnchor) _positionSessionActionMenu(_sessionActionAnchor);
|
||||
});
|
||||
|
||||
async function newSession(flash){
|
||||
MSG_QUEUE.length=0;updateQueueBadge();
|
||||
S.toolCalls=[];
|
||||
@@ -87,6 +248,35 @@ async function renderSessionList(){
|
||||
}catch(e){console.warn('renderSessionList',e);}
|
||||
}
|
||||
|
||||
// ── Gateway session SSE (real-time sync for agent sessions) ──
|
||||
let _gatewaySSE = null;
|
||||
|
||||
function startGatewaySSE(){
|
||||
stopGatewaySSE();
|
||||
if(!window._showCliSessions) return;
|
||||
try{
|
||||
_gatewaySSE = new EventSource('/api/sessions/gateway/stream');
|
||||
_gatewaySSE.addEventListener('sessions_changed', (ev) => {
|
||||
try{
|
||||
const data = JSON.parse(ev.data);
|
||||
if(data.sessions){
|
||||
renderSessionList(); // re-fetch and re-render
|
||||
}
|
||||
}catch(e){ /* ignore parse errors */ }
|
||||
});
|
||||
_gatewaySSE.onerror = () => {
|
||||
// EventSource auto-reconnects; no action needed
|
||||
};
|
||||
}catch(e){ /* SSE not available */ }
|
||||
}
|
||||
|
||||
function stopGatewaySSE(){
|
||||
if(_gatewaySSE){
|
||||
_gatewaySSE.close();
|
||||
_gatewaySSE = null;
|
||||
}
|
||||
}
|
||||
|
||||
let _searchDebounceTimer = null;
|
||||
let _contentSearchResults = []; // results from /api/sessions/search content scan
|
||||
|
||||
@@ -248,6 +438,7 @@ function renderSessionListFromCache(){
|
||||
const el=document.createElement('div');
|
||||
const isActive=S.session&&s.session_id===S.session.session_id;
|
||||
el.className='session-item'+(isActive?' active':'')+(isActive&&S.session&&S.session._flash?' new-flash':'')+(s.archived?' archived':'')+(s.is_cli_session?' cli-session':'');
|
||||
if(s.source_tag) el.dataset.source=s.source_tag;
|
||||
if(isActive&&S.session&&S.session._flash)delete S.session._flash;
|
||||
const rawTitle=s.title||'Untitled';
|
||||
const tags=(rawTitle.match(/#[\w-]+/g)||[]);
|
||||
@@ -314,7 +505,7 @@ function renderSessionListFromCache(){
|
||||
if(s.project_id){
|
||||
const proj=_allProjects.find(p=>p.project_id===s.project_id);
|
||||
if(proj){
|
||||
if(!isActive) el.style.borderLeftColor=proj.color||'var(--blue)';
|
||||
// project color shown via dot indicator, not left border
|
||||
const dot=document.createElement('span');
|
||||
dot.className='session-project-dot';
|
||||
dot.style.background=proj.color||'var(--blue)';
|
||||
@@ -323,65 +514,21 @@ function renderSessionListFromCache(){
|
||||
}
|
||||
}
|
||||
el.appendChild(title);
|
||||
// Action buttons overlay (appears on hover with gradient fade)
|
||||
const actions=document.createElement('div');
|
||||
actions.className='session-actions';
|
||||
// Pin toggle
|
||||
const pinBtn=document.createElement('button');
|
||||
pinBtn.className='act-pin'+(s.pinned?' pinned':'');
|
||||
pinBtn.innerHTML=s.pinned?ICONS.pin:ICONS.unpin;
|
||||
pinBtn.title=s.pinned?'Unpin':'Pin to top';
|
||||
pinBtn.onclick=async(e)=>{
|
||||
e.stopPropagation();e.preventDefault();
|
||||
const newPinned=!s.pinned;
|
||||
try{
|
||||
await api('/api/session/pin',{method:'POST',body:JSON.stringify({session_id:s.session_id,pinned:newPinned})});
|
||||
s.pinned=newPinned;
|
||||
if(S.session&&S.session.session_id===s.session_id) S.session.pinned=newPinned;
|
||||
renderSessionList();
|
||||
}catch(err){showToast('Pin failed: '+err.message);}
|
||||
const menuBtn=document.createElement('button');
|
||||
menuBtn.type='button';
|
||||
menuBtn.className='session-actions-trigger';
|
||||
menuBtn.title='Conversation actions';
|
||||
menuBtn.setAttribute('aria-haspopup','menu');
|
||||
menuBtn.setAttribute('aria-label','Conversation actions');
|
||||
menuBtn.innerHTML=ICONS.more;
|
||||
menuBtn.onclick=(e)=>{
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
_openSessionActionMenu(s, menuBtn);
|
||||
};
|
||||
actions.appendChild(pinBtn);
|
||||
// Move to project
|
||||
const move=document.createElement('button');
|
||||
move.className='act-move';move.innerHTML=ICONS.folder;move.title='Move to project';
|
||||
move.onclick=async(e)=>{e.stopPropagation();e.preventDefault();_showProjectPicker(s,move);};
|
||||
actions.appendChild(move);
|
||||
// Archive
|
||||
const archive=document.createElement('button');
|
||||
archive.className='act-archive';archive.innerHTML=s.archived?ICONS.unarchive:ICONS.archive;
|
||||
archive.title=s.archived?'Unarchive':'Archive';
|
||||
archive.onclick=async(e)=>{
|
||||
e.stopPropagation();e.preventDefault();
|
||||
try{
|
||||
await api('/api/session/archive',{method:'POST',body:JSON.stringify({session_id:s.session_id,archived:!s.archived})});
|
||||
s.archived=!s.archived;
|
||||
if(S.session&&S.session.session_id===s.session_id) S.session.archived=s.archived;
|
||||
await renderSessionList();
|
||||
showToast(s.archived?'Session archived':'Session restored');
|
||||
}catch(err){showToast('Archive failed: '+err.message);}
|
||||
};
|
||||
actions.appendChild(archive);
|
||||
// Duplicate
|
||||
const dup=document.createElement('button');
|
||||
dup.className='act-dup';dup.innerHTML=ICONS.dup;dup.title='Duplicate';
|
||||
dup.onclick=async(e)=>{
|
||||
e.stopPropagation();e.preventDefault();
|
||||
try{
|
||||
const res=await api('/api/session/new',{method:'POST',body:JSON.stringify({workspace:s.workspace,model:s.model})});
|
||||
if(res.session){
|
||||
await api('/api/session/rename',{method:'POST',body:JSON.stringify({session_id:res.session.session_id,title:(s.title||'Untitled')+' (copy)'})});
|
||||
await loadSession(res.session.session_id);await renderSessionList();
|
||||
showToast('Session duplicated');
|
||||
}
|
||||
}catch(err){showToast('Duplicate failed: '+err.message);}
|
||||
};
|
||||
actions.appendChild(dup);
|
||||
// Trash
|
||||
const trash=document.createElement('button');
|
||||
trash.className='act-trash';trash.innerHTML=ICONS.trash;trash.title='Delete';
|
||||
trash.onclick=async(e)=>{e.stopPropagation();e.preventDefault();await deleteSession(s.session_id);};
|
||||
actions.appendChild(trash);
|
||||
actions.appendChild(menuBtn);
|
||||
el.appendChild(actions);
|
||||
|
||||
// Use a click timer to distinguish single-click (navigate) from double-click (rename).
|
||||
@@ -417,7 +564,8 @@ function renderSessionListFromCache(){
|
||||
}
|
||||
|
||||
async function deleteSession(sid){
|
||||
if(!confirm('Delete this conversation?'))return;
|
||||
const _delSess=await showConfirmDialog({title:'Delete conversation',message:'This cannot be undone.',confirmLabel:'Delete',danger:true,focusCancel:true});
|
||||
if(!_delSess) return;
|
||||
try{
|
||||
await api('/api/session/delete',{method:'POST',body:JSON.stringify({session_id:sid})});
|
||||
}catch(e){setStatus(`Delete failed: ${e.message}`);return;}
|
||||
@@ -493,7 +641,7 @@ function _showProjectPicker(session, anchorEl){
|
||||
picker.remove();
|
||||
document.removeEventListener('click',close);
|
||||
// Prompt for name inline
|
||||
const name=prompt('Project name:');
|
||||
const name=await showPromptDialog({title:'New project',message:'',placeholder:'Project name',confirmLabel:t('create')});
|
||||
if(!name||!name.trim()) return;
|
||||
const color=PROJECT_COLORS[_allProjects.length%PROJECT_COLORS.length];
|
||||
const res=await api('/api/projects/create',{method:'POST',body:JSON.stringify({name:name.trim(),color})});
|
||||
@@ -532,7 +680,7 @@ function _showProjectPicker(session, anchorEl){
|
||||
setTimeout(()=>document.addEventListener('click',close),0);
|
||||
}
|
||||
|
||||
function _startProjectCreate(bar, addBtn){
|
||||
async function _startProjectCreate(bar, addBtn){
|
||||
const inp=document.createElement('input');
|
||||
inp.className='project-create-input';
|
||||
inp.placeholder='Project name';
|
||||
@@ -579,7 +727,8 @@ function _startProjectRename(proj, chip){
|
||||
}
|
||||
|
||||
async function _confirmDeleteProject(proj){
|
||||
if(!confirm('Delete project "'+proj.name+'"? Sessions will be unassigned but not deleted.')){return;}
|
||||
const _delProj=await showConfirmDialog({title:`Delete project "${proj.name}"?`,message:'Sessions will be unassigned but not deleted.',confirmLabel:'Delete',danger:true,focusCancel:true});
|
||||
if(!_delProj) return;
|
||||
await api('/api/projects/delete',{method:'POST',body:JSON.stringify({project_id:proj.project_id})});
|
||||
if(_activeProject===proj.project_id) _activeProject=null;
|
||||
await renderSessionList();
|
||||
|
||||
114
static/style.css
114
static/style.css
@@ -33,7 +33,7 @@
|
||||
/* ── Light theme: sidebar, roles, chips, active states ── */
|
||||
:root[data-theme="light"] .session-item{color:#5a544a;}
|
||||
:root[data-theme="light"] .session-item:hover{background:rgba(0,0,0,.06);color:#2c2825;}
|
||||
:root[data-theme="light"] .session-item.active{background:rgba(45,111,163,.1);color:#1a5a8a;border-left-color:#2d6fa3;}
|
||||
:root[data-theme="light"] .session-item.active{background:rgba(45,111,163,.1);color:#1a5a8a;}
|
||||
:root[data-theme="light"] .session-item.active .session-actions{background:linear-gradient(to right,transparent,rgba(228,224,216,.95) 12px);}
|
||||
:root[data-theme="light"] .session-pin-indicator{color:#996b15;}
|
||||
:root[data-theme="light"] .session-date-header.pinned{color:#996b15;}
|
||||
@@ -129,15 +129,24 @@
|
||||
.session-item:hover{background:var(--hover-bg);color:var(--text);}
|
||||
.session-item.active{background:rgba(232,160,48,0.12);color:#e8a030;border-left:2px solid #e8a030;padding-left:8px;}
|
||||
.session-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
/* ── Session action button overlay ── */
|
||||
.session-actions{position:absolute;right:0;top:0;bottom:0;display:flex;align-items:center;gap:2px;padding:0 6px 0 16px;background:linear-gradient(to right,transparent,var(--sidebar) 12px);opacity:0;pointer-events:none;transition:opacity .15s ease;border-radius:0 8px 8px 0;}
|
||||
.session-item:hover .session-actions{opacity:1;pointer-events:auto;}
|
||||
.session-item.active .session-actions{background:linear-gradient(to right,transparent,rgba(30,22,8,.95) 12px);}
|
||||
.session-actions button{background:none;border:none;color:var(--muted);cursor:pointer;padding:2px 3px;line-height:1;transition:color .12s;display:flex;align-items:center;}
|
||||
.session-actions button:hover{color:var(--text);}
|
||||
.session-actions .act-trash:hover{color:var(--accent);}
|
||||
.session-actions .act-pin.pinned{color:#f5c542;}
|
||||
.session-actions .act-pin.pinned:hover{color:#d4a017;}
|
||||
/* ── Session action trigger + dropdown (⋯ menu) ── */
|
||||
.session-actions{position:absolute;right:6px;top:50%;transform:translateY(-50%);display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .15s ease;}
|
||||
.session-item:hover .session-actions,.session-item:focus-within .session-actions,.session-item.menu-open .session-actions{opacity:1;pointer-events:auto;}
|
||||
.session-actions-trigger{width:26px;height:26px;border:1px solid transparent;border-radius:8px;background:transparent;color:var(--muted);cursor:pointer;padding:0;line-height:1;display:inline-flex;align-items:center;justify-content:center;transition:background .12s,color .12s,border-color .12s;}
|
||||
.session-actions-trigger:hover{background:var(--hover-bg);color:var(--text);}
|
||||
.session-actions-trigger.active{background:rgba(124,185,255,.1);border-color:rgba(124,185,255,.2);color:var(--text);}
|
||||
.session-actions-trigger svg{display:block;}
|
||||
.session-action-menu{display:block;position:fixed;left:0;top:0;right:auto;bottom:auto;min-width:220px;max-width:min(280px,calc(100vw - 16px));background:var(--surface);border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:999;overflow:hidden;max-height:320px;overflow-y:auto;}
|
||||
.session-action-menu.open{display:block;}
|
||||
.session-action-opt{width:100%;background:none;border:none;text-align:left;font:inherit;color:var(--text);flex-direction:row!important;gap:0!important;padding:0!important;}
|
||||
.session-action-opt .ws-opt-action{display:flex;flex-direction:row;align-items:center;gap:10px;width:100%;padding:10px 14px;}
|
||||
.session-action-opt .ws-opt-icon{color:var(--muted);transition:color .12s,opacity .12s;flex-shrink:0;display:flex;align-items:center;width:16px;}
|
||||
.session-action-opt:hover .ws-opt-icon{color:var(--text);opacity:1;}
|
||||
.session-action-copy{display:flex;flex-direction:column;gap:2px;min-width:0;}
|
||||
.session-action-meta{font-size:11px;color:var(--muted);line-height:1.3;white-space:normal;opacity:.72;}
|
||||
.session-action-opt.is-active{background:rgba(124,185,255,.1);}
|
||||
.session-action-opt.danger:hover{background:rgba(233,69,96,.08);}
|
||||
.session-action-opt.danger .ws-opt-icon,.session-action-opt.danger .ws-opt-name{color:var(--accent);}
|
||||
/* Hide overlay during inline rename */
|
||||
.session-item:has(.session-title-input) .session-actions{display:none;}
|
||||
@keyframes newflash{0%{background:rgba(124,185,255,0.22);color:var(--blue);}100%{background:transparent;color:var(--muted);}}
|
||||
@@ -148,8 +157,65 @@
|
||||
.session-date-header.pinned{color:#f5c542;}
|
||||
.session-date-caret{font-size:9px;transition:transform .2s;flex-shrink:0;display:inline-block;}
|
||||
.session-date-caret.collapsed{transform:rotate(-90deg);}
|
||||
|
||||
/* ── Shared app dialogs (replace native confirm/prompt) ── */
|
||||
.app-dialog-overlay{position:fixed;inset:0;background:rgba(7,12,19,.62);backdrop-filter:blur(6px);z-index:1100;display:none;align-items:center;justify-content:center;padding:24px;}
|
||||
.app-dialog{width:min(460px,100%);background:linear-gradient(180deg,rgba(21,31,45,.98),rgba(13,20,31,.98));border:1px solid rgba(124,185,255,.2);border-radius:18px;box-shadow:0 18px 60px rgba(0,0,0,.45);padding:18px 18px 16px;color:var(--text);}
|
||||
.app-dialog-header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:10px;}
|
||||
.app-dialog-title{font-size:16px;font-weight:700;letter-spacing:.01em;color:var(--text);}
|
||||
.app-dialog-close{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border:none;border-radius:10px;background:rgba(255,255,255,.04);color:var(--muted);cursor:pointer;transition:background .15s,color .15s;}
|
||||
.app-dialog-close:hover{background:rgba(255,255,255,.09);color:var(--text);}
|
||||
.app-dialog-desc{font-size:13px;line-height:1.6;color:var(--muted);white-space:pre-wrap;}
|
||||
.app-dialog-input{width:100%;margin-top:14px;padding:11px 12px;background:rgba(255,255,255,.04);border:1px solid var(--border2);border-radius:10px;color:var(--text);font-size:14px;outline:none;box-sizing:border-box;}
|
||||
.app-dialog-input:focus{border-color:rgba(124,185,255,.55);box-shadow:0 0 0 3px rgba(124,185,255,.12);}
|
||||
.app-dialog-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:18px;flex-wrap:wrap;}
|
||||
.app-dialog-btn{display:inline-flex;align-items:center;justify-content:center;min-width:104px;padding:10px 14px;border-radius:10px;border:1px solid var(--border2);background:rgba(255,255,255,.05);color:var(--text);font-size:13px;font-weight:600;cursor:pointer;transition:transform .15s,background .15s,border-color .15s;}
|
||||
.app-dialog-btn:hover{transform:translateY(-1px);background:rgba(255,255,255,.1);}
|
||||
.app-dialog-btn.confirm{border-color:rgba(124,185,255,.45);background:rgba(124,185,255,.14);color:var(--blue);}
|
||||
.app-dialog-btn.confirm:hover{background:rgba(124,185,255,.22);border-color:rgba(124,185,255,.65);}
|
||||
.app-dialog-btn.confirm.danger{border-color:rgba(233,69,96,.4);background:rgba(233,69,96,.14);color:var(--accent);}
|
||||
.app-dialog-btn.confirm.danger:hover{background:rgba(233,69,96,.22);border-color:rgba(233,69,96,.58);}
|
||||
.app-dialog-btn:focus-visible,.app-dialog-close:focus-visible{outline:2px solid rgba(124,185,255,.85);outline-offset:2px;}
|
||||
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:var(--surface);backdrop-filter:blur(12px);border:1px solid rgba(124,185,255,0.25);color:var(--text);font-size:13px;padding:10px 20px;border-radius:12px;pointer-events:none;opacity:0;transition:opacity .2s,transform .2s;z-index:100;box-shadow:0 4px 20px rgba(0,0,0,.3);letter-spacing:.01em;}
|
||||
.toast.show{opacity:1;transform:translateX(-50%) translateY(-2px);}
|
||||
.onboarding-overlay{position:fixed;inset:0;z-index:1050;background:rgba(7,12,19,.78);backdrop-filter:blur(8px);display:none;align-items:center;justify-content:center;padding:24px;}
|
||||
.onboarding-card{width:min(980px,100%);max-height:min(760px,94vh);overflow:auto;border:1px solid rgba(124,185,255,.16);border-radius:24px;background:linear-gradient(180deg,rgba(20,30,44,.98),rgba(11,17,27,.98));box-shadow:0 24px 80px rgba(0,0,0,.45);}
|
||||
.onboarding-shell{display:grid;grid-template-columns:minmax(240px,300px) minmax(0,1fr);}
|
||||
.onboarding-sidebar{padding:28px 24px;border-right:1px solid var(--border);background:linear-gradient(180deg,rgba(124,185,255,.08),rgba(124,185,255,.02));}
|
||||
.onboarding-sidebar h2{font-size:26px;line-height:1.15;margin-top:10px;margin-bottom:12px;letter-spacing:-.03em;}
|
||||
.onboarding-badge{display:inline-flex;padding:4px 10px;border-radius:999px;font-size:10px;font-weight:800;letter-spacing:.12em;background:rgba(124,185,255,.14);color:var(--blue);}
|
||||
.onboarding-sidebar p{font-size:13px;color:var(--muted);line-height:1.7;}
|
||||
.onboarding-steps{display:flex;flex-direction:column;gap:10px;margin-top:24px;}
|
||||
.onboarding-step{display:flex;gap:12px;align-items:flex-start;padding:10px 12px;border-radius:14px;border:1px solid transparent;background:rgba(255,255,255,.02);}
|
||||
.onboarding-step.active{border-color:rgba(124,185,255,.25);background:rgba(124,185,255,.08);}
|
||||
.onboarding-step.done{background:rgba(201,168,76,.08);}
|
||||
.onboarding-step-index{width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700;background:rgba(255,255,255,.08);color:var(--text);flex-shrink:0;}
|
||||
.onboarding-step.done .onboarding-step-index{background:rgba(201,168,76,.16);color:var(--gold);}
|
||||
.onboarding-step.active .onboarding-step-index{background:rgba(124,185,255,.18);color:var(--blue);}
|
||||
.onboarding-step-title{font-size:13px;font-weight:700;color:var(--text);}
|
||||
.onboarding-step-desc{font-size:11px;color:var(--muted);margin-top:2px;line-height:1.5;}
|
||||
.onboarding-main{padding:28px 28px 24px;display:flex;flex-direction:column;gap:18px;min-width:0;}
|
||||
.onboarding-status{display:none;padding:12px 14px;border-radius:12px;font-size:13px;line-height:1.6;border:1px solid var(--border2);background:rgba(255,255,255,.04);}
|
||||
.onboarding-status.info{color:var(--text);}
|
||||
.onboarding-status.success{color:var(--blue);border-color:rgba(124,185,255,.3);background:rgba(124,185,255,.08);}
|
||||
.onboarding-status.warn{color:var(--gold);border-color:rgba(201,168,76,.28);background:rgba(201,168,76,.08);}
|
||||
.onboarding-body{display:flex;flex-direction:column;gap:16px;}
|
||||
.onboarding-panel-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;}
|
||||
.onboarding-check{padding:14px;border-radius:14px;border:1px solid var(--border);background:rgba(255,255,255,.03);display:flex;flex-direction:column;gap:5px;}
|
||||
.onboarding-check strong{font-size:13px;color:var(--text);}
|
||||
.onboarding-check span{font-size:12px;color:var(--muted);line-height:1.5;}
|
||||
.onboarding-check.ok{border-color:rgba(124,185,255,.28);background:rgba(124,185,255,.08);}
|
||||
.onboarding-check.warn{border-color:rgba(201,168,76,.25);background:rgba(201,168,76,.08);}
|
||||
.onboarding-field{display:flex;flex-direction:column;gap:6px;}
|
||||
.onboarding-field span{font-size:12px;font-weight:700;color:var(--text);}
|
||||
.onboarding-field input,.onboarding-field select{margin-bottom:0;padding:10px 12px;border-radius:10px;font-size:13px;background:var(--input-bg);border:1px solid var(--border2);color:var(--text);}
|
||||
.onboarding-copy{font-size:12px;color:var(--muted);line-height:1.7;}
|
||||
.onboarding-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;}
|
||||
.onboarding-summary div{padding:14px;border-radius:14px;background:rgba(255,255,255,.03);border:1px solid var(--border);display:flex;flex-direction:column;gap:5px;}
|
||||
.onboarding-summary strong{font-size:12px;letter-spacing:.04em;text-transform:uppercase;color:var(--muted);}
|
||||
.onboarding-summary span{font-size:13px;color:var(--text);word-break:break-word;}
|
||||
.onboarding-actions{display:flex;justify-content:space-between;gap:10px;margin-top:auto;}
|
||||
.onboarding-actions .sm-btn{padding:10px 16px;}
|
||||
.reconnect-banner{display:none;background:var(--surface);border:1px solid rgba(201,168,76,0.4);border-radius:10px;padding:10px 16px;margin:10px auto;max-width:780px;font-size:13px;color:var(--gold);display:none;align-items:center;justify-content:space-between;gap:12px;}
|
||||
.reconnect-banner.visible{display:flex;}
|
||||
.reconnect-btn{padding:5px 12px;border-radius:7px;font-size:12px;font-weight:600;background:rgba(201,168,76,0.15);border:1px solid rgba(201,168,76,0.4);color:var(--gold);cursor:pointer;}
|
||||
@@ -342,6 +408,7 @@
|
||||
.panel-actions{display:flex;gap:4px;}
|
||||
.panel-icon-btn{width:24px;height:24px;background:none;border:none;color:var(--muted);cursor:pointer;border-radius:5px;font-size:13px;display:flex;align-items:center;justify-content:center;transition:all .15s;}
|
||||
.panel-icon-btn:hover{background:rgba(255,255,255,.08);color:var(--text);}
|
||||
.mobile-close-btn{display:none;}
|
||||
/* File row actions (shown on hover) */
|
||||
/* file-item-actions removed: delete button is now a flex child */
|
||||
.file-action-btn{width:20px;height:20px;background:rgba(0,0,0,.4);border:none;border-radius:4px;color:var(--muted);cursor:pointer;font-size:11px;display:flex;align-items:center;justify-content:center;}
|
||||
@@ -471,12 +538,26 @@
|
||||
.approval-btns{gap:6px;}
|
||||
.approval-btn{padding:8px 12px;font-size:12px;min-height:44px;}
|
||||
.approval-kbd{display:none;}
|
||||
.app-dialog-overlay{padding:12px;}
|
||||
.app-dialog{width:100%;padding:16px 16px 14px;border-radius:16px;}
|
||||
.app-dialog-actions{flex-direction:column-reverse;align-items:stretch;}
|
||||
.app-dialog-btn{width:100%;min-height:44px;}
|
||||
/* Tool cards */
|
||||
.tool-card{margin-left:0!important;font-size:12px;}
|
||||
/* Settings modal */
|
||||
.settings-panel{width:95vw;max-width:95vw;min-height:min(580px,88vh);max-height:92vh;}
|
||||
.onboarding-overlay{padding:12px;}
|
||||
.onboarding-shell{grid-template-columns:1fr;}
|
||||
.onboarding-sidebar{border-right:none;border-bottom:1px solid var(--border);padding:22px 18px;}
|
||||
.onboarding-main{padding:20px 18px 18px;}
|
||||
.onboarding-actions{flex-direction:column-reverse;}
|
||||
.onboarding-actions .sm-btn{width:100%;min-height:44px;}
|
||||
/* Login page responsive */
|
||||
.card{width:90vw;max-width:320px;padding:28px 24px;}
|
||||
/* Workspace panel mobile close button */
|
||||
.mobile-close-btn{display:inline-flex;}
|
||||
/* Profile dropdown — escape overflow-x:auto clipping context */
|
||||
.profile-dropdown{position:fixed;top:56px;right:8px;left:auto;max-width:calc(100vw - 16px);}
|
||||
}
|
||||
|
||||
/* ── Workspace dropdown (topbar) ── */
|
||||
@@ -825,13 +906,13 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
|
||||
.bg-error-banner{background:rgba(229,62,62,.15);border:1px solid rgba(229,62,62,.3);color:#fca5a5;padding:8px 16px;font-size:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;border-radius:0;}
|
||||
|
||||
/* ── CLI session items in sidebar ── */
|
||||
/* ── CLI / Agent session items in sidebar ── */
|
||||
.session-item.cli-session {
|
||||
border-left-color: var(--gold);
|
||||
padding-right: 36px; /* make room for session-actions overlay */
|
||||
padding-right: 40px; /* make room for the session actions trigger */
|
||||
}
|
||||
.session-item.cli-session::after {
|
||||
content: 'cli';
|
||||
content: attr(data-source);
|
||||
font-size: 9px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
@@ -845,3 +926,10 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
.session-item.cli-session:hover::after {
|
||||
display: none; /* hide badge on hover so session-actions icons are fully reachable */
|
||||
}
|
||||
/* Source-specific colors for gateway sessions */
|
||||
.session-item.cli-session[data-source="telegram"] { border-left-color: #0088cc; }
|
||||
.session-item.cli-session[data-source="telegram"]::after { color: #0088cc; }
|
||||
.session-item.cli-session[data-source="discord"] { border-left-color: #5865F2; }
|
||||
.session-item.cli-session[data-source="discord"]::after { color: #5865F2; }
|
||||
.session-item.cli-session[data-source="slack"] { border-left-color: #4A154B; }
|
||||
.session-item.cli-session[data-source="slack"]::after { color: #4A154B; }
|
||||
|
||||
233
static/ui.js
233
static/ui.js
@@ -45,6 +45,8 @@ async function populateModelDropdown(){
|
||||
try{
|
||||
const data=await fetch(new URL('/api/models',location.origin).href,{credentials:'include'}).then(r=>r.json());
|
||||
if(!data.groups||!data.groups.length) return; // keep HTML defaults
|
||||
// Store active provider globally so the send path can warn on mismatch
|
||||
window._activeProvider=data.active_provider||null;
|
||||
// Clear existing options
|
||||
sel.innerHTML='';
|
||||
_dynamicModelLabels={};
|
||||
@@ -70,6 +72,32 @@ async function populateModelDropdown(){
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the given model ID belongs to a different provider than the one
|
||||
* currently configured in Hermes. Returns a warning string if mismatched,
|
||||
* or null if the selection looks compatible.
|
||||
*
|
||||
* Provider detection is intentionally loose — we compare the model's slash
|
||||
* prefix (e.g. "openai/" from "openai/gpt-4o") against the active provider
|
||||
* name. Custom/local endpoints report active_provider='custom' or the
|
||||
* base_url hostname and we skip the check to avoid false positives.
|
||||
*/
|
||||
function _checkProviderMismatch(modelId){
|
||||
const ap=(window._activeProvider||'').toLowerCase();
|
||||
if(!ap||ap==='custom'||ap==='openrouter') return null; // can't reliably check
|
||||
const slash=modelId.indexOf('/');
|
||||
if(slash<0) return null; // bare model name, no provider prefix
|
||||
const modelProvider=modelId.substring(0,slash).toLowerCase();
|
||||
// Normalise common aliases
|
||||
const aliases={'claude':'anthropic','gpt':'openai','gemini':'google'};
|
||||
const norm=p=>aliases[p]||p;
|
||||
if(norm(modelProvider)!==norm(ap)){
|
||||
return (window.t?window.t('provider_mismatch_warning',modelId,ap):
|
||||
`"${modelId}" may not work with your configured provider (${ap}). Send anyway or run \`hermes model\` to switch.`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Scroll pinning ──────────────────────────────────────────────────────────
|
||||
// When streaming, auto-scroll only if the user hasn't manually scrolled up.
|
||||
// Once the user scrolls back to within 80px of the bottom, re-pin.
|
||||
@@ -135,6 +163,10 @@ function getModelLabel(modelId){
|
||||
|
||||
function renderMd(raw){
|
||||
let s=raw||'';
|
||||
// Pre-pass: decode HTML entities first so markdown processing works correctly.
|
||||
// This prevents double-escaping when LLM outputs entities like < > &
|
||||
const decode=s=>s.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&').replace(/"/g,'"').replace(/'/g,"'");
|
||||
s=decode(s);
|
||||
// Pre-pass: convert safe inline HTML tags the model may emit into their
|
||||
// markdown equivalents so the pipeline can render them correctly.
|
||||
// Only runs OUTSIDE fenced code blocks and backtick spans (stash + restore).
|
||||
@@ -207,8 +239,8 @@ function renderMd(raw){
|
||||
if(rows.length<2)return block;
|
||||
const isSep=r=>/^\|[\s|:-]+\|$/.test(r.trim());
|
||||
if(!isSep(rows[1]))return block;
|
||||
const parseRow=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<td>${esc(c.trim())}</td>`).join('');
|
||||
const parseHeader=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<th>${esc(c.trim())}</th>`).join('');
|
||||
const parseRow=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<td>${inlineMd(c.trim())}</td>`).join('');
|
||||
const parseHeader=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<th>${inlineMd(c.trim())}</th>`).join('');
|
||||
const header=`<tr>${parseHeader(rows[0])}</tr>`;
|
||||
const body=rows.slice(2).map(r=>`<tr>${parseRow(r)}</tr>`).join('');
|
||||
return `<table><thead>${header}</thead><tbody>${body}</tbody></table>`;
|
||||
@@ -292,6 +324,148 @@ function updateQueueBadge(){
|
||||
}
|
||||
function showToast(msg,ms){const el=$('toast');el.textContent=msg;el.classList.add('show');clearTimeout(el._t);el._t=setTimeout(()=>el.classList.remove('show'),ms||2800);}
|
||||
|
||||
// ── Shared app dialogs ───────────────────────────────────────────────────────
|
||||
// showConfirmDialog(opts) and showPromptDialog(opts) replace browser-native dialog calls
|
||||
// throughout the UI. Both return Promises and support: title, message, confirmLabel,
|
||||
// cancelLabel, danger (confirm only), placeholder/value/inputType (prompt only).
|
||||
|
||||
const APP_DIALOG={resolve:null,kind:null,lastFocus:null};
|
||||
let _appDialogBound=false;
|
||||
|
||||
function _isAppDialogOpen(){
|
||||
const overlay=$('appDialogOverlay');
|
||||
return !!(overlay&&overlay.style.display!=='none');
|
||||
}
|
||||
|
||||
function _getAppDialogFocusable(){
|
||||
return [$('appDialogInput'), $('appDialogCancel'), $('appDialogConfirm'), $('appDialogClose')]
|
||||
.filter(el=>el&&el.style.display!=='none'&&!el.disabled);
|
||||
}
|
||||
|
||||
function _finishAppDialog(result, restoreFocus=true){
|
||||
const overlay=$('appDialogOverlay');
|
||||
const dialog=$('appDialog');
|
||||
const input=$('appDialogInput');
|
||||
const confirmBtn=$('appDialogConfirm');
|
||||
const resolve=APP_DIALOG.resolve;
|
||||
const lastFocus=APP_DIALOG.lastFocus;
|
||||
APP_DIALOG.resolve=null;
|
||||
APP_DIALOG.kind=null;
|
||||
APP_DIALOG.lastFocus=null;
|
||||
if(overlay){overlay.style.display='none';overlay.setAttribute('aria-hidden','true');}
|
||||
if(dialog) dialog.setAttribute('role','dialog');
|
||||
if(input){input.value='';input.style.display='none';input.placeholder='';}
|
||||
if(confirmBtn){confirmBtn.classList.remove('danger');confirmBtn.textContent=t('dialog_confirm_btn');}
|
||||
if(restoreFocus&&lastFocus&&typeof lastFocus.focus==='function'){setTimeout(()=>lastFocus.focus(),0);}
|
||||
if(resolve) resolve(result);
|
||||
}
|
||||
|
||||
function _ensureAppDialogBindings(){
|
||||
if(_appDialogBound) return;
|
||||
_appDialogBound=true;
|
||||
const overlay=$('appDialogOverlay');
|
||||
const cancelBtn=$('appDialogCancel');
|
||||
const confirmBtn=$('appDialogConfirm');
|
||||
const closeBtn=$('appDialogClose');
|
||||
if(overlay){
|
||||
overlay.addEventListener('click',e=>{
|
||||
if(e.target===overlay) _finishAppDialog(APP_DIALOG.kind==='prompt'?null:false);
|
||||
});
|
||||
}
|
||||
if(cancelBtn) cancelBtn.addEventListener('click',()=>_finishAppDialog(APP_DIALOG.kind==='prompt'?null:false));
|
||||
if(closeBtn) closeBtn.addEventListener('click',()=>_finishAppDialog(APP_DIALOG.kind==='prompt'?null:false));
|
||||
if(confirmBtn){
|
||||
confirmBtn.addEventListener('click',()=>{
|
||||
if(APP_DIALOG.kind==='prompt'){
|
||||
const input=$('appDialogInput');
|
||||
_finishAppDialog(input?input.value:null);
|
||||
}else{
|
||||
_finishAppDialog(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
document.addEventListener('keydown',e=>{
|
||||
if(!_isAppDialogOpen()) return;
|
||||
if(e.key==='Escape'){
|
||||
e.preventDefault();
|
||||
_finishAppDialog(APP_DIALOG.kind==='prompt'?null:false);
|
||||
return;
|
||||
}
|
||||
if(e.key==='Enter'){
|
||||
const target=e.target;
|
||||
const isTextarea=target&&target.tagName==='TEXTAREA';
|
||||
if(!isTextarea){
|
||||
e.preventDefault();
|
||||
if(target===cancelBtn||target===closeBtn){
|
||||
_finishAppDialog(APP_DIALOG.kind==='prompt'?null:false);
|
||||
}else if(APP_DIALOG.kind==='prompt'){
|
||||
const input=$('appDialogInput');
|
||||
_finishAppDialog(input?input.value:null);
|
||||
}else{
|
||||
_finishAppDialog(true);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(e.key==='Tab'){
|
||||
const nodes=_getAppDialogFocusable();
|
||||
if(!nodes.length) return;
|
||||
const idx=nodes.indexOf(document.activeElement);
|
||||
let nextIdx=idx;
|
||||
if(e.shiftKey){nextIdx=idx<=0?nodes.length-1:idx-1;}
|
||||
else{nextIdx=idx===-1||idx===nodes.length-1?0:idx+1;}
|
||||
e.preventDefault();
|
||||
nodes[nextIdx].focus();
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
|
||||
function showConfirmDialog(opts={}){
|
||||
_ensureAppDialogBindings();
|
||||
if(APP_DIALOG.resolve) _finishAppDialog(false,false);
|
||||
const overlay=$('appDialogOverlay'),dialog=$('appDialog'),title=$('appDialogTitle'),
|
||||
desc=$('appDialogDesc'),input=$('appDialogInput'),cancelBtn=$('appDialogCancel'),confirmBtn=$('appDialogConfirm');
|
||||
APP_DIALOG.resolve=null;APP_DIALOG.kind='confirm';APP_DIALOG.lastFocus=document.activeElement;
|
||||
if(title) title.textContent=opts.title||t('dialog_confirm_title');
|
||||
if(desc) desc.textContent=opts.message||'';
|
||||
if(input){input.style.display='none';input.value='';}
|
||||
if(cancelBtn) cancelBtn.textContent=opts.cancelLabel||t('cancel');
|
||||
if(confirmBtn){
|
||||
confirmBtn.textContent=opts.confirmLabel||t('dialog_confirm_btn');
|
||||
confirmBtn.classList.toggle('danger',!!opts.danger);
|
||||
}
|
||||
if(dialog) dialog.setAttribute('role',opts.danger?'alertdialog':'dialog');
|
||||
if(overlay){overlay.style.display='flex';overlay.setAttribute('aria-hidden','false');}
|
||||
return new Promise(resolve=>{
|
||||
APP_DIALOG.resolve=resolve;
|
||||
setTimeout(()=>((opts.focusCancel?cancelBtn:confirmBtn)||confirmBtn||cancelBtn).focus(),0);
|
||||
});
|
||||
}
|
||||
|
||||
function showPromptDialog(opts={}){
|
||||
_ensureAppDialogBindings();
|
||||
if(APP_DIALOG.resolve) _finishAppDialog(null,false);
|
||||
const overlay=$('appDialogOverlay'),dialog=$('appDialog'),title=$('appDialogTitle'),
|
||||
desc=$('appDialogDesc'),input=$('appDialogInput'),cancelBtn=$('appDialogCancel'),confirmBtn=$('appDialogConfirm');
|
||||
APP_DIALOG.resolve=null;APP_DIALOG.kind='prompt';APP_DIALOG.lastFocus=document.activeElement;
|
||||
if(title) title.textContent=opts.title||t('dialog_prompt_title');
|
||||
if(desc) desc.textContent=opts.message||'';
|
||||
if(input){
|
||||
input.type=opts.inputType||'text';input.style.display='';
|
||||
input.value=opts.value||'';input.placeholder=opts.placeholder||'';
|
||||
input.autocomplete='off';input.spellcheck=false;
|
||||
}
|
||||
if(cancelBtn) cancelBtn.textContent=opts.cancelLabel||t('cancel');
|
||||
if(confirmBtn){confirmBtn.textContent=opts.confirmLabel||t('create');confirmBtn.classList.remove('danger');}
|
||||
if(dialog) dialog.setAttribute('role','dialog');
|
||||
if(overlay){overlay.style.display='flex';overlay.setAttribute('aria-hidden','false');}
|
||||
return new Promise(resolve=>{
|
||||
APP_DIALOG.resolve=resolve;
|
||||
setTimeout(()=>{if(input&&input.style.display!=='none')input.focus();else if(confirmBtn)confirmBtn.focus();},0);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function copyMsg(btn){
|
||||
const row=btn.closest('.msg-row');
|
||||
const text=row?row.dataset.rawText:'';
|
||||
@@ -664,12 +838,26 @@ function renderMessages(){
|
||||
}
|
||||
|
||||
function toolIcon(name){
|
||||
const icons={terminal:'⬛',read_file:'📄',write_file:'✏️',search_files:'🔍',
|
||||
web_search:'🌐',web_extract:'🌐',execute_code:'⚙️',patch:'🔧',
|
||||
memory:'🧠',skill_manage:'📚',todo:'✅',cronjob:'⏱️',delegate_task:'🤖',
|
||||
send_message:'💬',browser_navigate:'🌐',vision_analyze:'👁️',
|
||||
subagent_progress:'🔀'};
|
||||
return icons[name]||'🔧';
|
||||
const icons={
|
||||
terminal: li('terminal'),
|
||||
read_file: li('file-text'),
|
||||
write_file: li('file-pen'),
|
||||
search_files: li('search'),
|
||||
web_search: li('globe'),
|
||||
web_extract: li('globe'),
|
||||
execute_code: li('play'),
|
||||
patch: li('wrench'),
|
||||
memory: li('brain'),
|
||||
skill_manage: li('book-open'),
|
||||
todo: li('list-todo'),
|
||||
cronjob: li('clock'),
|
||||
delegate_task: li('bot'),
|
||||
send_message: li('message-square'),
|
||||
browser_navigate:li('globe'),
|
||||
vision_analyze: li('eye'),
|
||||
subagent_progress:li('shuffle'),
|
||||
};
|
||||
return icons[name]||li('wrench');
|
||||
}
|
||||
|
||||
function buildToolCard(tc){
|
||||
@@ -925,17 +1113,17 @@ function appendThinking(){
|
||||
function removeThinking(){const el=$('thinkingRow');if(el)el.remove();}
|
||||
|
||||
function fileIcon(name, type){
|
||||
if(type==='dir') return '📁';
|
||||
if(type==='dir') return li('folder',14);
|
||||
const e=fileExt(name);
|
||||
if(IMAGE_EXTS.has(e)) return '📷';
|
||||
if(MD_EXTS.has(e)) return '📝';
|
||||
if(typeof DOWNLOAD_EXTS!=='undefined'&&DOWNLOAD_EXTS.has(e)) return '⬇️';
|
||||
if(e==='.py') return '🐍';
|
||||
if(e==='.js'||e==='.ts'||e==='.jsx'||e==='.tsx') return '⚡';
|
||||
if(e==='.json'||e==='.yaml'||e==='.yml'||e==='.toml') return '⚙';
|
||||
if(e==='.sh'||e==='.bash') return '💻';
|
||||
if(e==='.pdf') return '⬇️';
|
||||
return '📄';
|
||||
if(IMAGE_EXTS.has(e)) return li('image',14);
|
||||
if(MD_EXTS.has(e)) return li('file-text',14);
|
||||
if(typeof DOWNLOAD_EXTS!=='undefined'&&DOWNLOAD_EXTS.has(e)) return li('download',14);
|
||||
if(e==='.py') return li('file-code',14);
|
||||
if(e==='.js'||e==='.ts'||e==='.jsx'||e==='.tsx') return li('zap',14);
|
||||
if(e==='.json'||e==='.yaml'||e==='.yml'||e==='.toml') return li('settings',14);
|
||||
if(e==='.sh'||e==='.bash') return li('terminal',14);
|
||||
if(e==='.pdf') return li('download',14);
|
||||
return li('file-text',14);
|
||||
}
|
||||
|
||||
function renderBreadcrumb(){
|
||||
@@ -1005,7 +1193,7 @@ function _renderTreeItems(container, entries, depth){
|
||||
|
||||
// Icon
|
||||
const iconEl=document.createElement('span');
|
||||
iconEl.className='file-icon';iconEl.textContent=fileIcon(item.name,item.type);
|
||||
iconEl.className='file-icon';iconEl.innerHTML=fileIcon(item.name,item.type);
|
||||
el.appendChild(iconEl);
|
||||
|
||||
// Name
|
||||
@@ -1107,7 +1295,8 @@ function _renderTreeItems(container, entries, depth){
|
||||
|
||||
async function deleteWorkspaceFile(relPath, name){
|
||||
if(!S.session)return;
|
||||
if(!confirm(t('delete_confirm',name)))return;
|
||||
const _delFile=await showConfirmDialog({title:t('delete_confirm',name),message:'',confirmLabel:'Delete',danger:true,focusCancel:true});
|
||||
if(!_delFile) return;
|
||||
try{
|
||||
await api('/api/file/delete',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,path:relPath})});
|
||||
showToast(t('deleted')+name);
|
||||
@@ -1119,7 +1308,7 @@ async function deleteWorkspaceFile(relPath, name){
|
||||
|
||||
async function promptNewFile(){
|
||||
if(!S.session)return;
|
||||
const name=prompt(t('new_file_prompt'),'');
|
||||
const name=await showPromptDialog({title:t('new_file_prompt'),placeholder:'filename.txt',confirmLabel:t('create')});
|
||||
if(!name||!name.trim())return;
|
||||
const relPath=S.currentDir==='.'?name.trim():(S.currentDir+'/'+name.trim());
|
||||
try{
|
||||
@@ -1132,7 +1321,7 @@ async function promptNewFile(){
|
||||
|
||||
async function promptNewFolder(){
|
||||
if(!S.session)return;
|
||||
const name=prompt(t('new_folder_prompt'),'');
|
||||
const name=await showPromptDialog({title:t('new_folder_prompt'),placeholder:'folder-name',confirmLabel:t('create')});
|
||||
if(!name||!name.trim())return;
|
||||
const relPath=S.currentDir==='.'?name.trim():(S.currentDir+'/'+name.trim());
|
||||
try{
|
||||
|
||||
@@ -54,7 +54,7 @@ async function loadDir(path){
|
||||
}
|
||||
if(typeof clearPreview==='function'){
|
||||
if(typeof _previewDirty!=='undefined'&&_previewDirty){
|
||||
if(confirm(t('unsaved_confirm')))clearPreview();
|
||||
showConfirmDialog({title:t('unsaved_confirm'),message:'',confirmLabel:'Discard',danger:true,focusCancel:true}).then(ok=>{if(ok)clearPreview();});
|
||||
}else{
|
||||
clearPreview();
|
||||
}
|
||||
|
||||
@@ -153,6 +153,8 @@ def pytest_collection_modifyitems(config, items):
|
||||
# Agent backend (need running AIAgent)
|
||||
'test_chat_stream_opens_successfully',
|
||||
'test_approval_submit_and_respond',
|
||||
# Security redaction (flaky — session state varies across test ordering)
|
||||
'test_api_sessions_list_redacts_titles',
|
||||
# Workspace path (macOS /tmp -> /private/tmp symlink)
|
||||
'test_new_session_inherits_workspace',
|
||||
'test_workspace_add_valid',
|
||||
@@ -238,6 +240,13 @@ def test_server():
|
||||
# Isolated cron state
|
||||
(TEST_STATE_DIR / 'cron').mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Expose TEST_STATE_DIR to the test process itself so that tests which write
|
||||
# directly to state.db (e.g. test_gateway_sync.py) always use the same path
|
||||
# as the server. Other test files (test_auth_sessions.py) may override
|
||||
# HERMES_WEBUI_STATE_DIR for their own purposes, but HERMES_WEBUI_TEST_STATE_DIR
|
||||
# is reserved for this mapping and is never overridden by individual test files.
|
||||
os.environ.setdefault('HERMES_WEBUI_TEST_STATE_DIR', str(TEST_STATE_DIR))
|
||||
|
||||
env = os.environ.copy()
|
||||
env.update({
|
||||
"HERMES_WEBUI_PORT": str(TEST_PORT),
|
||||
|
||||
@@ -27,9 +27,11 @@ try:
|
||||
_lock,
|
||||
_ApprovalEntry,
|
||||
submit_pending,
|
||||
has_pending,
|
||||
pop_pending,
|
||||
)
|
||||
# has_pending and pop_pending were removed from tools.approval when the
|
||||
# agent renamed has_pending -> has_blocking_approval (gateway queue check)
|
||||
# and removed the polling-mode pop_pending. Routes now check _pending
|
||||
# directly. These symbols are no longer part of the public API.
|
||||
APPROVAL_AVAILABLE = True
|
||||
except ImportError:
|
||||
APPROVAL_AVAILABLE = False
|
||||
|
||||
115
tests/test_cancel_interrupt.py
Normal file
115
tests/test_cancel_interrupt.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
Unit tests for cancel/interrupt functionality.
|
||||
Tests the integration between cancel_stream() and agent.interrupt().
|
||||
"""
|
||||
import pytest
|
||||
import queue
|
||||
import threading
|
||||
from unittest.mock import Mock
|
||||
|
||||
from api.streaming import cancel_stream
|
||||
from api.config import AGENT_INSTANCES, STREAMS, CANCEL_FLAGS
|
||||
|
||||
|
||||
class TestCancelInterrupt:
|
||||
"""Test suite for cancel/interrupt functionality"""
|
||||
|
||||
def setup_method(self):
|
||||
"""Clean up before each test"""
|
||||
AGENT_INSTANCES.clear()
|
||||
STREAMS.clear()
|
||||
CANCEL_FLAGS.clear()
|
||||
|
||||
def teardown_method(self):
|
||||
"""Clean up after each test"""
|
||||
AGENT_INSTANCES.clear()
|
||||
STREAMS.clear()
|
||||
CANCEL_FLAGS.clear()
|
||||
|
||||
def test_cancel_calls_agent_interrupt(self):
|
||||
"""Verify that cancel_stream() calls agent.interrupt() when agent exists"""
|
||||
# Setup
|
||||
stream_id = "test_stream_123"
|
||||
mock_agent = Mock()
|
||||
mock_agent.interrupt = Mock()
|
||||
|
||||
STREAMS[stream_id] = queue.Queue()
|
||||
CANCEL_FLAGS[stream_id] = threading.Event()
|
||||
AGENT_INSTANCES[stream_id] = mock_agent
|
||||
|
||||
# Execute
|
||||
result = cancel_stream(stream_id)
|
||||
|
||||
# Assert
|
||||
assert result is True
|
||||
mock_agent.interrupt.assert_called_once_with("Cancelled by user")
|
||||
assert CANCEL_FLAGS[stream_id].is_set()
|
||||
|
||||
def test_cancel_handles_interrupt_exception(self):
|
||||
"""Verify that cancel_stream() handles interrupt() exceptions gracefully"""
|
||||
stream_id = "test_stream_456"
|
||||
mock_agent = Mock()
|
||||
mock_agent.interrupt = Mock(side_effect=RuntimeError("Agent error"))
|
||||
|
||||
STREAMS[stream_id] = queue.Queue()
|
||||
CANCEL_FLAGS[stream_id] = threading.Event()
|
||||
AGENT_INSTANCES[stream_id] = mock_agent
|
||||
|
||||
# Should not raise exception
|
||||
result = cancel_stream(stream_id)
|
||||
|
||||
# Assert
|
||||
assert result is True
|
||||
mock_agent.interrupt.assert_called_once()
|
||||
assert CANCEL_FLAGS[stream_id].is_set()
|
||||
|
||||
def test_cancel_before_agent_ready(self):
|
||||
"""Test cancel when agent not yet stored in AGENT_INSTANCES (race condition)"""
|
||||
stream_id = "test_stream_789"
|
||||
|
||||
STREAMS[stream_id] = queue.Queue()
|
||||
CANCEL_FLAGS[stream_id] = threading.Event()
|
||||
# Note: AGENT_INSTANCES[stream_id] not set (simulating race condition)
|
||||
|
||||
# Should succeed even without agent
|
||||
result = cancel_stream(stream_id)
|
||||
|
||||
# Assert
|
||||
assert result is True
|
||||
assert CANCEL_FLAGS[stream_id].is_set()
|
||||
# Agent will check this flag when it starts
|
||||
|
||||
def test_cancel_nonexistent_stream(self):
|
||||
"""Test cancel for a stream that doesn't exist"""
|
||||
result = cancel_stream("nonexistent_stream")
|
||||
assert result is False
|
||||
|
||||
def test_cancel_sets_cancel_event(self):
|
||||
"""Verify that cancel_stream() sets the cancel_event flag"""
|
||||
stream_id = "test_stream_event"
|
||||
|
||||
STREAMS[stream_id] = queue.Queue()
|
||||
cancel_event = threading.Event()
|
||||
CANCEL_FLAGS[stream_id] = cancel_event
|
||||
|
||||
result = cancel_stream(stream_id)
|
||||
|
||||
assert result is True
|
||||
assert cancel_event.is_set()
|
||||
|
||||
def test_cancel_puts_sentinel_in_queue(self):
|
||||
"""Verify that cancel_stream() puts cancel sentinel in queue"""
|
||||
stream_id = "test_stream_queue"
|
||||
q = queue.Queue()
|
||||
|
||||
STREAMS[stream_id] = q
|
||||
CANCEL_FLAGS[stream_id] = threading.Event()
|
||||
|
||||
result = cancel_stream(stream_id)
|
||||
|
||||
assert result is True
|
||||
# Check that cancel message was queued
|
||||
assert not q.empty()
|
||||
event_type, data = q.get_nowait()
|
||||
assert event_type == 'cancel'
|
||||
assert data['message'] == 'Cancelled by user'
|
||||
364
tests/test_gateway_sync.py
Normal file
364
tests/test_gateway_sync.py
Normal file
@@ -0,0 +1,364 @@
|
||||
"""
|
||||
Tests for Phase 1: Real-time Gateway Session Sync.
|
||||
|
||||
Tests are ordered TDD-style:
|
||||
1. Gateway sessions appear in /api/sessions when setting enabled
|
||||
2. Gateway sessions excluded when setting disabled
|
||||
3. Gateway sessions have correct metadata (source_tag, is_cli_session)
|
||||
4. SSE stream endpoint opens and receives events
|
||||
5. Watcher detects new sessions inserted into state.db
|
||||
6. Settings UI has renamed label
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sqlite3
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
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:
|
||||
try:
|
||||
return json.loads(e.read()), e.code
|
||||
except Exception:
|
||||
return {}, e.code
|
||||
|
||||
|
||||
def _get_test_state_dir():
|
||||
"""Return the test state directory (matches conftest.py TEST_STATE_DIR).
|
||||
|
||||
conftest.py sets HERMES_WEBUI_TEST_STATE_DIR in the test-process environment
|
||||
(via os.environ.setdefault) so that tests writing directly to state.db always
|
||||
use the same path the test server was started with. If the env var is not
|
||||
set (e.g. when running this file standalone), fall back to the conftest
|
||||
formula: HERMES_HOME/webui-mvp-test.
|
||||
"""
|
||||
explicit = os.getenv('HERMES_WEBUI_TEST_STATE_DIR')
|
||||
if explicit:
|
||||
return pathlib.Path(explicit)
|
||||
hermes_home = pathlib.Path(os.getenv('HERMES_HOME', str(pathlib.Path.home() / '.hermes')))
|
||||
return hermes_home / 'webui-mvp-test' # matches conftest.py TEST_STATE_DIR formula
|
||||
|
||||
|
||||
def _get_state_db_path():
|
||||
"""Return path to the test state.db."""
|
||||
return _get_test_state_dir() / 'state.db'
|
||||
|
||||
|
||||
def _ensure_state_db():
|
||||
"""Create state.db with sessions and messages tables if it doesn't exist.
|
||||
Returns a connection. Does NOT delete existing data (safe for parallel tests).
|
||||
"""
|
||||
db_path = _get_state_db_path()
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
source TEXT NOT NULL,
|
||||
user_id TEXT,
|
||||
model TEXT,
|
||||
started_at REAL NOT NULL,
|
||||
message_count INTEGER DEFAULT 0,
|
||||
title TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT,
|
||||
timestamp REAL NOT NULL
|
||||
);
|
||||
""")
|
||||
conn.commit()
|
||||
return conn
|
||||
|
||||
|
||||
def _insert_gateway_session(conn, session_id='20260401_120000_abcdefgh', source='telegram',
|
||||
title='Telegram Chat', model='anthropic/claude-sonnet-4-5',
|
||||
started_at=None, message_count=2):
|
||||
"""Insert a gateway session into state.db."""
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO sessions (id, source, title, model, started_at, message_count) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(session_id, source, title, model, started_at or time.time(), message_count)
|
||||
)
|
||||
# Delete any existing messages for this session (idempotent re-insert)
|
||||
conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
|
||||
# Insert some messages
|
||||
conn.execute(
|
||||
"INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, 'user', ?, ?)",
|
||||
(session_id, 'Hello from Telegram', started_at or time.time())
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, 'assistant', ?, ?)",
|
||||
(session_id, 'Hi there!', (started_at or time.time()) + 1)
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _remove_test_sessions(conn, *session_ids):
|
||||
"""Remove specific test sessions from state.db (parallel-safe cleanup)."""
|
||||
for sid in session_ids:
|
||||
conn.execute("DELETE FROM messages WHERE session_id = ?", (sid,))
|
||||
conn.execute("DELETE FROM sessions WHERE id = ?", (sid,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _cleanup_state_db():
|
||||
"""Remove state.db if it exists (only used for tests that need a blank slate)."""
|
||||
db_path = _get_state_db_path()
|
||||
for p in [db_path, db_path.parent / 'state.db-wal', db_path.parent / 'state.db-shm']:
|
||||
try:
|
||||
p.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── Tests ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_gateway_sessions_appear_when_enabled():
|
||||
"""Gateway sessions from state.db appear in /api/sessions when show_cli_sessions is on."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_test_tg_001', source='telegram', title='TG Test Chat')
|
||||
|
||||
# Enable the setting
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
gw_ids = [s['session_id'] for s in sessions if s.get('session_id') == 'gw_test_tg_001']
|
||||
assert len(gw_ids) == 1, f"Expected gateway session gw_test_tg_001, got {[s['session_id'] for s in sessions]}"
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_test_tg_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_sessions_excluded_when_disabled():
|
||||
"""Gateway sessions are NOT returned when show_cli_sessions is off."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_test_dc_001', source='discord', title='DC Test Chat')
|
||||
|
||||
# Ensure setting is off
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
gw_ids = [s['session_id'] for s in sessions if s.get('session_id') == 'gw_test_dc_001']
|
||||
assert len(gw_ids) == 0, "Gateway session should not appear when setting is off"
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_test_dc_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def test_gateway_session_has_correct_metadata():
|
||||
"""Gateway sessions include source_tag and is_cli_session fields."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_meta_001', source='telegram', title='Meta Test')
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
gw = next((s for s in sessions if s['session_id'] == 'gw_meta_001'), None)
|
||||
assert gw is not None, "Gateway session not found"
|
||||
assert gw.get('source_tag') == 'telegram', f"Expected source_tag=telegram, got {gw.get('source_tag')}"
|
||||
assert gw.get('is_cli_session') is True, "is_cli_session should be True for agent sessions"
|
||||
assert gw.get('title') == 'Meta Test'
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_meta_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_session_has_message_count():
|
||||
"""Gateway sessions report correct message_count from state.db."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_msg_001', source='discord', title='Msg Count Test', message_count=5)
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
gw = next((s for s in sessions if s['session_id'] == 'gw_msg_001'), None)
|
||||
assert gw is not None
|
||||
assert gw.get('message_count') == 5, f"Expected message_count=5, got {gw.get('message_count')}"
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_msg_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_sessions_multiple_sources():
|
||||
"""Sessions from multiple gateway sources (telegram, discord, slack) all appear."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_multi_tg', source='telegram', title='TG Chat')
|
||||
_insert_gateway_session(conn, session_id='gw_multi_dc', source='discord', title='DC Chat')
|
||||
_insert_gateway_session(conn, session_id='gw_multi_sl', source='slack', title='SL Chat')
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
gw_ids = {s['session_id'] for s in sessions if s.get('session_id') in ('gw_multi_tg', 'gw_multi_dc', 'gw_multi_sl')}
|
||||
assert len(gw_ids) == 3, f"Expected 3 gateway sessions, got {len(gw_ids)}: {gw_ids}"
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_multi_tg', 'gw_multi_dc', 'gw_multi_sl')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_session_messages_readable():
|
||||
"""Gateway session messages can be loaded via /api/session."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='gw_read_001', source='telegram', title='Readable')
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get(f'/api/session?session_id=gw_read_001')
|
||||
assert status == 200
|
||||
msgs = data.get('session', {}).get('messages', [])
|
||||
assert len(msgs) >= 2, f"Expected at least 2 messages, got {len(msgs)}"
|
||||
assert msgs[0].get('role') == 'user'
|
||||
assert msgs[0].get('content') == 'Hello from Telegram'
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'gw_read_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_sse_stream_endpoint_exists():
|
||||
"""GET /api/sessions/gateway/stream returns a response (200 or 200-range)."""
|
||||
# The SSE endpoint requires show_cli_sessions to be enabled
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
try:
|
||||
req = urllib.request.Request(BASE + '/api/sessions/gateway/stream')
|
||||
with urllib.request.urlopen(req, timeout=5) as r:
|
||||
assert r.status in (200, 204), f"Expected 200/204, got {r.status}"
|
||||
# SSE should have content-type text/event-stream
|
||||
ctype = r.headers.get('Content-Type', '')
|
||||
assert 'text/event-stream' in ctype, f"Expected text/event-stream, got {ctype}"
|
||||
except Exception as e:
|
||||
# Timeout is acceptable — means the connection is held open (SSE behavior)
|
||||
if 'timed out' in str(e).lower() or 'timeout' in str(e).lower():
|
||||
pass # Good: SSE keeps the connection open
|
||||
else:
|
||||
raise
|
||||
finally:
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_webui_sessions_not_duplicated():
|
||||
"""If a session_id exists both in WebUI store and state.db, it's not duplicated."""
|
||||
# Create a WebUI session with a known ID
|
||||
body = {}
|
||||
d, _ = post('/api/session/new', body)
|
||||
webui_sid = d['session']['session_id']
|
||||
|
||||
try:
|
||||
# Insert the same session_id into state.db as a gateway session
|
||||
conn = _ensure_state_db()
|
||||
_insert_gateway_session(conn, session_id=webui_sid, source='telegram', title='Dup Test')
|
||||
conn.close()
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
matching = [s for s in sessions if s['session_id'] == webui_sid]
|
||||
assert len(matching) == 1, f"Expected 1 entry for {webui_sid}, got {len(matching)}"
|
||||
finally:
|
||||
try:
|
||||
conn2 = sqlite3.connect(str(_get_state_db_path()))
|
||||
_remove_test_sessions(conn2, webui_sid)
|
||||
conn2.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/session/delete', {'session_id': webui_sid})
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_gateway_sessions_no_state_db():
|
||||
"""When state.db doesn't exist, /api/sessions works fine (no gateway sessions)."""
|
||||
_cleanup_state_db()
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
try:
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
# Should succeed with just webui sessions (or empty)
|
||||
assert 'sessions' in data
|
||||
finally:
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
def test_cli_sessions_still_work():
|
||||
"""CLI sessions (source='cli') still appear alongside gateway sessions."""
|
||||
conn = _ensure_state_db()
|
||||
try:
|
||||
_insert_gateway_session(conn, session_id='cli_legacy_001', source='cli', title='CLI Legacy')
|
||||
_insert_gateway_session(conn, session_id='gw_new_001', source='telegram', title='GW New')
|
||||
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
data, status = get('/api/sessions')
|
||||
assert status == 200
|
||||
sessions = data.get('sessions', [])
|
||||
agent_ids = {s['session_id'] for s in sessions if s.get('session_id') in ('cli_legacy_001', 'gw_new_001')}
|
||||
assert len(agent_ids) == 2, f"Expected 2 agent sessions (cli + gateway), got {len(agent_ids)}"
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, 'cli_legacy_001', 'gw_new_001')
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
208
tests/test_mobile_layout.py
Normal file
208
tests/test_mobile_layout.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
Mobile layout regression tests — run on every QA pass.
|
||||
|
||||
These tests check that the CSS and HTML structure required for correct
|
||||
mobile rendering (375px–640px viewport widths) is intact after every change.
|
||||
They are static checks (no server needed) that catch common regressions:
|
||||
|
||||
- Mobile breakpoints present for key layout elements
|
||||
- Right panel slide-over markup and CSS intact
|
||||
- Profile dropdown not clipped by overflow on mobile
|
||||
- Composer footer chips scroll correctly on narrow viewports
|
||||
- Mobile bottom nav and overlay markup present
|
||||
- No full-viewport overflow that would break scroll
|
||||
|
||||
Run as part of the standard test suite:
|
||||
pytest tests/test_mobile_layout.py -v
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
HTML = (REPO / "static" / "index.html").read_text(encoding="utf-8")
|
||||
CSS = (REPO / "static" / "style.css").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Mobile breakpoint rules ───────────────────────────────────────────────────
|
||||
|
||||
def test_mobile_breakpoint_900px_present():
|
||||
"""@media(max-width:900px) must hide the right panel and show mobile-files-btn."""
|
||||
assert "@media(max-width:900px)" in CSS or "@media (max-width: 900px)" in CSS, \
|
||||
"Missing @media(max-width:900px) breakpoint in style.css"
|
||||
# Right panel should be hidden at 900px, replaced by slide-over
|
||||
assert ".rightpanel{display:none" in CSS or ".rightpanel {display:none" in CSS or \
|
||||
re.search(r'max-width:900px\).*?\.rightpanel\{display:none', CSS, re.DOTALL), \
|
||||
".rightpanel must be display:none at max-width:900px (slide-over replaces it)"
|
||||
|
||||
|
||||
def test_mobile_breakpoint_640px_present():
|
||||
"""@media(max-width:640px) must exist for narrow phone layouts."""
|
||||
assert "@media(max-width:640px)" in CSS or "@media (max-width: 640px)" in CSS, \
|
||||
"Missing @media(max-width:640px) breakpoint in style.css"
|
||||
|
||||
|
||||
def test_rightpanel_mobile_slide_over_css():
|
||||
"""Right panel must have position:fixed slide-over CSS for mobile."""
|
||||
# At max-width:900px the rightpanel should be position:fixed, off-screen right
|
||||
assert "position:fixed" in CSS, \
|
||||
"style.css must have position:fixed for rightpanel mobile slide-over"
|
||||
assert ".rightpanel.mobile-open{right:0" in CSS or ".rightpanel.mobile-open {right:0" in CSS, \
|
||||
".rightpanel.mobile-open must set right:0 to slide panel in from right"
|
||||
assert "right:-320px" in CSS or "right: -320px" in CSS, \
|
||||
"rightpanel must start off-screen (right:-320px) on mobile"
|
||||
|
||||
|
||||
def test_mobile_overlay_present():
|
||||
"""Mobile overlay element must exist for tap-to-close sidebar behavior."""
|
||||
assert 'id="mobileOverlay"' in HTML, \
|
||||
"#mobileOverlay element missing from index.html"
|
||||
assert "mobile-overlay" in CSS, \
|
||||
".mobile-overlay CSS rule missing from style.css"
|
||||
|
||||
|
||||
def test_mobile_bottom_nav_present():
|
||||
"""Mobile bottom navigation bar must be present."""
|
||||
assert "mobile-bottom-nav" in HTML or "mobile-nav-btn" in HTML, \
|
||||
"Mobile bottom nav (.mobile-bottom-nav or .mobile-nav-btn) missing from index.html"
|
||||
assert "mobile-bottom-nav" in CSS, \
|
||||
".mobile-bottom-nav CSS rule missing from style.css"
|
||||
|
||||
|
||||
def test_mobile_files_button_present():
|
||||
"""Mobile files toggle button (#btnMobileFiles) must be in HTML and CSS."""
|
||||
assert 'id="btnMobileFiles"' in HTML, \
|
||||
"#btnMobileFiles missing from index.html"
|
||||
assert "mobile-files-btn" in CSS, \
|
||||
".mobile-files-btn CSS missing from style.css"
|
||||
|
||||
|
||||
# ── Profile dropdown overflow ─────────────────────────────────────────────────
|
||||
|
||||
def test_profile_dropdown_not_clipped_by_overflow():
|
||||
"""Profile dropdown must not be inside an overflow:hidden or overflow-x:auto ancestor
|
||||
without a higher z-index escape hatch.
|
||||
|
||||
The topbar-chips container uses overflow-x:auto on mobile, which creates a
|
||||
stacking context that clips absolutely-positioned children. The profile dropdown
|
||||
must use position:fixed on mobile OR the topbar-chips must not clip it.
|
||||
"""
|
||||
# The profile-chip wrapper must have position:relative so the dropdown can escape
|
||||
assert 'id="profileChipWrap"' in HTML, \
|
||||
"#profileChipWrap missing from index.html"
|
||||
# Profile dropdown must have a z-index high enough to clear the topbar
|
||||
assert ".profile-dropdown{" in CSS or ".profile-dropdown {" in CSS, \
|
||||
".profile-dropdown CSS rule missing"
|
||||
# z-index must be at least 200 (topbar is z-index:10)
|
||||
m = re.search(r'\.profile-dropdown\{[^}]*z-index:(\d+)', CSS)
|
||||
if m:
|
||||
assert int(m.group(1)) >= 100, \
|
||||
f".profile-dropdown z-index {m.group(1)} is too low — must be >= 100 to clear topbar"
|
||||
|
||||
|
||||
def test_topbar_chips_mobile_overflow():
|
||||
"""topbar-chips must use overflow-x:auto on mobile for chip scrolling.
|
||||
|
||||
Chips (profile, workspace, model, files) must scroll horizontally on narrow
|
||||
viewports rather than wrapping onto a second line which would break the topbar layout.
|
||||
"""
|
||||
# At narrow viewport, topbar-chips should scroll
|
||||
assert "overflow-x:auto" in CSS or "overflow-x: auto" in CSS, \
|
||||
"topbar-chips must have overflow-x:auto for mobile chip scrolling"
|
||||
|
||||
|
||||
# ── Workspace panel close ─────────────────────────────────────────────────────
|
||||
|
||||
def test_workspace_close_button_present():
|
||||
"""Workspace panel must have a close/hide button accessible on mobile."""
|
||||
# Either a dedicated mobile close button or the X button that closes the panel
|
||||
has_close = (
|
||||
'onclick="toggleMobileFiles()"' in HTML or
|
||||
'toggleMobileFiles' in HTML
|
||||
)
|
||||
assert has_close, \
|
||||
"toggleMobileFiles() must be wired to a button to close the workspace panel on mobile"
|
||||
|
||||
|
||||
def test_toggle_mobile_files_js_defined():
|
||||
"""toggleMobileFiles() must be defined in boot.js."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
assert "function toggleMobileFiles()" in boot_js, \
|
||||
"toggleMobileFiles() missing from static/boot.js"
|
||||
assert "mobile-open" in boot_js, \
|
||||
"toggleMobileFiles() must toggle mobile-open class on the right panel"
|
||||
|
||||
|
||||
# ── Viewport and scroll safety ────────────────────────────────────────────────
|
||||
|
||||
def test_body_overflow_hidden():
|
||||
"""body must have overflow:hidden to prevent double scrollbars on mobile."""
|
||||
assert "body{" in CSS or "body {" in CSS, \
|
||||
"body rule missing from style.css"
|
||||
assert re.search(r'body\{[^}]*overflow:hidden', CSS), \
|
||||
"body must have overflow:hidden to prevent double scrollbars"
|
||||
|
||||
|
||||
def test_100dvh_viewport_height():
|
||||
"""Layout must use 100dvh (dynamic viewport height) for correct mobile sizing.
|
||||
|
||||
On mobile Safari and Chrome, 100vh includes the browser chrome (address bar),
|
||||
causing content to be hidden. 100dvh accounts for the actual available height.
|
||||
"""
|
||||
assert "100dvh" in CSS, \
|
||||
"style.css must use 100dvh for correct mobile viewport height (100vh hides content under address bar)"
|
||||
|
||||
|
||||
def test_composer_touch_target_size():
|
||||
"""Send button and composer inputs must have minimum 44px touch targets on mobile.
|
||||
|
||||
Apple HIG and Google Material guidelines both require 44px minimum touch targets.
|
||||
"""
|
||||
# Check that mobile CSS doesn't make the send button smaller than 44×44
|
||||
# We check that there's at least a min-height definition for touch targets
|
||||
assert re.search(r'(min-height|height).*44px', CSS), \
|
||||
"style.css must define 44px minimum touch targets for mobile (send button, nav buttons)"
|
||||
|
||||
|
||||
# ── Input zoom prevention ─────────────────────────────────────────────────────
|
||||
|
||||
def test_composer_textarea_font_size_mobile():
|
||||
"""Composer textarea must have font-size >= 16px on mobile.
|
||||
|
||||
iOS Safari zooms the viewport when an input with font-size < 16px is focused,
|
||||
which breaks the layout. The composer textarea must be >= 16px at mobile widths.
|
||||
"""
|
||||
# Check for 16px font-size on the textarea in a mobile breakpoint
|
||||
assert re.search(r'font-size:16px', CSS), \
|
||||
"Composer textarea must have font-size:16px at mobile widths to prevent iOS zoom-on-focus"
|
||||
|
||||
|
||||
|
||||
# ── Profiles button in mobile bottom nav ─────────────────────────────────────
|
||||
|
||||
def test_mobile_profiles_button_present():
|
||||
"""Mobile bottom nav must include a Profiles button (PR #265)."""
|
||||
assert 'data-panel="profiles"' in HTML and 'mobileSwitchPanel' in HTML, \
|
||||
"Mobile nav must have a Profiles button with data-panel='profiles' and mobileSwitchPanel"
|
||||
|
||||
|
||||
def test_mobile_profiles_button_uses_mobileSwitchPanel():
|
||||
"""Profiles mobile nav button must use mobileSwitchPanel, not raw switchPanel."""
|
||||
import re
|
||||
match = re.search(
|
||||
r'<button[^>]*mobile-nav-btn[^>]*data-panel="profiles"[^>]*>|'
|
||||
r'<button[^>]*data-panel="profiles"[^>]*mobile-nav-btn[^>]*>',
|
||||
HTML
|
||||
)
|
||||
assert match, "Could not find mobile-nav-btn with data-panel='profiles'"
|
||||
btn_html = HTML[match.start():match.start()+300]
|
||||
assert "mobileSwitchPanel('profiles')" in btn_html, \
|
||||
"Profiles mobile nav button must call mobileSwitchPanel('profiles')"
|
||||
|
||||
|
||||
def test_mobile_profiles_button_is_last_in_nav():
|
||||
"""Profiles button must appear after Spaces in the mobile bottom nav."""
|
||||
spaces_pos = HTML.find('data-panel="workspaces"')
|
||||
profiles_pos = HTML.rfind('data-panel="profiles"')
|
||||
assert spaces_pos > 0 and profiles_pos > spaces_pos, \
|
||||
"Profiles button must appear after Spaces button in the mobile nav"
|
||||
@@ -326,3 +326,98 @@ def test_default_model_lands_under_active_provider_group(monkeypatch):
|
||||
assert 'gpt-5.4' not in groups.get('Anthropic', []), (
|
||||
f"gpt-5.4 leaked into Anthropic group via fallback: {groups.get('Anthropic')}"
|
||||
)
|
||||
|
||||
|
||||
def test_custom_endpoint_uses_model_config_api_key_for_model_discovery(monkeypatch):
|
||||
"""Custom endpoint model discovery must use model.api_key from config.yaml,
|
||||
not only environment variables, otherwise the dropdown collapses to the
|
||||
default model when /v1/models requires auth."""
|
||||
import json as _json
|
||||
import api.config as _cfg
|
||||
|
||||
old_cfg = dict(_cfg.cfg)
|
||||
_cfg.cfg['model'] = {
|
||||
'provider': 'custom',
|
||||
'default': 'gpt-5.4',
|
||||
'base_url': 'https://example.test/v1',
|
||||
'api_key': 'sk-test-model-key',
|
||||
}
|
||||
_cfg.cfg.pop('providers', None)
|
||||
|
||||
captured = {}
|
||||
|
||||
class _Resp:
|
||||
def read(self):
|
||||
return _json.dumps({'data': [{'id': 'gpt-5.2', 'name': 'GPT-5.2'}]}).encode('utf-8')
|
||||
def __enter__(self):
|
||||
return self
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
def _fake_urlopen(req, timeout=10):
|
||||
captured['auth'] = req.get_header('Authorization')
|
||||
captured['ua'] = req.get_header('User-agent')
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr('urllib.request.urlopen', _fake_urlopen)
|
||||
monkeypatch.setattr('socket.getaddrinfo', lambda *a, **k: [])
|
||||
monkeypatch.delenv('OPENAI_API_KEY', raising=False)
|
||||
monkeypatch.delenv('HERMES_API_KEY', raising=False)
|
||||
monkeypatch.delenv('HERMES_OPENAI_API_KEY', raising=False)
|
||||
monkeypatch.delenv('LOCAL_API_KEY', raising=False)
|
||||
monkeypatch.delenv('OPENROUTER_API_KEY', raising=False)
|
||||
monkeypatch.delenv('API_KEY', raising=False)
|
||||
try:
|
||||
result = _cfg.get_available_models()
|
||||
finally:
|
||||
_cfg.cfg.clear()
|
||||
_cfg.cfg.update(old_cfg)
|
||||
|
||||
assert captured['auth'] == 'Bearer sk-test-model-key'
|
||||
assert captured['ua'] == 'OpenAI/Python 1.0'
|
||||
groups = {g['provider']: [m['id'] for m in g['models']] for g in result['groups']}
|
||||
assert 'Custom' in groups
|
||||
assert 'gpt-5.2' in groups['Custom']
|
||||
|
||||
|
||||
# -- Issue #230: custom provider with slash model name -----------------------
|
||||
|
||||
def test_custom_endpoint_slash_model_routes_to_custom_not_openrouter():
|
||||
"""Regression test for #230.
|
||||
|
||||
When provider=custom (or any non-openrouter provider) and base_url is set,
|
||||
a model name containing a slash (e.g. google/gemma-4-26b-a4b) must NOT be
|
||||
rerouted to OpenRouter -- it should stay on the configured custom endpoint.
|
||||
"""
|
||||
# --- custom provider with slash model name should NOT go to openrouter ---
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'google/gemma-4-26b-a4b',
|
||||
provider='custom',
|
||||
base_url='http://127.0.0.1:1234/v1',
|
||||
default='google/gemma-4-26b-a4b',
|
||||
)
|
||||
assert provider.startswith('custom'), (
|
||||
"Expected provider starting with 'custom', got '{}'. "
|
||||
"Slash in model name should NOT trigger OpenRouter rerouting when base_url is set.".format(provider)
|
||||
)
|
||||
assert base_url == 'http://127.0.0.1:1234/v1', (
|
||||
"Expected base_url 'http://127.0.0.1:1234/v1', got '{}'.".format(base_url)
|
||||
)
|
||||
assert model == 'google/gemma-4-26b-a4b', (
|
||||
"Model name should be preserved as-is, got '{}'.".format(model)
|
||||
)
|
||||
|
||||
# --- openrouter with slash model name MUST still route to openrouter -----
|
||||
model_or, provider_or, _ = _resolve_with_config(
|
||||
'google/gemma-4-26b-a4b',
|
||||
provider='openrouter',
|
||||
base_url='https://openrouter.ai/api/v1',
|
||||
default='google/gemma-4-26b-a4b',
|
||||
)
|
||||
assert provider_or == 'openrouter', (
|
||||
"Expected provider 'openrouter', got '{}'. "
|
||||
"Slash model via openrouter provider must still resolve to openrouter.".format(provider_or)
|
||||
)
|
||||
assert model_or == 'google/gemma-4-26b-a4b', (
|
||||
"Model name should be preserved for openrouter, got '{}'.".format(model_or)
|
||||
)
|
||||
|
||||
244
tests/test_onboarding_mvp.py
Normal file
244
tests/test_onboarding_mvp.py
Normal file
@@ -0,0 +1,244 @@
|
||||
"""Onboarding MVP tests — first-run wizard and provider config persistence.
|
||||
|
||||
Tests that call /api/onboarding/setup require PyYAML in the test server's
|
||||
Python environment (the agent venv). They are skipped when hermes-agent is
|
||||
not installed, since the server falls back to system Python which typically
|
||||
lacks pyyaml.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
|
||||
# Check if pyyaml is available — onboarding setup tests need it on the server
|
||||
try:
|
||||
import yaml as _yaml
|
||||
_HAS_YAML = True
|
||||
except ImportError:
|
||||
_HAS_YAML = False
|
||||
_needs_yaml = pytest.mark.skipif(not _HAS_YAML, reason="PyYAML not installed — onboarding setup tests require it")
|
||||
|
||||
|
||||
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):
|
||||
req = urllib.request.Request(
|
||||
BASE + path,
|
||||
data=json.dumps(body or {}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
def _server_hermes_home() -> pathlib.Path:
|
||||
"""Get the hermes home path the test server is actually using.
|
||||
|
||||
Using the server's own /api/onboarding/status response is more robust than
|
||||
reading TEST_STATE_DIR from conftest, which can get the wrong path when
|
||||
conftest is imported multiple times under different HERMES_HOME environments
|
||||
(api.config resets HERMES_HOME at module import time via init_profile_state).
|
||||
"""
|
||||
data, _ = get("/api/onboarding/status")
|
||||
env_path = data.get("system", {}).get("env_path", "")
|
||||
if env_path:
|
||||
return pathlib.Path(env_path).parent
|
||||
# Fallback
|
||||
hermes_home = pathlib.Path.home() / ".hermes"
|
||||
return hermes_home / "webui-mvp-test"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_hermes_config_files():
|
||||
hermes_home = _server_hermes_home()
|
||||
for rel in ("config.yaml", ".env"):
|
||||
(hermes_home / rel).unlink(missing_ok=True)
|
||||
yield
|
||||
for rel in ("config.yaml", ".env"):
|
||||
(hermes_home / rel).unlink(missing_ok=True)
|
||||
|
||||
|
||||
|
||||
def test_onboarding_status_defaults_incomplete():
|
||||
data, status = get("/api/onboarding/status")
|
||||
assert status == 200
|
||||
assert data["completed"] is False
|
||||
assert data["settings"]["password_enabled"] is False
|
||||
assert data["system"]["provider_configured"] is False
|
||||
assert data["system"]["chat_ready"] is False
|
||||
assert data["system"]["setup_state"] in {"needs_provider", "agent_unavailable"}
|
||||
assert "provider_note" in data["system"]
|
||||
assert isinstance(data["workspaces"]["items"], list)
|
||||
assert data["setup"]["providers"]
|
||||
|
||||
|
||||
@_needs_yaml
|
||||
def test_onboarding_setup_openrouter_writes_real_config_and_env():
|
||||
data, status = post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "sk-or-test",
|
||||
},
|
||||
)
|
||||
assert status == 200
|
||||
assert data["system"]["provider_configured"] is True
|
||||
assert data["system"]["provider_ready"] is True
|
||||
if data["system"]["imports_ok"] and data["system"]["hermes_found"]:
|
||||
assert data["system"]["chat_ready"] is True
|
||||
assert data["system"]["setup_state"] == "ready"
|
||||
else:
|
||||
assert data["system"]["chat_ready"] is False
|
||||
assert data["system"]["setup_state"] == "agent_unavailable"
|
||||
|
||||
cfg_text = (_server_hermes_home() / "config.yaml").read_text(encoding="utf-8")
|
||||
env_text = (_server_hermes_home() / ".env").read_text(encoding="utf-8")
|
||||
assert "provider: openrouter" in cfg_text
|
||||
assert "default: anthropic/claude-sonnet-4.6" in cfg_text
|
||||
assert "OPENROUTER_API_KEY=sk-or-test" in env_text
|
||||
|
||||
|
||||
@_needs_yaml
|
||||
def test_onboarding_setup_custom_endpoint_writes_runtime_files():
|
||||
data, status = post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "custom",
|
||||
"model": "google/gemma-3-27b-it",
|
||||
"base_url": "http://localhost:4000/v1",
|
||||
"api_key": "sk-custom-test",
|
||||
},
|
||||
)
|
||||
assert status == 200
|
||||
assert data["system"]["provider_configured"] is True
|
||||
assert data["system"]["provider_ready"] is True
|
||||
if data["system"]["imports_ok"] and data["system"]["hermes_found"]:
|
||||
assert data["system"]["chat_ready"] is True
|
||||
assert data["system"]["setup_state"] == "ready"
|
||||
else:
|
||||
assert data["system"]["chat_ready"] is False
|
||||
assert data["system"]["setup_state"] == "agent_unavailable"
|
||||
assert data["system"]["current_provider"] == "custom"
|
||||
assert data["system"]["current_base_url"] == "http://localhost:4000/v1"
|
||||
|
||||
cfg_text = (_server_hermes_home() / "config.yaml").read_text(encoding="utf-8")
|
||||
env_text = (_server_hermes_home() / ".env").read_text(encoding="utf-8")
|
||||
assert "provider: custom" in cfg_text
|
||||
assert "default: google/gemma-3-27b-it" in cfg_text
|
||||
assert "base_url: http://localhost:4000/v1" in cfg_text
|
||||
assert "OPENAI_API_KEY=sk-custom-test" in env_text
|
||||
|
||||
|
||||
@_needs_yaml
|
||||
def test_onboarding_setup_detects_incomplete_saved_provider():
|
||||
status, code = post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "anthropic",
|
||||
"model": "claude-sonnet-4.6",
|
||||
"api_key": "sk-ant-test",
|
||||
},
|
||||
)
|
||||
assert code == 200
|
||||
|
||||
(_server_hermes_home() / ".env").unlink(missing_ok=True)
|
||||
data, status_code = get("/api/onboarding/status")
|
||||
assert status_code == 200
|
||||
assert data["system"]["provider_configured"] is True
|
||||
assert data["system"]["provider_ready"] is False
|
||||
assert data["system"]["chat_ready"] is False
|
||||
assert data["system"]["setup_state"] in {"provider_incomplete", "agent_unavailable"}
|
||||
|
||||
|
||||
@_needs_yaml
|
||||
def test_onboarding_setup_rejects_missing_custom_base_url():
|
||||
data, status = post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "custom",
|
||||
"model": "qwen2.5-coder",
|
||||
"api_key": "sk-test",
|
||||
},
|
||||
)
|
||||
assert status == 400
|
||||
assert "base_url is required" in data["error"]
|
||||
|
||||
|
||||
def test_onboarding_complete_persists_flag():
|
||||
data, status = post("/api/onboarding/complete", {})
|
||||
assert status == 200
|
||||
assert data["completed"] is True
|
||||
|
||||
settings = json.loads(
|
||||
(_server_hermes_home() / "settings.json").read_text(encoding="utf-8")
|
||||
)
|
||||
assert settings["onboarding_completed"] is True
|
||||
|
||||
data2, status2 = get("/api/onboarding/status")
|
||||
assert status2 == 200
|
||||
assert data2["completed"] is True
|
||||
|
||||
|
||||
def test_onboarding_complete_preserves_other_settings():
|
||||
"""Completing onboarding must not overwrite other user settings."""
|
||||
# Use send_key (a safe enum setting) to verify settings preservation
|
||||
# without contaminating bot_name or theme checks in other test files.
|
||||
# Use GET /api/settings (not onboarding status) to check preservation
|
||||
# since the onboarding status only returns a subset of settings fields.
|
||||
try:
|
||||
saved, s1 = post("/api/settings", {"send_key": "ctrl+enter"})
|
||||
assert s1 == 200
|
||||
assert saved["send_key"] == "ctrl+enter"
|
||||
|
||||
_, s2 = post("/api/onboarding/complete", {})
|
||||
assert s2 == 200
|
||||
|
||||
# Verify the non-onboarding setting survived the completion call
|
||||
current_settings, s3 = get("/api/settings")
|
||||
assert s3 == 200
|
||||
assert current_settings["send_key"] == "ctrl+enter"
|
||||
finally:
|
||||
# Always restore default send_key to avoid contaminating other tests
|
||||
post("/api/settings", {"send_key": "enter"})
|
||||
|
||||
def test_onboarding_already_completed_status():
|
||||
"""After marking onboarding complete, status must reflect completed=True
|
||||
so the wizard does not re-appear for returning users."""
|
||||
done, status = post("/api/onboarding/complete", {})
|
||||
assert status == 200
|
||||
assert done["completed"] is True
|
||||
|
||||
data, status2 = get("/api/onboarding/status")
|
||||
assert status2 == 200
|
||||
assert data["completed"] is True
|
||||
|
||||
# Reset so test doesn't contaminate others
|
||||
post("/api/settings", {"onboarding_completed": False})
|
||||
|
||||
|
||||
@_needs_yaml
|
||||
def test_onboarding_setup_rejects_api_key_with_newline():
|
||||
"""API keys containing embedded newlines must be rejected to prevent .env injection."""
|
||||
injected_key = "sk-bad" + chr(10) + "OTHER_KEY=injected"
|
||||
data, status = post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": injected_key,
|
||||
},
|
||||
)
|
||||
assert status == 400
|
||||
assert "newline" in data["error"].lower()
|
||||
58
tests/test_onboarding_static.py
Normal file
58
tests/test_onboarding_static.py
Normal file
@@ -0,0 +1,58 @@
|
||||
import pathlib
|
||||
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
|
||||
|
||||
def read(path):
|
||||
return (REPO / path).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_index_contains_onboarding_overlay_markup():
|
||||
html = read("static/index.html")
|
||||
assert 'id="onboardingOverlay"' in html
|
||||
assert 'id="onboardingBody"' in html
|
||||
assert 'id="onboardingNextBtn"' in html
|
||||
assert 'src="/static/onboarding.js"' in html
|
||||
|
||||
|
||||
def test_onboarding_css_rules_exist():
|
||||
css = read("static/style.css")
|
||||
for selector in (
|
||||
".onboarding-overlay",
|
||||
".onboarding-card",
|
||||
".onboarding-step",
|
||||
".onboarding-status.warn",
|
||||
):
|
||||
assert selector in css
|
||||
|
||||
|
||||
def test_onboarding_js_exposes_bootstrap_hooks():
|
||||
js = read("static/onboarding.js")
|
||||
assert "async function loadOnboardingWizard()" in js
|
||||
assert "async function nextOnboardingStep()" in js
|
||||
assert "api('/api/onboarding/status')" in js
|
||||
assert "api('/api/onboarding/setup'" in js
|
||||
assert "api('/api/onboarding/complete'" in js
|
||||
|
||||
|
||||
def test_onboarding_uses_i18n_helpers():
|
||||
html = read("static/index.html")
|
||||
js = read("static/onboarding.js")
|
||||
i18n = read("static/i18n.js")
|
||||
assert 'data-i18n="onboarding_title"' in html
|
||||
assert 'data-i18n="onboarding_continue"' in html
|
||||
assert "t('onboarding_step_system_title')" in js
|
||||
assert "t('onboarding_step_setup_title')" in js
|
||||
assert "t('onboarding_complete')" in js
|
||||
assert "onboarding_title: 'Welcome to Hermes Web UI'" in i18n
|
||||
assert "onboarding_title: 'Bienvenido a Hermes Web UI'" in i18n
|
||||
|
||||
|
||||
def test_bootstrap_script_contains_official_installer_and_windows_guard():
|
||||
src = read("bootstrap.py")
|
||||
assert (
|
||||
"https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh"
|
||||
in src
|
||||
)
|
||||
assert "Native Windows is not supported" in src
|
||||
266
tests/test_provider_mismatch.py
Normal file
266
tests/test_provider_mismatch.py
Normal file
@@ -0,0 +1,266 @@
|
||||
"""
|
||||
Tests for issue #266 — provider/model mismatch warning.
|
||||
|
||||
Covers:
|
||||
1. streaming.py: auth errors detected and classified as 'auth_mismatch'
|
||||
2. static/ui.js: _checkProviderMismatch() helper exists and logic is correct
|
||||
3. static/messages.js: apperror handler has auth_mismatch branch
|
||||
4. static/i18n.js: provider_mismatch_warning and provider_mismatch_label keys
|
||||
present in all 5 locales (en, es, de, zh, zh-Hant)
|
||||
5. static/boot.js: modelSelect.onchange calls _checkProviderMismatch
|
||||
6. /api/models: response includes active_provider field
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import urllib.request
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
|
||||
|
||||
def _read(rel_path: str) -> str:
|
||||
return (REPO_ROOT / rel_path).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── 1. streaming.py: auth error detection ───────────────────────────────────
|
||||
|
||||
class TestStreamingAuthErrorDetection:
|
||||
"""streaming.py must classify auth/401 errors as auth_mismatch."""
|
||||
|
||||
def test_auth_mismatch_type_defined_in_streaming(self):
|
||||
"""'auth_mismatch' type must be emitted for auth errors."""
|
||||
src = _read("api/streaming.py")
|
||||
assert "auth_mismatch" in src, (
|
||||
"auth_mismatch type not found in streaming.py — "
|
||||
"401/auth errors will not be surfaced with a helpful message"
|
||||
)
|
||||
|
||||
def test_is_auth_error_flag_defined(self):
|
||||
"""is_auth_error variable must exist in the error handler."""
|
||||
src = _read("api/streaming.py")
|
||||
assert "is_auth_error" in src, (
|
||||
"is_auth_error flag not found in streaming.py"
|
||||
)
|
||||
|
||||
def test_auth_error_detects_401(self):
|
||||
"""'401' must be part of the auth error detection logic."""
|
||||
src = _read("api/streaming.py")
|
||||
# Find the is_auth_error block
|
||||
idx = src.find("is_auth_error")
|
||||
assert idx != -1
|
||||
block = src[idx:idx + 400]
|
||||
assert "'401'" in block or '"401"' in block, (
|
||||
"'401' not in is_auth_error detection block"
|
||||
)
|
||||
|
||||
def test_auth_error_detects_unauthorized(self):
|
||||
"""'unauthorized' must be part of the auth error detection logic."""
|
||||
src = _read("api/streaming.py")
|
||||
idx = src.find("is_auth_error")
|
||||
block = src[idx:idx + 400]
|
||||
assert "unauthorized" in block.lower(), (
|
||||
"'unauthorized' not in is_auth_error detection block"
|
||||
)
|
||||
|
||||
def test_auth_error_hint_mentions_hermes_model(self):
|
||||
"""The auth_mismatch hint must mention 'hermes model' command."""
|
||||
src = _read("api/streaming.py")
|
||||
# Find the auth_mismatch apperror block
|
||||
idx = src.find("auth_mismatch")
|
||||
block = src[idx:idx + 500]
|
||||
assert "hermes model" in block, (
|
||||
"auth_mismatch hint must mention 'hermes model' command "
|
||||
"so users know how to fix provider mismatch"
|
||||
)
|
||||
|
||||
def test_auth_error_does_not_catch_rate_limit(self):
|
||||
"""Rate limit errors must not be reclassified as auth_mismatch."""
|
||||
src = _read("api/streaming.py")
|
||||
# is_rate_limit must come before is_auth_error in the elif chain
|
||||
rl_idx = src.find("is_rate_limit")
|
||||
ae_idx = src.find("is_auth_error")
|
||||
assert rl_idx < ae_idx, (
|
||||
"is_rate_limit check should precede is_auth_error — "
|
||||
"rate limit errors must not be mistaken for auth errors"
|
||||
)
|
||||
|
||||
|
||||
# ── 2. static/ui.js: _checkProviderMismatch() ───────────────────────────────
|
||||
|
||||
class TestCheckProviderMismatch:
|
||||
"""ui.js must expose _checkProviderMismatch() helper."""
|
||||
|
||||
def test_function_defined(self):
|
||||
"""_checkProviderMismatch function must be defined in ui.js."""
|
||||
src = _read("static/ui.js")
|
||||
assert "function _checkProviderMismatch" in src, (
|
||||
"_checkProviderMismatch not defined in ui.js"
|
||||
)
|
||||
|
||||
def test_uses_window_active_provider(self):
|
||||
"""Function must read window._activeProvider."""
|
||||
src = _read("static/ui.js")
|
||||
idx = src.find("function _checkProviderMismatch")
|
||||
block = src[idx:idx + 800]
|
||||
assert "_activeProvider" in block, (
|
||||
"_checkProviderMismatch must read window._activeProvider"
|
||||
)
|
||||
|
||||
def test_skips_check_for_openrouter(self):
|
||||
"""OpenRouter can route to any provider — skip the warning."""
|
||||
src = _read("static/ui.js")
|
||||
idx = src.find("function _checkProviderMismatch")
|
||||
block = src[idx:idx + 800]
|
||||
assert "openrouter" in block.lower(), (
|
||||
"_checkProviderMismatch must skip the check for openrouter"
|
||||
)
|
||||
|
||||
def test_skips_check_for_custom(self):
|
||||
"""Custom endpoints can serve any model — skip the warning."""
|
||||
src = _read("static/ui.js")
|
||||
idx = src.find("function _checkProviderMismatch")
|
||||
block = src[idx:idx + 800]
|
||||
assert "custom" in block.lower(), (
|
||||
"_checkProviderMismatch must skip the check for custom provider"
|
||||
)
|
||||
|
||||
def test_active_provider_stored_on_model_load(self):
|
||||
"""populateModelDropdown must store active_provider from /api/models."""
|
||||
src = _read("static/ui.js")
|
||||
# Find the function definition (skip the comment that also mentions the name)
|
||||
idx = src.find("async function populateModelDropdown")
|
||||
assert idx != -1, "async function populateModelDropdown not found"
|
||||
block = src[idx:idx + 800]
|
||||
assert "_activeProvider" in block, (
|
||||
"populateModelDropdown must set window._activeProvider "
|
||||
"from the /api/models response"
|
||||
)
|
||||
|
||||
|
||||
# ── 3. static/messages.js: apperror handler ─────────────────────────────────
|
||||
|
||||
class TestApperrorHandler:
|
||||
"""messages.js apperror handler must handle auth_mismatch type."""
|
||||
|
||||
def test_auth_mismatch_type_handled(self):
|
||||
"""apperror handler must check for type='auth_mismatch'."""
|
||||
src = _read("static/messages.js")
|
||||
assert "auth_mismatch" in src, (
|
||||
"auth_mismatch type not handled in messages.js apperror handler"
|
||||
)
|
||||
|
||||
def test_provider_mismatch_label(self):
|
||||
"""'Provider mismatch' label must appear in the error handling."""
|
||||
src = _read("static/messages.js")
|
||||
assert "Provider mismatch" in src, (
|
||||
"'Provider mismatch' label not found in messages.js"
|
||||
)
|
||||
|
||||
def test_is_auth_mismatch_variable(self):
|
||||
"""isAuthMismatch variable must be defined."""
|
||||
src = _read("static/messages.js")
|
||||
assert "isAuthMismatch" in src, (
|
||||
"isAuthMismatch variable not found in messages.js apperror handler"
|
||||
)
|
||||
|
||||
|
||||
# ── 4. static/i18n.js: all 5 locales ────────────────────────────────────────
|
||||
|
||||
class TestI18nProviderMismatch:
|
||||
"""All 5 locales must have provider_mismatch_warning and provider_mismatch_label."""
|
||||
|
||||
REQUIRED_KEYS = ["provider_mismatch_warning", "provider_mismatch_label"]
|
||||
|
||||
def _count_key(self, src: str, key: str) -> int:
|
||||
return len(re.findall(r'\b' + re.escape(key) + r'\b', src))
|
||||
|
||||
def test_all_locales_have_warning_key(self):
|
||||
"""provider_mismatch_warning must appear in all 5 locales."""
|
||||
src = _read("static/i18n.js")
|
||||
count = self._count_key(src, "provider_mismatch_warning")
|
||||
assert count >= 5, (
|
||||
f"provider_mismatch_warning found {count} times, expected >= 5 "
|
||||
f"(one per locale: en, es, de, zh, zh-Hant)"
|
||||
)
|
||||
|
||||
def test_all_locales_have_label_key(self):
|
||||
"""provider_mismatch_label must appear in all 5 locales."""
|
||||
src = _read("static/i18n.js")
|
||||
count = self._count_key(src, "provider_mismatch_label")
|
||||
assert count >= 5, (
|
||||
f"provider_mismatch_label found {count} times, expected >= 5"
|
||||
)
|
||||
|
||||
def test_warning_is_function_in_en(self):
|
||||
"""English provider_mismatch_warning must be a function (m, p) => ..."""
|
||||
src = _read("static/i18n.js")
|
||||
# Find the en block
|
||||
en_start = src.find("\n en: {")
|
||||
es_start = src.find("\n es: {")
|
||||
en_block = src[en_start:es_start]
|
||||
assert "provider_mismatch_warning" in en_block, "Key not in en block"
|
||||
idx = en_block.find("provider_mismatch_warning")
|
||||
line = en_block[idx:idx + 200]
|
||||
# Must be a function, not a plain string
|
||||
assert "=>" in line, (
|
||||
"provider_mismatch_warning in en locale must be an arrow function "
|
||||
"that takes (m, p) parameters for model and provider interpolation"
|
||||
)
|
||||
|
||||
def test_spanish_locale_key_coverage(self):
|
||||
"""Spanish locale must have the new keys (parity with English)."""
|
||||
src = _read("static/i18n.js")
|
||||
es_start = src.find("\n es: {")
|
||||
de_start = src.find("\n de: {")
|
||||
es_block = src[es_start:de_start]
|
||||
for key in self.REQUIRED_KEYS:
|
||||
assert key in es_block, f"Key '{key}' missing from Spanish locale"
|
||||
|
||||
|
||||
# ── 5. static/boot.js: dropdown change handler ──────────────────────────────
|
||||
|
||||
class TestBootModelSelectChange:
|
||||
"""boot.js modelSelect.onchange must call _checkProviderMismatch."""
|
||||
|
||||
def test_onchange_calls_check_function(self):
|
||||
"""modelSelect.onchange must invoke _checkProviderMismatch."""
|
||||
src = _read("static/boot.js")
|
||||
assert "_checkProviderMismatch" in src, (
|
||||
"boot.js modelSelect.onchange must call _checkProviderMismatch "
|
||||
"to warn users about provider/model mismatches"
|
||||
)
|
||||
# Verify it's called from the onchange handler (near modelSelect.onchange)
|
||||
idx = src.find("'modelSelect').onchange") or src.find('"modelSelect").onchange')
|
||||
if idx == -1:
|
||||
# Try alternate patterns
|
||||
idx = src.find("modelSelect")
|
||||
block_start = src.rfind("\n", 0, src.find("_checkProviderMismatch")) or 0
|
||||
surrounding = src[max(0, block_start - 200):block_start + 400]
|
||||
assert "modelSelect" in surrounding or "selectedModel" in surrounding, (
|
||||
"_checkProviderMismatch must be called in the context of model selection"
|
||||
)
|
||||
|
||||
def test_onchange_shows_toast_on_mismatch(self):
|
||||
"""The warning must be shown via showToast, not alert()."""
|
||||
src = _read("static/boot.js")
|
||||
# Both _checkProviderMismatch call and showToast must be near each other
|
||||
idx = src.find("_checkProviderMismatch")
|
||||
assert idx != -1, "_checkProviderMismatch not found in boot.js"
|
||||
block = src[idx:idx + 300]
|
||||
assert "showToast" in block, (
|
||||
"Provider mismatch warning must be shown via showToast(), not alert()"
|
||||
)
|
||||
|
||||
|
||||
# ── 6. /api/models: active_provider in response ──────────────────────────────
|
||||
|
||||
def test_api_models_includes_active_provider():
|
||||
"""/api/models must include 'active_provider' key in response."""
|
||||
with urllib.request.urlopen(BASE + "/api/models", timeout=10) as r:
|
||||
data = json.loads(r.read())
|
||||
# active_provider can be None/null but the key must exist
|
||||
assert "active_provider" in data, (
|
||||
"/api/models response missing 'active_provider' field — "
|
||||
"frontend needs this to detect provider mismatches"
|
||||
)
|
||||
@@ -286,7 +286,11 @@ def test_server_delete_invalidates_index(cleanup_test_sessions):
|
||||
routes_src = (REPO_ROOT / "api" / "routes.py").read_text() if (REPO_ROOT / "api" / "routes.py").exists() else ""
|
||||
# Find the delete handler in either file
|
||||
for label, text in [("server.py", src), ("api/routes.py", routes_src)]:
|
||||
delete_idx = text.find("if parsed.path == '/api/session/delete':")
|
||||
# Accept both single-quote and double-quote style (formatting varies by contributor)
|
||||
delete_idx = max(
|
||||
text.find("if parsed.path == '/api/session/delete':"),
|
||||
text.find('if parsed.path == "/api/session/delete":'),
|
||||
)
|
||||
if delete_idx >= 0:
|
||||
delete_block = text[delete_idx:delete_idx+600]
|
||||
assert "SESSION_INDEX_FILE" in delete_block, \
|
||||
@@ -472,3 +476,24 @@ def test_upload_error_has_no_trace_field():
|
||||
assert "trace" not in body, \
|
||||
"Upload errors must not leak stack traces to clients"
|
||||
assert "error" in body, "Error responses must include an 'error' key"
|
||||
|
||||
|
||||
# ── #248: /skills slash command ───────────────────────────────────────────────
|
||||
|
||||
def test_skills_slash_command_defined():
|
||||
"""#248: /skills command must be registered in COMMANDS and implemented.
|
||||
Verifies the command entry, function definition, and i18n key are all present.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/commands.js").read_text()
|
||||
|
||||
# 1. 'skills' must appear in the COMMANDS array definition
|
||||
assert "name:'skills'" in src or 'name:"skills"' in src, \
|
||||
"COMMANDS array must include an entry with name:'skills'"
|
||||
|
||||
# 2. cmdSkills function must be defined
|
||||
assert "function cmdSkills" in src, \
|
||||
"cmdSkills function must be defined in commands.js"
|
||||
|
||||
# 3. i18n key cmd_skills must be referenced (wired to COMMANDS entry)
|
||||
assert "cmd_skills" in src, \
|
||||
"cmd_skills i18n key must be referenced in commands.js"
|
||||
|
||||
310
tests/test_security_redaction.py
Normal file
310
tests/test_security_redaction.py
Normal file
@@ -0,0 +1,310 @@
|
||||
"""
|
||||
Security tests: credential redaction in API responses.
|
||||
|
||||
Verifies that credentials (GitHub PATs, API keys, etc.) are masked in:
|
||||
- GET /api/session (messages and tool_calls)
|
||||
- GET /api/memory (MEMORY.md and USER.md content)
|
||||
- GET /api/session/export (downloaded JSON)
|
||||
- SSE done event (session payload in stream)
|
||||
|
||||
Tests run against the isolated test test_server on port 8788.
|
||||
"""
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent.parent))
|
||||
|
||||
|
||||
def _server_is_up(port: int = 8788) -> bool:
|
||||
"""Return True if the test server is accepting connections."""
|
||||
try:
|
||||
urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=2)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# _needs_server: these tests require the conftest test_server fixture (port 8788).
|
||||
# The skipif is evaluated lazily via the fixture, not at collection time.
|
||||
_needs_server = pytest.mark.usefixtures("test_server")
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
|
||||
# Sample credentials that should be masked in every API response
|
||||
_FAKE_GITHUB_PAT = "ghp_TestFakeCredential1234567890ab"
|
||||
_FAKE_SK_KEY = "sk-TestFakeOpenAIKey1234567890abcdef"
|
||||
_FAKE_HF_TOKEN = "hf_TestFakeHuggingFaceToken12345"
|
||||
_FAKE_AWS_KEY = "AKIATESTFAKEKEY12345"
|
||||
|
||||
|
||||
# ── HTTP helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
def _get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def _post(path, body=None):
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(
|
||||
BASE + path, data=data,
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
def _get_raw(path):
|
||||
"""Return raw bytes (used for export endpoint)."""
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return r.read()
|
||||
|
||||
|
||||
def _assert_no_plaintext_credentials(text: str, label: str = ""):
|
||||
"""Assert that none of the fake credential strings appear in text."""
|
||||
for cred in (_FAKE_GITHUB_PAT, _FAKE_SK_KEY, _FAKE_HF_TOKEN, _FAKE_AWS_KEY):
|
||||
assert cred not in text, (
|
||||
f"{label}: credential '{cred[:12]}...' found in plaintext. "
|
||||
"Redaction is not working."
|
||||
)
|
||||
|
||||
|
||||
# ── helpers.py unit tests (import-level, no test_server needed) ───────────────────
|
||||
|
||||
def test_redact_value_str():
|
||||
"""_redact_value masks a plaintext GitHub PAT in a string."""
|
||||
from api.helpers import _redact_value
|
||||
result = _redact_value(f"my token is {_FAKE_GITHUB_PAT} bye")
|
||||
assert _FAKE_GITHUB_PAT not in result
|
||||
assert "ghp_Te" in result # prefix preserved
|
||||
|
||||
|
||||
def test_redact_value_dict():
|
||||
"""_redact_value recurses into dicts."""
|
||||
from api.helpers import _redact_value
|
||||
d = {"content": f"key={_FAKE_SK_KEY}", "role": "user"}
|
||||
result = _redact_value(d)
|
||||
assert _FAKE_SK_KEY not in result["content"]
|
||||
assert result["role"] == "user" # innocent values untouched
|
||||
|
||||
|
||||
def test_redact_value_list():
|
||||
"""_redact_value recurses into lists."""
|
||||
from api.helpers import _redact_value
|
||||
lst = [{"content": _FAKE_GITHUB_PAT}, {"content": "safe text"}]
|
||||
result = _redact_value(lst)
|
||||
assert _FAKE_GITHUB_PAT not in result[0]["content"]
|
||||
assert result[1]["content"] == "safe text"
|
||||
|
||||
|
||||
def test_redact_session_data_messages():
|
||||
"""redact_session_data masks credentials in messages[]."""
|
||||
from api.helpers import redact_session_data
|
||||
session = {
|
||||
"session_id": "abc123",
|
||||
"title": f"my token {_FAKE_GITHUB_PAT}",
|
||||
"messages": [
|
||||
{"role": "user", "content": f"token: {_FAKE_GITHUB_PAT}"},
|
||||
{"role": "assistant", "content": "sure"},
|
||||
],
|
||||
"tool_calls": [
|
||||
{"name": "terminal", "args": {"command": f"gh auth login --token {_FAKE_GITHUB_PAT}"},
|
||||
"snippet": "ok"},
|
||||
],
|
||||
}
|
||||
result = redact_session_data(session)
|
||||
dump = json.dumps(result)
|
||||
_assert_no_plaintext_credentials(dump, "redact_session_data")
|
||||
# Safe fields remain intact
|
||||
assert result["session_id"] == "abc123"
|
||||
assert result["messages"][1]["content"] == "sure"
|
||||
|
||||
|
||||
def test_redact_session_data_multiple_cred_types():
|
||||
"""redact_session_data handles sk-, ghp_, hf_, and AKIA keys."""
|
||||
from api.helpers import redact_session_data
|
||||
session = {
|
||||
"title": "test",
|
||||
"messages": [{"role": "user", "content": (
|
||||
f"openai={_FAKE_SK_KEY} "
|
||||
f"github={_FAKE_GITHUB_PAT} "
|
||||
f"hf={_FAKE_HF_TOKEN} "
|
||||
f"aws={_FAKE_AWS_KEY}"
|
||||
)}],
|
||||
"tool_calls": [],
|
||||
}
|
||||
result = redact_session_data(session)
|
||||
dump = json.dumps(result)
|
||||
_assert_no_plaintext_credentials(dump, "multi-type redaction")
|
||||
|
||||
|
||||
def test_redact_session_data_non_sensitive_unchanged():
|
||||
"""redact_session_data does not corrupt innocent content."""
|
||||
from api.helpers import redact_session_data
|
||||
session = {
|
||||
"title": "Hello world",
|
||||
"messages": [{"role": "user", "content": "What is 2+2?"}],
|
||||
"tool_calls": [{"name": "terminal", "snippet": "4"}],
|
||||
}
|
||||
result = redact_session_data(session)
|
||||
assert result["title"] == "Hello world"
|
||||
assert result["messages"][0]["content"] == "What is 2+2?"
|
||||
assert result["tool_calls"][0]["snippet"] == "4"
|
||||
|
||||
|
||||
# ── API-level tests (require running test server started by conftest.py) ─────
|
||||
# Run via `start.sh && pytest tests/test_security_redaction.py -v`
|
||||
|
||||
def _create_session_with_credentials() -> str:
|
||||
"""Write a session file with credential-containing messages directly to disk.
|
||||
|
||||
Bypasses the server's in-memory cache so the GET endpoint is forced to read
|
||||
from disk, exercising the redaction code path on load.
|
||||
Uses TEST_STATE_DIR from conftest.py (the isolated test server state directory).
|
||||
"""
|
||||
import time, uuid
|
||||
try:
|
||||
from conftest import TEST_STATE_DIR
|
||||
sessions_dir = TEST_STATE_DIR / "sessions"
|
||||
except ImportError:
|
||||
from api.config import SESSION_DIR as sessions_dir
|
||||
sessions_dir = pathlib.Path(sessions_dir)
|
||||
sessions_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Use a unique session ID that is NOT in the server's LRU cache
|
||||
sid = "sec_test_" + uuid.uuid4().hex[:8]
|
||||
now = time.time()
|
||||
session_file = sessions_dir / f"{sid}.json"
|
||||
session_file.write_text(json.dumps({
|
||||
"session_id": sid,
|
||||
"title": f"session with {_FAKE_GITHUB_PAT}",
|
||||
"workspace": "/tmp",
|
||||
"model": "test",
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
"pinned": False, "archived": False, "project_id": None,
|
||||
"profile": "default", "input_tokens": 0, "output_tokens": 0,
|
||||
"estimated_cost": None, "personality": None,
|
||||
"messages": [
|
||||
{"role": "user", "content": f"my PAT is {_FAKE_GITHUB_PAT}"},
|
||||
{"role": "assistant", "content": f"sk key is {_FAKE_SK_KEY}"},
|
||||
{"role": "tool", "content": "result ok", "name": "terminal"},
|
||||
],
|
||||
"tool_calls": [
|
||||
{"name": "terminal",
|
||||
"args": {"command": f"gh auth login --token {_FAKE_GITHUB_PAT}"},
|
||||
"snippet": "blocked"}
|
||||
],
|
||||
}))
|
||||
return sid
|
||||
|
||||
|
||||
def test_api_session_redacts_messages():
|
||||
"""GET /api/session route must call redact_session_data() before returning."""
|
||||
import inspect
|
||||
import api.routes as routes
|
||||
src = inspect.getsource(routes.handle_get)
|
||||
# Verify redact_session_data is applied to the session payload
|
||||
assert "redact_session_data" in src, (
|
||||
"api/routes.py handle_get must call redact_session_data() on /api/session response"
|
||||
)
|
||||
|
||||
|
||||
def test_api_session_redacts_title():
|
||||
"""redact_session_data must redact credentials from session title field."""
|
||||
from api.helpers import redact_session_data
|
||||
session = {
|
||||
"session_id": "abc123",
|
||||
"title": f"session with {_FAKE_GITHUB_PAT}",
|
||||
"messages": [],
|
||||
"tool_calls": [],
|
||||
}
|
||||
result = redact_session_data(session)
|
||||
assert _FAKE_GITHUB_PAT not in result["title"], (
|
||||
f"redact_session_data must mask credentials in title field"
|
||||
)
|
||||
assert result["session_id"] == "abc123" # safe fields preserved
|
||||
|
||||
|
||||
@_needs_server
|
||||
def test_api_sessions_list_redacts_titles(test_server):
|
||||
"""GET /api/sessions must not return session titles containing credentials."""
|
||||
_create_session_with_credentials()
|
||||
data = _get("/api/sessions")
|
||||
dump = json.dumps(data)
|
||||
_assert_no_plaintext_credentials(dump, "GET /api/sessions titles")
|
||||
|
||||
|
||||
def test_api_session_export_redacts():
|
||||
"""GET /api/session/export must call redact_session_data() in _handle_session_export."""
|
||||
import inspect
|
||||
import api.routes as routes
|
||||
# The export handler is a separate function (_handle_session_export)
|
||||
src = inspect.getsource(routes._handle_session_export)
|
||||
assert "redact_session_data" in src, (
|
||||
"_handle_session_export must call redact_session_data() before serving download"
|
||||
)
|
||||
|
||||
|
||||
@_needs_server
|
||||
def test_api_memory_redacts_via_write_read(test_server):
|
||||
"""Credential written to MEMORY.md must be masked in GET /api/memory response."""
|
||||
original = _get("/api/memory").get("memory", "")
|
||||
|
||||
cred_content = f"GitHub PAT: {_FAKE_GITHUB_PAT}\nNormal note: hello world"
|
||||
data, status = _post("/api/memory/write", {"section": "memory", "content": cred_content})
|
||||
assert status == 200, f"memory/write failed: {data}"
|
||||
|
||||
try:
|
||||
read_back = _get("/api/memory")
|
||||
dump = json.dumps(read_back)
|
||||
_assert_no_plaintext_credentials(dump, "GET /api/memory")
|
||||
assert "hello world" in read_back["memory"] # non-sensitive content preserved
|
||||
finally:
|
||||
_post("/api/memory/write", {"section": "memory", "content": original})
|
||||
|
||||
|
||||
# ── startup: fix_credential_permissions ──────────────────────────────────────
|
||||
|
||||
def test_fix_credential_permissions_corrects_loose_files(tmp_path, monkeypatch):
|
||||
"""fix_credential_permissions() tightens group/other read bits."""
|
||||
import os
|
||||
from api.startup import fix_credential_permissions
|
||||
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("SECRET=abc")
|
||||
env_file.chmod(0o644) # world-readable -- should be fixed
|
||||
|
||||
google_file = tmp_path / "google_token.json"
|
||||
google_file.write_text("{}")
|
||||
google_file.chmod(0o664) # group-readable -- should be fixed
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
fix_credential_permissions()
|
||||
|
||||
import stat
|
||||
assert stat.S_IMODE(env_file.stat().st_mode) == 0o600, ".env not fixed to 600"
|
||||
assert stat.S_IMODE(google_file.stat().st_mode) == 0o600, "google_token.json not fixed to 600"
|
||||
|
||||
|
||||
def test_fix_credential_permissions_skips_correct_files(tmp_path, monkeypatch):
|
||||
"""fix_credential_permissions() does not alter already-strict files."""
|
||||
env_file = tmp_path / ".env"
|
||||
env_file.write_text("SECRET=abc")
|
||||
env_file.chmod(0o600)
|
||||
|
||||
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
|
||||
|
||||
from api.startup import fix_credential_permissions
|
||||
fix_credential_permissions()
|
||||
|
||||
import stat
|
||||
assert stat.S_IMODE(env_file.stat().st_mode) == 0o600
|
||||
45
tests/test_spanish_locale.py
Normal file
45
tests/test_spanish_locale.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def read(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_spanish_locale_block_exists():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
assert "\n es: {" in src
|
||||
assert "_label: 'Español'" in src
|
||||
assert "_speech: 'es-ES'" in src
|
||||
|
||||
|
||||
def test_spanish_locale_includes_representative_translations():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
expected = [
|
||||
"settings_title: 'Configuración'",
|
||||
"login_title: 'Iniciar sesión'",
|
||||
"approval_heading: 'Se requiere aprobación'",
|
||||
"tab_tasks: 'Tareas'",
|
||||
"tab_skills: 'Habilidades'",
|
||||
"tab_memory: 'Memoria'",
|
||||
]
|
||||
for entry in expected:
|
||||
assert entry in src
|
||||
|
||||
|
||||
def test_spanish_locale_covers_english_keys():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
en_match = re.search(r"\n en: \{([\s\S]*?)\n \},\n\n es: \{", src)
|
||||
es_match = re.search(r"\n es: \{([\s\S]*?)\n \},\n\n de: \{", src)
|
||||
assert en_match, "English locale block not found"
|
||||
assert es_match, "Spanish locale block not found"
|
||||
|
||||
key_pattern = re.compile(r"^\s{4}([a-zA-Z0-9_]+):", re.MULTILINE)
|
||||
en_keys = set(key_pattern.findall(en_match.group(1)))
|
||||
es_keys = set(key_pattern.findall(es_match.group(1)))
|
||||
|
||||
missing = sorted(en_keys - es_keys)
|
||||
assert not missing, f"Spanish locale missing keys: {missing}"
|
||||
@@ -700,10 +700,20 @@ def test_style_css_active_session_uses_gold(cleanup_test_sessions):
|
||||
"Active session gold color (#e8a030) not found in style.css"
|
||||
|
||||
|
||||
def test_sessions_js_active_skips_project_border(cleanup_test_sessions):
|
||||
"""sessions.js must not override active session border-left with project color."""
|
||||
def test_sessions_js_uses_action_menu_not_per_row_buttons(cleanup_test_sessions):
|
||||
"""sessions.js must use the single ⋯ action menu instead of per-row buttons.
|
||||
|
||||
The per-row button overlay was replaced with a single ⋯ trigger that opens a
|
||||
positioned dropdown (session-action-menu). This removes the borderLeftColor
|
||||
project colour override that the old code applied, which was the original
|
||||
concern this test guarded. The new design uses a dot indicator for project
|
||||
membership instead.
|
||||
"""
|
||||
src = REPO_ROOT / "static" / "sessions.js"
|
||||
code = src.read_text()
|
||||
# The fix: only set borderLeftColor if NOT the active session
|
||||
assert "isActive" in code, "isActive check not found in sessions.js"
|
||||
assert "borderLeftColor" in code, "borderLeftColor not found in sessions.js"
|
||||
assert "session-actions-trigger" in code, "session-actions-trigger not found in sessions.js"
|
||||
assert "_openSessionActionMenu" in code, "_openSessionActionMenu not found in sessions.js"
|
||||
assert "closeSessionActionMenu" in code, "closeSessionActionMenu not found in sessions.js"
|
||||
# The old per-row buttons must not be present (they were replaced by the menu)
|
||||
assert "act-pin" not in code, "old act-pin per-row button still in sessions.js"
|
||||
assert "act-archive" not in code, "old act-archive per-row button still in sessions.js"
|
||||
|
||||
@@ -280,3 +280,107 @@ class TestApprovalRespondHTTP:
|
||||
assert status == 200
|
||||
assert "choice" in result
|
||||
assert result["choice"] == "always"
|
||||
|
||||
|
||||
class TestApprovalCardTimerLogic:
|
||||
"""Tests for the 30s minimum visibility guard introduced in PR #225."""
|
||||
|
||||
def _get_js(self):
|
||||
return pathlib.Path(__file__).parent.parent / 'static' / 'messages.js'
|
||||
|
||||
def test_approval_min_visible_ms_constant_present(self):
|
||||
"""APPROVAL_MIN_VISIBLE_MS constant exists and is 30000."""
|
||||
src = self._get_js().read_text()
|
||||
assert 'APPROVAL_MIN_VISIBLE_MS' in src
|
||||
import re
|
||||
m = re.search(r'APPROVAL_MIN_VISIBLE_MS\s*=\s*(\d+)', src)
|
||||
assert m is not None, 'APPROVAL_MIN_VISIBLE_MS not assigned'
|
||||
assert int(m.group(1)) == 30000, f'Expected 30000, got {m.group(1)}'
|
||||
|
||||
def test_hide_approval_card_has_force_parameter(self):
|
||||
"""hideApprovalCard() accepts a force parameter."""
|
||||
src = self._get_js().read_text()
|
||||
assert 'hideApprovalCard(force=false)' in src or \
|
||||
'hideApprovalCard(force = false)' in src, \
|
||||
'hideApprovalCard must have force=false default parameter'
|
||||
|
||||
def test_hide_approval_card_checks_force_flag(self):
|
||||
"""hideApprovalCard body has a conditional on force."""
|
||||
src = self._get_js().read_text()
|
||||
# The guard: if (!force && _approvalVisibleSince)
|
||||
assert '!force' in src, 'hideApprovalCard must check !force before deferred hide'
|
||||
|
||||
def test_approval_hide_timer_variable_present(self):
|
||||
"""Module-level _approvalHideTimer variable is declared."""
|
||||
src = self._get_js().read_text()
|
||||
assert '_approvalHideTimer' in src
|
||||
|
||||
def test_approval_visible_since_variable_present(self):
|
||||
"""Module-level _approvalVisibleSince variable is declared."""
|
||||
src = self._get_js().read_text()
|
||||
assert '_approvalVisibleSince' in src
|
||||
|
||||
def test_approval_signature_variable_present(self):
|
||||
"""Module-level _approvalSignature variable is declared."""
|
||||
src = self._get_js().read_text()
|
||||
assert '_approvalSignature' in src
|
||||
|
||||
def test_respond_approval_calls_hide_with_force(self):
|
||||
"""respondApproval must call hideApprovalCard(true) — not no-arg."""
|
||||
src = self._get_js().read_text()
|
||||
# Extract respondApproval function body
|
||||
import re
|
||||
m = re.search(r'async function respondApproval.*?(?=\nasync function|\nfunction |\Z)',
|
||||
src, re.DOTALL)
|
||||
assert m, 'respondApproval function not found'
|
||||
body = m.group(0)
|
||||
# Must call hideApprovalCard(true), not the bare hideApprovalCard()
|
||||
assert 'hideApprovalCard(true)' in body, \
|
||||
'respondApproval must call hideApprovalCard(true) so card hides immediately after user clicks'
|
||||
# Must NOT have bare hideApprovalCard() without force
|
||||
bare_calls = re.findall(r'hideApprovalCard\((?!true)', body)
|
||||
assert not bare_calls, \
|
||||
f'respondApproval has bare hideApprovalCard() calls (no force=true): {bare_calls}'
|
||||
|
||||
def test_stream_done_calls_hide_with_force(self):
|
||||
"""Done SSE event handler must call hideApprovalCard(true)."""
|
||||
src = self._get_js().read_text()
|
||||
# Find the done event handler section (stopApprovalPolling followed by hideApprovalCard)
|
||||
import re
|
||||
# Look for pattern: stopApprovalPolling();\n + hideApprovalCard
|
||||
matches = re.findall(
|
||||
r'stopApprovalPolling\(\);\s*\n\s*if\(!_approvalSessionId[^)]*\)\s*hideApprovalCard\((\w*)\)',
|
||||
src
|
||||
)
|
||||
# All stopApprovalPolling paths that call hideApprovalCard should use force=true
|
||||
for match in matches:
|
||||
assert match == 'true', \
|
||||
f'After stopApprovalPolling(), hideApprovalCard called without force=true (got: {match!r})'
|
||||
|
||||
def test_poll_loop_still_uses_no_force(self):
|
||||
"""Poll loop hideApprovalCard() (when pending gone) keeps no-force — correct behavior."""
|
||||
src = self._get_js().read_text()
|
||||
# Line 446: else { hideApprovalCard(); } — this is the poll-loop path
|
||||
# The 30s guard should protect this call (don't force from poll ticks)
|
||||
assert 'else { hideApprovalCard(); }' in src or \
|
||||
'else {hideApprovalCard();}' in src or \
|
||||
'else { hideApprovalCard() }' in src, \
|
||||
'Poll loop should still call hideApprovalCard() without force=true'
|
||||
|
||||
def test_show_approval_card_signature_dedup(self):
|
||||
"""showApprovalCard uses a signature to avoid resetting timer on repeat polls."""
|
||||
src = self._get_js().read_text()
|
||||
# The sig computation must use JSON.stringify on card content
|
||||
import re
|
||||
m = re.search(r'function showApprovalCard.*?(?=\nfunction |\nasync function |\Z)',
|
||||
src, re.DOTALL)
|
||||
assert m, 'showApprovalCard function not found'
|
||||
body = m.group(0)
|
||||
assert 'JSON.stringify' in body, 'showApprovalCard must compute a signature via JSON.stringify'
|
||||
assert '_approvalSignature' in body, 'showApprovalCard must check/set _approvalSignature'
|
||||
|
||||
def test_clear_approval_hide_timer_helper_present(self):
|
||||
"""_clearApprovalHideTimer helper exists to cancel deferred hides."""
|
||||
src = self._get_js().read_text()
|
||||
assert '_clearApprovalHideTimer' in src, \
|
||||
'_clearApprovalHideTimer helper must exist to cancel deferred setTimeout'
|
||||
|
||||
143
tests/test_sprint31.py
Normal file
143
tests/test_sprint31.py
Normal file
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Tests for issue #170: new profile form with optional custom endpoint fields.
|
||||
|
||||
Tests cover:
|
||||
1. _write_endpoint_to_config writes base_url into config.yaml
|
||||
2. _write_endpoint_to_config writes api_key into config.yaml
|
||||
3. _write_endpoint_to_config writes both together
|
||||
4. _write_endpoint_to_config merges with existing config (does not clobber)
|
||||
5. _write_endpoint_to_config is a no-op when both args are None/empty
|
||||
6. API route accepts base_url and api_key in POST body
|
||||
7. Profile created via API has base_url in config.yaml
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import os
|
||||
import pytest
|
||||
|
||||
yaml = pytest.importorskip("yaml", reason="PyYAML required for config write tests")
|
||||
|
||||
|
||||
# ── 1-5: _write_endpoint_to_config unit tests ─────────────────────────────────
|
||||
|
||||
class TestWriteEndpointToConfig:
|
||||
def test_writes_base_url(self, tmp_path):
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, base_url="http://localhost:11434")
|
||||
cfg = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
assert cfg["model"]["base_url"] == "http://localhost:11434"
|
||||
|
||||
def test_writes_api_key(self, tmp_path):
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, api_key="sk-local-test")
|
||||
cfg = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
assert cfg["model"]["api_key"] == "sk-local-test"
|
||||
|
||||
def test_writes_both(self, tmp_path):
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, base_url="http://localhost:8080", api_key="mykey")
|
||||
cfg = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
assert cfg["model"]["base_url"] == "http://localhost:8080"
|
||||
assert cfg["model"]["api_key"] == "mykey"
|
||||
|
||||
def test_merges_with_existing_config(self, tmp_path):
|
||||
"""Does not clobber other top-level config keys."""
|
||||
existing = {"model": {"default": "gpt-4o", "provider": "openai"}, "agent": {"max_turns": 90}}
|
||||
(tmp_path / "config.yaml").write_text(yaml.dump(existing))
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, base_url="http://localhost:1234")
|
||||
cfg = yaml.safe_load((tmp_path / "config.yaml").read_text())
|
||||
# Existing keys preserved
|
||||
assert cfg["model"]["default"] == "gpt-4o"
|
||||
assert cfg["model"]["provider"] == "openai"
|
||||
assert cfg["agent"]["max_turns"] == 90
|
||||
# New key added
|
||||
assert cfg["model"]["base_url"] == "http://localhost:1234"
|
||||
|
||||
def test_noop_when_both_none(self, tmp_path):
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, base_url=None, api_key=None)
|
||||
assert not (tmp_path / "config.yaml").exists()
|
||||
|
||||
def test_noop_when_both_empty_strings(self, tmp_path):
|
||||
from api.profiles import _write_endpoint_to_config
|
||||
_write_endpoint_to_config(tmp_path, base_url="", api_key="")
|
||||
assert not (tmp_path / "config.yaml").exists()
|
||||
|
||||
|
||||
# ── 6-7: API integration tests ────────────────────────────────────────────────
|
||||
|
||||
_TEST_BASE = "http://127.0.0.1:8788"
|
||||
|
||||
|
||||
def _post(path, body=None):
|
||||
import urllib.request
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(
|
||||
_TEST_BASE + path, data=data, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), None
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return json.loads(e.read()), e.code
|
||||
except Exception:
|
||||
return {}, e.code
|
||||
|
||||
|
||||
class TestProfileCreateAPIWithEndpoint:
|
||||
_PROFILE_NAME = "test-ep-sprint31"
|
||||
|
||||
def _cleanup(self):
|
||||
"""Remove the test profile from wherever hermes_cli placed it."""
|
||||
home_hermes = pathlib.Path.home() / ".hermes"
|
||||
# Walk all profile roots: real ~/.hermes, and any subdirs that might be HERMES_HOME
|
||||
roots_to_check = set()
|
||||
roots_to_check.add(home_hermes)
|
||||
for root, dirs, _ in os.walk(str(home_hermes)):
|
||||
if "profiles" in dirs:
|
||||
roots_to_check.add(pathlib.Path(root))
|
||||
if root.count(os.sep) - str(home_hermes).count(os.sep) > 4:
|
||||
break # don't recurse too deep
|
||||
for search_root in roots_to_check:
|
||||
candidate = search_root / "profiles" / self._PROFILE_NAME
|
||||
if candidate.exists():
|
||||
shutil.rmtree(candidate)
|
||||
|
||||
def setup_method(self, _):
|
||||
self._cleanup()
|
||||
|
||||
def teardown_method(self, _):
|
||||
self._cleanup()
|
||||
|
||||
def test_api_route_accepts_base_url(self, test_server):
|
||||
"""POST /api/profile/create with base_url returns ok:True."""
|
||||
data, err = _post("/api/profile/create", {
|
||||
"name": self._PROFILE_NAME,
|
||||
"base_url": "http://localhost:11434",
|
||||
})
|
||||
assert err is None, f"Expected 200, got {err}: {data}"
|
||||
assert data.get("ok") is True
|
||||
|
||||
def test_api_route_writes_base_url_to_config(self, test_server):
|
||||
"""Route accepts base_url and returns profile metadata.
|
||||
|
||||
The actual config.yaml write is covered by the unit tests above.
|
||||
"""
|
||||
data, err = _post("/api/profile/create", {
|
||||
"name": self._PROFILE_NAME,
|
||||
"base_url": "http://localhost:9999",
|
||||
})
|
||||
assert err is None, f"Expected 200, got {err}: {data}"
|
||||
assert data.get("ok") is True
|
||||
assert data.get("profile", {}).get("path"), f"API response missing profile.path: {data}"
|
||||
|
||||
def test_api_route_rejects_invalid_base_url(self, test_server):
|
||||
"""POST /api/profile/create with a non-http base_url returns 400."""
|
||||
data, err = _post("/api/profile/create", {
|
||||
"name": self._PROFILE_NAME,
|
||||
"base_url": "ftp://localhost:11434",
|
||||
})
|
||||
assert err == 400, f"Expected 400, got {err}: {data}"
|
||||
59
tests/test_sprint33.py
Normal file
59
tests/test_sprint33.py
Normal file
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
Sprint 33 Tests: Shared app dialogs replace native confirm/prompt usage.
|
||||
|
||||
These tests verify the static assets expose the reusable confirm/input modal
|
||||
and that browser-native confirm/prompt calls are no longer used in the Web UI.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
|
||||
|
||||
def read(path):
|
||||
return (REPO / path).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_index_has_shared_app_dialog_markup():
|
||||
html = read("static/index.html")
|
||||
assert 'id="appDialogOverlay"' in html
|
||||
assert 'id="appDialog"' in html
|
||||
assert 'id="appDialogTitle"' in html
|
||||
assert 'id="appDialogDesc"' in html
|
||||
assert 'id="appDialogInput"' in html
|
||||
assert 'id="appDialogCancel"' in html
|
||||
assert 'id="appDialogConfirm"' in html
|
||||
|
||||
|
||||
def test_app_dialog_css_rules_exist():
|
||||
css = read("static/style.css")
|
||||
for selector in (
|
||||
".app-dialog-overlay",
|
||||
".app-dialog",
|
||||
".app-dialog-input",
|
||||
".app-dialog-actions",
|
||||
".app-dialog-btn.confirm",
|
||||
".app-dialog-btn.confirm.danger",
|
||||
):
|
||||
assert selector in css, f"missing CSS selector: {selector}"
|
||||
|
||||
|
||||
def test_ui_js_exposes_shared_dialog_helpers():
|
||||
src = read("static/ui.js")
|
||||
assert "function showConfirmDialog(opts={})" in src
|
||||
assert "function showPromptDialog(opts={})" in src
|
||||
assert "document.addEventListener('keydown'" in src
|
||||
|
||||
|
||||
def test_no_native_confirm_calls_remain_in_static_js():
|
||||
for path in (REPO / "static").glob("*.js"):
|
||||
src = path.read_text(encoding="utf-8")
|
||||
assert not re.search(r"\bconfirm\s*\(", src), f"native confirm() remains in {path.name}"
|
||||
|
||||
|
||||
def test_no_native_prompt_calls_remain_in_static_js():
|
||||
for path in (REPO / "static").glob("*.js"):
|
||||
src = path.read_text(encoding="utf-8")
|
||||
assert not re.search(r"\bprompt\s*\(", src), f"native prompt() remains in {path.name}"
|
||||
228
tests/test_sprint34.py
Normal file
228
tests/test_sprint34.py
Normal file
@@ -0,0 +1,228 @@
|
||||
"""
|
||||
Sprint 34 Tests: OAuth provider support in onboarding (issues #303, #304).
|
||||
|
||||
Covers:
|
||||
1. _provider_oauth_authenticated() returns True for known OAuth providers
|
||||
with valid tokens in auth.json
|
||||
2. _provider_oauth_authenticated() returns False when auth.json is absent,
|
||||
empty, or has no token data
|
||||
3. _provider_oauth_authenticated() returns False for unknown/API-key providers
|
||||
4. _status_from_runtime() marks copilot/openai-codex as provider_ready when
|
||||
credentials exist
|
||||
5. _status_from_runtime() gives a helpful "hermes auth" note (not "API key")
|
||||
for OAuth providers that have no credentials yet
|
||||
6. API route /api/onboarding/status reflects OAuth-ready state
|
||||
"""
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import tempfile
|
||||
import unittest.mock
|
||||
|
||||
import pytest
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def _make_auth_json(provider_id: str, tokens: dict, tmp_dir: pathlib.Path) -> pathlib.Path:
|
||||
"""Write an auth.json with the given tokens for provider_id into tmp_dir."""
|
||||
store = {"providers": {provider_id: tokens}}
|
||||
auth_path = tmp_dir / "auth.json"
|
||||
auth_path.write_text(json.dumps(store), encoding="utf-8")
|
||||
return auth_path
|
||||
|
||||
|
||||
# ── 1–3. _provider_oauth_authenticated unit tests ────────────────────────────
|
||||
|
||||
class TestProviderOAuthAuthenticated:
|
||||
"""Unit tests for the new _provider_oauth_authenticated() helper."""
|
||||
|
||||
def _call(self, provider: str, hermes_home: pathlib.Path) -> bool:
|
||||
# Import fresh so we don't get a stale module reference
|
||||
from api.onboarding import _provider_oauth_authenticated
|
||||
return _provider_oauth_authenticated(provider, hermes_home)
|
||||
|
||||
def test_returns_false_when_auth_json_absent(self, tmp_path):
|
||||
"""No auth.json -> not authenticated."""
|
||||
assert self._call("openai-codex", tmp_path) is False
|
||||
|
||||
def test_openai_codex_with_access_token(self, tmp_path):
|
||||
"""openai-codex with a valid access_token -> authenticated."""
|
||||
_make_auth_json(
|
||||
"openai-codex",
|
||||
{"access_token": "ey.test.token", "refresh_token": "ref123"},
|
||||
tmp_path,
|
||||
)
|
||||
assert self._call("openai-codex", tmp_path) is True
|
||||
|
||||
def test_openai_codex_with_refresh_token_only(self, tmp_path):
|
||||
"""openai-codex with only a refresh_token -> still authenticated."""
|
||||
_make_auth_json(
|
||||
"openai-codex",
|
||||
{"access_token": "", "refresh_token": "ref_only_token"},
|
||||
tmp_path,
|
||||
)
|
||||
assert self._call("openai-codex", tmp_path) is True
|
||||
|
||||
def test_copilot_with_api_key(self, tmp_path):
|
||||
"""copilot with an api_key (GitHub token) -> authenticated."""
|
||||
_make_auth_json("copilot", {"api_key": "ghu_test_token_123"}, tmp_path)
|
||||
assert self._call("copilot", tmp_path) is True
|
||||
|
||||
def test_empty_tokens_returns_false(self, tmp_path):
|
||||
"""All token fields empty -> not authenticated."""
|
||||
_make_auth_json(
|
||||
"openai-codex",
|
||||
{"access_token": "", "refresh_token": "", "api_key": ""},
|
||||
tmp_path,
|
||||
)
|
||||
assert self._call("openai-codex", tmp_path) is False
|
||||
|
||||
def test_missing_provider_key_in_auth_json(self, tmp_path):
|
||||
"""auth.json present but provider key absent -> not authenticated."""
|
||||
store = {"providers": {"some-other-provider": {"access_token": "tok"}}}
|
||||
(tmp_path / "auth.json").write_text(json.dumps(store), encoding="utf-8")
|
||||
assert self._call("openai-codex", tmp_path) is False
|
||||
|
||||
def test_unknown_provider_not_in_oauth_list(self, tmp_path):
|
||||
"""A provider that is not a known OAuth provider -> always False."""
|
||||
_make_auth_json("some-random-provider", {"access_token": "tok"}, tmp_path)
|
||||
assert self._call("some-random-provider", tmp_path) is False
|
||||
|
||||
def test_nous_provider_recognized(self, tmp_path):
|
||||
"""nous is in the known OAuth set."""
|
||||
_make_auth_json("nous", {"access_token": "nous_tok"}, tmp_path)
|
||||
assert self._call("nous", tmp_path) is True
|
||||
|
||||
def test_qwen_oauth_provider_recognized(self, tmp_path):
|
||||
"""qwen-oauth is in the known OAuth set."""
|
||||
_make_auth_json("qwen-oauth", {"access_token": "qwen_tok"}, tmp_path)
|
||||
assert self._call("qwen-oauth", tmp_path) is True
|
||||
|
||||
def test_empty_provider_string_returns_false(self, tmp_path):
|
||||
"""Empty provider string -> False, no crash."""
|
||||
assert self._call("", tmp_path) is False
|
||||
assert self._call(" ", tmp_path) is False
|
||||
|
||||
|
||||
# ── 4–5. _status_from_runtime integration ────────────────────────────────────
|
||||
|
||||
class TestStatusFromRuntimeOAuth:
|
||||
"""_status_from_runtime should treat OAuth providers with tokens as ready."""
|
||||
|
||||
def _call(self, provider: str, model: str, hermes_home: pathlib.Path) -> dict:
|
||||
from api.onboarding import _status_from_runtime
|
||||
import api.onboarding as _ob
|
||||
orig_home = _ob._get_active_hermes_home
|
||||
orig_found = _ob._HERMES_FOUND
|
||||
_ob._get_active_hermes_home = lambda: hermes_home
|
||||
# Simulate hermes-agent being available so we reach the provider logic
|
||||
# (without this, _status_from_runtime short-circuits to agent_unavailable)
|
||||
_ob._HERMES_FOUND = True
|
||||
try:
|
||||
cfg = {"model": {"provider": provider, "default": model}}
|
||||
return _status_from_runtime(cfg, True)
|
||||
finally:
|
||||
_ob._get_active_hermes_home = orig_home
|
||||
_ob._HERMES_FOUND = orig_found
|
||||
|
||||
def test_copilot_ready_when_api_key_in_auth_json(self, tmp_path):
|
||||
"""copilot configured + api_key in auth.json -> provider_ready True."""
|
||||
_make_auth_json("copilot", {"api_key": "ghu_abc123"}, tmp_path)
|
||||
result = self._call("copilot", "gpt-5.4", tmp_path)
|
||||
assert result["provider_configured"] is True
|
||||
assert result["provider_ready"] is True
|
||||
assert result["setup_state"] == "ready"
|
||||
|
||||
def test_openai_codex_ready_when_token_in_auth_json(self, tmp_path):
|
||||
"""openai-codex configured + access_token -> provider_ready True."""
|
||||
_make_auth_json(
|
||||
"openai-codex",
|
||||
{"access_token": "ey.test", "refresh_token": "ref"},
|
||||
tmp_path,
|
||||
)
|
||||
result = self._call("openai-codex", "codex-mini-latest", tmp_path)
|
||||
assert result["provider_configured"] is True
|
||||
assert result["provider_ready"] is True
|
||||
assert result["setup_state"] == "ready"
|
||||
|
||||
def test_copilot_not_ready_without_credentials(self, tmp_path):
|
||||
"""copilot configured but no credentials -> provider_ready False.
|
||||
|
||||
We mock hermes_cli.auth to be unavailable so the function falls through
|
||||
to the auth.json path. With no auth.json the result must be False.
|
||||
"""
|
||||
import unittest.mock
|
||||
|
||||
# Prevent the hermes_cli fast path from finding real credentials
|
||||
with unittest.mock.patch(
|
||||
"api.onboarding._provider_oauth_authenticated",
|
||||
return_value=False,
|
||||
):
|
||||
result = self._call("copilot", "gpt-5.4", tmp_path)
|
||||
|
||||
assert result["provider_configured"] is True
|
||||
assert result["provider_ready"] is False
|
||||
assert result["setup_state"] == "provider_incomplete"
|
||||
|
||||
def test_oauth_incomplete_note_mentions_hermes_auth(self, tmp_path):
|
||||
"""When OAuth provider is incomplete, note should mention hermes auth/model."""
|
||||
result = self._call("openai-codex", "codex-mini-latest", tmp_path)
|
||||
note = result["provider_note"]
|
||||
assert "hermes auth" in note or "hermes model" in note, (
|
||||
f"Expected 'hermes auth' or 'hermes model' in note, got: {note!r}"
|
||||
)
|
||||
|
||||
def test_oauth_incomplete_note_does_not_say_api_key(self, tmp_path):
|
||||
"""OAuth provider incomplete note must not say 'API key' — that's misleading."""
|
||||
result = self._call("copilot", "gpt-5.4", tmp_path)
|
||||
note = result["provider_note"]
|
||||
assert "API key" not in note, (
|
||||
f"Note misleadingly mentions 'API key' for OAuth provider: {note!r}"
|
||||
)
|
||||
|
||||
def test_standard_provider_incomplete_note_still_says_api_key(self, tmp_path):
|
||||
"""For a standard API-key provider (openrouter), note should still say API key."""
|
||||
# openrouter with no .env
|
||||
result = self._call("openrouter", "anthropic/claude-sonnet-4.6", tmp_path)
|
||||
assert result["provider_ready"] is False
|
||||
note = result["provider_note"]
|
||||
assert "API key" in note, (
|
||||
f"Expected 'API key' in note for openrouter, got: {note!r}"
|
||||
)
|
||||
|
||||
|
||||
# ── 6. API endpoint reflects OAuth-ready state ───────────────────────────────
|
||||
|
||||
class TestOnboardingStatusApiOAuth:
|
||||
"""
|
||||
The /api/onboarding/status endpoint should report provider_ready=True
|
||||
when an OAuth provider is configured and has valid credentials.
|
||||
"""
|
||||
|
||||
def test_status_endpoint_returns_200(self):
|
||||
import urllib.request
|
||||
with urllib.request.urlopen(BASE + "/api/onboarding/status", timeout=10) as r:
|
||||
assert r.status == 200
|
||||
data = json.loads(r.read())
|
||||
assert "system" in data
|
||||
assert "provider_ready" in data["system"]
|
||||
|
||||
def test_onboarding_status_has_chat_ready_field(self):
|
||||
import urllib.request
|
||||
with urllib.request.urlopen(BASE + "/api/onboarding/status", timeout=10) as r:
|
||||
data = json.loads(r.read())
|
||||
assert "chat_ready" in data["system"]
|
||||
|
||||
def test_status_setup_state_valid_values(self):
|
||||
"""setup_state must be one of the known string values."""
|
||||
import urllib.request
|
||||
with urllib.request.urlopen(BASE + "/api/onboarding/status", timeout=10) as r:
|
||||
data = json.loads(r.read())
|
||||
valid = {"ready", "provider_incomplete", "needs_provider", "agent_unavailable"}
|
||||
assert data["system"]["setup_state"] in valid, (
|
||||
f"Unexpected setup_state: {data['system']['setup_state']!r}"
|
||||
)
|
||||
317
tests/test_update_checker.py
Normal file
317
tests/test_update_checker.py
Normal file
@@ -0,0 +1,317 @@
|
||||
"""
|
||||
Tests for api/updates.py -- specifically the diagnostic code paths added
|
||||
in fix/223-update-pull-failed-diagnostics (PR #227).
|
||||
|
||||
Tests cover the four new branches in _apply_update_inner():
|
||||
1. fetch fails → network error message
|
||||
2. pull fails + diverged history → recovery command with git reset --hard
|
||||
3. pull fails + no upstream tracking → recovery command with set-upstream-to
|
||||
4. pull fails + generic fallback → raw git output truncated at 300 chars
|
||||
"""
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, call
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _make_run_git_side_effect(*sequence):
|
||||
"""Return a side_effect function that yields successive (stdout, ok) tuples."""
|
||||
it = iter(sequence)
|
||||
def _side_effect(args, cwd, timeout=10):
|
||||
return next(it)
|
||||
return _side_effect
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Path used for patching
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_MODULE = 'api.updates'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests for _apply_update_inner() diagnostic paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestApplyUpdateDiagnostics:
|
||||
"""New code paths introduced in PR #227."""
|
||||
|
||||
def _apply(self, target, run_git_side_effect):
|
||||
"""Call _apply_update_inner with _apply_lock bypassed and _run_git mocked."""
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}._run_git', side_effect=run_git_side_effect), \
|
||||
patch.object(updates, '_apply_lock') as mock_lock:
|
||||
mock_lock.acquire.return_value = True
|
||||
mock_lock.release.return_value = None
|
||||
return updates._apply_update_inner(target)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Path 1: fetch step fails → network error message
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_fetch_failure_returns_network_error_message(self, tmp_path):
|
||||
"""When git fetch fails, return a human-readable connection error."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
# Call sequence: upstream query, fetch
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True), # rev-parse @{upstream}
|
||||
('', False), # fetch fails
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
msg = result['message'].lower()
|
||||
assert 'could not reach' in msg or 'internet connection' in msg or 'remote repository' in msg
|
||||
|
||||
def test_fetch_failure_does_not_attempt_pull(self, tmp_path):
|
||||
"""When fetch fails, pull is never called."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True), # upstream query
|
||||
('', False), # fetch fails
|
||||
]
|
||||
updates._apply_update_inner('webui')
|
||||
# Only 2 calls: upstream query + fetch. No pull call.
|
||||
assert mock_run_git.call_count == 2
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Path 2: pull fails + diverged history
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_diverged_history_returns_reset_hard_command(self, tmp_path):
|
||||
"""Diverged history produces a message with 'reset --hard'."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True), # upstream query
|
||||
('', True), # fetch succeeds
|
||||
('', True), # status --porcelain (clean)
|
||||
('Not possible to fast-forward, aborting.', False), # pull fails
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert result.get('diverged') is True
|
||||
msg = result['message']
|
||||
assert 'reset --hard' in msg
|
||||
|
||||
def test_diverged_history_message_contains_compare_ref(self, tmp_path):
|
||||
"""Diverged history message includes the upstream ref."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/feat/my-feature', True), # upstream query
|
||||
('', True), # fetch
|
||||
('', True), # status (clean)
|
||||
('Your branch and origin have diverged.', False), # pull
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'origin/feat/my-feature' in result['message']
|
||||
|
||||
def test_diverged_matching_is_case_insensitive(self, tmp_path):
|
||||
"""'DIVERGED' in uppercase is still detected."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', True),
|
||||
('', True),
|
||||
('DIVERGED from upstream', False),
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert result.get('diverged') is True
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Path 3: pull fails + no upstream tracking configured
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_no_tracking_returns_set_upstream_command(self, tmp_path):
|
||||
"""Missing upstream tracking branch produces set-upstream-to message."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True), # upstream query
|
||||
('', True), # fetch
|
||||
('', True), # status (clean)
|
||||
('There is no tracking information for the current branch.', False), # pull
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'set-upstream-to' in result['message']
|
||||
assert result.get('diverged') is None
|
||||
|
||||
def test_no_tracking_alternate_phrasing(self, tmp_path):
|
||||
"""'does not track' alternate git message is also detected."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', True),
|
||||
('', True),
|
||||
('fatal: The current branch local does not track a remote branch.', False),
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'set-upstream-to' in result['message']
|
||||
|
||||
def test_no_tracking_message_contains_compare_ref(self, tmp_path):
|
||||
"""set-upstream-to message includes the upstream ref to configure."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/main', True),
|
||||
('', True),
|
||||
('', True),
|
||||
('no tracking information', False),
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'origin/main' in result['message']
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Path 4: pull fails + generic fallback (truncated raw output)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_generic_failure_includes_truncated_git_output(self, tmp_path):
|
||||
"""Generic pull failure includes up to 300 chars of git output."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
long_error = 'X' * 500 # 500-char error from git
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', True),
|
||||
('', True),
|
||||
(long_error, False),
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
msg = result['message']
|
||||
# The raw output in the message must be truncated at 300 chars
|
||||
assert 'X' * 300 in msg
|
||||
assert 'X' * 301 not in msg
|
||||
|
||||
def test_generic_failure_empty_output_shows_sentinel(self, tmp_path):
|
||||
"""When git produces no output, message contains a fallback sentinel."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', True),
|
||||
('', True),
|
||||
('', False), # pull fails with empty output
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'no output' in result['message'].lower() or result['message']
|
||||
|
||||
def test_generic_failure_does_not_set_diverged(self, tmp_path):
|
||||
"""A generic pull failure must not set diverged=True."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', True),
|
||||
('', True),
|
||||
('Some unrecognized git error', False),
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert not result.get('diverged')
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Regression: existing success path still works after fetch addition
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_successful_update_still_returns_ok(self, tmp_path):
|
||||
"""Fetch + status + pull success path returns ok=True (regression guard)."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
# Patch the cache's 'checked_at' key directly to avoid the lock
|
||||
# invalidation block raising. We use a fresh dict swap.
|
||||
fake_cache = {'webui': None, 'agent': None, 'checked_at': 1}
|
||||
with patch(f'{_MODULE}.REPO_ROOT', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git, \
|
||||
patch(f'{_MODULE}._update_cache', fake_cache), \
|
||||
patch(f'{_MODULE}._cache_lock'):
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True), # upstream query
|
||||
('', True), # fetch succeeds
|
||||
('', True), # status (clean working tree)
|
||||
('Already up to date.', True), # pull succeeds
|
||||
]
|
||||
result = updates._apply_update_inner('webui')
|
||||
|
||||
assert result['ok'] is True
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Agent target works the same as webui target
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_fetch_failure_for_agent_target(self, tmp_path):
|
||||
"""Fetch failure path also works when target='agent'."""
|
||||
(tmp_path / '.git').mkdir()
|
||||
|
||||
from api import updates
|
||||
with patch(f'{_MODULE}._AGENT_DIR', tmp_path), \
|
||||
patch(f'{_MODULE}._run_git') as mock_run_git:
|
||||
mock_run_git.side_effect = [
|
||||
('origin/master', True),
|
||||
('', False), # fetch fails
|
||||
]
|
||||
result = updates._apply_update_inner('agent')
|
||||
|
||||
assert result['ok'] is False
|
||||
assert 'could not reach' in result['message'].lower() or \
|
||||
'internet' in result['message'].lower() or \
|
||||
'remote' in result['message'].lower()
|
||||
53
tests/test_updates.py
Normal file
53
tests/test_updates.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Tests for self-update diagnostics (api/updates.py)."""
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import api.updates as updates
|
||||
|
||||
|
||||
def test_run_git_returns_stderr_on_failure(tmp_path):
|
||||
"""When a git command fails, _run_git should return stderr (not empty string)."""
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=1,
|
||||
stdout='',
|
||||
stderr="fatal: 'origin/master' does not appear to be a git repository\n",
|
||||
)
|
||||
out, ok = updates._run_git(['pull', '--ff-only', 'origin/master'], tmp_path)
|
||||
|
||||
assert ok is False
|
||||
assert "does not appear to be a git repository" in out
|
||||
|
||||
|
||||
def test_run_git_returns_stdout_when_no_stderr(tmp_path):
|
||||
"""If stderr is empty on failure, fall back to stdout."""
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=128,
|
||||
stdout='Already up to date.',
|
||||
stderr='',
|
||||
)
|
||||
out, ok = updates._run_git(['pull'], tmp_path)
|
||||
|
||||
assert ok is False
|
||||
assert 'Already up to date' in out
|
||||
|
||||
|
||||
def test_run_git_returns_exit_code_when_no_output(tmp_path):
|
||||
"""If both stdout and stderr are empty, report the exit code."""
|
||||
with patch('subprocess.run') as mock_run:
|
||||
mock_run.return_value = MagicMock(
|
||||
returncode=1,
|
||||
stdout='',
|
||||
stderr='',
|
||||
)
|
||||
out, ok = updates._run_git(['status'], tmp_path)
|
||||
|
||||
assert ok is False
|
||||
assert 'status 1' in out
|
||||
|
||||
|
||||
def test_split_remote_ref_splits_tracking_ref():
|
||||
"""_split_remote_ref should correctly split origin/branch."""
|
||||
assert updates._split_remote_ref('origin/master') == ('origin', 'master')
|
||||
assert updates._split_remote_ref('origin/feature/foo') == ('origin', 'feature/foo')
|
||||
assert updates._split_remote_ref('master') == (None, 'master')
|
||||
Reference in New Issue
Block a user