Compare commits
354 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
25d38a467a | ||
|
|
6c5911a79f | ||
|
|
54e83fb8b6 | ||
|
|
8a1bc134fa | ||
|
|
b5fc32b18d | ||
|
|
db1240dde5 | ||
|
|
2efc1fb8e8 | ||
|
|
a9a22ee751 | ||
|
|
a512f2020e | ||
|
|
45426bdcd1 | ||
|
|
360379136b | ||
|
|
e4fec9e4e0 | ||
|
|
8cf10b152b | ||
|
|
07c25f0766 | ||
|
|
4f79b3f941 | ||
|
|
54d0ee5f6c | ||
|
|
3e1ba1b783 | ||
|
|
0a9b952d4c | ||
|
|
8864001941 | ||
|
|
7e8ed4afff | ||
|
|
215f7eff4d | ||
|
|
a4ce9ccc99 | ||
|
|
8ff3fd9442 | ||
|
|
53ce8a107b | ||
|
|
ec44a437a2 | ||
|
|
400b1721d7 | ||
|
|
fbce1093b9 | ||
|
|
c0bffa15f1 | ||
|
|
27d3f9543e | ||
|
|
51767f9d90 | ||
|
|
9d4c075e2b | ||
|
|
f5c4e110a4 | ||
|
|
4c142da3f6 | ||
|
|
3b53b3f4f6 | ||
|
|
69effc7b22 | ||
|
|
7bfba201da | ||
|
|
dc2334c5a3 | ||
|
|
bd55379886 | ||
|
|
392c315d4b | ||
|
|
25fae902d3 | ||
|
|
d6b58b9ce0 | ||
|
|
ac839e0d01 | ||
|
|
ce4e01ea92 | ||
|
|
4f7db62c58 | ||
|
|
3033fb65e3 | ||
|
|
03df7132d0 | ||
|
|
50d7d1cf88 | ||
|
|
e4688425ab | ||
|
|
9220a876bc | ||
|
|
e077d110c3 | ||
|
|
8f7bee7b34 | ||
|
|
dc43a30af7 | ||
|
|
74dee6b665 | ||
|
|
96c4102aa7 | ||
|
|
d3251fdbfd | ||
|
|
31196d42af | ||
|
|
1050c673e6 | ||
|
|
178251a5c0 | ||
|
|
21a7564afd | ||
|
|
44a544362f | ||
|
|
36830e3cd1 | ||
|
|
7ea7331f26 | ||
|
|
eb760a2158 | ||
|
|
0b96f08b3e | ||
|
|
4f1623520d | ||
|
|
505bfc6a9a | ||
|
|
1bd0341243 | ||
|
|
ccba2f5c01 | ||
|
|
45d3dc0f68 | ||
|
|
69cd0832de | ||
|
|
7b9f08c774 | ||
|
|
2810233af4 | ||
|
|
642f4536f0 | ||
|
|
f0d49b5b59 | ||
|
|
e6447ebad2 | ||
|
|
887893ecd1 | ||
|
|
75de03c99f | ||
|
|
d8ab326b73 | ||
|
|
7753e954e5 | ||
|
|
2343dc1d85 | ||
|
|
85f1017514 | ||
|
|
eb7ec5bac3 | ||
|
|
b673006b7f | ||
|
|
5a79dd0dc9 | ||
|
|
0a570ada87 | ||
|
|
53acc8e0e1 | ||
|
|
34b98285a1 | ||
|
|
e228b1414f | ||
|
|
bb445ffe9a | ||
|
|
2eb0679104 | ||
|
|
12949a2771 | ||
|
|
7b0fb246ee | ||
|
|
f86581e3e5 | ||
|
|
3c5ca2db62 | ||
|
|
c7381ee3f1 | ||
|
|
32669f4a5b | ||
|
|
c9a0e02301 | ||
|
|
bfb9bbb0bf | ||
|
|
5507dae3d7 | ||
|
|
0349df6ee4 | ||
|
|
8c36203dd4 | ||
|
|
c4d1e8c5d0 | ||
|
|
c0c0195f7f | ||
|
|
8199fa333e | ||
|
|
77769750c2 | ||
|
|
b3ad60d2c9 | ||
|
|
85d8aad0ae | ||
|
|
f1590fdb07 | ||
|
|
3776b09f4a | ||
|
|
2400e14a31 | ||
|
|
69b0a905a4 | ||
|
|
c3251ea97d | ||
|
|
924c833878 | ||
|
|
5fd7dc0c17 | ||
|
|
a4136f2da5 | ||
|
|
3c3cae89f8 | ||
|
|
8b857d9efc | ||
|
|
8d1c257ea8 | ||
|
|
6e303fbd93 | ||
|
|
61ecdaded3 | ||
|
|
09e278461c | ||
|
|
6347949463 | ||
|
|
204dc23c6b | ||
|
|
c4efe96725 | ||
|
|
6a513f49b2 | ||
|
|
db392bd532 | ||
|
|
b394efce17 | ||
|
|
28d226f5ce | ||
|
|
d8aa387c3c | ||
|
|
4ad7efe8cf | ||
|
|
57a50591ee | ||
|
|
16c58e60f4 | ||
|
|
37850a4dfd | ||
|
|
415270ff03 | ||
|
|
2a7a5ddfaf | ||
|
|
a5abe51cc5 | ||
|
|
3cc5839bf3 | ||
|
|
539501ed2b | ||
|
|
c91eaaf05f | ||
|
|
d3fea34c41 | ||
|
|
a2258139f2 | ||
|
|
1345ccccee | ||
|
|
4de4ed9a15 | ||
|
|
04ed0ff43d | ||
|
|
2beebaa6a2 | ||
|
|
0f8fec7ccd | ||
|
|
12a60faaee | ||
|
|
2acee7fc34 | ||
|
|
acc14f2f0b | ||
|
|
9948fcf1db | ||
|
|
6a1dda4082 | ||
|
|
56944cc0ab | ||
|
|
7f69155904 | ||
|
|
54181d1a07 | ||
|
|
9542639a90 | ||
|
|
bcdd7ed3f3 | ||
|
|
7a80e73eb2 | ||
|
|
78de40e015 | ||
|
|
00eb13b316 | ||
|
|
a71047bbc3 | ||
|
|
68426124c5 | ||
|
|
4c8042ea00 | ||
|
|
a6484f69a8 | ||
|
|
f13f753de8 | ||
|
|
f948baceb6 | ||
|
|
5bdeb93559 | ||
|
|
d0e08fee88 | ||
|
|
dd17a0e9b7 | ||
|
|
04401787ec | ||
|
|
09bbbfc657 | ||
|
|
88dc8bbe26 | ||
|
|
1fee123ac8 | ||
|
|
a683553699 | ||
|
|
63fb22b7ee | ||
|
|
05f09012a5 | ||
|
|
3c771c4d2c | ||
|
|
2398ec51fe | ||
|
|
4eaf4e0743 | ||
|
|
1c0d13c6d9 | ||
|
|
4c78d8a56b | ||
|
|
229680ae1e | ||
|
|
e0e642a239 | ||
|
|
e684fdd731 | ||
|
|
2a3324c201 | ||
|
|
39d42be396 | ||
|
|
2fc19a8326 | ||
|
|
7d9d7e7b66 | ||
|
|
9c44d0cf3e | ||
|
|
7552cd3e9b | ||
|
|
f316fb7502 | ||
|
|
50583f0667 | ||
|
|
26c24867e6 | ||
|
|
2562567730 | ||
|
|
2b21bb68b8 | ||
|
|
84ca4d617b | ||
|
|
9021e76708 | ||
|
|
eddf3249c1 | ||
|
|
ede1a5fc50 | ||
|
|
ed2d55f020 | ||
|
|
28354a9702 | ||
|
|
bd3ec45aa9 | ||
|
|
74a4263056 | ||
|
|
28a0f0bef9 | ||
|
|
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 | ||
|
|
0df9d4830f | ||
|
|
e0a95193d8 | ||
|
|
e3c85624d9 | ||
|
|
ed9023a431 | ||
|
|
e59fedd351 | ||
|
|
9a5435176d | ||
|
|
31281a6025 | ||
|
|
cc8cbc4d3f | ||
|
|
0e5e465ea0 | ||
|
|
a92e21553d | ||
|
|
06f46439c0 | ||
|
|
e68c1b92a4 | ||
|
|
fb19c7ea1f | ||
|
|
cb069794dd | ||
|
|
be92e59bdb | ||
|
|
f90be60e31 | ||
|
|
011034dc71 | ||
|
|
392bc5df6e | ||
|
|
fdf6ebfbe6 | ||
|
|
04678b7b6e | ||
|
|
4d68fb31d4 | ||
|
|
80b26c7c72 | ||
|
|
012ac6f149 | ||
|
|
18aca24063 | ||
|
|
a5b843d6f9 | ||
|
|
9714c1779f | ||
|
|
0126044ecb | ||
|
|
166a4c3e7b | ||
|
|
1ac1e74512 | ||
|
|
b979b4c443 | ||
|
|
c04caf3f5b | ||
|
|
799cbb7eca | ||
|
|
0d83837650 | ||
|
|
5f7564e8bb | ||
|
|
8ff5d83e14 | ||
|
|
5e899ee8fe | ||
|
|
907bb224d9 | ||
|
|
d919b584c6 | ||
|
|
4422a87de9 | ||
|
|
9e9fcb09d2 | ||
|
|
12e5de9c4e | ||
|
|
7e6fec1c85 | ||
|
|
a064542df9 | ||
|
|
ac969e4bd6 | ||
|
|
67a83368f0 | ||
|
|
a9b2a2f22f | ||
|
|
e3303c6e89 | ||
|
|
40cbd024b9 | ||
|
|
ccabdf9882 | ||
|
|
70a486ddef | ||
|
|
ab6147fba9 | ||
|
|
8aa1c9684d | ||
|
|
4d2887531d | ||
|
|
d6de7c8650 | ||
|
|
76241bc255 | ||
|
|
5b4c5b0094 | ||
|
|
027e7314f0 | ||
|
|
107c446187 | ||
|
|
01896d67f3 | ||
|
|
5a52259fd7 | ||
|
|
d71daad002 | ||
|
|
481eefaf91 | ||
|
|
534eefe09a | ||
|
|
d89639dbb3 | ||
|
|
2442fca5e5 | ||
|
|
442b0d872a | ||
|
|
3bba645364 | ||
|
|
5f014b7c4a | ||
|
|
cd598c896a | ||
|
|
58eb6e7fd5 | ||
|
|
76cdfb69e0 | ||
|
|
4622b64ca9 | ||
|
|
89891c65c8 | ||
|
|
173261c428 | ||
|
|
863dc4e938 | ||
|
|
4407c3097b | ||
|
|
71dd691ed0 | ||
|
|
9f3b2e113e | ||
|
|
e8a8fceb26 | ||
|
|
e1c2e7e3d6 | ||
|
|
c6017f461b | ||
|
|
e829fa50d5 | ||
|
|
1777cf7bfe | ||
|
|
48ba2e79e2 | ||
|
|
52e3fb70e0 | ||
|
|
c1bbdf9aeb | ||
|
|
3ca7f08b59 | ||
|
|
af76622c97 | ||
|
|
27706367b7 | ||
|
|
beb56b1a8b | ||
|
|
8d1b7a1e01 | ||
|
|
257092d107 | ||
|
|
b327103885 | ||
|
|
df9ad1fd27 | ||
|
|
2f01afd557 | ||
|
|
74fcd2e0ab | ||
|
|
4d333acbbc | ||
|
|
3d063b08a9 | ||
|
|
814e016965 | ||
|
|
0119365bd8 | ||
|
|
39066bc614 | ||
|
|
853b23cd14 | ||
|
|
cf3ccb0666 | ||
|
|
2f58724863 | ||
|
|
a3f4ad7111 | ||
|
|
0ed2981205 | ||
|
|
5762aaafba | ||
|
|
3294e54e00 | ||
|
|
2eddef3275 | ||
|
|
7bcd6623e9 | ||
|
|
82a942a2b1 | ||
|
|
805fa296c8 | ||
|
|
b8b063f325 | ||
|
|
882fc947e5 | ||
|
|
96137750a4 | ||
|
|
d10871c0e4 | ||
|
|
6d4c258d90 | ||
|
|
c312dd36ca | ||
|
|
bb595afde9 |
@@ -26,3 +26,6 @@
|
||||
|
||||
# Path to your Hermes config.yaml (for toolsets and model config)
|
||||
# HERMES_CONFIG_PATH=~/.hermes/config.yaml
|
||||
|
||||
# Display name for the assistant in the UI (default: Hermes)
|
||||
# HERMES_WEBUI_BOT_NAME=Hermes
|
||||
|
||||
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/
|
||||
|
||||
@@ -7,20 +7,37 @@
|
||||
>
|
||||
> Keep this document updated as architecture changes are made.
|
||||
|
||||
> Current shipped build: `v0.50.36-local.1` (April 14, 2026).
|
||||
> Baseline: upstream `nesquena/hermes-webui` `v0.50.36`.
|
||||
> Intentional local delta: first-time password enablement from Settings immediately issues a `hermes_session` cookie so the current browser remains signed in. The previous `Assistant Reply Language` customization has been removed, and legacy `assistant_language` settings are filtered out on load/save.
|
||||
> Automated coverage: 1059 passing tests.
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview and Purpose
|
||||
|
||||
The Hermes Web UI is a lightweight web application that gives you a browser-based
|
||||
interface to the Hermes agent that is functionally equivalent to the CLI. It is modeled on
|
||||
the Claude-style interface: a three-panel layout with a sidebar for session management,
|
||||
a central chat area, and a right panel for workspace file browsing.
|
||||
the Claude-style interface: a sidebar for session management, a central chat area,
|
||||
and a demand-driven right panel used for workspace browsing and preview surfaces.
|
||||
The right panel is closed by default on desktop and opens only when it is actively
|
||||
being used for browsing or previewing content.
|
||||
|
||||
The design philosophy is deliberately minimal. There is no build step, no bundler, no
|
||||
frontend framework. The Python server is split into a routing shell (server.py) and
|
||||
business logic modules (api/). The frontend is seven vanilla JS modules loaded from static/.
|
||||
This makes the code easy to modify from a terminal or by an agent.
|
||||
|
||||
For the current local build, the codebase is intentionally as close to upstream as possible:
|
||||
the app now tracks upstream `v0.50.36`, keeps the password-session continuity patch in the
|
||||
settings/onboarding flow, and does not carry forward the prior reply-language preference
|
||||
feature.
|
||||
|
||||
Hermes-level chrome is intentionally consolidated: the sidebar has no dedicated brand header.
|
||||
Instead, the footer exposes a single "Hermes WebUI" launch button that opens one tabbed
|
||||
control-center modal for global preferences, conversation import/export, and clear-conversation
|
||||
actions. The topbar remains focused on conversation context and the workspace/files toggle.
|
||||
|
||||
---
|
||||
|
||||
## 2. File Inventory
|
||||
@@ -28,7 +45,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,7 +57,9 @@ 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)
|
||||
upload.py Multipart parser, file upload handler (~78 lines)
|
||||
workspace.py File ops: list_dir, read_file_content, workspace helpers (~77 lines)
|
||||
@@ -48,11 +68,12 @@ This makes the code easy to modify from a terminal or by an agent.
|
||||
style.css All CSS incl. mobile responsive (~670 lines)
|
||||
ui.js DOM helpers, renderMd, tool cards, model dropdown, file tree (~977 lines)
|
||||
workspace.js File preview, file ops, loadDir, clearPreview (~185 lines)
|
||||
sessions.js Session CRUD, list rendering, search, SVG icons, overlay actions (~533 lines)
|
||||
sessions.js Session CRUD, list rendering, search, SVG icons, dropdown actions (~533 lines)
|
||||
messages.js send(), SSE event handlers, approval, transcript (~297 lines)
|
||||
panels.js Cron, skills, memory, workspace, profiles, todo, settings (~974 lines)
|
||||
commands.js Slash command registry, parser, autocomplete dropdown (~156 lines)
|
||||
boot.js Event wiring, mobile nav, voice input, boot IIFE (~338 lines)
|
||||
onboarding.js First-run wizard overlay, provider setup flow, and settings/workspace orchestration.
|
||||
boot.js Event wiring, mobile sidebar/workspace nav, voice input, boot IIFE (~338 lines)
|
||||
tests/
|
||||
conftest.py Isolated test server (port 8788, separate HERMES_HOME) (~240 lines)
|
||||
test_sprint{1-20b}.py Feature tests per sprint (21 files, 415 test functions)
|
||||
@@ -347,7 +368,7 @@ highlighting) and Mermaid.js (diagrams) from CDN, both loaded async/deferred wit
|
||||
Six JS modules loaded in order at end of <body>:
|
||||
1. ui.js (~846 lines) DOM helpers, renderMd, tool card rendering, global state
|
||||
2. workspace.js (~169 lines) File tree, preview, file operations
|
||||
3. sessions.js (~532 lines) Session CRUD, list rendering, search, SVG icons, overlay actions, project picker
|
||||
3. sessions.js (~532 lines) Session CRUD, list rendering, search, SVG icons, dropdown actions, project picker
|
||||
4. messages.js (~293 lines) send(), SSE event handlers, approval, transcript
|
||||
5. panels.js (~771 lines) Cron, skills, memory, workspace, todo, switchPanel
|
||||
6. boot.js (~175 lines) Event wiring + boot IIFE
|
||||
@@ -358,10 +379,19 @@ inherit `currentColor` for consistent theming.
|
||||
|
||||
Three-panel layout (in static/index.html):
|
||||
|
||||
<aside class="sidebar"> Left panel: session list, nav tabs, model selector
|
||||
<aside class="sidebar"> Left panel: session list, nav tabs, sidebar-footer Hermes WebUI trigger
|
||||
<main class="main"> Center: topbar, messages area, approval card, composer
|
||||
<aside class="rightpanel"> Right panel: workspace file tree and file preview
|
||||
|
||||
Composer footer layout (current):
|
||||
|
||||
left cluster attach button, mic button, per-conversation model selector
|
||||
right cluster compact circular context-usage badge, send button
|
||||
|
||||
The model selector is still the authoritative control for new-session creation
|
||||
and session updates; it was moved out of the sidebar so model choice feels scoped
|
||||
to the active conversation rather than a global app setting.
|
||||
|
||||
### 5.2 Global State
|
||||
|
||||
const S = {
|
||||
@@ -406,11 +436,19 @@ Approval:
|
||||
stopApprovalPolling clearInterval
|
||||
|
||||
UI helpers:
|
||||
setStatus(t) Updates #statusText in composer footer
|
||||
setStatus(t) Fallback helper: shows a toast for non-chat status/error messages
|
||||
setComposerStatus(t) Updates the inline composer status label for turn-scoped states
|
||||
setBusy(v) Sets S.busy, disables/enables Send button, clears status on false
|
||||
showToast(msg, ms) Bottom-center fade toast (default 2800ms)
|
||||
showConfirmDialog(o) Shared in-app confirmation modal, resolves true/false
|
||||
showPromptDialog(o) Shared in-app input modal, resolves string/null
|
||||
autoResize() Auto-resize #msg textarea up to 200px
|
||||
|
||||
Dialog policy:
|
||||
Native browser confirm()/prompt() are not used in the Web UI.
|
||||
Destructive actions use showConfirmDialog(...), then a toast on success.
|
||||
Lightweight naming flows (new file/folder/project) use showPromptDialog(...).
|
||||
|
||||
Files:
|
||||
loadDir(path) GET /api/list, rebuild #fileTree
|
||||
openFile(path) GET /api/file, show in #previewArea
|
||||
@@ -463,7 +501,7 @@ Known gaps:
|
||||
- Nested lists: single regex pass, multi-level indentation not handled
|
||||
- Mixed bold+link in same line: may produce garbled output
|
||||
|
||||
### 5.5 Model Chip Label (Fixed in Sprint 1)
|
||||
### 5.5 Model Label Resolution (Fixed in Sprint 1, reused by composer selector)
|
||||
|
||||
B3 was resolved in Sprint 1. Current code uses a MODEL_LABELS dict:
|
||||
|
||||
@@ -474,10 +512,10 @@ B3 was resolved in Sprint 1. Current code uses a MODEL_LABELS dict:
|
||||
'anthropic/claude-haiku-3-5': 'Haiku 3.5', 'google/gemini-2.5-pro': 'Gemini 2.5 Pro',
|
||||
'deepseek/deepseek-chat-v3-0324': 'DeepSeek V3', 'meta-llama/llama-4-scout': 'Llama 4 Scout',
|
||||
};
|
||||
$('modelChip').textContent = MODEL_LABELS[m] || (m.split('/').pop() || 'Unknown');
|
||||
getModelLabel(m) => MODEL_LABELS[m] || (m.split('/').pop() || 'Unknown');
|
||||
|
||||
Fallback: any unlisted model shows its short ID (after the last /) rather than a wrong label.
|
||||
To add a new model: add an entry to MODEL_LABELS and add an <option> to the <select>.
|
||||
To add a new model: add an entry to MODEL_LABELS and add an <option> to the composer footer <select>.
|
||||
|
||||
### 5.6 Session Delete Rules (from skill)
|
||||
|
||||
@@ -1095,7 +1133,7 @@ The model chip label bug is now fixed. The MODEL_LABELS object in syncTopbar():
|
||||
'deepseek/deepseek-chat-v3-0324': 'DeepSeek V3',
|
||||
'meta-llama/llama-4-scout': 'Llama 4 Scout',
|
||||
};
|
||||
$('modelChip').textContent = MODEL_LABELS[m] || (m.split('/').pop() || 'Unknown');
|
||||
getModelLabel(m) => MODEL_LABELS[m] || (m.split('/').pop() || 'Unknown');
|
||||
|
||||
Fallback: splits on '/' and uses the last segment, so any unlisted model shows its
|
||||
short identifier rather than a wrong hardcoded label.
|
||||
|
||||
1410
CHANGELOG.md
1410
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
171
CONTRIBUTING.md
Normal file
171
CONTRIBUTING.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# Contributing to Hermes WebUI
|
||||
|
||||
Thanks for contributing.
|
||||
|
||||
Hermes WebUI is intentionally simple to work on: Python on the server, vanilla JS in the browser, no build step, no bundler, no frontend framework. The best pull requests preserve that simplicity while solving a real problem cleanly.
|
||||
|
||||
## Two Paths to a Strong Pull Request
|
||||
|
||||
### Path 1: Small, Focused Changes
|
||||
|
||||
This is the fastest path to review and merge.
|
||||
|
||||
- Fix one clear bug or add one tightly scoped improvement
|
||||
- Touch the fewest files you can
|
||||
- Avoid drive-by refactors mixed into functional changes
|
||||
- Run the relevant tests locally before opening the PR
|
||||
- Keep the PR description concise and specific
|
||||
|
||||
These are the changes that are easiest to review and safest to merge quickly.
|
||||
|
||||
### Path 2: Bigger Changes
|
||||
|
||||
If you want to change architecture, reshape a workflow, add a substantial UI feature, or alter core behavior, align on direction first.
|
||||
|
||||
- Open an issue, start a discussion, or open a draft PR early
|
||||
- Explain the problem you are solving, not just the implementation you want
|
||||
- Call out tradeoffs, migration risk, and any alternatives you considered
|
||||
- Keep the final PR easy to review by separating unrelated work
|
||||
|
||||
Large changes are welcome, but surprise rewrites are hard to review well.
|
||||
|
||||
## What We Expect in Every PR
|
||||
|
||||
### 1. One Logical Change Per PR
|
||||
|
||||
Keep each PR focused. A small related group of fixes is fine. A bug fix plus a CSS cleanup plus a refactor plus a docs rewrite is not.
|
||||
|
||||
### 2. Local Verification
|
||||
|
||||
Run the test suite locally:
|
||||
|
||||
```bash
|
||||
pytest tests/ -v --timeout=60
|
||||
```
|
||||
|
||||
CI also runs this suite on Python `3.11`, `3.12`, and `3.13`.
|
||||
|
||||
If your change affects browser behavior, also run the relevant manual checks from [TESTING.md](TESTING.md).
|
||||
|
||||
### 3. Clear PR Description
|
||||
|
||||
There is currently no PR template in this repo, so include the important sections yourself:
|
||||
|
||||
- Thinking Path
|
||||
- What Changed
|
||||
- Why It Matters
|
||||
- Verification
|
||||
- Risks / Follow-ups
|
||||
- Model Used
|
||||
|
||||
If the change is user-visible, include screenshots or a short video.
|
||||
|
||||
For UI or UX changes, before/after images are required. PRs that change the interface or interaction flow without before/after images will likely be ignored, or closed in a regular maintainer sweep without review.
|
||||
|
||||
### 4. AI Usage Disclosure
|
||||
|
||||
If AI helped produce the change, say so in the PR description.
|
||||
|
||||
Include:
|
||||
|
||||
- Provider
|
||||
- Exact model name or ID
|
||||
- Any notable mode or tool use that mattered
|
||||
|
||||
If no AI was used, write: `None — human-authored`.
|
||||
|
||||
### 5. Keep the Docs Honest
|
||||
|
||||
If your change alters behavior, architecture, testing, setup, or user-facing workflows, update the relevant docs in the same PR.
|
||||
|
||||
Common files:
|
||||
|
||||
- [README.md](README.md) for setup, usage, and contributor-facing commands
|
||||
- [ROADMAP.md](ROADMAP.md) for shipped features and sprint history
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) for implementation details and design constraints
|
||||
- [TESTING.md](TESTING.md) for manual and automated verification guidance
|
||||
- [CHANGELOG.md](CHANGELOG.md) when maintainers want release-note-ready entries
|
||||
|
||||
## Project-Specific Guidelines
|
||||
|
||||
### Preserve the Design Constraints
|
||||
|
||||
Hermes WebUI is deliberately:
|
||||
|
||||
- No build step
|
||||
- No bundler
|
||||
- No frontend framework
|
||||
- Easy to modify from a terminal
|
||||
|
||||
Do not introduce new infrastructure or dependencies unless the gain is clear and the tradeoff is justified.
|
||||
|
||||
### Match the Existing Shape of the Codebase
|
||||
|
||||
- Server logic belongs in `api/` with `server.py` staying thin
|
||||
- Frontend behavior belongs in the existing `static/*.js` modules
|
||||
- Prefer extending current patterns over introducing parallel abstractions
|
||||
- Keep changes legible to future contributors working directly from the repo in a terminal
|
||||
|
||||
### Be Careful With User-Facing Changes
|
||||
|
||||
This project is heavily UI-driven. If you change interaction flows, session behavior, workspace browsing, onboarding, or mobile layouts:
|
||||
|
||||
- test the happy path
|
||||
- test reload behavior where relevant
|
||||
- test narrow/mobile layouts where relevant
|
||||
- include before/after images in the PR
|
||||
|
||||
### Security and Safety Matter
|
||||
|
||||
This app can expose workspace contents, run agent actions, and optionally sit behind a reverse proxy or Docker deployment. Treat auth, path handling, uploads, streaming, and environment handling as high-risk areas.
|
||||
|
||||
If your PR touches security-sensitive behavior, say so explicitly in the PR description and explain how you verified it.
|
||||
|
||||
## Writing a Good PR Message
|
||||
|
||||
Start with a short Thinking Path that explains the chain from project goal to the specific fix.
|
||||
|
||||
Example:
|
||||
|
||||
> - Hermes WebUI aims for near 1:1 parity with the Hermes CLI in a browser
|
||||
> - Long-running chat turns rely on SSE streaming and session recovery
|
||||
> - Reloading during an in-flight turn can leave the UI in an inconsistent state
|
||||
> - The bug was that recovered sessions restored messages but not the live stream state
|
||||
> - This PR fixes the recovery path so in-flight turns reconnect cleanly after reload
|
||||
> - The benefit is that users can refresh or reconnect without losing visibility into active work
|
||||
|
||||
Another example:
|
||||
|
||||
> - Hermes WebUI is intentionally a simple Python + vanilla JS application
|
||||
> - The right panel is used for workspace browsing and previews
|
||||
> - On mobile, panel state changes need to be obvious and touch-friendly
|
||||
> - The existing close affordance was inconsistent with the bottom-nav flow
|
||||
> - This PR fixes the mobile panel close behavior and aligns it with the current navigation model
|
||||
> - The result is fewer dead-end UI states on phones
|
||||
|
||||
After that, cover:
|
||||
|
||||
- what you changed
|
||||
- why you changed it
|
||||
- how you verified it
|
||||
- what risks remain
|
||||
|
||||
## Review Tips
|
||||
|
||||
Want the smoothest review?
|
||||
|
||||
- Keep diffs tight
|
||||
- Name things clearly
|
||||
- Avoid unnecessary rewrites
|
||||
- Add short comments only where the code would otherwise be hard to follow
|
||||
- Respond directly to review feedback and update the PR description if the scope changes
|
||||
|
||||
## Development References
|
||||
|
||||
- [README.md](README.md)
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md)
|
||||
- [TESTING.md](TESTING.md)
|
||||
- [ROADMAP.md](ROADMAP.md)
|
||||
- [SPRINTS.md](SPRINTS.md)
|
||||
|
||||
Questions are best raised early, before a large change is finished.
|
||||
83
Dockerfile
83
Dockerfile
@@ -3,21 +3,86 @@ 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 root
|
||||
|
||||
# Pre-install uv system-wide so the container doesn't need internet access at runtime.
|
||||
# Installing as root places uv in /usr/local/bin, available to all users.
|
||||
# The init script will skip the download when uv is already on PATH.
|
||||
RUN curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh
|
||||
|
||||
USER hermeswebuitoo
|
||||
|
||||
COPY . /apptoo
|
||||
|
||||
# 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
|
||||
|
||||
314
README.md
314
README.md
@@ -1,16 +1,32 @@
|
||||
# Hermes Web UI
|
||||
|
||||
[Hermes Agent](https://hermes-agent.nousresearch.com/) is a sophisticated autonomous agent that lives on your server, accessed via a terminal or messaging apps, remembers what it learns, and gets more capable the longer it runs.
|
||||
[Hermes Agent](https://hermes-agent.nousresearch.com/) is a sophisticated autonomous agent that lives on your server, accessed via a terminal or messaging apps, that remembers what it learns and gets more capable the longer it runs.
|
||||
|
||||
Hermes WebUI is a lightweight, dark-themed web app interface in your browser for [Hermes Agent](https://hermes-agent.nousresearch.com/).
|
||||
Full parity with the CLI experience - everything you can do from a terminal,
|
||||
you can do from this UI. No build step, no framework, no bundler. Just Python
|
||||
and vanilla JS.
|
||||
|
||||
Layout: three-panel Claude-style. Left sidebar for sessions and tools,
|
||||
center for chat, right for workspace file browsing.
|
||||
Layout: three-panel. Left sidebar for sessions and navigation, center for chat,
|
||||
right for workspace file browsing. Model, profile, and workspace controls live in
|
||||
the **composer footer** — always visible while composing. A circular context ring
|
||||
shows token usage at a glance. All settings and session tools are in the
|
||||
**Hermes Control Center** (launcher at the sidebar bottom).
|
||||
|
||||
<img width="1392" alt="Hermes Web UI — three-panel layout" src="https://github.com/user-attachments/assets/79cd3c0d-3167-42ed-9434-447a742c25c3" />
|
||||
<img alt="Hermes Web UI — three-panel layout" width="1417" height="867" alt="image" src="https://github.com/user-attachments/assets/51adff98-53ee-4800-8508-78b6c34dd3dc" />
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<img alt="Light mode with full profile support" src="https://github.com/user-attachments/assets/9b68142f-d974-4493-a8d1-fd73e622c7fd" />
|
||||
<br /><sub>Light mode with full profile support</sub>
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<img alt="Customize your settings, configure a password" src="https://github.com/user-attachments/assets/941f3156-21e3-41fd-bcc8-f975d5000cb8" />
|
||||
<br /><sub>Customize your settings, configure a password</sub>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@@ -79,20 +95,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/). Once installed:
|
||||
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 checkout automatically.
|
||||
2. Find (or create) a Python environment with the required dependencies.
|
||||
3. Start the 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.
|
||||
|
||||
---
|
||||
|
||||
@@ -100,14 +127,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
|
||||
```
|
||||
|
||||
@@ -115,7 +151,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.
|
||||
@@ -123,15 +163,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
|
||||
@@ -202,6 +270,40 @@ are running over SSH.
|
||||
|
||||
---
|
||||
|
||||
## Accessing on your phone with Tailscale
|
||||
|
||||
[Tailscale](https://tailscale.com) is a zero-config mesh VPN built on
|
||||
WireGuard. Install it on your server and your phone, and they join the same
|
||||
private network -- no port forwarding, no SSH tunnels, no public exposure.
|
||||
|
||||
The Hermes Web UI is fully responsive with a mobile-optimized layout
|
||||
(hamburger sidebar, sidebar top tabs in the drawer, touch-friendly controls),
|
||||
so it works well as a daily-driver agent interface from your phone.
|
||||
|
||||
**Setup:**
|
||||
|
||||
1. Install [Tailscale](https://tailscale.com/download) on your server and
|
||||
your iPhone/Android.
|
||||
2. Start the WebUI listening on all interfaces with password auth enabled:
|
||||
|
||||
```bash
|
||||
HERMES_WEBUI_HOST=0.0.0.0 HERMES_WEBUI_PASSWORD=your-secret ./start.sh
|
||||
```
|
||||
|
||||
3. Open `http://<server-tailscale-ip>:8787` in your phone's browser
|
||||
(find your server's Tailscale IP in the Tailscale app or with
|
||||
`tailscale ip -4` on the server).
|
||||
|
||||
That's it. Traffic is encrypted end-to-end by WireGuard, and password auth
|
||||
protects the UI at the application level. You can add it to your home screen
|
||||
for an app-like experience.
|
||||
|
||||
> **Tip:** If using Docker, set `HERMES_WEBUI_HOST=0.0.0.0` in your
|
||||
> `docker-compose.yml` environment (already the default) and set
|
||||
> `HERMES_WEBUI_PASSWORD`.
|
||||
|
||||
---
|
||||
|
||||
## Manual launch (without start.sh)
|
||||
|
||||
If you prefer to launch the server directly:
|
||||
@@ -237,8 +339,8 @@ Or using the agent venv explicitly:
|
||||
```
|
||||
|
||||
Tests run against an isolated server on port 8788 with a separate state directory.
|
||||
Production data and real cron jobs are never touched. Current count: **424 tests**
|
||||
across 22 test files.
|
||||
Production data and real cron jobs are never touched. Current count: **961 tests**
|
||||
across 53 test files.
|
||||
|
||||
---
|
||||
|
||||
@@ -250,7 +352,7 @@ across 22 test files.
|
||||
- Send a message while one is processing -- it queues automatically
|
||||
- Edit any past user message inline and regenerate from that point
|
||||
- Retry the last assistant response with one click
|
||||
- Cancel a running task from the activity bar
|
||||
- Cancel a running task directly from the composer footer (Stop button next to Send)
|
||||
- Tool call cards inline -- each shows the tool name, args, and result snippet; expand/collapse all toggle for multi-tool turns
|
||||
- Subagent delegation cards -- child agent activity shown with distinct icon and indented border
|
||||
- Mermaid diagram rendering inline (flowcharts, sequence diagrams, gantt charts)
|
||||
@@ -267,6 +369,7 @@ across 22 test files.
|
||||
|
||||
### Sessions
|
||||
- Create, rename, duplicate, delete, search by title and message content
|
||||
- Session actions via `⋯` dropdown per session — pin, move to project, archive, duplicate, delete
|
||||
- Pin/star sessions to the top of the sidebar (gold indicator)
|
||||
- Archive sessions (hide without deleting, toggle to show)
|
||||
- Session projects -- named groups with colors for organizing sessions
|
||||
@@ -298,10 +401,11 @@ across 22 test files.
|
||||
- Hidden when browser doesn't support Web Speech API (Chrome, Edge, Safari)
|
||||
|
||||
### Profiles
|
||||
- Profile picker in the topbar -- purple chip with dropdown showing all profiles
|
||||
- Profile chip in the **composer footer** -- dropdown showing all profiles with gateway status and model info
|
||||
- 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)
|
||||
|
||||
@@ -314,17 +418,25 @@ across 22 test files.
|
||||
- 20MB POST body size limit
|
||||
- CDN resources pinned with SRI integrity hashes
|
||||
|
||||
### Themes
|
||||
- 7 built-in themes: Dark (default), Light, Slate, Solarized Dark, Monokai, Nord, OLED
|
||||
- Switch via Settings panel dropdown (instant live preview) or `/theme` command
|
||||
- Persists across reloads (server-side in settings.json + localStorage for flicker-free loading)
|
||||
- Custom themes: define a `:root[data-theme="name"]` CSS block and it works — see [THEMES.md](THEMES.md)
|
||||
|
||||
### Settings and configuration
|
||||
- Settings panel (gear icon) -- default model, default workspace, send key preference
|
||||
- **Hermes Control Center** (sidebar launcher button) -- Conversation tab (export/import/clear), Preferences tab (model, send key, theme, language, all toggles), System tab (version, password)
|
||||
- Send key: Enter (default) or Ctrl/Cmd+Enter
|
||||
- Show/hide CLI sessions toggle (enabled by default)
|
||||
- Token usage display toggle (off by default, also via `/usage` command)
|
||||
- Control Center always opens on the Conversation tab; resets on close
|
||||
- Unsaved changes guard -- discard/save prompt when closing with unpersisted changes
|
||||
- Cron completion alerts -- toast notifications and unread badge on Tasks tab
|
||||
- Background agent error alerts -- banner when a non-active session encounters an error
|
||||
|
||||
### Slash commands
|
||||
- Type `/` in the composer for autocomplete dropdown
|
||||
- Built-in: `/help`, `/clear`, `/model <name>`, `/workspace <name>`, `/new`, `/usage`
|
||||
- Built-in: `/help`, `/clear`, `/model <name>`, `/workspace <name>`, `/new`, `/usage`, `/theme`, `/compact`
|
||||
- Arrow keys navigate, Tab/Enter select, Escape closes
|
||||
- Unrecognized commands pass through to the agent
|
||||
|
||||
@@ -339,10 +451,10 @@ across 22 test files.
|
||||
|
||||
### Mobile responsive
|
||||
- Hamburger sidebar -- slide-in overlay on mobile (<640px)
|
||||
- Bottom navigation bar -- 5-tab iOS-style fixed bar
|
||||
- Sidebar top tabs stay available on mobile; no fixed bottom nav stealing chat height
|
||||
- Files slide-over panel from right edge
|
||||
- Touch targets minimum 44px on all interactive elements
|
||||
- Composer positioned above bottom nav
|
||||
- Full-height chat/composer on phones without bottom-nav spacing
|
||||
- Desktop layout completely unchanged
|
||||
|
||||
---
|
||||
@@ -350,31 +462,33 @@ across 22 test files.
|
||||
## Architecture
|
||||
|
||||
```
|
||||
server.py HTTP routing shell + auth middleware (~83 lines)
|
||||
server.py HTTP routing shell + auth middleware (~154 lines)
|
||||
api/
|
||||
auth.py Optional password authentication, signed cookies (~149 lines)
|
||||
config.py Discovery, globals, model detection, reloadable config (~726 lines)
|
||||
helpers.py HTTP helpers, security headers (~71 lines)
|
||||
models.py Session model + CRUD + CLI bridge (~338 lines)
|
||||
profiles.py Profile state management, hermes_cli wrapper (~366 lines)
|
||||
routes.py All GET + POST route handlers (~1314 lines)
|
||||
streaming.py SSE engine, run_agent, cancel support (~332 lines)
|
||||
upload.py Multipart parser, file upload handler (~78 lines)
|
||||
auth.py Optional password authentication, signed cookies (~201 lines)
|
||||
config.py Discovery, globals, model detection, reloadable config (~1110 lines)
|
||||
helpers.py HTTP helpers, security headers (~175 lines)
|
||||
models.py Session model + CRUD + CLI bridge (~377 lines)
|
||||
onboarding.py First-run onboarding wizard, OAuth provider support (~507 lines)
|
||||
profiles.py Profile state management, hermes_cli wrapper (~411 lines)
|
||||
routes.py All GET + POST route handlers (~2250 lines)
|
||||
state_sync.py /insights sync — message_count to state.db (~113 lines)
|
||||
streaming.py SSE engine, run_agent, cancel support (~660 lines)
|
||||
updates.py Self-update check and release notes (~257 lines)
|
||||
upload.py Multipart parser, file upload handler (~82 lines)
|
||||
workspace.py File ops, workspace helpers, git detection (~288 lines)
|
||||
static/
|
||||
index.html HTML template (~388 lines)
|
||||
style.css All CSS incl. mobile responsive (~726 lines)
|
||||
ui.js DOM helpers, renderMd, tool cards, context indicator (~1063 lines)
|
||||
workspace.js File preview, file ops, git badge (~247 lines)
|
||||
sessions.js Session CRUD, collapsible groups, search (~589 lines)
|
||||
messages.js send(), SSE handlers, rAF throttle (~352 lines)
|
||||
panels.js Cron, skills, memory, profiles, settings (~1146 lines)
|
||||
commands.js Slash command autocomplete (~170 lines)
|
||||
boot.js Mobile nav, voice input, boot IIFE (~338 lines)
|
||||
index.html HTML template (~600 lines)
|
||||
style.css All CSS incl. mobile responsive, themes (~1050 lines)
|
||||
ui.js DOM helpers, renderMd, tool cards, context indicator (~1740 lines)
|
||||
workspace.js File preview, file ops, git badge (~286 lines)
|
||||
sessions.js Session CRUD, collapsible groups, search, reload recovery (~800 lines)
|
||||
messages.js send(), SSE handlers, live streaming, session recovery (~655 lines)
|
||||
panels.js Cron, skills, memory, profiles, settings (~1438 lines)
|
||||
commands.js Slash command autocomplete (~267 lines)
|
||||
boot.js Mobile nav, voice input, boot IIFE (~524 lines)
|
||||
tests/
|
||||
conftest.py Isolated test server (port 8788)
|
||||
test_sprint{1-23}.py 22 test files, 426 test functions
|
||||
test_regressions.py Permanent regression gate (23 tests)
|
||||
61 test files 961 test functions
|
||||
Dockerfile python:3.12-slim container image
|
||||
docker-compose.yml Compose with named volume and optional auth
|
||||
.github/workflows/ CI: multi-arch Docker build + GitHub Release on tag
|
||||
@@ -393,6 +507,120 @@ State lives outside the repo at `~/.hermes/webui-mvp/` by default
|
||||
- `TESTING.md` -- manual browser test plan and automated coverage reference
|
||||
- `CHANGELOG.md` -- release notes per sprint
|
||||
- `SPRINTS.md` -- forward sprint plan with CLI + Claude parity targets
|
||||
- `THEMES.md` -- theme system documentation, custom theme guide
|
||||
|
||||
## Contributors
|
||||
|
||||
Hermes WebUI is built with help from the open-source community. Every PR — whether merged directly or incorporated via rebase — shapes the project, and we're grateful to everyone who has taken the time to contribute.
|
||||
|
||||
### Major contributions
|
||||
|
||||
**[@aronprins](https://github.com/aronprins)** — v0.50.0 UI overhaul (PR #242)
|
||||
The biggest single contribution to the project: a complete UI redesign that moved model/profile/workspace controls into the composer footer, replaced the gear-icon settings panel with the Hermes Control Center (tabbed modal), removed the activity bar in favor of inline composer status, redesigned the session list with a `⋯` action dropdown, and added the workspace panel state machine. 26 commits, thoroughly designed and iterated through multiple review rounds.
|
||||
|
||||
**[@iRonin](https://github.com/iRonin)** — Security hardening sprint (PRs #196–#204)
|
||||
Six consecutive security and reliability PRs: session memory leak fix (expired token pruning), Content-Security-Policy + Permissions-Policy headers, 30-second slow-client connection timeout, optional HTTPS/TLS support via environment variables, upstream branch tracking fix for self-update, and CLI session support in the file browser API. This is the kind of focused, high-quality security work that makes a self-hosted tool trustworthy.
|
||||
|
||||
**[@DavidSchuchert](https://github.com/DavidSchuchert)** — German translation (PR #190)
|
||||
Complete German locale (`de`) covering all UI strings, settings labels, commands, and system messages — and in doing so, stress-tested the i18n system and exposed several elements that weren't yet translatable, which got fixed as part of the same PR.
|
||||
|
||||
**[@Jordan-SkyLF](https://github.com/Jordan-SkyLF)** — Live streaming, session recovery, workspace fallback (PRs #366, #367)
|
||||
Three interlocking improvements: workspace fallback resolution so the server recovers gracefully when the configured workspace is deleted or unavailable; live reasoning cards that upgrade the generic thinking spinner to a real-time reasoning display as the model thinks; and durable session state recovery via `localStorage` so in-flight tool cards, partial assistant output, and the live SSE stream all survive a full page reload or session switch.
|
||||
|
||||
### Feature contributions
|
||||
|
||||
**[@gabogabucho](https://github.com/gabogabucho)** — Spanish locale + onboarding wizard (PRs #275, #285)
|
||||
Full Spanish (`es`) locale covering all 175 UI strings, plus the one-shot bootstrap onboarding wizard that guides new users through provider setup on first launch — the feature most responsible for new users actually getting started.
|
||||
|
||||
**[@bergeouss](https://github.com/bergeouss)** — Real-time gateway session sync (PR #274)
|
||||
Bridged the gateway session database (Telegram, Discord, Slack, etc.) into the WebUI sidebar with live SSE polling. Gateway sessions now appear alongside WebUI sessions in real time, without any changes to hermes-agent.
|
||||
|
||||
**[@ccqqlo](https://github.com/ccqqlo)** — Terminal approval UX + custom model discovery + mobile close button (PRs #224, #225, #238, #333)
|
||||
A run of focused quality-of-life improvements: terminal tool approval prompts that stay visible long enough to actually be read, restored custom model API key discovery, and the redundant mobile close button fix that had been confusing users on narrow screens.
|
||||
|
||||
**[@kevin-ho](https://github.com/kevin-ho)** — OLED theme (PR #168)
|
||||
Added the 7th built-in theme: pure black backgrounds with warm accents tuned to reduce burn-in risk. Small diff, big impact for anyone on an OLED display.
|
||||
|
||||
**[@Bobby9228](https://github.com/Bobby9228)** — Mobile Profiles button + Android Chrome fixes (PRs #253, #263, #265)
|
||||
Added the Profiles entry to the mobile navigation flow, making profile switching reachable on phones, plus a set of Android Chrome-specific fixes for the profile dropdown.
|
||||
|
||||
**[@franksong2702](https://github.com/franksong2702)** — Session title guard + breadcrumb nav (PRs #301, #302)
|
||||
Two clean bug fixes / features: the session title guard that stops `title_from()` from overwriting user-renamed sessions after every turn, and clickable breadcrumb navigation in the workspace file preview panel.
|
||||
|
||||
**[@betamod](https://github.com/betamod)** — Security hardening (PR #171)
|
||||
A comprehensive security audit PR covering CSRF protection, SSRF guards, XSS escaping improvements, and the env race condition between concurrent agent sessions — foundational security work that shipped in v0.39.0.
|
||||
|
||||
**[@TaraTheStar](https://github.com/TaraTheStar)** — Bot name + thinking blocks + login refactor (PRs #132, #176, #181)
|
||||
Made the assistant display name configurable throughout the UI, added thinking/reasoning block display in chat, and refactored the login page to use template variables instead of inline string replacement.
|
||||
|
||||
**[@thadreber-web](https://github.com/thadreber-web)** — CLI session bridge (PR #56)
|
||||
The original CLI session bridge: reads CLI sessions from the agent's SQLite state store and surfaces them in the WebUI sidebar. This was the first bridge between the CLI and WebUI session worlds.
|
||||
|
||||
**[@deboste](https://github.com/deboste)** — Reverse proxy auth + mobile responsive layout + model routing (PRs #3, #4, #5)
|
||||
Three of the very first community PRs: fixed EventSource/fetch to use the URL origin for reverse proxy setups, corrected model provider routing from config, and added mobile responsive layout with dvh viewport fix. Early foundation work.
|
||||
|
||||
### Bug fix and security contributions
|
||||
|
||||
**[@Hinotoi-agent](https://github.com/Hinotoi-agent)** — Profile .env secret isolation (PR #351)
|
||||
Fixed API key leakage between profiles on switch — switching from a profile with `OPENAI_API_KEY` to one without it left the key in the process environment for the duration of the session, effectively leaking credentials. A subtle and important security fix.
|
||||
|
||||
**[@lawrencel1ng](https://github.com/lawrencel1ng)** — Bandit security fixes B310/B324/B110 + QuietHTTPServer (PR #354)
|
||||
Systematic bandit security scan fixes: URL scheme validation before `urlopen`, MD5 `usedforsecurity=False`, and 40+ bare `except: pass` blocks replaced with proper logging — plus `QuietHTTPServer` to stop client-disconnect log spam from SSE streams.
|
||||
|
||||
**[@lx3133584](https://github.com/lx3133584)** — CSRF fix for reverse proxy on non-standard ports (PR #360)
|
||||
Fixed CSRF rejection for deployments behind Nginx Proxy Manager or similar on non-standard ports — a real-world blocker for anyone hosting on a port other than 80/443.
|
||||
|
||||
**[@DelightRun](https://github.com/DelightRun)** — session_search fix for WebUI sessions (PR #356)
|
||||
The `session_search` tool silently returned "Session database not available" in every WebUI session. Tracked down the missing `SessionDB` injection in the streaming path and fixed it.
|
||||
|
||||
**[@shaoxianbilly](https://github.com/shaoxianbilly)** — Unicode filename downloads (PR #378)
|
||||
Fixed `UnicodeEncodeError` crashes when downloading workspace files with Chinese, Japanese, or other non-ASCII names. Implemented proper `Content-Disposition` header with RFC 5987 `filename*=UTF-8''...` encoding.
|
||||
|
||||
**[@huangzt](https://github.com/huangzt)** — Cancel interrupts agent (PR #244)
|
||||
Made the Cancel button actually interrupt the running agent and clean up UI state, rather than just hiding the button while the agent kept running.
|
||||
|
||||
**[@tgaalman](https://github.com/tgaalman)** — Thinking card fix (PR #169)
|
||||
Fixed top-level reasoning fields being missed in the thinking card display — an edge case in how Claude's extended thinking blocks surface in the API response.
|
||||
|
||||
**[@smurmann](https://github.com/smurmann)** — Custom provider routing fix (PR #189)
|
||||
Fixed model routing for slash-prefixed custom provider models, which were being misrouted in the model selector. A precise fix for a real edge case in multi-provider setups.
|
||||
|
||||
**[@jeffscottward](https://github.com/jeffscottward)** — Claude Haiku model ID fix (PR #145)
|
||||
Caught and corrected the Claude Haiku model ID (`3-5` → `4-5`) immediately after the Anthropic release — the kind of quick community catch that keeps the model dropdown accurate.
|
||||
|
||||
**[@kcclaw001](https://github.com/kcclaw001)** — Credential redaction in API responses (PR #243)
|
||||
Added credential redaction to all API response paths so API keys, tokens, and other secrets in session data or error messages are masked before reaching the browser.
|
||||
|
||||
**[@mbac](https://github.com/mbac)** — Phantom "Custom" provider group fix (PR #191)
|
||||
Removed the phantom "Custom" optgroup that appeared in the model dropdown even when no custom provider was configured — a small but consistently confusing UI noise issue.
|
||||
|
||||
**[@andrewy-wizard](https://github.com/andrewy-wizard)** — Chinese localization (PR #177)
|
||||
Added Simplified Chinese (`zh`) locale to the WebUI. One of the first non-English locales and the most-used non-English locale in the codebase.
|
||||
|
||||
**[@mmartial](https://github.com/mmartial)** — Docker UID/GID matching (PR #237)
|
||||
Added Docker support for running as an arbitrary UID/GID matching the host user, eliminating permission issues with bind-mounted volumes — essential for Docker deployments where the host user isn't UID 1000.
|
||||
|
||||
**[@vCillusion](https://github.com/vCillusion)** — pip package resolution fix (PR #76)
|
||||
Fixed agent dependency resolution to prefer packages from the venv's site-packages over the agent directory itself, preventing shadowing bugs when developing locally.
|
||||
|
||||
**[@carlytwozero](https://github.com/carlytwozero)** — API key pass-through for non-Anthropic providers (PR #78)
|
||||
Fixed `api_key` not being passed to `AIAgent` for non-Anthropic `/anthropic` providers — a quiet regression that silently broke any non-default provider.
|
||||
|
||||
**[@mangodxd](https://github.com/mangodxd)** — Type hints cleanup (PR #115)
|
||||
Added missing type hints across 10 files and corrected 9 inaccurate existing ones — the kind of maintenance work that makes the codebase easier to reason about.
|
||||
|
||||
**[@Argonaut790](https://github.com/Argonaut790)** — HTML entity decode + Traditional Chinese locale (PR #239)
|
||||
Fixed double-escaping of HTML entities in `renderMd()` — LLM output containing `<code>` was being escaped a second time, rendering as literal text instead of the intended markdown. The same PR also completed the Simplified Chinese translation (40+ missing keys) and added a full Traditional Chinese (`zh-Hant`) locale.
|
||||
|
||||
**[@indigokarasu](https://github.com/indigokarasu)** — Visual redesign proposal: icon rail + design token system + 7 themes (PR #213)
|
||||
A CSS-only redesign of the full UI — proper design tokens (`--bg-primary`, `--text-info`, spacing scale), an icon rail sidebar replacing the emoji tab strip, consistent form cards, breadcrumb nav, and 7 built-in themes as custom properties. The PR didn't merge as-is but directly shaped the design language and theme architecture that shipped in v0.50.0.
|
||||
|
||||
**[@zenc-cp](https://github.com/zenc-cp)** — Anti-hallucination guard for ReAct loop (PR #133)
|
||||
Added a streaming token buffer and post-run message scrub to `streaming.py` to detect and strip fake tool execution JSON that weaker models write inline instead of calling tools properly. A three-layer approach: ephemeral anti-hallucination prompt, live token filtering, and session history cleanup. The pattern influenced later streaming.py improvements.
|
||||
|
||||
---
|
||||
|
||||
Want to contribute? See [ARCHITECTURE.md](ARCHITECTURE.md) for the codebase layout and [TESTING.md](TESTING.md) for how to run the test suite. The best contributions are focused, well-tested, and solve a real problem — exactly what every person on this list did.
|
||||
|
||||
## Repo
|
||||
|
||||
|
||||
73
ROADMAP.md
73
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.31.2 (April 5, 2026)
|
||||
> Tests: 424 total (424 passing, 0 failures)
|
||||
> Last updated: v0.50.44 (April 14, 2026) — 1195 tests, 1195 passing
|
||||
> Local delta: enabling password from Settings keeps the current browser signed in; the former Assistant Reply Language enhancement has been removed.
|
||||
> Tests: 1059 total (1059 passing, 0 failures)
|
||||
> Source: <repo>/
|
||||
|
||||
---
|
||||
@@ -32,14 +33,50 @@
|
||||
| Sprint 13 | Alerts + polish | Cron completion alerts (polling + badge), background error banner, session duplicate, browser tab title | 221 |
|
||||
| Sprint 14 | Visual polish + workspace ops | Mermaid diagrams, message timestamps, file rename, folder create, session tags, session archive | 233 |
|
||||
| Sprint 15 | Session projects + code copy | Session projects/folders, code block copy button, tool card expand/collapse toggle | 237 |
|
||||
| Sprint 16 | Session sidebar visual polish | SVG action icons, overlay hover actions, pin indicator, project border, safe HTML rendering | 289 |
|
||||
| Sprint 16 | Session sidebar visual polish | SVG action icons, session action dropdown, pin indicator, project border, safe HTML rendering | 289 |
|
||||
| Sprint 17 | Workspace polish + slash commands + settings | Breadcrumb navigation, slash command autocomplete, send key setting (#26) | 318 |
|
||||
| Sprint 18 | Thinking display + workspace tree | File preview auto-close, thinking/reasoning cards, expandable directory tree (#22) | 318 |
|
||||
| Sprint 19 | Auth + security hardening | Password auth (off by default), login page, security headers, 20MB body limit (#23) | 328 |
|
||||
| Sprint 20 | Voice input + send button | Voice input (Web Speech API), send button icon-circle with pop-in animation | 415 |
|
||||
| Sprint 21 | Mobile responsive + Docker | Hamburger sidebar, bottom nav, files slide-over, Docker support (#21, #7) | 415 |
|
||||
| Sprint 21 | Mobile responsive + Docker | Hamburger sidebar, mobile 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 added to the mobile navigation flow with correct panel wiring and SVG sizing (#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 |
|
||||
| v0.34.1 | Theme variable polish | 30+ hardcoded dark-navy colors replaced with theme-aware CSS variables | 433 |
|
||||
| v0.34.2 | Theme text colors | 5 new per-theme typography variables (--strong, --em, --code-text, --code-inline-bg, --pre-text) | 433 |
|
||||
| v0.34.3 | Light theme final polish | 46 light-scoped selector overrides for sidebar, roles, chips, interactive elements | 433 |
|
||||
| v0.35 | Security hardening | Env race fix, random signing key, upload path traversal, PBKDF2 password hash | 433 |
|
||||
| v0.36–v0.37 | Model routing, personality config, tool card reload, duplicate model fixes | Model routing by provider prefix, personality via config.yaml, tool cards reload on page refresh | 466 |
|
||||
| v0.38.0–v0.38.6 | Model selector, custom endpoints, OLED theme, reasoning display, insights sync | Custom endpoint URL fix, OLED theme, top-level reasoning field fix, message_count sync to state.db | 466 |
|
||||
| v0.39.0 | Security hardening (Sprint 29) | CSRF, PBKDF2, rate limiting, session ID validation, SSRF, ENV_LOCK, XSS, HMAC, skills traversal, secure cookie, error sanitization, startup warning | 499 |
|
||||
| v0.40–v0.44.2 | Approval card + Lucide icons + sprint auth | Approval prompt surfaced in UI, emoji icons → Lucide SVG, login CSP inline fix, update diagnostics | 579 |
|
||||
| v0.45–v0.46 | Custom endpoints + security + i18n + cancel | Custom endpoint Base URL + API key on profile create, credential redaction (PR #243), Docker UID/GID (PR #237), HTML entity decode + zh/zh-Hant i18n, cancel interrupts agent | 624 |
|
||||
| v0.47–v0.47.1 | Dialogs + session menu + skills + mobile QA + Spanish | Shared app dialogs, session ⋯ menu, /skills command, mobile QA suite, Android Chrome fixes, Spanish locale (@gabogabucho) | 648 |
|
||||
| v0.48–v0.48.2 | Gateway session sync + table formatting + provider warnings | Real-time Telegram/Discord/Slack sessions in sidebar (@bergeouss), inlineMd() in table cells, provider/model mismatch toast | 679 |
|
||||
| v0.49–v0.49.1 | Onboarding wizard + Docker two-container | One-shot bootstrap + guided setup wizard, OpenRouter/Anthropic/OpenAI/Custom provider config, two-container Docker compose, mobile Profiles button | 700 |
|
||||
| v0.50.0 | v0.50.0 UI overhaul (Sprint 34) | Composer-centric controls, Hermes Control Center modal, workspace panel state machine, collapsible date groups, rAF streaming throttle, context ring indicator (@aronprins) | 742 |
|
||||
| v0.50.5–v0.50.10 | Think-tag edge cases + onboarding hardening + mobile fixes | MiniMax M2.5 leading-whitespace think-tag fix, skip-onboarding env var, OAuth provider path, Docker bridge networks fix, model dropdown dedup, title auto-generation fix, mobile close button | 802 |
|
||||
| v0.50.11–v0.50.12 | Chat table styles + URL autolink + profile env isolation | .msg-body table borders, plain URL auto-linking, profile .env secret isolation on switch (prevents API key leakage across profiles, @Hinotoi-agent) | 815 |
|
||||
| v0.50.13–v0.50.15 | session_search + security sweep + KaTeX math | SessionDB injection for session_search in WebUI (@DelightRun), bandit B310/B324/B110 + QuietHTTPServer (@lawrencel1ng), KaTeX math rendering with fence-before-math fix | 871 |
|
||||
| v0.50.16–v0.50.17 | CSRF reverse proxy + Docker uv pre-install | Scheme-aware CSRF port normalization for non-standard ports (@lx3133584), Docker uv pre-installed at build time as root (fixes air-gapped startup, @mmartial-pattern) | 900 |
|
||||
| v0.50.18–v0.50.19 | Workspace fallback + Unicode filenames | Cascading workspace path recovery (@Jordan-SkyLF), Unicode Content-Disposition headers with RFC 5987 filename* (@shaoxianbilly), silent auth error surfacing, stale model cleanup | 924 |
|
||||
| v0.50.20–v0.50.21 | Silent errors + live model fetching + durable streaming recovery | apperror on empty agent response, /api/models/live endpoint with SSRF guard, live reasoning cards, tool_complete SSE events, SESSION_QUEUES, localStorage reload recovery (@Jordan-SkyLF) | 961 |
|
||||
| v0.50.22–v0.50.36-local.1 | Upstream sync + minimal local patch retention | Synced to upstream `v0.50.36`; retained first-password session continuity in Settings/onboarding; removed local Assistant Reply Language enhancement; added legacy settings cleanup regression coverage | 1059 |
|
||||
| v0.50.37–v0.50.40 | Sprint 40 — rendering fixes + KaTeX CSP + MEDIA images | Think-tag edge cases, renderMd link double-linking fix, MEDIA: inline image rendering, KaTeX CSP font-src fix | 1117 |
|
||||
| v0.50.41–v0.50.43 | Sprint 41/42 — context ring, session polish, renderMd hardening | Context indicator live usage, session display fixes, renderMd bold+code stash, outer link pass ordering, _ob_stash, autolink double-link fixes (@multiple contributors) | 1150 |
|
||||
| v0.50.44 | Renderer formatting bug fixes (#486, #487) | CSS: inline code sizing in table cells; JS: markdown image syntax  → <img> in renderMd + inlineMd; _img_stash for autolink protection | 1195 |
|
||||
|
||||
---
|
||||
|
||||
@@ -47,14 +84,14 @@
|
||||
|
||||
| Layer | Location | Status |
|
||||
|-------|----------|--------|
|
||||
| Python server | <repo>/server.py (~81 lines) + api/ modules (~3210 lines) | Thin shell + auth middleware + business logic in api/ |
|
||||
| HTML template | <repo>/static/index.html (~364 lines) | Served from disk |
|
||||
| CSS | <repo>/static/style.css (~670 lines) | Served from disk, incl. mobile responsive |
|
||||
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands}.js | 7 modules, ~3610 lines total |
|
||||
| Python server | <repo>/server.py (~165 lines) + api/ modules (~5000 lines) | Thin shell + QuietHTTPServer + auth middleware + business logic in api/ |
|
||||
| HTML template | <repo>/static/index.html (~600 lines) | Served from disk |
|
||||
| CSS | <repo>/static/style.css (~1050 lines) | Served from disk, incl. mobile responsive, KaTeX, table styles |
|
||||
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands,icons,i18n,login}.js | 10 modules, ~7100 lines total |
|
||||
| Docker | Dockerfile, docker-compose.yml, .dockerignore | python:3.12-slim, multi-arch (amd64+arm64) |
|
||||
| CI/CD | .github/workflows/release.yml | Auto-release + GHCR publish on tag push |
|
||||
| Runtime state | ~/.hermes/webui-mvp/sessions/ | Session JSON files |
|
||||
| Test server | Port 8788, state dir ~/.hermes/webui-mvp-test/ | Isolated, wiped per run |
|
||||
| Test server | Port 8788 (conftest.py), port 8789 (browser sanity) | Isolated, wiped per run |
|
||||
| Production server | Port 8787 | SSH tunnel from Mac |
|
||||
|
||||
---
|
||||
@@ -64,11 +101,12 @@
|
||||
### Chat and Agent
|
||||
- [x] Send messages, get SSE-streaming responses
|
||||
- [x] Switch models per session (10 models, grouped by provider)
|
||||
- [x] Composer-scoped model picker in footer (moved from sidebar to align with per-conversation model selection)
|
||||
- [x] Multi-provider API support: use any Hermes agent API provider (OpenAI, Anthropic, Google, etc.) directly, not just OpenRouter (Sprint 11)
|
||||
- [x] Custom endpoint model discovery: auto-detect models from Ollama, LM Studio, and other local LLM servers via base_url (PR #18)
|
||||
- [x] Upload files to workspace (drag-drop, click, clipboard paste)
|
||||
- [x] File tray with remove button
|
||||
- [x] Tool progress shown in activity bar above composer
|
||||
- [x] Tool progress shown inline in the conversation via live tool cards
|
||||
- [x] Approval card for dangerous commands (Allow once/session/always, Deny)
|
||||
- [x] Approval polling + SSE-pushed approval events
|
||||
- [x] INFLIGHT guard: switch sessions mid-request without losing response
|
||||
@@ -80,23 +118,25 @@
|
||||
- [x] Token/cost estimate per message (Sprint 23)
|
||||
|
||||
### Tool Visibility
|
||||
- [x] Tool progress in activity bar (moved out of composer footer)
|
||||
- [x] Tool progress in live tool cards (kept out of the composer/footer chrome)
|
||||
- [x] Approval card with all 4 choices
|
||||
- [x] Tool call cards inline (collapsed, show name/args/result)
|
||||
|
||||
### Workspace / Files
|
||||
- [x] Workspace panel defaults closed and opens only for active browsing or preview
|
||||
- [x] Browse workspace directory tree with type icons
|
||||
- [x] Preview text/code files (read-only)
|
||||
- [x] Preview markdown files (rendered, tables supported)
|
||||
- [x] Preview image files (PNG, JPG, GIF, SVG, WEBP inline)
|
||||
- [x] Edit files inline (Edit button, Enter to save, Escape to cancel)
|
||||
- [x] Create new file (+ button in panel header)
|
||||
- [x] Delete file (hover trash, confirm dialog)
|
||||
- [x] Delete file (hover trash, confirmation modal)
|
||||
- [x] File name truncation with tooltip for long names
|
||||
- [x] Right panel resizable (drag inner edge)
|
||||
- [x] Syntax highlighted code preview (Prism.js)
|
||||
- [x] Rename file (Sprint 14)
|
||||
- [x] Create folder (Sprint 14)
|
||||
- [x] Shared app modal for confirm/input flows (Sprint 33)
|
||||
|
||||
### Sessions
|
||||
- [x] Create session (+ button or Cmd/Ctrl+K)
|
||||
@@ -186,7 +226,7 @@
|
||||
- [x] Voice input via Web Speech API (Sprint 20)
|
||||
|
||||
### Mobile
|
||||
- [x] Mobile responsive layout — hamburger sidebar, bottom nav, files slide-over (Sprint 21)
|
||||
- [x] Mobile responsive layout — hamburger sidebar, sidebar tabs on phones, files slide-over (Sprint 21 + later mobile nav simplification)
|
||||
|
||||
### Profiles
|
||||
- [x] Multi-profile support — create, switch, delete profiles (Sprint 22, Issue #28)
|
||||
@@ -197,16 +237,17 @@
|
||||
- [x] Streaming performance -- rAF-throttled token rendering (Sprint 24, PR #81)
|
||||
- [x] Workspace git detection -- branch name and dirty status badge (Sprint 24, PR #82)
|
||||
- [x] Collapsible date groups -- click group headers to collapse (Sprint 24, PR #80)
|
||||
- [x] Context usage indicator -- token count and cost in composer footer (Sprint 24, PR #83)
|
||||
- [x] Context usage indicator -- compact circular badge in composer footer (Sprint 24, PR #83; refreshed April 10, 2026)
|
||||
- [ ] LLM-generated session titles -- auto-title via small model instead of first-message substring (PR #75)
|
||||
- [ ] Workspace git detection -- show branch name, dirty status in workspace header (PR #75)
|
||||
- [ ] Clarify dialog -- agent can ask clarifying questions that block until user responds (PR #75)
|
||||
- [ ] Gateway approval polling -- support blocking approvals from messaging gateway (PR #75)
|
||||
- [ ] Unified session storage -- SessionDB shared between webui and CLI (PR #75)
|
||||
- [ ] TTS playback of responses (deferred)
|
||||
- [x] Background task cancel (activity bar Cancel button)
|
||||
- [x] Background task cancel (composer footer stop button)
|
||||
- [ ] Code execution cell (deferred)
|
||||
- [ ] Desktop application (deferred)
|
||||
- [ ] Desktop application (Sprint 25, PLANNED)
|
||||
- [x] Pluggable UI themes -- Dark, Light, Slate, Solarized, Monokai, Nord (Sprint 26, v0.34)
|
||||
- [ ] Extended slash command / skill integration (deferred)
|
||||
- [ ] Virtual scroll for large lists (deferred)
|
||||
|
||||
|
||||
350
SPRINTS.md
350
SPRINTS.md
@@ -1,32 +1,46 @@
|
||||
# Hermes Web UI -- Forward Sprint Plan
|
||||
|
||||
> Current state: v0.32 | 424 tests | Daily driver ready
|
||||
> This document plans the path from here to two targets:
|
||||
> Current state: v0.50.21 | 961 tests | Full daily driver — CLI parity achieved
|
||||
>
|
||||
> Target A: 1:1 feature parity with the Hermes CLI (everything you can do from the
|
||||
> terminal, you can do from the browser)
|
||||
> NOTE: Most planned work in this document has now shipped. This file is preserved
|
||||
> as a historical planning record. Current sprint state and version history live
|
||||
> in CHANGELOG.md and ROADMAP.md.
|
||||
>
|
||||
> Target B: 1:1 parity with Claude's reproducible features (the full Claude
|
||||
> browser UI experience, minus things only Anthropic can build)
|
||||
> Target A (CLI parity): ✅ Complete — all core tools, workspace, cron, skills,
|
||||
> memory, sessions, profiles, model routing, streaming, voice, mobile.
|
||||
>
|
||||
> Sprints are ordered by impact. Each builds on the one before.
|
||||
> Past sprint history lives in CHANGELOG.md.
|
||||
> Target B (Claude parity): ~90% — thinking display, math rendering (KaTeX),
|
||||
> tool cards, workspace preview, onboarding, settings panel all done.
|
||||
> Remaining: full subagent transparency UI, file diff viewer.
|
||||
>
|
||||
> Last meaningful update: v0.50.21 (April 13, 2026). See CHANGELOG.md for full history.
|
||||
|
||||
---
|
||||
|
||||
## Where we are now (v0.21)
|
||||
## Where we are now (v0.50.21 — updated April 2026)
|
||||
|
||||
**CLI parity: ~90% complete.** Core agent loop, all tools visible, workspace
|
||||
file ops with tree view, cron/skills/memory CRUD, session management, streaming,
|
||||
cancel, multi-provider models, custom endpoint discovery, slash commands,
|
||||
thinking/reasoning display, password auth -- all solid. Gaps are subagent
|
||||
visibility, toolset control, and code execution.
|
||||
> The sections below describe the state as of v0.36 for historical reference.
|
||||
> See ROADMAP.md for the current sprint history table (v0.36 → v0.50.21).
|
||||
|
||||
**Claude parity: ~70% complete.** Chat, streaming, file browser, session
|
||||
management, tool cards, syntax highlighting, model switching, projects,
|
||||
settings, Mermaid diagrams, mobile layout, breadcrumb workspace nav, slash
|
||||
commands, thinking display, auth -- all present. Gaps are artifacts, voice,
|
||||
TTS, sharing, mobile-optimized layout.
|
||||
**CLI parity: ✅ Complete** as of v0.50.x. Core agent loop, all tools visible, workspace
|
||||
file ops with tree view and git detection, cron/skills/memory CRUD, session
|
||||
management, streaming with rAF throttle, cancel, multi-provider models, custom
|
||||
endpoint discovery, slash commands (help/clear/model/workspace/new/usage/theme/compact),
|
||||
thinking/reasoning display, password auth, multi-profile support with seamless
|
||||
switching, CLI session bridge (read and import from state.db), context
|
||||
auto-compaction handling, self-update checker. Remaining gaps: subagent
|
||||
session tree, toolset control per session, code execution cells.
|
||||
|
||||
**Claude parity: ~85% complete.** Chat, streaming, file browser, session
|
||||
management with projects and tags, tool cards with subagent delegation,
|
||||
syntax highlighting, model switching, Mermaid diagrams, mobile responsive
|
||||
layout (hamburger sidebar, bottom nav, files slide-over), breadcrumb
|
||||
workspace nav with tree view, slash commands, thinking/reasoning display,
|
||||
auth with signed cookies, 6 pluggable UI themes (dark/light/slate/solarized/
|
||||
monokai/nord), voice input (Web Speech API), collapsible date groups,
|
||||
context usage indicator, token/cost display, git branch badge, Docker
|
||||
support. Remaining gaps: artifacts (HTML/SVG preview), TTS playback,
|
||||
sharing/public URLs, code execution inline.
|
||||
|
||||
---
|
||||
|
||||
@@ -75,7 +89,7 @@ heavy agentic work.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 12 -- Settings Panel + Reliability + Session QoL
|
||||
## Sprint 12 -- Settings Panel + Reliability + Session QoL (COMPLETED)
|
||||
|
||||
**Theme:** Persist your preferences, survive network blips, and organize sessions.
|
||||
|
||||
@@ -118,7 +132,7 @@ to keep important conversations accessible.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 13 -- Alerts, Session QoL, Polish
|
||||
## Sprint 13 -- Alerts, Session QoL, Polish (COMPLETED)
|
||||
|
||||
**Theme:** Know what Hermes is doing, and small quality-of-life wins.
|
||||
|
||||
@@ -248,7 +262,7 @@ inconsistently across platforms. These were the most common visual complaints.
|
||||
button now only appears in the hover overlay like all other actions.
|
||||
|
||||
### Track B: Features
|
||||
- **SVG action icons.** Replaced all emoji HTML entities (★, 📂, 📦, ⊕, 🗑)
|
||||
- **SVG action icons.** Replaced old symbol and emoji HTML entities
|
||||
with monochrome SVG line icons that inherit `currentColor`. Consistent
|
||||
rendering across macOS, Linux, and Windows. Icons: pin (star), folder,
|
||||
archive (box), duplicate (overlapping squares), trash (bin with lines).
|
||||
@@ -511,15 +525,14 @@ single default profile, blocking multi-persona workflows.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 23 -- Profile/Workspace/Model Coherence (COMPLETED)
|
||||
## Sprint 23 -- Agentic Transparency + Context Visibility (COMPLETED)
|
||||
|
||||
**Theme:** Make profiles, workspaces, models, and sessions coherent across
|
||||
profile switches.
|
||||
**Theme:** Surface what the agent is doing and how much context it's using.
|
||||
|
||||
**Why now:** Sprint 22 added profile switching but five coherence bugs remained:
|
||||
the model picker ignored the profile's default, workspaces were a global file,
|
||||
DEFAULT_WORKSPACE was a startup singleton, the session list showed all profiles,
|
||||
and switchToProfile() didn't refresh workspaces or sessions.
|
||||
**Why now:** Users had no visibility into tool call arguments, session token
|
||||
usage, or context window fill. Sprint 22 left five coherence bugs in the
|
||||
profile/workspace/model flow that also needed closing before the UI felt
|
||||
reliable.
|
||||
|
||||
### Track A: Bugs
|
||||
- **Model picker ignores profile on switch.** `populateModelDropdown()` skipped
|
||||
@@ -611,12 +624,9 @@ the app to others.
|
||||
CSS `contain: strict` + IntersectionObserver approach, no library needed.
|
||||
|
||||
### Track C: Code Quality
|
||||
- **SPRINTS.md + ROADMAP.md + CHANGELOG.md updated** to reflect Sprint 23
|
||||
completion (agentic transparency) and correct test counts.
|
||||
- **Remove stale Sprint 23 description** from SPRINTS.md (the "Profile/Workspace
|
||||
coherence" text is from an older plan; Sprint 23 actually shipped agentic
|
||||
transparency features).
|
||||
- **CHANGELOG entry for v0.29** covering Sprint 23 deliverables.
|
||||
- Audit and remove any remaining dead code introduced by Sprint 23 (e.g. `S.lastUsage` assignment in messages.js that nothing reads).
|
||||
- Verify tool call args render correctly in settled history cards on session reload.
|
||||
- Update test count in all docs to match actual pytest output after sprint merges.
|
||||
|
||||
**Estimated tests:** ~10 new. Target total: ~435.
|
||||
**Hermes CLI parity impact:** Low
|
||||
@@ -758,7 +768,7 @@ Both architectures in one .app. No separate downloads needed.
|
||||
- JS bridge fires when approval card appears/disappears
|
||||
|
||||
**Menu bar mode (optional, v2):**
|
||||
- A small status bar item (⚗️ icon in menu bar) that opens a compact popover
|
||||
- A small status bar item (beaker icon in menu bar) that opens a compact popover
|
||||
- Popover shows current session status, last message, quick-compose field
|
||||
- Useful for running Hermes in the background without a full window
|
||||
|
||||
@@ -897,6 +907,270 @@ genuinely differentiating for an open-source project
|
||||
|
||||
---
|
||||
|
||||
*Last updated: April 5, 2026*
|
||||
*Current version: v0.32 | 424 tests*
|
||||
## Sprint 26 -- Pluggable UI Themes (COMPLETED)
|
||||
|
||||
**Theme:** Let users choose how the app looks -- light, dark, and custom color
|
||||
schemes. One-click switching, persistent preference, zero flicker on load.
|
||||
|
||||
**Difficulty: Low-Medium.** The existing CSS is already 100% CSS-variable-driven
|
||||
off a single `:root` block. Every color, background, and accent in the entire UI
|
||||
is already a variable. Adding themes is mostly a matter of defining alternative
|
||||
`:root` overrides and wiring a picker -- not a rewrite. The main engineering
|
||||
work is flicker prevention on load and the settings UI.
|
||||
|
||||
**Estimated effort:** 1 sprint, ~2 days of implementation. 8-12 new tests.
|
||||
|
||||
---
|
||||
|
||||
### Why now
|
||||
|
||||
The UI ships only one dark theme. Contributors have asked for light mode. Power
|
||||
users want to match their terminal colorscheme. This is low-risk, high-value
|
||||
polish that makes the app feel more finished and more personal. It's also a
|
||||
good precedent-setter: once the theme system exists, community members can
|
||||
contribute new themes as a pure CSS addition with no Python changes needed.
|
||||
|
||||
---
|
||||
|
||||
### Design decisions
|
||||
|
||||
**Themes are CSS-variable overrides, not separate stylesheets.** Each theme is
|
||||
a named `:root[data-theme="name"]` block. The base stylesheet stays untouched.
|
||||
Switching themes sets `document.documentElement.dataset.theme = name` in JS.
|
||||
No FOUC (flash of unstyled content), no stylesheet swap latency.
|
||||
|
||||
**Theme preference persists server-side in `settings.json`.** Same mechanism
|
||||
as `send_key` and `show_token_usage`. The server includes `theme` in the
|
||||
`GET /api/settings` response. Boot.js reads it and applies before first paint.
|
||||
|
||||
**Flicker prevention.** A tiny inline `<script>` in `<head>` (before the
|
||||
stylesheet link) reads `localStorage.getItem('hermes-theme')` and sets
|
||||
`document.documentElement.dataset.theme` synchronously. This prevents a
|
||||
dark-flash on light-mode users during the round-trip to `/api/settings`.
|
||||
The localStorage value is kept in sync whenever the user changes themes.
|
||||
|
||||
**No third-party dependencies.** Pure CSS + vanilla JS. No theme library.
|
||||
|
||||
---
|
||||
|
||||
### Track A: Core theme system
|
||||
|
||||
**1. CSS variable blocks in `static/style.css`**
|
||||
|
||||
The existing `:root` block becomes the `dark` (default) theme. Add named
|
||||
theme blocks immediately after:
|
||||
|
||||
```css
|
||||
/* ── Default (dark) theme ── already in :root ── */
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--bg: #f5f5f7;
|
||||
--sidebar: #e8e8ed;
|
||||
--border: rgba(0,0,0,0.10);
|
||||
--border2: rgba(0,0,0,0.16);
|
||||
--text: #1c1c1e;
|
||||
--muted: #6e6e80;
|
||||
--accent: #c0392b;
|
||||
--blue: #0a6dc2;
|
||||
--gold: #a07a20;
|
||||
--code-bg: #f0f0f5;
|
||||
}
|
||||
|
||||
:root[data-theme="solarized"] {
|
||||
--bg: #002b36;
|
||||
--sidebar: #073642;
|
||||
--border: rgba(255,255,255,0.08);
|
||||
--border2: rgba(255,255,255,0.13);
|
||||
--text: #839496;
|
||||
--muted: #657b83;
|
||||
--accent: #dc322f;
|
||||
--blue: #268bd2;
|
||||
--gold: #b58900;
|
||||
--code-bg: #073642;
|
||||
}
|
||||
|
||||
:root[data-theme="monokai"] {
|
||||
--bg: #272822;
|
||||
--sidebar: #1e1f1c;
|
||||
--border: rgba(255,255,255,0.07);
|
||||
--border2: rgba(255,255,255,0.12);
|
||||
--text: #f8f8f2;
|
||||
--muted: #75715e;
|
||||
--accent: #f92672;
|
||||
--blue: #66d9e8;
|
||||
--gold: #e6db74;
|
||||
--code-bg: #1e1f1c;
|
||||
}
|
||||
|
||||
:root[data-theme="nord"] {
|
||||
--bg: #2e3440;
|
||||
--sidebar: #272c36;
|
||||
--border: rgba(255,255,255,0.07);
|
||||
--border2: rgba(255,255,255,0.12);
|
||||
--text: #eceff4;
|
||||
--muted: #9099aa;
|
||||
--accent: #bf616a;
|
||||
--blue: #81a1c1;
|
||||
--gold: #ebcb8b;
|
||||
--code-bg: #272c36;
|
||||
}
|
||||
```
|
||||
|
||||
Additional theming notes:
|
||||
- `syntax-highlight` colors (Prism.js) are theme-independent (they come from the
|
||||
CDN stylesheet) -- acceptable for v1.
|
||||
- The logo gradient (`linear-gradient(145deg,#e8a030,var(--accent))`) uses
|
||||
`--accent` already so it adapts automatically.
|
||||
- Scrollbar colors and `::selection` backgrounds need explicit overrides in the
|
||||
light theme to avoid dark scrollbars on a light background.
|
||||
|
||||
**2. Flicker-prevention inline script in `static/index.html`**
|
||||
|
||||
Immediately after `<head>` opens, before the stylesheet `<link>`:
|
||||
|
||||
```html
|
||||
<script>
|
||||
(function(){
|
||||
var t=localStorage.getItem('hermes-theme');
|
||||
if(t && t!=='dark') document.documentElement.dataset.theme=t;
|
||||
})();
|
||||
</script>
|
||||
```
|
||||
|
||||
This runs synchronously before the stylesheet parses. Zero flicker.
|
||||
|
||||
**3. Theme loading in `static/boot.js`**
|
||||
|
||||
In the existing `api('/api/settings')` call, read and apply the theme:
|
||||
|
||||
```js
|
||||
const s = await api('/api/settings');
|
||||
window._sendKey = s.send_key || 'enter';
|
||||
window._showTokenUsage = !!s.show_token_usage;
|
||||
window._showCliSessions = !!s.show_cli_sessions;
|
||||
// Theme: apply server preference, update localStorage for flicker prevention
|
||||
const theme = s.theme || 'dark';
|
||||
document.documentElement.dataset.theme = theme;
|
||||
localStorage.setItem('hermes-theme', theme);
|
||||
```
|
||||
|
||||
**4. Theme setting in `api/config.py`**
|
||||
|
||||
```python
|
||||
_SETTINGS_DEFAULTS = {
|
||||
...
|
||||
'theme': 'dark', # active UI theme name
|
||||
...
|
||||
}
|
||||
_SETTINGS_ALLOWED_KEYS = set(_SETTINGS_DEFAULTS.keys()) - {'password_hash'}
|
||||
```
|
||||
|
||||
No enum constraint on `theme` -- allows user-defined theme names to work
|
||||
without server changes.
|
||||
|
||||
---
|
||||
|
||||
### Track B: Theme picker UI
|
||||
|
||||
**Settings panel addition (`static/index.html` + `static/panels.js`)**
|
||||
|
||||
A `<select>` in the Settings panel, below the send-key picker:
|
||||
|
||||
```html
|
||||
<div class="settings-field">
|
||||
<label for="settingsTheme">Theme</label>
|
||||
<select id="settingsTheme" ...>
|
||||
<option value="dark">Dark (default)</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="solarized">Solarized Dark</option>
|
||||
<option value="monokai">Monokai</option>
|
||||
<option value="nord">Nord</option>
|
||||
</select>
|
||||
</div>
|
||||
```
|
||||
|
||||
In `loadSettingsPanel()`:
|
||||
```js
|
||||
const themeSel = $('settingsTheme');
|
||||
if(themeSel) themeSel.value = settings.theme || 'dark';
|
||||
```
|
||||
|
||||
In `saveSettings()`:
|
||||
```js
|
||||
body.theme = $('settingsTheme').value;
|
||||
```
|
||||
|
||||
**Live preview on select change (no save required):**
|
||||
```js
|
||||
$('settingsTheme').addEventListener('change', e => {
|
||||
document.documentElement.dataset.theme = e.target.value;
|
||||
localStorage.setItem('hermes-theme', e.target.value);
|
||||
});
|
||||
```
|
||||
|
||||
This gives instant visual feedback as the user clicks through options.
|
||||
The full settings save then persists it server-side.
|
||||
|
||||
**`/theme` slash command (`static/commands.js`)**
|
||||
|
||||
```js
|
||||
async function cmdTheme(arg) {
|
||||
const themes = ['dark','light','solarized','monokai','nord'];
|
||||
if(!arg || !themes.includes(arg)) {
|
||||
showToast('Usage: /theme dark|light|solarized|monokai|nord');
|
||||
return;
|
||||
}
|
||||
document.documentElement.dataset.theme = arg;
|
||||
localStorage.setItem('hermes-theme', arg);
|
||||
try { await api('/api/settings', {method:'POST', body: JSON.stringify({theme: arg})}); } catch(e) {}
|
||||
showToast('Theme: ' + arg);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Track C: Tests
|
||||
|
||||
New test cases in `tests/test_sprint26.py`:
|
||||
|
||||
1. `GET /api/settings` returns `theme: 'dark'` by default
|
||||
2. `POST /api/settings` with `{theme: 'light'}` persists and round-trips
|
||||
3. `POST /api/settings` with `{theme: 'nord'}` accepts any string (no enum gate)
|
||||
4. Theme value survives server restart (reads from `settings.json`)
|
||||
5. `/theme` command fires without error for each named theme
|
||||
6. `loadSettingsPanel()` populates the select with the current theme value
|
||||
7. Settings save includes theme in the POST body
|
||||
8. `data-theme` attribute is set on `<html>` before first paint (inline script)
|
||||
|
||||
**Estimated new tests:** 8. Target total after sprint: ~443.
|
||||
|
||||
---
|
||||
|
||||
### What's out of scope
|
||||
|
||||
- **Custom color editors** (hex pickers for each variable): saves that for v2.
|
||||
The five shipped themes cover the main use cases. A custom theme can always
|
||||
be added by dropping a CSS block with no code changes.
|
||||
- **Per-session themes**: single global preference is the right call for v1.
|
||||
- **System `prefers-color-scheme` sync**: nice-to-have, low priority. The
|
||||
flicker-prevention script could be extended to read the media query if no
|
||||
explicit preference is set.
|
||||
- **Prism.js theme switching**: the code-block syntax highlighting comes from
|
||||
a CDN stylesheet. Swapping it requires a `<link>` swap and SRI re-check.
|
||||
Defer to a future sprint; the default Prism Tomorrow theme works on all
|
||||
current dark themes and is acceptable on light.
|
||||
|
||||
---
|
||||
|
||||
**Estimated tests:** 8 new. Target total: ~443.
|
||||
**Hermes CLI parity impact:** None
|
||||
**Claude parity impact:** Medium (Claude.ai has light/dark/system sync)
|
||||
**User-facing value:** High -- first thing many users ask for
|
||||
|
||||
---
|
||||
|
||||
*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*
|
||||
|
||||
132
TESTING.md
132
TESTING.md
@@ -1,14 +1,14 @@
|
||||
# Hermes Web UI: Browser Testing Plan
|
||||
|
||||
> This document is for manual browser testing by you or by a Claude browser agent.
|
||||
> It covers user-facing features of the UI through Sprint 22 (v0.24).
|
||||
> It covers user-facing features of the UI through v0.50.21 and later releases.
|
||||
> Each section is written as a step-by-step test procedure with expected outcomes.
|
||||
> A browser agent (e.g. Claude with Chrome access) can execute this plan directly.
|
||||
>
|
||||
> Prerequisites: SSH tunnel is active on port 8787. Open http://localhost:8787 in browser.
|
||||
> Server health check: curl http://127.0.0.1:8787/health should return {"status":"ok"}.
|
||||
>
|
||||
> Automated tests: 424 total (424 passing, 0 failures)
|
||||
> Automated tests: 1195 total (1195 passing, 0 known failures). Includes onboarding coverage for bootstrap/static wizard presence, real provider config persistence (`config.yaml` + `.env`), the `/api/onboarding/*` backend, and the onboarding skip/existing-config guard.
|
||||
> Run: `pytest tests/ -v --timeout=60`
|
||||
|
||||
---
|
||||
@@ -32,9 +32,11 @@ SETUP: Clear localStorage (DevTools > Application > Local Storage > delete herme
|
||||
STEPS:
|
||||
1. Navigate to http://localhost:8787
|
||||
EXPECT:
|
||||
- Dark background, Hermes logo in sidebar header
|
||||
- Dark background
|
||||
- Sidebar begins directly with the icon tab row; there is no dedicated branding header
|
||||
- Center area shows "What can I help with?" heading with suggestion buttons
|
||||
- Session list in sidebar is empty or shows existing sessions
|
||||
- Sidebar footer shows a single "Hermes WebUI" control-center button
|
||||
- No session is highlighted active
|
||||
- Send button is present but there is no input focus by default
|
||||
FAIL: Page shows error, blank white screen, or auto-creates a new session without user action.
|
||||
@@ -73,11 +75,11 @@ STEPS:
|
||||
EXPECT:
|
||||
- User message appears immediately in chat
|
||||
- Thinking dots (three animated dots) appear below
|
||||
- Status bar shows "Hermes is thinking..."
|
||||
- Send button becomes disabled (grayed out)
|
||||
- A red stop button appears in the composer footer while the turn is running
|
||||
- Within 10-30 seconds, Hermes responds with a three-word greeting
|
||||
- Thinking dots disappear
|
||||
- Send button re-enables
|
||||
- Send button re-enables and the stop button disappears
|
||||
- Session title in sidebar updates to reflect the first message
|
||||
FAIL: Message never appears, thinking dots never go away, Send button stays disabled forever.
|
||||
|
||||
@@ -144,7 +146,7 @@ FAIL: New session created, error thrown, or UI breaks.
|
||||
### T3.1: Model Dropdown Shows All Options
|
||||
SETUP: Any active session.
|
||||
STEPS:
|
||||
1. Look at the sidebar bottom: "Model" label and a dropdown
|
||||
1. Look at the composer footer: to the right of the attach/mic controls there is a model dropdown
|
||||
2. Click the dropdown to expand it
|
||||
EXPECT:
|
||||
- Provider groups visible: OpenAI, Anthropic, Other
|
||||
@@ -153,18 +155,30 @@ EXPECT:
|
||||
- Other group: Gemini 2.5 Pro, DeepSeek V3, Llama 4 Scout
|
||||
FAIL: Only 2 options visible, no groups, or missing models.
|
||||
|
||||
### T3.2: Model Chip Reflects Selection
|
||||
### T3.2: Model Dropdown Reflects Active Conversation
|
||||
SETUP: Active session.
|
||||
STEPS:
|
||||
1. Change model dropdown to "Claude Sonnet 4.6"
|
||||
EXPECT:
|
||||
- The blue chip in the topbar right updates to "Sonnet 4.6" immediately
|
||||
- NOT "GPT-5.4 Mini" (this was Bug B3, now fixed)
|
||||
- The composer footer dropdown stays on "Claude Sonnet 4.6"
|
||||
- Sending the next message uses that session model rather than an older one from another conversation
|
||||
STEPS (continued):
|
||||
2. Change model to "Gemini 2.5 Pro"
|
||||
EXPECT:
|
||||
- Chip updates to "Gemini 2.5 Pro" (not "GPT-5.4 Mini")
|
||||
FAIL: Chip shows wrong model name for any non-Sonnet selection.
|
||||
- The dropdown updates to "Gemini 2.5 Pro"
|
||||
- Switching away and back to the conversation restores the same model in the footer selector
|
||||
FAIL: Dropdown shows the wrong active model after a session switch, or sending uses a stale model.
|
||||
|
||||
### T3.3: Context Badge Shares Footer Space Cleanly
|
||||
SETUP: Active session with at least one completed response.
|
||||
STEPS:
|
||||
1. Look at the right side of the composer footer
|
||||
EXPECT:
|
||||
- A compact circular context badge appears next to the send button when usage data is available
|
||||
- The number in the center shows the used percentage
|
||||
- Hovering or focusing the badge shows a tooltip with percent used, token count, auto-compress threshold, and estimated cost when available
|
||||
- The model dropdown remains usable without overlapping the send button or pushing controls out of view
|
||||
FAIL: Linear meter still shown, tooltip missing/incomplete, controls overlap, or footer wraps in a broken way.
|
||||
|
||||
---
|
||||
|
||||
@@ -228,8 +242,18 @@ FAIL: File not removed, error.
|
||||
|
||||
## Section 5: Workspace File Browser
|
||||
|
||||
### T5.1: File Tree Loads on Session Start
|
||||
### T5.0: Panel Is Closed By Default
|
||||
SETUP: Active session with workspace set.
|
||||
EXPECT:
|
||||
- Right workspace panel is hidden on initial load
|
||||
- Center chat column uses the freed width
|
||||
- "Files" toggle is visible in the topbar
|
||||
FAIL: Right panel starts open without any browsing or preview action.
|
||||
|
||||
### T5.1: File Tree Loads When Files Panel Is Opened
|
||||
SETUP: Active session with workspace set.
|
||||
STEPS:
|
||||
1. Click the "Files" toggle in the topbar
|
||||
EXPECT:
|
||||
- Right panel shows "WORKSPACE" header
|
||||
- File tree lists files and directories in the workspace
|
||||
@@ -263,10 +287,11 @@ STEPS:
|
||||
1. Click the X button in the panel header
|
||||
EXPECT:
|
||||
- Preview closes
|
||||
- File tree is visible again
|
||||
- If the panel auto-opened for that preview, the entire right panel closes again
|
||||
- If the panel was manually opened for browsing first, the file tree is visible again
|
||||
- Preview area is hidden
|
||||
- Reopening the same file shows fresh content (no stale cached text)
|
||||
FAIL: X button does nothing, tree does not reappear.
|
||||
FAIL: X button does nothing, panel stays stuck open, or the file tree does not reappear after manual browse mode.
|
||||
|
||||
### T5.5: Preview an Image File (Sprint 2)
|
||||
SETUP: Upload a PNG, JPG, or any image file to the workspace, OR the workspace already contains one.
|
||||
@@ -377,7 +402,8 @@ FAIL: Command blocked after Allow once, card stays, error.
|
||||
### T8.1: Download Conversation as Markdown
|
||||
SETUP: A session with at least 2 messages (1 user + 1 assistant).
|
||||
STEPS:
|
||||
1. Click the "Transcript" download button in the sidebar bottom
|
||||
1. Click the "Hermes" button in the sidebar footer
|
||||
2. In the Control Center modal, click "Transcript"
|
||||
EXPECT:
|
||||
- Browser downloads a .md file named hermes-{session_id}.md
|
||||
- Opening the file shows the conversation in markdown format:
|
||||
@@ -468,6 +494,7 @@ FAIL: No log output, log shows Apache-style text instead of JSON, log file not c
|
||||
SETUP: Message is sending (thinking dots visible).
|
||||
EXPECT:
|
||||
- Send button is visually grayed out
|
||||
- Stop button is visible in the composer footer
|
||||
- Pressing Enter does NOT send another message
|
||||
- Clicking Send button does nothing
|
||||
FAIL: Multiple messages sent while one is in flight.
|
||||
@@ -831,7 +858,7 @@ FAIL: No icon ever appears, icon always visible (not hover-only).
|
||||
### T21.2: Delete a File with Confirmation
|
||||
STEPS:
|
||||
1. Hover over a file and click its trash icon
|
||||
2. A browser confirm dialog appears: "Delete [filename]?"
|
||||
2. An in-app confirmation modal appears: "Delete [filename]?"
|
||||
3. Click OK
|
||||
EXPECT:
|
||||
- Toast: "Deleted [filename]"
|
||||
@@ -842,7 +869,7 @@ FAIL: File not deleted, no confirmation dialog, error.
|
||||
### T21.3: Cancel Delete Does Nothing
|
||||
STEPS:
|
||||
1. Hover over a file and click its trash icon
|
||||
2. Click Cancel on the confirm dialog
|
||||
2. Click Cancel on the confirmation modal
|
||||
EXPECT:
|
||||
- File remains in the tree
|
||||
- No toast, no error
|
||||
@@ -851,7 +878,7 @@ FAIL: File deleted despite cancel.
|
||||
### T21.4: Create a New File
|
||||
STEPS:
|
||||
1. Click the + button in the workspace panel header
|
||||
2. A prompt dialog appears: "New file name (e.g. notes.md):"
|
||||
2. An in-app input modal appears: "New file name (e.g. notes.md):"
|
||||
3. Type "test-sprint4.md" and click OK
|
||||
EXPECT:
|
||||
- Toast: "Created test-sprint4.md"
|
||||
@@ -925,7 +952,7 @@ FAIL: Invalid path added, no error.
|
||||
### T22.4: Remove a Workspace
|
||||
STEPS:
|
||||
1. Click the X button next to any non-default workspace
|
||||
2. Confirm the dialog
|
||||
2. Confirm the modal
|
||||
EXPECT:
|
||||
- Workspace disappears from the list
|
||||
- Toast: "Workspace removed"
|
||||
@@ -981,7 +1008,7 @@ STEPS:
|
||||
1. Hover over an assistant message
|
||||
2. Click the clipboard icon
|
||||
EXPECT:
|
||||
- Icon briefly shows a checkmark (✓) then reverts to clipboard
|
||||
- Icon briefly shows a check icon, then reverts to the copy icon
|
||||
- Paste (Cmd+V) elsewhere shows the full text of that message
|
||||
FAIL: No visual feedback, clipboard empty or wrong content.
|
||||
|
||||
@@ -994,23 +1021,23 @@ STEPS:
|
||||
1. Click any .py, .js, or .txt file in the workspace file tree
|
||||
EXPECT:
|
||||
- File content shows in read-only monospace view
|
||||
- An "✎ Edit" button is visible in the preview path bar
|
||||
- An Edit button with a pencil icon is visible in the preview path bar
|
||||
- Content is NOT editable (clicking in it does nothing)
|
||||
FAIL: Content immediately editable, no Edit button.
|
||||
|
||||
### T24.2: Edit Button Enters Edit Mode
|
||||
STEPS:
|
||||
1. Click "✎ Edit" on a code file preview
|
||||
1. Click the Edit button on a code file preview
|
||||
EXPECT:
|
||||
- Read-only view replaced by an editable textarea
|
||||
- Content of the file is pre-populated in the textarea
|
||||
- Button changes to "💾 Save"
|
||||
- Button changes to "Save" with a disk icon
|
||||
FAIL: Nothing changes, button doesn't change.
|
||||
|
||||
### T24.3: Save Writes Changes to Disk
|
||||
STEPS:
|
||||
1. In edit mode, change some text
|
||||
2. Click "💾 Save"
|
||||
2. Click the Save button
|
||||
EXPECT:
|
||||
- Read-only view returns, showing the updated content
|
||||
- Toast: "Saved"
|
||||
@@ -1022,8 +1049,8 @@ STEPS:
|
||||
1. Enter edit mode on a file
|
||||
2. Make any change (type a character)
|
||||
EXPECT:
|
||||
- Button shows "💾 Save*" (asterisk indicates unsaved changes)
|
||||
FAIL: No asterisk, button stays as "💾 Save".
|
||||
- Button shows "Save*" with the disk icon still visible (asterisk indicates unsaved changes)
|
||||
FAIL: No asterisk, button stays as "Save".
|
||||
|
||||
### T24.5: Markdown File Edit-Save Roundtrip
|
||||
STEPS:
|
||||
@@ -1070,7 +1097,7 @@ against each criterion below. A Claude browser agent can verify these with brows
|
||||
|
||||
### T25.1: Sidebar Nav Tabs are Icon-Only
|
||||
EXPECT:
|
||||
- Five icon-only tabs in the sidebar nav row: 💬 ⏱️ 📚 🧠 📁
|
||||
- Five icon-only tabs in the sidebar nav row: message, clock, book, brain, folder
|
||||
- No text labels visible by default (text removed to prevent overflow)
|
||||
- Hovering a tab shows a tooltip with the label (Chat/Tasks/Skills/Memory/Spaces)
|
||||
- Active tab has a blue underline, icon brighter blue
|
||||
@@ -1194,7 +1221,7 @@ STEPS:
|
||||
3. Click Create job
|
||||
EXPECT:
|
||||
- Form closes
|
||||
- Toast: "Job created ✓"
|
||||
- Toast: "Job created"
|
||||
- New job appears in the cron list with status "active"
|
||||
FAIL: Error shown, job not created, form stays open.
|
||||
|
||||
@@ -1225,7 +1252,8 @@ FAIL: Job created, form doesn't close.
|
||||
### T28.1: JSON Export Button Downloads File
|
||||
SETUP: Active session with at least a few messages.
|
||||
STEPS:
|
||||
1. Click the "JSON" button in the sidebar footer (next to Transcript)
|
||||
1. Click the "Hermes" button in the sidebar footer
|
||||
2. In the Control Center modal, click "JSON"
|
||||
EXPECT:
|
||||
- Browser downloads a file named hermes-{session_id}.json
|
||||
- Opening the file shows valid JSON with: session_id, title, messages array,
|
||||
@@ -1289,7 +1317,7 @@ STEPS (continued from T29.1):
|
||||
1. Change the name field to "Renamed Job"
|
||||
2. Click Save
|
||||
EXPECT:
|
||||
- Form closes, toast "Job updated ✓"
|
||||
- Form closes, toast "Job updated"
|
||||
- Job header shows new name
|
||||
FAIL: Save fails, name unchanged.
|
||||
|
||||
@@ -1297,7 +1325,7 @@ FAIL: Save fails, name unchanged.
|
||||
SETUP: A cron job you can safely delete (or a test job created for this).
|
||||
STEPS:
|
||||
1. Expand the job, click "Delete"
|
||||
2. Confirm the dialog
|
||||
2. Confirm the modal
|
||||
EXPECT:
|
||||
- Toast: "Job deleted"
|
||||
- Job disappears from the list
|
||||
@@ -1326,7 +1354,7 @@ tags: [test]
|
||||
# Test"
|
||||
2. Click Save skill
|
||||
EXPECT:
|
||||
- Toast "Skill created ✓", form closes
|
||||
- Toast "Skill created", form closes
|
||||
- Skill appears in the skills list
|
||||
FAIL: Error, skill not in list.
|
||||
|
||||
@@ -1354,7 +1382,7 @@ STEPS:
|
||||
1. In edit mode, add a line to the textarea
|
||||
2. Click Save
|
||||
EXPECT:
|
||||
- Toast "Memory saved ✓", form closes
|
||||
- Toast "Memory saved", form closes
|
||||
- Memory panel reloads showing the updated content
|
||||
FAIL: Save fails, content unchanged.
|
||||
|
||||
@@ -1467,14 +1495,16 @@ FAIL: Both messages removed, wrong message sent, crash.
|
||||
### T34.1: Clear Button Appears When Session Has Messages
|
||||
SETUP: Session with at least one message.
|
||||
EXPECT:
|
||||
- A "🗑 Clear" chip appears in the topbar right side (next to the workspace chip)
|
||||
- Button NOT visible when session has no messages / empty state
|
||||
- The "Hermes" button is visible in the sidebar footer
|
||||
- Opening the Control Center shows a "Clear" action in the Conversation section
|
||||
- The Clear action is disabled when there is no active session or no messages
|
||||
FAIL: Button always visible, never visible.
|
||||
|
||||
### T34.2: Clear Wipes Messages and Resets Title
|
||||
STEPS:
|
||||
1. Click the Clear button in the topbar
|
||||
2. Confirm the dialog
|
||||
1. Click the "Hermes" button in the sidebar footer
|
||||
2. Click "Clear" in the Conversation section
|
||||
3. Confirm the modal
|
||||
EXPECT:
|
||||
- All messages disappear from the chat area
|
||||
- Empty state ("What can I help with?") reappears
|
||||
@@ -1485,7 +1515,7 @@ FAIL: Session deleted, messages remain, title not reset.
|
||||
|
||||
### T34.3: Cancel Clear Does Nothing
|
||||
STEPS:
|
||||
1. Click Clear, then click Cancel in the confirm dialog
|
||||
1. Click Clear, then click Cancel in the confirmation modal
|
||||
EXPECT:
|
||||
- All messages still present
|
||||
- No toast, no change
|
||||
@@ -1609,7 +1639,7 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
- Switch model. Send a message. Verify response uses selected model.
|
||||
|
||||
### Sprint 12: Settings + Pin + Import
|
||||
- Click gear icon. Settings overlay opens.
|
||||
- Click the "Hermes WebUI" button in the sidebar footer. Control Center overlay opens with vertical section tabs on the left.
|
||||
- Change default model, save. Restart server. Verify setting persisted.
|
||||
- Pin a session (star icon in hover overlay). Verify it floats to top of list.
|
||||
- Export session as JSON. Import it back. Verify messages restored.
|
||||
@@ -1637,11 +1667,12 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
|
||||
### Sprint 16: Sidebar Visual Polish
|
||||
- Session titles use full sidebar width (no truncated space for hidden icons).
|
||||
- Hover a session → action buttons appear from right with gradient fade.
|
||||
- Hover a session → a dotted actions trigger appears on the right.
|
||||
- Click the dotted trigger → a dropdown opens with pin, project, archive, duplicate, and delete actions.
|
||||
- All icons are monochrome SVGs (not emoji). Consistent across platforms.
|
||||
- Pinned sessions show small gold star inline. Unpinned = no star, full title width.
|
||||
- Active session has gold highlight (not blue). Overlay gradient matches.
|
||||
- Double-click to rename → overlay hides during rename.
|
||||
- Active session has gold highlight (not blue).
|
||||
- Double-click to rename → session actions hide during rename.
|
||||
|
||||
### Sprint 17: Workspace + Slash Commands + Send Key
|
||||
- Navigate into a subdirectory. Breadcrumb bar appears with clickable segments.
|
||||
@@ -1684,12 +1715,13 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
- Open on mobile viewport (<640px): hamburger icon visible in topbar.
|
||||
- Tap hamburger → sidebar slides in from left with backdrop overlay.
|
||||
- Tap outside sidebar → closes. Tap a session → closes and loads session.
|
||||
- Bottom navigation bar: 5 tabs (Chat, Tasks, Skills, Memory, Spaces).
|
||||
- Tap "Tasks" in bottom nav → sidebar opens showing Tasks panel.
|
||||
- Tap "Chat" in bottom nav → sidebar closes (chat is in main area).
|
||||
- Sidebar top nav remains visible inside the mobile drawer; includes Chat/Tasks/Skills/Memory/Spaces/Profile tabs.
|
||||
- Tap "Tasks" in the drawer nav → Tasks panel opens in the sidebar drawer.
|
||||
- Tap "Chat" in the drawer nav → sidebar closes and chat is unobstructed in the main area.
|
||||
- Files button in topbar → right panel slides in from right.
|
||||
- No fixed mobile bottom nav; chat transcript and composer use the reclaimed vertical space.
|
||||
- All touch targets are at least 44px (session items, buttons, icons).
|
||||
- Desktop viewport (>640px): no hamburger, no bottom nav, no mobile elements.
|
||||
- Desktop viewport (>640px): no hamburger or mobile overlay; desktop layout unchanged.
|
||||
- Docker: `docker compose up -d` starts server on port 8787.
|
||||
- Docker: session data persists across container restarts (named volume).
|
||||
|
||||
@@ -1702,14 +1734,14 @@ Each has automated API-level tests in `tests/test_sprint{N}.py`.
|
||||
- "Use" button switches profile. Delete button removes non-default profiles.
|
||||
- "+ New profile" form: name validation (lowercase + hyphens), clone config checkbox.
|
||||
- Create profile → appears in list and dropdown.
|
||||
- Delete profile → confirm dialog. Auto-switches to default if deleting active.
|
||||
- Delete profile → confirmation modal. Auto-switches to default if deleting active.
|
||||
- Attempt switch while agent busy → blocked with toast message.
|
||||
- With hermes-agent not installed → only default profile shown, graceful fallback.
|
||||
|
||||
---
|
||||
|
||||
*Last updated: Sprint 22 / v0.24, April 3, 2026*
|
||||
*Total automated tests: 415 (392 passing, 23 pre-existing failures)*
|
||||
*Regression gate: tests/test_regressions.py (23 tests)*
|
||||
*Last updated: v0.50.44, April 14, 2026*
|
||||
*Total automated tests: 1195 (1195 passing, 0 failures)*
|
||||
*Regression gate: tests/test_regressions.py*
|
||||
*Run: pytest tests/ -v --timeout=60*
|
||||
*Source: <repo>/*
|
||||
|
||||
145
THEMES.md
Normal file
145
THEMES.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# Hermes Web UI — Themes
|
||||
|
||||
Hermes Web UI supports pluggable color themes. Seven themes ship built-in, and
|
||||
you can create your own with pure CSS — no Python changes needed.
|
||||
|
||||
---
|
||||
|
||||
## Switching Themes
|
||||
|
||||
**Settings panel:** Click the gear icon, select a theme from the dropdown. The
|
||||
preview is instant — the UI updates as you click through options.
|
||||
|
||||
**Slash command:** Type `/theme dark` or `/theme light` in the composer.
|
||||
|
||||
**Themes persist** across page reloads and server restarts (stored in
|
||||
`settings.json` server-side, with `localStorage` for flicker-free loading).
|
||||
|
||||
---
|
||||
|
||||
## Built-in Themes
|
||||
|
||||
| Theme | Description |
|
||||
|-------|-------------|
|
||||
| **Dark** (default) | Deep navy/indigo with muted blue accents. Easy on the eyes for long sessions. |
|
||||
| **Light** | Warm off-white with dark text. High contrast for bright environments. |
|
||||
| **Slate** | Warm charcoal, lighter than Dark. Easier on the eyes for extended use. |
|
||||
| **Solarized Dark** | Ethan Schoonover's classic dark palette. Teal background, warm accents. |
|
||||
| **Monokai** | Warm dark theme inspired by the Monokai editor scheme. Green/pink accents. |
|
||||
| **Nord** | Arctic blue-gray palette from the Nord color system. Calm and minimal. |
|
||||
| **OLED** | True black (#000) backgrounds for OLED displays. Minimizes glow and burn-in risk. |
|
||||
| **Custom themes** | Any string accepted by `settings.json`, `POST /api/settings`, and `/theme` if added to the picker/command list. Pure CSS variables only. |
|
||||
|
||||
---
|
||||
|
||||
## Creating a Custom Theme
|
||||
|
||||
A theme is a CSS block that overrides the color variables. Add it to
|
||||
`static/style.css` (or a separate file that you link after the main stylesheet).
|
||||
|
||||
### Step 1: Define your theme block
|
||||
|
||||
Every color in the UI comes from these CSS variables:
|
||||
|
||||
```css
|
||||
:root[data-theme="your-theme-name"] {
|
||||
/* Core palette */
|
||||
--bg: #1a1a2e; /* Main background */
|
||||
--sidebar: #16213e; /* Sidebar background */
|
||||
--border: rgba(255,255,255,0.08); /* Subtle borders */
|
||||
--border2: rgba(255,255,255,0.14); /* Stronger borders */
|
||||
--text: #e8e8f0; /* Primary text color */
|
||||
--muted: #8888aa; /* Secondary/muted text */
|
||||
--accent: #e94560; /* Accent color (errors, warnings, delete) */
|
||||
--blue: #7cb9ff; /* Primary action color (links, active states) */
|
||||
--gold: #c9a84c; /* Secondary accent (pinned items, gold highlights) */
|
||||
--code-bg: #0d1117; /* Code block background */
|
||||
|
||||
/* Surface and chrome (required for full theme polish) */
|
||||
--surface: #1a2535; /* Dropdowns, popups, toast, approval card */
|
||||
--topbar-bg: rgba(22,33,62,.98); /* Topbar background */
|
||||
--main-bg: rgba(26,26,46,0.5); /* Main chat area background */
|
||||
--input-bg: rgba(255,255,255,.04); /* Input/button subtle backgrounds */
|
||||
--hover-bg: rgba(255,255,255,.06); /* Hover state backgrounds */
|
||||
--focus-ring: rgba(124,185,255,.35); /* Focus border color */
|
||||
--focus-glow: rgba(124,185,255,.08); /* Focus box-shadow glow */
|
||||
|
||||
/* Typography (required for readable text across themes) */
|
||||
--strong: #fff; /* Bold text in messages */
|
||||
--em: #c9c9e8; /* Italic text in messages */
|
||||
--code-text: #f0c27f; /* Inline code text color */
|
||||
--code-inline-bg: rgba(0,0,0,.35); /* Inline code background */
|
||||
--pre-text: #e2e8f0; /* Code block text color */
|
||||
}
|
||||
```
|
||||
|
||||
The **core palette** controls the overall mood. The **surface/chrome** and
|
||||
**typography** variables are part of the standard theme contract — define all
|
||||
of them for a complete theme.
|
||||
|
||||
For **light themes**, you also need `:root[data-theme="name"]` overrides
|
||||
for elements that use `rgba(255,255,255,.XX)` hover/border effects (these
|
||||
are invisible on light backgrounds). See the built-in light theme for the
|
||||
full pattern — it overrides ~45 selectors for proper dark-on-light contrast
|
||||
on hover states, borders, chips, role labels, session items, and
|
||||
interactive elements.
|
||||
|
||||
### Step 2: Add it to the theme picker (optional)
|
||||
|
||||
To make your theme appear in the Settings dropdown, add an `<option>` to the
|
||||
theme `<select>` in `static/index.html`:
|
||||
|
||||
```html
|
||||
<option value="your-theme-name">Your Theme Name</option>
|
||||
```
|
||||
|
||||
And update the `/theme` command's valid theme list in `static/commands.js`.
|
||||
|
||||
### Step 3: Test it
|
||||
|
||||
Switch to your theme via `/theme your-theme-name` or the Settings panel.
|
||||
Check these areas:
|
||||
- Sidebar session list (hover states, active state, project borders)
|
||||
- Message bubbles (user vs assistant styling)
|
||||
- Code blocks (background contrast, copy button visibility)
|
||||
- Tool cards (running indicator, expand/collapse)
|
||||
- Settings panel and login page
|
||||
- Mobile layout (hamburger sidebar, bottom nav)
|
||||
|
||||
### Tips
|
||||
|
||||
- **Light themes** need scrollbar and selection overrides, plus the full
|
||||
text/code set (`--strong`, `--em`, `--code-text`, `--code-inline-bg`,
|
||||
`--pre-text`) or they will look broken.
|
||||
- The **logo gradient** uses `--accent` automatically, so it adapts to your
|
||||
theme without extra work.
|
||||
- **Prism.js syntax highlighting** uses its own CDN stylesheet (Tomorrow theme).
|
||||
It works well on dark themes; on light themes the contrast is acceptable but
|
||||
not perfect. Custom Prism theme support is planned for a future update.
|
||||
- **No server changes needed.** The `theme` setting in `settings.json` accepts
|
||||
any string — your custom theme name will persist without code changes.
|
||||
|
||||
---
|
||||
|
||||
## How Themes Work Internally
|
||||
|
||||
1. Each theme is a `:root[data-theme="name"]` CSS block that overrides variables.
|
||||
2. Switching themes sets `document.documentElement.dataset.theme = name` in JS.
|
||||
3. A tiny inline `<script>` in `<head>` reads `localStorage` before the
|
||||
stylesheet loads — this prevents a flash of the wrong theme on page load.
|
||||
4. The theme preference is saved server-side via `POST /api/settings` and
|
||||
loaded on boot via `GET /api/settings`.
|
||||
5. The `/theme` command and Settings dropdown both update the DOM, localStorage,
|
||||
and server settings simultaneously.
|
||||
|
||||
---
|
||||
|
||||
## Contributing a Theme
|
||||
|
||||
To contribute a new built-in theme:
|
||||
|
||||
1. Add your `:root[data-theme="name"]` block to `static/style.css`
|
||||
2. Add the `<option>` to the Settings panel in `static/index.html`
|
||||
3. Add the theme name to the valid list in `cmdTheme()` in `static/commands.js`
|
||||
4. Test on desktop and mobile
|
||||
5. Open a PR — themes are pure CSS additions with no backend changes needed
|
||||
89
api/auth.py
89
api/auth.py
@@ -6,12 +6,15 @@ or configuring a password in the Settings panel.
|
||||
import hashlib
|
||||
import hmac
|
||||
import http.cookies
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from api.config import STATE_DIR, load_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Public paths (no auth required) ─────────────────────────────────────────
|
||||
PUBLIC_PATHS = frozenset({
|
||||
'/login', '/health', '/favicon.ico',
|
||||
@@ -24,19 +27,60 @@ SESSION_TTL = 86400 # 24 hours
|
||||
# Active sessions: token -> expiry timestamp
|
||||
_sessions = {}
|
||||
|
||||
# ── Login rate limiter ──────────────────────────────────────────────────────
|
||||
_login_attempts = {} # ip -> [timestamp, ...]
|
||||
_LOGIN_MAX_ATTEMPTS = 5
|
||||
_LOGIN_WINDOW = 60 # seconds
|
||||
|
||||
def _check_login_rate(ip: str) -> bool:
|
||||
"""Return True if the IP is allowed to attempt login."""
|
||||
now = time.time()
|
||||
attempts = _login_attempts.get(ip, [])
|
||||
# Prune old attempts
|
||||
attempts = [t for t in attempts if now - t < _LOGIN_WINDOW]
|
||||
_login_attempts[ip] = attempts
|
||||
return len(attempts) < _LOGIN_MAX_ATTEMPTS
|
||||
|
||||
def _record_login_attempt(ip: str) -> None:
|
||||
now = time.time()
|
||||
attempts = _login_attempts.get(ip, [])
|
||||
attempts.append(now)
|
||||
_login_attempts[ip] = attempts
|
||||
|
||||
|
||||
def _signing_key():
|
||||
"""Derive a stable signing key from STATE_DIR."""
|
||||
return hashlib.sha256(str(STATE_DIR).encode()).digest()
|
||||
"""Return a random signing key, generating and persisting one on first call."""
|
||||
key_file = STATE_DIR / '.signing_key'
|
||||
if key_file.exists():
|
||||
try:
|
||||
raw = key_file.read_bytes()
|
||||
if len(raw) >= 32:
|
||||
return raw[:32]
|
||||
except Exception:
|
||||
logger.debug("Failed to read signing key from file, generating new key")
|
||||
# Generate a new random key
|
||||
key = secrets.token_bytes(32)
|
||||
try:
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
key_file.write_bytes(key)
|
||||
key_file.chmod(0o600)
|
||||
except Exception:
|
||||
logger.debug("Failed to persist signing key, using in-memory key only")
|
||||
return key
|
||||
|
||||
|
||||
def _hash_password(password):
|
||||
"""SHA-256 hash with a salt derived from STATE_DIR."""
|
||||
salt = str(STATE_DIR).encode()
|
||||
return hashlib.sha256(salt + password.encode()).hexdigest()
|
||||
"""PBKDF2-SHA256 with 600k iterations (OWASP recommendation).
|
||||
Salt is the persisted random signing key, which is secret and unique per
|
||||
installation. This keeps the stored hash format a plain hex string
|
||||
(no format change to settings.json) while replacing the predictable
|
||||
STATE_DIR-derived salt from the original implementation."""
|
||||
salt = _signing_key()
|
||||
dk = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600_000)
|
||||
return dk.hex()
|
||||
|
||||
|
||||
def get_password_hash():
|
||||
def get_password_hash() -> str | None:
|
||||
"""Return the active password hash, or None if auth is disabled.
|
||||
Priority: env var > settings.json."""
|
||||
env_pw = os.getenv('HERMES_WEBUI_PASSWORD', '').strip()
|
||||
@@ -46,12 +90,12 @@ def get_password_hash():
|
||||
return settings.get('password_hash') or None
|
||||
|
||||
|
||||
def is_auth_enabled():
|
||||
def is_auth_enabled() -> bool:
|
||||
"""True if a password is configured (env var or settings)."""
|
||||
return get_password_hash() is not None
|
||||
|
||||
|
||||
def verify_password(plain):
|
||||
def verify_password(plain) -> bool:
|
||||
"""Verify a plaintext password against the stored hash."""
|
||||
expected = get_password_hash()
|
||||
if not expected:
|
||||
@@ -59,20 +103,28 @@ def verify_password(plain):
|
||||
return hmac.compare_digest(_hash_password(plain), expected)
|
||||
|
||||
|
||||
def create_session():
|
||||
def create_session() -> str:
|
||||
"""Create a new auth session. Returns signed cookie value."""
|
||||
token = secrets.token_hex(32)
|
||||
_sessions[token] = time.time() + SESSION_TTL
|
||||
sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:16]
|
||||
sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
return f"{token}.{sig}"
|
||||
|
||||
|
||||
def verify_session(cookie_value):
|
||||
def _prune_expired_sessions():
|
||||
"""Remove all expired session entries to prevent unbounded memory growth."""
|
||||
now = time.time()
|
||||
for token in [t for t, exp in _sessions.items() if now > exp]:
|
||||
_sessions.pop(token, None)
|
||||
|
||||
|
||||
def verify_session(cookie_value) -> bool:
|
||||
"""Verify a signed session cookie. Returns True if valid and not expired."""
|
||||
if not cookie_value or '.' not in cookie_value:
|
||||
return False
|
||||
_prune_expired_sessions() # lazy cleanup on every verification attempt
|
||||
token, sig = cookie_value.rsplit('.', 1)
|
||||
expected_sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:16]
|
||||
expected_sig = hmac.new(_signing_key(), token.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
if not hmac.compare_digest(sig, expected_sig):
|
||||
return False
|
||||
expiry = _sessions.get(token)
|
||||
@@ -82,14 +134,14 @@ def verify_session(cookie_value):
|
||||
return True
|
||||
|
||||
|
||||
def invalidate_session(cookie_value):
|
||||
def invalidate_session(cookie_value) -> None:
|
||||
"""Remove a session token."""
|
||||
if cookie_value and '.' in cookie_value:
|
||||
token = cookie_value.rsplit('.', 1)[0]
|
||||
_sessions.pop(token, None)
|
||||
|
||||
|
||||
def parse_cookie(handler):
|
||||
def parse_cookie(handler) -> str | None:
|
||||
"""Extract the auth cookie from the request headers."""
|
||||
cookie_header = handler.headers.get('Cookie', '')
|
||||
if not cookie_header:
|
||||
@@ -103,7 +155,7 @@ def parse_cookie(handler):
|
||||
return morsel.value if morsel else None
|
||||
|
||||
|
||||
def check_auth(handler, parsed):
|
||||
def check_auth(handler, parsed) -> bool:
|
||||
"""Check if request is authorized. Returns True if OK.
|
||||
If not authorized, sends 401 (API) or 302 redirect (page) and returns False."""
|
||||
if not is_auth_enabled():
|
||||
@@ -128,7 +180,7 @@ def check_auth(handler, parsed):
|
||||
return False
|
||||
|
||||
|
||||
def set_auth_cookie(handler, cookie_value):
|
||||
def set_auth_cookie(handler, cookie_value) -> None:
|
||||
"""Set the auth cookie on the response."""
|
||||
cookie = http.cookies.SimpleCookie()
|
||||
cookie[COOKIE_NAME] = cookie_value
|
||||
@@ -136,10 +188,13 @@ def set_auth_cookie(handler, cookie_value):
|
||||
cookie[COOKIE_NAME]['samesite'] = 'Lax'
|
||||
cookie[COOKIE_NAME]['path'] = '/'
|
||||
cookie[COOKIE_NAME]['max-age'] = str(SESSION_TTL)
|
||||
# Set Secure flag when connection is HTTPS
|
||||
if getattr(handler.request, 'getpeercert', None) is not None or handler.headers.get('X-Forwarded-Proto', '') == 'https':
|
||||
cookie[COOKIE_NAME]['secure'] = True
|
||||
handler.send_header('Set-Cookie', cookie[COOKIE_NAME].OutputString())
|
||||
|
||||
|
||||
def clear_auth_cookie(handler):
|
||||
def clear_auth_cookie(handler) -> None:
|
||||
"""Clear the auth cookie on the response."""
|
||||
cookie = http.cookies.SimpleCookie()
|
||||
cookie[COOKIE_NAME] = ''
|
||||
|
||||
128
api/clarify.py
Normal file
128
api/clarify.py
Normal file
@@ -0,0 +1,128 @@
|
||||
"""Clarify prompt state for the WebUI.
|
||||
|
||||
This mirrors the approval flow structure, but the response is a free-form
|
||||
clarification string instead of an approval decision.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from typing import Optional
|
||||
|
||||
|
||||
_lock = threading.Lock()
|
||||
_pending: dict[str, dict] = {}
|
||||
_gateway_queues: dict[str, list] = {}
|
||||
_gateway_notify_cbs: dict[str, object] = {}
|
||||
|
||||
|
||||
class _ClarifyEntry:
|
||||
"""One pending clarify request inside a session."""
|
||||
|
||||
__slots__ = ("event", "data", "result")
|
||||
|
||||
def __init__(self, data: dict):
|
||||
self.event = threading.Event()
|
||||
self.data = data
|
||||
self.result: Optional[str] = None
|
||||
|
||||
|
||||
def register_gateway_notify(session_key: str, cb) -> None:
|
||||
"""Register a per-session callback for sending clarify requests to the UI."""
|
||||
with _lock:
|
||||
_gateway_notify_cbs[session_key] = cb
|
||||
|
||||
|
||||
def _clear_queue_locked(session_key: str) -> list[_ClarifyEntry]:
|
||||
entries = _gateway_queues.pop(session_key, [])
|
||||
_pending.pop(session_key, None)
|
||||
return entries
|
||||
|
||||
|
||||
def unregister_gateway_notify(session_key: str) -> None:
|
||||
"""Unregister the per-session callback and unblock any waiting clarify prompt."""
|
||||
with _lock:
|
||||
_gateway_notify_cbs.pop(session_key, None)
|
||||
entries = _clear_queue_locked(session_key)
|
||||
for entry in entries:
|
||||
entry.event.set()
|
||||
|
||||
|
||||
def clear_pending(session_key: str) -> int:
|
||||
"""Clear any pending clarify prompts for the session without removing the callback."""
|
||||
with _lock:
|
||||
entries = _clear_queue_locked(session_key)
|
||||
for entry in entries:
|
||||
entry.event.set()
|
||||
return len(entries)
|
||||
|
||||
|
||||
def submit_pending(session_key: str, data: dict) -> _ClarifyEntry:
|
||||
"""Queue a pending clarify request and notify the UI callback if registered."""
|
||||
with _lock:
|
||||
queue = _gateway_queues.setdefault(session_key, [])
|
||||
# De-duplicate while unresolved: if the most recent pending clarify is
|
||||
# semantically identical, reuse it instead of stacking duplicates.
|
||||
if queue:
|
||||
last = queue[-1]
|
||||
if (
|
||||
str(last.data.get("question", "")) == str(data.get("question", ""))
|
||||
and list(last.data.get("choices_offered") or [])
|
||||
== list(data.get("choices_offered") or [])
|
||||
):
|
||||
entry = last
|
||||
cb = _gateway_notify_cbs.get(session_key)
|
||||
# Keep _pending aligned to the oldest unresolved entry.
|
||||
_pending[session_key] = queue[0].data
|
||||
if cb:
|
||||
try:
|
||||
cb(dict(entry.data))
|
||||
except Exception:
|
||||
pass
|
||||
return entry
|
||||
|
||||
entry = _ClarifyEntry(data)
|
||||
queue.append(entry)
|
||||
_pending[session_key] = queue[0].data
|
||||
cb = _gateway_notify_cbs.get(session_key)
|
||||
if cb:
|
||||
try:
|
||||
cb(data)
|
||||
except Exception:
|
||||
pass
|
||||
return entry
|
||||
|
||||
|
||||
def get_pending(session_key: str) -> dict | None:
|
||||
"""Return the oldest pending clarify request for this session, if any."""
|
||||
with _lock:
|
||||
queue = _gateway_queues.get(session_key) or []
|
||||
if queue:
|
||||
return dict(queue[0].data)
|
||||
pending = _pending.get(session_key)
|
||||
return dict(pending) if pending else None
|
||||
|
||||
|
||||
def has_pending(session_key: str) -> bool:
|
||||
with _lock:
|
||||
return bool(_gateway_queues.get(session_key))
|
||||
|
||||
|
||||
def resolve_clarify(session_key: str, response: str, resolve_all: bool = False) -> int:
|
||||
"""Resolve the oldest pending clarify request for a session."""
|
||||
with _lock:
|
||||
queue = _gateway_queues.get(session_key)
|
||||
if not queue:
|
||||
_pending.pop(session_key, None)
|
||||
return 0
|
||||
entries = list(queue) if resolve_all else [queue.pop(0)]
|
||||
if queue:
|
||||
_pending[session_key] = queue[0].data
|
||||
else:
|
||||
_clear_queue_locked(session_key)
|
||||
count = 0
|
||||
for entry in entries:
|
||||
entry.result = response
|
||||
entry.event.set()
|
||||
count += 1
|
||||
return count
|
||||
1215
api/config.py
1215
api/config.py
File diff suppressed because it is too large
Load Diff
229
api/gateway_watcher.py
Normal file
229
api/gateway_watcher.py
Normal file
@@ -0,0 +1,229 @@
|
||||
"""
|
||||
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 logging
|
||||
import os
|
||||
import queue
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from api.config import HOME
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ── 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(), usedforsecurity=False).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
|
||||
HAVING COUNT(m.id) > 0
|
||||
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 None,
|
||||
'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:
|
||||
logger.debug("Failed to send sentinel to subscriber")
|
||||
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:
|
||||
logger.debug("Failed to send sentinel to dead subscriber")
|
||||
|
||||
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:
|
||||
logger.debug("Error in gateway watcher poll loop", exc_info=True)
|
||||
|
||||
# Sleep in small increments so we can stop promptly
|
||||
for _ in range(self.POLL_INTERVAL * 10):
|
||||
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
|
||||
114
api/helpers.py
114
api/helpers.py
@@ -2,22 +2,32 @@
|
||||
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
|
||||
|
||||
|
||||
def require(body: dict, *fields):
|
||||
def require(body: dict, *fields) -> None:
|
||||
"""Phase D: Validate required fields. Raises ValueError with clean message."""
|
||||
missing = [f for f in fields if not body.get(f) and body.get(f) != 0]
|
||||
if missing:
|
||||
raise ValueError(f"Missing required field(s): {', '.join(missing)}")
|
||||
|
||||
|
||||
def bad(handler, msg, status=400):
|
||||
def bad(handler, msg, status: int=400):
|
||||
"""Return a clean JSON error response."""
|
||||
return j(handler, {'error': msg}, status=status)
|
||||
|
||||
|
||||
def _sanitize_error(e: Exception) -> str:
|
||||
"""Strip filesystem paths from exception messages before returning to client."""
|
||||
import re
|
||||
msg = str(e)
|
||||
# Remove absolute paths (Unix and Windows)
|
||||
msg = re.sub(r'(?:(?:/[a-zA-Z0-9_.-]+)+|(?:[A-Z]:\\[^\s]+))', '<path>', msg)
|
||||
return msg
|
||||
|
||||
|
||||
def safe_resolve(root: Path, requested: str) -> Path:
|
||||
"""Resolve a relative path inside root, raising ValueError on traversal."""
|
||||
resolved = (root / requested).resolve()
|
||||
@@ -30,9 +40,21 @@ def _security_headers(handler):
|
||||
handler.send_header('X-Content-Type-Options', 'nosniff')
|
||||
handler.send_header('X-Frame-Options', 'DENY')
|
||||
handler.send_header('Referrer-Policy', 'same-origin')
|
||||
handler.send_header(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; "
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
|
||||
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "
|
||||
"img-src 'self' data:; font-src 'self' data: https://cdn.jsdelivr.net; connect-src 'self'; "
|
||||
"base-uri 'self'; form-action 'self'"
|
||||
)
|
||||
handler.send_header(
|
||||
'Permissions-Policy',
|
||||
'camera=(), microphone=(self), geolocation=()'
|
||||
)
|
||||
|
||||
|
||||
def j(handler, payload, status=200):
|
||||
def j(handler, payload, status: int=200) -> None:
|
||||
"""Send a JSON response."""
|
||||
body = _json.dumps(payload, ensure_ascii=False, indent=2).encode('utf-8')
|
||||
handler.send_response(status)
|
||||
@@ -44,7 +66,7 @@ def j(handler, payload, status=200):
|
||||
handler.wfile.write(body)
|
||||
|
||||
|
||||
def t(handler, payload, status=200, content_type='text/plain; charset=utf-8'):
|
||||
def t(handler, payload, status: int=200, content_type: str='text/plain; charset=utf-8') -> None:
|
||||
"""Send a plain text or HTML response."""
|
||||
body = payload if isinstance(payload, bytes) else str(payload).encode('utf-8')
|
||||
handler.send_response(status)
|
||||
@@ -59,7 +81,89 @@ def t(handler, payload, status=200, content_type='text/plain; charset=utf-8'):
|
||||
MAX_BODY_BYTES = 20 * 1024 * 1024 # 20MB limit for non-upload POST bodies
|
||||
|
||||
|
||||
def read_body(handler):
|
||||
# ── 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))
|
||||
if length > MAX_BODY_BYTES:
|
||||
|
||||
@@ -3,6 +3,7 @@ Hermes Web UI -- Session model and in-memory session store.
|
||||
"""
|
||||
import collections
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
@@ -14,6 +15,8 @@ from api.config import (
|
||||
)
|
||||
from api.workspace import get_last_workspace
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _write_session_index():
|
||||
"""Rebuild the session index file for O(1) future reads."""
|
||||
@@ -24,7 +27,7 @@ def _write_session_index():
|
||||
s = Session.load(p.stem)
|
||||
if s: entries.append(s.compact())
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to load session from %s", p)
|
||||
with LOCK:
|
||||
for s in SESSIONS.values():
|
||||
if not any(e['session_id'] == s.session_id for e in entries):
|
||||
@@ -34,12 +37,17 @@ def _write_session_index():
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, session_id=None, title='Untitled',
|
||||
def __init__(self, session_id: str=None, title: str='Untitled',
|
||||
workspace=str(DEFAULT_WORKSPACE), model=DEFAULT_MODEL,
|
||||
messages=None, created_at=None, updated_at=None,
|
||||
tool_calls=None, pinned=False, archived=False,
|
||||
project_id=None, profile=None,
|
||||
input_tokens=0, output_tokens=0, estimated_cost=None,
|
||||
tool_calls=None, pinned: bool=False, archived: bool=False,
|
||||
project_id: str=None, profile=None,
|
||||
input_tokens: int=0, output_tokens: int=0, estimated_cost=None,
|
||||
personality=None,
|
||||
active_stream_id: str=None,
|
||||
pending_user_message: str=None,
|
||||
pending_attachments=None,
|
||||
pending_started_at=None,
|
||||
**kwargs):
|
||||
self.session_id = session_id or uuid.uuid4().hex[:12]
|
||||
self.title = title
|
||||
@@ -56,13 +64,19 @@ class Session:
|
||||
self.input_tokens = input_tokens or 0
|
||||
self.output_tokens = output_tokens or 0
|
||||
self.estimated_cost = estimated_cost
|
||||
self.personality = personality
|
||||
self.active_stream_id = active_stream_id
|
||||
self.pending_user_message = pending_user_message
|
||||
self.pending_attachments = pending_attachments or []
|
||||
self.pending_started_at = pending_started_at
|
||||
|
||||
@property
|
||||
def path(self):
|
||||
return SESSION_DIR / f'{self.session_id}.json'
|
||||
|
||||
def save(self):
|
||||
self.updated_at = time.time()
|
||||
def save(self, touch_updated_at: bool = True) -> None:
|
||||
if touch_updated_at:
|
||||
self.updated_at = time.time()
|
||||
self.path.write_text(
|
||||
json.dumps(self.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding='utf-8',
|
||||
@@ -71,12 +85,15 @@ class Session:
|
||||
|
||||
@classmethod
|
||||
def load(cls, sid):
|
||||
# Validate session ID format to prevent path traversal
|
||||
if not sid or not all(c in '0123456789abcdefghijklmnopqrstuvwxyz_' for c in sid):
|
||||
return None
|
||||
p = SESSION_DIR / f'{sid}.json'
|
||||
if not p.exists():
|
||||
return None
|
||||
return cls(**json.loads(p.read_text(encoding='utf-8')))
|
||||
|
||||
def compact(self):
|
||||
def compact(self) -> dict:
|
||||
return {
|
||||
'session_id': self.session_id,
|
||||
'title': self.title,
|
||||
@@ -92,6 +109,7 @@ class Session:
|
||||
'input_tokens': self.input_tokens,
|
||||
'output_tokens': self.output_tokens,
|
||||
'estimated_cost': self.estimated_cost,
|
||||
'personality': self.personality,
|
||||
}
|
||||
|
||||
def get_session(sid):
|
||||
@@ -145,7 +163,7 @@ def all_sessions():
|
||||
s['profile'] = 'default'
|
||||
return result
|
||||
except Exception:
|
||||
pass # fall through to full scan
|
||||
logger.debug("Failed to load session index, falling back to full scan")
|
||||
# Full scan fallback
|
||||
out = []
|
||||
for p in SESSION_DIR.glob('*.json'):
|
||||
@@ -154,7 +172,7 @@ def all_sessions():
|
||||
s = Session.load(p.stem)
|
||||
if s: out.append(s)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to load session from %s", p)
|
||||
for s in SESSIONS.values():
|
||||
if all(s.session_id != x.session_id for x in out): out.append(s)
|
||||
out.sort(key=lambda s: (getattr(s, 'pinned', False), s.updated_at), reverse=True)
|
||||
@@ -165,7 +183,7 @@ def all_sessions():
|
||||
return result
|
||||
|
||||
|
||||
def title_from(messages, fallback='Untitled'):
|
||||
def title_from(messages, fallback: str='Untitled'):
|
||||
"""Derive a session title from the first user message."""
|
||||
for m in messages:
|
||||
if m.get('role') == 'user':
|
||||
@@ -180,7 +198,7 @@ def title_from(messages, fallback='Untitled'):
|
||||
|
||||
# ── Project helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
def load_projects():
|
||||
def load_projects() -> list:
|
||||
"""Load project list from disk. Returns list of project dicts."""
|
||||
if not PROJECTS_FILE.exists():
|
||||
return []
|
||||
@@ -189,12 +207,20 @@ def load_projects():
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def save_projects(projects):
|
||||
def save_projects(projects) -> None:
|
||||
"""Write project list to disk."""
|
||||
PROJECTS_FILE.write_text(json.dumps(projects, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
|
||||
def import_cli_session(session_id, title, messages, model='unknown', profile=None):
|
||||
def import_cli_session(
|
||||
session_id: str,
|
||||
title: str,
|
||||
messages,
|
||||
model: str='unknown',
|
||||
profile=None,
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
):
|
||||
"""Create a new WebUI session populated with CLI messages.
|
||||
Returns the Session object.
|
||||
"""
|
||||
@@ -205,14 +231,16 @@ def import_cli_session(session_id, title, messages, model='unknown', profile=Non
|
||||
model=model,
|
||||
messages=messages,
|
||||
profile=profile,
|
||||
created_at=created_at,
|
||||
updated_at=updated_at,
|
||||
)
|
||||
s.save()
|
||||
s.save(touch_updated_at=False)
|
||||
return s
|
||||
|
||||
|
||||
# ── CLI session bridge ──────────────────────────────────────────────────────
|
||||
|
||||
def get_cli_sessions():
|
||||
def get_cli_sessions() -> list:
|
||||
"""Read CLI sessions from the agent's SQLite store and return them as
|
||||
dicts in a format the WebUI sidebar can render alongside local sessions.
|
||||
|
||||
@@ -263,6 +291,7 @@ def get_cli_sessions():
|
||||
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
|
||||
@@ -274,11 +303,13 @@ def get_cli_sessions():
|
||||
# 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',
|
||||
'model': row['model'] or None,
|
||||
'message_count': row['message_count'] or 0,
|
||||
'created_at': row['started_at'],
|
||||
'updated_at': raw_ts,
|
||||
@@ -286,7 +317,7 @@ def get_cli_sessions():
|
||||
'archived': False,
|
||||
'project_id': None,
|
||||
'profile': profile,
|
||||
'source_tag': 'cli',
|
||||
'source_tag': _source,
|
||||
'is_cli_session': True,
|
||||
})
|
||||
except Exception:
|
||||
@@ -296,7 +327,7 @@ def get_cli_sessions():
|
||||
return cli_sessions
|
||||
|
||||
|
||||
def get_cli_session_messages(sid):
|
||||
def get_cli_session_messages(sid) -> list:
|
||||
"""Read messages for a single CLI session from the SQLite store.
|
||||
Returns a list of {role, content, timestamp} dicts.
|
||||
Returns empty list on any error.
|
||||
@@ -338,7 +369,7 @@ def get_cli_session_messages(sid):
|
||||
return msgs
|
||||
|
||||
|
||||
def delete_cli_session(sid):
|
||||
def delete_cli_session(sid) -> bool:
|
||||
"""Delete a CLI session from state.db (messages + session row).
|
||||
Returns True if deleted, False if not found or error.
|
||||
"""
|
||||
|
||||
563
api/onboarding.py
Normal file
563
api/onboarding.py
Normal file
@@ -0,0 +1,563 @@
|
||||
"""Hermes Web UI -- first-run onboarding helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
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
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_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
|
||||
|
||||
# For providers not in _SUPPORTED_PROVIDER_SETUPS (e.g. minimax-cn, deepseek,
|
||||
# xai, etc.), ask the hermes_cli auth registry — it knows every provider's env
|
||||
# var names and can check os.environ for a valid key.
|
||||
# Exclude known OAuth/token-flow providers — those are handled separately by
|
||||
# _provider_oauth_authenticated() and should not be short-circuited here.
|
||||
_known_oauth = {"openai-codex", "copilot", "copilot-acp", "qwen-oauth", "nous"}
|
||||
if provider not in _SUPPORTED_PROVIDER_SETUPS and provider not in _known_oauth:
|
||||
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
|
||||
|
||||
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:
|
||||
logger.debug("Failed to get auth status for provider %s", provider)
|
||||
|
||||
# Fallback: parse auth.json ourselves for known OAuth provider IDs.
|
||||
# Covers deployments where hermes_cli is installed but the import above
|
||||
# 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 provider — may be an OAuth flow (openai-codex, copilot, etc.)
|
||||
# OR an API-key provider not in the quick-setup list (minimax-cn, deepseek,
|
||||
# xai, etc.). Check both: api key presence first (covers the majority of
|
||||
# third-party providers), then OAuth auth.json.
|
||||
provider_ready = (
|
||||
_provider_api_key_present(provider, cfg, env_values)
|
||||
or _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",
|
||||
}
|
||||
)
|
||||
|
||||
# Flag whether the currently-configured provider is OAuth-based (not in the
|
||||
# API-key flow). The frontend uses this to show a confirmation card instead
|
||||
# of a key input when the user has already authenticated via 'hermes auth'.
|
||||
current_is_oauth = current_provider not in _SUPPORTED_PROVIDER_SETUPS and bool(
|
||||
current_provider
|
||||
)
|
||||
|
||||
return {
|
||||
"providers": providers,
|
||||
"unsupported_note": _UNSUPPORTED_PROVIDER_NOTE,
|
||||
"current_is_oauth": current_is_oauth,
|
||||
"current": {
|
||||
"provider": current_provider,
|
||||
"model": current_model
|
||||
or _SUPPORTED_PROVIDER_SETUPS.get(current_provider, {}).get(
|
||||
"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()
|
||||
|
||||
# HERMES_WEBUI_SKIP_ONBOARDING=1 lets hosting providers (e.g. Agent37) ship
|
||||
# a pre-configured instance without the wizard blocking the first load.
|
||||
# This is an operator-level override and is honoured unconditionally —
|
||||
# the operator knows their deployment is configured; we must not second-guess
|
||||
# it by requiring chat_ready to also be true.
|
||||
skip_env = os.environ.get("HERMES_WEBUI_SKIP_ONBOARDING", "").strip()
|
||||
skip_requested = skip_env in {"1", "true", "yes"}
|
||||
auto_completed = skip_requested # unconditional: operator says skip, we skip
|
||||
|
||||
# Auto-complete for existing Hermes users: if config.yaml already exists
|
||||
# AND the system is chat_ready, treat onboarding as done. These users
|
||||
# configured Hermes via the CLI before the Web UI existed; they must never
|
||||
# be shown the first-run wizard — it would silently overwrite their config.
|
||||
config_exists = Path(_get_config_path()).exists()
|
||||
config_auto_completed = config_exists and bool(runtime.get("chat_ready"))
|
||||
|
||||
return {
|
||||
"completed": bool(settings.get("onboarding_completed")) or auto_completed or config_auto_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:
|
||||
# Hard guard: if the operator set SKIP_ONBOARDING, the wizard should never
|
||||
# have appeared. Even if the frontend somehow calls this endpoint anyway
|
||||
# (e.g. a stale JS bundle or a curious user), we must not overwrite the
|
||||
# operator's config.yaml or .env files. Just mark onboarding complete and
|
||||
# return the current status — no file writes.
|
||||
skip_env = os.environ.get("HERMES_WEBUI_SKIP_ONBOARDING", "").strip()
|
||||
if skip_env in {"1", "true", "yes"}:
|
||||
save_settings({"onboarding_completed": True})
|
||||
return get_onboarding_status()
|
||||
|
||||
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:
|
||||
# Unsupported providers (openai-codex, copilot, nous, etc.) are already
|
||||
# configured via the CLI. Just mark onboarding as complete and let the
|
||||
# user through — the agent is already set up, no further setup needed.
|
||||
save_settings({"onboarding_completed": True})
|
||||
return get_onboarding_status()
|
||||
if not model:
|
||||
raise ValueError("model is required")
|
||||
|
||||
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://")
|
||||
|
||||
config_path = _get_config_path()
|
||||
# Guard: if config.yaml already exists and the caller did not explicitly
|
||||
# acknowledge the overwrite, refuse to proceed. The frontend must pass
|
||||
# confirm_overwrite=True after showing the user a confirmation step.
|
||||
if Path(config_path).exists() and not body.get("confirm_overwrite"):
|
||||
return {
|
||||
"error": "config_exists",
|
||||
"message": (
|
||||
"Hermes is already configured (config.yaml exists). "
|
||||
"Pass confirm_overwrite=true to overwrite it."
|
||||
),
|
||||
"requires_confirm": True,
|
||||
}
|
||||
|
||||
cfg = _load_yaml_config(config_path)
|
||||
env_path = _get_active_hermes_home() / ".env"
|
||||
env_values = _load_env_file(env_path)
|
||||
|
||||
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(config_path, cfg)
|
||||
|
||||
if api_key:
|
||||
_write_env_file(env_path, {provider_meta["env_var"]: api_key})
|
||||
|
||||
# Reload the hermes_cli provider/config cache so the next streaming call
|
||||
# picks up the new key without requiring a server restart.
|
||||
try:
|
||||
from api.profiles import _reload_dotenv
|
||||
_reload_dotenv(_get_active_hermes_home())
|
||||
except Exception:
|
||||
logger.debug("Failed to reload dotenv")
|
||||
|
||||
# Belt-and-braces: set directly on os.environ AFTER _reload_dotenv so the
|
||||
# value survives even if _reload_dotenv cleared it (e.g. when _write_env_file
|
||||
# wrote to disk but the profile isolation tracking hasn't seen it yet).
|
||||
if api_key:
|
||||
os.environ[provider_meta["env_var"]] = api_key
|
||||
|
||||
try:
|
||||
# hermes_cli may cache config at import time; ask it to reload if possible.
|
||||
from hermes_cli.config import reload as _cli_reload
|
||||
_cli_reload()
|
||||
except Exception:
|
||||
logger.debug("Failed to reload hermes_cli config")
|
||||
|
||||
reload_config()
|
||||
return get_onboarding_status()
|
||||
|
||||
|
||||
def complete_onboarding() -> dict:
|
||||
save_settings({"onboarding_completed": True})
|
||||
return get_onboarding_status()
|
||||
106
api/profiles.py
106
api/profiles.py
@@ -9,12 +9,15 @@ cached paths in hermes-agent modules (skills_tool, cron/jobs) that snapshot
|
||||
HERMES_HOME at import time.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Constants (match hermes_cli.profiles upstream) ─────────────────────────
|
||||
_PROFILE_ID_RE = re.compile(r'^[a-z0-9][a-z0-9_-]{0,63}$')
|
||||
_PROFILE_DIRS = [
|
||||
@@ -26,6 +29,7 @@ _CLONE_CONFIG_FILES = ['config.yaml', '.env', 'SOUL.md']
|
||||
# ── Module state ────────────────────────────────────────────────────────────
|
||||
_active_profile = 'default'
|
||||
_profile_lock = threading.Lock()
|
||||
_loaded_profile_env_keys: set[str] = set()
|
||||
|
||||
def _resolve_base_hermes_home() -> Path:
|
||||
"""Return the BASE ~/.hermes directory — the root that contains profiles/.
|
||||
@@ -75,7 +79,7 @@ def _read_active_profile_file() -> str:
|
||||
if name:
|
||||
return name
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to read active profile file")
|
||||
return 'default'
|
||||
|
||||
|
||||
@@ -106,7 +110,7 @@ def _set_hermes_home(home: Path):
|
||||
_sk.HERMES_HOME = home
|
||||
_sk.SKILLS_DIR = home / 'skills'
|
||||
except (ImportError, AttributeError):
|
||||
pass
|
||||
logger.debug("Failed to patch skills_tool module")
|
||||
|
||||
# Patch cron/jobs module-level cache
|
||||
try:
|
||||
@@ -116,15 +120,28 @@ def _set_hermes_home(home: Path):
|
||||
_cj.JOBS_FILE = _cj.CRON_DIR / 'jobs.json'
|
||||
_cj.OUTPUT_DIR = _cj.CRON_DIR / 'output'
|
||||
except (ImportError, AttributeError):
|
||||
pass
|
||||
logger.debug("Failed to patch cron.jobs module")
|
||||
|
||||
|
||||
def _reload_dotenv(home: Path):
|
||||
"""Load .env from the profile dir into os.environ (additive)."""
|
||||
"""Load .env from the profile dir into os.environ with profile isolation.
|
||||
|
||||
Clears env vars that were loaded from the previously active profile before
|
||||
applying the current profile's .env. This prevents API keys and other
|
||||
profile-scoped secrets from leaking across profile switches.
|
||||
"""
|
||||
global _loaded_profile_env_keys
|
||||
|
||||
# Remove keys loaded from the previous profile first.
|
||||
for key in list(_loaded_profile_env_keys):
|
||||
os.environ.pop(key, None)
|
||||
_loaded_profile_env_keys = set()
|
||||
|
||||
env_path = home / '.env'
|
||||
if not env_path.exists():
|
||||
return
|
||||
try:
|
||||
loaded_keys: set[str] = set()
|
||||
for line in env_path.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#') and '=' in line:
|
||||
@@ -133,11 +150,14 @@ def _reload_dotenv(home: Path):
|
||||
v = v.strip().strip('"').strip("'")
|
||||
if k and v:
|
||||
os.environ[k] = v
|
||||
loaded_keys.add(k)
|
||||
_loaded_profile_env_keys = loaded_keys
|
||||
except Exception:
|
||||
pass
|
||||
_loaded_profile_env_keys = set()
|
||||
logger.debug("Failed to reload dotenv from %s", env_path)
|
||||
|
||||
|
||||
def init_profile_state():
|
||||
def init_profile_state() -> None:
|
||||
"""Initialize profile state at server startup.
|
||||
|
||||
Reads ~/.hermes/active_profile, sets HERMES_HOME env var, patches
|
||||
@@ -176,7 +196,7 @@ def switch_profile(name: str) -> dict:
|
||||
if name == 'default':
|
||||
home = _DEFAULT_HERMES_HOME
|
||||
else:
|
||||
home = _DEFAULT_HERMES_HOME / 'profiles' / name
|
||||
home = _resolve_named_profile_home(name)
|
||||
if not home.is_dir():
|
||||
raise ValueError(f"Profile '{name}' does not exist.")
|
||||
|
||||
@@ -190,7 +210,7 @@ def switch_profile(name: str) -> dict:
|
||||
ap_file = _DEFAULT_HERMES_HOME / 'active_profile'
|
||||
ap_file.write_text(name if name != 'default' else '')
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to write active profile file")
|
||||
|
||||
# Reload config.yaml from the new profile
|
||||
reload_config()
|
||||
@@ -267,6 +287,24 @@ def _validate_profile_name(name: str):
|
||||
)
|
||||
|
||||
|
||||
def _profiles_root() -> Path:
|
||||
"""Return the canonical root that contains named profiles."""
|
||||
return (_DEFAULT_HERMES_HOME / 'profiles').resolve()
|
||||
|
||||
|
||||
def _resolve_named_profile_home(name: str) -> Path:
|
||||
"""Resolve a named profile to a directory under the profiles root.
|
||||
|
||||
Validates *name* as a logical profile identifier first, then resolves the
|
||||
final filesystem path and enforces containment under ~/.hermes/profiles.
|
||||
"""
|
||||
_validate_profile_name(name)
|
||||
profiles_root = _profiles_root()
|
||||
candidate = (profiles_root / name).resolve()
|
||||
candidate.relative_to(profiles_root)
|
||||
return candidate
|
||||
|
||||
|
||||
def _create_profile_fallback(name: str, clone_from: str = None,
|
||||
clone_config: bool = False) -> Path:
|
||||
"""Create a profile directory without hermes_cli (Docker/standalone fallback)."""
|
||||
@@ -294,8 +332,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:
|
||||
logger.debug("Failed to load config from %s", config_path)
|
||||
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 +383,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:
|
||||
logger.debug("Failed to parse profile path")
|
||||
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
|
||||
@@ -340,6 +423,7 @@ def delete_profile_api(name: str) -> dict:
|
||||
"""Delete a profile. Switches to default first if it's the active one."""
|
||||
if name == 'default':
|
||||
raise ValueError("Cannot delete the default profile.")
|
||||
_validate_profile_name(name)
|
||||
|
||||
# If deleting the active profile, switch to default first
|
||||
if _active_profile == name:
|
||||
@@ -357,7 +441,7 @@ def delete_profile_api(name: str) -> dict:
|
||||
except ImportError:
|
||||
# Manual fallback: just remove the directory
|
||||
import shutil
|
||||
profile_dir = _DEFAULT_HERMES_HOME / 'profiles' / name
|
||||
profile_dir = _resolve_named_profile_home(name)
|
||||
if profile_dir.is_dir():
|
||||
shutil.rmtree(str(profile_dir))
|
||||
else:
|
||||
|
||||
2586
api/routes.py
2586
api/routes.py
File diff suppressed because it is too large
Load Diff
74
api/startup.py
Normal file
74
api/startup.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""Hermes Web UI -- startup helpers."""
|
||||
from __future__ import annotations
|
||||
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')]:
|
||||
if not raw:
|
||||
continue
|
||||
p = Path(raw).expanduser()
|
||||
if p.is_dir():
|
||||
return p.resolve()
|
||||
return None
|
||||
|
||||
def auto_install_agent_deps() -> bool:
|
||||
agent_dir = _agent_dir()
|
||||
if agent_dir is None:
|
||||
print('[!!] Auto-install skipped: agent directory not found.', flush=True)
|
||||
return False
|
||||
req_file = agent_dir / 'requirements.txt'
|
||||
pyproject = agent_dir / 'pyproject.toml'
|
||||
if req_file.exists():
|
||||
install_args = [sys.executable, '-m', 'pip', 'install', '--quiet', '-r', str(req_file)]
|
||||
print(f' Installing from {req_file} ...', flush=True)
|
||||
elif pyproject.exists():
|
||||
install_args = [sys.executable, '-m', 'pip', 'install', '--quiet', str(agent_dir)]
|
||||
print(f' Installing from {agent_dir} (pyproject.toml) ...', flush=True)
|
||||
else:
|
||||
print('[!!] Auto-install skipped: no requirements.txt or pyproject.toml in agent dir.', flush=True)
|
||||
return False
|
||||
try:
|
||||
result = subprocess.run(install_args, capture_output=True, text=True, timeout=120)
|
||||
if result.returncode != 0:
|
||||
print(f'[!!] pip install failed (exit {result.returncode}):', flush=True)
|
||||
for line in (result.stderr or '').splitlines()[-10:]:
|
||||
print(f' {line}', flush=True)
|
||||
return False
|
||||
print('[ok] pip install completed.', flush=True)
|
||||
return True
|
||||
except subprocess.TimeoutExpired:
|
||||
print('[!!] Auto-install timed out after 120s.', flush=True)
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f'[!!] Auto-install error: {e}', flush=True)
|
||||
return False
|
||||
118
api/state_sync.py
Normal file
118
api/state_sync.py
Normal file
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
Hermes Web UI -- Optional state.db sync bridge.
|
||||
|
||||
Mirrors WebUI session metadata (token usage, title, model) into the
|
||||
hermes-agent state.db so that /insights, session lists, and cost
|
||||
tracking include WebUI activity.
|
||||
|
||||
This is opt-in via the 'sync_to_insights' setting (default: off).
|
||||
All operations are wrapped in try/except -- if state.db is unavailable,
|
||||
locked, or the schema doesn't match, the WebUI continues normally.
|
||||
|
||||
The bridge uses absolute token counts (not deltas) because the WebUI
|
||||
Session object already accumulates totals across turns. This avoids
|
||||
any double-counting risk.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_state_db():
|
||||
"""Get a SessionDB instance for the active profile's state.db.
|
||||
Returns None if hermes_state is not importable or DB is unavailable.
|
||||
Each caller is responsible for calling db.close() when done.
|
||||
"""
|
||||
try:
|
||||
from hermes_state import SessionDB
|
||||
except ImportError:
|
||||
return None
|
||||
|
||||
try:
|
||||
from api.profiles import get_active_hermes_home
|
||||
hermes_home = Path(get_active_hermes_home()).expanduser().resolve()
|
||||
except Exception:
|
||||
logger.debug("Failed to resolve hermes home, using default")
|
||||
hermes_home = Path(os.getenv('HERMES_HOME', str(Path.home() / '.hermes')))
|
||||
|
||||
db_path = hermes_home / 'state.db'
|
||||
if not db_path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
return SessionDB(db_path)
|
||||
except Exception:
|
||||
logger.debug("Failed to open state.db")
|
||||
return None
|
||||
|
||||
|
||||
def sync_session_start(session_id: str, model=None) -> None:
|
||||
"""Register a WebUI session in state.db (idempotent).
|
||||
Called when a session's first message is sent.
|
||||
"""
|
||||
db = _get_state_db()
|
||||
if not db:
|
||||
return
|
||||
try:
|
||||
db.ensure_session(
|
||||
session_id=session_id,
|
||||
source='webui',
|
||||
model=model,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Failed to sync session start to state.db")
|
||||
finally:
|
||||
try:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("Failed to close state.db")
|
||||
|
||||
|
||||
def sync_session_usage(session_id: str, input_tokens: int=0, output_tokens: int=0,
|
||||
estimated_cost=None, model=None, title: str=None,
|
||||
message_count: int=None) -> None:
|
||||
"""Update token usage and title for a WebUI session in state.db.
|
||||
Called after each turn completes. Uses absolute=True to set totals
|
||||
(the WebUI Session already accumulates across turns).
|
||||
"""
|
||||
db = _get_state_db()
|
||||
if not db:
|
||||
return
|
||||
try:
|
||||
# Ensure session exists first (idempotent)
|
||||
db.ensure_session(session_id=session_id, source='webui', model=model)
|
||||
# Set absolute token counts
|
||||
db.update_token_counts(
|
||||
session_id=session_id,
|
||||
input_tokens=input_tokens,
|
||||
output_tokens=output_tokens,
|
||||
estimated_cost_usd=estimated_cost,
|
||||
model=model,
|
||||
absolute=True,
|
||||
)
|
||||
# Update title if we have one, using the public API
|
||||
if title:
|
||||
try:
|
||||
db.set_session_title(session_id, title)
|
||||
except Exception:
|
||||
logger.debug("Failed to sync session title to state.db")
|
||||
# Update message count
|
||||
if message_count is not None:
|
||||
try:
|
||||
def _set_msg_count(conn):
|
||||
conn.execute(
|
||||
"UPDATE sessions SET message_count = ? WHERE id = ?",
|
||||
(message_count, session_id),
|
||||
)
|
||||
db._execute_write(_set_msg_count)
|
||||
except Exception:
|
||||
logger.debug("Failed to sync message count to state.db")
|
||||
except Exception:
|
||||
logger.debug("Failed to sync session usage to state.db")
|
||||
finally:
|
||||
try:
|
||||
db.close()
|
||||
except Exception:
|
||||
logger.debug("Failed to close state.db")
|
||||
967
api/streaming.py
967
api/streaming.py
File diff suppressed because it is too large
Load Diff
257
api/updates.py
Normal file
257
api/updates.py
Normal file
@@ -0,0 +1,257 @@
|
||||
"""
|
||||
Hermes Web UI -- Self-update checker.
|
||||
|
||||
Checks if the webui and hermes-agent git repos are behind their upstream
|
||||
branches. Results are cached server-side (30-min TTL) so git fetch runs
|
||||
at most twice per hour regardless of client count.
|
||||
|
||||
Skips repos that are not git checkouts (e.g. Docker baked images where
|
||||
.git does not exist).
|
||||
"""
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from api.config import REPO_ROOT
|
||||
|
||||
# Lazy -- may be None if agent not found
|
||||
try:
|
||||
from api.config import _AGENT_DIR
|
||||
except ImportError:
|
||||
_AGENT_DIR = None
|
||||
|
||||
_update_cache = {'webui': None, 'agent': None, 'checked_at': 0}
|
||||
_cache_lock = threading.Lock()
|
||||
_check_in_progress = False
|
||||
_apply_lock = threading.Lock() # prevents concurrent stash/pull/pop on same repo
|
||||
CACHE_TTL = 1800 # 30 minutes
|
||||
|
||||
|
||||
def _run_git(args, cwd, timeout=10):
|
||||
"""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,
|
||||
)
|
||||
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):
|
||||
"""Detect the remote default branch (master or main)."""
|
||||
out, ok = _run_git(['symbolic-ref', 'refs/remotes/origin/HEAD'], path)
|
||||
if ok and out:
|
||||
# refs/remotes/origin/master -> master
|
||||
return out.split('/')[-1]
|
||||
# Fallback: try master, then main
|
||||
for branch in ('master', 'main'):
|
||||
_, ok = _run_git(['rev-parse', '--verify', f'origin/{branch}'], path)
|
||||
if ok:
|
||||
return branch
|
||||
return 'master'
|
||||
|
||||
|
||||
def _check_repo(path, name):
|
||||
"""Check if a git repo is behind its upstream. Returns dict or None."""
|
||||
if path is None or not (path / '.git').exists():
|
||||
return None
|
||||
|
||||
# Fetch latest from origin (network call, cached by TTL)
|
||||
_, fetch_ok = _run_git(['fetch', 'origin', '--quiet'], path, timeout=15)
|
||||
if not fetch_ok:
|
||||
return {'name': name, 'behind': 0, 'error': 'fetch failed'}
|
||||
|
||||
# Use the current branch's upstream tracking branch, not the repo default.
|
||||
# This avoids false "N updates behind" alerts when the user is on a feature
|
||||
# branch and master/main has moved forward with unrelated commits.
|
||||
# If no upstream is set (brand-new local branch), fall back to the default branch.
|
||||
upstream, ok = _run_git(['rev-parse', '--abbrev-ref', '@{upstream}'], path)
|
||||
if ok and upstream:
|
||||
# upstream is like "origin/feat/foo" — use it directly in rev-list
|
||||
compare_ref = upstream
|
||||
else:
|
||||
branch = _detect_default_branch(path)
|
||||
compare_ref = f'origin/{branch}'
|
||||
|
||||
# Count commits behind
|
||||
out, ok = _run_git(['rev-list', '--count', f'HEAD..{compare_ref}'], path)
|
||||
behind = int(out) if ok and out.isdigit() else 0
|
||||
|
||||
# Get short SHAs for display
|
||||
current, _ = _run_git(['rev-parse', '--short', 'HEAD'], path)
|
||||
latest, _ = _run_git(['rev-parse', '--short', compare_ref], path)
|
||||
|
||||
return {
|
||||
'name': name,
|
||||
'behind': behind,
|
||||
'current_sha': current,
|
||||
'latest_sha': latest,
|
||||
'branch': compare_ref,
|
||||
}
|
||||
|
||||
|
||||
def check_for_updates(force=False):
|
||||
"""Return cached update status for webui and agent repos."""
|
||||
global _check_in_progress
|
||||
with _cache_lock:
|
||||
if not force and time.time() - _update_cache['checked_at'] < CACHE_TTL:
|
||||
return dict(_update_cache)
|
||||
if _check_in_progress:
|
||||
return dict(_update_cache) # another thread is already checking
|
||||
_check_in_progress = True
|
||||
|
||||
try:
|
||||
# Run checks outside the lock (network I/O)
|
||||
webui_info = _check_repo(REPO_ROOT, 'webui')
|
||||
agent_info = _check_repo(_AGENT_DIR, 'agent')
|
||||
|
||||
with _cache_lock:
|
||||
_update_cache['webui'] = webui_info
|
||||
_update_cache['agent'] = agent_info
|
||||
_update_cache['checked_at'] = time.time()
|
||||
return dict(_update_cache)
|
||||
finally:
|
||||
_check_in_progress = False
|
||||
|
||||
|
||||
def apply_update(target):
|
||||
"""Stash, pull --ff-only, pop for the given target repo."""
|
||||
if not _apply_lock.acquire(blocking=False):
|
||||
return {'ok': False, 'message': 'Update already in progress'}
|
||||
try:
|
||||
return _apply_update_inner(target)
|
||||
finally:
|
||||
_apply_lock.release()
|
||||
|
||||
|
||||
def _apply_update_inner(target):
|
||||
"""Inner implementation of apply_update, called under _apply_lock."""
|
||||
if target == 'webui':
|
||||
path = REPO_ROOT
|
||||
elif target == 'agent':
|
||||
path = _AGENT_DIR
|
||||
else:
|
||||
return {'ok': False, 'message': f'Unknown target: {target}'}
|
||||
|
||||
if path is None or not (path / '.git').exists():
|
||||
return {'ok': False, 'message': 'Not a git repository'}
|
||||
|
||||
# Use the current branch's upstream for pull, matching the behaviour
|
||||
# of _check_repo. Falls back to default branch if no upstream is set.
|
||||
upstream, ok = _run_git(['rev-parse', '--abbrev-ref', '@{upstream}'], path)
|
||||
if ok and upstream:
|
||||
compare_ref = upstream
|
||||
else:
|
||||
branch = _detect_default_branch(path)
|
||||
compare_ref = f'origin/{branch}'
|
||||
|
||||
# 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)
|
||||
if not ok:
|
||||
return {'ok': False, 'message': 'Failed to stash local changes'}
|
||||
stashed = True
|
||||
|
||||
# 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)
|
||||
|
||||
# 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:
|
||||
_, pop_ok = _run_git(['stash', 'pop'], path)
|
||||
if not pop_ok:
|
||||
return {
|
||||
'ok': False,
|
||||
'message': 'Updated but stash pop failed -- manual merge needed',
|
||||
'stash_conflict': True,
|
||||
}
|
||||
|
||||
# Invalidate cache
|
||||
with _cache_lock:
|
||||
_update_cache['checked_at'] = 0
|
||||
|
||||
return {'ok': True, 'message': f'{target} updated successfully', 'target': target}
|
||||
@@ -3,6 +3,7 @@ Hermes Web UI -- File upload: multipart parser and upload handler.
|
||||
"""
|
||||
import re as _re
|
||||
import email.parser
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from api.config import MAX_UPLOAD_BYTES
|
||||
@@ -11,7 +12,7 @@ from api.models import get_session
|
||||
from api.workspace import safe_resolve_ws
|
||||
|
||||
|
||||
def parse_multipart(rfile, content_type, content_length):
|
||||
def parse_multipart(rfile, content_type, content_length) -> tuple:
|
||||
import re as _re, email.parser as _ep
|
||||
m = _re.search(r'boundary=([^;\s]+)', content_type)
|
||||
if not m:
|
||||
@@ -50,8 +51,15 @@ def parse_multipart(rfile, content_type, content_length):
|
||||
return fields, files
|
||||
|
||||
|
||||
def _sanitize_upload_name(filename: str) -> str:
|
||||
safe_name = _re.sub(r'[^\w.\-]', '_', Path(filename).name)[:200]
|
||||
if not safe_name or safe_name.strip('.') == '':
|
||||
raise ValueError('Invalid filename')
|
||||
return safe_name
|
||||
|
||||
|
||||
def handle_upload(handler):
|
||||
import re as _re, traceback as _tb
|
||||
import traceback as _tb
|
||||
try:
|
||||
content_type = handler.headers.get('Content-Type', '')
|
||||
content_length = int(handler.headers.get('Content-Length', 0) or 0)
|
||||
@@ -69,10 +77,55 @@ def handle_upload(handler):
|
||||
except KeyError:
|
||||
return j(handler, {'error': 'Session not found'}, status=404)
|
||||
workspace = Path(s.workspace)
|
||||
safe_name = _re.sub(r'[^\w.\-]', '_', Path(filename).name)[:200]
|
||||
dest = workspace / safe_name
|
||||
safe_name = _sanitize_upload_name(filename)
|
||||
dest = safe_resolve_ws(workspace, safe_name)
|
||||
dest.write_bytes(file_bytes)
|
||||
return j(handler, {'filename': safe_name, 'path': str(dest), 'size': dest.stat().st_size})
|
||||
except Exception as e:
|
||||
except ValueError as e:
|
||||
return j(handler, {'error': str(e)}, status=400)
|
||||
except Exception:
|
||||
print('[webui] upload error: ' + _tb.format_exc(), flush=True)
|
||||
return j(handler, {'error': 'Upload failed'}, status=500)
|
||||
|
||||
|
||||
def handle_transcribe(handler):
|
||||
import traceback as _tb
|
||||
temp_path = None
|
||||
try:
|
||||
content_type = handler.headers.get('Content-Type', '')
|
||||
content_length = int(handler.headers.get('Content-Length', 0) or 0)
|
||||
if content_length > MAX_UPLOAD_BYTES:
|
||||
return j(handler, {'error': f'File too large (max {MAX_UPLOAD_BYTES//1024//1024}MB)'}, status=413)
|
||||
fields, files = parse_multipart(handler.rfile, content_type, content_length)
|
||||
if 'file' not in files:
|
||||
return j(handler, {'error': 'No file field in request'}, status=400)
|
||||
filename, file_bytes = files['file']
|
||||
if not filename:
|
||||
return j(handler, {'error': 'No filename in upload'}, status=400)
|
||||
safe_name = _sanitize_upload_name(filename)
|
||||
suffix = Path(safe_name).suffix or '.webm'
|
||||
with tempfile.NamedTemporaryFile(prefix='webui-stt-', suffix=suffix, delete=False) as tmp:
|
||||
temp_path = tmp.name
|
||||
tmp.write(file_bytes)
|
||||
try:
|
||||
from tools.transcription_tools import transcribe_audio
|
||||
except ImportError:
|
||||
return j(handler, {'error': 'Speech-to-text is unavailable on this server'}, status=503)
|
||||
result = transcribe_audio(temp_path)
|
||||
if not result.get('success'):
|
||||
msg = str(result.get('error') or 'Transcription failed')
|
||||
status = 503 if 'unavailable' in msg.lower() or 'not configured' in msg.lower() else 400
|
||||
return j(handler, {'error': msg}, status=status)
|
||||
transcript = str(result.get('transcript') or '').strip()
|
||||
return j(handler, {'ok': True, 'transcript': transcript})
|
||||
except ValueError as e:
|
||||
return j(handler, {'error': str(e)}, status=400)
|
||||
except Exception:
|
||||
print('[webui] transcribe error: ' + _tb.format_exc(), flush=True)
|
||||
return j(handler, {'error': 'Transcription failed'}, status=500)
|
||||
finally:
|
||||
if temp_path:
|
||||
try:
|
||||
Path(temp_path).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
112
api/workspace.py
112
api/workspace.py
@@ -8,10 +8,13 @@ profile has its own workspace configuration. State files live at
|
||||
paths are used as fallback when no profile module is available.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from api.config import (
|
||||
WORKSPACES_FILE as _GLOBAL_WS_FILE,
|
||||
LAST_WORKSPACE_FILE as _GLOBAL_LW_FILE,
|
||||
@@ -37,7 +40,7 @@ def _profile_state_dir() -> Path:
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
except ImportError:
|
||||
pass
|
||||
logger.debug("Failed to import profiles module, using global state dir")
|
||||
return _GLOBAL_WS_FILE.parent
|
||||
|
||||
|
||||
@@ -80,7 +83,7 @@ def _profile_default_workspace() -> str:
|
||||
if p.is_dir():
|
||||
return str(p)
|
||||
except (ImportError, Exception):
|
||||
pass
|
||||
logger.debug("Failed to load profile default workspace config")
|
||||
return str(_BOOT_DEFAULT_WORKSPACE)
|
||||
|
||||
|
||||
@@ -89,7 +92,6 @@ def _profile_default_workspace() -> str:
|
||||
def _clean_workspace_list(workspaces: list) -> list:
|
||||
"""Sanitize a workspace list:
|
||||
- Remove entries whose paths no longer exist on disk.
|
||||
- Remove entries that look like test artifacts (webui-mvp-test, test-workspace).
|
||||
- Remove entries whose paths live inside another profile's directory
|
||||
(e.g. ~/.hermes/profiles/X/... should not appear on a different profile).
|
||||
- Rename any entry whose name is literally 'default' to 'Home' (avoids
|
||||
@@ -102,18 +104,24 @@ def _clean_workspace_list(workspaces: list) -> list:
|
||||
path = w.get('path', '')
|
||||
name = w.get('name', '')
|
||||
p = Path(path).resolve() if path else Path('/')
|
||||
# Skip test artifacts
|
||||
if 'test-workspace' in path or 'webui-mvp-test' in path:
|
||||
continue
|
||||
# Skip paths that no longer exist
|
||||
if not p.is_dir():
|
||||
continue
|
||||
# Skip paths inside a named profile's directory (cross-profile leak)
|
||||
# Skip paths inside a DIFFERENT profile's directory (cross-profile leak).
|
||||
# Allow paths inside the CURRENT profile's own directory (e.g. test workspaces
|
||||
# created under ~/.hermes/profiles/webui/webui-mvp-test/).
|
||||
try:
|
||||
p.relative_to(hermes_profiles)
|
||||
continue # it IS under profiles/ — remove it
|
||||
# p is under ~/.hermes/profiles/ — only skip if it's under a DIFFERENT profile
|
||||
try:
|
||||
from api.profiles import get_active_hermes_home
|
||||
own_profile_dir = get_active_hermes_home().resolve()
|
||||
p.relative_to(own_profile_dir)
|
||||
# p is under our own profile dir — keep it
|
||||
except (ValueError, Exception):
|
||||
continue # under profiles/ but not our own — cross-profile leak, skip
|
||||
except ValueError:
|
||||
pass
|
||||
pass # not under profiles/ at all — keep it
|
||||
# Rename confusing 'default' label to 'Home'
|
||||
if name.lower() == 'default':
|
||||
name = 'Home'
|
||||
@@ -156,10 +164,10 @@ def load_workspaces() -> list:
|
||||
json.dumps(cleaned, ensure_ascii=False, indent=2), encoding='utf-8'
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to persist cleaned workspace list")
|
||||
return cleaned or [{'path': _profile_default_workspace(), 'name': 'Home'}]
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to load workspaces from %s", ws_file)
|
||||
# No profile-local file yet.
|
||||
# For the DEFAULT profile: migrate from the legacy global file (one-time cleanup).
|
||||
# For NAMED profiles: always start clean with just their own workspace.
|
||||
@@ -176,7 +184,7 @@ def load_workspaces() -> list:
|
||||
return [{'path': _profile_default_workspace(), 'name': 'Home'}]
|
||||
|
||||
|
||||
def save_workspaces(workspaces: list):
|
||||
def save_workspaces(workspaces: list) -> None:
|
||||
ws_file = _workspaces_file()
|
||||
ws_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
ws_file.write_text(json.dumps(workspaces, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
@@ -190,7 +198,7 @@ def get_last_workspace() -> str:
|
||||
if p and Path(p).is_dir():
|
||||
return p
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to read last workspace from %s", lw_file)
|
||||
# Fallback: try global file
|
||||
if _GLOBAL_LW_FILE.exists():
|
||||
try:
|
||||
@@ -198,18 +206,88 @@ def get_last_workspace() -> str:
|
||||
if p and Path(p).is_dir():
|
||||
return p
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("Failed to read global last workspace")
|
||||
return _profile_default_workspace()
|
||||
|
||||
|
||||
def set_last_workspace(path: str):
|
||||
def set_last_workspace(path: str) -> None:
|
||||
try:
|
||||
lw_file = _last_workspace_file()
|
||||
lw_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
lw_file.write_text(str(path), encoding='utf-8')
|
||||
except Exception:
|
||||
logger.debug("Failed to set last workspace")
|
||||
|
||||
|
||||
def resolve_trusted_workspace(path: str | Path | None = None) -> Path:
|
||||
"""Resolve and validate a workspace path.
|
||||
|
||||
A path is trusted if it satisfies at least one of:
|
||||
(A) It is under the user's home directory (Path.home()).
|
||||
Works cross-platform: ~/... on Linux/macOS, C:\\Users\\... on Windows.
|
||||
(B) It is already in the profile's saved workspace list.
|
||||
This covers self-hosted deployments where workspaces live outside home
|
||||
(e.g. /data/projects, /opt/workspace) — once a workspace is saved by
|
||||
an admin, it can be reused without re-validation.
|
||||
|
||||
Additionally enforced regardless of (A)/(B):
|
||||
1. The path must exist.
|
||||
2. The path must be a directory.
|
||||
3. The path must not be a known system root (/etc, /usr, /var, /bin, /sbin,
|
||||
/boot, /proc, /sys, /dev, /root on Linux/macOS; Windows system dirs).
|
||||
This prevents even admin-saved workspaces from pointing at OS internals.
|
||||
|
||||
None/empty path falls back to the boot-time DEFAULT_WORKSPACE, which is always
|
||||
trusted (it was validated at server startup).
|
||||
"""
|
||||
_BLOCKED_SYSTEM_ROOTS = {
|
||||
# Linux / macOS
|
||||
Path('/etc'), Path('/usr'), Path('/var'), Path('/bin'), Path('/sbin'),
|
||||
Path('/boot'), Path('/proc'), Path('/sys'), Path('/dev'),
|
||||
Path('/lib'), Path('/lib64'), Path('/opt/homebrew'),
|
||||
}
|
||||
|
||||
if path in (None, ""):
|
||||
return Path(_BOOT_DEFAULT_WORKSPACE).expanduser().resolve()
|
||||
|
||||
candidate = Path(path).expanduser().resolve()
|
||||
|
||||
if not candidate.exists():
|
||||
raise ValueError(f"Path does not exist: {candidate}")
|
||||
if not candidate.is_dir():
|
||||
raise ValueError(f"Path is not a directory: {candidate}")
|
||||
|
||||
# Block known system roots and their children
|
||||
for blocked in _BLOCKED_SYSTEM_ROOTS:
|
||||
try:
|
||||
candidate.relative_to(blocked)
|
||||
raise ValueError(f"Path points to a system directory: {candidate}")
|
||||
except ValueError as e:
|
||||
if "system directory" in str(e):
|
||||
raise
|
||||
# relative_to raised ValueError = candidate is NOT under blocked = safe
|
||||
|
||||
# (A) Trusted if under the user's home directory — cross-platform via Path.home()
|
||||
try:
|
||||
candidate.relative_to(Path.home().resolve())
|
||||
return candidate
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# (B) Trusted if already in the saved workspace list — covers non-home installs
|
||||
try:
|
||||
saved = load_workspaces()
|
||||
saved_paths = {Path(w["path"]).resolve() for w in saved if w.get("path")}
|
||||
if candidate in saved_paths:
|
||||
return candidate
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raise ValueError(
|
||||
f"Path is outside the user home directory and not in the saved workspace "
|
||||
f"list: {candidate}. Add it via Settings → Workspaces first."
|
||||
)
|
||||
|
||||
|
||||
def safe_resolve_ws(root: Path, requested: str) -> Path:
|
||||
"""Resolve a relative path inside a workspace root, raising ValueError on traversal."""
|
||||
@@ -218,7 +296,7 @@ def safe_resolve_ws(root: Path, requested: str) -> Path:
|
||||
return resolved
|
||||
|
||||
|
||||
def list_dir(workspace: Path, rel='.'):
|
||||
def list_dir(workspace: Path, rel: str='.'):
|
||||
target = safe_resolve_ws(workspace, rel)
|
||||
if not target.is_dir():
|
||||
raise FileNotFoundError(f"Not a directory: {rel}")
|
||||
@@ -235,7 +313,7 @@ def list_dir(workspace: Path, rel='.'):
|
||||
return entries
|
||||
|
||||
|
||||
def read_file_content(workspace: Path, rel: str):
|
||||
def read_file_content(workspace: Path, rel: str) -> dict:
|
||||
target = safe_resolve_ws(workspace, rel)
|
||||
if not target.is_file():
|
||||
raise FileNotFoundError(f"Not a file: {rel}")
|
||||
|
||||
232
bootstrap.py
Normal file
232
bootstrap.py
Normal file
@@ -0,0 +1,232 @@
|
||||
#!/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"))
|
||||
# Set HERMES_WEBUI_SKIP_ONBOARDING=1 to bypass the first-run wizard when
|
||||
# the environment is already fully configured (e.g. managed hosting).
|
||||
|
||||
|
||||
def info(msg: str) -> None:
|
||||
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
|
||||
# Validate URL scheme to prevent file:// and other dangerous schemes
|
||||
if not url.startswith(("http://", "https://")):
|
||||
raise ValueError(f"Invalid health check URL: {url}")
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=2) as response: # nosec B310
|
||||
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)
|
||||
58
docker-compose.two-container.yml
Normal file
58
docker-compose.two-container.yml
Normal file
@@ -0,0 +1,58 @@
|
||||
# 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
|
||||
# Workspace directory — browse and edit files from the WebUI.
|
||||
# Adapt the host path to your project directory.
|
||||
- ~/workspace:/workspace
|
||||
environment:
|
||||
- HERMES_WEBUI_HOST=0.0.0.0
|
||||
- HERMES_WEBUI_PORT=8787
|
||||
- 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,34 @@ 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
|
||||
# Mount hermes home for agent features and profile management
|
||||
- ${HERMES_HOME:-${HOME}/.hermes}:/root/.hermes
|
||||
# Mount your Hermes home directory into the container.
|
||||
# The default (${HOME}/.hermes) works on both macOS (/Users/<you>/.hermes)
|
||||
# and Linux (/home/<you>/.hermes) — no change needed for standard installs.
|
||||
# Only set HERMES_HOME explicitly if your .hermes lives somewhere non-standard.
|
||||
# macOS note: set UID and GID below to match your user ID (run `id -u` and `id -g`).
|
||||
- ${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:
|
||||
# Set to your host user ID: run `id -u` and `id -g` to find them.
|
||||
# On macOS, UIDs start at 501 (not 1000), so set UID and GID in a .env file:
|
||||
# echo "UID=$(id -u)" >> .env
|
||||
# echo "GID=$(id -g)" >> .env
|
||||
# Without this, the container may not be able to read your mounted files.
|
||||
- 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:
|
||||
|
||||
280
docker_init.bash
Normal file
280
docker_init.bash
Normal file
@@ -0,0 +1,280 @@
|
||||
#!/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
|
||||
# Auto-detect from mounted workspace if still unset (#569).
|
||||
# On macOS, host UIDs start at 501. Using the wrong UID means the container
|
||||
# user cannot read the bind-mounted files, making the workspace appear empty.
|
||||
# Prefer the workspace mount UID over the hardcoded default of 1024.
|
||||
if [ -z "${WANTED_UID+x}" ] || [ "${WANTED_UID}" = "1024" ]; then
|
||||
# Use /workspace — the standard bind-mount point — to read the host UID.
|
||||
if [ -d "/workspace" ]; then
|
||||
_detected_uid=$(stat -c '%u' "/workspace" 2>/dev/null || echo "")
|
||||
if [ -n "$_detected_uid" ] && [ "$_detected_uid" != "0" ]; then
|
||||
echo "-- Auto-detected workspace UID: $_detected_uid (from /workspace)"
|
||||
WANTED_UID=$_detected_uid
|
||||
fi
|
||||
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
|
||||
# Auto-detect GID from mounted workspace to match (#569)
|
||||
if [ -z "${WANTED_GID+x}" ] || [ "${WANTED_GID}" = "1024" ]; then
|
||||
if [ -d "/workspace" ]; then
|
||||
_detected_gid=$(stat -c '%g' "/workspace" 2>/dev/null || echo "")
|
||||
if [ -n "$_detected_gid" ] && [ "$_detected_gid" != "0" ]; then
|
||||
echo "-- Auto-detected workspace GID: $_detected_gid (from /workspace)"
|
||||
WANTED_GID=$_detected_gid
|
||||
fi
|
||||
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"
|
||||
# Use sudo for mkdir/chown — Docker may auto-create bind-mount directories as root,
|
||||
# leaving them unwritable by the hermeswebui user (#357).
|
||||
sudo mkdir -p "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit "Failed to create default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
sudo chown hermeswebui:hermeswebui "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit "Failed to set owner of $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
if [ ! -d "$HERMES_WEBUI_DEFAULT_WORKSPACE" ]; then error_exit "HERMES_WEBUI_DEFAULT_WORKSPACE directory does not exist at $HERMES_WEBUI_DEFAULT_WORKSPACE"; fi
|
||||
it="$HERMES_WEBUI_DEFAULT_WORKSPACE/.testfile"; touch $it || error_exit "Failed to verify default workspace at $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
rm -f $it || error_exit "Failed to delete test file in $HERMES_WEBUI_DEFAULT_WORKSPACE"
|
||||
|
||||
echo ""; echo "==================="
|
||||
echo ""; echo "== Installing uv and creating a new virtual environment for hermes-webui"
|
||||
|
||||
export PATH="/home/hermeswebui/.local/bin/:$PATH"
|
||||
if command -v uv &>/dev/null; then
|
||||
echo "-- uv already installed ($(uv --version)), skipping download"
|
||||
else
|
||||
echo "-- uv not found, downloading..."
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh || error_exit "Failed to install uv — check network connectivity"
|
||||
fi
|
||||
export UV_PROJECT_ENVIRONMENT=venv
|
||||
|
||||
export UV_CACHE_DIR=/uv_cache
|
||||
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
|
||||
if [ -f /app/venv/bin/python3 ]; then
|
||||
echo ""; echo "== Existing virtual environment found — reusing (fast restart)"
|
||||
else
|
||||
echo ""; echo "== Creating new virtual environment"
|
||||
uv venv venv
|
||||
fi
|
||||
export VIRTUAL_ENV=/app/venv
|
||||
test -d /app/venv
|
||||
test -f /app/venv/bin/activate
|
||||
|
||||
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
|
||||
|
||||
if [ -f /app/venv/.deps_installed ]; then
|
||||
echo ""; echo "== Dependencies already installed — skipping (fast restart)"
|
||||
else
|
||||
echo ""; echo "== Installing hermes-webui dependencies"
|
||||
uv pip install -r requirements.txt --trusted-host pypi.org --trusted-host files.pythonhosted.org
|
||||
uv pip install -U pip setuptools --trusted-host pypi.org --trusted-host files.pythonhosted.org
|
||||
test -x /app/venv/bin/pip
|
||||
|
||||
echo ""; echo "== Adding hermes-agent's pyproject.toml base dependencies to the virtual environment"
|
||||
if [ -d "/home/hermeswebui/.hermes/hermes-agent" ] && [ -f "/home/hermeswebui/.hermes/hermes-agent/pyproject.toml" ]; then
|
||||
uv pip install "/home/hermeswebui/.hermes/hermes-agent[honcho]" --trusted-host pypi.org --trusted-host files.pythonhosted.org || error_exit "Failed to install hermes-agent's requirements"
|
||||
else
|
||||
echo ""
|
||||
echo "!! WARNING: hermes-agent source not found at /home/hermeswebui/.hermes/hermes-agent"
|
||||
echo "!! The WebUI will start with reduced functionality (no model auto-detection,"
|
||||
echo "!! no personality routing, no CLI session imports)."
|
||||
echo "!! To fix: mount the agent source volume into the container. See:"
|
||||
echo "!! https://github.com/nesquena/hermes-webui/blob/master/docker-compose.two-container.yml"
|
||||
echo ""
|
||||
fi
|
||||
touch /app/venv/.deps_installed
|
||||
fi
|
||||
|
||||
echo ""; echo "== Running hermes-webui"
|
||||
cd /app; python server.py || error_exit "hermes-webui failed or exited with an error"
|
||||
|
||||
# we should never be here because the server should be running indefinitely, but if we are, we exit safely
|
||||
ok_exit "Clean exit"
|
||||
120
server.py
120
server.py
@@ -3,22 +3,51 @@ Hermes Web UI -- Main server entry point.
|
||||
Thin routing shell: imports Handler, delegates to api/routes.py, runs server.
|
||||
All business logic lives in api/*.
|
||||
"""
|
||||
import logging
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from api.auth import check_auth
|
||||
from api.config import HOST, PORT, STATE_DIR, SESSION_DIR, DEFAULT_WORKSPACE
|
||||
from api.helpers import j
|
||||
from api.routes import handle_get, handle_post
|
||||
from api.startup import auto_install_agent_deps, fix_credential_permissions
|
||||
|
||||
|
||||
class QuietHTTPServer(ThreadingHTTPServer):
|
||||
"""Custom HTTP server that silently handles common network errors."""
|
||||
|
||||
def handle_error(self, request, client_address):
|
||||
"""Override to suppress logging for common client disconnect errors."""
|
||||
exc_type, exc_value, _ = sys.exc_info()
|
||||
|
||||
# Silently ignore common connection errors caused by client disconnects
|
||||
if exc_type in (ConnectionResetError, BrokenPipeError, ConnectionAbortedError):
|
||||
return
|
||||
|
||||
# Also handle socket errors that indicate client disconnect
|
||||
if exc_type is socket.error:
|
||||
# errno 54 is Connection reset by peer on macOS/BSD
|
||||
# errno 104 is Connection reset by peer on Linux
|
||||
if exc_value.errno in (54, 104, 32): # ECONNRESET, EPIPE
|
||||
return
|
||||
|
||||
# For other errors, use default logging
|
||||
super().handle_error(request, client_address)
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = 'HermesWebUI/0.2'
|
||||
timeout = 30 # seconds — kills idle/incomplete connections to prevent thread exhaustion
|
||||
server_version = 'HermesWebUI/0.50.38'
|
||||
def log_message(self, fmt, *args): pass # suppress default Apache-style log
|
||||
|
||||
def log_request(self, code='-', size='-'):
|
||||
def log_request(self, code: str='-', size: str='-') -> None:
|
||||
"""Structured JSON logs for each request."""
|
||||
import json as _json
|
||||
duration_ms = round((time.time() - getattr(self, '_req_t0', time.time())) * 1000, 1)
|
||||
@@ -31,7 +60,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
})
|
||||
print(f'[webui] {record}', flush=True)
|
||||
|
||||
def do_GET(self):
|
||||
def do_GET(self) -> None:
|
||||
self._req_t0 = time.time()
|
||||
try:
|
||||
parsed = urlparse(self.path)
|
||||
@@ -43,7 +72,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||
print(f'[webui] ERROR {self.command} {self.path}\n' + traceback.format_exc(), flush=True)
|
||||
return j(self, {'error': 'Internal server error'}, status=500)
|
||||
|
||||
def do_POST(self):
|
||||
def do_POST(self) -> None:
|
||||
self._req_t0 = time.time()
|
||||
try:
|
||||
parsed = urlparse(self.path)
|
||||
@@ -56,28 +85,97 @@ class Handler(BaseHTTPRequestHandler):
|
||||
return j(self, {'error': 'Internal server error'}, status=500)
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
from api.config import print_startup_config, verify_hermes_imports, _HERMES_FOUND
|
||||
|
||||
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():
|
||||
print(f'[!!] WARNING: Binding to {HOST} with NO PASSWORD SET.', flush=True)
|
||||
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:
|
||||
print(f'[!!] Warning: Hermes agent found but missing modules: {missing}', flush=True)
|
||||
for mod, err in errors.items():
|
||||
print(f' {mod}: {err}', flush=True)
|
||||
print(' Agent features may not work correctly.', flush=True)
|
||||
print(' Attempting to install missing dependencies from agent requirements.txt...', flush=True)
|
||||
auto_install_agent_deps()
|
||||
ok, missing, errors = verify_hermes_imports()
|
||||
if not ok:
|
||||
print(f'[!!] Still missing after install attempt: {missing}', flush=True)
|
||||
for mod, err in errors.items():
|
||||
print(f' {mod}: {err}', flush=True)
|
||||
print(' Agent features may not work correctly.', flush=True)
|
||||
else:
|
||||
print('[ok] Agent dependencies installed successfully.', flush=True)
|
||||
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
||||
DEFAULT_WORKSPACE.mkdir(parents=True, exist_ok=True)
|
||||
httpd = ThreadingHTTPServer((HOST, PORT), Handler)
|
||||
print(f' Hermes Web UI listening on http://{HOST}:{PORT}', flush=True)
|
||||
if HOST == '127.0.0.1':
|
||||
|
||||
# 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 = QuietHTTPServer((HOST, PORT), Handler)
|
||||
|
||||
# ── TLS/HTTPS setup (optional) ─────────────────────────────────────────
|
||||
from api.config import TLS_ENABLED, TLS_CERT, TLS_KEY
|
||||
scheme = 'https' if TLS_ENABLED else 'http'
|
||||
if TLS_ENABLED:
|
||||
try:
|
||||
import ssl
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ctx.load_cert_chain(TLS_CERT, TLS_KEY)
|
||||
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
|
||||
print(f' TLS enabled: cert={TLS_CERT}, key={TLS_KEY}', flush=True)
|
||||
except Exception as e:
|
||||
print(f'[!!] WARNING: TLS setup failed ({e}), falling back to HTTP', flush=True)
|
||||
scheme = 'http'
|
||||
|
||||
print(f' Hermes Web UI listening on {scheme}://{HOST}:{PORT}', flush=True)
|
||||
if HOST == '127.0.0.1' 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: http://localhost:{PORT}', 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:
|
||||
logger.debug("Failed to stop gateway watcher during shutdown")
|
||||
|
||||
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 "$@"
|
||||
|
||||
525
static/boot.js
525
static/boot.js
@@ -2,13 +2,129 @@ async function cancelStream(){
|
||||
const streamId = S.activeStreamId;
|
||||
if(!streamId) return;
|
||||
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('Cancelling…');
|
||||
}catch(e){setStatus('Cancel failed: '+e.message);}
|
||||
await fetch(new URL(`api/chat/cancel?stream_id=${encodeURIComponent(streamId)}`,location.href).href,{credentials:'include'});
|
||||
}catch(e){/* cancel request failed — cleanup below still runs */}
|
||||
// Clear status unconditionally after the cancel request completes.
|
||||
// The SSE cancel event may also fire, but if the connection is already
|
||||
// closed it won't arrive — so we handle cleanup here as the guaranteed path.
|
||||
const btn=$('btnCancel');if(btn)btn.style.display='none';
|
||||
S.activeStreamId=null;
|
||||
setBusy(false);
|
||||
if(typeof setComposerStatus==='function') setComposerStatus('');
|
||||
else setStatus('');
|
||||
}
|
||||
|
||||
// ── Mobile navigation ──────────────────────────────────────────────────────
|
||||
let _workspacePanelMode='closed'; // 'closed' | 'browse' | 'preview'
|
||||
|
||||
function _isCompactWorkspaceViewport(){
|
||||
return window.matchMedia('(max-width: 900px)').matches;
|
||||
}
|
||||
|
||||
function _workspacePanelEls(){
|
||||
return {
|
||||
layout: document.querySelector('.layout'),
|
||||
panel: document.querySelector('.rightpanel'),
|
||||
toggleBtn: $('btnWorkspacePanelToggle'),
|
||||
collapseBtn: $('btnCollapseWorkspacePanel'),
|
||||
};
|
||||
}
|
||||
|
||||
function _hasWorkspacePreviewVisible(){
|
||||
const preview=$('previewArea');
|
||||
return !!(preview&&preview.classList.contains('visible'));
|
||||
}
|
||||
|
||||
function _setWorkspacePanelMode(mode){
|
||||
const {layout,panel}= _workspacePanelEls();
|
||||
if(!layout||!panel)return;
|
||||
_workspacePanelMode=(mode==='browse'||mode==='preview')?mode:'closed';
|
||||
const open=_workspacePanelMode!=='closed';
|
||||
// Persist open/closed across refreshes (browse/preview → open; closed → closed)
|
||||
localStorage.setItem('hermes-webui-workspace-panel', open ? 'open' : 'closed');
|
||||
layout.classList.toggle('workspace-panel-collapsed',!open);
|
||||
if(_isCompactWorkspaceViewport()){
|
||||
panel.classList.toggle('mobile-open',open);
|
||||
}else{
|
||||
panel.classList.remove('mobile-open');
|
||||
}
|
||||
syncWorkspacePanelUI();
|
||||
}
|
||||
|
||||
function syncWorkspacePanelState(){
|
||||
const hasPreview=_hasWorkspacePreviewVisible();
|
||||
if(hasPreview){
|
||||
if(_workspacePanelMode==='closed') _setWorkspacePanelMode('preview');
|
||||
else syncWorkspacePanelUI();
|
||||
return;
|
||||
}
|
||||
if(!S.session){
|
||||
_setWorkspacePanelMode('closed');
|
||||
return;
|
||||
}
|
||||
_setWorkspacePanelMode(_workspacePanelMode==='preview'?'closed':_workspacePanelMode);
|
||||
}
|
||||
|
||||
function openWorkspacePanel(mode='browse'){
|
||||
if(mode==='browse'&&!S.session&&!_hasWorkspacePreviewVisible())return;
|
||||
if(mode==='preview'&&_workspacePanelMode==='browse'){
|
||||
syncWorkspacePanelUI();
|
||||
return;
|
||||
}
|
||||
_setWorkspacePanelMode(mode);
|
||||
}
|
||||
|
||||
function closeWorkspacePanel(){
|
||||
_setWorkspacePanelMode('closed');
|
||||
}
|
||||
|
||||
function ensureWorkspacePreviewVisible(){
|
||||
if(_workspacePanelMode==='closed') _setWorkspacePanelMode('preview');
|
||||
else syncWorkspacePanelUI();
|
||||
}
|
||||
|
||||
function handleWorkspaceClose(){
|
||||
if(_hasWorkspacePreviewVisible()){
|
||||
clearPreview();
|
||||
return;
|
||||
}
|
||||
closeWorkspacePanel();
|
||||
}
|
||||
|
||||
function syncWorkspacePanelUI(){
|
||||
const {layout,panel,toggleBtn,collapseBtn}= _workspacePanelEls();
|
||||
if(!layout||!panel)return;
|
||||
const desktopOpen=_workspacePanelMode!=='closed';
|
||||
const mobileOpen=panel.classList.contains('mobile-open');
|
||||
const isCompact=_isCompactWorkspaceViewport();
|
||||
const isOpen=isCompact?mobileOpen:desktopOpen;
|
||||
const canBrowse=!!S.session||_hasWorkspacePreviewVisible();
|
||||
const hasPreview=_hasWorkspacePreviewVisible();
|
||||
if(toggleBtn){
|
||||
toggleBtn.classList.toggle('active',isOpen);
|
||||
toggleBtn.setAttribute('aria-pressed',isOpen?'true':'false');
|
||||
toggleBtn.title=isOpen?'Hide workspace panel':'Show workspace panel';
|
||||
toggleBtn.disabled=!canBrowse;
|
||||
}
|
||||
if(collapseBtn){
|
||||
collapseBtn.title=isCompact?'Close workspace panel':'Hide workspace panel';
|
||||
}
|
||||
const hasSession=!!S.session;
|
||||
['btnUpDir','btnNewFile','btnNewFolder','btnRefreshPanel'].forEach(id=>{
|
||||
const el=$(id);
|
||||
if(el)el.disabled=!hasSession;
|
||||
});
|
||||
const clearBtn=$('btnClearPreview');
|
||||
if(clearBtn){
|
||||
clearBtn.disabled=!isOpen;
|
||||
clearBtn.title=hasPreview?'Close preview':'Hide workspace panel';
|
||||
// On desktop, only show the X button when a file preview is open.
|
||||
// In browse mode the chevron (btnCollapseWorkspacePanel) already serves
|
||||
// as the close control, so showing both produces a duplicate X.
|
||||
if(!isCompact) clearBtn.style.display=hasPreview?'':'none';
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMobileSidebar(){
|
||||
const sidebar=document.querySelector('.sidebar');
|
||||
const overlay=$('mobileOverlay');
|
||||
@@ -24,16 +140,22 @@ function closeMobileSidebar(){
|
||||
if(overlay)overlay.classList.remove('visible');
|
||||
}
|
||||
function toggleMobileFiles(){
|
||||
const panel=document.querySelector('.rightpanel');
|
||||
toggleWorkspacePanel();
|
||||
}
|
||||
function toggleWorkspacePanel(force){
|
||||
const {panel}= _workspacePanelEls();
|
||||
if(!panel)return;
|
||||
panel.classList.toggle('mobile-open');
|
||||
const currentlyOpen=_workspacePanelMode!=='closed';
|
||||
const nextOpen=typeof force==='boolean'?force:!currentlyOpen;
|
||||
if(!nextOpen){
|
||||
closeWorkspacePanel();
|
||||
return;
|
||||
}
|
||||
const nextMode=_hasWorkspacePreviewVisible()?'preview':'browse';
|
||||
openWorkspacePanel(nextMode);
|
||||
}
|
||||
function mobileSwitchPanel(name){
|
||||
// Switch the panel content view
|
||||
switchPanel(name);
|
||||
// For non-chat panels (tasks, skills, memory, spaces), open the sidebar
|
||||
// so the panel is visible. For 'chat', the content is in the main area —
|
||||
// just close the sidebar so the chat view is unobstructed.
|
||||
if(name==='chat'){
|
||||
closeMobileSidebar();
|
||||
} else {
|
||||
@@ -44,30 +166,34 @@ function mobileSwitchPanel(name){
|
||||
if(overlay)overlay.classList.add('visible');
|
||||
}
|
||||
}
|
||||
// Update bottom nav active state
|
||||
document.querySelectorAll('.mobile-nav-btn').forEach(btn=>{
|
||||
btn.classList.toggle('active',btn.dataset.panel===name);
|
||||
});
|
||||
}
|
||||
|
||||
$('btnSend').onclick=()=>{if(window._micActive)_stopMic();send();};
|
||||
$('btnSend').onclick=()=>{
|
||||
if(window._micActive){
|
||||
window._micPendingSend=true;
|
||||
_stopMic();
|
||||
return;
|
||||
}
|
||||
send();
|
||||
};
|
||||
$('btnAttach').onclick=()=>$('fileInput').click();
|
||||
|
||||
// ── Voice input (Web Speech API) ─────────────────────────────────────────
|
||||
// ── Voice input (Web Speech API + MediaRecorder fallback) ───────────────────
|
||||
(function(){
|
||||
const SpeechRecognition=window.SpeechRecognition||window.webkitSpeechRecognition;
|
||||
if(!SpeechRecognition) return; // Browser unsupported — mic button stays hidden
|
||||
const _canRecordAudio=!!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia&&window.MediaRecorder);
|
||||
if(!SpeechRecognition&&!_canRecordAudio) return; // Browser unsupported — mic button stays hidden
|
||||
|
||||
const btn=$('btnMic');
|
||||
const status=$('micStatus');
|
||||
const ta=$('msg');
|
||||
btn.style.display=''; // Show button — browser supports speech
|
||||
|
||||
const recognition=new SpeechRecognition();
|
||||
recognition.continuous=false;
|
||||
recognition.interimResults=true;
|
||||
recognition.lang='en-US';
|
||||
const statusText=status?status.querySelector('.status-text'):null;
|
||||
btn.style.display=''; // Show button — browser supports speech recognition or recording fallback
|
||||
|
||||
let recognition=SpeechRecognition?new SpeechRecognition():null;
|
||||
let mediaRecorder=null;
|
||||
let mediaStream=null;
|
||||
let audioChunks=[];
|
||||
let _finalText='';
|
||||
let _prefix='';
|
||||
|
||||
@@ -75,67 +201,162 @@ $('btnAttach').onclick=()=>$('fileInput').click();
|
||||
window._micActive=on;
|
||||
btn.classList.toggle('recording',on);
|
||||
status.style.display=on?'':'none';
|
||||
if(statusText) statusText.textContent=on?'Listening':'Listening';
|
||||
if(!on){ _finalText=''; _prefix=''; }
|
||||
}
|
||||
|
||||
recognition.onstart=()=>{ _finalText=''; };
|
||||
|
||||
recognition.onresult=(event)=>{
|
||||
let interim='';
|
||||
let final=_finalText;
|
||||
for(let i=event.resultIndex;i<event.results.length;i++){
|
||||
const t=event.results[i][0].transcript;
|
||||
if(event.results[i].isFinal){ final+=t; _finalText=final; }
|
||||
else{ interim+=t; }
|
||||
}
|
||||
// Append to whatever was already in the textarea before mic started
|
||||
ta.value=_prefix+(final||interim);
|
||||
autoResize();
|
||||
};
|
||||
|
||||
recognition.onend=()=>{
|
||||
// Commit: prefix + final transcription; trim trailing space if prefix was non-empty
|
||||
const committed=_finalText
|
||||
function _commitTranscript(text){
|
||||
const clean=(text||'').trim();
|
||||
const committed=clean
|
||||
? (_prefix&&!_prefix.endsWith(' ')&&!_prefix.endsWith('\n')
|
||||
? _prefix+' '+_finalText.trimStart()
|
||||
: _prefix+_finalText)
|
||||
: ta.value; // no speech detected — leave whatever is there
|
||||
_setRecording(false);
|
||||
? _prefix+' '+clean.trimStart()
|
||||
: _prefix+clean)
|
||||
: ta.value;
|
||||
ta.value=committed;
|
||||
autoResize();
|
||||
};
|
||||
if(window._micPendingSend){
|
||||
window._micPendingSend=false;
|
||||
send();
|
||||
}
|
||||
}
|
||||
|
||||
recognition.onerror=(event)=>{
|
||||
_setRecording(false);
|
||||
const msgs={
|
||||
'not-allowed':'Microphone access denied. Check browser permissions.',
|
||||
'no-speech':'No speech detected. Try again.',
|
||||
'network':'Speech recognition unavailable.',
|
||||
};
|
||||
showToast(msgs[event.error]||'Voice input error: '+event.error);
|
||||
};
|
||||
async function _transcribeBlob(blob){
|
||||
const ext=(blob.type&&blob.type.includes('ogg'))?'ogg':'webm';
|
||||
const form=new FormData();
|
||||
form.append('file',new File([blob],`voice-input.${ext}`,{type:blob.type||`audio/${ext}`}));
|
||||
setComposerStatus('Transcribing…');
|
||||
try{
|
||||
const res=await fetch('api/transcribe',{method:'POST',body:form});
|
||||
const data=await res.json().catch(()=>({}));
|
||||
if(!res.ok) throw new Error(data.error||'Transcription failed');
|
||||
_commitTranscript(data.transcript||'');
|
||||
}catch(err){
|
||||
window._micPendingSend=false;
|
||||
showToast(err.message||t('mic_network'));
|
||||
}finally{
|
||||
setComposerStatus('');
|
||||
}
|
||||
}
|
||||
|
||||
function _stopTracks(){
|
||||
if(mediaStream){
|
||||
mediaStream.getTracks().forEach(track=>track.stop());
|
||||
mediaStream=null;
|
||||
}
|
||||
}
|
||||
|
||||
function _stopMic(){
|
||||
if(window._micActive){ recognition.stop(); }
|
||||
if(!window._micActive) return;
|
||||
if(recognition){
|
||||
recognition.stop();
|
||||
return;
|
||||
}
|
||||
if(mediaRecorder&&mediaRecorder.state!=='inactive'){
|
||||
mediaRecorder.stop();
|
||||
return;
|
||||
}
|
||||
_setRecording(false);
|
||||
_stopTracks();
|
||||
}
|
||||
window._stopMic=_stopMic; // expose for send-guard above
|
||||
|
||||
btn.onclick=()=>{
|
||||
if(recognition){
|
||||
recognition.continuous=false;
|
||||
recognition.interimResults=true;
|
||||
recognition.lang=(typeof _locale!=='undefined'&&_locale._speech)||'en-US';
|
||||
|
||||
recognition.onstart=()=>{ _finalText=''; };
|
||||
|
||||
recognition.onresult=(event)=>{
|
||||
let interim='';
|
||||
let final=_finalText;
|
||||
for(let i=event.resultIndex;i<event.results.length;i++){
|
||||
const t=event.results[i][0].transcript;
|
||||
if(event.results[i].isFinal){ final+=t; _finalText=final; }
|
||||
else{ interim+=t; }
|
||||
}
|
||||
ta.value=_prefix+(final||interim);
|
||||
autoResize();
|
||||
};
|
||||
|
||||
recognition.onend=()=>{
|
||||
const committed=_finalText
|
||||
? (_prefix&&!_prefix.endsWith(' ')&&!_prefix.endsWith('\n')
|
||||
? _prefix+' '+_finalText.trimStart()
|
||||
: _prefix+_finalText)
|
||||
: ta.value;
|
||||
_setRecording(false);
|
||||
ta.value=committed;
|
||||
autoResize();
|
||||
if(window._micPendingSend){
|
||||
window._micPendingSend=false;
|
||||
send();
|
||||
}
|
||||
};
|
||||
|
||||
recognition.onerror=(event)=>{
|
||||
_setRecording(false);
|
||||
window._micPendingSend=false;
|
||||
const msgs={
|
||||
'not-allowed':t('mic_denied'),
|
||||
'no-speech':t('mic_no_speech'),
|
||||
'network':t('mic_network'),
|
||||
};
|
||||
showToast(msgs[event.error]||t('mic_error')+event.error);
|
||||
};
|
||||
}
|
||||
|
||||
btn.onclick=async()=>{
|
||||
if(window._micActive){
|
||||
recognition.stop();
|
||||
// _setRecording(false) will be called by onend
|
||||
} else {
|
||||
_finalText='';
|
||||
// Snapshot existing textarea content so we append rather than replace
|
||||
_prefix=ta.value;
|
||||
_stopMic();
|
||||
return;
|
||||
}
|
||||
_finalText='';
|
||||
_prefix=ta.value;
|
||||
if(recognition){
|
||||
recognition.start();
|
||||
_setRecording(true);
|
||||
return;
|
||||
}
|
||||
if(!_canRecordAudio){
|
||||
showToast(t('mic_network'));
|
||||
return;
|
||||
}
|
||||
try{
|
||||
mediaStream=await navigator.mediaDevices.getUserMedia({audio:true});
|
||||
const preferredTypes=['audio/webm;codecs=opus','audio/webm','audio/ogg;codecs=opus','audio/ogg'];
|
||||
const mimeType=preferredTypes.find(type=>window.MediaRecorder.isTypeSupported?.(type))||'';
|
||||
mediaRecorder=new MediaRecorder(mediaStream,mimeType?{mimeType}:undefined);
|
||||
audioChunks=[];
|
||||
mediaRecorder.ondataavailable=e=>{if(e.data&&e.data.size)audioChunks.push(e.data);};
|
||||
mediaRecorder.onerror=()=>{
|
||||
_setRecording(false);
|
||||
window._micPendingSend=false;
|
||||
_stopTracks();
|
||||
showToast(t('mic_network'));
|
||||
};
|
||||
mediaRecorder.onstop=async()=>{
|
||||
const blob=new Blob(audioChunks,{type:mediaRecorder.mimeType||mimeType||'audio/webm'});
|
||||
_setRecording(false);
|
||||
_stopTracks();
|
||||
if(blob.size){ await _transcribeBlob(blob); }
|
||||
else if(window._micPendingSend){
|
||||
window._micPendingSend=false;
|
||||
}
|
||||
};
|
||||
mediaRecorder.start();
|
||||
_setRecording(true);
|
||||
}catch(err){
|
||||
window._micPendingSend=false;
|
||||
_stopTracks();
|
||||
showToast(t('mic_denied'));
|
||||
}
|
||||
};
|
||||
})();
|
||||
window._micActive=window._micActive||false;
|
||||
window._micPendingSend=window._micPendingSend||false;
|
||||
$('fileInput').onchange=e=>{addFiles(Array.from(e.target.files));e.target.value='';};
|
||||
$('btnNewChat').onclick=async()=>{await newSession();await renderSessionList();$('msg').focus();};
|
||||
$('btnNewChat').onclick=async()=>{await newSession();await renderSessionList();closeMobileSidebar();$('msg').focus();};
|
||||
$('btnDownload').onclick=()=>{
|
||||
if(!S.session)return;
|
||||
const blob=new Blob([transcript()],{type:'text/markdown'});
|
||||
@@ -160,14 +381,17 @@ $('importFileInput').onchange=async(e)=>{
|
||||
if(res.ok&&res.session){
|
||||
await loadSession(res.session.session_id);
|
||||
await renderSessionList();
|
||||
showToast('Session imported');
|
||||
const overlay=$('settingsOverlay');
|
||||
if(overlay) overlay.style.display='none';
|
||||
showToast(t('session_imported'));
|
||||
}
|
||||
}catch(err){
|
||||
showToast('Import failed: '+(err.message||'Invalid JSON'));
|
||||
showToast(t('import_failed')+(err.message||t('import_invalid_json')));
|
||||
}
|
||||
};
|
||||
// btnRefreshFiles is now panel-icon-btn in header (see HTML)
|
||||
function clearPreview(){
|
||||
const closePanelAfter=_workspacePanelMode==='preview';
|
||||
const pa=$('previewArea');if(pa)pa.classList.remove('visible');
|
||||
const pi=$('previewImg');if(pi){pi.onerror=null;pi.src='';}
|
||||
const pm=$('previewMd');if(pm)pm.innerHTML='';
|
||||
@@ -175,15 +399,31 @@ function clearPreview(){
|
||||
const pp=$('previewPathText');if(pp)pp.textContent='';
|
||||
const ft=$('fileTree');if(ft)ft.style.display='';
|
||||
_previewCurrentPath='';_previewCurrentMode='';_previewDirty=false;
|
||||
// Restore directory breadcrumb after closing file preview
|
||||
if(typeof renderBreadcrumb==='function') renderBreadcrumb();
|
||||
if(closePanelAfter)closeWorkspacePanel();
|
||||
else syncWorkspacePanelUI();
|
||||
}
|
||||
$('btnClearPreview').onclick=clearPreview;
|
||||
$('btnClearPreview').onclick=handleWorkspaceClose;
|
||||
// workspacePath click handler removed -- use topbar workspace chip dropdown instead
|
||||
$('modelSelect').onchange=async()=>{
|
||||
if(!S.session)return;
|
||||
const selectedModel=$('modelSelect').value;
|
||||
if(typeof closeModelDropdown==='function') closeModelDropdown();
|
||||
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();
|
||||
S.session.model=selectedModel;
|
||||
if(typeof syncModelChip==='function') syncModelChip();
|
||||
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);
|
||||
}
|
||||
// Notify user that model changes only take effect in the next conversation (#419)
|
||||
if(S.messages && S.messages.length > 0 && typeof showToast==='function'){
|
||||
showToast('Model change takes effect in your next conversation', 3000);
|
||||
}
|
||||
};
|
||||
$('msg').addEventListener('input',()=>{
|
||||
autoResize();
|
||||
@@ -206,11 +446,22 @@ $('msg').addEventListener('keydown',e=>{
|
||||
if(e.key==='ArrowDown'){e.preventDefault();navigateCmdDropdown(1);return;}
|
||||
if(e.key==='Tab'){e.preventDefault();selectCmdDropdownItem();return;}
|
||||
if(e.key==='Escape'){e.preventDefault();hideCmdDropdown();return;}
|
||||
if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();selectCmdDropdownItem();return;}
|
||||
if(e.key==='Enter'&&!e.shiftKey){
|
||||
if(e.isComposing){return;}
|
||||
e.preventDefault();
|
||||
selectCmdDropdownItem();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Send key: respect user preference
|
||||
// Send key: respect user preference.
|
||||
// On touch-primary devices (software keyboard), default to Enter = newline
|
||||
// since there's no physical Shift key. Users send via the Send button.
|
||||
// The 'ctrl+enter' setting also uses this behavior (Enter = newline).
|
||||
// Users can override in Settings by explicitly choosing 'enter' mode.
|
||||
if(e.key==='Enter'){
|
||||
if(window._sendKey==='ctrl+enter'){
|
||||
if(e.isComposing){return;}
|
||||
const _mobileDefault=matchMedia('(pointer:coarse)').matches&&window._sendKey==='enter';
|
||||
if(window._sendKey==='ctrl+enter'||_mobileDefault){
|
||||
if(e.ctrlKey||e.metaKey){e.preventDefault();send();}
|
||||
} else {
|
||||
if(!e.shiftKey){e.preventDefault();send();}
|
||||
@@ -219,14 +470,31 @@ $('msg').addEventListener('keydown',e=>{
|
||||
});
|
||||
// B14: Cmd/Ctrl+K creates a new chat from anywhere
|
||||
document.addEventListener('keydown',async e=>{
|
||||
// Enter on approval card = Allow once (when a button inside the card is focused or
|
||||
// card is visible and focus is not on an input/textarea/select)
|
||||
if(e.key==='Enter'&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey){
|
||||
const card=$('approvalCard');
|
||||
const tag=(document.activeElement||{}).tagName||'';
|
||||
if(card&&card.classList.contains('visible')&&tag!=='TEXTAREA'&&tag!=='INPUT'&&tag!=='SELECT'){
|
||||
e.preventDefault();
|
||||
if(typeof respondApproval==='function') respondApproval('once');
|
||||
return;
|
||||
}
|
||||
}
|
||||
if((e.metaKey||e.ctrlKey)&&e.key==='k'){
|
||||
e.preventDefault();
|
||||
if(!S.busy){await newSession();await renderSessionList();$('msg').focus();}
|
||||
if(!S.busy){await newSession();await renderSessionList();closeMobileSidebar();$('msg').focus();}
|
||||
}
|
||||
if(e.key==='Escape'){
|
||||
// Close onboarding overlay if open (skip/dismiss the wizard)
|
||||
const onboardingOverlay=$('onboardingOverlay');
|
||||
if(onboardingOverlay&&onboardingOverlay.style.display!=='none'){
|
||||
if(typeof skipOnboarding==='function') skipOnboarding();
|
||||
return;
|
||||
}
|
||||
// Close settings overlay if open
|
||||
const settingsOverlay=$('settingsOverlay');
|
||||
if(settingsOverlay&&settingsOverlay.style.display!=='none'){toggleSettings();return;}
|
||||
if(settingsOverlay&&settingsOverlay.style.display!=='none'){_closeSettingsPanel();return;}
|
||||
// Close workspace dropdown
|
||||
closeWsDropdown();
|
||||
// Clear session search
|
||||
@@ -251,17 +519,21 @@ $('msg').addEventListener('paste',e=>{
|
||||
return new File([blob],`screenshot-${Date.now()}.${ext}`,{type:i.type});
|
||||
});
|
||||
addFiles(files);
|
||||
setStatus(`Image pasted: ${files.map(f=>f.name).join(', ')}`);
|
||||
setStatus(t('image_pasted')+files.map(f=>f.name).join(', '));
|
||||
});
|
||||
document.querySelectorAll('.suggestion').forEach(btn=>{
|
||||
btn.onclick=()=>{$('msg').value=btn.dataset.msg;send();};
|
||||
});
|
||||
|
||||
window.addEventListener('resize',()=>{
|
||||
syncWorkspacePanelState();
|
||||
});
|
||||
|
||||
// Boot: restore last session or start fresh
|
||||
// ── Resizable panels ──────────────────────────────────────────────────────
|
||||
(function(){
|
||||
const SIDEBAR_MIN=180, SIDEBAR_MAX=420;
|
||||
const PANEL_MIN=180, PANEL_MAX=500;
|
||||
const PANEL_MIN=180, PANEL_MAX=1200;
|
||||
|
||||
function initResize(handleId, targetEl, edge, minW, maxW, storageKey){
|
||||
const handle = $(handleId);
|
||||
@@ -306,9 +578,93 @@ document.querySelectorAll('.suggestion').forEach(btn=>{
|
||||
};
|
||||
})();
|
||||
|
||||
// ── System theme helper ──────────────────────────────────────────────────────
|
||||
function _applyTheme(name){
|
||||
const resolved=(name==='system')
|
||||
?(window.matchMedia('(prefers-color-scheme:dark)').matches?'dark':'light')
|
||||
:name;
|
||||
document.documentElement.dataset.theme=resolved||'dark';
|
||||
// Swap Prism syntax-highlighting theme to match UI theme
|
||||
(function(){
|
||||
const link=document.getElementById('prism-theme');
|
||||
if(!link) return;
|
||||
const isDark=(resolved!=='light');
|
||||
const want=isDark
|
||||
?'https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css'
|
||||
:'https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism.min.css';
|
||||
if(link.href!==want){ link.href=want; }
|
||||
})();
|
||||
// Re-register OS change listener whenever system theme is active
|
||||
if(name==='system'){
|
||||
const mq=window.matchMedia('(prefers-color-scheme:dark)');
|
||||
const _onOsChange=()=>{ document.documentElement.dataset.theme=mq.matches?'dark':'light'; };
|
||||
mq.removeEventListener('change',_onOsChange);
|
||||
mq.addEventListener('change',_onOsChange);
|
||||
}
|
||||
}
|
||||
|
||||
function applyBotName(){
|
||||
const name=window._botName||'Hermes';
|
||||
document.title=name;
|
||||
const sidebarH1=document.querySelector('.sidebar-header h1');
|
||||
if(sidebarH1) sidebarH1.textContent=name;
|
||||
const logo=document.querySelector('.sidebar-header .logo');
|
||||
if(logo) logo.textContent=name.charAt(0).toUpperCase();
|
||||
const topbarTitle=$('topbarTitle');
|
||||
if(topbarTitle && (!S.session)) topbarTitle.textContent=name;
|
||||
const msg=$('msg');
|
||||
if(msg) msg.placeholder='Message '+name+'\u2026';
|
||||
}
|
||||
|
||||
(async()=>{
|
||||
// Load send key preference
|
||||
try{const s=await api('/api/settings');window._sendKey=s.send_key||'enter';window._showTokenUsage=!!s.show_token_usage;window._showCliSessions=!!s.show_cli_sessions;}catch(e){window._sendKey='enter';window._showTokenUsage=false;window._showCliSessions=false;}
|
||||
let _bootSettings={};
|
||||
try{
|
||||
const s=await api('/api/settings');
|
||||
_bootSettings=s;
|
||||
window._sendKey=s.send_key||'enter';
|
||||
window._showTokenUsage=!!s.show_token_usage;
|
||||
window._showCliSessions=!!s.show_cli_sessions;
|
||||
window._soundEnabled=!!s.sound_enabled;
|
||||
window._notificationsEnabled=!!s.notifications_enabled;
|
||||
window._botName=s.bot_name||'Hermes';
|
||||
const _theme=s.theme||'dark';
|
||||
localStorage.setItem('hermes-theme',_theme);
|
||||
_applyTheme(_theme);
|
||||
document.body.classList.toggle('bubble-layout',!!s.bubble_layout);
|
||||
if(typeof setLocale==='function'){
|
||||
const _lang=typeof resolvePreferredLocale==='function'
|
||||
? resolvePreferredLocale(s.language, localStorage.getItem('hermes-lang'))
|
||||
: (s.language || localStorage.getItem('hermes-lang') || 'en');
|
||||
setLocale(_lang);
|
||||
if(typeof applyLocaleToDOM==='function')applyLocaleToDOM();
|
||||
}
|
||||
applyBotName();
|
||||
}catch(e){
|
||||
window._sendKey='enter';
|
||||
window._showTokenUsage=false;
|
||||
window._showCliSessions=false;
|
||||
window._soundEnabled=false;
|
||||
window._notificationsEnabled=false;
|
||||
window._botName='Hermes';
|
||||
_bootSettings={check_for_updates:false};
|
||||
document.body.classList.remove('bubble-layout');
|
||||
if(typeof setLocale==='function'){
|
||||
const _lang=typeof resolvePreferredLocale==='function'
|
||||
? resolvePreferredLocale(null, localStorage.getItem('hermes-lang'))
|
||||
: (localStorage.getItem('hermes-lang') || 'en');
|
||||
setLocale(_lang);
|
||||
if(typeof applyLocaleToDOM==='function')applyLocaleToDOM();
|
||||
}
|
||||
applyBotName();
|
||||
}
|
||||
// Non-blocking update check (fire-and-forget, once per tab session)
|
||||
// ?test_updates=1 in URL forces banner display for testing (bypasses sessionStorage guards)
|
||||
const _testUpdates=new URLSearchParams(location.search).get('test_updates')==='1';
|
||||
if(_testUpdates||(_bootSettings.check_for_updates!==false&&!sessionStorage.getItem('hermes-update-checked')&&!sessionStorage.getItem('hermes-update-dismissed'))){
|
||||
const _checkUrl='/api/updates/check'+(_testUpdates?'?simulate=1':'');
|
||||
api(_checkUrl).then(d=>{if(!_testUpdates)sessionStorage.setItem('hermes-update-checked','1');if((d.webui&&d.webui.behind>0)||(d.agent&&d.agent.behind>0))_showUpdateBanner(d);}).catch(()=>{});
|
||||
}
|
||||
// Fetch active profile
|
||||
try{const p=await api('/api/profile/active');S.activeProfile=p.name||'default';}catch(e){S.activeProfile='default';}
|
||||
// Update profile chip label immediately
|
||||
@@ -325,14 +681,27 @@ document.querySelectorAll('.suggestion').forEach(btn=>{
|
||||
}
|
||||
// Pre-load workspace list so sidebar name is correct from first render
|
||||
await loadWorkspaceList();
|
||||
await loadOnboardingWizard();
|
||||
_initResizePanels();
|
||||
// Workspace panel restore happens AFTER loadSession so we know if
|
||||
// the session has a workspace — prevents the snap-open-then-closed flash (#576).
|
||||
const saved=localStorage.getItem('hermes-webui-session');
|
||||
if(saved){
|
||||
try{await loadSession(saved);await renderSessionList();await checkInflightOnBoot(saved);return;}
|
||||
try{
|
||||
await loadSession(saved);
|
||||
// Only restore the panel from localStorage when the session actually has a workspace.
|
||||
// Without this guard, sessions without a workspace snap open then immediately closed.
|
||||
if(S.session&&S.session.workspace&&localStorage.getItem('hermes-webui-workspace-panel')==='open'){
|
||||
_workspacePanelMode='browse';
|
||||
}
|
||||
syncWorkspacePanelState();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 +
|
||||
syncTopbar();
|
||||
syncWorkspacePanelState();
|
||||
$('emptyState').style.display='';
|
||||
await renderSessionList();
|
||||
// Start real-time gateway session sync if setting is enabled
|
||||
if(typeof startGatewaySSE==='function') startGatewaySSE();
|
||||
})();
|
||||
|
||||
|
||||
@@ -3,13 +3,16 @@
|
||||
// (no round-trip to the agent) and shows feedback via toast or local message.
|
||||
|
||||
const COMMANDS=[
|
||||
{name:'help', desc:'List available commands', fn:cmdHelp},
|
||||
{name:'clear', desc:'Clear conversation messages', fn:cmdClear},
|
||||
{name:'compact', desc:'Compress conversation context', fn:cmdCompact},
|
||||
{name:'model', desc:'Switch model (e.g. /model gpt-4o)', fn:cmdModel, arg:'model_name'},
|
||||
{name:'workspace', desc:'Switch workspace by name', fn:cmdWorkspace, arg:'name'},
|
||||
{name:'new', desc:'Start a new chat session', fn:cmdNew},
|
||||
{name:'usage', desc:'Toggle token usage display on/off', fn:cmdUsage},
|
||||
{name:'help', desc:t('cmd_help'), fn:cmdHelp},
|
||||
{name:'clear', desc:t('cmd_clear'), fn:cmdClear},
|
||||
{name:'compact', desc:t('cmd_compact'), fn:cmdCompact},
|
||||
{name:'model', desc:t('cmd_model'), fn:cmdModel, arg:'model_name'},
|
||||
{name:'workspace', desc:t('cmd_workspace'), fn:cmdWorkspace, arg:'name'},
|
||||
{name:'new', desc:t('cmd_new'), fn:cmdNew},
|
||||
{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){
|
||||
@@ -41,10 +44,10 @@ function cmdHelp(){
|
||||
const usage=c.arg?` <${c.arg}>`:'';
|
||||
return ` /${c.name}${usage} — ${c.desc}`;
|
||||
});
|
||||
const msg={role:'assistant',content:'**Available commands:**\n'+lines.join('\n')};
|
||||
const msg={role:'assistant',content:t('available_commands')+'\n'+lines.join('\n')};
|
||||
S.messages.push(msg);
|
||||
renderMessages();
|
||||
showToast('Type / to see commands');
|
||||
showToast(t('type_slash'));
|
||||
}
|
||||
|
||||
function cmdClear(){
|
||||
@@ -53,11 +56,11 @@ function cmdClear(){
|
||||
clearLiveToolCards();
|
||||
renderMessages();
|
||||
$('emptyState').style.display='';
|
||||
showToast('Conversation cleared');
|
||||
showToast(t('conversation_cleared'));
|
||||
}
|
||||
|
||||
async function cmdModel(args){
|
||||
if(!args){showToast('Usage: /model <name>');return;}
|
||||
if(!args){showToast(t('model_usage'));return;}
|
||||
const sel=$('modelSelect');
|
||||
if(!sel)return;
|
||||
const q=args.toLowerCase();
|
||||
@@ -68,36 +71,31 @@ async function cmdModel(args){
|
||||
match=opt.value;break;
|
||||
}
|
||||
}
|
||||
if(!match){showToast(`No model matching "${args}"`);return;}
|
||||
if(!match){showToast(t('no_model_match')+`"${args}"`);return;}
|
||||
sel.value=match;
|
||||
await sel.onchange();
|
||||
showToast(`Switched to ${match}`);
|
||||
showToast(t('switched_to')+match);
|
||||
}
|
||||
|
||||
async function cmdWorkspace(args){
|
||||
if(!args){showToast('Usage: /workspace <name>');return;}
|
||||
if(!args){showToast(t('workspace_usage'));return;}
|
||||
try{
|
||||
const data=await api('/api/workspaces');
|
||||
const q=args.toLowerCase();
|
||||
const ws=(data.workspaces||[]).find(w=>
|
||||
(w.name||'').toLowerCase().includes(q)||w.path.toLowerCase().includes(q)
|
||||
);
|
||||
if(!ws){showToast(`No workspace matching "${args}"`);return;}
|
||||
if(!S.session)return;
|
||||
await api('/api/session/update',{method:'POST',body:JSON.stringify({
|
||||
session_id:S.session.session_id,workspace:ws.path,model:S.session.model
|
||||
})});
|
||||
S.session.workspace=ws.path;
|
||||
syncTopbar();await loadDir('.');
|
||||
showToast(`Switched to workspace: ${ws.name||ws.path}`);
|
||||
}catch(e){showToast('Workspace switch failed: '+e.message);}
|
||||
if(!ws){showToast(t('no_workspace_match')+`"${args}"`);return;}
|
||||
if(typeof switchToWorkspace==='function') await switchToWorkspace(ws.path, ws.name||ws.path);
|
||||
else showToast(t('switched_workspace')+(ws.name||ws.path));
|
||||
}catch(e){showToast(t('workspace_switch_failed')+e.message);}
|
||||
}
|
||||
|
||||
async function cmdNew(){
|
||||
await newSession();
|
||||
await renderSessionList();
|
||||
$('msg').focus();
|
||||
showToast('New session created');
|
||||
showToast(t('new_session'));
|
||||
}
|
||||
|
||||
function cmdCompact(){
|
||||
@@ -106,7 +104,7 @@ function cmdCompact(){
|
||||
// We send a user message so it appears in the conversation.
|
||||
$('msg').value='Please compress and summarize the conversation context to free up space.';
|
||||
send();
|
||||
showToast('Requesting context compression...');
|
||||
showToast(t('compressing'));
|
||||
}
|
||||
|
||||
async function cmdUsage(){
|
||||
@@ -119,7 +117,96 @@ async function cmdUsage(){
|
||||
const cb=$('settingsShowTokenUsage');
|
||||
if(cb) cb.checked=next;
|
||||
renderMessages();
|
||||
showToast('Token usage '+(next?'on':'off'));
|
||||
showToast(next?t('token_usage_on'):t('token_usage_off'));
|
||||
}
|
||||
|
||||
async function cmdTheme(args){
|
||||
const themes=['system','dark','light','slate','solarized','monokai','nord','oled'];
|
||||
if(!args||!themes.includes(args.toLowerCase())){
|
||||
showToast(t('theme_usage')+themes.join('|'));
|
||||
return;
|
||||
}
|
||||
const themeName=args.toLowerCase();
|
||||
localStorage.setItem('hermes-theme',themeName);
|
||||
_applyTheme(themeName);
|
||||
try{await api('/api/settings',{method:'POST',body:JSON.stringify({theme:themeName})});}catch(e){}
|
||||
// Update settings dropdown if panel is open
|
||||
const sel=$('settingsTheme');
|
||||
if(sel)sel.value=themeName;
|
||||
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){
|
||||
// List available personalities
|
||||
try{
|
||||
const data=await api('/api/personalities');
|
||||
if(!data.personalities||!data.personalities.length){
|
||||
showToast(t('no_personalities'));
|
||||
return;
|
||||
}
|
||||
const list=data.personalities.map(p=>` **${p.name}**${p.description?' — '+p.description:''}`).join('\n');
|
||||
S.messages.push({role:'assistant',content:t('available_personalities')+'\n\n'+list+t('personality_switch_hint')});
|
||||
renderMessages();
|
||||
}catch(e){showToast(t('personalities_load_failed'));}
|
||||
return;
|
||||
}
|
||||
const name=args.trim();
|
||||
if(name.toLowerCase()==='none'||name.toLowerCase()==='default'||name.toLowerCase()==='clear'){
|
||||
try{
|
||||
await api('/api/personality/set',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,name:''})});
|
||||
showToast(t('personality_cleared'));
|
||||
}catch(e){showToast(t('failed_colon')+e.message);}
|
||||
return;
|
||||
}
|
||||
try{
|
||||
const res=await api('/api/personality/set',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,name})});
|
||||
showToast(t('personality_set')+name);
|
||||
}catch(e){showToast(t('failed_colon')+e.message);}
|
||||
}
|
||||
|
||||
// ── Autocomplete dropdown ───────────────────────────────────────────────────
|
||||
|
||||
1767
static/i18n.js
Normal file
1767
static/i18n.js
Normal file
File diff suppressed because it is too large
Load Diff
77
static/icons.js
Normal file
77
static/icons.js
Normal file
@@ -0,0 +1,77 @@
|
||||
// ── 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"/>',
|
||||
'save': '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/>',
|
||||
'chevron-down': '<polyline points="6 9 12 15 18 9"/>',
|
||||
'chevron-right': '<polyline points="9 18 15 12 9 6"/>',
|
||||
'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"/>',
|
||||
'arrow-right': '<line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>',
|
||||
'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"/>',
|
||||
'pause': '<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>',
|
||||
// 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"/>',
|
||||
'paperclip': '<path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.82-2.82l8.48-8.48"/>',
|
||||
'copy': '<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
|
||||
'rotate-ccw': '<path d="M3 2v6h6"/><path d="M3 8a9 9 0 1 0 2.64-4.36L3 8"/>',
|
||||
'user': '<path d="M20 21a8 8 0 0 0-16 0"/><circle cx="12" cy="7" r="4"/>',
|
||||
// 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>`;
|
||||
}
|
||||
@@ -4,41 +4,46 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Hermes</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<!-- base href enables subpath mount support; all static paths must stay relative (no leading slash) -->
|
||||
<script>(function(){var p=location.pathname.endsWith('/')?location.pathname:(location.pathname.replace(/\/[^\/]*$/,'/')||'/');document.write('<base href="'+location.origin+p+'">');})()</script>
|
||||
<script>(function(){var t=localStorage.getItem('hermes-theme');if(t==='system'){t=window.matchMedia('(prefers-color-scheme:dark)').matches?'dark':'light';}if(t&&t!=='dark')document.documentElement.dataset.theme=t;})()</script>
|
||||
<link rel="stylesheet" href="static/style.css">
|
||||
<!-- KaTeX math rendering CSS (loaded eagerly to prevent layout shift) -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css" integrity="sha384-5TcZemv2l/9On385z///+d7MSYlvIEw9FuZTIdZ14vJLqWphw7e7ZPuOiCHJcFCP" crossorigin="anonymous">
|
||||
<!-- Prism.js syntax highlighting (loaded async, non-blocking) -->
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css" integrity="sha384-wFjoQjtV1y5jVHbt0p35Ui8aV8GVpEZkyF99OXWqP/eNJDU93D3Ugxkoyh6Y2I4A" crossorigin="anonymous">
|
||||
<link id="prism-theme" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css" integrity="sha384-wFjoQjtV1y5jVHbt0p35Ui8aV8GVpEZkyF99OXWqP/eNJDU93D3Ugxkoyh6Y2I4A" crossorigin="anonymous">
|
||||
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js" integrity="sha384-MXybTpajaBV0AkcBaCPT4KIvo0FzoCiWXgcihYsw4FUkEz0Pv3JGV6tk2G8vJtDc" crossorigin="anonymous" defer></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha384-Uq05+JLko69eOiPr39ta9bh7kld5PKZoU+fF7g0EXTAriEollhZ+DrN8Q/Oi8J2Q" crossorigin="anonymous" defer></script>
|
||||
</head>
|
||||
<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.32</div></div></div>
|
||||
|
||||
<div class="sidebar-nav">
|
||||
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat">💬</button>
|
||||
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks">📅</button>
|
||||
<button class="nav-tab" data-panel="skills" data-label="Skills" onclick="switchPanel('skills')" title="Skills">🧩</button>
|
||||
<button class="nav-tab" data-panel="memory" data-label="Memory" onclick="switchPanel('memory')" title="Memory">🧠</button>
|
||||
<button class="nav-tab" data-panel="workspaces" data-label="Spaces" onclick="switchPanel('workspaces')" title="Spaces">📁</button>
|
||||
<button class="nav-tab" data-panel="profiles" data-label="Profiles" onclick="switchPanel('profiles')" title="Agent profiles"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></button>
|
||||
<button class="nav-tab" data-panel="todos" data-label="Todos" onclick="switchPanel('todos')" title="Current task list">✅</button>
|
||||
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat" data-i18n-title="tab_chat"><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"><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">
|
||||
<div class="sidebar-section">
|
||||
<button class="new-chat-btn" id="btnNewChat">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
New conversation <span style="font-size:10px;opacity:.5;margin-left:4px">⌘K</span>
|
||||
<span data-i18n="new_conversation">New conversation</span> <span style="font-size:10px;opacity:.5;margin-left:4px">Cmd+K</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="session-search"><input id="sessionSearch" placeholder="Filter conversations..." oninput="filterSessions()"></div>
|
||||
<div class="session-search"><input id="sessionSearch" placeholder="Filter conversations..." data-i18n-placeholder="filter_conversations" oninput="filterSessions()"></div>
|
||||
<div class="session-list" id="sessionList"></div>
|
||||
</div>
|
||||
<!-- Tasks (cron) panel -->
|
||||
<div class="panel-view" id="panelTasks">
|
||||
<div class="sidebar-section" style="padding-bottom:4px;display:flex;align-items:center;justify-content:space-between">
|
||||
<div style="font-size:11px;color:var(--muted)">Scheduled jobs</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleCronForm()">+ New job</button>
|
||||
<div style="font-size:11px;color:var(--muted)" data-i18n="scheduled_jobs">Scheduled jobs</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleCronForm()">+ <span data-i18n="new_job">New job</span></button>
|
||||
</div>
|
||||
<!-- Create job form (hidden by default) -->
|
||||
<div id="cronCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
|
||||
@@ -56,18 +61,18 @@
|
||||
<div id="cronFormSkillTags" class="skill-picker-tags"></div>
|
||||
</div>
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitCronCreate()">Create job</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleCronForm()">Cancel</button>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitCronCreate()" data-i18n="create_job">Create job</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleCronForm()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="cronFormError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
<div class="cron-list" id="cronList"><div style="padding:12px;color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div class="cron-list" id="cronList"><div style="padding:12px;color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
</div>
|
||||
<!-- Skills panel -->
|
||||
<div class="panel-view" id="panelSkills">
|
||||
<div class="sidebar-section" style="padding-bottom:4px;display:flex;align-items:center;justify-content:space-between">
|
||||
<div class="skills-search" style="flex:1;padding:0"><input id="skillsSearch" placeholder="Search skills..." oninput="filterSkills()"></div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px;flex-shrink:0;margin-left:6px" onclick="toggleSkillForm()">+ New skill</button>
|
||||
<div class="skills-search" style="flex:1;padding:0"><input id="skillsSearch" placeholder="Search skills..." data-i18n-placeholder="search_skills" oninput="filterSkills()"></div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px;flex-shrink:0;margin-left:6px" onclick="toggleSkillForm()">+ <span data-i18n="new_skill">New skill</span></button>
|
||||
</div>
|
||||
<!-- Skill create/edit form (hidden by default) -->
|
||||
<div id="skillCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
|
||||
@@ -75,46 +80,46 @@
|
||||
<input id="skillFormCategory" placeholder="Category (optional, e.g. devops)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;margin-bottom:6px;box-sizing:border-box">
|
||||
<textarea id="skillFormContent" rows="6" placeholder="SKILL.md content (YAML frontmatter + markdown body)" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;resize:vertical;font-family:'SF Mono',ui-monospace,monospace;margin-bottom:6px;box-sizing:border-box"></textarea>
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitSkillSave()">Save skill</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleSkillForm()">Cancel</button>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitSkillSave()" data-i18n="save_skill">Save skill</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="toggleSkillForm()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="skillFormError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
<div class="skills-list" id="skillsList"><div style="padding:12px;color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div class="skills-list" id="skillsList"><div style="padding:12px;color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
</div>
|
||||
<!-- Memory panel -->
|
||||
<div class="panel-view" id="panelMemory">
|
||||
<div style="padding:8px 12px 4px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0">
|
||||
<span style="font-size:11px;color:var(--muted)">Personal memory</span>
|
||||
<button class="cron-btn run" id="memEditBtn" style="padding:3px 8px;font-size:10px" onclick="toggleMemoryEdit()">✎ Edit</button>
|
||||
<span style="font-size:11px;color:var(--muted)" data-i18n="personal_memory">Personal memory</span>
|
||||
<button class="cron-btn run" id="memEditBtn" style="padding:3px 8px;font-size:10px" onclick="toggleMemoryEdit()"><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">Loading...</div></div>
|
||||
<div class="memory-panel" id="memoryPanel"><div style="color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
<!-- Memory edit form (hidden by default) -->
|
||||
<div id="memoryEditForm" style="display:none;padding:8px 12px;border-top:1px solid var(--border);flex-shrink:0">
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:4px">Editing: <span id="memEditSection">memory</span></div>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:4px"><span data-i18n="editing">Editing</span>: <span id="memEditSection">memory</span></div>
|
||||
<textarea id="memEditContent" rows="10" style="width:100%;background:rgba(255,255,255,.05);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:11px;outline:none;resize:vertical;font-family:'SF Mono',ui-monospace,monospace;box-sizing:border-box;margin-bottom:6px;line-height:1.5"></textarea>
|
||||
<div style="display:flex;gap:6px">
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitMemorySave()">Save</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="closeMemoryEdit()">Cancel</button>
|
||||
<button class="cron-btn run" style="flex:1" onclick="submitMemorySave()" data-i18n="save">Save</button>
|
||||
<button class="cron-btn" style="flex:1" onclick="closeMemoryEdit()" data-i18n="cancel">Cancel</button>
|
||||
</div>
|
||||
<div id="memEditError" style="font-size:11px;color:var(--accent);margin-top:6px;display:none"></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Todo panel -->
|
||||
<div class="panel-view" id="panelTodos">
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted);flex-shrink:0">Current task list</div>
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted);flex-shrink:0" data-i18n="current_task_list">Current task list</div>
|
||||
<div id="todoPanel" style="flex:1;overflow-y:auto;padding:8px 12px"></div>
|
||||
</div>
|
||||
<!-- Workspaces panel -->
|
||||
<div class="panel-view" id="panelWorkspaces">
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted)">Add and switch workspaces for your sessions.</div>
|
||||
<div style="flex:1;overflow-y:auto;padding:0 12px 12px" id="workspacesPanel"><div style="color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
<div style="padding:10px 12px 4px;font-size:11px;color:var(--muted)" data-i18n="workspace_desc">Add and switch workspaces for your sessions.</div>
|
||||
<div style="flex:1;overflow-y:auto;padding:0 12px 12px" id="workspacesPanel"><div style="color:var(--muted);font-size:12px" data-i18n="loading">Loading...</div></div>
|
||||
</div>
|
||||
<!-- Profiles panel -->
|
||||
<div class="panel-view" id="panelProfiles">
|
||||
<div class="sidebar-section" style="padding-bottom:4px;display:flex;align-items:center;justify-content:space-between">
|
||||
<div style="font-size:11px;color:var(--muted)">Agent profiles</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleProfileForm()">+ New profile</button>
|
||||
<div style="font-size:11px;color:var(--muted)" data-i18n="tab_profiles">Agent profiles</div>
|
||||
<button class="cron-btn run" style="padding:3px 8px;font-size:10px" onclick="toggleProfileForm()">+ <span data-i18n="new_profile">New profile</span></button>
|
||||
</div>
|
||||
<!-- Profile create form (hidden by default) -->
|
||||
<div id="profileCreateForm" style="display:none;padding:8px 12px;border-bottom:1px solid var(--border);flex-shrink:0">
|
||||
@@ -122,6 +127,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>
|
||||
@@ -131,42 +138,30 @@
|
||||
<div style="flex:1;overflow-y:auto;padding:0 12px 12px" id="profilesPanel"><div style="color:var(--muted);font-size:12px">Loading...</div></div>
|
||||
</div>
|
||||
<div class="sidebar-bottom">
|
||||
<div class="field-label" style="font-size:10px;letter-spacing:.07em;margin-bottom:4px">MODEL</div>
|
||||
<select id="modelSelect">
|
||||
<optgroup label="OpenAI">
|
||||
<option value="openai/gpt-5.4-mini">GPT-5.4 Mini</option>
|
||||
<option value="openai/gpt-4o">GPT-4o</option>
|
||||
<option value="openai/o3">o3</option>
|
||||
<option value="openai/o4-mini">o4-mini</option>
|
||||
</optgroup>
|
||||
<optgroup label="Anthropic">
|
||||
<option value="anthropic/claude-sonnet-4.6">Claude Sonnet 4.6</option>
|
||||
<option value="anthropic/claude-sonnet-4-5">Claude Sonnet 4.5</option>
|
||||
<option value="anthropic/claude-haiku-3-5">Claude Haiku 3.5</option>
|
||||
</optgroup>
|
||||
<optgroup label="Other">
|
||||
<option value="google/gemini-2.5-pro">Gemini 2.5 Pro</option>
|
||||
<option value="deepseek/deepseek-chat-v3-0324">DeepSeek V3</option>
|
||||
<option value="meta-llama/llama-4-scout">Llama 4 Scout</option>
|
||||
</optgroup>
|
||||
</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>
|
||||
<div style="min-width:0;flex:1">
|
||||
<div style="font-size:11px;font-weight:600;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap" id="sidebarWsName">Workspace</div>
|
||||
<div style="font-size:10px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:1px" id="sidebarWsPath"></div>
|
||||
</div>
|
||||
<span style="font-size:10px;color:var(--muted);flex-shrink:0">▾</span>
|
||||
</div>
|
||||
<div class="ws-dropdown" id="wsDropdown"></div>
|
||||
</div>
|
||||
<div class="sidebar-actions">
|
||||
<button class="sm-btn" id="btnDownload" title="Download as Markdown">↓ Transcript</button>
|
||||
<button class="sm-btn" id="btnExportJSON" title="Export full session as JSON">❬/❭ JSON</button>
|
||||
<button class="sm-btn" id="btnImportJSON" title="Import session from JSON">↑ Import</button>
|
||||
<input type="file" id="importFileInput" accept=".json" style="display:none">
|
||||
</div>
|
||||
<button class="hermes-launch-btn" id="btnHermesPanel" onclick="toggleSettings()" title="Open Hermes control center">
|
||||
<span class="hermes-launch-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="hermes-gold-sidebar" 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-sidebar)"/>
|
||||
<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></span>
|
||||
<span class="hermes-launch-copy">
|
||||
<span class="hermes-launch-title">Hermes WebUI</span>
|
||||
<span class="hermes-launch-meta">Preferences, imports, exports</span>
|
||||
</span>
|
||||
<span class="hermes-launch-chevron" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="resize-handle" id="sidebarResize"></div>
|
||||
</aside>
|
||||
@@ -175,68 +170,98 @@
|
||||
<button class="mobile-hamburger" id="btnHamburger" onclick="toggleMobileSidebar()" title="Menu">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
|
||||
</button>
|
||||
<div style="flex:1;min-width:0;overflow:hidden"><div class="topbar-title" id="topbarTitle">Hermes</div><div class="topbar-meta" id="topbarMeta">Start a new conversation</div></div>
|
||||
<div style="flex:1;min-width:0;overflow:hidden"><div class="topbar-title" id="topbarTitle">Hermes</div><div class="topbar-meta" id="topbarMeta" data-i18n="new_conversation">Start a new conversation</div></div>
|
||||
<div class="topbar-chips">
|
||||
<div id="profileChipWrap" style="position:relative">
|
||||
<div class="chip profile-chip" id="profileChip" onclick="toggleProfileDropdown()" title="Switch profile" style="cursor:pointer"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg><span id="profileChipLabel">default</span> ▾</div>
|
||||
<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">🗑 Clear</button>
|
||||
<button class="chip gear-btn" id="btnSettings" onclick="toggleSettings()" title="Settings">⚙</button>
|
||||
<button class="chip mobile-files-btn" id="btnMobileFiles" onclick="toggleMobileFiles()" title="Files">📁</button>
|
||||
<button class="chip workspace-toggle-btn" id="btnWorkspacePanelToggle" onclick="toggleWorkspacePanel()" title="Show workspace panel" aria-pressed="false"><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 class="workspace-toggle-label">Files</span></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="messages" id="messages">
|
||||
<div class="empty-state" id="emptyState">
|
||||
<div class="empty-logo">🦉</div>
|
||||
<h2>What can I help with?</h2>
|
||||
<p>Ask anything, run commands, explore files, or manage your scheduled tasks.</p>
|
||||
<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?">📁 What files are in this workspace?</button>
|
||||
<button class="suggestion" data-msg="What's on my schedule today?">📋 What's on my schedule today?</button>
|
||||
<button class="suggestion" data-msg="Help me plan a small project.">🗺 Help me plan a small project.</button>
|
||||
<button class="suggestion" data-msg="What files are in this workspace?"><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>
|
||||
<div id="liveToolCards" style="display:none;max-width:800px;margin:0 auto;width:100%;padding:0 24px;"></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>
|
||||
<div class="update-banner" id="updateBanner">
|
||||
<span id="updateMsg"></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="update-btn" onclick="dismissUpdate()">Later</button>
|
||||
<button class="update-btn update-primary" id="btnApplyUpdate" onclick="applyUpdates()">Update Now</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="approval-card" id="approvalCard">
|
||||
<div class="reconnect-banner" id="reconnectBanner">
|
||||
<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()"><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">
|
||||
<div class="approval-inner">
|
||||
<div class="approval-header">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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>
|
||||
Dangerous command — approval required
|
||||
<span id="approvalHeading" data-i18n="approval_heading">Approval required</span>
|
||||
</div>
|
||||
<div class="approval-desc" id="approvalDesc"></div>
|
||||
<div class="approval-cmd" id="approvalCmd"></div>
|
||||
<div class="approval-counter" id="approvalCounter" style="display:none;font-size:0.75em;opacity:0.6;margin-top:4px;"></div>
|
||||
<div class="approval-btns">
|
||||
<button class="approval-btn once" onclick="respondApproval('once')">✓ Allow once</button>
|
||||
<button class="approval-btn session" onclick="respondApproval('session')">🔒 Allow this session</button>
|
||||
<button class="approval-btn always" onclick="respondApproval('always')">☆ Always allow</button>
|
||||
<button class="approval-btn deny" onclick="respondApproval('deny')">✕ Deny</button>
|
||||
<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"><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"><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"><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"><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>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 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="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>
|
||||
<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>
|
||||
<span style="width:4px;height:4px;border-radius:50%;background:var(--blue);opacity:.3;animation:pulse 1.4s ease-in-out .44s infinite"></span>
|
||||
</span>
|
||||
<div class="clarify-card" id="clarifyCard" role="dialog" aria-labelledby="clarifyHeading" aria-describedby="clarifyQuestion clarifyHint">
|
||||
<div class="clarify-inner">
|
||||
<div class="clarify-header">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 17h.01"/><path d="M9.09 9a3 3 0 1 1 5.82 1c0 2-3 2-3 4"/><circle cx="12" cy="12" r="10"/></svg>
|
||||
<span id="clarifyHeading" data-i18n="clarify_heading">Clarification needed</span>
|
||||
</div>
|
||||
<div class="clarify-question" id="clarifyQuestion"></div>
|
||||
<div class="clarify-choices" id="clarifyChoices"></div>
|
||||
<div class="clarify-response">
|
||||
<input class="clarify-input" id="clarifyInput" type="text" data-i18n-placeholder="clarify_input_placeholder" placeholder="Type your response…">
|
||||
<button class="clarify-submit" id="clarifySubmit" onclick="respondClarify()" data-i18n="clarify_send">Send</button>
|
||||
</div>
|
||||
<div class="clarify-hint" id="clarifyHint" data-i18n="clarify_hint">Pick a choice, or type your own answer below.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="composer-wrap" id="composerWrap">
|
||||
@@ -251,7 +276,7 @@
|
||||
<textarea id="msg" rows="1" placeholder="Message Hermes…"></textarea>
|
||||
<div class="composer-footer">
|
||||
<div class="composer-left">
|
||||
<input type="file" id="fileInput" multiple accept="image/*,text/*,application/pdf,application/json,.md,.py,.js,.ts,.yaml,.yml,.toml,.csv,.sh,.txt,.log,.env" style="display:none">
|
||||
<input type="file" id="fileInput" multiple accept="image/*,text/*,application/pdf,application/json,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.md,.py,.js,.ts,.yaml,.yml,.toml,.csv,.sh,.txt,.log,.env,.xls,.xlsx,.doc,.docx" style="display:none">
|
||||
<button class="icon-btn" id="btnAttach" title="Attach files">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>
|
||||
</button>
|
||||
@@ -263,16 +288,77 @@
|
||||
<line x1="8" y1="23" x2="16" y2="23"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="ctx-indicator" id="ctxIndicator" style="display:none" title="Context window usage">
|
||||
<span class="ctx-bar-wrap"><span class="ctx-bar" id="ctxBar"></span></span>
|
||||
<span class="ctx-label" id="ctxLabel"></span>
|
||||
<div class="composer-divider" aria-hidden="true"></div>
|
||||
<div id="profileChipWrap" class="composer-profile-wrap">
|
||||
<button class="composer-profile-chip profile-chip" id="profileChip" type="button" onclick="toggleProfileDropdown()" title="Switch profile">
|
||||
<span class="composer-profile-icon" aria-hidden="true"><svg width="14" height="14" 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></span>
|
||||
<span class="composer-profile-label" id="profileChipLabel">default</span>
|
||||
<span class="composer-profile-chevron" aria-hidden="true"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="composer-ws-wrap">
|
||||
<button class="composer-workspace-chip ws-chip" id="composerWorkspaceChip" type="button" onclick="toggleComposerWsDropdown()" title="Switch workspace" disabled>
|
||||
<span class="composer-workspace-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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>
|
||||
<span class="composer-workspace-label" id="composerWorkspaceLabel">Workspace</span>
|
||||
<span class="composer-workspace-chevron" aria-hidden="true"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="composer-model-wrap">
|
||||
<button class="composer-model-chip" id="composerModelChip" type="button" onclick="toggleModelDropdown()" title="Conversation model">
|
||||
<span class="composer-model-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2"/><rect x="9" y="9" width="6" height="6"/><path d="M15 2v2"/><path d="M15 20v2"/><path d="M2 15h2"/><path d="M2 9h2"/><path d="M20 15h2"/><path d="M20 9h2"/><path d="M9 2v2"/><path d="M9 20v2"/></svg></span>
|
||||
<span class="composer-model-label" id="composerModelLabel">Model</span>
|
||||
<span class="composer-model-chevron" aria-hidden="true"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></span>
|
||||
</button>
|
||||
<select id="modelSelect" class="composer-model-select" title="Conversation model" aria-hidden="true" tabindex="-1">
|
||||
<optgroup label="OpenAI">
|
||||
<option value="openai/gpt-5.4-mini">GPT-5.4 Mini</option>
|
||||
<option value="openai/gpt-4o">GPT-4o</option>
|
||||
<option value="openai/o3">o3</option>
|
||||
<option value="openai/o4-mini">o4-mini</option>
|
||||
</optgroup>
|
||||
<optgroup label="Anthropic">
|
||||
<option value="anthropic/claude-sonnet-4.6">Claude Sonnet 4.6</option>
|
||||
<option value="anthropic/claude-sonnet-4-5">Claude Sonnet 4.5</option>
|
||||
<option value="anthropic/claude-haiku-3-5">Claude Haiku 3.5</option>
|
||||
</optgroup>
|
||||
<optgroup label="Other">
|
||||
<option value="google/gemini-2.5-pro">Gemini 2.5 Pro</option>
|
||||
<option value="deepseek/deepseek-chat-v3-0324">DeepSeek V3</option>
|
||||
<option value="meta-llama/llama-4-scout">Llama 4 Scout</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="composer-right">
|
||||
<button class="send-btn" id="btnSend" title="Send message" style="display:none">
|
||||
<span class="composer-status" id="composerStatus" style="display:none"></span>
|
||||
<div class="ctx-indicator-wrap" id="ctxIndicatorWrap" style="display:none">
|
||||
<button class="ctx-indicator" id="ctxIndicator" type="button" aria-label="Context window usage" aria-describedby="ctxTooltip">
|
||||
<span class="ctx-ring">
|
||||
<svg class="ctx-ring-svg" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<circle class="ctx-ring-track" cx="12" cy="12" r="9.75"></circle>
|
||||
<circle class="ctx-ring-value" id="ctxRingValue" cx="12" cy="12" r="9.75"></circle>
|
||||
</svg>
|
||||
<span class="ctx-ring-center" id="ctxPercent">0</span>
|
||||
</span>
|
||||
</button>
|
||||
<div class="ctx-tooltip" id="ctxTooltip" role="tooltip" aria-hidden="true">
|
||||
<div class="ctx-tooltip-title">Context window</div>
|
||||
<div class="ctx-tooltip-line" id="ctxTooltipUsage"></div>
|
||||
<div class="ctx-tooltip-line" id="ctxTooltipTokens"></div>
|
||||
<div class="ctx-tooltip-line" id="ctxTooltipThreshold"></div>
|
||||
<div class="ctx-tooltip-line" id="ctxTooltipCost" style="display:none"></div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="cancel-btn" id="btnCancel" onclick="cancelStream()" style="display:none" title="Stop generation" aria-label="Stop generation">
|
||||
<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="5" y="5" width="14" height="14" rx="2"></rect></svg>
|
||||
</button>
|
||||
<button class="send-btn" id="btnSend" title="Send message" disabled>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="profile-dropdown" id="profileDropdown"></div>
|
||||
<div class="ws-dropdown ws-dropdown-footer" id="composerWsDropdown"></div>
|
||||
<div class="model-dropdown" id="composerModelDropdown"></div>
|
||||
</div>
|
||||
<div class="upload-bar-wrap" id="uploadBarWrap"><div class="upload-bar" id="uploadBar"></div></div>
|
||||
</div>
|
||||
@@ -284,11 +370,13 @@
|
||||
<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="btnCollapseWorkspacePanel" title="Hide workspace panel" onclick="toggleWorkspacePanel(false)"><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="15 18 9 12 15 6"/></svg></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="handleWorkspaceClose()" title="Close" aria-label="Close workspace panel">×</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="breadcrumb-bar" id="breadcrumbBar" style="display:none"></div>
|
||||
@@ -297,8 +385,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>
|
||||
@@ -307,83 +395,209 @@
|
||||
</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="onboardingSkipBtn" onclick="skipOnboarding()" style="margin-right:auto;opacity:.7" data-i18n="onboarding_skip">Skip setup</button>
|
||||
<button class="sm-btn" id="onboardingNextBtn" onclick="nextOnboardingStep()" style="font-weight:700;color:var(--blue);border-color:rgba(124,185,255,.32)" data-i18n="onboarding_continue">Continue</button>
|
||||
</div>
|
||||
</div>
|
||||
</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">Settings</h3>
|
||||
<button class="panel-icon-btn" onclick="toggleSettings()" title="Close">✕</button>
|
||||
<div class="settings-heading">
|
||||
<div class="settings-kicker">Hermes WebUI</div>
|
||||
<h3 style="margin:0;font-size:18px">Control Center</h3>
|
||||
<div class="settings-subtitle">Preferences, conversation tools, and system controls.</div>
|
||||
</div>
|
||||
<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">
|
||||
<label for="settingsModel">Default Model</label>
|
||||
<select id="settingsModel" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px"></select>
|
||||
<div class="settings-shell">
|
||||
<div class="settings-tabs" role="tablist" aria-label="Hermes control center sections">
|
||||
<button class="settings-tab active" id="settingsTabConversation" type="button" role="tab" aria-selected="true" aria-controls="settingsPaneConversation" onclick="switchSettingsSection('conversation')">
|
||||
<svg class="settings-tab-icon" width="16" height="16" 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>
|
||||
<span class="settings-tab-title">Conversation</span>
|
||||
</button>
|
||||
<button class="settings-tab" id="settingsTabPreferences" type="button" role="tab" aria-selected="false" aria-controls="settingsPanePreferences" onclick="switchSettingsSection('preferences')">
|
||||
<svg class="settings-tab-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></svg>
|
||||
<span class="settings-tab-title">Preferences</span>
|
||||
</button>
|
||||
<button class="settings-tab" id="settingsTabSystem" type="button" role="tab" aria-selected="false" aria-controls="settingsPaneSystem" onclick="switchSettingsSection('system')">
|
||||
<svg class="settings-tab-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="3" width="20" height="8" rx="2"/><rect x="2" y="13" width="20" height="8" rx="2"/><line x1="6" y1="7" x2="6.01" y2="7"/><line x1="6" y1="17" x2="6.01" y2="17"/></svg>
|
||||
<span class="settings-tab-title">System</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="settings-main">
|
||||
<div class="settings-pane active" id="settingsPaneConversation" role="tabpanel" aria-labelledby="settingsTabConversation">
|
||||
<div class="settings-section-head">
|
||||
<div>
|
||||
<div class="settings-section-title">Conversation</div>
|
||||
<div class="settings-section-meta" id="hermesSessionMeta">No active conversation selected.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="hermes-action-grid">
|
||||
<button class="settings-action-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="settings-action-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="settings-action-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>
|
||||
<button class="settings-action-btn danger" id="btnClearConvModal" onclick="clearConversation()" title="Clear all messages in this conversation"><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 1 2 2 2v2"/></svg> Clear</button>
|
||||
</div>
|
||||
<input type="file" id="importFileInput" accept=".json" style="display:none">
|
||||
</div>
|
||||
<div class="settings-pane" id="settingsPanePreferences" role="tabpanel" aria-labelledby="settingsTabPreferences">
|
||||
<div class="settings-section-head">
|
||||
<div>
|
||||
<div class="settings-section-title">Preferences</div>
|
||||
<div class="settings-section-meta">Defaults and UI behavior for Hermes Web UI.</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsModel" data-i18n="settings_label_model">Default Model</label>
|
||||
<select id="settingsModel" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px"></select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsSendKey" data-i18n="settings_label_send_key">Send Key</label>
|
||||
<select id="settingsSendKey" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px">
|
||||
<option value="enter">Enter (Shift+Enter for newline)</option>
|
||||
<option value="ctrl+enter">Ctrl+Enter (Enter for newline)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsTheme" data-i18n="settings_label_theme">Theme</label>
|
||||
<select id="settingsTheme" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px" onchange="_applyTheme(this.value)">
|
||||
<option value="system">System (auto)</option>
|
||||
<option value="dark">Dark (default)</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="slate">Slate (charcoal)</option>
|
||||
<option value="solarized">Solarized Dark</option>
|
||||
<option value="monokai">Monokai</option>
|
||||
<option value="nord">Nord</option>
|
||||
<option value="oled">OLED</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsLanguage" data-i18n="settings_label_language">Language</label>
|
||||
<select id="settingsLanguage" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px"></select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsSoundEnabled" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_sound">Notification sound</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_sound">Play a sound when the assistant finishes a response.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsNotificationsEnabled" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_notifications">Browser notifications</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_notifications">Show a system notification when a response completes while the tab is in the background.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsShowTokenUsage" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_token_usage">Show token usage after responses</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_token_usage">Displays input/output token count below each assistant reply. Also toggled with <code>/usage</code>.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsBubbleLayout" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_bubble_layout">Chat bubble layout</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_bubble_layout">Right-align user messages and left-align assistant replies. Off by default to keep code blocks and tool output full-width.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsShowCliSessions" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_cli_sessions">Show CLI sessions in sidebar</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_cli_sessions">Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsSyncInsights" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_sync_insights">Sync usage to /insights</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_sync_insights">Mirrors WebUI token usage to state.db so <code>hermes /insights</code> includes browser session data. Off by default.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsCheckUpdates" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
<span data-i18n="settings_label_check_updates">Check for updates</span>
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px" data-i18n="settings_desc_check_updates">Show a banner when newer versions of the WebUI or Agent are available. Runs a background git fetch periodically.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsBotName" data-i18n="settings_label_bot_name">Assistant Name</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px" data-i18n="settings_desc_bot_name">Display name for the assistant throughout the UI. Defaults to Hermes.</div>
|
||||
<input type="text" id="settingsBotName" placeholder="Hermes" maxlength="64" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px;font-size:13px">
|
||||
</div>
|
||||
<button class="sm-btn" onclick="saveSettings()" style="margin-top:12px;width:100%;padding:8px;font-weight:600" data-i18n="settings_save_btn">Save Settings</button>
|
||||
</div>
|
||||
<div class="settings-pane" id="settingsPaneSystem" role="tabpanel" aria-labelledby="settingsTabSystem">
|
||||
<div class="settings-section-head">
|
||||
<div>
|
||||
<div class="settings-section-title">System</div>
|
||||
<div class="settings-section-meta">Instance version and access controls.</div>
|
||||
</div>
|
||||
<span class="settings-version-badge">v0.50.69</span>
|
||||
</div>
|
||||
<div class="settings-field" style="border-top:1px solid var(--border);padding-top:12px;margin-top:8px">
|
||||
<label for="settingsPassword" data-i18n="settings_label_password">Access Password</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px" data-i18n="settings_desc_password">Enter a new password to set or change it. Leave blank to keep current setting.</div>
|
||||
<input type="password" id="settingsPassword" placeholder="Enter new password…" data-i18n-placeholder="password_placeholder" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px;font-size:13px">
|
||||
</div>
|
||||
<button class="sm-btn" id="btnDisableAuth" onclick="disableAuth()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:#e8a030;border-color:rgba(232,160,48,.3);display:none" data-i18n="disable_auth">Disable Auth</button>
|
||||
<button class="sm-btn" id="btnSignOut" onclick="signOut()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:var(--accent);border-color:rgba(233,69,96,.3);display:none" data-i18n="sign_out">Sign Out</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsWorkspace">Default Workspace</label>
|
||||
<select id="settingsWorkspace" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px"></select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label for="settingsSendKey">Send Key</label>
|
||||
<select id="settingsSendKey" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px">
|
||||
<option value="enter">Enter (Shift+Enter for newline)</option>
|
||||
<option value="ctrl+enter">Ctrl+Enter (Enter for newline)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsShowTokenUsage" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
Show token usage after responses
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Displays input/output token count below each assistant reply. Also toggled with <code>/usage</code>.</div>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<label style="display:flex;align-items:center;gap:8px;cursor:pointer">
|
||||
<input type="checkbox" id="settingsShowCliSessions" style="width:15px;height:15px;accent-color:var(--accent)">
|
||||
Show CLI sessions in sidebar
|
||||
</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-top:4px">Merges sessions from the Hermes CLI (state.db) into the session list. Click a CLI session to import it and continue the conversation.</div>
|
||||
</div>
|
||||
<div class="settings-field" style="border-top:1px solid var(--border);padding-top:12px;margin-top:8px">
|
||||
<label for="settingsPassword">Access Password</label>
|
||||
<div style="font-size:11px;color:var(--muted);margin-bottom:6px">Enter a new password to set or change it. Leave blank to keep current setting.</div>
|
||||
<input type="password" id="settingsPassword" placeholder="Enter new password…" style="width:100%;padding:8px;background:var(--code-bg);color:var(--text);border:1px solid var(--border2);border-radius:6px;font-size:13px">
|
||||
</div>
|
||||
<button class="sm-btn" onclick="saveSettings()" style="margin-top:12px;width:100%;padding:8px;font-weight:600">Save Settings</button>
|
||||
<button class="sm-btn" id="btnDisableAuth" onclick="disableAuth()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:#e8a030;border-color:rgba(232,160,48,.3);display:none">Disable Auth</button>
|
||||
<button class="sm-btn" id="btnSignOut" onclick="signOut()" style="margin-top:6px;width:100%;padding:8px;font-weight:600;color:var(--accent);border-color:rgba(233,69,96,.3);display:none">Sign Out</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mobile-overlay" id="mobileOverlay" onclick="closeMobileSidebar()"></div>
|
||||
<nav class="mobile-bottom-nav" id="mobileBottomNav">
|
||||
<button class="mobile-nav-btn active" data-panel="chat" onclick="mobileSwitchPanel('chat')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
|
||||
<span>Chat</span>
|
||||
</button>
|
||||
<button class="mobile-nav-btn" data-panel="tasks" onclick="mobileSwitchPanel('tasks')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
|
||||
<span>Tasks</span>
|
||||
</button>
|
||||
<button class="mobile-nav-btn" data-panel="skills" onclick="mobileSwitchPanel('skills')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
|
||||
<span>Skills</span>
|
||||
</button>
|
||||
<button class="mobile-nav-btn" data-panel="memory" onclick="mobileSwitchPanel('memory')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 2a7 7 0 0 1 7 7c0 2.5-1.3 4.7-3.2 6H8.2C6.3 13.7 5 11.5 5 9a7 7 0 0 1 7-7z"/><line x1="9" y1="17" x2="15" y2="17"/><line x1="10" y1="20" x2="14" y2="20"/></svg>
|
||||
<span>Memory</span>
|
||||
</button>
|
||||
<button class="mobile-nav-btn" data-panel="workspaces" onclick="mobileSwitchPanel('workspaces')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2 4h8l2 2h10v14H2z"/></svg>
|
||||
<span>Spaces</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="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>
|
||||
<div class="toast" id="toast"></div>
|
||||
<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/boot.js"></script>
|
||||
<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>
|
||||
</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);
|
||||
}
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
390
static/onboarding.js
Normal file
390
static/onboarding.js
Normal file
@@ -0,0 +1,390 @@
|
||||
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)}.`:'';
|
||||
|
||||
// OAuth provider path: configured via CLI, no API key input needed.
|
||||
const currentIsOauth=!!(ONBOARDING.status.setup||{}).current_is_oauth;
|
||||
const currentProviderName=((ONBOARDING.status.setup||{}).current||{}).provider||'';
|
||||
if(currentIsOauth){
|
||||
const isReady=!!(ONBOARDING.status.system||{}).chat_ready;
|
||||
const providerLabel=esc(currentProviderName);
|
||||
if(isReady){
|
||||
_setOnboardingNotice(t('onboarding_notice_setup_already_ready'),'success');
|
||||
body.innerHTML=`
|
||||
<div class="onboarding-oauth-card onboarding-oauth-ready">
|
||||
<div class="onboarding-oauth-icon">✓</div>
|
||||
<div>
|
||||
<strong>${t('onboarding_oauth_provider_ready_title')}</strong>
|
||||
<p>${t('onboarding_oauth_provider_ready_body').replace('{provider}',providerLabel)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="onboarding-copy" style="margin-top:20px">${t('onboarding_oauth_switch_hint')}</p>
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_provider_label')}</span>
|
||||
<select id="onboardingProviderSelect" onchange="syncOnboardingProvider(this.value)">${options}</select>
|
||||
</label>
|
||||
<label class="onboarding-field" id="onboardingApiKeyField">
|
||||
<span>${t('onboarding_api_key_label')}</span>
|
||||
<input id="onboardingApiKeyInput" type="password" value="${esc(ONBOARDING.form.apiKey||'')}" placeholder="${t('onboarding_api_key_placeholder')}" oninput="ONBOARDING.form.apiKey=this.value">
|
||||
</label>
|
||||
${showBaseUrl?`<label class="onboarding-field"><span>${t('onboarding_base_url_label')}</span><input id="onboardingBaseUrlInput" value="${esc(ONBOARDING.form.baseUrl||'')}" placeholder="${t('onboarding_base_url_placeholder')}" oninput="ONBOARDING.form.baseUrl=this.value"></label>`:''}
|
||||
<p class="onboarding-copy">${keyHelp}</p>`;
|
||||
} else {
|
||||
_setOnboardingNotice(t('onboarding_notice_setup_required'),'warn');
|
||||
body.innerHTML=`
|
||||
<div class="onboarding-oauth-card onboarding-oauth-pending">
|
||||
<div class="onboarding-oauth-icon">⚠</div>
|
||||
<div>
|
||||
<strong>${t('onboarding_oauth_provider_not_ready_title')}</strong>
|
||||
<p>${t('onboarding_oauth_provider_not_ready_body').replace('{provider}',providerLabel)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<p class="onboarding-copy" style="margin-top:20px">${t('onboarding_oauth_switch_hint')}</p>
|
||||
<label class="onboarding-field">
|
||||
<span>${t('onboarding_provider_label')}</span>
|
||||
<select id="onboardingProviderSelect" onchange="syncOnboardingProvider(this.value)">${options}</select>
|
||||
</label>
|
||||
<label class="onboarding-field" id="onboardingApiKeyField">
|
||||
<span>${t('onboarding_api_key_label')}</span>
|
||||
<input id="onboardingApiKeyInput" type="password" value="${esc(ONBOARDING.form.apiKey||'')}" placeholder="${t('onboarding_api_key_placeholder')}" oninput="ONBOARDING.form.apiKey=this.value">
|
||||
</label>
|
||||
${showBaseUrl?`<label class="onboarding-field"><span>${t('onboarding_base_url_label')}</span><input id="onboardingBaseUrlInput" value="${esc(ONBOARDING.form.baseUrl||'')}" placeholder="${t('onboarding_base_url_placeholder')}" oninput="ONBOARDING.form.baseUrl=this.value"></label>`:''}
|
||||
<p class="onboarding-copy">${keyHelp}</p>`;
|
||||
}
|
||||
const providerSel=$('onboardingProviderSelect');
|
||||
if(providerSel) providerSel.value=ONBOARDING.form.provider;
|
||||
return;
|
||||
}
|
||||
|
||||
_setOnboardingNotice(system.chat_ready?t('onboarding_notice_setup_already_ready'):t('onboarding_notice_setup_required'),system.chat_ready?'success':'info');
|
||||
body.innerHTML=`
|
||||
<label class="onboarding-field">
|
||||
<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>${t(_getOnboardingPasswordSummaryKey(settings))}</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 _getOnboardingPasswordSummaryKey(settings){
|
||||
const hasExistingPassword=!!(settings&&settings.password_enabled);
|
||||
const hasNewPassword=!!((ONBOARDING.form.password||'').trim());
|
||||
if(hasNewPassword) return hasExistingPassword?'onboarding_password_will_replace':'onboarding_password_will_enable';
|
||||
return hasExistingPassword?'onboarding_password_keep_existing':'onboarding_password_remains_disabled';
|
||||
}
|
||||
|
||||
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);
|
||||
// Skip the POST when nothing changed. We also skip when the provider is
|
||||
// unsupported/OAuth-based and already working — chat_ready may be false for
|
||||
// providers not in the quick-setup list (e.g. minimax-cn) even though they are
|
||||
// fully configured. Posting in that case would either be a no-op (the server
|
||||
// just marks complete for unsupported providers) or could silently overwrite
|
||||
// config.yaml if the user accidentally changed the provider dropdown.
|
||||
const currentIsOauth=!!(ONBOARDING.status&&ONBOARDING.status.setup&&ONBOARDING.status.setup.current_is_oauth);
|
||||
if(isUnchanged && !apiKey && ((ONBOARDING.status.system||{}).chat_ready || currentIsOauth)) 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;
|
||||
const saved=await api('/api/settings',{method:'POST',body:JSON.stringify(body)});
|
||||
if(ONBOARDING.status){
|
||||
ONBOARDING.status.settings={...(ONBOARDING.status.settings||{}),password_enabled:!!saved.auth_enabled};
|
||||
}
|
||||
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 skipOnboarding(){
|
||||
try{
|
||||
// Mark onboarding completed server-side without changing any config
|
||||
await api('/api/onboarding/complete',{method:'POST',body:'{}'});
|
||||
ONBOARDING.active=false;
|
||||
$('onboardingOverlay').style.display='none';
|
||||
showToast(t('onboarding_skipped')||'Setup skipped');
|
||||
}catch(e){
|
||||
_setOnboardingNotice((e.message||String(e)),'warn');
|
||||
}
|
||||
}
|
||||
|
||||
async function nextOnboardingStep(){
|
||||
try{
|
||||
if(ONBOARDING.steps[ONBOARDING.step]==='setup'){
|
||||
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');
|
||||
}
|
||||
}
|
||||
710
static/panels.js
710
static/panels.js
File diff suppressed because it is too large
Load Diff
@@ -7,10 +7,11 @@ 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>',
|
||||
};
|
||||
|
||||
async function newSession(flash){
|
||||
MSG_QUEUE.length=0;updateQueueBadge();
|
||||
updateQueueBadge();
|
||||
S.toolCalls=[];
|
||||
clearLiveToolCards();
|
||||
// Use profile default workspace for new sessions after a profile switch (one-shot),
|
||||
@@ -19,51 +20,142 @@ async function newSession(flash){
|
||||
S._profileDefaultWorkspace=null; // consume — only applies to the first new session after switch
|
||||
const data=await api('/api/session/new',{method:'POST',body:JSON.stringify({model:$('modelSelect').value,workspace:inheritWs})});
|
||||
S.session=data.session;S.messages=data.session.messages||[];
|
||||
S.lastUsage={...(data.session.last_usage||{})};
|
||||
if(flash)S.session._flash=true;
|
||||
localStorage.setItem('hermes-webui-session',S.session.session_id);
|
||||
syncTopbar();await loadDir('.');renderMessages();
|
||||
// Reset per-session visual state: a fresh chat is idle even if another
|
||||
// conversation is still streaming in the background.
|
||||
S.busy=false;
|
||||
S.activeStreamId=null;
|
||||
updateSendBtn();
|
||||
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
|
||||
setStatus('');
|
||||
setComposerStatus('');
|
||||
updateQueueBadge(S.session.session_id);
|
||||
syncTopbar();renderMessages();loadDir('.');
|
||||
// don't call renderSessionList here - callers do it when needed
|
||||
}
|
||||
|
||||
async function loadSession(sid){
|
||||
stopApprovalPolling();hideApprovalCard();
|
||||
if(typeof stopClarifyPolling==='function') stopClarifyPolling();
|
||||
if(typeof hideClarifyCard==='function') hideClarifyCard();
|
||||
const data=await api(`/api/session?session_id=${encodeURIComponent(sid)}`);
|
||||
S.session=data.session;
|
||||
S.lastUsage={...(data.session.last_usage||{})};
|
||||
localStorage.setItem('hermes-webui-session',S.session.session_id);
|
||||
// B9: sanitize empty assistant messages that can appear when agent only ran tool calls
|
||||
data.session.messages=(data.session.messages||[]).filter(m=>{
|
||||
if(!m||!m.role)return false;
|
||||
if(m.role==='tool')return false;
|
||||
if(m.role==='assistant'){let c=m.content||'';if(Array.isArray(c))c=c.filter(p=>p&&p.type==='text').map(p=>p.text||'').join('');return String(c).trim().length>0;}
|
||||
return true;
|
||||
});
|
||||
// B9: sanitize empty assistant messages (PR #402) — build index map to remap
|
||||
// session-level tool_calls.assistant_msg_idx to the new sanitized positions.
|
||||
const allMsgs = data.session.messages || [];
|
||||
const sanitized = [];
|
||||
const origIdxToSanitizedIdx = {};
|
||||
let lastKeptAsstIdx = -1;
|
||||
for (let i = 0; i < allMsgs.length; i++) {
|
||||
const m = allMsgs[i];
|
||||
if (!m || !m.role) continue;
|
||||
if (m.role === 'tool') continue;
|
||||
if (m.role === 'assistant') {
|
||||
let c = m.content || '';
|
||||
if (Array.isArray(c)) c = c.filter(p => p && p.type === 'text').map(p => p.text || '').join('');
|
||||
if (!String(c).trim().length) { continue; } // empty assistant — skip
|
||||
lastKeptAsstIdx = sanitized.length;
|
||||
}
|
||||
origIdxToSanitizedIdx[i] = sanitized.length;
|
||||
sanitized.push(m);
|
||||
}
|
||||
if (data.session.tool_calls && data.session.tool_calls.length) {
|
||||
for (const tc of data.session.tool_calls) {
|
||||
if (!tc || tc.assistant_msg_idx === undefined) continue;
|
||||
const origIdx = tc.assistant_msg_idx;
|
||||
tc.assistant_msg_idx = (origIdx in origIdxToSanitizedIdx)
|
||||
? origIdxToSanitizedIdx[origIdx]
|
||||
: (lastKeptAsstIdx >= 0 ? lastKeptAsstIdx : -1);
|
||||
}
|
||||
}
|
||||
data.session.messages = sanitized;
|
||||
const activeStreamId=data.session.active_stream_id||null;
|
||||
if(!INFLIGHT[sid]&&activeStreamId&&typeof loadInflightState==='function'){
|
||||
const stored=loadInflightState(sid, activeStreamId);
|
||||
if(stored){
|
||||
INFLIGHT[sid]={
|
||||
messages:Array.isArray(stored.messages)&&stored.messages.length?stored.messages:[...(data.session.messages||[])],
|
||||
uploaded:Array.isArray(stored.uploaded)?stored.uploaded:[...(data.session.pending_attachments||[])],
|
||||
toolCalls:Array.isArray(stored.toolCalls)?stored.toolCalls:[],
|
||||
reattach:true,
|
||||
};
|
||||
}
|
||||
}
|
||||
if(INFLIGHT[sid]){
|
||||
S.messages=INFLIGHT[sid].messages;
|
||||
// Restore live tool cards for this in-flight session
|
||||
S.toolCalls=(INFLIGHT[sid].toolCalls||[]);
|
||||
S.busy=true;
|
||||
syncTopbar();renderMessages();appendThinking();loadDir('.');
|
||||
clearLiveToolCards();
|
||||
if(typeof placeLiveToolCardsHost==='function') placeLiveToolCardsHost();
|
||||
for(const tc of (S.toolCalls||[])){
|
||||
if(tc&&tc.name) appendLiveToolCard(tc);
|
||||
}
|
||||
syncTopbar();await loadDir('.');renderMessages();appendThinking();
|
||||
setBusy(true);setStatus('Hermes is thinking\u2026');
|
||||
setBusy(true);setComposerStatus('');
|
||||
startApprovalPolling(sid);
|
||||
if(typeof startClarifyPolling==='function') startClarifyPolling(sid);
|
||||
S.activeStreamId=activeStreamId;
|
||||
const _cb=$('btnCancel');if(_cb&&activeStreamId)_cb.style.display='inline-flex';
|
||||
if(INFLIGHT[sid].reattach&&activeStreamId&&typeof attachLiveStream==='function'){
|
||||
INFLIGHT[sid].reattach=false;
|
||||
attachLiveStream(sid, activeStreamId, data.session.pending_attachments||[], {reconnecting:true});
|
||||
}
|
||||
}else{
|
||||
MSG_QUEUE.length=0;updateQueueBadge(); // clear queue for the viewed session
|
||||
updateQueueBadge(sid);
|
||||
S.messages=data.session.messages||[];
|
||||
S.toolCalls=(data.session.tool_calls||[]).map(tc=>({...tc,done:true}));
|
||||
// Reset per-session visual state: the viewed session is idle even if another
|
||||
// session's stream is still running in the background.
|
||||
// We directly update the DOM instead of calling setBusy(false), because
|
||||
// setBusy(false) drains MSG_QUEUE which we don't want here.
|
||||
S.busy=false;
|
||||
S.activeStreamId=null;
|
||||
$('btnSend').disabled=false;
|
||||
$('btnSend').style.opacity='1';
|
||||
const _dots=$('activityDots');if(_dots)_dots.style.display='none';
|
||||
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
|
||||
setStatus('');
|
||||
const pendingMsg=typeof getPendingSessionMessage==='function'?getPendingSessionMessage(data.session):null;
|
||||
if(pendingMsg) S.messages.push(pendingMsg);
|
||||
// Fix (PR #402): do NOT pre-fill S.toolCalls from session-level tool_calls —
|
||||
// those have stale assistant_msg_idx values after B9 sanitization. Instead,
|
||||
// set S.toolCalls=[] and let renderMessages() derive them from per-message
|
||||
// tool_calls (which already have correct sanitized-array indices).
|
||||
S.toolCalls=[];
|
||||
clearLiveToolCards();
|
||||
syncTopbar();await loadDir('.');renderMessages();highlightCode();
|
||||
if(activeStreamId){
|
||||
S.busy=true;
|
||||
S.activeStreamId=activeStreamId;
|
||||
updateSendBtn();
|
||||
const _cb=$('btnCancel');if(_cb)_cb.style.display='inline-flex';
|
||||
setStatus('');
|
||||
setComposerStatus('');
|
||||
syncTopbar();renderMessages();appendThinking();loadDir('.');
|
||||
updateQueueBadge(sid);
|
||||
startApprovalPolling(sid);
|
||||
if(typeof startClarifyPolling==='function') startClarifyPolling(sid);
|
||||
if(typeof attachLiveStream==='function') attachLiveStream(sid, activeStreamId, data.session.pending_attachments||[], {reconnecting:true});
|
||||
else if(typeof watchInflightSession==='function') watchInflightSession(sid, activeStreamId);
|
||||
}else{
|
||||
// Reset per-session visual state: the viewed session is idle even if another
|
||||
// session's stream is still running in the background.
|
||||
// We directly update the DOM instead of calling setBusy(false), because
|
||||
// setBusy(false) drains the viewed session's queued follow-up turns.
|
||||
S.busy=false;
|
||||
S.activeStreamId=null;
|
||||
updateSendBtn();
|
||||
const _cb=$('btnCancel');if(_cb)_cb.style.display='none';
|
||||
setStatus('');
|
||||
setComposerStatus('');
|
||||
updateQueueBadge(sid);
|
||||
syncTopbar();renderMessages();highlightCode();loadDir('.');
|
||||
}
|
||||
}
|
||||
// Sync context usage indicator from session data
|
||||
const _s=S.session;
|
||||
if(_s&&typeof _syncCtxIndicator==='function'){
|
||||
const u=S.lastUsage||{};
|
||||
const _pick=(latest,stored,dflt=0)=>latest!=null?latest:(stored!=null?stored:dflt);
|
||||
_syncCtxIndicator({
|
||||
input_tokens: _pick(u.input_tokens, _s.input_tokens),
|
||||
output_tokens: _pick(u.output_tokens, _s.output_tokens),
|
||||
estimated_cost: _pick(u.estimated_cost, _s.estimated_cost),
|
||||
context_length: _pick(u.context_length, _s.context_length),
|
||||
last_prompt_tokens:_pick(u.last_prompt_tokens,_s.last_prompt_tokens),
|
||||
threshold_tokens: _pick(u.threshold_tokens, _s.threshold_tokens),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +165,164 @@ let _showArchived = false; // toggle to show archived sessions
|
||||
let _allProjects = []; // cached project list
|
||||
let _activeProject = null; // project_id filter (null = show all)
|
||||
let _showAllProfiles = false; // false = filter to active profile only
|
||||
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 renderSessionList(){
|
||||
try{
|
||||
@@ -87,6 +337,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
|
||||
|
||||
@@ -107,9 +386,76 @@ function filterSessions(){
|
||||
}, 350);
|
||||
}
|
||||
|
||||
function _sessionTimestampMs(session) {
|
||||
const raw = Number(session && (session.updated_at || session.created_at || 0));
|
||||
return Number.isFinite(raw) ? raw * 1000 : 0;
|
||||
}
|
||||
|
||||
function _localDayOrdinal(timestampMs) {
|
||||
const date = new Date(timestampMs);
|
||||
return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86400000);
|
||||
}
|
||||
|
||||
function _sessionCalendarBoundaries(nowMs = Date.now()) {
|
||||
const now = new Date(nowMs);
|
||||
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const startOfYesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
|
||||
const startOfWeek = new Date(startOfToday);
|
||||
startOfWeek.setDate(startOfWeek.getDate() - ((startOfWeek.getDay() + 6) % 7));
|
||||
const startOfLastWeek = new Date(startOfWeek);
|
||||
startOfLastWeek.setDate(startOfLastWeek.getDate() - 7);
|
||||
return {
|
||||
startOfToday: startOfToday.getTime(),
|
||||
startOfYesterday: startOfYesterday.getTime(),
|
||||
startOfWeek: startOfWeek.getTime(),
|
||||
startOfLastWeek: startOfLastWeek.getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
function _formatSessionDate(timestampMs, nowMs = Date.now()) {
|
||||
const date = new Date(timestampMs);
|
||||
const now = new Date(nowMs);
|
||||
const options = {month:'short', day:'numeric'};
|
||||
if (date.getFullYear() !== now.getFullYear()) options.year = 'numeric';
|
||||
return date.toLocaleDateString(undefined, options);
|
||||
}
|
||||
|
||||
function _formatRelativeSessionTime(timestampMs, nowMs = Date.now()) {
|
||||
if (!timestampMs) return t('session_time_unknown');
|
||||
const diffMs = Math.max(0, nowMs - timestampMs);
|
||||
const minute = 60 * 1000;
|
||||
const hour = 60 * minute;
|
||||
const {startOfToday, startOfYesterday, startOfWeek, startOfLastWeek} = _sessionCalendarBoundaries(nowMs);
|
||||
const dayDiff = Math.max(0, _localDayOrdinal(nowMs) - _localDayOrdinal(timestampMs));
|
||||
if (timestampMs >= startOfToday) {
|
||||
if (diffMs < minute) return t('session_time_just_now');
|
||||
if (diffMs < hour) {
|
||||
const minutes = Math.floor(diffMs / minute);
|
||||
return t('session_time_minutes_ago', minutes);
|
||||
}
|
||||
const hours = Math.floor(diffMs / hour);
|
||||
return t('session_time_hours_ago', hours);
|
||||
}
|
||||
if (timestampMs >= startOfYesterday) return t('session_time_bucket_yesterday');
|
||||
if (timestampMs >= startOfWeek) return t('session_time_days_ago', dayDiff);
|
||||
if (timestampMs >= startOfLastWeek) return t('session_time_last_week');
|
||||
return _formatSessionDate(timestampMs, nowMs);
|
||||
}
|
||||
|
||||
function _sessionTimeBucketLabel(timestampMs, nowMs = Date.now()) {
|
||||
if (!timestampMs) return t('session_time_bucket_older');
|
||||
const {startOfToday, startOfYesterday, startOfWeek, startOfLastWeek} = _sessionCalendarBoundaries(nowMs);
|
||||
if (timestampMs >= startOfToday) return t('session_time_bucket_today');
|
||||
if (timestampMs >= startOfYesterday) return t('session_time_bucket_yesterday');
|
||||
if (timestampMs >= startOfWeek) return t('session_time_bucket_this_week');
|
||||
if (timestampMs >= startOfLastWeek) return t('session_time_bucket_last_week');
|
||||
return t('session_time_bucket_older');
|
||||
}
|
||||
|
||||
function renderSessionListFromCache(){
|
||||
// Don't re-render while user is actively renaming a session (would destroy the input)
|
||||
if(_renamingSid) return;
|
||||
closeSessionActionMenu();
|
||||
const q=($('sessionSearch').value||'').toLowerCase();
|
||||
const titleMatches=q?_allSessions.filter(s=>(s.title||'Untitled').toLowerCase().includes(q)):_allSessions;
|
||||
// Merge content matches (deduped): content matches appended after title matches
|
||||
@@ -192,12 +538,12 @@ function renderSessionListFromCache(){
|
||||
empty.textContent='No sessions in this project yet.';
|
||||
list.appendChild(empty);
|
||||
}
|
||||
const orderedSessions=[...sessions].sort((a,b)=>_sessionTimestampMs(b)-_sessionTimestampMs(a));
|
||||
// Separate pinned from unpinned
|
||||
const pinned=sessions.filter(s=>s.pinned);
|
||||
const unpinned=sessions.filter(s=>!s.pinned);
|
||||
// Date grouping: Pinned / Today / Yesterday / Earlier
|
||||
const pinned=orderedSessions.filter(s=>s.pinned);
|
||||
const unpinned=orderedSessions.filter(s=>!s.pinned);
|
||||
// Date grouping: Pinned / Today / Yesterday / This week / Last week / Older
|
||||
const now=Date.now();
|
||||
const ONE_DAY=86400000;
|
||||
// Collapse state persisted in localStorage
|
||||
let _groupCollapsed={};
|
||||
try{_groupCollapsed=JSON.parse(localStorage.getItem('hermes-date-groups-collapsed')||'{}');}catch(e){}
|
||||
@@ -207,8 +553,8 @@ function renderSessionListFromCache(){
|
||||
let curLabel=null,curItems=[];
|
||||
if(pinned.length) groups.push({label:'\u2605 Pinned',items:pinned,isPinned:true});
|
||||
for(const s of unpinned){
|
||||
const ts=(s.updated_at||s.created_at||0)*1000;
|
||||
const label=ts>now-ONE_DAY?'Today':ts>now-2*ONE_DAY?'Yesterday':'Earlier';
|
||||
const ts=_sessionTimestampMs(s);
|
||||
const label=_sessionTimeBucketLabel(ts, now);
|
||||
if(label!==curLabel){
|
||||
if(curItems.length) groups.push({label:curLabel,items:curItems});
|
||||
curLabel=label;curItems=[s];
|
||||
@@ -247,15 +593,26 @@ function renderSessionListFromCache(){
|
||||
function _renderOneSession(s){
|
||||
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':'');
|
||||
el.className='session-item'+(isActive?' active':'')+(isActive&&S.session&&S.session._flash?' new-flash':'')+(s.archived?' archived':'');
|
||||
if(isActive&&S.session&&S.session._flash)delete S.session._flash;
|
||||
const rawTitle=s.title||'Untitled';
|
||||
const tags=(rawTitle.match(/#[\w-]+/g)||[]);
|
||||
const cleanTitle=tags.length?rawTitle.replace(/#[\w-]+/g,'').trim():rawTitle;
|
||||
let cleanTitle=tags.length?rawTitle.replace(/#[\w-]+/g,'').trim():rawTitle;
|
||||
// Guard: system prompt content must never surface as a visible session title
|
||||
if(cleanTitle.startsWith('[SYSTEM:')){
|
||||
cleanTitle='Session';
|
||||
}
|
||||
const sessionText=document.createElement('div');
|
||||
sessionText.className='session-text';
|
||||
const titleRow=document.createElement('div');
|
||||
titleRow.className='session-title-row';
|
||||
const title=document.createElement('span');
|
||||
title.className='session-title';
|
||||
title.textContent=cleanTitle||'Untitled';
|
||||
title.title='Double-click to rename';
|
||||
const tsMs=_sessionTimestampMs(s);
|
||||
titleRow.appendChild(title);
|
||||
sessionText.appendChild(titleRow);
|
||||
// Append tag chips after the title text
|
||||
for(const tag of tags){
|
||||
const chip=document.createElement('span');
|
||||
@@ -272,6 +629,7 @@ function renderSessionListFromCache(){
|
||||
|
||||
// Rename: called directly when we confirm it's a double-click
|
||||
const startRename=()=>{
|
||||
closeSessionActionMenu();
|
||||
_renamingSid = s.session_id;
|
||||
const inp=document.createElement('input');
|
||||
inp.className='session-title-input';
|
||||
@@ -294,7 +652,12 @@ function renderSessionListFromCache(){
|
||||
setTimeout(()=>{ if(_renamingSid===null) renderSessionListFromCache(); },50);
|
||||
};
|
||||
inp.onkeydown=e2=>{
|
||||
if(e2.key==='Enter'){e2.preventDefault();e2.stopPropagation();finish(true);}
|
||||
if(e2.key==='Enter'){
|
||||
if(e2.isComposing){return;}
|
||||
e2.preventDefault();
|
||||
e2.stopPropagation();
|
||||
finish(true);
|
||||
}
|
||||
if(e2.key==='Escape'){e2.preventDefault();e2.stopPropagation();finish(false);}
|
||||
};
|
||||
// onblur: cancel only -- no accidental saves
|
||||
@@ -310,11 +673,10 @@ function renderSessionListFromCache(){
|
||||
pinInd.innerHTML=ICONS.pin;
|
||||
el.appendChild(pinInd);
|
||||
}
|
||||
// Project indicator: colored left border (active item keeps its own gold color)
|
||||
// Project indicator: colored dot appended after the title
|
||||
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)';
|
||||
const dot=document.createElement('span');
|
||||
dot.className='session-project-dot';
|
||||
dot.style.background=proj.color||'var(--blue)';
|
||||
@@ -322,66 +684,23 @@ function renderSessionListFromCache(){
|
||||
title.appendChild(dot);
|
||||
}
|
||||
}
|
||||
el.appendChild(title);
|
||||
// Action buttons overlay (appears on hover with gradient fade)
|
||||
el.appendChild(sessionText);
|
||||
// Single trigger button that opens a shared dropdown menu
|
||||
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 +736,12 @@ function renderSessionListFromCache(){
|
||||
}
|
||||
|
||||
async function deleteSession(sid){
|
||||
if(!confirm('Delete this conversation?'))return;
|
||||
const ok=await showConfirmDialog({
|
||||
message:'Delete this conversation?',
|
||||
confirmLabel:t('delete_title'),
|
||||
danger:true
|
||||
});
|
||||
if(!ok)return;
|
||||
try{
|
||||
await api('/api/session/delete',{method:'POST',body:JSON.stringify({session_id:sid})});
|
||||
}catch(e){setStatus(`Delete failed: ${e.message}`);return;}
|
||||
@@ -429,7 +753,7 @@ async function deleteSession(sid){
|
||||
if(remaining.sessions&&remaining.sessions.length){
|
||||
await loadSession(remaining.sessions[0].session_id);
|
||||
}else{
|
||||
$('topbarTitle').textContent='Hermes';
|
||||
$('topbarTitle').textContent=window._botName||'Hermes';
|
||||
$('topbarMeta').textContent='Start a new conversation';
|
||||
$('msgInner').innerHTML='';
|
||||
$('emptyState').style.display='';
|
||||
@@ -492,8 +816,11 @@ function _showProjectPicker(session, anchorEl){
|
||||
createItem.onclick=async()=>{
|
||||
picker.remove();
|
||||
document.removeEventListener('click',close);
|
||||
// Prompt for name inline
|
||||
const name=prompt('Project name:');
|
||||
const name=await showPromptDialog({
|
||||
message:t('project_name_prompt'),
|
||||
confirmLabel:t('create'),
|
||||
placeholder:'Project name'
|
||||
});
|
||||
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})});
|
||||
@@ -547,7 +874,11 @@ function _startProjectCreate(bar, addBtn){
|
||||
}
|
||||
};
|
||||
inp.onkeydown=(e)=>{
|
||||
if(e.key==='Enter'){e.preventDefault();finish(true);}
|
||||
if(e.key==='Enter'){
|
||||
if(e.isComposing){return;}
|
||||
e.preventDefault();
|
||||
finish(true);
|
||||
}
|
||||
if(e.key==='Escape'){e.preventDefault();finish(false);}
|
||||
};
|
||||
inp.onblur=()=>finish(false);
|
||||
@@ -569,7 +900,11 @@ function _startProjectRename(proj, chip){
|
||||
}
|
||||
};
|
||||
inp.onkeydown=(e)=>{
|
||||
if(e.key==='Enter'){e.preventDefault();finish(true);}
|
||||
if(e.key==='Enter'){
|
||||
if(e.isComposing){return;}
|
||||
e.preventDefault();
|
||||
finish(true);
|
||||
}
|
||||
if(e.key==='Escape'){e.preventDefault();finish(false);}
|
||||
};
|
||||
inp.onblur=()=>finish(false);
|
||||
@@ -579,11 +914,14 @@ function _startProjectRename(proj, chip){
|
||||
}
|
||||
|
||||
async function _confirmDeleteProject(proj){
|
||||
if(!confirm('Delete project "'+proj.name+'"? Sessions will be unassigned but not deleted.')){return;}
|
||||
const ok=await showConfirmDialog({
|
||||
message:'Delete project "'+proj.name+'"? Sessions will be unassigned but not deleted.',
|
||||
confirmLabel:t('delete_title'),
|
||||
danger:true
|
||||
});
|
||||
if(!ok){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();
|
||||
showToast('Project deleted');
|
||||
}
|
||||
|
||||
|
||||
|
||||
707
static/style.css
707
static/style.css
@@ -2,10 +2,181 @@
|
||||
:root {
|
||||
--bg:#1a1a2e;--sidebar:#16213e;--border:rgba(255,255,255,0.08);--border2:rgba(255,255,255,0.14);
|
||||
--text:#e8e8f0;--muted:#8888aa;--accent:#e94560;--blue:#7cb9ff;--gold:#c9a84c;--code-bg:#0d1117;
|
||||
--surface:#1a2535;--topbar-bg:rgba(22,33,62,.98);--main-bg:rgba(26,26,46,0.5);
|
||||
--focus-ring:rgba(124,185,255,.35);--focus-glow:rgba(124,185,255,.08);
|
||||
--input-bg:rgba(255,255,255,.04);--hover-bg:rgba(255,255,255,.06);
|
||||
--strong:#fff;--em:#c9c9e8;--code-text:#f0c27f;--code-inline-bg:rgba(0,0,0,.35);--pre-text:#e2e8f0;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;font-size:14px;line-height:1.6;
|
||||
}
|
||||
/* ── Slate theme ── */
|
||||
:root[data-theme="slate"]{
|
||||
--bg:#2b2d30;--sidebar:#25272b;--border:rgba(255,255,255,0.09);--border2:rgba(255,255,255,0.16);
|
||||
--text:#d4d4d8;--muted:#8a8a9a;--accent:#e06c75;--blue:#82aaff;--gold:#d4a85a;--code-bg:#1e2023;
|
||||
--surface:#2f3134;--topbar-bg:rgba(37,39,43,.98);--main-bg:rgba(43,45,48,0.5);
|
||||
--focus-ring:rgba(130,170,255,.35);--focus-glow:rgba(130,170,255,.08);
|
||||
--strong:#f0f0f3;--em:#b0b0c0;--code-text:#dca06a;--code-inline-bg:rgba(0,0,0,.3);--pre-text:#d0d0d6;
|
||||
}
|
||||
/* ── Light theme ── */
|
||||
:root[data-theme="light"]{
|
||||
--bg:#f0ede8;--sidebar:#e4e0d8;--border:rgba(0,0,0,0.09);--border2:rgba(0,0,0,0.15);
|
||||
--text:#2c2825;--muted:#7a746a;--accent:#b5451b;--blue:#2d6fa3;--gold:#8a6520;--code-bg:#ddd8d0;
|
||||
--surface:#e0dcd4;--topbar-bg:rgba(228,224,216,.98);--main-bg:rgba(240,237,232,0.5);
|
||||
--focus-ring:rgba(45,111,163,.35);--focus-glow:rgba(45,111,163,.1);
|
||||
--input-bg:rgba(0,0,0,.03);--hover-bg:rgba(0,0,0,.05);
|
||||
--strong:#1a1715;--em:#5a544a;--code-text:#8b4513;--code-inline-bg:rgba(0,0,0,.06);--pre-text:#2c2825;
|
||||
}
|
||||
/* #594: app-dialog light theme overrides — base styles use hardcoded dark gradients */
|
||||
:root[data-theme="light"] .app-dialog{
|
||||
background:linear-gradient(180deg,rgba(240,237,232,.99),rgba(228,224,216,.99));
|
||||
border-color:rgba(0,0,0,.12);
|
||||
box-shadow:0 12px 40px rgba(0,0,0,.15);
|
||||
}
|
||||
:root[data-theme="light"] .app-dialog-input{
|
||||
background:rgba(0,0,0,.04);border-color:rgba(0,0,0,.2);
|
||||
}
|
||||
:root[data-theme="light"] .app-dialog-input:focus{
|
||||
border-color:rgba(45,111,163,.5);box-shadow:0 0 0 3px rgba(45,111,163,.12);
|
||||
}
|
||||
:root[data-theme="light"] .app-dialog-close{
|
||||
background:rgba(0,0,0,.04);
|
||||
}
|
||||
:root[data-theme="light"] .app-dialog-close:hover{background:rgba(0,0,0,.09);}
|
||||
:root[data-theme="light"] .app-dialog-btn{background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .app-dialog-btn:hover{background:rgba(0,0,0,.09);}
|
||||
:root[data-theme="light"] .app-dialog-btn.confirm{
|
||||
border-color:rgba(45,111,163,.45);background:rgba(45,111,163,.12);color:var(--blue);
|
||||
}
|
||||
:root[data-theme="light"] .app-dialog-btn.confirm:hover{background:rgba(45,111,163,.2);}
|
||||
:root[data-theme="light"] .file-rename-input{
|
||||
background:rgba(0,0,0,.04);
|
||||
}
|
||||
:root[data-theme="light"] ::-webkit-scrollbar-thumb{background:rgba(0,0,0,.15);}
|
||||
:root[data-theme="light"] ::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,.3);}
|
||||
:root[data-theme="light"] ::selection{background:rgba(45,111,163,.2);}
|
||||
:root[data-theme="light"] *{scrollbar-color:rgba(0,0,0,.15) transparent;}
|
||||
:root[data-theme="light"] .settings-overlay{background:rgba(0,0,0,.3);}
|
||||
/* ── 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;}
|
||||
:root[data-theme="light"] .session-item.active .session-title{color:#1a5a8a;}
|
||||
:root[data-theme="light"] .session-pin-indicator{color:#996b15;}
|
||||
:root[data-theme="light"] .session-date-header.pinned{color:#996b15;}
|
||||
:root[data-theme="light"] .session-actions-trigger.active,
|
||||
:root[data-theme="light"] .session-item.menu-open .session-actions-trigger{background:rgba(45,111,163,.12);border-color:rgba(45,111,163,.22);color:#1a5a8a;}
|
||||
:root[data-theme="light"] .session-action-opt.is-active{background:rgba(45,111,163,.1);}
|
||||
:root[data-theme="light"] .msg-role.user{color:#2d6fa3;}
|
||||
:root[data-theme="light"] .msg-role.assistant{color:#8a6520;}
|
||||
:root[data-theme="light"] .role-icon.user{background:rgba(45,111,163,.12);color:#2d6fa3;border-color:rgba(45,111,163,.25);}
|
||||
:root[data-theme="light"] .role-icon.assistant{background:rgba(138,101,32,.12);color:#8a6520;border-color:rgba(138,101,32,.25);}
|
||||
:root[data-theme="light"] .project-chip{border-color:rgba(0,0,0,.12);background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .project-chip:hover{background:rgba(0,0,0,.08);color:#2c2825;}
|
||||
:root[data-theme="light"] .project-chip.active{background:rgba(45,111,163,.1);color:#1a5a8a;border-color:rgba(45,111,163,.3);}
|
||||
:root[data-theme="light"] .chip{border-color:rgba(0,0,0,.1);background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .chip.model{color:#2d6fa3;border-color:rgba(45,111,163,.3);background:rgba(45,111,163,.08);}
|
||||
:root[data-theme="light"] .new-chat-btn{border-color:rgba(45,111,163,.25);color:#2d6fa3;}
|
||||
:root[data-theme="light"] .new-chat-btn:hover{background:rgba(45,111,163,.08);}
|
||||
:root[data-theme="light"] .session-search input{border-color:rgba(0,0,0,.1);background:rgba(0,0,0,.03);}
|
||||
:root[data-theme="light"] .session-search input:focus{border-color:rgba(45,111,163,.4);background:rgba(0,0,0,.02);}
|
||||
:root[data-theme="light"] .cron-item{border-color:rgba(0,0,0,.08);background:rgba(0,0,0,.02);}
|
||||
:root[data-theme="light"] .sm-btn{border-color:rgba(0,0,0,.1);}
|
||||
:root[data-theme="light"] .sm-btn:hover{background:rgba(0,0,0,.06);border-color:rgba(0,0,0,.15);}
|
||||
:root[data-theme="light"] select{border-color:rgba(0,0,0,.12);}
|
||||
:root[data-theme="light"] .composer-box{border-color:rgba(0,0,0,.12);}
|
||||
:root[data-theme="light"] .composer-box:focus-within{border-color:rgba(45,111,163,.5);box-shadow:0 0 0 3px rgba(45,111,163,.08);}
|
||||
:root[data-theme="light"] .suggestion{border-color:rgba(0,0,0,.08);}
|
||||
:root[data-theme="light"] .suggestion:hover{background:rgba(45,111,163,.06);border-color:rgba(45,111,163,.2);}
|
||||
:root[data-theme="light"] .tool-card{border-color:rgba(0,0,0,.08);}
|
||||
:root[data-theme="light"] .tool-card:hover{border-color:rgba(0,0,0,.15);}
|
||||
:root[data-theme="light"] .icon-btn:hover{background:rgba(0,0,0,.06);}
|
||||
:root[data-theme="light"] .panel-icon-btn:hover{background:rgba(0,0,0,.06);}
|
||||
:root[data-theme="light"] .file-item:hover{background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .preview-md th{background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .msg-body th{background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .preview-md td{border-color:rgba(0,0,0,.08);}
|
||||
:root[data-theme="light"] .msg-body td{border-color:rgba(0,0,0,.08);}
|
||||
:root[data-theme="light"] .preview-badge.code{background:rgba(0,0,0,.05);}
|
||||
:root[data-theme="light"] .ctx-ring-center{background:var(--bg);color:#5a544a;}
|
||||
:root[data-theme="light"] .ctx-ring-track{stroke:rgba(0,0,0,.12);}
|
||||
:root[data-theme="light"] .ws-opt:hover{background:rgba(0,0,0,.05);}
|
||||
:root[data-theme="light"] .profile-opt:hover{background:rgba(0,0,0,.05);}
|
||||
:root[data-theme="light"] .profile-opt.active{background:rgba(45,111,163,.06);}
|
||||
:root[data-theme="light"] .profile-chip{color:#7a5a90!important;}
|
||||
/* ── Light theme: Prism syntax token overrides (prism-tomorrow is dark-only) ── */
|
||||
:root[data-theme="light"] .token.comment,
|
||||
:root[data-theme="light"] .token.prolog,
|
||||
:root[data-theme="light"] .token.doctype,
|
||||
:root[data-theme="light"] .token.cdata{color:#7a7060;font-style:italic;}
|
||||
:root[data-theme="light"] .token.punctuation{color:#5a4e44;}
|
||||
:root[data-theme="light"] .token.namespace{opacity:.8;}
|
||||
:root[data-theme="light"] .token.property,
|
||||
:root[data-theme="light"] .token.tag,
|
||||
:root[data-theme="light"] .token.boolean,
|
||||
:root[data-theme="light"] .token.number,
|
||||
:root[data-theme="light"] .token.constant,
|
||||
:root[data-theme="light"] .token.symbol,
|
||||
:root[data-theme="light"] .token.deleted{color:#a0290a;}
|
||||
:root[data-theme="light"] .token.selector,
|
||||
:root[data-theme="light"] .token.attr-name,
|
||||
:root[data-theme="light"] .token.string,
|
||||
:root[data-theme="light"] .token.char,
|
||||
:root[data-theme="light"] .token.builtin,
|
||||
:root[data-theme="light"] .token.inserted{color:#276b30;}
|
||||
:root[data-theme="light"] .token.operator,
|
||||
:root[data-theme="light"] .token.entity,
|
||||
:root[data-theme="light"] .token.url,
|
||||
:root[data-theme="light"] .language-css .token.string,
|
||||
:root[data-theme="light"] .style .token.string{color:#5a3e8a;}
|
||||
:root[data-theme="light"] .token.atrule,
|
||||
:root[data-theme="light"] .token.attr-value,
|
||||
:root[data-theme="light"] .token.keyword{color:#2d6fa3;}
|
||||
:root[data-theme="light"] .token.function,
|
||||
:root[data-theme="light"] .token.class-name{color:#7a3a00;}
|
||||
:root[data-theme="light"] .token.regex,
|
||||
:root[data-theme="light"] .token.important,
|
||||
:root[data-theme="light"] .token.variable{color:#8a4a00;}
|
||||
:root[data-theme="light"] .token.important,
|
||||
:root[data-theme="light"] .token.bold{font-weight:bold;}
|
||||
:root[data-theme="light"] .token.italic{font-style:italic;}
|
||||
:root[data-theme="light"] .nav-tab:hover::after{background:var(--surface);border-color:rgba(45,111,163,.25);color:#2d6fa3;}
|
||||
:root[data-theme="light"] .cron-status.disabled{background:rgba(0,0,0,.05);}
|
||||
:root[data-theme="light"] .cron-btn{background:rgba(0,0,0,.04);}
|
||||
:root[data-theme="light"] .cron-btn:hover{background:rgba(0,0,0,.08);}
|
||||
/* ── Solarized Dark theme ── */
|
||||
:root[data-theme="solarized"]{
|
||||
--bg:#002b36;--sidebar:#073642;--border:rgba(255,255,255,0.08);--border2:rgba(255,255,255,0.13);
|
||||
--text:#839496;--muted:#657b83;--accent:#dc322f;--blue:#268bd2;--gold:#b58900;--code-bg:#073642;
|
||||
--surface:#0a3c48;--topbar-bg:rgba(7,54,66,.98);--main-bg:rgba(0,43,54,0.5);
|
||||
--focus-ring:rgba(38,139,210,.35);--focus-glow:rgba(38,139,210,.08);
|
||||
--strong:#fdf6e3;--em:#93a1a1;--code-text:#cb4b16;--code-inline-bg:rgba(0,0,0,.25);--pre-text:#93a1a1;
|
||||
}
|
||||
/* ── Monokai theme ── */
|
||||
:root[data-theme="monokai"]{
|
||||
--bg:#272822;--sidebar:#1e1f1c;--border:rgba(255,255,255,0.07);--border2:rgba(255,255,255,0.12);
|
||||
--text:#f8f8f2;--muted:#75715e;--accent:#f92672;--blue:#66d9e8;--gold:#e6db74;--code-bg:#1e1f1c;
|
||||
--surface:#2d2e28;--topbar-bg:rgba(30,31,28,.98);--main-bg:rgba(39,40,34,0.5);
|
||||
--focus-ring:rgba(102,217,232,.35);--focus-glow:rgba(102,217,232,.08);
|
||||
--strong:#f8f8f0;--em:#a6a28c;--code-text:#e6db74;--code-inline-bg:rgba(0,0,0,.3);--pre-text:#f8f8f2;
|
||||
}
|
||||
/* ── Nord theme ── */
|
||||
:root[data-theme="nord"]{
|
||||
--bg:#2e3440;--sidebar:#272c36;--border:rgba(255,255,255,0.07);--border2:rgba(255,255,255,0.12);
|
||||
--text:#eceff4;--muted:#9099aa;--accent:#bf616a;--blue:#81a1c1;--gold:#ebcb8b;--code-bg:#272c36;
|
||||
--surface:#333a47;--topbar-bg:rgba(39,44,54,.98);--main-bg:rgba(46,52,64,0.5);
|
||||
--focus-ring:rgba(129,161,193,.35);--focus-glow:rgba(129,161,193,.08);
|
||||
--strong:#eceff4;--em:#b8c0cc;--code-text:#a3be8c;--code-inline-bg:rgba(0,0,0,.2);--pre-text:#d8dee9;
|
||||
}
|
||||
/* ── OLED theme ── */
|
||||
:root[data-theme="oled"]{
|
||||
--bg:#000000;--sidebar:#000000;--border:rgba(255,255,255,0.06);--border2:rgba(255,255,255,0.12);
|
||||
--text:#e0e0e0;--muted:#777777;--accent:#ff3b5c;--blue:#6cb4ff;--gold:#d4a74a;--code-bg:#080808;
|
||||
--surface:#0a0a0a;--topbar-bg:rgba(0,0,0,.98);--main-bg:rgba(0,0,0,0.5);
|
||||
--focus-ring:rgba(108,180,255,.3);--focus-glow:rgba(108,180,255,.06);
|
||||
--strong:#ffffff;--em:#c0c0d0;--code-text:#e8b86d;--code-inline-bg:rgba(255,255,255,.06);--pre-text:#d0d0d8;
|
||||
--input-bg:rgba(255,255,255,.03);--hover-bg:rgba(255,255,255,.05);
|
||||
}
|
||||
body{background:var(--bg);color:var(--text);height:100vh;height:100dvh;overflow:hidden;display:flex;}
|
||||
.layout{display:flex;width:100%;height:100vh;height:100dvh;}
|
||||
.layout{display:flex;width:100%;height:100vh;height:100dvh;min-height:0;}
|
||||
.sidebar{width:300px;background:var(--sidebar);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:visible;flex-shrink:0;}
|
||||
.sidebar-header{padding:16px 18px 14px;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:10px;}
|
||||
.logo{width:32px;height:32px;border-radius:9px;background:linear-gradient(145deg,#e8a030,var(--accent));display:flex;align-items:center;justify-content:center;font-weight:800;font-size:14px;color:#fff;flex-shrink:0;box-shadow:0 2px 8px rgba(233,69,96,.3);}
|
||||
@@ -15,24 +186,37 @@
|
||||
.new-chat-btn:hover{background:rgba(124,185,255,0.13);border-color:rgba(124,185,255,.3);}
|
||||
.session-list{flex:1;overflow-y:auto;padding:0 8px 8px;min-height:0;}
|
||||
.session-search{padding:4px 10px 8px;flex-shrink:0;}
|
||||
.session-search input{width:100%;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:8px;color:var(--text);padding:7px 12px;font-size:12px;outline:none;transition:all .15s;}
|
||||
.session-search input:focus{border-color:rgba(124,185,255,.35);background:rgba(255,255,255,.06);box-shadow:0 0 0 2px rgba(124,185,255,.07);}
|
||||
.session-search input{width:100%;background:var(--input-bg);border:1px solid var(--border);border-radius:8px;color:var(--text);padding:10px 12px;font-size:12px;outline:none;transition:all .15s;}
|
||||
.session-search input:focus{border-color:rgba(124,185,255,.35);background:var(--hover-bg);box-shadow:0 0 0 2px rgba(124,185,255,.07);}
|
||||
.session-search input::placeholder{color:var(--muted);opacity:.7;}
|
||||
/* Inline session title edit */
|
||||
.session-title-input{flex:1;background:rgba(20,32,60,.9);border:1px solid rgba(124,185,255,.6);border-radius:6px;color:var(--text);padding:3px 8px;font-size:13px;outline:none;min-width:0;box-shadow:0 0 0 2px rgba(124,185,255,.15);font-family:inherit;}
|
||||
.session-item{padding:8px 10px 8px 8px;border-radius:0 8px 8px 0;cursor:pointer;font-size:13px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background .15s,color .15s,border-color .15s;display:flex;align-items:center;gap:6px;min-width:0;border-left:2px solid transparent;position:relative;}
|
||||
.session-item:hover{background:rgba(255,255,255,0.06);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-title-input{flex:1;background:var(--surface);border:1px solid rgba(124,185,255,.6);border-radius:6px;color:var(--text);padding:3px 8px;font-size:13px;outline:none;min-width:0;box-shadow:0 0 0 2px rgba(124,185,255,.15);font-family:inherit;}
|
||||
.session-item{padding:8px 40px 8px 8px;margin-bottom:2px;border-radius:8px;cursor:pointer;font-size:13px;color:var(--muted);transition:background .15s,color .15s;display:flex;align-items:flex-start;gap:8px;min-width:0;position:relative;}
|
||||
.session-item:hover{background:var(--hover-bg);color:var(--text);}
|
||||
.session-item.active{background:rgba(232,160,48,0.12);color:#e8a030;}
|
||||
.session-text{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px;overflow:hidden;}
|
||||
.session-title-row{display:flex;align-items:center;gap:6px;min-width:0;}
|
||||
.session-title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text);}
|
||||
.session-item.active .session-title{color:var(--gold);}
|
||||
.session-time{display:none;}
|
||||
/* ── Session action trigger + dropdown ── */
|
||||
.session-actions{position:absolute;right:6px;top:50%;transform:translateY(-50%);display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .15s ease;}
|
||||
.session-item:hover .session-actions,.session-item:focus-within .session-actions,.session-item.menu-open .session-actions{opacity:1;pointer-events:auto;}
|
||||
.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);}}
|
||||
@@ -43,33 +227,136 @@
|
||||
.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);}
|
||||
.toast{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:rgba(20,30,50,.95);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;}
|
||||
.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);}
|
||||
.reconnect-banner{display:none;background:#1a2535;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;}
|
||||
.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-oauth-card{display:flex;align-items:flex-start;gap:14px;padding:16px 18px;border-radius:14px;border:1px solid var(--border);background:rgba(255,255,255,.03);margin-bottom:4px;}
|
||||
.onboarding-oauth-card p{margin:6px 0 0;font-size:13px;color:var(--muted);line-height:1.5;}
|
||||
.onboarding-oauth-card strong{font-size:13px;color:var(--text);}
|
||||
.onboarding-oauth-card code{font-size:12px;background:rgba(255,255,255,.08);padding:1px 5px;border-radius:4px;}
|
||||
.onboarding-oauth-icon{font-size:18px;flex-shrink:0;margin-top:1px;}
|
||||
.onboarding-oauth-ready{border-color:rgba(124,185,255,.28);background:rgba(124,185,255,.08);}
|
||||
.onboarding-oauth-ready .onboarding-oauth-icon{color:#7cb9ff;}
|
||||
.onboarding-oauth-pending{border-color:rgba(201,168,76,.25);background:rgba(201,168,76,.08);}
|
||||
.onboarding-oauth-pending .onboarding-oauth-icon{color:#c9a84c;}
|
||||
.onboarding-actions{display:flex;justify-content:space-between;gap:10px;margin-top:auto;}
|
||||
.onboarding-actions .sm-btn{padding:10px 16px;}
|
||||
.reconnect-banner{display:none;background:var(--surface);border:1px solid rgba(201,168,76,0.4);border-radius:10px;padding:10px 16px;margin:10px auto;max-width:780px;font-size:13px;color:var(--gold);display:none;align-items:center;justify-content:space-between;gap:12px;}
|
||||
.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;}
|
||||
.reconnect-btn{padding:6px 12px;border-radius:8px;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;}
|
||||
.reconnect-btn:hover{background:rgba(201,168,76,0.25);}
|
||||
/* ── Update banner ── */
|
||||
.update-banner{display:none;background:var(--surface);border:1px solid rgba(124,185,255,0.4);border-radius:10px;padding:10px 16px;margin:10px auto;max-width:780px;font-size:13px;color:var(--blue);align-items:center;justify-content:space-between;gap:12px;}
|
||||
.update-banner.visible{display:flex;}
|
||||
.update-btn{padding:6px 12px;border-radius:8px;font-size:12px;font-weight:600;background:rgba(124,185,255,0.1);border:1px solid rgba(124,185,255,0.3);color:var(--blue);cursor:pointer;transition:background .15s;}
|
||||
.update-btn:hover{background:rgba(124,185,255,0.2);}
|
||||
.update-primary{background:rgba(124,185,255,0.2);border-color:rgba(124,185,255,0.5);}
|
||||
.update-btn:disabled{opacity:0.5;cursor:not-allowed;}
|
||||
/* ── Approval card ── */
|
||||
.approval-card{display:none;max-width:780px;margin:0 auto 0;padding:0 20px 12px;}
|
||||
.approval-card.visible{display:block;}
|
||||
.approval-inner{background:rgba(20,30,50,.95);backdrop-filter:blur(8px);border:1px solid rgba(233,69,96,0.35);border-radius:14px;padding:14px 16px;}
|
||||
.approval-inner{background:var(--surface);backdrop-filter:blur(8px);border:1px solid rgba(233,69,96,0.35);border-radius:14px;padding:16px 18px;}
|
||||
.approval-header{display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:13px;font-weight:600;color:#e94560;}
|
||||
.approval-desc{font-size:12px;color:var(--muted);margin-bottom:8px;}
|
||||
.approval-cmd{background:var(--code-bg);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:8px 12px;font-family:"SF Mono",ui-monospace,monospace;font-size:12px;color:#e2e8f0;white-space:pre-wrap;word-break:break-all;margin-bottom:12px;max-height:120px;overflow-y:auto;}
|
||||
.approval-btns{display:flex;gap:8px;flex-wrap:wrap;}
|
||||
.approval-btn{padding:6px 14px;border-radius:8px;font-size:12px;font-weight:600;border:1px solid var(--border2);background:rgba(255,255,255,0.06);color:var(--text);cursor:pointer;transition:all .15s;}
|
||||
.approval-btn:hover{background:rgba(255,255,255,0.12);}
|
||||
.approval-btn.once{border-color:rgba(124,185,255,0.5);color:var(--blue);}
|
||||
.approval-btn.once:hover{background:rgba(124,185,255,0.15);}
|
||||
.approval-btn.session{border-color:rgba(124,185,255,0.3);color:var(--blue);}
|
||||
.approval-desc{font-size:12px;color:var(--muted);margin-bottom:8px;line-height:1.5;}
|
||||
.approval-cmd{background:var(--code-bg);border:1px solid var(--border);border-radius:8px;padding:8px 12px;font-family:"SF Mono",ui-monospace,monospace;font-size:12px;color:var(--pre-text);white-space:pre-wrap;word-break:break-all;margin-bottom:14px;max-height:120px;overflow-y:auto;}
|
||||
.approval-btns{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}
|
||||
.approval-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;font-size:12px;font-weight:600;border:1px solid var(--border2);background:var(--hover-bg);color:var(--text);cursor:pointer;transition:all .15s;white-space:nowrap;}
|
||||
.approval-btn:hover{background:rgba(255,255,255,0.12);transform:translateY(-1px);box-shadow:0 2px 8px rgba(0,0,0,0.2);}
|
||||
.approval-btn:active{transform:translateY(0);box-shadow:none;}
|
||||
.approval-btn:disabled{opacity:.5;cursor:not-allowed;transform:none;}
|
||||
.approval-btn-icon{font-size:13px;line-height:1;}
|
||||
.approval-btn-label{line-height:1;}
|
||||
.approval-kbd{display:inline-flex;align-items:center;justify-content:center;padding:1px 5px;border-radius:4px;font-size:10px;font-family:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.15);color:var(--muted);line-height:1.4;margin-left:2px;}
|
||||
.approval-btn.once{border-color:rgba(124,185,255,0.6);color:var(--blue);background:rgba(124,185,255,0.08);}
|
||||
.approval-btn.once:hover{background:rgba(124,185,255,0.18);border-color:rgba(124,185,255,0.8);}
|
||||
.approval-btn.session{border-color:rgba(124,185,255,0.35);color:var(--blue);}
|
||||
.approval-btn.session:hover{background:rgba(124,185,255,0.12);border-color:rgba(124,185,255,0.55);}
|
||||
.approval-btn.always{border-color:rgba(201,168,76,0.5);color:var(--gold);}
|
||||
.approval-btn.always:hover{background:rgba(201,168,76,0.12);border-color:rgba(201,168,76,0.7);}
|
||||
.approval-btn.deny{border-color:rgba(233,69,96,0.5);color:var(--accent);}
|
||||
.approval-btn.deny:hover{background:rgba(233,69,96,0.12);}
|
||||
.approval-btn.deny:hover{background:rgba(233,69,96,0.12);border-color:rgba(233,69,96,0.7);}
|
||||
.approval-btn.loading{opacity:.7;cursor:wait;}
|
||||
/* ── Clarify card ── */
|
||||
.clarify-card{display:none;max-width:680px;margin:4px 0 2px 40px;padding:0;}
|
||||
.clarify-card.visible{display:block;}
|
||||
.clarify-inner{background:rgba(255,255,255,.03);backdrop-filter:blur(8px);border:1px solid rgba(124,185,255,0.16);border-radius:12px;padding:12px 14px 13px;box-shadow:0 1px 0 rgba(255,255,255,.02) inset;}
|
||||
.clarify-header{display:flex;align-items:center;gap:8px;margin-bottom:10px;font-size:12px;font-weight:700;color:var(--blue);letter-spacing:.01em;}
|
||||
.clarify-question{font-size:14px;color:var(--text);line-height:1.7;white-space:pre-wrap;margin-bottom:12px;}
|
||||
.clarify-choices{display:flex;flex-direction:column;gap:8px;margin-bottom:12px;}
|
||||
.clarify-choice{display:flex;align-items:flex-start;gap:10px;width:100%;padding:11px 14px;border-radius:12px;font-size:13px;font-weight:600;border:1px solid rgba(124,185,255,0.3);background:rgba(124,185,255,0.08);color:var(--blue);cursor:pointer;transition:all .15s;white-space:normal;text-align:left;box-shadow:0 1px 0 rgba(255,255,255,.03) inset;}
|
||||
.clarify-choice:hover{background:rgba(124,185,255,0.16);transform:translateY(-1px);box-shadow:0 4px 12px rgba(0,0,0,0.18);}
|
||||
.clarify-choice:focus-visible{outline:2px solid rgba(124,185,255,.75);outline-offset:2px;}
|
||||
.clarify-choice-badge{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;border-radius:999px;background:rgba(124,185,255,0.16);border:1px solid rgba(124,185,255,0.3);color:var(--blue);font-size:11px;font-weight:800;flex-shrink:0;line-height:1;}
|
||||
.clarify-choice-badge.other{background:rgba(201,168,76,0.12);border-color:rgba(201,168,76,0.32);color:var(--gold);}
|
||||
.clarify-choice-text{flex:1;line-height:1.45;min-width:0;}
|
||||
.clarify-choice.other{border-color:rgba(201,168,76,0.35);color:var(--gold);background:rgba(201,168,76,0.08);}
|
||||
.clarify-choice.other:hover{background:rgba(201,168,76,0.14);border-color:rgba(201,168,76,0.55);}
|
||||
.clarify-response{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
|
||||
.clarify-input{flex:1;min-width:220px;padding:10px 12px;border-radius:8px;border:1px solid var(--border2);background:var(--input-bg);color:var(--text);font:inherit;outline:none;transition:all .15s;}
|
||||
.clarify-input:focus{border-color:rgba(124,185,255,.5);box-shadow:0 0 0 3px rgba(124,185,255,.08);background:var(--hover-bg);}
|
||||
.clarify-submit{display:inline-flex;align-items:center;justify-content:center;min-width:92px;padding:10px 14px;border-radius:8px;border:1px solid rgba(124,185,255,0.35);background:rgba(124,185,255,0.14);color:var(--blue);font-size:12px;font-weight:700;cursor:pointer;transition:all .15s;white-space:nowrap;}
|
||||
.clarify-submit:hover{background:rgba(124,185,255,0.22);transform:translateY(-1px);}
|
||||
.clarify-submit:disabled{opacity:.6;cursor:not-allowed;transform:none;}
|
||||
.clarify-submit.loading{opacity:.75;cursor:wait;}
|
||||
.clarify-hint{margin-top:8px;font-size:11px;line-height:1.45;color:var(--muted);}
|
||||
.clarify-card.visible .clarify-question{padding-left:1px;}
|
||||
/* Sidebar navigation tabs */
|
||||
.sidebar-nav{display:flex;border-bottom:1px solid var(--border);flex-shrink:0;padding:6px 8px 0;gap:2px;}
|
||||
.nav-tab{flex:1;padding:10px 4px 8px;font-size:20px;text-align:center;cursor:pointer;color:var(--muted);border:none;background:none;transition:color .15s;border-bottom:2px solid transparent;white-space:nowrap;overflow:hidden;position:relative;}
|
||||
.nav-tab:hover{color:var(--text);}
|
||||
.nav-tab:hover::after{content:attr(data-label);position:absolute;bottom:calc(100% + 8px);left:50%;transform:translateX(-50%);background:rgba(15,22,40,.98);border:1px solid rgba(124,185,255,0.3);color:var(--blue);font-size:12px;font-weight:700;letter-spacing:.02em;padding:5px 11px;border-radius:7px;white-space:nowrap;pointer-events:none;z-index:50;box-shadow:0 4px 12px rgba(0,0,0,.3);}
|
||||
.nav-tab:hover::after{content:attr(data-label);position:absolute;bottom:calc(100% + 8px);left:50%;transform:translateX(-50%);background:var(--surface);border:1px solid rgba(124,185,255,0.3);color:var(--blue);font-size:12px;font-weight:700;letter-spacing:.02em;padding:6px 12px;border-radius:8px;white-space:nowrap;pointer-events:none;z-index:50;box-shadow:0 4px 12px rgba(0,0,0,.3);}
|
||||
.nav-tab.active{color:var(--blue);}
|
||||
.nav-tab.active::before{content:'';position:absolute;bottom:0;left:50%;transform:translateX(-50%);width:20px;height:2px;background:var(--blue);border-radius:2px 2px 0 0;}
|
||||
/* Panel content areas (swapped by tab) */
|
||||
@@ -77,16 +364,16 @@
|
||||
.panel-view.active{display:flex;}
|
||||
/* Cron panel */
|
||||
.cron-list{flex:1;overflow-y:auto;padding:8px;}
|
||||
.cron-item{border-radius:10px;border:1px solid rgba(255,255,255,.08);margin-bottom:6px;overflow:hidden;transition:border-color .15s,background .15s;background:rgba(255,255,255,.02);}
|
||||
.cron-item{border-radius:10px;border:1px solid var(--border);margin-bottom:6px;overflow:hidden;transition:border-color .15s,background .15s;background:rgba(255,255,255,.02);}
|
||||
.cron-item:hover{border-color:var(--border2);}
|
||||
.cron-header{display:flex;align-items:center;gap:8px;padding:9px 11px;cursor:pointer;}
|
||||
.cron-header{display:flex;align-items:center;gap:8px;padding:10px 12px;cursor:pointer;}
|
||||
.cron-name{flex:1;font-size:13px;color:var(--text);font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.cron-status{font-size:10px;font-weight:700;padding:2px 7px;border-radius:99px;flex-shrink:0;}
|
||||
.cron-status{font-size:10px;font-weight:700;padding:2px 8px;border-radius:99px;flex-shrink:0;}
|
||||
.cron-status.active{background:rgba(34,197,94,.15);color:#4ade80;}
|
||||
.cron-status.paused{background:rgba(201,168,76,.15);color:var(--gold);}
|
||||
.cron-status.disabled{background:rgba(255,255,255,.07);color:var(--muted);}
|
||||
.cron-status.error{background:rgba(233,69,96,.15);color:var(--accent);}
|
||||
.cron-body{display:none;padding:0 11px 10px;border-top:1px solid var(--border);overflow:hidden;}
|
||||
.cron-body{display:none;padding:0 12px 10px;border-top:1px solid var(--border);overflow:hidden;}
|
||||
.cron-body.open{display:block;}
|
||||
.cron-schedule{font-size:11px;color:var(--muted);margin:8px 0 6px;}
|
||||
.cron-prompt{font-size:11px;color:var(--muted);line-height:1.55;max-height:80px;overflow-y:auto;background:rgba(0,0,0,.2);padding:6px 8px;border-radius:6px;white-space:pre-wrap;margin-bottom:8px;box-sizing:border-box;}
|
||||
@@ -100,14 +387,14 @@
|
||||
.cron-last-header{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);margin-bottom:4px;}
|
||||
/* Skills panel */
|
||||
.skills-search{padding:8px;flex-shrink:0;}
|
||||
.skills-search input{width:100%;background:rgba(255,255,255,.06);border:1px solid var(--border2);border-radius:7px;color:var(--text);padding:6px 10px;font-size:12px;outline:none;}
|
||||
.skills-search input{width:100%;background:var(--hover-bg);border:1px solid var(--border2);border-radius:8px;color:var(--text);padding:8px 10px;font-size:12px;outline:none;}
|
||||
.skills-search input::placeholder{color:var(--muted);}
|
||||
.skills-list{flex:1;overflow-y:auto;padding:0 8px 8px;}
|
||||
.skills-category{margin-bottom:4px;}
|
||||
.skills-cat-header{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);padding:8px 6px 4px;cursor:pointer;display:flex;align-items:center;gap:4px;}
|
||||
.skills-cat-header:hover{color:var(--text);}
|
||||
.skill-item{padding:7px 10px;border-radius:7px;cursor:pointer;font-size:12px;color:var(--muted);display:flex;align-items:flex-start;gap:6px;transition:all .12s;line-height:1.4;}
|
||||
.skill-item:hover{background:rgba(255,255,255,.06);color:var(--text);}
|
||||
.skill-item{padding:8px 10px;border-radius:8px;cursor:pointer;font-size:12px;color:var(--muted);display:flex;align-items:flex-start;gap:6px;transition:all .12s;line-height:1.4;}
|
||||
.skill-item:hover{background:var(--hover-bg);color:var(--text);}
|
||||
.skill-item.active{background:rgba(124,185,255,.1);color:var(--blue);}
|
||||
.skill-name{font-weight:500;flex-shrink:0;}
|
||||
.skill-desc{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;font-size:11px;opacity:.7;}
|
||||
@@ -120,25 +407,50 @@
|
||||
.memory-content p{margin-bottom:6px;}
|
||||
.memory-empty{color:var(--muted);font-size:12px;font-style:italic;}
|
||||
.sidebar-bottom{border-top:1px solid var(--border);padding:12px 14px;flex-shrink:0;position:relative;z-index:10;overflow:visible;}
|
||||
.hermes-launch-btn{width:100%;display:flex;align-items:center;gap:12px;padding:11px 12px;border-radius:12px;border:1px solid var(--border2);background:linear-gradient(180deg,rgba(255,255,255,.05),rgba(255,255,255,.03));color:var(--text);cursor:pointer;transition:background .15s,border-color .15s,transform .15s;text-align:left;}
|
||||
.hermes-launch-btn:hover{background:rgba(255,255,255,.08);border-color:rgba(124,185,255,.28);transform:translateY(-1px);}
|
||||
.hermes-launch-icon{width:32px;height:32px;border-radius:10px;background:linear-gradient(145deg,rgba(124,185,255,.15),rgba(201,168,76,.1));border:1px solid rgba(124,185,255,.2);display:flex;align-items:center;justify-content:center;flex-shrink:0;overflow:hidden;box-shadow:0 4px 16px rgba(124,185,255,.08);}
|
||||
.hermes-launch-icon svg{display:block;width:22px;height:22px;flex-shrink:0;}
|
||||
.hermes-launch-copy{display:flex;flex-direction:column;min-width:0;flex:1;}
|
||||
.hermes-launch-title{font-size:13px;font-weight:700;letter-spacing:.01em;color:var(--text);}
|
||||
.hermes-launch-meta{font-size:11px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||
.hermes-launch-chevron{color:var(--muted);flex-shrink:0;}
|
||||
.field-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:5px;opacity:.8;}
|
||||
select{width:100%;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,.1);border-radius:8px;color:var(--text);padding:7px 28px 7px 10px;font-size:12px;outline:none;appearance:none;margin-bottom:6px;cursor:pointer;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%238888aa' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;}
|
||||
select{width:100%;background:var(--input-bg);border:1px solid var(--border2);border-radius:8px;color:var(--text);padding:8px 28px 8px 10px;font-size:12px;outline:none;appearance:none;margin-bottom:6px;cursor:pointer;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%238888aa' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 10px center;}
|
||||
select:focus{border-color:rgba(124,185,255,.4);box-shadow:0 0 0 2px rgba(124,185,255,.08);}
|
||||
optgroup{color:var(--muted);font-size:11px;font-weight:700;}
|
||||
option{background:#1a1a2e;color:var(--text);padding:6px;}
|
||||
option{background:var(--bg);color:var(--text);padding:6px;}
|
||||
.sidebar-actions{display:flex;gap:6px;}
|
||||
.sm-btn{flex:1;padding:7px 0;border-radius:8px;font-size:11px;font-weight:500;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,.08);color:var(--muted);cursor:pointer;transition:all .15s;text-align:center;letter-spacing:.02em;}
|
||||
.sm-btn{flex:1;padding:8px 0;border-radius:8px;font-size:11px;font-weight:500;background:var(--input-bg);border:1px solid var(--border);color:var(--muted);cursor:pointer;transition:all .15s;text-align:center;letter-spacing:.02em;}
|
||||
.sm-btn:hover{background:rgba(255,255,255,0.09);color:var(--text);border-color:rgba(255,255,255,.15);}
|
||||
.main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0;background:rgba(26,26,46,0.5);}
|
||||
.topbar{padding:12px 20px;border-bottom:1px solid var(--border);background:rgba(22,33,62,.98);backdrop-filter:blur(12px);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;position:relative;z-index:10;}
|
||||
.sm-btn:disabled{opacity:.45;cursor:not-allowed;}
|
||||
.main{flex:1;display:flex;flex-direction:column;overflow:hidden;min-width:0;min-height:0;background:var(--main-bg);}
|
||||
.topbar{padding:12px 20px;border-bottom:1px solid var(--border);background:var(--topbar-bg);backdrop-filter:blur(12px);display:flex;align-items:center;justify-content:space-between;flex-shrink:0;position:relative;z-index:10;}
|
||||
.topbar-title{font-size:15px;font-weight:600;letter-spacing:-.01em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||
.topbar-meta{font-size:11px;color:var(--muted);margin-top:3px;opacity:.75;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
||||
.topbar-chips{display:flex;gap:6px;align-items:center;flex-shrink:0;}
|
||||
.chip{font-size:11px;padding:4px 10px;border-radius:999px;background:rgba(255,255,255,0.05);border:1px solid rgba(255,255,255,.1);color:var(--muted);font-weight:500;}
|
||||
.chip{font-size:11px;padding:4px 10px;border-radius:999px;background:rgba(255,255,255,0.05);border:1px solid var(--border2);color:var(--muted);font-weight:500;}
|
||||
.workspace-toggle-btn{display:inline-flex!important;align-items:center;gap:6px;cursor:pointer;}
|
||||
.workspace-toggle-btn.active{color:var(--blue);border-color:rgba(124,185,255,.35);background:rgba(124,185,255,.1);}
|
||||
.workspace-toggle-btn:disabled{opacity:.38;cursor:not-allowed;}
|
||||
.chip.model{color:var(--blue);border-color:rgba(124,185,255,0.35);background:rgba(124,185,255,0.1);}
|
||||
.messages{flex:1;overflow-y:auto;display:flex;flex-direction:column;min-height:0;position:relative;z-index:0;}
|
||||
.messages-inner{max-width:800px;margin:0 auto;width:100%;padding:20px 24px 32px;display:flex;flex-direction:column;}
|
||||
.messages{flex:1;overflow-y:auto;display:flex;flex-direction:column;min-height:0;position:relative;z-index:0;-webkit-overflow-scrolling:touch;touch-action:pan-y;overscroll-behavior-y:contain;}
|
||||
.messages-inner{margin:0 auto;width:100%;padding:20px 24px 32px;display:flex;flex-direction:column;}
|
||||
@media(min-width:1400px){.messages-inner{max-width:1100px;}}
|
||||
@media(min-width:1800px){.messages-inner{max-width:1200px;}}
|
||||
.msg-row{padding:10px 0;}
|
||||
.msg-row+.msg-row{border-top:none;}
|
||||
/* Bubble layout (issue #336): opt-in chat-bubble look with user messages right-aligned
|
||||
and assistant messages left-aligned. Uses :has() to tag rows by role without JS
|
||||
changes. Full-width by default -- enabled via body.bubble-layout from settings. */
|
||||
body.bubble-layout .msg-row:has(.msg-role.user){align-self:flex-end;max-width:75%;}
|
||||
body.bubble-layout .msg-row:has(.msg-role.user) .msg-body{padding-left:0;padding-right:30px;max-width:none;}
|
||||
body.bubble-layout .msg-row:has(.msg-role.user) .msg-role{flex-direction:row-reverse;}
|
||||
body.bubble-layout .msg-row:has(.msg-role.assistant){align-self:flex-start;max-width:75%;}
|
||||
@media(max-width:700px){
|
||||
body.bubble-layout .msg-row:has(.msg-role.user),
|
||||
body.bubble-layout .msg-row:has(.msg-role.assistant){max-width:92%;}
|
||||
}
|
||||
.msg-role{font-size:12px;font-weight:500;letter-spacing:.01em;margin-bottom:8px;display:flex;align-items:center;gap:8px;}
|
||||
.msg-role.user{color:rgba(124,185,255,0.65);}
|
||||
.msg-role.assistant{color:rgba(201,168,76,0.6);}
|
||||
@@ -150,18 +462,37 @@
|
||||
.msg-body ul,.msg-body ol{margin:6px 0 10px 20px;}.msg-body li{margin-bottom:3px;}
|
||||
.msg-body h1,.msg-body h2,.msg-body h3{margin:16px 0 6px;font-weight:600;}
|
||||
.msg-body h1{font-size:18px;}.msg-body h2{font-size:16px;}.msg-body h3{font-size:14px;}
|
||||
.msg-body strong{color:#fff;font-weight:600;}.msg-body em{color:#c9c9e8;font-style:italic;}
|
||||
.msg-body code{font-family:"SF Mono","Fira Code",ui-monospace,monospace;font-size:12.5px;background:rgba(0,0,0,.35);padding:1px 5px;border-radius:4px;color:#f0c27f;}
|
||||
.msg-body pre{background:var(--code-bg);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:14px 16px;overflow-x:auto;margin:10px 0;}
|
||||
.msg-body pre code{background:none;padding:0;border-radius:0;color:#e2e8f0;font-size:13px;line-height:1.6;}
|
||||
.pre-header{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);padding:8px 16px 8px;background:rgba(255,255,255,.04);border-radius:10px 10px 0 0;border:1px solid rgba(255,255,255,.08);border-bottom:1px solid rgba(255,255,255,.05);display:flex;align-items:center;gap:6px;}
|
||||
.msg-body strong{color:var(--strong);font-weight:600;}.msg-body em{color:var(--em);font-style:italic;}
|
||||
.msg-body code{font-family:"SF Mono","Fira Code",ui-monospace,monospace;font-size:12.5px;background:var(--code-inline-bg);padding:1px 5px;border-radius:4px;color:var(--code-text);}
|
||||
.msg-body pre{background:var(--code-bg);border:1px solid var(--border);border-radius:10px;padding:14px 16px;overflow-x:auto;margin:10px 0;}
|
||||
.msg-body pre code{background:none;padding:0;border-radius:0;color:var(--pre-text);font-size:13px;line-height:1.6;}
|
||||
/* Keep original theme background — prevent prism-tomorrow from overriding --code-bg */
|
||||
.msg-body pre[class*="language-"],.msg-body pre code[class*="language-"]{background:var(--code-bg) !important;}
|
||||
.pre-header{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);padding:8px 16px 8px;background:var(--input-bg);border-radius:10px 10px 0 0;border:1px solid var(--border);border-bottom:1px solid var(--border);display:flex;align-items:center;gap:6px;}
|
||||
.pre-header::before{content:'';width:8px;height:8px;border-radius:50%;background:var(--muted);opacity:.4;}
|
||||
.pre-header+pre{border-radius:0 0 10px 10px;border-top:none;margin-top:0;}
|
||||
.msg-body blockquote{border-left:3px solid var(--blue);padding-left:14px;color:var(--muted);font-style:italic;margin:10px 0;}
|
||||
.msg-body a{color:var(--blue);text-decoration:underline;}
|
||||
.msg-body hr{border:none;border-top:1px solid var(--border);margin:14px 0;}
|
||||
.msg-body table{border-collapse:collapse;width:100%;margin:8px 0;font-size:12px;}
|
||||
.msg-body th{background:rgba(255,255,255,.07);padding:6px 10px;text-align:left;font-weight:600;border:1px solid var(--border2);}
|
||||
.msg-body td{padding:5px 10px;border:1px solid rgba(255,255,255,.06);}
|
||||
.msg-body tr:nth-child(even){background:rgba(255,255,255,.03);}
|
||||
/* #486: inline code inside table cells needs scaled sizing to avoid overflow/clipping */
|
||||
.msg-body td code,.msg-body th code{font-size:0.85em;padding:1px 4px;vertical-align:baseline;}
|
||||
/* KaTeX math rendering */
|
||||
.katex-block{display:block;text-align:center;margin:12px 0;overflow-x:auto;}
|
||||
.katex-inline{display:inline;}
|
||||
.katex-block .katex-html{text-align:center;}
|
||||
.msg-body .katex{font-size:1.1em;}
|
||||
.msg-body .katex-display{margin:8px 0;}
|
||||
.msg-files{display:flex;flex-wrap:wrap;gap:6px;padding-left:30px;margin-bottom:10px;}
|
||||
.msg-file-badge{display:flex;align-items:center;gap:5px;background:rgba(124,185,255,0.1);border:1px solid rgba(124,185,255,0.25);border-radius:6px;padding:4px 9px;font-size:12px;color:var(--blue);}
|
||||
/* MEDIA: inline image rendering (feat #450) */
|
||||
.msg-media-img{display:block;max-width:min(480px,100%);max-height:400px;border-radius:8px;margin:6px 0;cursor:zoom-in;object-fit:contain;border:1px solid var(--border);}
|
||||
.msg-media-img--full{max-width:100%;max-height:none;cursor:zoom-out;}
|
||||
.msg-media-link{display:inline-flex;align-items:center;gap:5px;background:rgba(124,185,255,0.08);border:1px solid rgba(124,185,255,0.2);border-radius:6px;padding:4px 10px;font-size:13px;color:var(--blue);text-decoration:none;}
|
||||
.msg-media-link:hover{background:rgba(124,185,255,0.16);}
|
||||
.thinking{display:flex;align-items:center;gap:5px;color:var(--muted);font-size:13px;padding-left:30px;}
|
||||
.dot{width:6px;height:6px;border-radius:50%;background:var(--blue);opacity:.3;animation:pulse 1.4s ease-in-out infinite;}
|
||||
.dot:nth-child(2){animation-delay:.22s;}.dot:nth-child(3){animation-delay:.44s;}
|
||||
@@ -171,11 +502,11 @@
|
||||
.empty-state h2{font-size:20px;color:var(--text);font-weight:700;letter-spacing:-.02em;}
|
||||
.empty-state p{font-size:14px;text-align:center;max-width:320px;}
|
||||
.suggestion-grid{display:flex;flex-direction:column;gap:8px;margin-top:12px;width:100%;max-width:380px;}
|
||||
.suggestion{padding:11px 14px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,.08);border-radius:10px;font-size:13px;color:var(--muted);cursor:pointer;transition:all .15s;text-align:left;}
|
||||
.suggestion{padding:12px 14px;background:var(--input-bg);border:1px solid var(--border);border-radius:10px;font-size:13px;color:var(--muted);cursor:pointer;transition:all .15s;text-align:left;}
|
||||
.suggestion:hover{background:rgba(124,185,255,0.07);color:var(--text);border-color:rgba(124,185,255,.3);transform:translateX(2px);}
|
||||
/* ── Composer ── */
|
||||
.composer-wrap{border-top:1px solid var(--border);padding:12px 20px 16px;background:var(--bg);flex-shrink:0;}
|
||||
.composer-box{max-width:780px;margin:0 auto;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,.12);border-radius:16px;display:flex;flex-direction:column;transition:border-color .2s,box-shadow .2s;position:relative;}
|
||||
.composer-box{max-width:780px;margin:0 auto;background:var(--input-bg);border:1px solid var(--border2);border-radius:16px;display:flex;flex-direction:column;transition:border-color .2s,box-shadow .2s;position:relative;}
|
||||
.composer-box:focus-within{border-color:rgba(124,185,255,0.5);box-shadow:0 0 0 3px rgba(124,185,255,0.08);}
|
||||
.composer-wrap.drag-over .composer-box{border-color:var(--blue);background:rgba(124,185,255,0.06);}
|
||||
.drop-hint{display:none;position:absolute;inset:0;align-items:center;justify-content:center;background:rgba(124,185,255,0.08);border:2px dashed var(--blue);border-radius:14px;font-size:14px;color:var(--blue);pointer-events:none;z-index:10;flex-direction:column;gap:8px;}
|
||||
@@ -187,16 +518,53 @@
|
||||
.attach-chip button:hover{color:var(--accent);}
|
||||
textarea#msg{width:100%;background:transparent;border:none;outline:none;color:var(--text);font-size:14px;line-height:1.65;padding:12px 16px 6px;resize:none;min-height:44px;max-height:200px;font-family:inherit;}
|
||||
textarea#msg::placeholder{color:var(--muted);}
|
||||
.composer-footer{display:flex;align-items:center;justify-content:space-between;padding:6px 10px 10px;}
|
||||
.composer-left{display:flex;gap:2px;align-items:center;}
|
||||
.composer-footer{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:6px 10px 10px;position:relative;}
|
||||
.composer-left{display:flex;align-items:center;gap:4px;min-width:0;flex:1;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;}
|
||||
.composer-left::-webkit-scrollbar{display:none;}
|
||||
.composer-divider{width:1px;height:16px;background:var(--border);margin:0 3px;flex-shrink:0;}
|
||||
.composer-profile-wrap{position:relative;flex:0 1 auto;min-width:0;}
|
||||
.composer-profile-chip{display:inline-flex;align-items:center;gap:8px;max-width:180px;padding:8px 10px 8px 12px;border-radius:999px;border:1px solid transparent;background-color:transparent;font-weight:500;cursor:pointer;transition:color .15s,background-color .15s,border-color .15s;}
|
||||
.composer-profile-chip:hover{background-color:var(--hover-bg);}
|
||||
.composer-profile-chip.active{background:rgba(168,139,250,.08);border-color:rgba(168,139,250,.22);}
|
||||
.composer-profile-icon,.composer-profile-chevron{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;line-height:1;}
|
||||
.composer-profile-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.composer-ws-wrap{position:relative;flex:0 1 auto;min-width:0;}
|
||||
.composer-workspace-chip{display:inline-flex;align-items:center;gap:8px;max-width:240px;padding:8px 10px 8px 12px;border-radius:999px;border:1px solid transparent;background-color:transparent;color:var(--muted);font-weight:500;cursor:pointer;transition:color .15s,background-color .15s,border-color .15s;}
|
||||
.composer-workspace-chip:hover{color:var(--text);background-color:var(--hover-bg);}
|
||||
.composer-workspace-chip:disabled{opacity:.45;cursor:not-allowed;}
|
||||
.composer-workspace-chip:disabled:hover{color:var(--muted);background-color:transparent;}
|
||||
.composer-workspace-chip.active{color:var(--text);background:rgba(124,185,255,.08);border-color:rgba(124,185,255,.22);}
|
||||
.composer-workspace-icon,.composer-workspace-chevron{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;line-height:1;}
|
||||
.composer-workspace-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.composer-model-wrap{position:relative;flex:0 1 auto;min-width:0;}
|
||||
.composer-model-chip{display:inline-flex;align-items:center;gap:8px;max-width:220px;padding:8px 10px 8px 12px;border-radius:999px;border:1px solid transparent;background-color:transparent;color:var(--muted);font-weight:500;cursor:pointer;transition:color .15s,background-color .15s,border-color .15s;}
|
||||
.composer-model-chip:hover{color:var(--text);background-color:var(--hover-bg);}
|
||||
.composer-model-chip.active{color:var(--text);background:rgba(124,185,255,.08);border-color:rgba(124,185,255,.22);}
|
||||
.composer-model-label{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.composer-model-icon,.composer-model-chevron{display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;line-height:1;}
|
||||
.composer-model-select{position:absolute!important;left:-9999px!important;width:1px!important;height:1px!important;opacity:0!important;pointer-events:none!important;}
|
||||
.composer-right{display:flex;gap:8px;align-items:center;flex-shrink:0;}
|
||||
.composer-status{font-size:11px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:170px;}
|
||||
/* Context usage indicator */
|
||||
.ctx-indicator{display:flex;align-items:center;gap:6px;padding:2px 4px;flex-shrink:1;min-width:0;}
|
||||
.ctx-bar-wrap{width:70px;height:5px;border-radius:3px;background:rgba(255,255,255,.08);overflow:hidden;flex-shrink:0;}
|
||||
.ctx-bar{display:block;height:100%;border-radius:3px;transition:width .4s ease,background .4s ease;min-width:2px;background:var(--blue);}
|
||||
.ctx-bar.ctx-mid{background:#e6a817;}
|
||||
.ctx-bar.ctx-high{background:#e05252;}
|
||||
.ctx-label{font-size:9px;color:var(--muted);white-space:nowrap;font-variant-numeric:tabular-nums;}
|
||||
.composer-right{display:flex;gap:6px;align-items:center;}
|
||||
.ctx-indicator-wrap{position:relative;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;}
|
||||
.ctx-indicator{width:34px;height:34px;padding:0;border:none;background:none;color:var(--muted);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;transition:opacity .15s,transform .15s;}
|
||||
.ctx-indicator:hover{opacity:.88;transform:translateY(-1px);}
|
||||
.ctx-ring{position:relative;display:flex;width:24px;height:24px;align-items:center;justify-content:center;}
|
||||
.ctx-ring-svg{position:absolute;inset:0;width:24px;height:24px;transform:rotate(-90deg);}
|
||||
.ctx-ring-track,.ctx-ring-value{fill:none;stroke-width:3;}
|
||||
.ctx-ring-track{stroke:rgba(255,255,255,.12);}
|
||||
.ctx-ring-value{stroke:var(--muted);stroke-linecap:round;stroke-dasharray:61.261056745;stroke-dashoffset:61.261056745;transition:stroke-dashoffset .45s ease,stroke .25s ease;}
|
||||
.ctx-ring-center{position:relative;display:flex;width:15px;height:15px;align-items:center;justify-content:center;border-radius:999px;background:var(--bg);font-size:8px;font-weight:600;line-height:1;color:var(--muted);font-variant-numeric:tabular-nums;}
|
||||
.ctx-indicator.ctx-mid .ctx-ring-value{stroke:#e6a817;}
|
||||
.ctx-indicator.ctx-high .ctx-ring-value{stroke:#e05252;}
|
||||
.ctx-tooltip{position:absolute;right:0;bottom:calc(100% + 10px);min-width:210px;max-width:250px;padding:10px 12px;border:1px solid var(--border2);border-radius:12px;background:var(--surface);box-shadow:0 12px 30px rgba(0,0,0,.28);font-size:11px;line-height:1.45;color:var(--muted);opacity:0;transform:translateY(4px);pointer-events:none;transition:opacity .14s ease,transform .14s ease;z-index:30;}
|
||||
.ctx-tooltip::after{content:'';position:absolute;right:10px;top:100%;border-width:6px 6px 0 6px;border-style:solid;border-color:var(--surface) transparent transparent transparent;}
|
||||
.ctx-indicator-wrap:hover .ctx-tooltip,.ctx-indicator-wrap:focus-within .ctx-tooltip{opacity:1;transform:translateY(0);}
|
||||
.ctx-tooltip-title{font-size:12px;font-weight:600;color:var(--text);margin-bottom:5px;}
|
||||
.ctx-tooltip-line+.ctx-tooltip-line{margin-top:3px;}
|
||||
.cancel-btn{width:34px;height:34px;border-radius:50%;background:rgba(233,69,96,.88);border:none;color:#fff;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;transition:background .15s,transform .15s,box-shadow .15s;box-shadow:0 2px 10px rgba(233,69,96,.28);}
|
||||
.cancel-btn:hover{background:#e94560;transform:scale(1.06);box-shadow:0 4px 14px rgba(233,69,96,.38);}
|
||||
.cancel-btn:active{transform:scale(.96);}
|
||||
.icon-btn{width:34px;height:34px;border-radius:8px;background:none;border:none;color:var(--muted);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:16px;transition:all .15s;}
|
||||
.icon-btn{opacity:.75;}
|
||||
.icon-btn:hover{background:rgba(255,255,255,.08);color:var(--text);opacity:1;}
|
||||
@@ -212,16 +580,19 @@
|
||||
.send-btn:disabled{opacity:.35;cursor:not-allowed;transform:none;box-shadow:none;}
|
||||
.send-btn.visible{animation:send-pop-in .18s cubic-bezier(.34,1.56,.64,1) forwards;}
|
||||
@keyframes send-pop-in{from{opacity:0;transform:scale(.55);}to{opacity:1;transform:scale(1);}}
|
||||
.upload-bar-wrap{display:none;height:3px;background:rgba(255,255,255,.06);border-radius:0 0 16px 16px;overflow:hidden;}
|
||||
.upload-bar-wrap{display:none;height:3px;background:var(--hover-bg);border-radius:0 0 16px 16px;overflow:hidden;}
|
||||
.upload-bar-wrap.active{display:block;}
|
||||
.upload-bar{height:100%;background:linear-gradient(90deg,var(--blue),#a0d0ff);width:0%;transition:width .3s ease;}
|
||||
.rightpanel{width:300px;background:var(--sidebar);border-left:1px solid rgba(255,255,255,.06);display:flex;flex-direction:column;overflow:hidden;flex-shrink:0;}
|
||||
.rightpanel{width:300px;background:var(--sidebar);border-left:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden;flex-shrink:0;min-width:0;opacity:1;transform:translateX(0);transform-origin:right center;transition:width .24s cubic-bezier(.22,1,.36,1),opacity .18s ease,transform .24s cubic-bezier(.22,1,.36,1),border-color .24s ease;}
|
||||
.panel-header{padding:12px 16px;border-bottom:1px solid var(--border);font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.1em;display:flex;align-items:center;justify-content:space-between;}
|
||||
.git-badge{font-size:9px;font-weight:600;color:var(--muted);background:rgba(255,255,255,.06);padding:2px 7px;border-radius:4px;letter-spacing:.02em;margin-left:auto;margin-right:4px;white-space:nowrap;font-family:'SF Mono',ui-monospace,monospace;}
|
||||
.git-badge{font-size:9px;font-weight:600;color:var(--muted);background:var(--hover-bg);padding:2px 7px;border-radius:4px;letter-spacing:.02em;margin-left:auto;margin-right:4px;white-space:nowrap;font-family:'SF Mono',ui-monospace,monospace;}
|
||||
.git-badge.dirty{color:var(--gold);background:rgba(201,168,76,.1);}
|
||||
.panel-actions{display:flex;gap:4px;}
|
||||
.mobile-close-btn{display:none;}
|
||||
.panel-icon-btn{width:24px;height:24px;background:none;border:none;color:var(--muted);cursor:pointer;border-radius:5px;font-size:13px;display:flex;align-items:center;justify-content:center;transition:all .15s;}
|
||||
.panel-icon-btn:hover{background:rgba(255,255,255,.08);color:var(--text);}
|
||||
.panel-icon-btn:disabled{opacity:.35;cursor:not-allowed;}
|
||||
.panel-icon-btn:disabled:hover{background:none;color:var(--muted);}
|
||||
/* 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;}
|
||||
@@ -231,11 +602,11 @@
|
||||
.breadcrumb-bar{display:flex;align-items:center;gap:2px;padding:6px 12px;font-size:12px;border-bottom:1px solid var(--border);flex-shrink:0;overflow:hidden;white-space:nowrap;}
|
||||
.breadcrumb-seg{padding:1px 3px;border-radius:3px;}
|
||||
.breadcrumb-link{color:var(--muted);cursor:pointer;transition:color .12s;}
|
||||
.breadcrumb-link:hover{color:var(--text);background:rgba(255,255,255,.06);}
|
||||
.breadcrumb-link:hover{color:var(--text);background:var(--hover-bg);}
|
||||
.breadcrumb-current{color:var(--text);font-weight:500;}
|
||||
.breadcrumb-sep{color:var(--border);margin:0 1px;font-size:11px;}
|
||||
.file-tree{flex:1;overflow-y:auto;padding:8px;}
|
||||
.file-item{display:flex;align-items:center;gap:6px;padding:6px 10px;border-radius:7px;cursor:pointer;font-size:12px;color:var(--muted);transition:all .12s;min-width:0;}
|
||||
.file-item{display:flex;align-items:center;gap:6px;padding:6px 10px;border-radius:8px;cursor:pointer;font-size:12px;color:var(--muted);transition:all .12s;min-width:0;}
|
||||
.file-item:hover{background:rgba(255,255,255,.07);color:var(--text);}
|
||||
.file-item.active{background:rgba(124,185,255,.12);color:var(--blue);}
|
||||
.file-tree-toggle{font-size:10px;color:var(--muted);flex-shrink:0;width:10px;text-align:center;line-height:1;}
|
||||
@@ -251,21 +622,25 @@
|
||||
/* Markdown rendered preview */
|
||||
.preview-md{font-size:13px;line-height:1.7;color:var(--text);flex:1;overflow-y:auto;min-height:0;}
|
||||
.preview-md p{margin-bottom:10px;}.preview-md p:last-child{margin-bottom:0;}
|
||||
.preview-md h1{font-size:18px;font-weight:700;margin:16px 0 8px;color:#fff;border-bottom:1px solid var(--border);padding-bottom:6px;}
|
||||
.preview-md h2{font-size:15px;font-weight:600;margin:14px 0 6px;color:#fff;}
|
||||
.preview-md h1{font-size:18px;font-weight:700;margin:16px 0 8px;color:var(--strong);border-bottom:1px solid var(--border);padding-bottom:6px;}
|
||||
.preview-md h2{font-size:15px;font-weight:600;margin:14px 0 6px;color:var(--strong);}
|
||||
.preview-md h3{font-size:13px;font-weight:600;margin:12px 0 4px;color:#e8e8f0;}
|
||||
.preview-md ul,.preview-md ol{margin:4px 0 10px 18px;}.preview-md li{margin-bottom:3px;}
|
||||
.preview-md code{font-family:"SF Mono",ui-monospace,monospace;font-size:11.5px;background:rgba(0,0,0,.35);padding:1px 5px;border-radius:4px;color:#f0c27f;}
|
||||
.preview-md pre{background:var(--code-bg);border:1px solid rgba(255,255,255,.08);border-radius:8px;padding:10px 12px;overflow-x:auto;margin:8px 0;}
|
||||
.preview-md pre code{background:none;padding:0;color:#e2e8f0;font-size:11.5px;line-height:1.55;}
|
||||
.preview-md code{font-family:"SF Mono",ui-monospace,monospace;font-size:11.5px;background:var(--code-inline-bg);padding:1px 5px;border-radius:4px;color:var(--code-text);}
|
||||
.preview-md pre{background:var(--code-bg);border:1px solid var(--border);border-radius:8px;padding:10px 12px;overflow-x:auto;margin:8px 0;}
|
||||
.preview-md pre code{background:none;padding:0;color:var(--pre-text);font-size:11.5px;line-height:1.55;}
|
||||
/* Keep original theme background — prevent prism-tomorrow from overriding --code-bg */
|
||||
.preview-md pre[class*="language-"],.preview-md pre code[class*="language-"]{background:var(--code-bg) !important;}
|
||||
.preview-md blockquote{border-left:3px solid var(--blue);padding-left:12px;color:var(--muted);font-style:italic;margin:8px 0;}
|
||||
.preview-md strong{color:#fff;font-weight:600;}.preview-md em{color:#c9c9e8;}
|
||||
.preview-md strong{color:var(--strong);font-weight:600;}.preview-md em{color:var(--em);}
|
||||
.preview-md a{color:var(--blue);text-decoration:underline;}
|
||||
.preview-md hr{border:none;border-top:1px solid var(--border);margin:12px 0;}
|
||||
.preview-md table{border-collapse:collapse;width:100%;margin:8px 0;font-size:12px;}
|
||||
.preview-md th{background:rgba(255,255,255,.07);padding:6px 10px;text-align:left;font-weight:600;border:1px solid var(--border2);}
|
||||
.preview-md td{padding:5px 10px;border:1px solid rgba(255,255,255,.06);}
|
||||
.preview-md tr:nth-child(even){background:rgba(255,255,255,.03);}
|
||||
/* #486: inline code inside table cells needs scaled sizing to avoid overflow/clipping */
|
||||
.preview-md td code,.preview-md th code{font-size:0.85em;padding:1px 4px;vertical-align:baseline;}
|
||||
/* File type badge in preview path bar */
|
||||
.preview-badge{display:inline-block;font-size:10px;font-weight:600;padding:2px 6px;border-radius:4px;margin-left:8px;text-transform:uppercase;letter-spacing:.06em;}
|
||||
.preview-badge.img{background:rgba(124,185,255,.15);color:var(--blue);}
|
||||
@@ -279,9 +654,17 @@
|
||||
.mobile-hamburger{display:none;}
|
||||
.mobile-files-btn{display:none!important;}
|
||||
.mobile-overlay{display:none;}
|
||||
.mobile-bottom-nav{display:none;}
|
||||
|
||||
@media(max-width:900px){.rightpanel{display:none}.mobile-files-btn{display:inline-flex!important;}}
|
||||
@media(min-width:901px){
|
||||
.layout.workspace-panel-collapsed .rightpanel{width:0 !important;opacity:0;transform:translateX(14px);border-left-color:transparent;pointer-events:none;}
|
||||
}
|
||||
|
||||
@media(max-width:900px){
|
||||
.rightpanel{display:none}
|
||||
.workspace-toggle-btn,.mobile-files-btn{display:inline-flex!important;}
|
||||
.mobile-close-btn{display:flex;}
|
||||
#btnCollapseWorkspacePanel{display:none;}
|
||||
}
|
||||
|
||||
@media(max-width:640px){
|
||||
/* ── Sidebar: slide-in overlay instead of hidden ── */
|
||||
@@ -299,48 +682,53 @@
|
||||
z-index:199;-webkit-tap-highlight-color:transparent;}
|
||||
.mobile-overlay.visible{display:block;}
|
||||
/* Files button in topbar */
|
||||
.mobile-files-btn{display:inline-flex!important;}
|
||||
.workspace-toggle-btn,.mobile-files-btn{display:inline-flex!important;}
|
||||
/* Right panel: slide-over from right */
|
||||
.rightpanel{display:flex!important;position:fixed;right:-320px;top:0;bottom:0;
|
||||
width:300px;z-index:200;transition:right .25s ease;
|
||||
box-shadow:-4px 0 24px rgba(0,0,0,.4);}
|
||||
.rightpanel.mobile-open{right:0;}
|
||||
.rightpanel .resize-handle{display:none;}
|
||||
/* Bottom navigation bar */
|
||||
.mobile-bottom-nav{display:flex;position:fixed;bottom:0;left:0;right:0;
|
||||
background:var(--sidebar);border-top:1px solid var(--border);
|
||||
z-index:150;padding:4px 0 env(safe-area-inset-bottom,0);
|
||||
justify-content:space-around;align-items:center;}
|
||||
.mobile-nav-btn{display:flex;flex-direction:column;align-items:center;gap:2px;
|
||||
background:none;border:none;color:var(--muted);font-size:9px;padding:6px 4px;
|
||||
cursor:pointer;min-width:44px;min-height:44px;justify-content:center;
|
||||
-webkit-tap-highlight-color:transparent;transition:color .15s;}
|
||||
.mobile-nav-btn.active{color:var(--blue);}
|
||||
.mobile-nav-btn:hover{color:var(--text);}
|
||||
.mobile-nav-btn svg{flex-shrink:0;}
|
||||
/* Hide sidebar nav tabs (replaced by bottom nav) */
|
||||
.sidebar-nav{display:none;}
|
||||
/* Hide sidebar bottom section on mobile (model select, workspace) */
|
||||
.sidebar-bottom{display:none;}
|
||||
/* Keep the Hermes control available at the bottom of the mobile sidebar */
|
||||
.sidebar-bottom{display:block;padding:10px;}
|
||||
/* Topbar adjustments */
|
||||
.topbar{padding:8px 12px;gap:8px;}
|
||||
.topbar-title{font-size:14px;}
|
||||
.topbar-meta{display:none;}
|
||||
.topbar-chips{flex-wrap:nowrap;gap:4px;overflow-x:auto;-webkit-overflow-scrolling:touch;}
|
||||
.topbar-chips .chip,.topbar-chips .ws-chip,.topbar-chips button{font-size:11px!important;padding:3px 8px!important;white-space:nowrap;}
|
||||
/* Messages area — account for bottom nav */
|
||||
.messages{padding-bottom:60px;}
|
||||
.topbar-chips .chip,.topbar-chips .ws-chip,.topbar-chips button{font-size:11px!important;padding:4px 8px!important;white-space:nowrap;}
|
||||
.settings-shell{grid-template-columns:1fr;gap:0;}
|
||||
.settings-tabs{flex-direction:row;overflow-x:auto;padding:10px 12px;border-right:none;border-bottom:1px solid var(--border);gap:6px;}
|
||||
.settings-tab{flex-shrink:0;}
|
||||
.settings-main{padding:18px 16px;}
|
||||
.hermes-action-grid{grid-template-columns:1fr;}
|
||||
.messages-inner{padding:12px 10px 20px;}
|
||||
.msg-body{padding-left:0;max-width:100%;}
|
||||
.msg-role{font-size:12px;}
|
||||
/* Composer — above bottom nav */
|
||||
.composer-wrap{padding:8px 10px 12px!important;margin-bottom:56px;}
|
||||
.composer-wrap{padding:8px 10px 12px!important;}
|
||||
.composer-box{border-radius:12px;}
|
||||
.composer-box textarea{font-size:16px;min-height:40px;}
|
||||
.composer-footer{padding:6px 8px 8px!important;gap:8px;}
|
||||
/* icon-only composer chips below 768px */
|
||||
.composer-profile-label,
|
||||
.composer-workspace-label,
|
||||
.composer-model-label,
|
||||
.composer-profile-chevron,
|
||||
.composer-workspace-chevron,
|
||||
.composer-model-chevron{display:none;}
|
||||
.composer-profile-chip,
|
||||
.composer-workspace-chip,
|
||||
.composer-model-chip{max-width:44px;min-width:44px;min-height:44px;padding:6px;justify-content:center;gap:0;font-size:11px;}
|
||||
.composer-divider{display:none;}
|
||||
.composer-status{max-width:96px;font-size:10px;}
|
||||
.send-btn{width:32px;height:32px;}
|
||||
.cancel-btn{width:32px;height:32px;}
|
||||
.ctx-indicator{width:32px;height:32px;}
|
||||
.ctx-tooltip{right:-4px;min-width:190px;max-width:220px;}
|
||||
/* Touch targets — minimum 44px */
|
||||
.icon-btn,.mic-btn{min-width:44px;min-height:44px;}
|
||||
.session-item{min-height:44px;padding:10px 12px;}
|
||||
.session-item{min-height:44px;padding:10px 40px 10px 12px;}
|
||||
.session-actions{opacity:1;pointer-events:auto;}
|
||||
/* Empty state */
|
||||
.empty-state h2{font-size:18px;}
|
||||
.empty-state p{font-size:13px;}
|
||||
@@ -350,18 +738,52 @@
|
||||
.approval-card{padding:0 10px 8px;}
|
||||
.approval-btns{gap:6px;}
|
||||
.approval-btn{padding:8px 12px;font-size:12px;min-height:44px;}
|
||||
.approval-kbd{display:none;}
|
||||
/* Clarify card */
|
||||
.clarify-card{margin:6px 0 4px 0;max-width:100%;}
|
||||
.clarify-inner{padding:12px 12px 13px;}
|
||||
.clarify-response{flex-direction:column;align-items:stretch;}
|
||||
.clarify-input,.clarify-submit{width:100%;min-height:44px;}
|
||||
.clarify-choice{min-height:44px;}
|
||||
.clarify-choice-badge{min-width:22px;height:22px;}
|
||||
.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;}
|
||||
.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 dropdown (topbar) ── */
|
||||
.ws-chip{user-select:none;}
|
||||
.ws-dropdown{display:none;position:absolute;bottom:calc(100% + 4px);left:0;right:0;min-width:200px;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:320px;overflow-y:auto;}
|
||||
.ws-dropdown{display:none;position:absolute;bottom:calc(100% + 4px);left:0;right:0;min-width:200px;background:var(--surface);border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:320px;overflow-y:auto;}
|
||||
.ws-dropdown.open{display:block;}
|
||||
.ws-dropdown-footer{left:0;right:auto;bottom:calc(100% + 4px);min-width:280px;max-width:min(420px,calc(100vw - 32px));}
|
||||
.model-dropdown{display:none;position:absolute;bottom:calc(100% + 4px);left:0;min-width:280px;max-width:min(420px,calc(100vw - 32px));background:var(--surface);border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:320px;overflow-y:auto;}
|
||||
.model-dropdown.open{display:block;}
|
||||
.model-group{padding:8px 14px 4px;font-size:10px;font-weight:700;letter-spacing:.04em;color:var(--muted);text-transform:uppercase;}
|
||||
.model-opt{padding:10px 14px;cursor:pointer;transition:background .12s;display:flex;flex-direction:column;gap:3px;align-items:flex-start;}
|
||||
.model-opt:hover{background:rgba(255,255,255,.07);}
|
||||
.model-opt.active{background:rgba(124,185,255,.1);}
|
||||
.model-opt-name{display:block;font-size:13px;color:var(--text);font-weight:500;line-height:1.25;}
|
||||
.model-opt-id{display:block;font-size:10px;color:var(--muted);line-height:1.3;opacity:.72;word-break:break-word;}
|
||||
.model-custom-sep{padding-top:4px;border-top:1px solid var(--border);margin-top:4px;}
|
||||
.model-custom-row{display:flex;align-items:center;gap:6px;padding:6px 10px 8px;}
|
||||
.model-custom-input{flex:1;background:var(--code-bg);border:1px solid var(--border2);border-radius:6px;color:var(--text);padding:5px 8px;font-size:12px;outline:none;font-family:inherit;min-width:0;}
|
||||
.model-custom-input:focus{border-color:rgba(124,185,255,.5);}
|
||||
.model-custom-btn{flex-shrink:0;width:24px;height:24px;border:1px solid var(--border2);border-radius:6px;background:transparent;color:var(--muted);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:color .12s,border-color .12s;}
|
||||
.model-custom-btn:hover{color:var(--blue);border-color:rgba(124,185,255,.4);}
|
||||
.ws-opt{padding:10px 14px;cursor:pointer;transition:background .12s;display:flex;flex-direction:column;gap:4px;align-items:flex-start;}
|
||||
.ws-opt:hover{background:rgba(255,255,255,.07);}
|
||||
.ws-opt.active{background:rgba(124,185,255,.1);}
|
||||
@@ -369,6 +791,9 @@
|
||||
.ws-opt-path{display:block;font-size:10px;color:var(--muted);line-height:1.3;overflow:hidden;text-overflow:ellipsis;white-space:normal;opacity:.72;word-break:break-word;}
|
||||
.ws-divider{height:1px;background:var(--border);margin:4px 0;}
|
||||
.ws-manage{color:var(--muted);font-size:12px;}
|
||||
.ws-opt-action{display:flex;flex-direction:row;align-items:center;gap:8px;}
|
||||
.ws-opt-icon{display:inline-flex;align-items:center;justify-content:center;opacity:.82;flex-shrink:0;}
|
||||
.ws-opt-meta{font-size:11px;color:var(--muted);}
|
||||
/* ── Workspace management panel ── */
|
||||
.ws-row{display:flex;align-items:center;gap:8px;padding:8px 0;border-bottom:1px solid var(--border);}
|
||||
.ws-row:last-of-type{border-bottom:none;}
|
||||
@@ -376,13 +801,13 @@
|
||||
.ws-row-name{font-size:13px;font-weight:500;color:var(--text);}
|
||||
.ws-row-path{font-size:11px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
.ws-row-actions{display:flex;gap:4px;flex-shrink:0;}
|
||||
.ws-action-btn{padding:4px 9px;border-radius:6px;font-size:11px;font-weight:600;border:1px solid var(--border2);background:rgba(255,255,255,.05);color:var(--muted);cursor:pointer;transition:all .15s;white-space:nowrap;}
|
||||
.ws-action-btn{padding:4px 8px;border-radius:6px;font-size:11px;font-weight:600;border:1px solid var(--border2);background:rgba(255,255,255,.05);color:var(--muted);cursor:pointer;transition:all .15s;white-space:nowrap;}
|
||||
.ws-action-btn:hover{background:rgba(255,255,255,.1);color:var(--text);}
|
||||
/* ── Profile dropdown + management panel ── */
|
||||
.profile-chip{user-select:none;color:rgba(168,139,250,.9)!important;}
|
||||
.profile-dropdown{display:none;position:absolute;top:calc(100% + 6px);right:0;min-width:260px;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:380px;overflow-y:auto;}
|
||||
.profile-dropdown{display:none;position:absolute;bottom:calc(100% + 4px);left:0;min-width:260px;max-width:min(260px,calc(100vw - 32px));background:var(--surface);border:1px solid var(--border2);border-radius:10px;box-shadow:0 -4px 24px rgba(0,0,0,.4);z-index:200;overflow:hidden;max-height:380px;overflow-y:auto;}
|
||||
.profile-dropdown.open{display:block;}
|
||||
.profile-opt{padding:9px 14px;cursor:pointer;transition:background .12s;}
|
||||
.profile-opt{padding:10px 14px;cursor:pointer;transition:background .12s;}
|
||||
.profile-opt:hover{background:rgba(255,255,255,.07);}
|
||||
.profile-opt.active{background:rgba(168,139,250,.08);}
|
||||
.profile-opt-name{font-size:13px;color:var(--text);font-weight:500;}
|
||||
@@ -398,7 +823,7 @@
|
||||
.profile-card-meta{font-size:11px;color:var(--muted);margin-top:3px;padding-left:12px;}
|
||||
.profile-card-actions{display:flex;gap:4px;flex-shrink:0;}
|
||||
/* ── Slash command autocomplete dropdown ── */
|
||||
.cmd-dropdown{display:none;position:absolute;bottom:100%;left:0;right:0;background:#1a2535;border:1px solid var(--border2);border-radius:10px;box-shadow:0 -8px 24px rgba(0,0,0,.4);z-index:200;max-height:240px;overflow-y:auto;margin-bottom:4px;}
|
||||
.cmd-dropdown{display:none;position:absolute;bottom:100%;left:0;right:0;background:var(--surface);border:1px solid var(--border2);border-radius:10px;box-shadow:0 -8px 24px rgba(0,0,0,.4);z-index:200;max-height:240px;overflow-y:auto;margin-bottom:4px;}
|
||||
.cmd-dropdown.open{display:block;}
|
||||
.cmd-item{padding:8px 14px;cursor:pointer;transition:background .12s;}
|
||||
.cmd-item:hover,.cmd-item.selected{background:rgba(255,255,255,.07);}
|
||||
@@ -416,9 +841,9 @@
|
||||
/* ── Edit message inline ── */
|
||||
.msg-edit-area{width:100%;background:rgba(255,255,255,.05);border:1px solid rgba(124,185,255,.35);border-radius:8px;color:var(--text);padding:10px 12px;font-size:14px;font-family:inherit;line-height:1.6;resize:none;outline:none;min-height:60px;box-sizing:border-box;box-shadow:0 0 0 3px rgba(124,185,255,.07);margin-top:4px;}
|
||||
.msg-edit-bar{display:flex;gap:8px;margin-top:8px;margin-bottom:4px;}
|
||||
.msg-edit-send{background:var(--blue);color:#fff;border:none;border-radius:7px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;transition:opacity .15s;}
|
||||
.msg-edit-send{background:var(--blue);color:#fff;border:none;border-radius:8px;padding:6px 16px;font-size:13px;font-weight:600;cursor:pointer;transition:opacity .15s;}
|
||||
.msg-edit-send:hover{opacity:.85;}
|
||||
.msg-edit-cancel{background:rgba(255,255,255,.06);color:var(--muted);border:1px solid var(--border2);border-radius:7px;padding:6px 12px;font-size:13px;cursor:pointer;transition:background .15s;}
|
||||
.msg-edit-cancel{background:var(--hover-bg);color:var(--muted);border:1px solid var(--border2);border-radius:8px;padding:6px 12px;font-size:13px;cursor:pointer;transition:background .15s;}
|
||||
.msg-edit-cancel:hover{background:rgba(255,255,255,.1);}
|
||||
|
||||
/* ── Clear conversation chip ── */
|
||||
@@ -455,6 +880,7 @@
|
||||
|
||||
/* Approval buttons: tab stops */
|
||||
.approval-btn:focus{outline:2px solid var(--blue);outline-offset:2px;}
|
||||
.clarify-choice:focus,.clarify-submit:focus,.clarify-input:focus{outline:2px solid var(--blue);outline-offset:2px;}
|
||||
|
||||
/* Message role: breathing room between icon and name */
|
||||
.msg-role > span{line-height:1;}
|
||||
@@ -482,10 +908,6 @@
|
||||
/* Empty state: add subtle gradient behind logo */
|
||||
.empty-state{background:radial-gradient(ellipse at 50% 20%,rgba(124,185,255,.04) 0%,transparent 60%);}
|
||||
|
||||
/* ── Activity bar (tool status above composer) ── */
|
||||
@keyframes fadeIn{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:none}}
|
||||
#activityBar{padding-bottom:8px;flex-shrink:0;}
|
||||
#activityBarInner{transition:opacity .2s;}
|
||||
/* Remove old status-text from composer (kept for error messages only) */
|
||||
.status-text{font-size:11px;color:var(--muted);padding-left:2px;display:none;}
|
||||
|
||||
@@ -498,7 +920,7 @@
|
||||
padding: 8px 10px 3px !important;
|
||||
font-size: 10px !important;
|
||||
}
|
||||
/* Sidebar bottom: tighten model field */
|
||||
/* Sidebar bottom: tighten spacing */
|
||||
.sidebar-bottom { padding: 10px 14px 12px; }
|
||||
/* Right panel file tree: more padding for breathing room */
|
||||
|
||||
@@ -596,12 +1018,12 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
.skill-linked-section{margin-bottom:8px;}
|
||||
.skill-linked-section h4{font-size:10px;text-transform:uppercase;letter-spacing:.05em;color:var(--muted);margin-bottom:4px;}
|
||||
.skill-linked-file{display:block;font-size:12px;padding:3px 6px;border-radius:4px;cursor:pointer;color:var(--blue);text-decoration:none;}
|
||||
.skill-linked-file:hover{background:rgba(255,255,255,.06);}
|
||||
.skill-linked-file:hover{background:var(--hover-bg);}
|
||||
.tool-card-row{margin:0;padding:1px 0;}
|
||||
.tool-card{background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:6px;margin:2px 0 2px 40px;overflow:hidden;transition:border-color .15s;}
|
||||
.tool-card:hover{border-color:rgba(255,255,255,.12);}
|
||||
.tool-card-running{border-color:rgba(124,185,255,.25);background:rgba(124,185,255,.04);}
|
||||
.tool-card-header{display:flex;align-items:center;gap:7px;padding:4px 10px;cursor:pointer;user-select:none;}
|
||||
.tool-card-header{display:flex;align-items:center;gap:8px;padding:4px 10px;cursor:pointer;user-select:none;}
|
||||
.tool-card-icon{font-size:13px;flex-shrink:0;opacity:.8;}
|
||||
.tool-card-name{font-size:12px;font-weight:600;color:var(--muted);font-family:'SF Mono',ui-monospace,monospace;flex-shrink:0;}
|
||||
.tool-card-preview{font-size:11px;color:var(--muted);opacity:.6;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
|
||||
@@ -624,17 +1046,38 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
|
||||
/* ── Settings overlay ── */
|
||||
.settings-overlay{position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:1000;display:flex;align-items:center;justify-content:center;}
|
||||
.settings-panel{background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:0;width:380px;max-width:90vw;max-height:80vh;overflow:visible;box-shadow:0 12px 40px rgba(0,0,0,.5);display:flex;flex-direction:column;}
|
||||
.settings-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px 12px;border-bottom:1px solid var(--border);}
|
||||
.settings-body{padding:20px;overflow-y:auto;flex:1;}
|
||||
.settings-panel{background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:0;width:860px;max-width:92vw;height:min(700px,92vh);overflow:visible;box-shadow:0 12px 40px rgba(0,0,0,.5);display:flex;flex-direction:column;}
|
||||
.settings-header{display:flex;align-items:flex-start;justify-content:space-between;padding:18px 24px 14px;border-bottom:1px solid var(--border);gap:16px;}
|
||||
.settings-heading{display:flex;flex-direction:column;gap:3px;}
|
||||
.settings-kicker{font-size:10px;font-weight:700;letter-spacing:.12em;text-transform:uppercase;color:var(--blue);}
|
||||
.settings-subtitle{font-size:12px;color:var(--muted);line-height:1.5;}
|
||||
.settings-body{padding:0;flex:1;display:flex;min-height:0;overflow:hidden;}
|
||||
.settings-shell{display:grid;grid-template-columns:220px minmax(0,1fr);gap:0;flex:1;min-height:0;min-width:0;}
|
||||
.settings-tabs{display:flex;flex-direction:column;gap:4px;padding:18px 12px;border-right:1px solid var(--border);align-self:stretch;min-height:0;}
|
||||
.settings-tab{display:flex;flex-direction:row;gap:12px;align-items:center;padding:10px 12px;border-radius:8px;border:1px solid transparent;background:transparent;color:var(--muted);cursor:pointer;transition:background .15s,border-color .15s,color .15s;text-align:left;width:100%;}
|
||||
.settings-tab:hover{background:rgba(255,255,255,.05);color:var(--text);}
|
||||
.settings-tab.active{background:rgba(124,185,255,.1);border-color:rgba(124,185,255,.22);color:var(--text);}
|
||||
.settings-tab-icon{flex-shrink:0;opacity:.9;}
|
||||
.settings-tab-title{font-size:13px;font-weight:600;letter-spacing:.01em;}
|
||||
.settings-main{overflow-y:auto;padding:22px 24px;min-width:0;}
|
||||
.settings-pane{display:none;}
|
||||
.settings-pane.active{display:block;}
|
||||
.settings-section-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:14px;}
|
||||
.settings-section-title{font-size:13px;font-weight:700;letter-spacing:.01em;color:var(--text);}
|
||||
.settings-section-meta{font-size:11px;color:var(--muted);margin-top:3px;line-height:1.5;}
|
||||
.settings-version-badge{display:inline-flex;align-items:center;padding:4px 8px;border-radius:999px;border:1px solid rgba(124,185,255,.22);background:rgba(124,185,255,.08);color:var(--blue);font-size:11px;font-weight:700;flex-shrink:0;}
|
||||
.hermes-action-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;}
|
||||
.settings-action-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:10px 12px;border-radius:10px;border:1px solid var(--border2);background:var(--input-bg);color:var(--text);font-size:12px;font-weight:600;cursor:pointer;transition:background .15s,border-color .15s,color .15s;}
|
||||
.settings-action-btn:hover{background:rgba(255,255,255,.08);border-color:rgba(255,255,255,.18);}
|
||||
.settings-action-btn.danger{color:var(--accent);border-color:rgba(233,69,96,.25);}
|
||||
.settings-action-btn.danger:hover{background:rgba(233,69,96,.08);border-color:rgba(233,69,96,.4);}
|
||||
.settings-action-btn:disabled,.settings-action-btn.disabled{opacity:.45;cursor:not-allowed;}
|
||||
.settings-action-btn:disabled:hover,.settings-action-btn.disabled:hover{background:var(--input-bg);border-color:var(--border2);}
|
||||
.settings-field{margin-bottom:16px;}
|
||||
.settings-field label{display:block;font-size:11px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--muted);margin-bottom:6px;}
|
||||
/* Save button inside the settings panel */
|
||||
.settings-panel .settings-btn{background:var(--accent);color:#fff;border:none;border-radius:6px;padding:8px 16px;cursor:pointer;font-weight:600;font-size:13px;}
|
||||
.settings-panel .settings-btn:hover{opacity:.9;}
|
||||
/* Gear icon in topbar -- muted chip, no red */
|
||||
.gear-btn{font-size:13px;cursor:pointer;transition:color .15s,background .15s;}
|
||||
.gear-btn:hover{color:var(--text);background:rgba(255,255,255,.08);}
|
||||
|
||||
/* ── Session pin indicator (inline, only when pinned) ── */
|
||||
.session-pin-indicator{flex-shrink:0;color:#f5c542;line-height:1;display:flex;align-items:center;}
|
||||
@@ -666,13 +1109,13 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
|
||||
/* ── Session projects ── */
|
||||
.project-bar{display:flex;gap:4px;padding:4px 10px 8px;flex-wrap:wrap;align-items:center;flex-shrink:0;}
|
||||
.project-chip{font-size:10px;font-weight:600;padding:3px 8px;border-radius:12px;cursor:pointer;border:1px solid var(--border2);background:rgba(255,255,255,.04);color:var(--muted);transition:all .15s;white-space:nowrap;display:inline-flex;align-items:center;gap:4px;}
|
||||
.project-chip{font-size:10px;font-weight:600;padding:3px 8px;border-radius:12px;cursor:pointer;border:1px solid var(--border2);background:var(--input-bg);color:var(--muted);transition:all .15s;white-space:nowrap;display:inline-flex;align-items:center;gap:4px;}
|
||||
.project-chip:hover{background:rgba(255,255,255,.08);color:var(--text);}
|
||||
.project-chip.active{background:rgba(124,185,255,.12);color:var(--blue);border-color:rgba(124,185,255,.4);}
|
||||
.project-chip .color-dot{width:6px;height:6px;border-radius:50%;display:inline-block;flex-shrink:0;}
|
||||
.project-create-btn{font-size:10px;padding:3px 6px;border-radius:12px;cursor:pointer;border:1px dashed var(--border2);background:none;color:var(--muted);opacity:.6;transition:all .15s;}
|
||||
.project-create-btn:hover{opacity:1;border-color:var(--blue);color:var(--blue);}
|
||||
.project-create-input{font-size:10px;padding:3px 8px;border-radius:12px;border:1px solid rgba(124,185,255,.6);background:rgba(20,32,60,.9);color:var(--text);outline:none;width:100px;font-family:inherit;box-shadow:0 0 0 2px rgba(124,185,255,.15);}
|
||||
.project-create-input{font-size:10px;padding:3px 8px;border-radius:12px;border:1px solid rgba(124,185,255,.6);background:var(--surface);color:var(--text);outline:none;width:100px;font-family:inherit;box-shadow:0 0 0 2px rgba(124,185,255,.15);}
|
||||
.project-picker{position:absolute;right:0;top:100%;background:var(--sidebar);border:1px solid var(--border2);border-radius:8px;padding:4px;z-index:30;min-width:160px;max-width:220px;width:max-content;box-shadow:0 4px 16px rgba(0,0,0,.3);}
|
||||
.project-picker-item{padding:5px 10px;font-size:11px;border-radius:6px;cursor:pointer;color:var(--muted);transition:all .1s;display:flex;align-items:center;gap:6px;}
|
||||
.project-picker-item:hover{background:rgba(255,255,255,.08);color:var(--text);}
|
||||
@@ -682,7 +1125,7 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
.session-project-dot{width:6px;height:6px;border-radius:50%;flex-shrink:0;display:inline-block;margin-left:4px;vertical-align:middle;}
|
||||
|
||||
/* ── Code copy button ── */
|
||||
.code-copy-btn{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:4px;color:var(--muted);font-size:11px;cursor:pointer;padding:2px 6px;transition:all .15s;line-height:1.3;}
|
||||
.code-copy-btn{background:var(--hover-bg);border:1px solid var(--border2);border-radius:4px;color:var(--muted);font-size:11px;cursor:pointer;padding:2px 6px;transition:all .15s;line-height:1.3;}
|
||||
.code-copy-btn:hover{background:rgba(255,255,255,.12);color:var(--text);}
|
||||
|
||||
/* ── Tool card expand/collapse toggle ── */
|
||||
@@ -704,23 +1147,3 @@ 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 ── */
|
||||
.session-item.cli-session {
|
||||
border-left-color: var(--gold);
|
||||
padding-right: 36px; /* make room for session-actions overlay */
|
||||
}
|
||||
.session-item.cli-session::after {
|
||||
content: 'cli';
|
||||
font-size: 9px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .04em;
|
||||
color: var(--gold);
|
||||
opacity: .5;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
pointer-events: none; /* don't block clicks on session-actions beneath */
|
||||
}
|
||||
.session-item.cli-session:hover::after {
|
||||
display: none; /* hide badge on hover so session-actions icons are fully reachable */
|
||||
}
|
||||
|
||||
1146
static/ui.js
1146
static/ui.js
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,7 @@
|
||||
async function api(path,opts={}){
|
||||
const url=new URL(path,location.origin);
|
||||
// Strip leading slash so URL resolves relative to location.href (supports subpath mounts)
|
||||
const rel = path.startsWith('/') ? path.slice(1) : path;
|
||||
const url=new URL(rel,location.href);
|
||||
const res=await fetch(url.href,{credentials:'include',headers:{'Content-Type':'application/json'},...opts});
|
||||
if(!res.ok){
|
||||
const text=await res.text();
|
||||
@@ -54,7 +56,7 @@ async function loadDir(path){
|
||||
}
|
||||
if(typeof clearPreview==='function'){
|
||||
if(typeof _previewDirty!=='undefined'&&_previewDirty){
|
||||
if(confirm('You have unsaved changes in the preview. Discard and navigate?'))clearPreview();
|
||||
showConfirmDialog({title:t('unsaved_confirm'),message:'',confirmLabel:'Discard',danger:true,focusCancel:true}).then(ok=>{if(ok)clearPreview();});
|
||||
}else{
|
||||
clearPreview();
|
||||
}
|
||||
@@ -131,8 +133,8 @@ function updateEditBtn(){
|
||||
const editable = _previewCurrentMode==='code'||_previewCurrentMode==='md';
|
||||
btn.style.display = editable?'':'none';
|
||||
const editing = $('previewEditArea').style.display!=='none';
|
||||
btn.innerHTML = editing ? '💾 Save' : '✎ Edit';
|
||||
btn.title = editing ? 'Save changes' : 'Edit this file';
|
||||
btn.innerHTML = editing ? `💾 ${t('save')}` : `✎ ${t('edit')}`;
|
||||
btn.title = editing ? t('save_title') : t('edit_title');
|
||||
btn.style.color = editing ? 'var(--blue)' : '';
|
||||
if(_previewDirty) btn.innerHTML = '💾 Save*';
|
||||
}
|
||||
@@ -150,12 +152,12 @@ async function toggleEditMode(){
|
||||
_previewDirty=false;
|
||||
// Update read-only views
|
||||
if(_previewCurrentMode==='code') $('previewCode').textContent=content;
|
||||
else $('previewMd').innerHTML=renderMd(content);
|
||||
else { $('previewMd').innerHTML=renderMd(content); requestAnimationFrame(()=>{if(typeof renderKatexBlocks==='function')renderKatexBlocks();}); }
|
||||
$('previewEditArea').style.display='none';
|
||||
if(_previewCurrentMode==='code') $('previewCode').style.display='';
|
||||
else $('previewMd').style.display='';
|
||||
showToast('Saved');
|
||||
}catch(e){setStatus('Save failed: '+e.message);}
|
||||
showToast(t('saved'));
|
||||
}catch(e){setStatus(t('save_failed')+e.message);}
|
||||
}else{
|
||||
// Enter edit mode: populate textarea with current content
|
||||
const currentText = _previewCurrentMode==='code'
|
||||
@@ -200,13 +202,14 @@ async function openFile(path){
|
||||
$('fileTree').style.display='none';
|
||||
|
||||
_previewCurrentPath = path;
|
||||
renderFileBreadcrumb(path);
|
||||
if(IMAGE_EXTS.has(ext)){
|
||||
// Image: load via raw endpoint, show as <img>
|
||||
showPreview('image');
|
||||
const url=`/api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}`;
|
||||
const url=`api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}`;
|
||||
$('previewImg').alt=path;
|
||||
$('previewImg').src=url;
|
||||
$('previewImg').onerror=()=>setStatus('Could not load image');
|
||||
$('previewImg').onerror=()=>setStatus(t('image_load_failed'));
|
||||
} else if(MD_EXTS.has(ext)){
|
||||
// Markdown: fetch text, render with renderMd, display as formatted HTML
|
||||
try{
|
||||
@@ -214,7 +217,8 @@ async function openFile(path){
|
||||
showPreview('md');
|
||||
_previewRawContent = data.content;
|
||||
$('previewMd').innerHTML=renderMd(data.content);
|
||||
}catch(e){setStatus('Could not open file');}
|
||||
requestAnimationFrame(()=>{if(typeof renderKatexBlocks==='function')renderKatexBlocks();});
|
||||
}catch(e){setStatus(t('file_open_failed'));}
|
||||
} else {
|
||||
// Plain code / text -- but fall back to download if server signals binary
|
||||
try{
|
||||
@@ -236,12 +240,50 @@ async function openFile(path){
|
||||
function downloadFile(path){
|
||||
if(!S.session)return;
|
||||
// Trigger browser download via the raw file endpoint with content-disposition attachment
|
||||
const url=`/api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}&download=1`;
|
||||
const url=`api/file/raw?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}&download=1`;
|
||||
const filename=path.split('/').pop();
|
||||
const a=document.createElement('a');
|
||||
a.href=url;a.download=filename;
|
||||
document.body.appendChild(a);a.click();
|
||||
setTimeout(()=>document.body.removeChild(a),100);
|
||||
showToast(`Downloading ${filename}\u2026`,2000);
|
||||
showToast(t('downloading',filename),2000);
|
||||
}
|
||||
|
||||
|
||||
// ── Render breadcrumb for file preview mode ──────────────────────────────────
|
||||
function renderFileBreadcrumb(filePath) {
|
||||
const bar = $('breadcrumbBar');
|
||||
if (!bar) return;
|
||||
bar.style.display = 'flex';
|
||||
const upBtn = $('btnUpDir');
|
||||
if (upBtn) upBtn.style.display = '';
|
||||
|
||||
bar.innerHTML = '';
|
||||
// Root
|
||||
const root = document.createElement('span');
|
||||
root.className = 'breadcrumb-seg breadcrumb-link';
|
||||
root.textContent = '~';
|
||||
root.onclick = () => { clearPreview(); loadDir('.'); };
|
||||
bar.appendChild(root);
|
||||
|
||||
const parts = filePath.split('/');
|
||||
let accumulated = '';
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const sep = document.createElement('span');
|
||||
sep.className = 'breadcrumb-sep';
|
||||
sep.textContent = '/';
|
||||
bar.appendChild(sep);
|
||||
|
||||
accumulated += (accumulated ? '/' : '') + parts[i];
|
||||
const seg = document.createElement('span');
|
||||
seg.textContent = parts[i];
|
||||
if (i < parts.length - 1) {
|
||||
seg.className = 'breadcrumb-seg breadcrumb-link';
|
||||
const target = accumulated;
|
||||
seg.onclick = () => { clearPreview(); loadDir(target); };
|
||||
} else {
|
||||
seg.className = 'breadcrumb-seg breadcrumb-current';
|
||||
}
|
||||
bar.appendChild(seg);
|
||||
}
|
||||
}
|
||||
|
||||
42
tests/_pytest_port.py
Normal file
42
tests/_pytest_port.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
Shared test server constants for use in individual test files.
|
||||
|
||||
Instead of hardcoding ``BASE = "http://127.0.0.1:8788"`` in every test file,
|
||||
import from here so the port and state dir are always consistent with
|
||||
what conftest.py computed for this worktree.
|
||||
|
||||
Usage::
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
conftest.py publishes ``HERMES_WEBUI_TEST_PORT`` and
|
||||
``HERMES_WEBUI_TEST_STATE_DIR`` to ``os.environ`` at module level
|
||||
(before any test file is imported), so this module always reads the
|
||||
correct values. The auto-derivation fallback matches conftest's logic
|
||||
exactly, so standalone imports also work correctly.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
def _auto_test_port(repo_root: pathlib.Path) -> int:
|
||||
h = int(hashlib.md5(str(repo_root).encode()).hexdigest(), 16)
|
||||
return 20000 + (h % 10000)
|
||||
|
||||
def _auto_state_dir_name(repo_root: pathlib.Path) -> str:
|
||||
h = hashlib.md5(str(repo_root).encode()).hexdigest()[:8]
|
||||
return f"webui-test-{h}"
|
||||
|
||||
_TESTS_DIR = pathlib.Path(__file__).parent.resolve()
|
||||
_REPO_ROOT = _TESTS_DIR.parent.resolve()
|
||||
_HERMES_HOME = pathlib.Path(os.getenv('HERMES_HOME',
|
||||
str(pathlib.Path.home() / '.hermes')))
|
||||
|
||||
TEST_PORT = int(os.environ.get('HERMES_WEBUI_TEST_PORT',
|
||||
str(_auto_test_port(_REPO_ROOT))))
|
||||
BASE = f"http://127.0.0.1:{TEST_PORT}"
|
||||
|
||||
TEST_STATE_DIR = pathlib.Path(os.environ.get(
|
||||
'HERMES_WEBUI_TEST_STATE_DIR',
|
||||
str(_HERMES_HOME / _auto_state_dir_name(_REPO_ROOT))
|
||||
))
|
||||
@@ -31,14 +31,37 @@ HOME = pathlib.Path.home()
|
||||
HERMES_HOME = pathlib.Path(os.getenv('HERMES_HOME', str(HOME / '.hermes')))
|
||||
|
||||
# ── Test server config ────────────────────────────────────────────────────
|
||||
TEST_PORT = int(os.getenv('HERMES_WEBUI_TEST_PORT', '8788'))
|
||||
# Port and state dir auto-derive from the repo path when no env var is set,
|
||||
# giving every worktree its own isolated port (8800-8899) and state directory.
|
||||
# Override with HERMES_WEBUI_TEST_PORT / HERMES_WEBUI_TEST_STATE_DIR to pin.
|
||||
|
||||
def _auto_test_port(repo_root) -> int:
|
||||
"""Map repo path to a unique port in 20000-29999 (10k range = near-zero collisions).
|
||||
Far from system port ranges and Linux ephemeral ports (32768+).
|
||||
Override with HERMES_WEBUI_TEST_PORT to use a specific port."""
|
||||
import hashlib
|
||||
h = int(hashlib.md5(str(repo_root).encode()).hexdigest(), 16)
|
||||
return 20000 + (h % 10000)
|
||||
|
||||
def _auto_state_dir_name(repo_root) -> str:
|
||||
import hashlib
|
||||
h = hashlib.md5(str(repo_root).encode()).hexdigest()[:8]
|
||||
return f"webui-test-{h}"
|
||||
|
||||
TEST_PORT = int(os.getenv('HERMES_WEBUI_TEST_PORT',
|
||||
str(_auto_test_port(REPO_ROOT))))
|
||||
TEST_BASE = f"http://127.0.0.1:{TEST_PORT}"
|
||||
TEST_STATE_DIR = pathlib.Path(os.getenv(
|
||||
'HERMES_WEBUI_TEST_STATE_DIR',
|
||||
str(HERMES_HOME / 'webui-mvp-test')
|
||||
str(HERMES_HOME / _auto_state_dir_name(REPO_ROOT))
|
||||
))
|
||||
TEST_WORKSPACE = TEST_STATE_DIR / 'test-workspace'
|
||||
|
||||
# Publish at module level so _pytest_port.py (imported at collection time)
|
||||
# and any test file using os.environ sees the right values immediately.
|
||||
os.environ.setdefault('HERMES_WEBUI_TEST_PORT', str(TEST_PORT))
|
||||
os.environ.setdefault('HERMES_WEBUI_TEST_STATE_DIR', str(TEST_STATE_DIR))
|
||||
|
||||
# ── Server script: always relative to repo root ───────────────────────────
|
||||
SERVER_SCRIPT = REPO_ROOT / 'server.py'
|
||||
if not SERVER_SCRIPT.exists():
|
||||
@@ -153,6 +176,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',
|
||||
@@ -170,7 +195,7 @@ def pytest_collection_modifyitems(config, items):
|
||||
skipped += 1
|
||||
|
||||
if skipped:
|
||||
print(f"\n⚠️ hermes-agent not found — {skipped} agent-dependent tests will be skipped\n")
|
||||
print(f"\nWARNING: hermes-agent not found; {skipped} agent-dependent tests will be skipped\n")
|
||||
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
@@ -210,6 +235,18 @@ def test_server():
|
||||
Start an isolated test server on TEST_PORT with a clean state directory.
|
||||
Paths are discovered dynamically -- no hardcoded absolute path assumptions.
|
||||
"""
|
||||
# Kill any leftover process on the test port before starting.
|
||||
# Stale servers from QA harness runs or prior test sessions cause
|
||||
# conftest to think the server is already up, producing false failures.
|
||||
try:
|
||||
import subprocess as _sp
|
||||
_sp.run(['fuser', '-k', f'{TEST_PORT}/tcp'],
|
||||
capture_output=True, timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
import time as _time
|
||||
_time.sleep(0.5) # brief pause to let the port release
|
||||
|
||||
# Clean slate
|
||||
if TEST_STATE_DIR.exists():
|
||||
shutil.rmtree(TEST_STATE_DIR)
|
||||
@@ -226,6 +263,16 @@ 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.
|
||||
# Export both port and state-dir as env vars so individual test files
|
||||
# can read them without importing conftest (avoids circular imports).
|
||||
os.environ.setdefault('HERMES_WEBUI_TEST_PORT', str(TEST_PORT))
|
||||
# os.environ already set at module level above; no-op here.
|
||||
|
||||
env = os.environ.copy()
|
||||
env.update({
|
||||
"HERMES_WEBUI_PORT": str(TEST_PORT),
|
||||
|
||||
188
tests/test_approval_queue.py
Normal file
188
tests/test_approval_queue.py
Normal file
@@ -0,0 +1,188 @@
|
||||
"""Tests for approval queue multi-entry support (issue #527).
|
||||
|
||||
Previously _pending[sid] held one entry, so simultaneous approvals overwrote
|
||||
each other. This PR changes submit_pending() to append to a list and adds
|
||||
approval_id so /api/approval/respond can target a specific entry.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
ROUTES_SRC = (REPO_ROOT / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
MESSAGES_JS = (REPO_ROOT / "static" / "messages.js").read_text(encoding="utf-8")
|
||||
INDEX_HTML = (REPO_ROOT / "static" / "index.html").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Static-analysis: Python routes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_submit_pending_appends_to_list():
|
||||
"""submit_pending() must append to a list, not overwrite."""
|
||||
# The new wrapper must contain queue.append
|
||||
assert "queue.append(entry)" in ROUTES_SRC, \
|
||||
"submit_pending() must append entry to a list queue, not overwrite _pending[sid]"
|
||||
|
||||
|
||||
def test_submit_pending_adds_approval_id():
|
||||
"""Each queued entry must get a unique approval_id."""
|
||||
assert "approval_id" in ROUTES_SRC and "uuid.uuid4().hex" in ROUTES_SRC, \
|
||||
"submit_pending() must assign a uuid4 approval_id to each queued entry"
|
||||
|
||||
|
||||
def test_handle_approval_pending_returns_count():
|
||||
"""_handle_approval_pending must return pending_count in its response."""
|
||||
assert '"pending_count"' in ROUTES_SRC, \
|
||||
"_handle_approval_pending must include pending_count in the JSON response"
|
||||
|
||||
|
||||
def test_handle_approval_respond_pops_by_approval_id():
|
||||
"""_handle_approval_respond must target entry by approval_id."""
|
||||
assert 'approval_id = body.get("approval_id"' in ROUTES_SRC, \
|
||||
"_handle_approval_respond must read approval_id from request body"
|
||||
assert 'entry.get("approval_id") == approval_id' in ROUTES_SRC, \
|
||||
"_handle_approval_respond must find and pop the matching entry by approval_id"
|
||||
|
||||
|
||||
def test_handle_approval_respond_fallback_to_oldest():
|
||||
"""When no approval_id is given, fall back to popping the oldest entry (FIFO)."""
|
||||
# The fallback path: queue.pop(0) when approval_id is empty
|
||||
assert "queue.pop(0)" in ROUTES_SRC, \
|
||||
"_handle_approval_respond must fall back to popping the oldest entry when approval_id is absent"
|
||||
|
||||
|
||||
def test_backward_compat_legacy_dict_value():
|
||||
"""The respond handler must tolerate a legacy single-dict value in _pending."""
|
||||
assert "Legacy single-dict value" in ROUTES_SRC or \
|
||||
"# Legacy single-dict" in ROUTES_SRC or \
|
||||
"elif queue:" in ROUTES_SRC, \
|
||||
"respond handler must handle legacy single-dict _pending values for backward compatibility"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Static-analysis: JavaScript frontend
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_respond_sends_approval_id():
|
||||
"""respondApproval() must include approval_id in the POST body."""
|
||||
assert "approval_id: approvalId" in MESSAGES_JS, \
|
||||
"respondApproval() must send approval_id in the POST body to /api/approval/respond"
|
||||
|
||||
|
||||
def test_show_approval_card_accepts_count():
|
||||
"""showApprovalCard must accept a pendingCount parameter."""
|
||||
assert re.search(r"function showApprovalCard\(pending,\s*pendingCount\)", MESSAGES_JS), \
|
||||
"showApprovalCard() must accept a pendingCount argument"
|
||||
|
||||
|
||||
def test_show_approval_card_renders_counter():
|
||||
"""showApprovalCard must display a '1 of N pending' counter when N > 1."""
|
||||
assert '"1 of " + pendingCount + " pending"' in MESSAGES_JS or \
|
||||
"'1 of ' + pendingCount + ' pending'" in MESSAGES_JS, \
|
||||
"showApprovalCard() must render '1 of N pending' counter for multiple queued approvals"
|
||||
|
||||
|
||||
def test_approval_current_id_tracked():
|
||||
"""_approvalCurrentId must be set and cleared around each approval."""
|
||||
assert "_approvalCurrentId" in MESSAGES_JS, \
|
||||
"_approvalCurrentId must track the approval_id of the currently displayed card"
|
||||
assert "_approvalCurrentId = pending.approval_id" in MESSAGES_JS or \
|
||||
"_approvalCurrentId = pending.approval_id || null" in MESSAGES_JS, \
|
||||
"_approvalCurrentId must be assigned from pending.approval_id"
|
||||
# Must be nulled on respond
|
||||
assert "_approvalCurrentId = null" in MESSAGES_JS, \
|
||||
"_approvalCurrentId must be cleared when respondApproval() is called"
|
||||
|
||||
|
||||
def test_polling_passes_count_to_show():
|
||||
"""The poll loop must pass pending_count to showApprovalCard."""
|
||||
assert "showApprovalCard(data.pending, data.pending_count" in MESSAGES_JS, \
|
||||
"Poll loop must pass data.pending_count to showApprovalCard"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTML: counter element present
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_approval_counter_element_exists():
|
||||
"""index.html must contain an approvalCounter element."""
|
||||
assert 'id="approvalCounter"' in INDEX_HTML, \
|
||||
"index.html must contain an element with id='approvalCounter' for the '1 of N' display"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Functional: multiple entries behave correctly (via routes module directly)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_multiple_approvals_both_surfaced():
|
||||
"""Two submit_pending calls must produce two queued entries, not one."""
|
||||
import threading
|
||||
from api import routes as r
|
||||
|
||||
# Reset state
|
||||
sid = "test-multi-approval-sid"
|
||||
with r._lock:
|
||||
r._pending.pop(sid, None)
|
||||
|
||||
r.submit_pending(sid, {"command": "cmd1", "pattern_key": "p1", "pattern_keys": ["p1"], "description": "d1"})
|
||||
r.submit_pending(sid, {"command": "cmd2", "pattern_key": "p2", "pattern_keys": ["p2"], "description": "d2"})
|
||||
|
||||
with r._lock:
|
||||
queue = r._pending.get(sid)
|
||||
|
||||
assert isinstance(queue, list), "After two submit_pending calls, _pending[sid] must be a list"
|
||||
assert len(queue) == 2, f"Expected 2 queued entries, got {len(queue)}"
|
||||
assert queue[0]["command"] == "cmd1"
|
||||
assert queue[1]["command"] == "cmd2"
|
||||
assert queue[0].get("approval_id"), "First entry must have an approval_id"
|
||||
assert queue[1].get("approval_id"), "Second entry must have an approval_id"
|
||||
assert queue[0]["approval_id"] != queue[1]["approval_id"], "Each entry must have a unique approval_id"
|
||||
|
||||
# Cleanup
|
||||
with r._lock:
|
||||
r._pending.pop(sid, None)
|
||||
|
||||
|
||||
def test_respond_by_approval_id_pops_correct_entry():
|
||||
"""Responding with approval_id must remove only the targeted entry."""
|
||||
from api import routes as r
|
||||
|
||||
sid = "test-respond-by-id-sid"
|
||||
with r._lock:
|
||||
r._pending.pop(sid, None)
|
||||
|
||||
r.submit_pending(sid, {"command": "cmd1", "pattern_key": "p1", "pattern_keys": ["p1"], "description": "d1"})
|
||||
r.submit_pending(sid, {"command": "cmd2", "pattern_key": "p2", "pattern_keys": ["p2"], "description": "d2"})
|
||||
|
||||
with r._lock:
|
||||
queue = r._pending.get(sid, [])
|
||||
aid2 = queue[1]["approval_id"] if len(queue) > 1 else None
|
||||
|
||||
assert aid2, "Second entry must have an approval_id"
|
||||
|
||||
# Respond to the SECOND entry by its approval_id
|
||||
# We call the handler internals directly (no HTTP)
|
||||
with r._lock:
|
||||
queue = r._pending.get(sid, [])
|
||||
popped = None
|
||||
for i, entry in enumerate(queue):
|
||||
if entry.get("approval_id") == aid2:
|
||||
popped = queue.pop(i)
|
||||
break
|
||||
|
||||
assert popped is not None, "Should have found and popped entry by approval_id"
|
||||
assert popped["command"] == "cmd2", "Popped the wrong entry"
|
||||
|
||||
with r._lock:
|
||||
remaining = r._pending.get(sid, [])
|
||||
|
||||
assert len(remaining) == 1, "One entry should remain after popping the second"
|
||||
assert remaining[0]["command"] == "cmd1", "The remaining entry should be cmd1"
|
||||
|
||||
# Cleanup
|
||||
with r._lock:
|
||||
r._pending.pop(sid, None)
|
||||
288
tests/test_approval_unblock.py
Normal file
288
tests/test_approval_unblock.py
Normal file
@@ -0,0 +1,288 @@
|
||||
"""
|
||||
Tests for fix/approval-stuck-thinking:
|
||||
Verify that /api/approval/respond correctly unblocks gateway approval queues
|
||||
and that the approval module exports the symbols streaming.py and routes.py
|
||||
need to prevent the UI getting stuck in "Thinking…" during dangerous commands.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
|
||||
import pytest
|
||||
|
||||
# Import approval internals — shared module-level state within this process.
|
||||
# The HTTP tests use the test server (port 8788, separate process).
|
||||
# The unit tests operate directly on the module.
|
||||
try:
|
||||
from tools.approval import (
|
||||
register_gateway_notify,
|
||||
unregister_gateway_notify,
|
||||
resolve_gateway_approval,
|
||||
_gateway_queues,
|
||||
_gateway_notify_cbs,
|
||||
_lock,
|
||||
_ApprovalEntry,
|
||||
submit_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
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not APPROVAL_AVAILABLE,
|
||||
reason="tools.approval not available in this environment"
|
||||
)
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
url = BASE + path
|
||||
with urllib.request.urlopen(url, timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def post(path, body=None):
|
||||
url = BASE + path
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(url, 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
|
||||
|
||||
|
||||
# ── Unit tests (in-process, no HTTP server needed) ──────────────────────────
|
||||
|
||||
class TestGatewayApprovalUnblocking:
|
||||
"""Unit tests for the gateway queue unblocking mechanism."""
|
||||
|
||||
def test_resolve_gateway_approval_sets_event(self):
|
||||
"""resolve_gateway_approval() must set the entry's event and store the result."""
|
||||
sid = f"unit-resolve-{uuid.uuid4().hex[:8]}"
|
||||
data = {"command": "rm -rf /tmp/x", "description": "recursive delete"}
|
||||
entry = _ApprovalEntry(data)
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
|
||||
resolved = resolve_gateway_approval(sid, "once", resolve_all=False)
|
||||
assert resolved == 1
|
||||
assert entry.event.is_set()
|
||||
assert entry.result == "once"
|
||||
|
||||
# Queue should be cleaned up
|
||||
with _lock:
|
||||
assert sid not in _gateway_queues
|
||||
|
||||
def test_resolve_gateway_approval_deny(self):
|
||||
"""Deny choice is propagated correctly."""
|
||||
sid = f"unit-deny-{uuid.uuid4().hex[:8]}"
|
||||
entry = _ApprovalEntry({"command": "pkill -9 x", "description": "force kill"})
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
|
||||
resolve_gateway_approval(sid, "deny")
|
||||
assert entry.result == "deny"
|
||||
|
||||
def test_resolve_gateway_approval_no_queue_is_harmless(self):
|
||||
"""resolve_gateway_approval with no queue entry returns 0, no crash."""
|
||||
sid = f"unit-no-queue-{uuid.uuid4().hex[:8]}"
|
||||
result = resolve_gateway_approval(sid, "once")
|
||||
assert result == 0
|
||||
|
||||
def test_resolve_all_unblocks_multiple_entries(self):
|
||||
"""resolve_all=True unblocks every pending entry in the queue."""
|
||||
sid = f"unit-resolve-all-{uuid.uuid4().hex[:8]}"
|
||||
entries = [_ApprovalEntry({"command": f"cmd{i}"}) for i in range(3)]
|
||||
with _lock:
|
||||
_gateway_queues[sid] = list(entries)
|
||||
|
||||
resolved = resolve_gateway_approval(sid, "session", resolve_all=True)
|
||||
assert resolved == 3
|
||||
for e in entries:
|
||||
assert e.event.is_set()
|
||||
assert e.result == "session"
|
||||
|
||||
def test_register_and_fire_notify_cb(self):
|
||||
"""register_gateway_notify stores the cb; calling it delivers approval data."""
|
||||
sid = f"unit-notify-{uuid.uuid4().hex[:8]}"
|
||||
fired = []
|
||||
register_gateway_notify(sid, lambda d: fired.append(d))
|
||||
|
||||
with _lock:
|
||||
cb = _gateway_notify_cbs.get(sid)
|
||||
assert cb is not None
|
||||
|
||||
data = {"command": "test", "description": "test"}
|
||||
cb(data)
|
||||
assert fired == [data]
|
||||
|
||||
unregister_gateway_notify(sid)
|
||||
|
||||
def test_unregister_clears_cb_and_signals_entries(self):
|
||||
"""unregister_gateway_notify removes cb and unblocks any queued entries."""
|
||||
sid = f"unit-unreg-{uuid.uuid4().hex[:8]}"
|
||||
register_gateway_notify(sid, lambda d: None)
|
||||
|
||||
entry = _ApprovalEntry({"command": "x"})
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
|
||||
unregister_gateway_notify(sid)
|
||||
|
||||
assert entry.event.is_set(), "unregister should signal blocked entries"
|
||||
with _lock:
|
||||
assert sid not in _gateway_notify_cbs
|
||||
assert sid not in _gateway_queues
|
||||
|
||||
def test_streaming_approval_integration(self):
|
||||
"""
|
||||
End-to-end unit simulation of the streaming.py fix:
|
||||
1. streaming.py registers notify_cb
|
||||
2. check_all_command_guards fires notify_cb (pushing approval SSE)
|
||||
3. User responds — resolve_gateway_approval unblocks agent thread
|
||||
4. Agent thread sees choice and continues
|
||||
"""
|
||||
sid = f"unit-e2e-{uuid.uuid4().hex[:8]}"
|
||||
approval_events_sent = []
|
||||
|
||||
# Step 1: streaming.py registers the notify callback
|
||||
def _approval_notify_cb(approval_data):
|
||||
approval_events_sent.append(approval_data) # would be put('approval', ...)
|
||||
register_gateway_notify(sid, _approval_notify_cb)
|
||||
|
||||
# Step 2: check_all_command_guards fires the callback and queues an entry
|
||||
approval_data = {
|
||||
"command": "rm -rf /tmp/test",
|
||||
"pattern_key": "recursive delete",
|
||||
"pattern_keys": ["recursive delete"],
|
||||
"description": "recursive delete",
|
||||
}
|
||||
entry = _ApprovalEntry(approval_data)
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
# notify_cb fires synchronously (gateway notifies user)
|
||||
with _lock:
|
||||
cb = _gateway_notify_cbs.get(sid)
|
||||
cb(approval_data)
|
||||
|
||||
assert len(approval_events_sent) == 1, "approval SSE event should have been queued"
|
||||
|
||||
# Step 3: user responds via /api/approval/respond → resolve_gateway_approval
|
||||
resolved = resolve_gateway_approval(sid, "once")
|
||||
assert resolved == 1
|
||||
|
||||
# Step 4: agent thread is unblocked with the correct choice
|
||||
assert entry.event.is_set()
|
||||
assert entry.result == "once"
|
||||
|
||||
# Cleanup
|
||||
unregister_gateway_notify(sid)
|
||||
|
||||
|
||||
# ── Symbol existence tests ───────────────────────────────────────────────────
|
||||
|
||||
class TestApprovalModuleExports:
|
||||
"""Verify the module exports all symbols that streaming.py and routes.py need."""
|
||||
|
||||
def test_register_gateway_notify_exported(self):
|
||||
import tools.approval as ap
|
||||
assert hasattr(ap, "register_gateway_notify"), \
|
||||
"tools.approval must export register_gateway_notify"
|
||||
|
||||
def test_unregister_gateway_notify_exported(self):
|
||||
import tools.approval as ap
|
||||
assert hasattr(ap, "unregister_gateway_notify"), \
|
||||
"tools.approval must export unregister_gateway_notify"
|
||||
|
||||
def test_resolve_gateway_approval_exported(self):
|
||||
import tools.approval as ap
|
||||
assert hasattr(ap, "resolve_gateway_approval"), \
|
||||
"tools.approval must export resolve_gateway_approval"
|
||||
|
||||
def test_approval_entry_exported(self):
|
||||
import tools.approval as ap
|
||||
assert hasattr(ap, "_ApprovalEntry"), \
|
||||
"tools.approval must export _ApprovalEntry"
|
||||
|
||||
|
||||
# ── HTTP regression tests (test server, port 8788) ───────────────────────────
|
||||
|
||||
class TestApprovalHTTPEndpoints:
|
||||
"""
|
||||
Regression tests for /api/approval/respond against the live test server.
|
||||
These verify that the HTTP layer behaves correctly — they don't rely on
|
||||
in-process module state shared with the server subprocess.
|
||||
"""
|
||||
|
||||
def test_respond_returns_ok_no_pending(self):
|
||||
"""respond with no pending entry returns ok (no crash, no 500)."""
|
||||
sid = f"http-no-pending-{uuid.uuid4().hex[:8]}"
|
||||
result, status = post("/api/approval/respond", {
|
||||
"session_id": sid,
|
||||
"choice": "deny",
|
||||
})
|
||||
assert status == 200
|
||||
assert result["ok"] is True
|
||||
|
||||
def test_respond_clears_injected_pending(self):
|
||||
"""Inject a pending entry, respond, verify it's cleared."""
|
||||
sid = f"http-clear-{uuid.uuid4().hex[:8]}"
|
||||
cmd = "rm -rf /tmp/testdir"
|
||||
|
||||
inject = get(f"/api/approval/inject_test?session_id={urllib.parse.quote(sid)}"
|
||||
f"&pattern_key=recursive+delete&command={urllib.parse.quote(cmd)}")
|
||||
assert inject["ok"] is True
|
||||
|
||||
data = get(f"/api/approval/pending?session_id={urllib.parse.quote(sid)}")
|
||||
assert data["pending"] is not None
|
||||
|
||||
result, status = post("/api/approval/respond", {
|
||||
"session_id": sid,
|
||||
"choice": "deny",
|
||||
})
|
||||
assert status == 200
|
||||
assert result["ok"] is True
|
||||
|
||||
data2 = get(f"/api/approval/pending?session_id={urllib.parse.quote(sid)}")
|
||||
assert data2["pending"] is None, "pending should be cleared after respond"
|
||||
|
||||
def test_respond_rejects_invalid_choice(self):
|
||||
"""respond with an unknown choice returns 400."""
|
||||
result, status = post("/api/approval/respond", {
|
||||
"session_id": "some-session",
|
||||
"choice": "INVALID",
|
||||
})
|
||||
assert status == 400
|
||||
|
||||
def test_respond_requires_session_id(self):
|
||||
"""respond without session_id returns 400."""
|
||||
result, status = post("/api/approval/respond", {"choice": "deny"})
|
||||
assert status == 400
|
||||
|
||||
def test_respond_session_choice_clears_pending(self):
|
||||
"""Inject pending, respond with 'session', verify cleared."""
|
||||
sid = f"http-session-{uuid.uuid4().hex[:8]}"
|
||||
inject = get(f"/api/approval/inject_test?session_id={urllib.parse.quote(sid)}"
|
||||
f"&pattern_key=force+kill+processes&command=pkill+-9+something")
|
||||
assert inject["ok"] is True
|
||||
|
||||
result, status = post("/api/approval/respond", {
|
||||
"session_id": sid,
|
||||
"choice": "session",
|
||||
})
|
||||
assert status == 200
|
||||
assert result["choice"] == "session"
|
||||
|
||||
data = get(f"/api/approval/pending?session_id={urllib.parse.quote(sid)}")
|
||||
assert data["pending"] is None
|
||||
134
tests/test_auth_sessions.py
Normal file
134
tests/test_auth_sessions.py
Normal file
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Tests for auth session lifecycle — session creation, verification, expiry,
|
||||
and lazy pruning of expired entries.
|
||||
"""
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
# Isolate state dir so we don't touch real sessions
|
||||
_TEST_STATE = Path(tempfile.mkdtemp())
|
||||
os.environ["HERMES_WEBUI_STATE_DIR"] = str(_TEST_STATE)
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
import importlib
|
||||
|
||||
# Force re-import of auth module so it picks up our TEST_STATE_DIR
|
||||
auth = importlib.import_module("api.auth")
|
||||
|
||||
|
||||
class TestSessionPruning(unittest.TestCase):
|
||||
"""Verify expired session cleanup works correctly."""
|
||||
|
||||
def setUp(self):
|
||||
# Clear any leftover sessions from other tests
|
||||
auth._sessions.clear()
|
||||
|
||||
def test_session_created_valid(self):
|
||||
"""A fresh session token should verify as valid."""
|
||||
token = auth.create_session()
|
||||
self.assertTrue(auth.verify_session(token))
|
||||
|
||||
def test_expired_session_pruned(self):
|
||||
"""Manually inserting an expired entry should be pruned on next verify_session call."""
|
||||
# Insert sessions that have already expired
|
||||
auth._sessions["fake_token"] = time.time() - 100
|
||||
auth._sessions["another_fake"] = time.time() - 50
|
||||
# Insert one valid session (far future)
|
||||
auth._sessions["good_token"] = time.time() + 3600
|
||||
|
||||
# _sessions has 3 entries, 2 expired
|
||||
self.assertEqual(len(auth._sessions), 3)
|
||||
|
||||
# Call verify_session — this triggers _prune_expired_sessions()
|
||||
# Cookie format is token.signature, so we need a dot to pass the early check
|
||||
auth.verify_session("fake_token.fake_sig")
|
||||
|
||||
# After verification, only the valid session should remain
|
||||
self.assertEqual(len(auth._sessions), 1)
|
||||
self.assertIn("good_token", auth._sessions)
|
||||
self.assertNotIn("fake_token", auth._sessions)
|
||||
self.assertNotIn("another_fake", auth._sessions)
|
||||
|
||||
def test_prune_does_not_remove_valid_sessions(self):
|
||||
"""_prune_expired_sessions should never remove sessions that are still active."""
|
||||
auth._sessions["active_1"] = time.time() + 86400 # 24 hours from now
|
||||
auth._sessions["active_2"] = time.time() + 7200 # 2 hours from now
|
||||
auth._sessions["expired_1"] = time.time() - 10
|
||||
|
||||
auth._prune_expired_sessions()
|
||||
|
||||
self.assertEqual(len(auth._sessions), 2)
|
||||
self.assertIn("active_1", auth._sessions)
|
||||
self.assertIn("active_2", auth._sessions)
|
||||
self.assertNotIn("expired_1", auth._sessions)
|
||||
|
||||
def test_verify_session_prunes_before_verification(self):
|
||||
"""verify_session should prune expired entries before checking the target token.
|
||||
|
||||
This ensures that _prune_expired_sessions() is called at the very top
|
||||
of verify_session(), so cleanup happens on every auth check.
|
||||
"""
|
||||
auth._sessions["expired_for_test"] = time.time() - 999
|
||||
|
||||
# verify_session with an invalid cookie triggers the full path:
|
||||
# _prune_expired_sessions -> signature check -> return False
|
||||
result = auth.verify_session("nonexistent.bad_sig")
|
||||
self.assertFalse(result)
|
||||
|
||||
# The expired entry should have been cleaned up
|
||||
self.assertNotIn("expired_for_test", auth._sessions)
|
||||
|
||||
def test_prune_handles_empty_dict(self):
|
||||
"""_prune_expired_sessions should be safe on an empty dict."""
|
||||
auth._sessions.clear()
|
||||
auth._prune_expired_sessions()
|
||||
self.assertEqual(len(auth._sessions), 0)
|
||||
|
||||
def test_session_ttl_is_24_hours(self):
|
||||
"""Newly created sessions should have the expected 24-hour TTL."""
|
||||
auth._sessions.clear()
|
||||
token_hex = auth.create_session().split(".")[0]
|
||||
# The _sessions dict stores token -> expiry_time
|
||||
# We can check the expiry is approximately SESSION_TTL seconds from now
|
||||
# by looking up the raw entry via the token
|
||||
from api.auth import _sessions, SESSION_TTL
|
||||
# find our entry
|
||||
for t, exp in _sessions.items():
|
||||
if t == token_hex:
|
||||
# expiry should be within 5 seconds of now + SESSION_TTL
|
||||
expected = time.time() + SESSION_TTL
|
||||
self.assertAlmostEqual(exp, expected, delta=5)
|
||||
break
|
||||
else:
|
||||
self.fail("Session token not found in _sessions")
|
||||
|
||||
|
||||
class TestSessionInvalidation(unittest.TestCase):
|
||||
"""Test session logout / invalidation."""
|
||||
|
||||
def setUp(self):
|
||||
auth._sessions.clear()
|
||||
|
||||
def test_invalidate_session_removes_token(self):
|
||||
"""Calling invalidate_session should remove the token from _sessions."""
|
||||
token = auth.create_session()
|
||||
self.assertTrue(auth.verify_session(token))
|
||||
|
||||
auth.invalidate_session(token)
|
||||
# Token should be gone
|
||||
self.assertFalse(auth.verify_session(token))
|
||||
|
||||
def test_invalidate_unknown_token_is_safe(self):
|
||||
"""Invalidating a non-existent token should not raise."""
|
||||
auth._sessions.clear()
|
||||
auth.invalidate_session("nonexistent_token")
|
||||
# Should not raise
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
199
tests/test_batch_fixes.py
Normal file
199
tests/test_batch_fixes.py
Normal file
@@ -0,0 +1,199 @@
|
||||
"""Tests for the batch of fixes from PRs #506-#521 (v0.50.47).
|
||||
|
||||
Covers:
|
||||
- /root workspace unblocking (#510/#521)
|
||||
- Attached-files split guard (#521)
|
||||
- custom_providers model visibility (#515/#519)
|
||||
- Cron skill cache invalidation (#507/#508)
|
||||
- System (auto) theme (#504/#506/#509/#514)
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
|
||||
|
||||
def read(rel):
|
||||
return (REPO / rel).read_text()
|
||||
|
||||
|
||||
# ── Group A: /root workspace ──────────────────────────────────────────────────
|
||||
|
||||
class TestRootWorkspaceUnblocked:
|
||||
|
||||
def test_root_not_in_blocked_system_roots(self):
|
||||
src = read("api/workspace.py")
|
||||
assert "Path('/root')" not in src, (
|
||||
"/root must not be in _BLOCKED_SYSTEM_ROOTS — "
|
||||
"breaks deployments where Hermes runs as root"
|
||||
)
|
||||
|
||||
def test_etc_still_blocked(self):
|
||||
"""Sanity: other dangerous paths remain blocked."""
|
||||
src = read("api/workspace.py")
|
||||
assert "Path('/etc')" in src
|
||||
assert "Path('/proc')" in src
|
||||
|
||||
def test_split_guard_present(self):
|
||||
src = read("api/streaming.py")
|
||||
assert "'\\n\\n[Attached files:' in msg_text" in src, (
|
||||
"base_text split must guard against missing '[Attached files:' "
|
||||
"to avoid empty-string on plain messages"
|
||||
)
|
||||
|
||||
|
||||
# ── Group B: custom_providers visibility ─────────────────────────────────────
|
||||
|
||||
class TestCustomProvidersVisibility:
|
||||
|
||||
def test_has_custom_providers_variable_present(self):
|
||||
src = read("api/config.py")
|
||||
assert "_has_custom_providers" in src, (
|
||||
"_has_custom_providers variable must exist in get_available_models()"
|
||||
)
|
||||
|
||||
def test_discard_custom_conditional_on_no_custom_providers(self):
|
||||
src = read("api/config.py")
|
||||
assert "not _has_custom_providers" in src, (
|
||||
"detected_providers.discard('custom') must be gated on "
|
||||
"'not _has_custom_providers'"
|
||||
)
|
||||
|
||||
def test_custom_providers_isinstance_check(self):
|
||||
src = read("api/config.py")
|
||||
assert "isinstance(_custom_providers_cfg, list)" in src, (
|
||||
"_has_custom_providers must check isinstance(..., list)"
|
||||
)
|
||||
|
||||
|
||||
# ── Group C: cron skill cache ─────────────────────────────────────────────────
|
||||
|
||||
class TestCronSkillCacheInvalidation:
|
||||
|
||||
def _panels_src(self):
|
||||
return read("static/panels.js")
|
||||
|
||||
def test_cache_busted_on_form_open(self):
|
||||
src = self._panels_src()
|
||||
# toggleCronForm should set cache to null unconditionally
|
||||
m = re.search(
|
||||
r'function toggleCronForm\(\)\{.*?_cronSkillsCache=null',
|
||||
src, re.DOTALL
|
||||
)
|
||||
assert m, (
|
||||
"toggleCronForm must unconditionally null _cronSkillsCache "
|
||||
"before fetching skills"
|
||||
)
|
||||
|
||||
def test_cache_not_guarded_by_if_on_open(self):
|
||||
src = self._panels_src()
|
||||
# The old guard should be gone
|
||||
assert "if(!_cronSkillsCache)" not in src, (
|
||||
"toggleCronForm should not use 'if(!_cronSkillsCache)' guard — "
|
||||
"cache must always be busted on open"
|
||||
)
|
||||
|
||||
def test_cache_busted_on_skill_save(self):
|
||||
src = self._panels_src()
|
||||
# After submitSkillSave's api() call, _cronSkillsCache must be nulled
|
||||
m = re.search(
|
||||
r'async function submitSkillSave\(\).*?_skillsData\s*=\s*null.*?_cronSkillsCache\s*=\s*null',
|
||||
src, re.DOTALL
|
||||
)
|
||||
assert m, (
|
||||
"_cronSkillsCache must be set to null in submitSkillSave() "
|
||||
"right after _skillsData = null"
|
||||
)
|
||||
|
||||
|
||||
# ── Group D: System (auto) theme ──────────────────────────────────────────────
|
||||
|
||||
class TestSystemTheme:
|
||||
|
||||
def test_apply_theme_helper_in_boot_js(self):
|
||||
src = read("static/boot.js")
|
||||
assert "function _applyTheme(" in src, (
|
||||
"_applyTheme helper function must be defined in boot.js"
|
||||
)
|
||||
|
||||
def test_apply_theme_resolves_system(self):
|
||||
src = read("static/boot.js")
|
||||
assert "name==='system'" in src or "=== 'system'" in src, (
|
||||
"_applyTheme must branch on 'system' to resolve via matchMedia"
|
||||
)
|
||||
|
||||
def test_apply_theme_uses_matchmedia(self):
|
||||
src = read("static/boot.js")
|
||||
assert "prefers-color-scheme" in src, (
|
||||
"_applyTheme must use matchMedia('(prefers-color-scheme:dark)')"
|
||||
)
|
||||
|
||||
def test_load_settings_calls_apply_theme(self):
|
||||
src = read("static/boot.js")
|
||||
assert "_applyTheme(_theme)" in src, (
|
||||
"loadSettings must call _applyTheme() instead of direct data-theme assignment"
|
||||
)
|
||||
|
||||
def test_system_option_in_theme_select(self):
|
||||
html = read("static/index.html")
|
||||
assert 'value="system"' in html, (
|
||||
"Theme <select> must include <option value=\"system\">"
|
||||
)
|
||||
assert "System (auto)" in html, (
|
||||
"Theme picker must show 'System (auto)' label"
|
||||
)
|
||||
|
||||
def test_theme_select_uses_apply_theme_onchange(self):
|
||||
html = read("static/index.html")
|
||||
assert "_applyTheme(this.value)" in html, (
|
||||
"Theme <select> onchange must call _applyTheme(this.value)"
|
||||
)
|
||||
|
||||
def test_flicker_script_resolves_system(self):
|
||||
html = read("static/index.html")
|
||||
# The head flicker-prevention IIFE must handle 'system'
|
||||
assert "==='system'" in html or "=== 'system'" in html, (
|
||||
"Flicker-prevention head script must resolve 'system' before setting data-theme"
|
||||
)
|
||||
|
||||
def test_system_in_commands_themes_list(self):
|
||||
src = read("static/commands.js")
|
||||
assert "'system'" in src, (
|
||||
"/theme command must include 'system' in the valid themes array"
|
||||
)
|
||||
|
||||
def test_commands_uses_apply_theme(self):
|
||||
src = read("static/commands.js")
|
||||
assert "_applyTheme(themeName)" in src, (
|
||||
"cmdTheme must call _applyTheme() to handle system resolution"
|
||||
)
|
||||
|
||||
def test_panels_reverts_via_apply_theme(self):
|
||||
src = read("static/panels.js")
|
||||
assert "_applyTheme(_settingsThemeOnOpen)" in src or \
|
||||
"_applyTheme(" in src, (
|
||||
"_revertSettingsPreview must call _applyTheme() so 'system' "
|
||||
"is correctly re-activated on settings discard"
|
||||
)
|
||||
|
||||
def test_panels_saves_system_string_not_resolved(self):
|
||||
src = read("static/panels.js")
|
||||
assert "localStorage.getItem('hermes-theme')" in src, (
|
||||
"_settingsThemeOnOpen must read from localStorage to preserve "
|
||||
"the 'system' string, not the resolved 'dark'/'light'"
|
||||
)
|
||||
|
||||
def test_i18n_cmd_theme_includes_system_english(self):
|
||||
src = read("static/i18n.js")
|
||||
assert "system/dark/light" in src, (
|
||||
"English cmd_theme i18n key must include 'system' in the theme list"
|
||||
)
|
||||
|
||||
def test_i18n_cmd_theme_all_locales(self):
|
||||
src = read("static/i18n.js")
|
||||
count = src.count("system/dark/light")
|
||||
assert count >= 5, (
|
||||
f"cmd_theme description should mention 'system' in all 5 locales; "
|
||||
f"found {count}"
|
||||
)
|
||||
141
tests/test_bugbatch_apr2026.py
Normal file
141
tests/test_bugbatch_apr2026.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
Bug batch fixes — April 2026.
|
||||
|
||||
Covers:
|
||||
- #594: .app-dialog and .file-rename-input have light theme overrides in style.css
|
||||
- #576: workspace panel localStorage restore is gated on session.workspace presence (boot.js)
|
||||
- #585: get_available_models() calls reload_config() before reading config cache
|
||||
- #567: docker-compose.yml comment mentions macOS UID mismatch
|
||||
- #590: _transcribeBlob already calls setComposerStatus('Transcribing…') — confirmed present
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text(encoding="utf-8")
|
||||
BOOT_JS = (REPO_ROOT / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
COMPOSE = (REPO_ROOT / "docker-compose.yml").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── #594: light theme dialog overrides ───────────────────────────────────────
|
||||
|
||||
def test_594_app_dialog_has_light_theme_override():
|
||||
"""style.css must have a light theme rule targeting .app-dialog background."""
|
||||
assert ':root[data-theme="light"] .app-dialog{' in STYLE_CSS or \
|
||||
":root[data-theme='light'] .app-dialog{" in STYLE_CSS, (
|
||||
"Missing light theme override for .app-dialog — dialogs appear dark on light theme"
|
||||
)
|
||||
|
||||
|
||||
def test_594_app_dialog_input_has_light_theme_override():
|
||||
"""style.css must have a light theme rule for .app-dialog-input."""
|
||||
assert ":root[data-theme=\"light\"] .app-dialog-input{" in STYLE_CSS, (
|
||||
"Missing light theme override for .app-dialog-input"
|
||||
)
|
||||
|
||||
|
||||
def test_594_app_dialog_btn_has_light_theme_override():
|
||||
"""style.css must have a light theme rule for .app-dialog-btn."""
|
||||
assert ":root[data-theme=\"light\"] .app-dialog-btn{" in STYLE_CSS, (
|
||||
"Missing light theme override for .app-dialog-btn"
|
||||
)
|
||||
|
||||
|
||||
def test_594_app_dialog_close_has_light_theme_override():
|
||||
"""style.css must have a light theme rule for .app-dialog-close."""
|
||||
assert ":root[data-theme=\"light\"] .app-dialog-close{" in STYLE_CSS, (
|
||||
"Missing light theme override for .app-dialog-close"
|
||||
)
|
||||
|
||||
|
||||
def test_594_file_rename_input_has_light_theme_override():
|
||||
"""style.css must have a light theme rule for .file-rename-input."""
|
||||
assert ":root[data-theme=\"light\"] .file-rename-input{" in STYLE_CSS, (
|
||||
"Missing light theme override for .file-rename-input"
|
||||
)
|
||||
|
||||
|
||||
# ── #576: workspace panel snap fix ───────────────────────────────────────────
|
||||
|
||||
def test_576_panel_restore_gated_on_workspace():
|
||||
"""boot.js: localStorage panel restore must be gated on session.workspace."""
|
||||
# The guard must appear: session.workspace check before _workspacePanelMode='browse'
|
||||
assert "S.session&&S.session.workspace&&localStorage.getItem('hermes-webui-workspace-panel')" in BOOT_JS, (
|
||||
"Workspace panel localStorage restore must be gated on S.session.workspace "
|
||||
"to prevent snap-open-then-closed on sessions without a workspace (#576)"
|
||||
)
|
||||
|
||||
|
||||
def test_576_restore_happens_after_load_session():
|
||||
"""boot.js: loadSession() must come before the panel restore guard."""
|
||||
load_pos = BOOT_JS.find("await loadSession(saved)")
|
||||
restore_pos = BOOT_JS.find("S.session&&S.session.workspace&&localStorage")
|
||||
assert load_pos != -1, "loadSession call not found in boot.js"
|
||||
assert restore_pos != -1, "workspace panel restore guard not found"
|
||||
assert load_pos < restore_pos, (
|
||||
"loadSession() must run before the panel restore guard "
|
||||
"so S.session.workspace is known at restore time"
|
||||
)
|
||||
|
||||
|
||||
# ── #585: get_available_models reloads config ─────────────────────────────────
|
||||
|
||||
def test_585_get_available_models_calls_reload_config():
|
||||
"""api/config.py: get_available_models() must do a mtime-based reload check."""
|
||||
config_src = (REPO_ROOT / "api" / "config.py").read_text(encoding="utf-8")
|
||||
fn_start = config_src.find("def get_available_models()")
|
||||
assert fn_start != -1, "get_available_models not found"
|
||||
fn_body_end = config_src.find('"""', config_src.find('"""', fn_start + 30) + 3) + 3
|
||||
# Must check mtime before reading config
|
||||
mtime_pos = config_src.find("_current_mtime", fn_body_end)
|
||||
active_prov_pos = config_src.find("active_provider = None", fn_body_end)
|
||||
assert mtime_pos != -1, (
|
||||
"get_available_models() must check config file mtime before reading cache (#585)"
|
||||
)
|
||||
assert mtime_pos < active_prov_pos, (
|
||||
"mtime check must come before active_provider = None in get_available_models()"
|
||||
)
|
||||
|
||||
|
||||
# ── #567: docker-compose UID note ─────────────────────────────────────────────
|
||||
|
||||
def test_567_compose_mentions_macos_uid():
|
||||
"""docker-compose.yml must mention macOS UID / id -u to help macOS users."""
|
||||
assert "macOS" in COMPOSE or "macos" in COMPOSE.lower(), (
|
||||
"docker-compose.yml should mention macOS UID issue (#567)"
|
||||
)
|
||||
assert "id -u" in COMPOSE, (
|
||||
"docker-compose.yml should tell users to run 'id -u' to find their UID (#567)"
|
||||
)
|
||||
|
||||
|
||||
# ── #590: transcription spinner already present ───────────────────────────────
|
||||
|
||||
def test_590_transcribing_status_shown_before_fetch():
|
||||
"""boot.js: setComposerStatus('Transcribing…') must fire before the fetch call."""
|
||||
transcribe_fn_start = BOOT_JS.find("async function _transcribeBlob(")
|
||||
assert transcribe_fn_start != -1, "_transcribeBlob not found in boot.js"
|
||||
fn_body = BOOT_JS[transcribe_fn_start:transcribe_fn_start + 600]
|
||||
status_pos = fn_body.find("setComposerStatus('Transcribing")
|
||||
fetch_pos = fn_body.find("await fetch(")
|
||||
assert status_pos != -1, (
|
||||
"setComposerStatus('Transcribing…') must be called before the fetch in _transcribeBlob"
|
||||
)
|
||||
assert fetch_pos != -1, "await fetch not found in _transcribeBlob"
|
||||
assert status_pos < fetch_pos, (
|
||||
"setComposerStatus('Transcribing…') must appear before 'await fetch' "
|
||||
"so the UI shows a spinner immediately on stop (#590)"
|
||||
)
|
||||
|
||||
|
||||
def test_590_recording_stops_before_transcribe():
|
||||
"""boot.js: _setRecording(false) must fire in onstop before _transcribeBlob."""
|
||||
onstop_start = BOOT_JS.find("mediaRecorder.onstop")
|
||||
assert onstop_start != -1, "mediaRecorder.onstop not found"
|
||||
onstop_body = BOOT_JS[onstop_start:onstop_start + 400]
|
||||
rec_pos = onstop_body.find("_setRecording(false)")
|
||||
blob_pos = onstop_body.find("_transcribeBlob(")
|
||||
assert rec_pos != -1 and blob_pos != -1
|
||||
assert rec_pos < blob_pos, (
|
||||
"_setRecording(false) must come before _transcribeBlob so mic icon clears immediately"
|
||||
)
|
||||
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'
|
||||
111
tests/test_chinese_locale.py
Normal file
111
tests/test_chinese_locale.py
Normal file
@@ -0,0 +1,111 @@
|
||||
from collections import Counter
|
||||
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 extract_locale_block(src: str, locale_key: str) -> str:
|
||||
start_match = re.search(rf"\b{re.escape(locale_key)}\s*:\s*\{{", src)
|
||||
assert start_match, f"{locale_key} locale block not found"
|
||||
|
||||
start = start_match.end() - 1 # "{"
|
||||
depth = 0
|
||||
in_single = False
|
||||
in_double = False
|
||||
in_backtick = False
|
||||
escape = False
|
||||
|
||||
for i in range(start, len(src)):
|
||||
ch = src[i]
|
||||
|
||||
if escape:
|
||||
escape = False
|
||||
continue
|
||||
|
||||
if in_single:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "'":
|
||||
in_single = False
|
||||
continue
|
||||
|
||||
if in_double:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_double = False
|
||||
continue
|
||||
|
||||
if in_backtick:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "`":
|
||||
in_backtick = False
|
||||
continue
|
||||
|
||||
if ch == "'":
|
||||
in_single = True
|
||||
continue
|
||||
if ch == '"':
|
||||
in_double = True
|
||||
continue
|
||||
if ch == "`":
|
||||
in_backtick = True
|
||||
continue
|
||||
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
continue
|
||||
if ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return src[start + 1 : i]
|
||||
|
||||
raise AssertionError(f"{locale_key} locale block braces are not balanced")
|
||||
|
||||
|
||||
def test_chinese_locale_block_exists():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
assert "\n zh: {" in src
|
||||
assert "_lang: 'zh'" in src
|
||||
assert "_speech: 'zh-CN'" in src
|
||||
|
||||
|
||||
def test_chinese_locale_includes_representative_translations():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
expected = [
|
||||
"settings_title: '\\u8bbe\\u7f6e'",
|
||||
"login_title: '\\u767b\\u5f55'",
|
||||
"approval_heading: '需要审批'",
|
||||
"tab_tasks: '任务'",
|
||||
"tab_profiles: '配置'",
|
||||
"session_time_just_now: '刚刚'",
|
||||
"onboarding_title: '欢迎使用 Hermes Web UI'",
|
||||
"onboarding_complete: '引导完成'",
|
||||
]
|
||||
for entry in expected:
|
||||
assert entry in src
|
||||
|
||||
|
||||
def test_chinese_locale_covers_english_keys():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
key_pattern = re.compile(r"^\s{4}([a-zA-Z0-9_]+):", re.MULTILINE)
|
||||
en_keys = set(key_pattern.findall(extract_locale_block(src, "en")))
|
||||
zh_keys = set(key_pattern.findall(extract_locale_block(src, "zh")))
|
||||
|
||||
missing = sorted(en_keys - zh_keys)
|
||||
assert not missing, f"Chinese locale missing keys: {missing}"
|
||||
|
||||
|
||||
def test_chinese_locale_has_no_duplicate_keys():
|
||||
src = read(REPO / "static" / "i18n.js")
|
||||
key_pattern = re.compile(r"^\s{4}([a-zA-Z0-9_]+):", re.MULTILINE)
|
||||
keys = key_pattern.findall(extract_locale_block(src, "zh"))
|
||||
duplicates = sorted(k for k, count in Counter(keys).items() if count > 1)
|
||||
assert not duplicates, f"Chinese locale has duplicate keys: {duplicates}"
|
||||
165
tests/test_clarify_unblock.py
Normal file
165
tests/test_clarify_unblock.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""Tests for clarify prompt unblocking and HTTP endpoints."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import uuid
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
|
||||
import pytest
|
||||
|
||||
try:
|
||||
from api.clarify import (
|
||||
register_gateway_notify,
|
||||
unregister_gateway_notify,
|
||||
resolve_clarify,
|
||||
clear_pending,
|
||||
_gateway_queues,
|
||||
_gateway_notify_cbs,
|
||||
_lock,
|
||||
_ClarifyEntry,
|
||||
submit_pending,
|
||||
)
|
||||
CLARIFY_AVAILABLE = True
|
||||
except ImportError:
|
||||
CLARIFY_AVAILABLE = False
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not CLARIFY_AVAILABLE,
|
||||
reason="api.clarify not available in this environment",
|
||||
)
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
url = BASE + path
|
||||
with urllib.request.urlopen(url, timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def post(path, body=None):
|
||||
url = BASE + path
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(url, 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
|
||||
|
||||
|
||||
class TestClarifyUnblocking:
|
||||
"""Unit tests for clarify queue resolution."""
|
||||
|
||||
def test_resolve_clarify_sets_event(self):
|
||||
sid = f"unit-clarify-{uuid.uuid4().hex[:8]}"
|
||||
entry = _ClarifyEntry({"question": "Pick one", "choices_offered": ["a", "b"]})
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
|
||||
resolved = resolve_clarify(sid, "a", resolve_all=False)
|
||||
assert resolved == 1
|
||||
assert entry.event.is_set()
|
||||
assert entry.result == "a"
|
||||
|
||||
def test_register_and_fire_notify_cb(self):
|
||||
sid = f"unit-notify-{uuid.uuid4().hex[:8]}"
|
||||
fired = []
|
||||
register_gateway_notify(sid, lambda d: fired.append(d))
|
||||
|
||||
with _lock:
|
||||
cb = _gateway_notify_cbs.get(sid)
|
||||
assert cb is not None
|
||||
|
||||
data = {"question": "What now?", "choices_offered": ["x", "y"]}
|
||||
cb(data)
|
||||
assert fired == [data]
|
||||
|
||||
unregister_gateway_notify(sid)
|
||||
|
||||
def test_clear_pending_unblocks_waiters(self):
|
||||
sid = f"unit-clear-{uuid.uuid4().hex[:8]}"
|
||||
entry = _ClarifyEntry({"question": "Wait", "choices_offered": []})
|
||||
with _lock:
|
||||
_gateway_queues.setdefault(sid, []).append(entry)
|
||||
|
||||
cleared = clear_pending(sid)
|
||||
assert cleared == 1
|
||||
assert entry.event.is_set()
|
||||
with _lock:
|
||||
assert sid not in _gateway_queues
|
||||
|
||||
def test_submit_pending_registers_entry(self):
|
||||
sid = f"unit-submit-{uuid.uuid4().hex[:8]}"
|
||||
data = {"question": "Pick", "choices_offered": ["one", "two"], "session_id": sid}
|
||||
entry = submit_pending(sid, data)
|
||||
assert entry.data == data
|
||||
with _lock:
|
||||
assert sid in _gateway_queues
|
||||
|
||||
clear_pending(sid)
|
||||
|
||||
|
||||
class TestClarifyModuleExports:
|
||||
def test_register_gateway_notify_exported(self):
|
||||
import api.clarify as ap
|
||||
assert hasattr(ap, "register_gateway_notify")
|
||||
|
||||
def test_unregister_gateway_notify_exported(self):
|
||||
import api.clarify as ap
|
||||
assert hasattr(ap, "unregister_gateway_notify")
|
||||
|
||||
def test_resolve_clarify_exported(self):
|
||||
import api.clarify as ap
|
||||
assert hasattr(ap, "resolve_clarify")
|
||||
|
||||
def test_clarify_entry_exported(self):
|
||||
import api.clarify as ap
|
||||
assert hasattr(ap, "_ClarifyEntry")
|
||||
|
||||
|
||||
class TestClarifyHTTPEndpoints:
|
||||
"""Regression tests for /api/clarify/respond against the live test server."""
|
||||
|
||||
def test_respond_returns_ok_no_pending(self):
|
||||
sid = f"http-no-pending-{uuid.uuid4().hex[:8]}"
|
||||
result, status = post("/api/clarify/respond", {
|
||||
"session_id": sid,
|
||||
"response": "Use option A",
|
||||
})
|
||||
assert status == 200
|
||||
assert result["ok"] is True
|
||||
|
||||
def test_respond_requires_session_id(self):
|
||||
result, status = post("/api/clarify/respond", {"response": "Hello"})
|
||||
assert status == 400
|
||||
|
||||
def test_respond_requires_response(self):
|
||||
sid = f"http-no-response-{uuid.uuid4().hex[:8]}"
|
||||
result, status = post("/api/clarify/respond", {"session_id": sid})
|
||||
assert status == 400
|
||||
|
||||
def test_respond_clears_injected_pending(self):
|
||||
sid = f"http-clear-{uuid.uuid4().hex[:8]}"
|
||||
question = urllib.parse.quote("Pick the better option")
|
||||
choices = urllib.parse.quote("A")
|
||||
inject = get(
|
||||
f"/api/clarify/inject_test?session_id={urllib.parse.quote(sid)}"
|
||||
f"&question={question}&choices={choices}"
|
||||
)
|
||||
assert inject["ok"] is True
|
||||
|
||||
data = get(f"/api/clarify/pending?session_id={urllib.parse.quote(sid)}")
|
||||
assert data["pending"] is not None
|
||||
|
||||
result, status = post("/api/clarify/respond", {
|
||||
"session_id": sid,
|
||||
"response": "B",
|
||||
})
|
||||
assert status == 200
|
||||
assert result["ok"] is True
|
||||
|
||||
data2 = get(f"/api/clarify/pending?session_id={urllib.parse.quote(sid)}")
|
||||
assert data2["pending"] is None
|
||||
135
tests/test_custom_provider_display_name.py
Normal file
135
tests/test_custom_provider_display_name.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
Tests for named custom provider display in the model dropdown (issue #557).
|
||||
|
||||
When a custom_providers entry carries a `name` field (e.g. "Agent37"), the
|
||||
web UI model picker should show that name as the group header rather than the
|
||||
generic "Custom" label.
|
||||
"""
|
||||
import api.config as config
|
||||
|
||||
|
||||
def _models_with_cfg(model_cfg=None, custom_providers=None, active_provider=None):
|
||||
"""Temporarily patch config.cfg, call get_available_models(), restore."""
|
||||
old_cfg = dict(config.cfg)
|
||||
config.cfg.clear()
|
||||
if model_cfg:
|
||||
config.cfg["model"] = model_cfg
|
||||
if custom_providers is not None:
|
||||
config.cfg["custom_providers"] = custom_providers
|
||||
try:
|
||||
return config.get_available_models()
|
||||
finally:
|
||||
config.cfg.clear()
|
||||
config.cfg.update(old_cfg)
|
||||
|
||||
|
||||
# ── Named provider shows its name in the dropdown ─────────────────────────────
|
||||
|
||||
class TestNamedCustomProviderGroup:
|
||||
|
||||
def test_named_provider_uses_name_as_group_header(self):
|
||||
"""A custom_provider entry with name='Agent37' should produce
|
||||
a group whose 'provider' key is 'Agent37', not 'Custom'."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom", "base_url": "https://agent37.example.com/v1"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "default", "base_url": "https://agent37.example.com/v1"}
|
||||
],
|
||||
)
|
||||
group_names = [g["provider"] for g in result.get("groups", [])]
|
||||
assert "Agent37" in group_names, (
|
||||
f"Expected 'Agent37' in group names, got {group_names}"
|
||||
)
|
||||
|
||||
def test_named_provider_does_not_produce_generic_custom(self):
|
||||
"""When all custom_provider entries have names, no group called 'Custom'
|
||||
should appear alongside them."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom", "base_url": "https://agent37.example.com/v1"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "default", "base_url": "https://agent37.example.com/v1"}
|
||||
],
|
||||
)
|
||||
group_names = [g["provider"] for g in result.get("groups", [])]
|
||||
assert "Custom" not in group_names, (
|
||||
f"Expected no generic 'Custom' group when all entries are named, got {group_names}"
|
||||
)
|
||||
|
||||
def test_named_provider_model_appears_in_its_group(self):
|
||||
"""The model ID from the named entry should be inside the named group."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "my-llm", "base_url": "https://agent37.example.com/v1"}
|
||||
],
|
||||
)
|
||||
agent37_group = next(
|
||||
(g for g in result.get("groups", []) if g["provider"] == "Agent37"), None
|
||||
)
|
||||
assert agent37_group is not None, "Expected an 'Agent37' group"
|
||||
model_ids = [m["id"] for m in agent37_group.get("models", [])]
|
||||
assert "my-llm" in model_ids, (
|
||||
f"Expected 'my-llm' in Agent37 group models, got {model_ids}"
|
||||
)
|
||||
|
||||
def test_multiple_named_providers_each_get_their_own_group(self):
|
||||
"""Two named custom providers should produce two distinct groups."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "fast-model"},
|
||||
{"name": "PrivateProxy", "model": "private-llm"},
|
||||
],
|
||||
)
|
||||
group_names = [g["provider"] for g in result.get("groups", [])]
|
||||
assert "Agent37" in group_names, f"Expected 'Agent37' group, got {group_names}"
|
||||
assert "PrivateProxy" in group_names, f"Expected 'PrivateProxy' group, got {group_names}"
|
||||
assert "Custom" not in group_names, f"No generic 'Custom' group expected, got {group_names}"
|
||||
|
||||
def test_multiple_models_in_same_named_provider(self):
|
||||
"""Multiple entries with the same name should be collapsed into one group."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "model-a"},
|
||||
{"name": "Agent37", "model": "model-b"},
|
||||
],
|
||||
)
|
||||
agent37_groups = [g for g in result.get("groups", []) if g["provider"] == "Agent37"]
|
||||
assert len(agent37_groups) == 1, (
|
||||
f"Expected exactly one 'Agent37' group, got {len(agent37_groups)}"
|
||||
)
|
||||
model_ids = [m["id"] for m in agent37_groups[0].get("models", [])]
|
||||
assert "model-a" in model_ids
|
||||
assert "model-b" in model_ids
|
||||
|
||||
|
||||
# ── Unnamed entry still falls back to 'Custom' ─────────────────────────────────
|
||||
|
||||
class TestUnnamedCustomProviderFallback:
|
||||
|
||||
def test_unnamed_entry_still_produces_custom_group(self):
|
||||
"""A custom_provider entry without a name should still show as 'Custom'."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom"},
|
||||
custom_providers=[
|
||||
{"model": "unnamed-model"}
|
||||
],
|
||||
)
|
||||
group_names = [g["provider"] for g in result.get("groups", [])]
|
||||
assert "Custom" in group_names, (
|
||||
f"Expected generic 'Custom' group for unnamed entry, got {group_names}"
|
||||
)
|
||||
|
||||
def test_mixed_named_and_unnamed_entries(self):
|
||||
"""Named and unnamed entries should appear in their respective groups."""
|
||||
result = _models_with_cfg(
|
||||
model_cfg={"provider": "custom"},
|
||||
custom_providers=[
|
||||
{"name": "Agent37", "model": "named-model"},
|
||||
{"model": "unnamed-model"},
|
||||
],
|
||||
)
|
||||
group_names = [g["provider"] for g in result.get("groups", [])]
|
||||
assert "Agent37" in group_names, f"Expected 'Agent37' group, got {group_names}"
|
||||
assert "Custom" in group_names, f"Expected 'Custom' group for unnamed entry, got {group_names}"
|
||||
103
tests/test_default_workspace_fallback.py
Normal file
103
tests/test_default_workspace_fallback.py
Normal file
@@ -0,0 +1,103 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import api.config as config
|
||||
|
||||
|
||||
def test_resolve_default_workspace_falls_back_to_existing_home_work(monkeypatch, tmp_path):
|
||||
preferred = tmp_path / "work"
|
||||
preferred.mkdir()
|
||||
state_dir = tmp_path / "state"
|
||||
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
|
||||
resolved = config.resolve_default_workspace("/definitely/not/usable")
|
||||
|
||||
assert resolved == preferred.resolve()
|
||||
|
||||
|
||||
|
||||
def test_save_settings_rewrites_bad_default_workspace_to_fallback(monkeypatch, tmp_path):
|
||||
preferred = tmp_path / "work"
|
||||
preferred.mkdir()
|
||||
state_dir = tmp_path / "state"
|
||||
settings_file = tmp_path / "settings.json"
|
||||
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
monkeypatch.setattr(config, "SETTINGS_FILE", settings_file)
|
||||
monkeypatch.setattr(config, "DEFAULT_WORKSPACE", preferred)
|
||||
|
||||
saved = config.save_settings({"default_workspace": "/definitely/not/usable"})
|
||||
on_disk = json.loads(settings_file.read_text(encoding="utf-8"))
|
||||
|
||||
assert saved["default_workspace"] == str(preferred.resolve())
|
||||
assert on_disk["default_workspace"] == str(preferred.resolve())
|
||||
|
||||
|
||||
def test_resolve_default_workspace_creates_home_workspace_when_missing(monkeypatch, tmp_path):
|
||||
"""When no preferred dir exists, resolve falls back to creating ~/workspace."""
|
||||
state_dir = tmp_path / "state"
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
# Neither ~/work nor ~/workspace exists yet
|
||||
resolved = config.resolve_default_workspace(None)
|
||||
assert resolved == (tmp_path / "workspace").resolve()
|
||||
assert resolved.is_dir()
|
||||
|
||||
|
||||
def test_resolve_default_workspace_raises_when_all_candidates_fail(monkeypatch, tmp_path):
|
||||
"""RuntimeError is raised when every candidate is unwritable."""
|
||||
import stat, pytest
|
||||
# Make tmp_path read-only so mkdir inside it fails
|
||||
tmp_path.chmod(stat.S_IRUSR | stat.S_IXUSR)
|
||||
state_dir = tmp_path / "state"
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
monkeypatch.delenv("HERMES_WEBUI_DEFAULT_WORKSPACE", raising=False)
|
||||
try:
|
||||
with pytest.raises(RuntimeError, match="Could not create or access"):
|
||||
config.resolve_default_workspace(None)
|
||||
finally:
|
||||
tmp_path.chmod(stat.S_IRWXU) # restore for cleanup
|
||||
|
||||
|
||||
def test_workspace_candidates_deduplicates_home_workspace(monkeypatch, tmp_path):
|
||||
"""~/workspace must appear at most once in the candidates list even if it exists."""
|
||||
ws = tmp_path / "workspace"
|
||||
ws.mkdir()
|
||||
state_dir = tmp_path / "state"
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
monkeypatch.delenv("HERMES_WEBUI_DEFAULT_WORKSPACE", raising=False)
|
||||
candidates = config._workspace_candidates(None)
|
||||
paths = [str(p) for p in candidates]
|
||||
assert paths.count(str(ws.resolve())) <= 1, "~/workspace must not appear twice"
|
||||
|
||||
|
||||
def test_env_var_workspace_takes_priority_over_passed_raw(monkeypatch, tmp_path):
|
||||
"""HERMES_WEBUI_DEFAULT_WORKSPACE env var overrides a None raw arg but not a valid one."""
|
||||
env_ws = tmp_path / "env_workspace"
|
||||
env_ws.mkdir()
|
||||
state_dir = tmp_path / "state"
|
||||
monkeypatch.setattr(config, "HOME", tmp_path)
|
||||
monkeypatch.setattr(config, "STATE_DIR", state_dir)
|
||||
monkeypatch.setenv("HERMES_WEBUI_DEFAULT_WORKSPACE", str(env_ws))
|
||||
# When raw is None, env var should be used
|
||||
resolved = config.resolve_default_workspace(None)
|
||||
assert resolved == env_ws.resolve()
|
||||
|
||||
|
||||
def test_ensure_workspace_dir_returns_false_for_unwritable_path(monkeypatch, tmp_path):
|
||||
"""_ensure_workspace_dir returns False for a path that can't be created."""
|
||||
import stat
|
||||
# Make parent read-only so mkdir fails
|
||||
parent = tmp_path / "ro_parent"
|
||||
parent.mkdir()
|
||||
parent.chmod(stat.S_IRUSR | stat.S_IXUSR)
|
||||
try:
|
||||
result = config._ensure_workspace_dir(parent / "child")
|
||||
assert result is False
|
||||
finally:
|
||||
parent.chmod(stat.S_IRWXU)
|
||||
420
tests/test_gateway_sync.py
Normal file
420
tests/test_gateway_sync.py
Normal file
@@ -0,0 +1,420 @@
|
||||
"""
|
||||
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()
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
# Use _pytest_port which applies the same auto-derivation as conftest.py
|
||||
from tests._pytest_port import TEST_STATE_DIR as _ptsd
|
||||
return _ptsd
|
||||
|
||||
|
||||
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_importing_older_gateway_session_preserves_original_timestamps_and_order():
|
||||
"""Importing an older gateway session should not bump it above newer WebUI sessions."""
|
||||
conn = _ensure_state_db()
|
||||
older_started_at = time.time() - 1800
|
||||
imported_sid = 'gw_import_old_001'
|
||||
newer_webui_sid = None
|
||||
try:
|
||||
newer_webui, status = post('/api/session/new', {'model': 'openai/gpt-5'})
|
||||
assert status == 200, newer_webui
|
||||
newer_webui_sid = newer_webui['session']['session_id']
|
||||
|
||||
rename, rename_status = post(
|
||||
'/api/session/rename',
|
||||
{'session_id': newer_webui_sid, 'title': 'Newer WebUI Session'},
|
||||
)
|
||||
assert rename_status == 200, rename
|
||||
|
||||
_insert_gateway_session(
|
||||
conn,
|
||||
session_id=imported_sid,
|
||||
source='discord',
|
||||
title='Older imported gateway session',
|
||||
started_at=older_started_at,
|
||||
)
|
||||
post('/api/settings', {'show_cli_sessions': True})
|
||||
|
||||
imported, imported_status = post('/api/session/import_cli', {'session_id': imported_sid})
|
||||
assert imported_status == 200, imported
|
||||
imported_session = imported['session']
|
||||
assert abs(imported_session['created_at'] - older_started_at) < 2, imported_session
|
||||
assert abs(imported_session['updated_at'] - older_started_at) < 5, imported_session
|
||||
|
||||
sessions_payload, sessions_status = get('/api/sessions')
|
||||
assert sessions_status == 200, sessions_payload
|
||||
ordered_ids = [item['session_id'] for item in sessions_payload.get('sessions', [])]
|
||||
assert newer_webui_sid in ordered_ids, ordered_ids
|
||||
assert imported_sid in ordered_ids, ordered_ids
|
||||
assert ordered_ids.index(newer_webui_sid) < ordered_ids.index(imported_sid), ordered_ids
|
||||
finally:
|
||||
try:
|
||||
_remove_test_sessions(conn, imported_sid)
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
if imported_sid:
|
||||
try:
|
||||
post('/api/session/delete', {'session_id': imported_sid})
|
||||
except Exception:
|
||||
pass
|
||||
if newer_webui_sid:
|
||||
try:
|
||||
post('/api/session/delete', {'session_id': newer_webui_sid})
|
||||
except Exception:
|
||||
pass
|
||||
post('/api/settings', {'show_cli_sessions': False})
|
||||
|
||||
|
||||
|
||||
def test_gateway_sse_stream_endpoint_exists():
|
||||
"""GET /api/sessions/gateway/stream returns a response (200 or 200-range)."""
|
||||
# The SSE endpoint requires show_cli_sessions to be enabled
|
||||
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})
|
||||
61
tests/test_ime_composition.py
Normal file
61
tests/test_ime_composition.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
BOOT_JS = (REPO_ROOT / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text(encoding="utf-8")
|
||||
SESSIONS_JS = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _ime_guarded_enter_pattern(event_var_pattern, require_no_shift=False):
|
||||
no_shift = rf"\s*&&\s*!\s*{event_var_pattern}\.shiftKey" if require_no_shift else ""
|
||||
return (
|
||||
rf"if\s*\(\s*{event_var_pattern}\.key\s*===\s*'Enter'{no_shift}\s*\)\s*\{{\s*"
|
||||
rf"if\s*\(\s*{event_var_pattern}\.isComposing\s*\)\s*"
|
||||
rf"(?:\{{\s*return\s*;?\s*\}}|return\s*;?)"
|
||||
)
|
||||
|
||||
|
||||
def test_boot_chat_enter_send_respects_ime_composition():
|
||||
assert re.search(
|
||||
_ime_guarded_enter_pattern("e"),
|
||||
BOOT_JS,
|
||||
re.DOTALL,
|
||||
), "Chat composer Enter handler must ignore IME composition Enter in static/boot.js"
|
||||
assert re.search(
|
||||
_ime_guarded_enter_pattern("e", require_no_shift=True),
|
||||
BOOT_JS,
|
||||
re.DOTALL,
|
||||
), "Command dropdown Enter handler must ignore IME composition Enter in static/boot.js"
|
||||
|
||||
|
||||
def test_ui_enter_submit_paths_respect_ime_composition():
|
||||
assert re.search(
|
||||
rf"document\.addEventListener\('keydown',e=>\{{[\s\S]*?{_ime_guarded_enter_pattern('e')}",
|
||||
UI_JS,
|
||||
re.DOTALL,
|
||||
), \
|
||||
"App dialog Enter handler must ignore IME composition Enter in static/ui.js"
|
||||
assert re.search(
|
||||
_ime_guarded_enter_pattern("e", require_no_shift=True),
|
||||
UI_JS,
|
||||
re.DOTALL,
|
||||
), \
|
||||
"Message edit Enter-to-save handler must ignore IME composition Enter in static/ui.js"
|
||||
assert re.search(
|
||||
rf"inp\.onkeydown=\(e2\)=>\{{\s*{_ime_guarded_enter_pattern('e2')}",
|
||||
UI_JS,
|
||||
re.DOTALL,
|
||||
), \
|
||||
"Workspace rename Enter handler must ignore IME composition Enter in static/ui.js"
|
||||
|
||||
|
||||
def test_sessions_enter_submit_paths_respect_ime_composition():
|
||||
matches = re.findall(
|
||||
_ime_guarded_enter_pattern(r"e2?"),
|
||||
SESSIONS_JS,
|
||||
re.DOTALL,
|
||||
)
|
||||
assert len(matches) >= 3, \
|
||||
"Session and project rename/create Enter handlers must ignore IME composition Enter in static/sessions.js"
|
||||
322
tests/test_issue336.py
Normal file
322
tests/test_issue336.py
Normal file
@@ -0,0 +1,322 @@
|
||||
"""
|
||||
Tests for issue #336 — opt-in chat bubble layout (PR #398).
|
||||
|
||||
Covers:
|
||||
- api/config.py: bubble_layout present in _SETTINGS_DEFAULTS with default False
|
||||
- api/config.py: bubble_layout present in _SETTINGS_BOOL_KEYS
|
||||
- api/config.py: bubble_layout not in password-filtered keys (safe to expose)
|
||||
- static/boot.js: boot path applies bubble-layout class from settings
|
||||
- static/boot.js: catch path removes bubble-layout class on API failure
|
||||
- static/panels.js: loadSettingsPanel reads bubble_layout checkbox
|
||||
- static/panels.js: saveSettings writes bubble_layout and toggles body class
|
||||
- static/style.css: body.bubble-layout CSS selectors present
|
||||
- static/style.css: responsive max-width rule for bubble layout
|
||||
- static/index.html: settingsBubbleLayout checkbox element present
|
||||
- static/index.html: i18n keys wired on label and description
|
||||
- static/i18n.js: English label and description keys present
|
||||
- static/i18n.js: Spanish label and description keys present
|
||||
- Integration: bubble_layout default is False in GET /api/settings
|
||||
- Integration: bubble_layout persists via POST /api/settings
|
||||
- Integration: non-bool value is coerced to bool on POST
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
CONFIG_PY = (REPO_ROOT / "api" / "config.py").read_text()
|
||||
BOOT_JS = (REPO_ROOT / "static" / "boot.js").read_text()
|
||||
PANELS_JS = (REPO_ROOT / "static" / "panels.js").read_text()
|
||||
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text()
|
||||
INDEX_HTML = (REPO_ROOT / "static" / "index.html").read_text()
|
||||
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text()
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def _get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
|
||||
|
||||
def _post(path, body=None):
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(
|
||||
BASE + path, data=data, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
# ── config.py static checks ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutConfig(unittest.TestCase):
|
||||
"""Verify bubble_layout is correctly registered in config.py."""
|
||||
|
||||
def test_bubble_layout_in_settings_defaults(self):
|
||||
"""bubble_layout must appear in _SETTINGS_DEFAULTS."""
|
||||
self.assertIn(
|
||||
'"bubble_layout"',
|
||||
CONFIG_PY,
|
||||
"bubble_layout key missing from _SETTINGS_DEFAULTS in api/config.py",
|
||||
)
|
||||
|
||||
def test_bubble_layout_default_is_false(self):
|
||||
"""bubble_layout default value must be False (opt-in, off by default)."""
|
||||
# Match "bubble_layout": False with optional spacing
|
||||
self.assertRegex(
|
||||
CONFIG_PY,
|
||||
r'"bubble_layout"\s*:\s*False',
|
||||
"bubble_layout default must be False in _SETTINGS_DEFAULTS",
|
||||
)
|
||||
|
||||
def test_bubble_layout_in_bool_keys(self):
|
||||
"""bubble_layout must be in _SETTINGS_BOOL_KEYS for coercion."""
|
||||
# Find the _SETTINGS_BOOL_KEYS block and verify membership
|
||||
bool_keys_match = re.search(
|
||||
r"_SETTINGS_BOOL_KEYS\s*=\s*\{([^}]+)\}", CONFIG_PY, re.DOTALL
|
||||
)
|
||||
self.assertIsNotNone(
|
||||
bool_keys_match, "_SETTINGS_BOOL_KEYS block not found in config.py"
|
||||
)
|
||||
self.assertIn(
|
||||
'"bubble_layout"',
|
||||
bool_keys_match.group(1),
|
||||
"bubble_layout missing from _SETTINGS_BOOL_KEYS",
|
||||
)
|
||||
|
||||
|
||||
# ── boot.js static checks ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutBootJS(unittest.TestCase):
|
||||
"""Verify bubble-layout class management in boot.js."""
|
||||
|
||||
def test_boot_applies_bubble_layout_class(self):
|
||||
"""boot.js success path must toggle body.bubble-layout from settings."""
|
||||
self.assertIn(
|
||||
"classList.toggle('bubble-layout',!!s.bubble_layout)",
|
||||
BOOT_JS,
|
||||
"boot.js must call classList.toggle('bubble-layout', ...) on settings load",
|
||||
)
|
||||
|
||||
def test_boot_catch_removes_bubble_layout_class(self):
|
||||
"""boot.js catch path must remove bubble-layout (default off on API failure)."""
|
||||
self.assertIn(
|
||||
"classList.remove('bubble-layout')",
|
||||
BOOT_JS,
|
||||
"boot.js catch block must call classList.remove('bubble-layout') on API failure",
|
||||
)
|
||||
|
||||
|
||||
# ── panels.js static checks ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutPanelsJS(unittest.TestCase):
|
||||
"""Verify settings panel wires the bubble_layout checkbox."""
|
||||
|
||||
def test_load_settings_reads_bubble_layout_checkbox(self):
|
||||
"""loadSettingsPanel must read the settingsBubbleLayout checkbox state."""
|
||||
self.assertIn(
|
||||
"settingsBubbleLayout",
|
||||
PANELS_JS,
|
||||
"panels.js must reference settingsBubbleLayout checkbox",
|
||||
)
|
||||
|
||||
def test_save_settings_writes_bubble_layout(self):
|
||||
"""saveSettings must write body.bubble_layout from the checkbox."""
|
||||
self.assertIn(
|
||||
"body.bubble_layout",
|
||||
PANELS_JS,
|
||||
"saveSettings must set body.bubble_layout from checkbox",
|
||||
)
|
||||
|
||||
def test_save_settings_toggles_body_class(self):
|
||||
"""saveSettings must apply body class toggle for live preview."""
|
||||
self.assertIn(
|
||||
"classList.toggle('bubble-layout', body.bubble_layout)",
|
||||
PANELS_JS,
|
||||
"saveSettings must toggle 'bubble-layout' on document.body for live preview",
|
||||
)
|
||||
|
||||
|
||||
# ── style.css static checks ──────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutCSS(unittest.TestCase):
|
||||
"""Verify CSS selectors for bubble layout are present and gated on body class."""
|
||||
|
||||
def test_user_row_right_align_selector_present(self):
|
||||
"""CSS must right-align user message rows when bubble-layout is active."""
|
||||
self.assertIn(
|
||||
"body.bubble-layout .msg-row:has(.msg-role.user)",
|
||||
STYLE_CSS,
|
||||
"CSS selector for user bubble alignment missing from style.css",
|
||||
)
|
||||
|
||||
def test_assistant_row_left_align_selector_present(self):
|
||||
"""CSS must left-align assistant message rows when bubble-layout is active."""
|
||||
self.assertIn(
|
||||
"body.bubble-layout .msg-row:has(.msg-role.assistant)",
|
||||
STYLE_CSS,
|
||||
"CSS selector for assistant bubble alignment missing from style.css",
|
||||
)
|
||||
|
||||
def test_bubble_layout_responsive_rule_present(self):
|
||||
"""A responsive max-width rule for narrow screens must be present."""
|
||||
# Both selectors must appear inside a @media block
|
||||
self.assertRegex(
|
||||
STYLE_CSS,
|
||||
r"@media\([^)]*700px[^)]*\)[^{]*\{[^}]*bubble-layout",
|
||||
"Responsive bubble-layout rule (700px breakpoint) missing from style.css",
|
||||
)
|
||||
|
||||
|
||||
# ── index.html static checks ─────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutHTML(unittest.TestCase):
|
||||
"""Verify the settings checkbox is present and correctly wired in index.html."""
|
||||
|
||||
def test_settings_checkbox_present(self):
|
||||
"""The settingsBubbleLayout checkbox must exist in index.html."""
|
||||
self.assertIn(
|
||||
'id="settingsBubbleLayout"',
|
||||
INDEX_HTML,
|
||||
"settingsBubbleLayout checkbox missing from index.html",
|
||||
)
|
||||
|
||||
def test_settings_label_i18n_key_wired(self):
|
||||
"""Label span must carry the settings_label_bubble_layout i18n key."""
|
||||
self.assertIn(
|
||||
'data-i18n="settings_label_bubble_layout"',
|
||||
INDEX_HTML,
|
||||
"settings_label_bubble_layout i18n key not wired on label span",
|
||||
)
|
||||
|
||||
def test_settings_desc_i18n_key_wired(self):
|
||||
"""Description div must carry the settings_desc_bubble_layout i18n key."""
|
||||
self.assertIn(
|
||||
'data-i18n="settings_desc_bubble_layout"',
|
||||
INDEX_HTML,
|
||||
"settings_desc_bubble_layout i18n key not wired on description div",
|
||||
)
|
||||
|
||||
|
||||
# ── i18n.js static checks ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutI18N(unittest.TestCase):
|
||||
"""Verify English and Spanish locale keys are present in i18n.js."""
|
||||
|
||||
def _extract_locale_block(self, lang_start_marker, lang_end_marker):
|
||||
"""Extract the content between two locale markers."""
|
||||
start = I18N_JS.find(lang_start_marker)
|
||||
end = I18N_JS.find(lang_end_marker, start)
|
||||
self.assertGreater(start, -1, f"Start marker '{lang_start_marker}' not found")
|
||||
self.assertGreater(end, start, f"End marker '{lang_end_marker}' not found after start")
|
||||
return I18N_JS[start:end]
|
||||
|
||||
def test_english_label_key_present(self):
|
||||
"""English locale must have settings_label_bubble_layout."""
|
||||
en_block = self._extract_locale_block("\n en: {", "\n es: {")
|
||||
self.assertIn(
|
||||
"settings_label_bubble_layout",
|
||||
en_block,
|
||||
"settings_label_bubble_layout missing from English locale",
|
||||
)
|
||||
|
||||
def test_english_desc_key_present(self):
|
||||
"""English locale must have settings_desc_bubble_layout."""
|
||||
en_block = self._extract_locale_block("\n en: {", "\n es: {")
|
||||
self.assertIn(
|
||||
"settings_desc_bubble_layout",
|
||||
en_block,
|
||||
"settings_desc_bubble_layout missing from English locale",
|
||||
)
|
||||
|
||||
def test_spanish_label_key_present(self):
|
||||
"""Spanish locale must have settings_label_bubble_layout."""
|
||||
es_block = self._extract_locale_block("\n es: {", "\n de: {")
|
||||
self.assertIn(
|
||||
"settings_label_bubble_layout",
|
||||
es_block,
|
||||
"settings_label_bubble_layout missing from Spanish locale",
|
||||
)
|
||||
|
||||
def test_spanish_desc_key_present(self):
|
||||
"""Spanish locale must have settings_desc_bubble_layout."""
|
||||
es_block = self._extract_locale_block("\n es: {", "\n de: {")
|
||||
self.assertIn(
|
||||
"settings_desc_bubble_layout",
|
||||
es_block,
|
||||
"settings_desc_bubble_layout missing from Spanish locale",
|
||||
)
|
||||
|
||||
|
||||
# ── Integration tests (require live server on test server port) ─────────────────
|
||||
|
||||
|
||||
class TestBubbleLayoutSettingsAPI(unittest.TestCase):
|
||||
"""Integration tests: bubble_layout via GET/POST /api/settings."""
|
||||
|
||||
def test_bubble_layout_default_is_false(self):
|
||||
"""GET /api/settings must return bubble_layout: false by default."""
|
||||
try:
|
||||
d, status = _get("/api/settings")
|
||||
except OSError:
|
||||
self.skipTest("Server not running on test server port")
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIn(
|
||||
"bubble_layout",
|
||||
d,
|
||||
"bubble_layout missing from GET /api/settings response",
|
||||
)
|
||||
self.assertFalse(
|
||||
d["bubble_layout"],
|
||||
"bubble_layout default must be False (opt-in feature)",
|
||||
)
|
||||
|
||||
def test_bubble_layout_persists_true(self):
|
||||
"""POST /api/settings with bubble_layout:true must persist and round-trip."""
|
||||
try:
|
||||
_, status = _post("/api/settings", {"bubble_layout": True})
|
||||
except OSError:
|
||||
self.skipTest("Server not running on test server port")
|
||||
self.assertEqual(status, 200)
|
||||
d, _ = _get("/api/settings")
|
||||
self.assertTrue(d["bubble_layout"], "bubble_layout=True must persist after POST")
|
||||
# Restore
|
||||
_post("/api/settings", {"bubble_layout": False})
|
||||
|
||||
def test_bubble_layout_persists_false(self):
|
||||
"""POST /api/settings with bubble_layout:false must persist and round-trip."""
|
||||
try:
|
||||
_post("/api/settings", {"bubble_layout": True})
|
||||
_post("/api/settings", {"bubble_layout": False})
|
||||
except OSError:
|
||||
self.skipTest("Server not running on test server port")
|
||||
d, _ = _get("/api/settings")
|
||||
self.assertFalse(d["bubble_layout"], "bubble_layout=False must persist after POST")
|
||||
|
||||
def test_bubble_layout_truthy_string_coerced_to_bool(self):
|
||||
"""Non-bool truthy value must be coerced to bool by _SETTINGS_BOOL_KEYS logic."""
|
||||
try:
|
||||
_post("/api/settings", {"bubble_layout": "1"})
|
||||
except OSError:
|
||||
self.skipTest("Server not running on test server port")
|
||||
d, _ = _get("/api/settings")
|
||||
self.assertIsInstance(
|
||||
d["bubble_layout"],
|
||||
bool,
|
||||
"bubble_layout must be a bool in API response (bool coercion via _SETTINGS_BOOL_KEYS)",
|
||||
)
|
||||
# Restore
|
||||
_post("/api/settings", {"bubble_layout": False})
|
||||
34
tests/test_issue341.py
Normal file
34
tests/test_issue341.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""Tests for GitHub issue #341: .msg-body table CSS styles."""
|
||||
import os
|
||||
|
||||
CSS_PATH = os.path.join(os.path.dirname(__file__), "..", "static", "style.css")
|
||||
|
||||
|
||||
def _read_css():
|
||||
with open(CSS_PATH, "r") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def test_msg_body_table_css_present():
|
||||
css = _read_css()
|
||||
assert ".msg-body table" in css, ".msg-body table rule missing from style.css"
|
||||
assert "border-collapse:collapse" in css, "border-collapse:collapse missing from style.css"
|
||||
|
||||
|
||||
def test_msg_body_table_th_td_present():
|
||||
css = _read_css()
|
||||
assert ".msg-body th" in css, ".msg-body th rule missing from style.css"
|
||||
assert ".msg-body td" in css, ".msg-body td rule missing from style.css"
|
||||
|
||||
|
||||
def test_msg_body_table_tr_stripe_present():
|
||||
css = _read_css()
|
||||
assert ".msg-body tr:nth-child(even)" in css, ".msg-body tr:nth-child(even) rule missing from style.css"
|
||||
|
||||
|
||||
def test_msg_body_light_theme_overrides():
|
||||
css = _read_css()
|
||||
assert ':root[data-theme="light"] .msg-body th' in css, \
|
||||
'Light-theme override for .msg-body th missing from style.css'
|
||||
assert ':root[data-theme="light"] .msg-body td' in css, \
|
||||
'Light-theme override for .msg-body td missing from style.css'
|
||||
124
tests/test_issue342.py
Normal file
124
tests/test_issue342.py
Normal file
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
Tests for GitHub issue #342: auto-link plain URLs in chat messages.
|
||||
|
||||
These are structural tests that verify the fix is present in static/ui.js
|
||||
without requiring a running server or JavaScript engine.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
|
||||
UI_JS = os.path.join(os.path.dirname(__file__), '..', 'static', 'ui.js')
|
||||
|
||||
|
||||
def read_ui_js():
|
||||
with open(UI_JS, 'r') as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def test_autolink_comment_present():
|
||||
"""The Autolink comment should be present in renderMd() to document the feature."""
|
||||
content = read_ui_js()
|
||||
assert 'Autolink: convert plain URLs' in content, (
|
||||
"Expected 'Autolink: convert plain URLs' comment not found in static/ui.js. "
|
||||
"Did the autolink pass get added?"
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_regex_in_rendermd():
|
||||
"""The autolink regex pattern (https?://) should appear in renderMd()."""
|
||||
content = read_ui_js()
|
||||
# Locate the renderMd function body
|
||||
rendermd_start = content.find('function renderMd(raw){')
|
||||
assert rendermd_start != -1, "renderMd function not found in ui.js"
|
||||
# Find the closing brace after renderMd (look for the autolink pattern within it)
|
||||
rendermd_body = content[rendermd_start:rendermd_start + 5000]
|
||||
assert 'https?:\\/\\/' in rendermd_body, (
|
||||
"Autolink regex (https?:\\/\\/) not found inside renderMd() body."
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_uses_esc_for_xss_safety():
|
||||
"""The autolink code must use esc() to escape the display text of URLs, preventing XSS.
|
||||
Note: esc() is intentionally NOT applied to the href value (that would corrupt & in
|
||||
query strings). It IS applied to the visible link text (esc(clean)) to prevent XSS."""
|
||||
content = read_ui_js()
|
||||
# Find the autolink section (between the SAFE_TAGS pass and paragraph wrap)
|
||||
autolink_idx = content.find('// Autolink: convert plain URLs')
|
||||
assert autolink_idx != -1, "Autolink comment not found in ui.js"
|
||||
# Extract the autolink block (next ~600 chars after the comment)
|
||||
autolink_block = content[autolink_idx:autolink_idx + 600]
|
||||
# esc() must be used on the visible link text to prevent XSS
|
||||
assert 'esc(clean)' in autolink_block, (
|
||||
"Autolink block should use esc(clean) for the link display text (XSS safety), "
|
||||
"but it was not found."
|
||||
)
|
||||
# esc() must NOT be used on the href value — that breaks URLs containing &
|
||||
assert 'href="${esc(clean)}"' not in autolink_block, (
|
||||
"Autolink block should use href=\"${clean}\" (not esc'd) to preserve & in query strings."
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_in_inline_md():
|
||||
"""The autolink pass should also be present inside the inlineMd() helper."""
|
||||
content = read_ui_js()
|
||||
# Find inlineMd function
|
||||
inline_start = content.find('function inlineMd(t){')
|
||||
assert inline_start != -1, "inlineMd function not found in ui.js"
|
||||
# Find closing brace of inlineMd by looking for 'return t;' followed by '}'
|
||||
inline_end = content.find('return t;\n }', inline_start)
|
||||
assert inline_end != -1, "Could not locate end of inlineMd function"
|
||||
inline_body = content[inline_start:inline_end + 20]
|
||||
assert 'https?:\\/\\/' in inline_body, (
|
||||
"Autolink regex not found inside inlineMd() — plain URLs in list items "
|
||||
"and blockquotes won't be autolinked."
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_after_safe_tags_pass():
|
||||
"""The autolink pass must come AFTER the SAFE_TAGS escape pass (ordering matters)."""
|
||||
content = read_ui_js()
|
||||
safe_tags_idx = content.find('s=s.replace(/<\\/?[a-z][^>]*>/gi,tag=>SAFE_TAGS.test(tag)?tag:esc(tag));')
|
||||
autolink_idx = content.find('// Autolink: convert plain URLs')
|
||||
parts_idx = content.find('const parts=s.split(/\\n{2,}/);')
|
||||
assert safe_tags_idx != -1, "SAFE_TAGS pass not found"
|
||||
assert autolink_idx != -1, "Autolink pass not found"
|
||||
assert parts_idx != -1, "Paragraph-wrap parts line not found"
|
||||
assert safe_tags_idx < autolink_idx < parts_idx, (
|
||||
f"Ordering wrong: SAFE_TAGS at {safe_tags_idx}, autolink at {autolink_idx}, "
|
||||
f"parts (paragraph wrap) at {parts_idx}. "
|
||||
"Autolink must come between SAFE_TAGS pass and paragraph wrap."
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_target_blank_and_rel():
|
||||
"""Autolinked URLs should open in a new tab with rel=noopener for security."""
|
||||
content = read_ui_js()
|
||||
autolink_idx = content.find('// Autolink: convert plain URLs')
|
||||
assert autolink_idx != -1, "Autolink comment not found"
|
||||
# Use a larger window to account for the stash preamble added by the fix
|
||||
autolink_block = content[autolink_idx:autolink_idx + 700]
|
||||
assert 'target="_blank"' in autolink_block, (
|
||||
'Autolinked URLs should have target="_blank"'
|
||||
)
|
||||
assert 'rel="noopener"' in autolink_block, (
|
||||
'Autolinked URLs should have rel="noopener" for security'
|
||||
)
|
||||
|
||||
|
||||
def test_safe_tags_includes_anchor():
|
||||
"""SAFE_TAGS regex must include 'a' so <a> tags from autolink are not escaped."""
|
||||
content = read_ui_js()
|
||||
# Find the SAFE_TAGS definition line — the pattern contains slashes so we
|
||||
# search for the line directly rather than extracting the regex literal.
|
||||
safe_tags_line = None
|
||||
for line in content.splitlines():
|
||||
if 'const SAFE_TAGS=' in line:
|
||||
safe_tags_line = line
|
||||
break
|
||||
assert safe_tags_line is not None, "SAFE_TAGS const definition not found in ui.js"
|
||||
# The pattern should include 'a' as a tag alternative (e.g. |a|)
|
||||
assert '|a|' in safe_tags_line or '|a)' in safe_tags_line, (
|
||||
f"SAFE_TAGS line does not include 'a' tag — "
|
||||
"<a> tags emitted by autolink would be escaped!\n"
|
||||
f"Line: {safe_tags_line}"
|
||||
)
|
||||
348
tests/test_issue347.py
Normal file
348
tests/test_issue347.py
Normal file
@@ -0,0 +1,348 @@
|
||||
"""
|
||||
Tests for GitHub issue #347: KaTeX / LaTeX math rendering in chat and workspace previews.
|
||||
|
||||
Structural tests — no server required. Verify:
|
||||
- renderMd() stashes and restores $..$ and $$...$$ math delimiters
|
||||
- KaTeX lazy-load function exists and follows the mermaid pattern
|
||||
- KaTeX JS loaded from CDN with SRI integrity hash
|
||||
- KaTeX CSS loaded in index.html with SRI hash
|
||||
- CSS rules present for .katex-block and .katex-inline
|
||||
- SAFE_TAGS updated to allow <span> (for inline math)
|
||||
- renderKatexBlocks() is wired into the requestAnimationFrame call
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
UI_JS = (REPO / 'static' / 'ui.js').read_text(encoding='utf-8')
|
||||
INDEX = (REPO / 'static' / 'index.html').read_text(encoding='utf-8')
|
||||
CSS = (REPO / 'static' / 'style.css').read_text(encoding='utf-8')
|
||||
|
||||
|
||||
# ── renderMd pipeline ──────────────────────────────────────────────────────────
|
||||
|
||||
def test_display_math_stash_present():
|
||||
"""renderMd must stash $$...$$ display math before other processing."""
|
||||
assert r'\$\$([\s\S]+?)\$\$' in UI_JS or '$$' in UI_JS, \
|
||||
'Display math $$..$$ stash regex not found in ui.js'
|
||||
# The stash uses \\x00M token
|
||||
assert '\\x00M' in UI_JS, 'Math stash token \\x00M not found in renderMd'
|
||||
|
||||
|
||||
def test_inline_math_stash_present():
|
||||
"""renderMd must stash $..$ inline math."""
|
||||
# Inline math regex must be present
|
||||
assert 'math_stash' in UI_JS, 'math_stash array not found in renderMd'
|
||||
|
||||
|
||||
def test_katex_block_placeholder_emitted():
|
||||
"""renderMd restore pass must emit .katex-block divs for display math."""
|
||||
assert 'katex-block' in UI_JS, \
|
||||
'.katex-block placeholder div not emitted by renderMd restore pass'
|
||||
|
||||
|
||||
def test_katex_inline_placeholder_emitted():
|
||||
"""renderMd restore pass must emit .katex-inline spans for inline math."""
|
||||
assert 'katex-inline' in UI_JS, \
|
||||
'.katex-inline placeholder span not emitted by renderMd restore pass'
|
||||
|
||||
|
||||
def test_data_katex_attribute_present():
|
||||
"""Placeholders must carry data-katex attribute for display/inline distinction."""
|
||||
assert 'data-katex' in UI_JS, \
|
||||
'data-katex attribute not found — renderKatexBlocks cannot distinguish display from inline'
|
||||
|
||||
|
||||
# ── renderKatexBlocks() ────────────────────────────────────────────────────────
|
||||
|
||||
def test_render_katex_blocks_function_exists():
|
||||
"""renderKatexBlocks() function must exist in ui.js."""
|
||||
assert 'function renderKatexBlocks()' in UI_JS, \
|
||||
'renderKatexBlocks() function not found in ui.js'
|
||||
|
||||
|
||||
def test_katex_lazy_load_follows_mermaid_pattern():
|
||||
"""KaTeX must use the same lazy-load pattern as mermaid (load on first use)."""
|
||||
assert '_katexLoading' in UI_JS, '_katexLoading flag not found'
|
||||
assert '_katexReady' in UI_JS, '_katexReady flag not found'
|
||||
|
||||
|
||||
def test_katex_js_loaded_from_cdn():
|
||||
"""KaTeX JS must be loaded from jsdelivr CDN."""
|
||||
assert 'katex@0.16' in UI_JS, \
|
||||
'KaTeX JS CDN URL not found in ui.js — expected katex@0.16.x'
|
||||
|
||||
|
||||
def test_katex_js_has_sri_hash():
|
||||
"""KaTeX JS CDN tag must have an SRI integrity hash."""
|
||||
# The hash is in the script.integrity assignment
|
||||
assert "script.integrity='sha384-" in UI_JS or 'script.integrity="sha384-' in UI_JS, \
|
||||
'KaTeX JS SRI integrity hash not found in ui.js'
|
||||
|
||||
|
||||
def test_katex_display_mode_used():
|
||||
"""renderKatexBlocks must pass displayMode based on data-katex attribute."""
|
||||
assert 'displayMode' in UI_JS, \
|
||||
'displayMode not passed to katex.render() — display math will render inline'
|
||||
|
||||
|
||||
def test_katex_throw_on_error_false():
|
||||
"""KaTeX must be configured with throwOnError:false to degrade gracefully."""
|
||||
assert 'throwOnError:false' in UI_JS, \
|
||||
'throwOnError:false not set — bad LaTeX will throw and break the message'
|
||||
|
||||
|
||||
def test_render_katex_blocks_wired_into_raf():
|
||||
"""renderKatexBlocks() must be called in the same requestAnimationFrame as renderMermaidBlocks()."""
|
||||
# Check that renderKatexBlocks appears somewhere near requestAnimationFrame
|
||||
raf_idx = UI_JS.find('requestAnimationFrame')
|
||||
# Find the rAF call that also contains renderKatexBlocks
|
||||
has_katex_in_raf = any(
|
||||
'renderKatexBlocks' in UI_JS[m.start():m.start()+200]
|
||||
for m in re.finditer(r'requestAnimationFrame', UI_JS)
|
||||
)
|
||||
assert has_katex_in_raf, \
|
||||
'renderKatexBlocks() not found in any requestAnimationFrame call — math will not render'
|
||||
|
||||
|
||||
# ── index.html ────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_katex_css_in_index_html():
|
||||
"""KaTeX CSS must be loaded in index.html."""
|
||||
assert 'katex@0.16' in INDEX, \
|
||||
'KaTeX CSS CDN link not found in index.html'
|
||||
|
||||
|
||||
def test_katex_css_has_sri_hash():
|
||||
"""KaTeX CSS link in index.html must have an SRI integrity hash."""
|
||||
assert 'sha384-5TcZemv2l' in INDEX or 'integrity' in INDEX and 'katex' in INDEX, \
|
||||
'KaTeX CSS SRI integrity hash not found in index.html'
|
||||
|
||||
|
||||
# ── style.css ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_katex_block_css_present():
|
||||
""".katex-block CSS rule must exist for centered display math."""
|
||||
assert '.katex-block' in CSS, \
|
||||
'.katex-block CSS rule missing from style.css — display math will have no layout'
|
||||
|
||||
|
||||
def test_katex_inline_css_present():
|
||||
""".katex-inline CSS rule must exist."""
|
||||
assert '.katex-inline' in CSS, \
|
||||
'.katex-inline CSS rule missing from style.css'
|
||||
|
||||
|
||||
def test_katex_block_text_align_center():
|
||||
""".katex-block must be text-align:center for display math."""
|
||||
assert 'text-align:center' in CSS, \
|
||||
'text-align:center not found for .katex-block'
|
||||
|
||||
|
||||
# ── SAFE_TAGS ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_safe_tags_includes_span():
|
||||
"""SAFE_TAGS must include <span> to allow .katex-inline spans through the escape pass."""
|
||||
# The SAFE_TAGS regex should contain 'span'
|
||||
safe_tags_match = re.search(r'SAFE_TAGS\s*=\s*/.*?/i', UI_JS)
|
||||
assert safe_tags_match, 'SAFE_TAGS pattern not found in ui.js'
|
||||
assert 'span' in safe_tags_match.group(), \
|
||||
'<span> not in SAFE_TAGS — inline math spans will be HTML-escaped and rendered as text'
|
||||
|
||||
|
||||
# ── Stash ordering: fence must protect code spans from math extraction ─────────
|
||||
|
||||
WORKSPACE_JS = (REPO / 'static' / 'workspace.js').read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def test_fence_stash_before_math_stash():
|
||||
"""fence_stash must be initialized and populated BEFORE math_stash in renderMd.
|
||||
|
||||
If math_stash runs first, dollar signs inside backtick code spans are extracted
|
||||
as math, leaving placeholder tokens inside the stashed code string. The code span
|
||||
then renders with KaTeX inside <code> instead of the literal dollar-sign text.
|
||||
"""
|
||||
fence_pos = UI_JS.find("const fence_stash=[]")
|
||||
math_pos = UI_JS.find("const math_stash=[]")
|
||||
assert fence_pos != -1, "fence_stash not found in renderMd"
|
||||
assert math_pos != -1, "math_stash not found in renderMd"
|
||||
assert fence_pos < math_pos, (
|
||||
"fence_stash must be declared BEFORE math_stash in renderMd "
|
||||
f"(fence at char {fence_pos}, math at char {math_pos}). "
|
||||
"If math runs first, `$x$` inside backticks gets extracted as math instead of code."
|
||||
)
|
||||
|
||||
|
||||
def test_fence_stash_populated_before_math_stash():
|
||||
"""The fence_stash s.replace call must appear before any math_stash s.replace calls."""
|
||||
# Find the s.replace call that populates each stash
|
||||
fence_replace_pos = UI_JS.find("fence_stash.push(m)")
|
||||
math_replace_pos = UI_JS.find("math_stash.push(")
|
||||
assert fence_replace_pos != -1, "fence_stash population call not found"
|
||||
assert math_replace_pos != -1, "math_stash population call not found"
|
||||
assert fence_replace_pos < math_replace_pos, (
|
||||
"fence_stash must be populated before math_stash to protect code span contents"
|
||||
)
|
||||
|
||||
|
||||
def test_math_stash_comment_says_after_fence():
|
||||
"""The math stash comment should explain it runs AFTER fence_stash, not before."""
|
||||
# Should not have the old misleading comment
|
||||
assert "Must run BEFORE fence_stash" not in UI_JS, (
|
||||
"Old misleading comment still present. Math stash runs AFTER fence_stash. "
|
||||
"The comment should say 'Runs AFTER fence_stash'."
|
||||
)
|
||||
|
||||
|
||||
# ── Pipeline regression: code spans protect their contents ────────────────────
|
||||
|
||||
def test_math_restore_after_fence_restore():
|
||||
"""Math stash tokens are restored AFTER fence restore, so code spans get
|
||||
their raw text back (not KaTeX placeholders)."""
|
||||
fence_restore_pos = UI_JS.find("fence_stash[+i]")
|
||||
math_restore_pos = UI_JS.find("math_stash[+i]")
|
||||
assert fence_restore_pos != -1, "fence_stash restore not found"
|
||||
assert math_restore_pos != -1, "math_stash restore not found"
|
||||
# Both restores must exist; their relative order doesn't matter for correctness
|
||||
# (they use different tokens: \x00F vs \x00M), but we assert both exist
|
||||
assert fence_restore_pos != math_restore_pos, "fence and math restore must be separate calls"
|
||||
|
||||
|
||||
def test_stash_tokens_distinct():
|
||||
"""fence_stash and math_stash must use distinct sentinel tokens to avoid collisions."""
|
||||
# fence uses \x00F, math uses \x00M (or similar unique prefix)
|
||||
# The JS source uses escaped \\x00F and \\x00M as sentinel characters
|
||||
# In the Python string read from the file these appear as '\\\\x00F' and '\\\\x00M'
|
||||
assert "'\\\\x00F'" in UI_JS or 'x00F' in UI_JS, (
|
||||
"fence stash token (\\x00F) not found — must be distinct from math token"
|
||||
)
|
||||
assert "'\\\\x00M'" in UI_JS or 'x00M' in UI_JS, (
|
||||
"math stash token (\\x00M) not found — must be distinct from fence token"
|
||||
)
|
||||
# The two tokens must use different discriminator characters
|
||||
assert 'x00F' in UI_JS and 'x00M' in UI_JS, (
|
||||
"Both \\x00F (fence) and \\x00M (math) tokens must exist"
|
||||
)
|
||||
|
||||
|
||||
# ── Workspace preview renderKatexBlocks wiring ────────────────────────────────
|
||||
|
||||
def test_workspace_calls_render_katex_after_preview():
|
||||
"""workspace.js must call renderKatexBlocks() after setting previewMd.innerHTML.
|
||||
|
||||
Without this, math placeholders appear in workspace file previews but are never
|
||||
rendered by KaTeX (renderKatexBlocks is only wired into renderMessages rAF).
|
||||
"""
|
||||
assert "renderKatexBlocks" in WORKSPACE_JS, (
|
||||
"workspace.js must call renderKatexBlocks() after renderMd() for file previews"
|
||||
)
|
||||
|
||||
|
||||
def test_workspace_renders_katex_after_file_open():
|
||||
"""workspace.js renderKatexBlocks call must come after the renderMd(data.content) assignment."""
|
||||
preview_md_pos = WORKSPACE_JS.find("renderMd(data.content)")
|
||||
# Use the actual call string (not a stray regex match on 'M' characters)
|
||||
katex_call_str = "renderKatexBlocks==='function'"
|
||||
katex_call_pos = WORKSPACE_JS.find(katex_call_str)
|
||||
assert preview_md_pos != -1, "renderMd(data.content) not found in workspace.js"
|
||||
assert katex_call_pos != -1, (
|
||||
"renderKatexBlocks guard (typeof renderKatexBlocks==='function') not found in workspace.js"
|
||||
)
|
||||
# The call after 'renderMd(data.content)' — find the LAST occurrence
|
||||
# (there may be an earlier one in the save path at line ~153)
|
||||
last_katex_pos = WORKSPACE_JS.rfind(katex_call_str)
|
||||
assert last_katex_pos > preview_md_pos, (
|
||||
"renderKatexBlocks must be called AFTER renderMd(data.content) in workspace.js "
|
||||
f"(renderMd at {preview_md_pos}, last renderKatexBlocks at {last_katex_pos})"
|
||||
)
|
||||
|
||||
|
||||
def test_workspace_katex_guarded_by_typeof():
|
||||
"""workspace.js renderKatexBlocks call must guard with typeof check for safety
|
||||
in case KaTeX feature is not loaded (e.g. test environments, offline)."""
|
||||
assert "typeof renderKatexBlocks" in WORKSPACE_JS, (
|
||||
"workspace.js must guard renderKatexBlocks call with typeof check: "
|
||||
"if(typeof renderKatexBlocks==='function')renderKatexBlocks()"
|
||||
)
|
||||
|
||||
|
||||
# ── SAFE_TAGS: span addition should not expand attack surface ─────────────────
|
||||
|
||||
def test_safe_tags_span_is_narrowly_scoped():
|
||||
"""SAFE_TAGS adding <span> is only a bypass if span carries dangerous attributes.
|
||||
Verify the SAFE_TAGS regex tests the tag NAME only, not arbitrary attributes.
|
||||
The rest of the pipeline uses esc() for user content, so attribute injection
|
||||
into KaTeX spans isn't possible.
|
||||
"""
|
||||
# The SAFE_TAGS regex must still require a word boundary / tag-end pattern
|
||||
safe_tags_match = re.search(r"SAFE_TAGS\s*=\s*/(.+?)/i", UI_JS)
|
||||
if not safe_tags_match:
|
||||
safe_tags_match = re.search(r'SAFE_TAGS\s*=\s*/(.*?)/i', UI_JS)
|
||||
assert safe_tags_match, "SAFE_TAGS regex not found"
|
||||
pattern = safe_tags_match.group(1)
|
||||
# Must have a trailing boundary check — ([\s>]|$) or similar
|
||||
assert r"[\s>]" in pattern or r'[\s>]' in pattern, (
|
||||
"SAFE_TAGS must enforce a boundary after the tag name to prevent "
|
||||
"<spanxss> from matching when checking for <span>"
|
||||
)
|
||||
|
||||
|
||||
# ── False-positive prevention ─────────────────────────────────────────────────
|
||||
|
||||
def test_inline_math_regex_requires_non_space_boundaries():
|
||||
"""The $...$ inline regex must require non-space at both boundaries.
|
||||
|
||||
This prevents 'costs $5 and $10' from matching — the space after the opening
|
||||
$ means it's a currency amount, not math.
|
||||
"""
|
||||
# The inline math stash push is type:'inline' — find its containing replace() line
|
||||
inline_push_idx = UI_JS.find("type:'inline',src:m")
|
||||
assert inline_push_idx != -1, "Inline math stash push not found"
|
||||
# Get the text from the start of that line back to find the regex
|
||||
line_start = UI_JS.rfind('\n', 0, inline_push_idx) + 1
|
||||
inline_line = UI_JS[line_start:inline_push_idx + 50]
|
||||
# The regex must use \s (via [^\s...]) to exclude spaces at boundaries
|
||||
assert '\\s' in inline_line or '[^' in inline_line, (
|
||||
f"Inline math regex must exclude spaces at boundaries to prevent false "
|
||||
f"positives on currency like $5. Found: {inline_line[:120]}"
|
||||
)
|
||||
def test_display_math_stashed_before_inline():
|
||||
"""$$...$$ display math must be stashed before $...$ inline math.
|
||||
|
||||
If inline runs first on '$$x$$', it could match '$' + 'x' + '$' leaving
|
||||
a stray outer '$', corrupting the output.
|
||||
"""
|
||||
display_pos = UI_JS.find("type:'display',src:m")
|
||||
inline_pos = UI_JS.find("type:'inline',src:m")
|
||||
assert display_pos != -1, "display math stash not found"
|
||||
assert inline_pos != -1, "inline math stash not found"
|
||||
# First occurrence of display must be before first occurrence of inline
|
||||
assert display_pos < inline_pos, (
|
||||
"Display math ($$...$$) must be stashed before inline math ($...$) "
|
||||
"to prevent $$ from being parsed as two adjacent inline delimiters"
|
||||
)
|
||||
|
||||
|
||||
def test_math_stash_token_uses_single_backslash_null_byte():
|
||||
"""Math stash tokens must use the null-byte form (single backslash x00M).
|
||||
|
||||
The restore regex expects a null byte character. If the stash emits
|
||||
a literal backslash+x00M (double backslash = 5-char string), the restore
|
||||
regex never matches and the tokens appear verbatim in the rendered output.
|
||||
|
||||
The fence_stash correctly uses the null byte convention. Math stash must be consistent.
|
||||
"""
|
||||
# In the source file, the correct form is: return '\x00M'
|
||||
# The wrong form (double backslash) would be: return '\\x00M'
|
||||
# Check that no double-backslash form exists in the math stash return statements
|
||||
import re
|
||||
bad_returns = re.findall(r"return\s+'\\\\x00M'", UI_JS)
|
||||
assert not bad_returns, (
|
||||
f"Found {len(bad_returns)} math stash return(s) using double-backslash \\\\x00M. "
|
||||
"Must use single backslash '\x00M' (null byte) to match the restore regex."
|
||||
)
|
||||
# Positive check: single-backslash form must exist
|
||||
good_returns = re.findall(r"math_stash\.push.*?return '\\x00M'", UI_JS, re.DOTALL)
|
||||
assert good_returns, (
|
||||
"Math stash return must use single-backslash '\x00M' (null byte convention)"
|
||||
)
|
||||
189
tests/test_issue357.py
Normal file
189
tests/test_issue357.py
Normal file
@@ -0,0 +1,189 @@
|
||||
"""
|
||||
Tests for GitHub issue #357: Docker container fails to start without internet access.
|
||||
|
||||
Structural tests — verify Dockerfile and docker_init.bash contain the expected
|
||||
patterns for pre-installed uv and workspace permission fixes.
|
||||
|
||||
Two problems fixed:
|
||||
1. uv was downloaded at container startup; fails in air-gapped / firewalled environments.
|
||||
Fix: pre-install uv in the Docker image at build time (system-wide in /usr/local/bin).
|
||||
2. workspace directory created with plain mkdir (as root); bind-mount dirs created by
|
||||
Docker as root are unwritable by the hermeswebui user.
|
||||
Fix: sudo mkdir + sudo chown for workspace directory.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
DOCKERFILE = (REPO / "Dockerfile").read_text(encoding="utf-8")
|
||||
INIT_SCRIPT = (REPO / "docker_init.bash").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Dockerfile: uv pre-installed at build time ───────────────────────────────
|
||||
|
||||
class TestDockerfileUvPreinstall:
|
||||
|
||||
def test_dockerfile_installs_uv_at_build_time(self):
|
||||
"""Dockerfile must install uv via RUN curl at build time (not only at runtime)."""
|
||||
assert "RUN curl" in DOCKERFILE and "uv/install.sh" in DOCKERFILE, (
|
||||
"Dockerfile must install uv at build time via RUN curl .../uv/install.sh"
|
||||
)
|
||||
|
||||
def test_dockerfile_uv_installed_system_wide(self):
|
||||
"""uv must be installed to a system-wide directory (/usr/local/bin) accessible
|
||||
to all users, not to a user-specific ~/.local/bin that another user can't see."""
|
||||
# The install command must target /usr/local/bin or use root to install globally
|
||||
uv_install_line = next(
|
||||
(line for line in DOCKERFILE.splitlines() if "uv/install.sh" in line),
|
||||
None,
|
||||
)
|
||||
assert uv_install_line is not None, "Could not find uv install line in Dockerfile"
|
||||
# Must either use UV_INSTALL_DIR pointing to /usr/local/bin, or run as root
|
||||
# (so the default install location is accessible to hermeswebui user)
|
||||
has_system_dir = "/usr/local/bin" in uv_install_line or "UV_INSTALL_DIR=/usr/local/bin" in DOCKERFILE
|
||||
assert has_system_dir, (
|
||||
"uv must be installed to /usr/local/bin (system-wide) so hermeswebui user "
|
||||
"can find it. Installing as hermeswebuitoo puts it in /home/hermeswebuitoo/.local/bin "
|
||||
"which is NOT on hermeswebui's PATH."
|
||||
)
|
||||
|
||||
def test_dockerfile_uv_installed_before_copy(self):
|
||||
"""uv installation must happen before COPY . /apptoo so it's in the image."""
|
||||
uv_pos = DOCKERFILE.find("uv/install.sh")
|
||||
copy_pos = DOCKERFILE.find("COPY . /apptoo")
|
||||
assert uv_pos != -1, "uv install not found in Dockerfile"
|
||||
assert copy_pos != -1, "COPY . /apptoo not found in Dockerfile"
|
||||
assert uv_pos < copy_pos, "uv must be installed before COPY . /apptoo"
|
||||
|
||||
def test_dockerfile_uv_installed_as_root_or_before_user_switch(self):
|
||||
"""uv must be installed as root (USER root) to reach /usr/local/bin.
|
||||
If installed as hermeswebuitoo, it lands in ~hermeswebuitoo/.local/bin,
|
||||
which the hermeswebui user at runtime can't see.
|
||||
"""
|
||||
lines = DOCKERFILE.splitlines()
|
||||
uv_line_idx = next(i for i, l in enumerate(lines) if "uv/install.sh" in l)
|
||||
# Find the last USER directive before the uv install line
|
||||
user_before = None
|
||||
for i in range(uv_line_idx - 1, -1, -1):
|
||||
if lines[i].strip().startswith("USER "):
|
||||
user_before = lines[i].strip().split()[1]
|
||||
break
|
||||
assert user_before == "root", (
|
||||
f"uv install must run as USER root (found USER {user_before!r}). "
|
||||
"Installing as hermeswebuitoo puts uv in /home/hermeswebuitoo/.local/bin "
|
||||
"which is not accessible to the hermeswebui runtime user."
|
||||
)
|
||||
|
||||
|
||||
# ── docker_init.bash: skip uv download when already present ─────────────────
|
||||
|
||||
class TestInitScriptUvSkip:
|
||||
|
||||
def test_init_script_checks_uv_before_download(self):
|
||||
"""docker_init.bash must check 'command -v uv' before attempting download."""
|
||||
assert "command -v uv" in INIT_SCRIPT, (
|
||||
"docker_init.bash must check 'command -v uv' to skip download "
|
||||
"when uv is already pre-installed in the image (#357)"
|
||||
)
|
||||
|
||||
def test_init_script_skips_download_if_present(self):
|
||||
"""Init script must use conditional logic (if/else) around the uv download."""
|
||||
# Pattern: if command -v uv ... else ... fi
|
||||
assert re.search(r'if\s+command\s+-v\s+uv', INIT_SCRIPT), (
|
||||
"docker_init.bash must use 'if command -v uv' guard around the download"
|
||||
)
|
||||
|
||||
def test_init_script_curl_download_in_else_branch(self):
|
||||
"""The curl download must be in the else branch (only runs if uv not found)."""
|
||||
# Find the conditional block
|
||||
m = re.search(
|
||||
r'if\s+command\s+-v\s+uv.*?fi',
|
||||
INIT_SCRIPT, re.DOTALL
|
||||
)
|
||||
assert m, "Could not find uv conditional block in docker_init.bash"
|
||||
block = m.group(0)
|
||||
# curl must appear after 'else' not in the 'then' branch
|
||||
else_pos = block.find("else")
|
||||
curl_pos = block.find("curl")
|
||||
assert else_pos != -1, "No 'else' branch in uv conditional"
|
||||
assert curl_pos != -1, "No 'curl' in uv conditional block"
|
||||
assert curl_pos > else_pos, (
|
||||
"curl download must be in the 'else' branch, not the 'if/then' branch"
|
||||
)
|
||||
|
||||
def test_init_script_error_exit_on_download_failure(self):
|
||||
"""Curl download must call error_exit on failure (not silently continue)."""
|
||||
assert "error_exit" in INIT_SCRIPT and "Failed to install uv" in INIT_SCRIPT, (
|
||||
"docker_init.bash must call error_exit if uv download fails, "
|
||||
"so the container exits with a clear message instead of failing silently"
|
||||
)
|
||||
|
||||
def test_init_script_path_includes_hermeswebui_local_bin(self):
|
||||
"""PATH must include /home/hermeswebui/.local/bin for fallback runtime install."""
|
||||
assert "/home/hermeswebui/.local/bin" in INIT_SCRIPT, (
|
||||
"docker_init.bash must include /home/hermeswebui/.local/bin in PATH "
|
||||
"for the case where uv is installed at runtime via curl"
|
||||
)
|
||||
|
||||
|
||||
# ── docker_init.bash: workspace directory permissions ────────────────────────
|
||||
|
||||
class TestWorkspacePermissions:
|
||||
|
||||
def test_workspace_uses_sudo_mkdir(self):
|
||||
"""docker_init.bash must use 'sudo mkdir' for the workspace directory.
|
||||
|
||||
Docker auto-creates bind-mount directories as root if they don't exist,
|
||||
leaving them unwritable by hermeswebui. sudo mkdir + chown fixes this.
|
||||
"""
|
||||
# Find the workspace section
|
||||
ws_section = INIT_SCRIPT[
|
||||
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE"):
|
||||
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE") + 800
|
||||
]
|
||||
assert "sudo mkdir" in ws_section, (
|
||||
"docker_init.bash must use 'sudo mkdir -p' for the workspace directory "
|
||||
"to handle the case where Docker created the bind-mount dir as root (#357)"
|
||||
)
|
||||
|
||||
def test_workspace_uses_sudo_chown(self):
|
||||
"""docker_init.bash must chown the workspace to hermeswebui after mkdir."""
|
||||
ws_section = INIT_SCRIPT[
|
||||
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE"):
|
||||
INIT_SCRIPT.find("HERMES_WEBUI_DEFAULT_WORKSPACE") + 800
|
||||
]
|
||||
assert "sudo chown" in ws_section and "hermeswebui" in ws_section, (
|
||||
"docker_init.bash must 'sudo chown hermeswebui:hermeswebui' the workspace "
|
||||
"directory after creating it, so the app user can write to it (#357)"
|
||||
)
|
||||
|
||||
def test_workspace_mkdir_before_chown(self):
|
||||
"""sudo mkdir must come before sudo chown in docker_init.bash."""
|
||||
mkdir_pos = INIT_SCRIPT.find("sudo mkdir -p \"$HERMES_WEBUI_DEFAULT_WORKSPACE\"")
|
||||
chown_pos = INIT_SCRIPT.find("sudo chown hermeswebui:hermeswebui \"$HERMES_WEBUI_DEFAULT_WORKSPACE\"")
|
||||
assert mkdir_pos != -1, "sudo mkdir for workspace not found"
|
||||
assert chown_pos != -1, "sudo chown for workspace not found"
|
||||
assert mkdir_pos < chown_pos, "sudo mkdir must come before sudo chown"
|
||||
|
||||
def test_workspace_error_exit_on_mkdir_failure(self):
|
||||
"""sudo mkdir must call error_exit on failure."""
|
||||
assert 'sudo mkdir -p "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit' in INIT_SCRIPT, (
|
||||
"sudo mkdir for workspace must call error_exit on failure"
|
||||
)
|
||||
|
||||
def test_workspace_error_exit_on_chown_failure(self):
|
||||
"""sudo chown must call error_exit on failure."""
|
||||
assert 'sudo chown hermeswebui:hermeswebui "$HERMES_WEBUI_DEFAULT_WORKSPACE" || error_exit' in INIT_SCRIPT, (
|
||||
"sudo chown for workspace must call error_exit on failure"
|
||||
)
|
||||
|
||||
def test_init_script_syntax_valid(self):
|
||||
"""docker_init.bash must pass bash -n syntax check."""
|
||||
import subprocess
|
||||
result = subprocess.run(
|
||||
["bash", "-n", str(REPO / "docker_init.bash")],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"docker_init.bash failed bash -n syntax check:\n{result.stderr}"
|
||||
)
|
||||
216
tests/test_issue401.py
Normal file
216
tests/test_issue401.py
Normal file
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
Regression tests for issue #401 / PR #402:
|
||||
Tool call cards show incorrect/duplicate entries on session load after context compaction.
|
||||
|
||||
Root cause: loadSession() applied its own B9 sanitization (producing a new message array
|
||||
with different indices) but did not remap the session-level tool_calls.assistant_msg_idx
|
||||
values to match. It then assigned the broken tool_calls directly to S.toolCalls, bypassing
|
||||
renderMessages()'s fallback that correctly derives tool calls from per-message tool_calls.
|
||||
|
||||
Fix: build origIdxToSanitizedIdx during the B9 pass and remap each tc.assistant_msg_idx;
|
||||
set S.toolCalls=[] so renderMessages() uses the fallback derivation.
|
||||
|
||||
These tests verify the JS logic statically (no server needed).
|
||||
"""
|
||||
import pathlib
|
||||
import subprocess
|
||||
import textwrap
|
||||
import json
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
SESSIONS_JS = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# --- Static structural checks ---
|
||||
|
||||
def test_loadsession_sets_toolcalls_empty():
|
||||
"""loadSession must set S.toolCalls=[] instead of pre-filling from session-level tool_calls."""
|
||||
assert "S.toolCalls=[]" in SESSIONS_JS, (
|
||||
"loadSession() must set S.toolCalls=[] so renderMessages() uses its fallback "
|
||||
"derivation from per-message tool_calls with correct sanitized-array indices"
|
||||
)
|
||||
|
||||
|
||||
def test_loadsession_does_not_assign_broken_tool_calls():
|
||||
"""loadSession must NOT assign session.tool_calls directly to S.toolCalls (causes index mismatch)."""
|
||||
# The old broken pattern: S.toolCalls=(data.session.tool_calls||[]).map(tc=>({...tc,done:true}))
|
||||
assert "S.toolCalls=(data.session.tool_calls" not in SESSIONS_JS, (
|
||||
"loadSession() must not assign session-level tool_calls directly to S.toolCalls — "
|
||||
"those indices are relative to the pre-sanitization array and will be wrong after B9 filtering"
|
||||
)
|
||||
|
||||
|
||||
def test_loadsession_builds_idx_remap():
|
||||
"""loadSession must build an origIdxToSanitizedIdx map during B9 sanitization."""
|
||||
assert "origIdxToSanitizedIdx" in SESSIONS_JS, (
|
||||
"loadSession() must build origIdxToSanitizedIdx during B9 sanitization "
|
||||
"to remap session-level tool_calls.assistant_msg_idx"
|
||||
)
|
||||
|
||||
|
||||
def test_loadsession_remaps_assistant_msg_idx():
|
||||
"""loadSession must remap tc.assistant_msg_idx using the index map."""
|
||||
assert "tc.assistant_msg_idx" in SESSIONS_JS, (
|
||||
"loadSession() must update tc.assistant_msg_idx using the sanitized index map"
|
||||
)
|
||||
|
||||
|
||||
# --- Behavioural Node.js tests ---
|
||||
|
||||
def _run_js(script_body: str) -> dict:
|
||||
"""Run a JS snippet that exercises the B9 sanitization logic extracted from sessions.js."""
|
||||
# Extract just the B9 + index-remap block from loadSession
|
||||
# We'll re-implement it inline for testability
|
||||
script = textwrap.dedent(f"""
|
||||
// Simulate the B9 sanitization + index remap logic from loadSession()
|
||||
function sanitizeAndRemap(messages, tool_calls) {{
|
||||
const allMsgs = messages || [];
|
||||
const sanitized = [];
|
||||
const origIdxToSanitizedIdx = {{}};
|
||||
let lastKeptAsstIdx = -1;
|
||||
for (let i = 0; i < allMsgs.length; i++) {{
|
||||
const m = allMsgs[i];
|
||||
if (!m || !m.role) continue;
|
||||
if (m.role === 'tool') continue;
|
||||
if (m.role === 'assistant') {{
|
||||
let c = m.content || '';
|
||||
if (Array.isArray(c)) c = c.filter(p => p && p.type === 'text').map(p => p.text || '').join('');
|
||||
if (!String(c).trim().length) {{ continue; }}
|
||||
lastKeptAsstIdx = sanitized.length;
|
||||
}}
|
||||
origIdxToSanitizedIdx[i] = sanitized.length;
|
||||
sanitized.push(m);
|
||||
}}
|
||||
const remapped = (tool_calls || []).map(tc => {{
|
||||
if (!tc || tc.assistant_msg_idx === undefined) return tc;
|
||||
const origIdx = tc.assistant_msg_idx;
|
||||
const newIdx = (origIdx in origIdxToSanitizedIdx)
|
||||
? origIdxToSanitizedIdx[origIdx]
|
||||
: (lastKeptAsstIdx >= 0 ? lastKeptAsstIdx : -1);
|
||||
return {{ ...tc, assistant_msg_idx: newIdx }};
|
||||
}});
|
||||
return {{ sanitized, remapped }};
|
||||
}}
|
||||
|
||||
{script_body}
|
||||
""")
|
||||
proc = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def test_b9_remaps_tool_call_idx_after_empty_assistant_filtered():
|
||||
"""Tool call pointing to index 1 (empty assistant at orig idx 1, kept at idx 0) remaps correctly."""
|
||||
result = _run_js("""
|
||||
const messages = [
|
||||
{ role: 'user', content: 'hello' }, // orig 0 -> sanitized 0
|
||||
{ role: 'assistant', content: '' }, // orig 1 -> FILTERED (empty)
|
||||
{ role: 'assistant', content: 'done.' }, // orig 2 -> sanitized 1
|
||||
];
|
||||
const tool_calls = [
|
||||
{ name: 'terminal', assistant_msg_idx: 1 }, // pointed to filtered-out empty assistant
|
||||
{ name: 'read_file', assistant_msg_idx: 2 }, // pointed to kept assistant
|
||||
];
|
||||
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
|
||||
process.stdout.write(JSON.stringify({
|
||||
sanitized_length: sanitized.length,
|
||||
tc0_new_idx: remapped[0].assistant_msg_idx, // should attach to lastKeptAsstIdx = 1
|
||||
tc1_new_idx: remapped[1].assistant_msg_idx, // should remap 2 -> 1
|
||||
}));
|
||||
""")
|
||||
assert result["sanitized_length"] == 2, f"Expected 2 messages after B9, got {result['sanitized_length']}"
|
||||
assert result["tc0_new_idx"] == 1, (
|
||||
f"Tool call pointing to filtered empty assistant should attach to last kept assistant (idx 1), got {result['tc0_new_idx']}"
|
||||
)
|
||||
assert result["tc1_new_idx"] == 1, (
|
||||
f"Tool call pointing to orig idx 2 should remap to sanitized idx 1, got {result['tc1_new_idx']}"
|
||||
)
|
||||
|
||||
|
||||
def test_b9_remaps_multiple_empty_assistants():
|
||||
"""Multiple consecutive empty assistants all remap to the last (nearest) kept assistant.
|
||||
|
||||
Note: the remapping pass runs after the full sanitization loop, so lastKeptAsstIdx
|
||||
already reflects the final kept-assistant position. This means even empty-assistant
|
||||
tool calls that came BEFORE the kept assistant get attached to it — which is correct
|
||||
behavior for context-compacted sessions where all tool calls belong to the one
|
||||
non-empty assistant response.
|
||||
"""
|
||||
result = _run_js("""
|
||||
const messages = [
|
||||
{ role: 'user', content: 'go' }, // orig 0 -> sanitized 0
|
||||
{ role: 'assistant', content: '' }, // orig 1 -> FILTERED
|
||||
{ role: 'assistant', content: '' }, // orig 2 -> FILTERED
|
||||
{ role: 'assistant', content: '' }, // orig 3 -> FILTERED
|
||||
{ role: 'assistant', content: 'result' }, // orig 4 -> sanitized 1
|
||||
];
|
||||
const tool_calls = [
|
||||
{ name: 'a', assistant_msg_idx: 1 },
|
||||
{ name: 'b', assistant_msg_idx: 2 },
|
||||
{ name: 'c', assistant_msg_idx: 3 },
|
||||
{ name: 'd', assistant_msg_idx: 4 },
|
||||
];
|
||||
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
|
||||
process.stdout.write(JSON.stringify({
|
||||
sanitized_length: sanitized.length,
|
||||
tc0_idx: remapped[0].assistant_msg_idx,
|
||||
tc1_idx: remapped[1].assistant_msg_idx,
|
||||
tc2_idx: remapped[2].assistant_msg_idx,
|
||||
tc3_idx: remapped[3].assistant_msg_idx,
|
||||
}));
|
||||
""")
|
||||
assert result["sanitized_length"] == 2
|
||||
# Tool calls from filtered empty assistants: after the full loop, lastKeptAsstIdx=1,
|
||||
# so all filtered-assistant tool calls correctly attach to the kept assistant at idx 1.
|
||||
assert result["tc0_idx"] == 1, f"Expected 1 (last kept asst), got {result['tc0_idx']}"
|
||||
assert result["tc1_idx"] == 1
|
||||
assert result["tc2_idx"] == 1
|
||||
# Tool call from the kept assistant at orig idx 4 -> sanitized idx 1
|
||||
assert result["tc3_idx"] == 1, f"Expected 1, got {result['tc3_idx']}"
|
||||
|
||||
|
||||
def test_b9_no_filtering_needed_indices_preserved():
|
||||
"""When no empty assistant messages exist, indices should pass through unchanged."""
|
||||
result = _run_js("""
|
||||
const messages = [
|
||||
{ role: 'user', content: 'hi' }, // orig 0 -> sanitized 0
|
||||
{ role: 'assistant', content: 'hello' }, // orig 1 -> sanitized 1
|
||||
{ role: 'user', content: 'more' }, // orig 2 -> sanitized 2
|
||||
{ role: 'assistant', content: 'yes' }, // orig 3 -> sanitized 3
|
||||
];
|
||||
const tool_calls = [
|
||||
{ name: 'x', assistant_msg_idx: 1 },
|
||||
{ name: 'y', assistant_msg_idx: 3 },
|
||||
];
|
||||
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
|
||||
process.stdout.write(JSON.stringify({
|
||||
sanitized_length: sanitized.length,
|
||||
tc0_idx: remapped[0].assistant_msg_idx,
|
||||
tc1_idx: remapped[1].assistant_msg_idx,
|
||||
}));
|
||||
""")
|
||||
assert result["sanitized_length"] == 4
|
||||
assert result["tc0_idx"] == 1, f"Expected 1, got {result['tc0_idx']}"
|
||||
assert result["tc1_idx"] == 3, f"Expected 3, got {result['tc1_idx']}"
|
||||
|
||||
|
||||
def test_b9_tool_role_messages_filtered():
|
||||
"""Messages with role='tool' must be filtered out and not affect index mapping."""
|
||||
result = _run_js("""
|
||||
const messages = [
|
||||
{ role: 'user', content: 'run' }, // orig 0 -> sanitized 0
|
||||
{ role: 'tool', content: 'output' }, // orig 1 -> FILTERED (tool role)
|
||||
{ role: 'assistant', content: 'done' }, // orig 2 -> sanitized 1
|
||||
];
|
||||
const tool_calls = [
|
||||
{ name: 'terminal', assistant_msg_idx: 2 },
|
||||
];
|
||||
const { sanitized, remapped } = sanitizeAndRemap(messages, tool_calls);
|
||||
process.stdout.write(JSON.stringify({
|
||||
sanitized_length: sanitized.length,
|
||||
tc0_idx: remapped[0].assistant_msg_idx,
|
||||
}));
|
||||
""")
|
||||
assert result["sanitized_length"] == 2, f"tool-role message must be filtered, got {result['sanitized_length']}"
|
||||
assert result["tc0_idx"] == 1, f"Expected orig idx 2 -> sanitized idx 1, got {result['tc0_idx']}"
|
||||
313
tests/test_issue470.py
Normal file
313
tests/test_issue470.py
Normal file
@@ -0,0 +1,313 @@
|
||||
"""
|
||||
Tests for issue #470 — markdown link rendering bugs in renderMd():
|
||||
1. Double-linking: [label](url) converted to <a>, then autolink re-matches
|
||||
the URL inside href="..." and wraps it in a second <a>.
|
||||
2. esc() applied to URLs in href attributes turns & → &, breaking
|
||||
URLs with query strings and producing & in displayed link text.
|
||||
3. Same double-linking bug inside table cells via inlineMd().
|
||||
|
||||
These tests verify the fixes by asserting against the rendered HTML that
|
||||
ui.js serves, using a live server request to evaluate the actual JS output
|
||||
indirectly (via checking ui.js source for the fixed patterns) AND by
|
||||
running a lightweight Python mirror of the fixed renderMd logic.
|
||||
|
||||
Strategy: verify the fix is present in the JS source, then test the
|
||||
expected rendering behaviour through the Python mirror.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import html as _html
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text()
|
||||
|
||||
|
||||
# ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def esc(s):
|
||||
return _html.escape(str(s), quote=True)
|
||||
|
||||
|
||||
def _make_link(url, label):
|
||||
"""Expected output for a [label](url) link after fix: href is NOT esc()-ed."""
|
||||
return f'<a href="{url}" target="_blank" rel="noopener">{esc(label)}</a>'
|
||||
|
||||
|
||||
# Minimal Python mirror of the FIXED renderMd() — enough to test link behaviour.
|
||||
# Mirrors the stash-based approach introduced by the fix.
|
||||
|
||||
def render_links_only(text):
|
||||
"""
|
||||
Simplified render that only applies the link-related passes from the fixed
|
||||
renderMd(): [label](url) conversion + autolink, with the stash protection.
|
||||
Sufficient for testing that links render correctly without double-linking.
|
||||
"""
|
||||
s = text
|
||||
|
||||
# Stash [label](url) links (fix: store href as raw URL, not esc(url))
|
||||
link_stash = []
|
||||
def stash_link(m):
|
||||
label, url = m.group(1), m.group(2)
|
||||
link_stash.append(f'<a href="{url}" target="_blank" rel="noopener">{esc(label)}</a>')
|
||||
return f'\x00L{len(link_stash)-1}\x00'
|
||||
s = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+)\)', stash_link, s)
|
||||
|
||||
# Autolink bare URLs (should NOT match inside already-stashed placeholders)
|
||||
def autolink(m):
|
||||
url = m.group(1)
|
||||
trail = url[-1] if url[-1] in '.,;:!?)' else ''
|
||||
clean = url[:-1] if trail else url
|
||||
return f'<a href="{clean}" target="_blank" rel="noopener">{esc(clean)}</a>{trail}'
|
||||
s = re.sub(r'(https?://[^\s<>"\')\]]+)', autolink, s)
|
||||
|
||||
# Restore stashed links
|
||||
s = re.sub(r'\x00L(\d+)\x00', lambda m: link_stash[int(m.group(1))], s)
|
||||
return s
|
||||
|
||||
|
||||
def render_table_with_links(md):
|
||||
"""
|
||||
Render a markdown table that may contain [label](url) cells.
|
||||
Mirrors the fixed inlineMd() + table rendering.
|
||||
"""
|
||||
lines = md.strip().split('\n')
|
||||
if len(lines) < 2:
|
||||
return md
|
||||
def is_sep(r):
|
||||
return bool(re.match(r'^\|[\s|:-]+\|$', r.strip()))
|
||||
if not is_sep(lines[1]):
|
||||
return md
|
||||
|
||||
def inline_md_fixed(t):
|
||||
"""Fixed inlineMd: stash links before autolink."""
|
||||
stash = []
|
||||
def stash_fn(m):
|
||||
lb, u = m.group(1), m.group(2)
|
||||
stash.append(f'<a href="{u}" target="_blank" rel="noopener">{esc(lb)}</a>')
|
||||
return f'\x00L{len(stash)-1}\x00'
|
||||
t = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+)\)', stash_fn, t)
|
||||
# autolink remaining bare URLs
|
||||
def autolink(m):
|
||||
url = m.group(1)
|
||||
trail = url[-1] if url[-1] in '.,;:!?)' else ''
|
||||
clean = url[:-1] if trail else url
|
||||
return f'<a href="{clean}" target="_blank" rel="noopener">{esc(clean)}</a>{trail}'
|
||||
t = re.sub(r'(https?://[^\s<>"\')\]]+)', autolink, t)
|
||||
t = re.sub(r'\x00L(\d+)\x00', lambda m: stash[int(m.group(1))], t)
|
||||
return t
|
||||
|
||||
def parse_row(r):
|
||||
cells = r.strip().lstrip('|').rstrip('|').split('|')
|
||||
return ''.join(f'<td>{inline_md_fixed(c.strip())}</td>' for c in cells)
|
||||
|
||||
def parse_header(r):
|
||||
cells = r.strip().lstrip('|').rstrip('|').split('|')
|
||||
return ''.join(f'<th>{inline_md_fixed(c.strip())}</th>' for c in cells)
|
||||
|
||||
header = f'<tr>{parse_header(lines[0])}</tr>'
|
||||
body = ''.join(f'<tr>{parse_row(r)}</tr>' for r in lines[2:])
|
||||
return f'<table><thead>{header}</thead><tbody>{body}</tbody></table>'
|
||||
|
||||
|
||||
# ── Source-level checks (verify fix is in the JS) ─────────────────────────────
|
||||
|
||||
def test_inlinemd_uses_link_stash():
|
||||
"""Fixed inlineMd() must stash [label](url) links before autolink runs."""
|
||||
assert '_link_stash' in UI_JS, (
|
||||
"inlineMd() should use _link_stash to prevent double-linking"
|
||||
)
|
||||
|
||||
|
||||
def test_inlinemd_no_esc_on_href():
|
||||
"""Fixed inlineMd() must not call esc() on the URL in href."""
|
||||
# The old broken pattern had esc(u) inside the href
|
||||
assert 'href="${esc(u)}"' not in UI_JS, (
|
||||
"inlineMd() should not call esc() on href URL — it breaks & in query strings"
|
||||
)
|
||||
|
||||
|
||||
def test_outer_link_pass_uses_a_stash():
|
||||
"""Fixed outer link pass must stash existing <a> tags before running."""
|
||||
assert '_a_stash' in UI_JS, (
|
||||
"Outer [label](url) pass should stash existing <a> tags to prevent autolink re-matching"
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_pass_uses_al_stash():
|
||||
"""Fixed autolink pass must stash existing <a> tags before running."""
|
||||
assert '_al_stash' in UI_JS, (
|
||||
"Autolink pass should stash existing <a> tags to prevent double-linking"
|
||||
)
|
||||
|
||||
|
||||
def test_autolink_no_esc_on_href():
|
||||
"""Fixed autolink pass must not call esc() on href URL."""
|
||||
idx = UI_JS.find('// Autolink: convert plain URLs to clickable links.')
|
||||
assert idx != -1, "New autolink comment not found"
|
||||
autolink_section = UI_JS[idx:idx+600]
|
||||
# The return line should have href="${clean}" (JS template literal, no esc call)
|
||||
assert 'href="${clean}"' in autolink_section, (
|
||||
'Autolink should use href="${clean}" not href="${esc(clean)}"'
|
||||
)
|
||||
assert 'href="${esc(clean)}"' not in autolink_section, (
|
||||
"Autolink should not esc() the URL in href"
|
||||
)
|
||||
|
||||
|
||||
# ── Behaviour tests (Python mirror of fixed renderMd) ─────────────────────────
|
||||
|
||||
def test_labeled_link_renders_as_single_anchor():
|
||||
"""[#461](https://github.com/.../461) must produce exactly one <a> tag."""
|
||||
url = 'https://github.com/nesquena/hermes-webui/issues/461'
|
||||
md = f'[#461]({url})'
|
||||
result = render_links_only(md)
|
||||
assert result.count('<a ') == 1, f"Expected 1 <a> tag, got: {result}"
|
||||
assert result.count('</a>') == 1
|
||||
assert f'href="{url}"' in result
|
||||
assert '#461' in result
|
||||
# Must not contain the raw brackets
|
||||
assert '[#461]' not in result
|
||||
assert f']({url})' not in result
|
||||
|
||||
|
||||
def test_href_not_html_escaped():
|
||||
"""URLs with & must appear as literal & in href, not &."""
|
||||
url = 'https://example.com/search?q=foo&bar=baz'
|
||||
md = f'[Search]({url})'
|
||||
result = render_links_only(md)
|
||||
assert f'href="{url}"' in result, (
|
||||
f"& in URL should not be escaped to & in href. Got: {result}"
|
||||
)
|
||||
assert '&' not in result
|
||||
|
||||
|
||||
def test_bare_url_not_double_linked():
|
||||
"""A bare https:// URL must produce exactly one <a> tag."""
|
||||
url = 'https://github.com/nesquena/hermes-webui/issues/461'
|
||||
result = render_links_only(url)
|
||||
assert result.count('<a ') == 1, f"Expected 1 <a> tag, got: {result}"
|
||||
assert result.count('</a>') == 1
|
||||
|
||||
|
||||
def test_labeled_link_in_table_cell_single_anchor():
|
||||
"""[#461](url) inside a markdown table cell must produce exactly one <a> tag."""
|
||||
url = 'https://github.com/nesquena/hermes-webui/issues/461'
|
||||
md = f'| Issue | Title |\n|---|---|\n| [#461]({url}) | Reasoning effort |'
|
||||
result = render_table_with_links(md)
|
||||
assert result.count('<a ') == 1, f"Expected 1 <a> in table, got: {result}"
|
||||
assert f'href="{url}"' in result
|
||||
assert '#461' in result
|
||||
# No raw brackets should appear in output
|
||||
assert '[#461]' not in result
|
||||
|
||||
|
||||
def test_multiple_links_in_table_no_double_linking():
|
||||
"""Multiple [label](url) links in a table must each produce exactly one <a>."""
|
||||
urls = [
|
||||
'https://github.com/nesquena/hermes-webui/issues/461',
|
||||
'https://github.com/nesquena/hermes-webui/issues/462',
|
||||
'https://github.com/nesquena/hermes-webui/issues/463',
|
||||
]
|
||||
rows = '\n'.join(f'| [#{461+i}]({url}) | Title {i} |' for i, url in enumerate(urls))
|
||||
md = f'| Issue | Title |\n|---|---|\n{rows}'
|
||||
result = render_table_with_links(md)
|
||||
assert result.count('<a ') == 3, f"Expected 3 <a> tags, got {result.count('<a ')}:\n{result}"
|
||||
assert result.count('</a>') == 3
|
||||
for url in urls:
|
||||
assert f'href="{url}"' in result
|
||||
|
||||
|
||||
def test_link_label_is_escaped():
|
||||
"""The label text (not the URL) must still be HTML-escaped."""
|
||||
url = 'https://example.com'
|
||||
md = f'[Click <here>]({url})'
|
||||
result = render_links_only(md)
|
||||
assert '<here>' in result, "Label text should be HTML-escaped"
|
||||
assert '<here>' not in result
|
||||
|
||||
|
||||
def test_link_not_broken_by_prior_autolink():
|
||||
"""A [label](url) followed by a bare URL must each produce one clean <a>."""
|
||||
url1 = 'https://github.com/issues/461'
|
||||
url2 = 'https://github.com/issues/462'
|
||||
md = f'See [#461]({url1}) and also {url2}'
|
||||
result = render_links_only(md)
|
||||
assert result.count('<a ') == 2, f"Expected 2 links, got: {result}"
|
||||
assert f'href="{url1}"' in result
|
||||
assert f'href="{url2}"' in result
|
||||
assert '#461' in result
|
||||
|
||||
def test_href_quote_sanitized():
|
||||
"""A URL containing a double-quote must have it percent-encoded in href to prevent attribute breakout."""
|
||||
# This would break out of href="..." and inject an event handler without the fix
|
||||
url = 'https://evil.com" onmouseover="alert(1)'
|
||||
# The [label](url) regex captures up to the closing ), so we test via the render helper
|
||||
# by constructing a URL that contains a literal quote character
|
||||
safe_url = 'https://example.com/path"with"quotes'
|
||||
result = render_links_only(f'[click]({safe_url})')
|
||||
# The href must not contain a raw unencoded double-quote
|
||||
href_start = result.find('href="') + 6
|
||||
href_end = result.find('"', href_start)
|
||||
href_val = result[href_start:href_end]
|
||||
assert '"' not in href_val, (
|
||||
f"href value must not contain unencoded double-quote. Got href: {href_val}"
|
||||
)
|
||||
|
||||
|
||||
def test_js_source_sanitizes_quotes_in_href():
|
||||
"""JS source must apply quote percent-encoding to URLs before placing in href."""
|
||||
# Both the inlineMd stash and outer link pass must sanitize quotes
|
||||
assert "%22" in UI_JS, (
|
||||
"URL placed in href should have double-quotes percent-encoded via .replace to %22"
|
||||
)
|
||||
|
||||
# ── Code-inside-bold tests (pre-existing bug, fixed in same PR) ───────────────
|
||||
|
||||
def test_js_inlinemd_stashes_code_before_bold():
|
||||
"""Fixed inlineMd() must stash backtick code spans before bold/italic processing."""
|
||||
assert '_code_stash' in UI_JS, (
|
||||
"inlineMd() should use _code_stash to protect backtick spans from bold/italic esc()"
|
||||
)
|
||||
|
||||
|
||||
def test_code_inside_bold_renders_correctly():
|
||||
"""Inline code inside bold text must render as <strong><code>...</code></strong>,
|
||||
not with escaped <code> tags visible on screen."""
|
||||
# This was the pre-existing bug: **`esc()`** → <strong><code>esc()</code></strong>
|
||||
text = '**`esc()` on `href`**: breaks URLs'
|
||||
# Simulate the fixed inlineMd()
|
||||
code_stash = []
|
||||
t = text
|
||||
t = re.sub(r'`([^`\n]+)`',
|
||||
lambda m: (code_stash.append(f'<code>{esc(m.group(1))}</code>') or f'\x00C{len(code_stash)-1}\x00'), t)
|
||||
t = re.sub(r'\*\*(.+?)\*\*', lambda m: f'<strong>{esc(m.group(1))}</strong>', t)
|
||||
t = re.sub(r'\x00C(\d+)\x00', lambda m: code_stash[int(m.group(1))], t)
|
||||
assert '<code>' not in t, (
|
||||
f"Code tags should not be HTML-escaped inside bold. Got: {t}"
|
||||
)
|
||||
assert '<code>esc()</code>' in t, (
|
||||
f"Code tags should render as <code> elements inside bold. Got: {t}"
|
||||
)
|
||||
assert '<strong>' in t, "Bold should still render"
|
||||
|
||||
|
||||
def test_code_and_bold_mixed_no_escaping():
|
||||
"""Bold text containing multiple backtick spans must render all code tags correctly."""
|
||||
cases = [
|
||||
('**`esc()` on `href`**', '<strong>', '<code>esc()</code>', '<code>href</code>'),
|
||||
('***`code` in bold-italic***', '<strong>', '<code>code</code>'),
|
||||
('`code` then **bold**', '<code>code</code>', '<strong>bold</strong>'),
|
||||
]
|
||||
for args in cases:
|
||||
text = args[0]
|
||||
expected_fragments = args[1:]
|
||||
code_stash = []
|
||||
t = text
|
||||
t = re.sub(r'`([^`\n]+)`',
|
||||
lambda m: (code_stash.append(f'<code>{esc(m.group(1))}</code>') or f'\x00C{len(code_stash)-1}\x00'), t)
|
||||
t = re.sub(r'\*\*\*(.+?)\*\*\*', lambda m: f'<strong><em>{esc(m.group(1))}</em></strong>', t)
|
||||
t = re.sub(r'\*\*(.+?)\*\*', lambda m: f'<strong>{esc(m.group(1))}</strong>', t)
|
||||
t = re.sub(r'\x00C(\d+)\x00', lambda m: code_stash[int(m.group(1))], t)
|
||||
assert '<code>' not in t, f"Escaped code tag in: {text!r} → {t}"
|
||||
for frag in expected_fragments:
|
||||
assert frag in t, f"Expected {frag!r} in output of {text!r}, got: {t}"
|
||||
26
tests/test_issue477.py
Normal file
26
tests/test_issue477.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""Tests for fix #477: KaTeX font-src CSP fix."""
|
||||
import pathlib
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
HELPERS_PY = (REPO / "api" / "helpers.py").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_font_src_allows_jsdelivr():
|
||||
"""font-src must include cdn.jsdelivr.net for KaTeX fonts."""
|
||||
assert "font-src 'self' data: https://cdn.jsdelivr.net" in HELPERS_PY, (
|
||||
"api/helpers.py CSP must allow cdn.jsdelivr.net in font-src "
|
||||
"so KaTeX math rendering fonts load without console errors."
|
||||
)
|
||||
|
||||
|
||||
def test_font_src_still_allows_self_and_data():
|
||||
"""font-src must still allow self and data: (used by other font assets)."""
|
||||
assert "'self'" in HELPERS_PY.split("font-src")[1].split(";")[0]
|
||||
assert "data:" in HELPERS_PY.split("font-src")[1].split(";")[0]
|
||||
|
||||
|
||||
def test_script_src_already_allows_jsdelivr():
|
||||
"""script-src already allows cdn.jsdelivr.net — font-src should too."""
|
||||
assert "https://cdn.jsdelivr.net" in HELPERS_PY.split("font-src")[0], (
|
||||
"script-src should already allow cdn.jsdelivr.net (KaTeX JS)"
|
||||
)
|
||||
572
tests/test_issue486_487.py
Normal file
572
tests/test_issue486_487.py
Normal file
@@ -0,0 +1,572 @@
|
||||
"""
|
||||
Tests for issue #486 (CSS: inline code in table cells) and
|
||||
issue #487 (JS renderer: markdown image syntax not implemented).
|
||||
|
||||
Issue #486 — CSS fix in static/style.css:
|
||||
Inline `code` spans inside table cells render with awkward sizing.
|
||||
Fix: td code, th code { font-size: 0.85em; padding: 1px 4px; vertical-align: baseline; }
|
||||
|
||||
Issue #487 — JS fix in static/ui.js:
|
||||
 image syntax not handled — renders as stray ! + link.
|
||||
Fix: add image pass to renderMd() (before link pass) and inlineMd()
|
||||
reusing the .msg-media-img class.
|
||||
|
||||
Strategy:
|
||||
- Source-level checks verify the fixes are present in the JS/CSS.
|
||||
- Python mirror tests verify the rendering logic with exhaustive edge cases,
|
||||
especially code blocks inside tables (the specific case Nathan flagged).
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import html as _html
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text()
|
||||
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text()
|
||||
|
||||
|
||||
# ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def esc(s):
|
||||
return _html.escape(str(s), quote=True)
|
||||
|
||||
|
||||
def inline_md(t):
|
||||
"""
|
||||
Python mirror of the fixed inlineMd() function — includes:
|
||||
- _code_stash (protects backtick spans from bold/italic AND from image pass)
|
||||
- image pass (NEW for #487 — runs while code stash is active, before link pass)
|
||||
- _img_stash (protects rendered img tags from autolink touching src=)
|
||||
- _link_stash (protects links from autolink)
|
||||
- autolink
|
||||
- code stash restore (after autolink, so code content is never autolinked)
|
||||
|
||||
Correct operation order:
|
||||
1. code stash — \x00C protects `...` from bold and image pass
|
||||
2. bold/italic — runs on plain text only
|
||||
3. image pass — runs while code content is still stashed (so 
|
||||
inside backticks stays protected as a \x00C token)
|
||||
4. img stash — \x00I protects <img src="url"> from autolink
|
||||
5. link stash — \x00L protects [label](url) links from autolink
|
||||
6. autolink — only matches URLs not already in a stash token
|
||||
7. link stash restore
|
||||
8. img stash restore
|
||||
9. code stash restore — restores <code> tags last
|
||||
"""
|
||||
# 1. Code stash — must be first to protect code content from all subsequent passes
|
||||
code_stash = []
|
||||
def stash_code(m):
|
||||
code_stash.append(f'<code>{esc(m.group(1))}</code>')
|
||||
return f'\x00C{len(code_stash)-1}\x00'
|
||||
t = re.sub(r'`([^`\n]+)`', stash_code, t)
|
||||
|
||||
# 2. Bold/italic (code content is safely stashed)
|
||||
t = re.sub(r'\*\*\*(.+?)\*\*\*', lambda m: f'<strong><em>{esc(m.group(1))}</em></strong>', t)
|
||||
t = re.sub(r'\*\*(.+?)\*\*', lambda m: f'<strong>{esc(m.group(1))}</strong>', t)
|
||||
t = re.sub(r'\*([^*\n]+)\*', lambda m: f'<em>{esc(m.group(1))}</em>', t)
|
||||
|
||||
# 3. Image pass (NEW — runs while code is still stashed, so  inside
|
||||
# backticks is protected as a \x00C token and won't match here)
|
||||
def render_image(m):
|
||||
alt, url = m.group(1), m.group(2)
|
||||
safe_url = url.replace('"', '%22')
|
||||
return (f'<img src="{safe_url}" alt="{esc(alt)}" '
|
||||
f'class="msg-media-img" loading="lazy" '
|
||||
f'onclick="this.classList.toggle(\'msg-media-img--full\')">')
|
||||
t = re.sub(r'!\[([^\]]*)\]\((https?://[^\)]+)\)', render_image, t)
|
||||
|
||||
# 4. Img stash — protect rendered <img> tags so autolink never touches src= values
|
||||
img_stash = []
|
||||
def stash_img(m):
|
||||
img_stash.append(m.group(0))
|
||||
return f'\x00I{len(img_stash)-1}\x00'
|
||||
t = re.sub(r'<img\b[^>]*>', stash_img, t)
|
||||
|
||||
# 5. Link stash
|
||||
link_stash = []
|
||||
def stash_link(m):
|
||||
lb, u = m.group(1), m.group(2)
|
||||
link_stash.append(f'<a href="{u.replace(chr(34), "%22")}" target="_blank" rel="noopener">{esc(lb)}</a>')
|
||||
return f'\x00L{len(link_stash)-1}\x00'
|
||||
t = re.sub(r'\[([^\]]+)\]\((https?://[^\)]+)\)', stash_link, t)
|
||||
|
||||
# 6. Autolink (img and link URLs are both stashed — safe)
|
||||
def autolink(m):
|
||||
url = m.group(1)
|
||||
trail = url[-1] if url[-1] in '.,;:!?)' else ''
|
||||
clean = url[:-1] if trail else url
|
||||
return f'<a href="{clean}" target="_blank" rel="noopener">{esc(clean)}</a>{trail}'
|
||||
t = re.sub(r'(https?://[^\s<>"\')\]]+)', autolink, t)
|
||||
|
||||
# 7. Restore link stash
|
||||
t = re.sub(r'\x00L(\d+)\x00', lambda m: link_stash[int(m.group(1))], t)
|
||||
|
||||
# 8. Restore img stash
|
||||
t = re.sub(r'\x00I(\d+)\x00', lambda m: img_stash[int(m.group(1))], t)
|
||||
|
||||
# 9. Restore code stash (last — code content was never touched by any pass)
|
||||
t = re.sub(r'\x00C(\d+)\x00', lambda m: code_stash[int(m.group(1))], t)
|
||||
return t
|
||||
|
||||
|
||||
def render_table(md):
|
||||
"""Python mirror of the table pass, using inline_md() per cell."""
|
||||
lines = md.strip().split('\n')
|
||||
if len(lines) < 2:
|
||||
return md
|
||||
|
||||
def is_sep(r):
|
||||
return bool(re.match(r'^\|[\s|:-]+\|$', r.strip()))
|
||||
|
||||
if not is_sep(lines[1]):
|
||||
return md
|
||||
|
||||
def parse_header(r):
|
||||
cells = r.strip().lstrip('|').rstrip('|').split('|')
|
||||
return ''.join(f'<th>{inline_md(c.strip())}</th>' for c in cells)
|
||||
|
||||
def parse_row(r):
|
||||
cells = r.strip().lstrip('|').rstrip('|').split('|')
|
||||
return ''.join(f'<td>{inline_md(c.strip())}</td>' for c in cells)
|
||||
|
||||
header = f'<tr>{parse_header(lines[0])}</tr>'
|
||||
body = ''.join(f'<tr>{parse_row(r)}</tr>' for r in lines[2:])
|
||||
return f'<table><thead>{header}</thead><tbody>{body}</tbody></table>'
|
||||
|
||||
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
# ISSUE #486 — CSS: code inside table cells
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestIssue486CssCodeInTable:
|
||||
"""CSS fix: td code and th code must have targeted sizing rules."""
|
||||
|
||||
def test_td_code_font_size_present(self):
|
||||
"""msg-body td code rule must set font-size (e.g. 0.85em) to prevent oversized code."""
|
||||
assert 'td code' in STYLE_CSS, (
|
||||
"Missing 'td code' CSS rule — inline code in table cells needs sizing fix"
|
||||
)
|
||||
|
||||
def test_th_code_rule_present(self):
|
||||
"""th code rule must also exist for header cells."""
|
||||
assert 'th code' in STYLE_CSS, (
|
||||
"Missing 'th code' CSS rule — inline code in header cells needs sizing fix"
|
||||
)
|
||||
|
||||
def test_td_code_has_font_size(self):
|
||||
"""The td code / th code block must include a font-size declaration."""
|
||||
# Find the msg-body scoped td code rule
|
||||
idx = STYLE_CSS.find('td code')
|
||||
assert idx != -1, "td code rule not found in style.css"
|
||||
# Check nearby text (within 200 chars) has font-size
|
||||
window = STYLE_CSS[idx:idx+200]
|
||||
assert 'font-size' in window, (
|
||||
f"td code rule must include font-size. Found near td code: {window!r}"
|
||||
)
|
||||
|
||||
def test_td_code_has_padding(self):
|
||||
"""The td code / th code block must include a padding declaration."""
|
||||
idx = STYLE_CSS.find('td code')
|
||||
assert idx != -1
|
||||
window = STYLE_CSS[idx:idx+200]
|
||||
assert 'padding' in window, (
|
||||
f"td code rule must include padding. Found near td code: {window!r}"
|
||||
)
|
||||
|
||||
def test_td_code_has_vertical_align(self):
|
||||
"""The td code / th code block must include vertical-align: baseline."""
|
||||
idx = STYLE_CSS.find('td code')
|
||||
assert idx != -1
|
||||
window = STYLE_CSS[idx:idx+200]
|
||||
assert 'vertical-align' in window, (
|
||||
f"td code rule must include vertical-align. Found near td code: {window!r}"
|
||||
)
|
||||
|
||||
def test_code_renders_inside_table_cell(self):
|
||||
"""Inline `code` inside a table cell must render as <code> element."""
|
||||
md = "| Syntax | Rendered |\n|---|---|\n| `code` | `code` |"
|
||||
result = render_table(md)
|
||||
assert '<code>code</code>' in result, (
|
||||
f"Inline code in table cell should render as <code>. Got: {result}"
|
||||
)
|
||||
|
||||
def test_bold_code_renders_inside_table_cell(self):
|
||||
"""**`bold code`** inside a table cell must render as <strong><code>."""
|
||||
md = "| Style | Example |\n|---|---|\n| bold code | **`bold code`** |"
|
||||
result = render_table(md)
|
||||
# Should have code tag (even inside bold)
|
||||
assert '<code>bold code</code>' in result, (
|
||||
f"Bold code in table should render as <code>. Got: {result}"
|
||||
)
|
||||
|
||||
def test_multiple_code_spans_in_same_cell(self):
|
||||
"""Multiple backtick spans in one cell all render as <code>."""
|
||||
md = "| Combined |\n|---|\n| `a` and `b` |"
|
||||
result = render_table(md)
|
||||
assert result.count('<code>') == 2, (
|
||||
f"Expected 2 code tags in cell, got: {result}"
|
||||
)
|
||||
|
||||
def test_code_in_header_cell(self):
|
||||
"""`code` in a <th> header cell must also render as <code>."""
|
||||
md = "| `header code` | Normal |\n|---|---|\n| data | data |"
|
||||
result = render_table(md)
|
||||
assert '<code>header code</code>' in result, (
|
||||
f"Code in header cell should render. Got: {result}"
|
||||
)
|
||||
|
||||
def test_code_not_mangled_by_bold_in_table(self):
|
||||
"""**`code`** in a table cell must NOT produce <code> (the pre-fix bug)."""
|
||||
md = "| Pattern | Example |\n|---|---|\n| bold-code | **`npm install`** |"
|
||||
result = render_table(md)
|
||||
assert '<code>' not in result, (
|
||||
f"Code tags inside bold in table must not be HTML-escaped. Got: {result}"
|
||||
)
|
||||
assert '<strong>' in result, "Bold wrapper should be present"
|
||||
assert '<code>npm install</code>' in result
|
||||
|
||||
def test_code_with_special_chars_in_table(self):
|
||||
"""`<script>` inside a table cell must have the angle brackets escaped."""
|
||||
md = "| Input | Output |\n|---|---|\n| `<script>` | sanitized |"
|
||||
result = render_table(md)
|
||||
assert '<script>' in result, (
|
||||
f"Code content must be HTML-escaped. Got: {result}"
|
||||
)
|
||||
# The <code> wrapper itself must be there
|
||||
assert '<code>' in result
|
||||
|
||||
def test_code_adjacent_to_link_in_table(self):
|
||||
"""`code` and [link](url) in same cell both render correctly."""
|
||||
url = 'https://example.com'
|
||||
md = f"| Mixed |\n|---|\n| `foo` and [bar]({url}) |"
|
||||
result = render_table(md)
|
||||
assert '<code>foo</code>' in result
|
||||
assert f'href="{url}"' in result
|
||||
assert 'bar' in result
|
||||
|
||||
def test_empty_code_span_in_table(self):
|
||||
"""Edge case: empty backtick span in table cell (`` ` ` ``) — no crash."""
|
||||
# This won't match the code regex (requires at least 1 char), should pass through
|
||||
md = "| Col |\n|---|\n| normal text |"
|
||||
result = render_table(md)
|
||||
assert '<td>normal text</td>' in result
|
||||
|
||||
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
# ISSUE #487 — JS renderer: markdown image syntax
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestIssue487ImageRendering:
|
||||
"""Image syntax  must render as <img>, not as ! + link."""
|
||||
|
||||
# ── Source-level checks ──────────────────────────────────────────────────
|
||||
|
||||
def test_image_pass_present_in_ui_js(self):
|
||||
"""renderMd() must contain an image regex pass for ."""
|
||||
assert ' regex)"
|
||||
)
|
||||
# More specifically, look for the img tag being generated
|
||||
assert 'msg-media-img' in UI_JS, (
|
||||
"Image pass should reuse .msg-media-img class"
|
||||
)
|
||||
|
||||
def test_image_pass_runs_before_link_pass_in_outer(self):
|
||||
"""Image regex must appear in ui.js BEFORE the [label](url) link pass."""
|
||||
# Find the image pass position
|
||||
img_idx = UI_JS.find('!\\[')
|
||||
if img_idx == -1:
|
||||
img_idx = UI_JS.find(" link pass "
|
||||
"to prevent the image from being consumed as a plain link"
|
||||
)
|
||||
|
||||
def test_image_url_sanitized_for_quotes(self):
|
||||
"""Image src URL must have double-quotes percent-encoded."""
|
||||
# The image pass must use .replace(/"/g,'%22') or equivalent
|
||||
# Look for the pattern near image handling
|
||||
img_idx = UI_JS.find('msg-media-img')
|
||||
assert img_idx != -1
|
||||
# Find all occurrences — there's the MEDIA restore and the new image pass
|
||||
# The new one should have %22 for URL sanitization
|
||||
assert '%22' in UI_JS, (
|
||||
"Image src URL must sanitize double-quotes to %22"
|
||||
)
|
||||
|
||||
def test_image_alt_uses_esc(self):
|
||||
"""Alt text must be passed through esc() to prevent XSS."""
|
||||
# Look for esc( call near the image rendering code
|
||||
# The pattern should be: alt="${esc(alt)}"
|
||||
assert 'esc(' in UI_JS, "esc() function must be used for alt text"
|
||||
|
||||
def test_safe_tags_includes_img(self):
|
||||
"""SAFE_TAGS allowlist must include 'img' to prevent the tag from being escaped."""
|
||||
# Find the SAFE_TAGS regex in ui.js
|
||||
safe_idx = UI_JS.find('SAFE_TAGS=')
|
||||
assert safe_idx != -1, "SAFE_TAGS not found in ui.js"
|
||||
safe_window = UI_JS[safe_idx:safe_idx+300]
|
||||
assert 'img' in safe_window, (
|
||||
f"SAFE_TAGS must include 'img' tag. Found: {safe_window!r}"
|
||||
)
|
||||
|
||||
def test_inlinemd_has_image_pass(self):
|
||||
"""inlineMd() must also handle  for images inside table cells."""
|
||||
# inlineMd is called for table cells, list items, blockquotes
|
||||
# Find inlineMd function body
|
||||
start = UI_JS.find('function inlineMd(')
|
||||
assert start != -1, "inlineMd function not found"
|
||||
# Get a generous window covering the function
|
||||
fn_window = UI_JS[start:start+1500]
|
||||
assert ' must produce an <img> tag."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result, f"Expected <img> tag, got: {result}"
|
||||
assert 'src="https://example.com/cat.png"' in result
|
||||
assert 'alt="A cat"' in result
|
||||
# Must NOT have the raw ![...] syntax left over
|
||||
assert ' must NOT produce an <a> tag (the pre-fix bug)."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<a ' not in result, (
|
||||
f"Image must not render as an <a> tag. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_stray_exclamation_not_present(self):
|
||||
"""No stray ! character before the img tag (the pre-fix symptom)."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
# Strip the img tag and check no ! is left
|
||||
cleaned = re.sub(r'<img[^>]+>', '', result)
|
||||
assert '!' not in cleaned, (
|
||||
f"Stray ! character present after image render. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_uses_msg_media_img_class(self):
|
||||
"""Rendered <img> must use class=\"msg-media-img\" for consistent styling."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert 'class="msg-media-img"' in result, (
|
||||
f"Image must use .msg-media-img class. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_has_lazy_loading(self):
|
||||
"""Rendered <img> must have loading=\"lazy\"."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert 'loading="lazy"' in result, f"Expected loading=lazy. Got: {result}"
|
||||
|
||||
def test_image_has_click_to_zoom(self):
|
||||
"""Rendered <img> must have onclick toggle for zoom."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert 'msg-media-img--full' in result, (
|
||||
f"Image must have click-to-zoom onclick. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_alt_is_escaped(self):
|
||||
"""Alt text with HTML special chars must be escaped."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<evil>' in result, (
|
||||
f"Alt text must be HTML-escaped. Got: {result}"
|
||||
)
|
||||
assert '<evil>' not in result
|
||||
|
||||
def test_image_url_quote_sanitized(self):
|
||||
"""Double-quote in image URL must be percent-encoded to prevent attribute breakout."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
# Find the src attribute value
|
||||
src_match = re.search(r'src="([^"]*)"', result)
|
||||
assert src_match, f"src attribute not found. Got: {result}"
|
||||
src_val = src_match.group(1)
|
||||
assert '"' not in src_val, (
|
||||
f"Raw double-quote in src would break attribute. Got src: {src_val!r}"
|
||||
)
|
||||
|
||||
def test_image_no_javascript_uri(self):
|
||||
"""javascript: URIs must not be rendered as image src (regex only matches http/https)."""
|
||||
t = ')'
|
||||
result = inline_md(t)
|
||||
# The regex requires https?://, so this should pass through unmodified
|
||||
assert '<img ' not in result, (
|
||||
f"javascript: URI must not render as <img>. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_no_data_uri(self):
|
||||
"""data: URIs must not be rendered as image src."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<img ' not in result, (
|
||||
f"data: URI must not render as <img>. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_followed_by_text(self):
|
||||
"""Image followed by plain text — only the image becomes an <img>."""
|
||||
t = ' and some text'
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result
|
||||
assert 'and some text' in result
|
||||
|
||||
def test_image_preceded_by_text(self):
|
||||
"""Text before an image — both render correctly."""
|
||||
t = 'Here is a screenshot: '
|
||||
result = inline_md(t)
|
||||
assert 'Here is a screenshot:' in result
|
||||
assert '<img ' in result
|
||||
|
||||
def test_image_and_link_in_same_cell(self):
|
||||
"""Image and link in same inline context both render correctly."""
|
||||
t = ' see [here](https://example.com)'
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result
|
||||
assert '<a href="https://example.com"' in result
|
||||
assert ' inside a markdown table cell must render as <img>."""
|
||||
md = ("| Image | Caption |\n"
|
||||
"|---|---|\n"
|
||||
"|  | Company logo |")
|
||||
result = render_table(md)
|
||||
assert '<img ' in result, f"Image in table should render as <img>. Got: {result}"
|
||||
assert 'src="https://example.com/logo.png"' in result
|
||||
assert '<a ' not in result, "Image in table must not render as <a>"
|
||||
|
||||
def test_image_in_table_no_stray_exclamation(self):
|
||||
"""No stray ! before the <img> when image is inside a table cell."""
|
||||
md = ("| X |\n|---|\n|  |")
|
||||
result = render_table(md)
|
||||
# Strip known tags and check no ! appears
|
||||
cleaned = re.sub(r'<[^>]+>', '', result)
|
||||
assert '!' not in cleaned, (
|
||||
f"Stray ! in table cell after image render. Cleaned: {cleaned!r}"
|
||||
)
|
||||
|
||||
def test_empty_alt_text_image(self):
|
||||
""" with empty alt renders as <img> with empty alt attribute."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result
|
||||
assert 'alt=""' in result
|
||||
|
||||
def test_multiple_images_in_one_cell(self):
|
||||
"""Two images in one table cell both render as <img> tags."""
|
||||
t = (' '
|
||||
'')
|
||||
result = inline_md(t)
|
||||
assert result.count('<img ') == 2, (
|
||||
f"Expected 2 img tags. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_with_https_url(self):
|
||||
"""https:// image URL renders correctly."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert 'src="https://secure.example.com/img.jpg"' in result
|
||||
|
||||
def test_image_with_http_url(self):
|
||||
"""http:// image URL also renders (non-https still valid)."""
|
||||
t = ''
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result
|
||||
assert 'src="http://example.com/img.jpg"' in result
|
||||
|
||||
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
# Cross-cutting: code + image together inside tables (the edge case Nathan flagged)
|
||||
# ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestEdgeCasesCodeAndImageInTables:
|
||||
"""Combination edge cases: code blocks and images mixed inside table cells."""
|
||||
|
||||
def test_code_and_image_in_same_table_row(self):
|
||||
"""Table row with code in one cell and image in another renders both correctly."""
|
||||
md = ("| Code | Preview |\n"
|
||||
"|---|---|\n"
|
||||
"| `print('hello')` |  |")
|
||||
result = render_table(md)
|
||||
assert "<code>print('hello')</code>" in result or "<code>print('hello')</code>" in result, (
|
||||
f"Code cell should render as <code>. Got: {result}"
|
||||
)
|
||||
assert '<img ' in result, "Image cell should render as <img>"
|
||||
|
||||
def test_code_in_cell_with_image_in_next_cell(self):
|
||||
"""Multiple columns: code stays code, image stays image, no cross-contamination."""
|
||||
md = ("| Step | Example |\n"
|
||||
"|---|---|\n"
|
||||
"| Run `npm install` |  |")
|
||||
result = render_table(md)
|
||||
assert '<code>npm install</code>' in result
|
||||
assert '<img ' in result
|
||||
assert '<a ' not in result # image must not become a link
|
||||
|
||||
def test_bold_code_in_cell_and_image_in_cell(self):
|
||||
"""**`code`** in one cell and image in another — no esc() mangling."""
|
||||
md = ("| Command | Result |\n"
|
||||
"|---|---|\n"
|
||||
"| **`git status`** |  |")
|
||||
result = render_table(md)
|
||||
assert '<code>' not in result, (
|
||||
"Bold+code in table cell must not produce escaped code tags"
|
||||
)
|
||||
assert '<code>git status</code>' in result
|
||||
assert '<img ' in result
|
||||
|
||||
def test_link_code_image_all_in_table(self):
|
||||
"""Table with code, link, and image cells all render correctly."""
|
||||
url = 'https://github.com/issues/486'
|
||||
img_url = 'https://example.com/img.png'
|
||||
md = (f"| Code | Link | Image |\n"
|
||||
f"|---|---|---|\n"
|
||||
f"| `var x = 1` | [#486]({url}) |  |")
|
||||
result = render_table(md)
|
||||
assert '<code>var x = 1</code>' in result
|
||||
assert f'href="{url}"' in result
|
||||
assert '<img ' in result
|
||||
# No double-linking
|
||||
assert result.count('<a ') == 1
|
||||
|
||||
def test_image_url_with_query_string_in_table(self):
|
||||
"""Image URL with & in query string inside table cell — & not mangled."""
|
||||
url = 'https://example.com/img?w=100&h=200'
|
||||
md = f"| Image |\n|---|\n|  |"
|
||||
result = render_table(md)
|
||||
assert f'src="{url}"' in result, (
|
||||
f"& in image URL must not be escaped. Got: {result}"
|
||||
)
|
||||
|
||||
def test_image_adjacent_to_code_no_interference(self):
|
||||
"""Image immediately followed by code span in same cell — no token cross-talk."""
|
||||
t = ' `code`'
|
||||
result = inline_md(t)
|
||||
assert '<img ' in result
|
||||
assert '<code>code</code>' in result
|
||||
|
||||
def test_image_inside_code_span_not_rendered(self):
|
||||
"""An image syntax inside a backtick span must NOT render as an img tag."""
|
||||
t = '``'
|
||||
result = inline_md(t)
|
||||
# The whole thing is inside backticks — should be literal code, not an img
|
||||
assert '<img ' not in result, (
|
||||
f"Image syntax inside code span must not render as <img>. Got: {result}"
|
||||
)
|
||||
# Should render as a code element with the raw text inside
|
||||
assert '<code>' in result
|
||||
131
tests/test_issue487b.py
Normal file
131
tests/test_issue487b.py
Normal file
@@ -0,0 +1,131 @@
|
||||
r"""
|
||||
Regression test for image src URL corruption by the autolink pass.
|
||||
|
||||
Bug: the _al_stash before the autolink pass only stashed <a> tags.
|
||||
<img> tags produced by the  image pass were NOT stashed,
|
||||
so the autolink regex matched the URL inside src="..." and wrapped it
|
||||
in <a href="...">url</a>, producing src="<a href="...">url</a>" —
|
||||
a completely broken image source.
|
||||
|
||||
Fix: extend _al_stash regex to also stash <img> tags:
|
||||
(<a\b[^>]*>[\s\S]*?<\/a>|<img\b[^>]*>)
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text()
|
||||
|
||||
|
||||
# ── Source-level check ────────────────────────────────────────────────────────
|
||||
|
||||
def test_al_stash_includes_img_tags():
|
||||
"""_al_stash regex must stash both <a> and <img> tags to protect src= from autolink."""
|
||||
assert '<img\\b[^>]*>' in UI_JS or '<img\\\\b[^>]*>' in UI_JS, (
|
||||
"_al_stash should include <img> tag pattern to prevent autolink mangling src= URLs"
|
||||
)
|
||||
|
||||
|
||||
# ── Behaviour tests (Python mirror of fixed pipeline) ─────────────────────────
|
||||
|
||||
import html as _html
|
||||
def esc(s): return _html.escape(str(s), quote=True)
|
||||
|
||||
SAFE_TAGS = re.compile(
|
||||
r'^</?(strong|em|code|pre|h[1-6]|ul|ol|li|table|thead|tbody|tr|th|td'
|
||||
r'|hr|blockquote|p|br|a|img|div|span)([\s>]|$)', re.I
|
||||
)
|
||||
|
||||
|
||||
def render_with_image_and_autolink(raw):
|
||||
"""Simulate the image pass + SAFE_TAGS + _al_stash + autolink pipeline."""
|
||||
s = raw
|
||||
# Image pass
|
||||
s = re.sub(
|
||||
r'!\[([^\]]*)\]\((https?://[^\)]+)\)',
|
||||
lambda m: (
|
||||
f'<img src="{m.group(2).replace(chr(34), "%22")}" '
|
||||
f'alt="{esc(m.group(1))}" class="msg-media-img" loading="lazy">'
|
||||
),
|
||||
s,
|
||||
)
|
||||
# SAFE_TAGS
|
||||
s = re.sub(
|
||||
r'</?[a-zA-Z][^>]*>',
|
||||
lambda m: m.group() if SAFE_TAGS.match(m.group()) else esc(m.group()),
|
||||
s,
|
||||
)
|
||||
# _al_stash (fixed: stashes both <a> and <img>)
|
||||
al_stash = []
|
||||
s = re.sub(
|
||||
r'(<a\b[^>]*>[\s\S]*?<\/a>|<img\b[^>]*>)',
|
||||
lambda m: (al_stash.append(m.group(1)) or f'\x00B{len(al_stash)-1}\x00'),
|
||||
s,
|
||||
)
|
||||
# Autolink
|
||||
def autolink(m):
|
||||
url = m.group(1)
|
||||
trail = url[-1] if url[-1] in '.,;:!?)' else ''
|
||||
clean = url[:-1] if trail else url
|
||||
return f'<a href="{clean}" target="_blank" rel="noopener">{esc(clean)}</a>{trail}'
|
||||
s = re.sub(r'(https?://[^\s<>"\')\]]+)', autolink, s)
|
||||
# Restore
|
||||
s = re.sub(r'\x00B(\d+)\x00', lambda m: al_stash[int(m.group(1))], s)
|
||||
return s
|
||||
|
||||
|
||||
def test_image_src_not_mangled_by_autolink():
|
||||
"""The URL inside src= of a rendered <img> must not be wrapped in <a> by autolink."""
|
||||
url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/280px-PNG_transparency_demonstration_1.png'
|
||||
result = render_with_image_and_autolink(f'')
|
||||
assert f'src="{url}"' in result, f"src= URL should be intact, got: {result[:200]}"
|
||||
# The URL inside src= must NOT be wrapped in <a>
|
||||
src_part = result.split('src="')[1].split('"')[0]
|
||||
assert '<a ' not in src_part, f"src= must not contain <a> tag, got: {src_part}"
|
||||
assert src_part == url, f"src= URL mangled: expected {url}, got {src_part}"
|
||||
|
||||
|
||||
def test_image_tag_renders_as_img():
|
||||
""" must produce an <img> tag, not a plain link."""
|
||||
result = render_with_image_and_autolink('')
|
||||
assert '<img ' in result, f"Expected <img> tag, got: {result}"
|
||||
assert 'src="https://example.com/img.png"' in result
|
||||
assert '<a ' not in result # no spurious link wrapper
|
||||
|
||||
|
||||
def test_image_and_link_in_same_paragraph():
|
||||
"""Image and link in same paragraph must each render correctly without interference."""
|
||||
result = render_with_image_and_autolink(
|
||||
'See  and visit https://example.com'
|
||||
)
|
||||
assert '<img ' in result, "Image should render"
|
||||
assert '<a ' in result, "Bare URL should autolink"
|
||||
# img src must not contain <a>
|
||||
src_part = result.split('src="')[1].split('"')[0]
|
||||
assert '<a' not in src_part, f"src= mangled: {src_part}"
|
||||
|
||||
|
||||
def test_image_count_is_one():
|
||||
"""One  should produce exactly one <img> tag."""
|
||||
result = render_with_image_and_autolink('')
|
||||
assert result.count('<img ') == 1, f"Expected 1 <img>, got {result.count('<img ')}: {result}"
|
||||
|
||||
|
||||
def test_multiple_images_not_mangled():
|
||||
"""Multiple images in one message each get clean src= values."""
|
||||
urls = [
|
||||
'https://example.com/a.png',
|
||||
'https://example.com/b.png',
|
||||
]
|
||||
raw = '\n\n'.join(f'' for i, url in enumerate(urls))
|
||||
result = render_with_image_and_autolink(raw)
|
||||
for url in urls:
|
||||
assert f'src="{url}"' in result, f"src= for {url} mangled in: {result[:300]}"
|
||||
|
||||
|
||||
def test_image_with_query_string_src_intact():
|
||||
"""Image URL with & in query string must have & (not &) in src."""
|
||||
url = 'https://example.com/img?w=100&h=200&fmt=png'
|
||||
result = render_with_image_and_autolink(f'')
|
||||
assert f'src="{url}"' in result, f"Query string URL mangled: {result[:200]}"
|
||||
assert '&' not in result.split('src="')[1].split('"')[0]
|
||||
105
tests/test_issue569_579.py
Normal file
105
tests/test_issue569_579.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Tests for fixes:
|
||||
|
||||
- #569: docker_init.bash auto-detects WANTED_UID/WANTED_GID from mounted workspace
|
||||
so macOS users (UID 501) don't need to manually set the env var.
|
||||
- #579: Topbar message count already filters tool messages (role !== 'tool') —
|
||||
confirmed present. Closing as already fixed by #584 which removed the
|
||||
sidebar meta row (the only place raw message_count was ever displayed).
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
INIT_SH = (REPO_ROOT / "docker_init.bash").read_text(encoding="utf-8")
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── #569: docker UID/GID auto-detect ─────────────────────────────────────────
|
||||
|
||||
def test_569_uid_autodetect_present():
|
||||
"""docker_init.bash must have workspace-based UID auto-detection (#569)."""
|
||||
assert "stat -c '%u'" in INIT_SH or 'stat -c \'%u\'' in INIT_SH, (
|
||||
"docker_init.bash must use stat to read workspace UID (#569)"
|
||||
)
|
||||
|
||||
|
||||
def test_569_gid_autodetect_present():
|
||||
"""docker_init.bash must have workspace-based GID auto-detection (#569)."""
|
||||
assert "stat -c '%g'" in INIT_SH or 'stat -c \'%g\'' in INIT_SH, (
|
||||
"docker_init.bash must use stat to read workspace GID (#569)"
|
||||
)
|
||||
|
||||
|
||||
def test_569_autodetect_before_usermod():
|
||||
"""UID auto-detect must appear before usermod call in docker_init.bash."""
|
||||
detect_pos = INIT_SH.find("stat -c '%u'")
|
||||
if detect_pos == -1:
|
||||
detect_pos = INIT_SH.find("stat -c")
|
||||
usermod_pos = INIT_SH.find("sudo usermod")
|
||||
assert detect_pos != -1, "stat UID detection not found"
|
||||
assert usermod_pos != -1, "sudo usermod not found"
|
||||
assert detect_pos < usermod_pos, (
|
||||
"UID auto-detect must occur before 'sudo usermod' so the correct UID "
|
||||
"is used when remapping the hermeswebui user"
|
||||
)
|
||||
|
||||
|
||||
def test_569_skips_root_uid():
|
||||
"""Auto-detect must not use UID 0 (root-owned mount = untrustworthy)."""
|
||||
detect_block_start = INIT_SH.find("Auto-detect from mounted workspace")
|
||||
assert detect_block_start != -1, "auto-detect comment block not found"
|
||||
block = INIT_SH[detect_block_start:detect_block_start + 600]
|
||||
assert '"0"' in block or "'0'" in block, (
|
||||
"Auto-detect block must skip UID 0 to avoid incorrectly using root ownership"
|
||||
)
|
||||
|
||||
|
||||
def test_569_fallback_preserved():
|
||||
"""Hardcoded default 1024 fallback must still exist after auto-detect."""
|
||||
assert "WANTED_UID=${WANTED_UID:-1024}" in INIT_SH, (
|
||||
"WANTED_UID default fallback must remain so explicit env var still works"
|
||||
)
|
||||
assert "WANTED_GID=${WANTED_GID:-1024}" in INIT_SH, (
|
||||
"WANTED_GID default fallback must remain"
|
||||
)
|
||||
|
||||
|
||||
# ── #579: topbar message count already filters tool messages ──────────────────
|
||||
|
||||
def test_579_topbar_filters_tool_messages():
|
||||
"""ui.js topbar count must filter out role='tool' messages (#579).
|
||||
|
||||
The sidebar previously showed raw message_count (which included tool
|
||||
messages), causing a mismatch with the topbar. PR #584 removed the
|
||||
sidebar count display entirely; the topbar was already correct.
|
||||
This test locks in the existing topbar filter so it can't regress.
|
||||
"""
|
||||
# Find the topbarMeta assignment
|
||||
meta_pos = UI_JS.find("topbarMeta")
|
||||
assert meta_pos != -1, "topbarMeta assignment not found in ui.js"
|
||||
|
||||
# Find the filter that precedes it — should exclude role==='tool'
|
||||
context = UI_JS[max(0, meta_pos - 400):meta_pos + 100]
|
||||
assert "role" in context and "tool" in context, (
|
||||
"topbarMeta count must filter by role — "
|
||||
"messages with role='tool' must be excluded from the displayed count"
|
||||
)
|
||||
# The filter must exclude tool messages (not include them)
|
||||
assert "!=='tool'" in context or "!= 'tool'" in context or "role!=='tool'" in context, (
|
||||
"topbar count filter must use !== 'tool' to exclude tool messages"
|
||||
)
|
||||
|
||||
|
||||
def test_579_sidebar_no_longer_shows_raw_count():
|
||||
"""sessions.js must not reference message_count in the render path (#579).
|
||||
|
||||
After PR #584, the sidebar no longer shows message_count at all,
|
||||
eliminating the inconsistency between sidebar (raw) and topbar (filtered).
|
||||
"""
|
||||
sessions_js = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
|
||||
# message_count should not appear in the client-side session renderer
|
||||
assert "message_count" not in sessions_js, (
|
||||
"sessions.js must not reference message_count — "
|
||||
"the meta row that displayed it was removed in PR #584"
|
||||
)
|
||||
205
tests/test_issue572.py
Normal file
205
tests/test_issue572.py
Normal file
@@ -0,0 +1,205 @@
|
||||
"""Tests for issue #572: onboarding must not fire or overwrite config for
|
||||
providers not in the quick-setup list (minimax-cn, deepseek, xai, etc.).
|
||||
|
||||
Root cause: _provider_api_key_present() only knew about the four providers in
|
||||
_SUPPORTED_PROVIDER_SETUPS. For any other provider it returned False, causing
|
||||
chat_ready=False, which made the wizard fire even when the user was fully
|
||||
configured. The second part of the fix ensures _saveOnboardingProviderSetup()
|
||||
in the frontend also skips the POST when current_is_oauth is set.
|
||||
|
||||
Covers:
|
||||
1. _provider_api_key_present returns True for minimax-cn when
|
||||
MINIMAX_CN_API_KEY is in env (via hermes_cli.auth.get_auth_status)
|
||||
2. _status_from_runtime gives chat_ready=True for minimax-cn with a key set
|
||||
3. get_onboarding_status returns completed=True for a fully-configured
|
||||
unsupported provider when config.yaml exists
|
||||
4. The hermes_cli import failure path is safe (falls back gracefully)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import types
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _inject_hermes_cli_auth(get_auth_status_return):
|
||||
"""Inject a minimal hermes_cli.auth stub into sys.modules.
|
||||
|
||||
CI doesn't install hermes_cli (it's a separate package). Tests that
|
||||
exercise the hermes_cli fallback path must inject the module themselves
|
||||
rather than relying on mock.patch('hermes_cli.auth.get_auth_status')
|
||||
which fails with ModuleNotFoundError when the module isn't installed.
|
||||
"""
|
||||
mock_auth = types.ModuleType("hermes_cli.auth")
|
||||
mock_auth.get_auth_status = mock.MagicMock(return_value=get_auth_status_return)
|
||||
mock_hermes_cli = types.ModuleType("hermes_cli")
|
||||
|
||||
return mock.patch.dict(sys.modules, {
|
||||
"hermes_cli": mock_hermes_cli,
|
||||
"hermes_cli.auth": mock_auth,
|
||||
})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _call_provider_api_key_present(provider: str, cfg: dict = None, env_values: dict = None):
|
||||
from api.onboarding import _provider_api_key_present
|
||||
return _provider_api_key_present(provider, cfg or {}, env_values or {})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. _provider_api_key_present via hermes_cli fallback
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestProviderApiKeyPresentFallback:
|
||||
|
||||
def test_minimax_cn_logged_in_returns_true(self):
|
||||
"""minimax-cn: if hermes_cli.auth.get_auth_status returns logged_in, must be True."""
|
||||
with mock.patch("api.onboarding._SUPPORTED_PROVIDER_SETUPS", {
|
||||
"openrouter": {}, "anthropic": {}, "openai": {}, "custom": {}
|
||||
}):
|
||||
with _inject_hermes_cli_auth({"logged_in": True}):
|
||||
result = _call_provider_api_key_present("minimax-cn")
|
||||
assert result is True
|
||||
|
||||
def test_unsupported_provider_logged_out_returns_false(self):
|
||||
"""Unsupported provider with no key → False, no crash."""
|
||||
with mock.patch("api.onboarding._SUPPORTED_PROVIDER_SETUPS", {
|
||||
"openrouter": {}, "anthropic": {}, "openai": {}, "custom": {}
|
||||
}):
|
||||
with _inject_hermes_cli_auth({"logged_in": False}):
|
||||
result = _call_provider_api_key_present("deepseek")
|
||||
assert result is False
|
||||
|
||||
def test_hermes_cli_import_failure_is_safe(self):
|
||||
"""If hermes_cli is unavailable, falls back silently to False."""
|
||||
import builtins
|
||||
real_import = builtins.__import__
|
||||
|
||||
def _block_hermes_cli(name, *args, **kwargs):
|
||||
if name.startswith("hermes_cli"):
|
||||
raise ImportError("hermes_cli not available")
|
||||
return real_import(name, *args, **kwargs)
|
||||
|
||||
with mock.patch("api.onboarding._SUPPORTED_PROVIDER_SETUPS", {
|
||||
"openrouter": {}, "anthropic": {}, "openai": {}, "custom": {}
|
||||
}):
|
||||
with mock.patch("builtins.__import__", side_effect=_block_hermes_cli):
|
||||
result = _call_provider_api_key_present("minimax-cn")
|
||||
assert result is False # safe fallback
|
||||
|
||||
def test_supported_provider_still_works_without_fallback(self):
|
||||
"""openrouter with env key must still succeed via the original path."""
|
||||
from api.onboarding import _provider_api_key_present, _SUPPORTED_PROVIDER_SETUPS
|
||||
env_values = {"OPENROUTER_API_KEY": "sk-test"}
|
||||
result = _provider_api_key_present("openrouter", {}, env_values)
|
||||
assert result is True
|
||||
|
||||
def test_inline_api_key_in_cfg_still_works(self):
|
||||
"""model.api_key in config.yaml must be recognized for any provider."""
|
||||
cfg = {"model": {"provider": "minimax-cn", "default": "MiniMax-M2.7", "api_key": "key123"}}
|
||||
result = _call_provider_api_key_present("minimax-cn", cfg)
|
||||
assert result is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. _status_from_runtime: unsupported provider with key → chat_ready=True
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestStatusFromRuntimeUnsupportedProvider:
|
||||
|
||||
def _run(self, provider: str, model: str, api_key_present: bool, oauth_present: bool = False):
|
||||
from api.onboarding import _status_from_runtime
|
||||
cfg = {"model": {"provider": provider, "default": model}}
|
||||
with (
|
||||
mock.patch("api.onboarding._HERMES_FOUND", True),
|
||||
mock.patch("api.onboarding._load_env_file", return_value={}),
|
||||
mock.patch("api.onboarding._get_active_hermes_home", return_value=pathlib.Path("/tmp")),
|
||||
mock.patch("api.onboarding._provider_api_key_present", return_value=api_key_present),
|
||||
mock.patch("api.onboarding._provider_oauth_authenticated", return_value=oauth_present),
|
||||
):
|
||||
return _status_from_runtime(cfg, True)
|
||||
|
||||
def test_minimax_cn_with_key_gives_chat_ready(self):
|
||||
"""minimax-cn + api key present → chat_ready must be True."""
|
||||
result = self._run("minimax-cn", "MiniMax-M2.7", api_key_present=True)
|
||||
assert result["chat_ready"] is True, f"Expected chat_ready=True, got: {result}"
|
||||
assert result["provider_ready"] is True
|
||||
assert result["setup_state"] == "ready"
|
||||
|
||||
def test_deepseek_with_key_gives_chat_ready(self):
|
||||
"""deepseek + api key → chat_ready."""
|
||||
result = self._run("deepseek", "deepseek-chat", api_key_present=True)
|
||||
assert result["chat_ready"] is True
|
||||
|
||||
def test_unsupported_provider_no_key_no_oauth_gives_not_ready(self):
|
||||
"""No key, no oauth → provider_ready=False."""
|
||||
result = self._run("minimax-cn", "MiniMax-M2.7", api_key_present=False, oauth_present=False)
|
||||
assert result["chat_ready"] is False
|
||||
assert result["provider_ready"] is False
|
||||
|
||||
def test_oauth_provider_still_works_via_oauth_path(self):
|
||||
"""openai-codex (OAuth) with no api_key but oauth present → ready."""
|
||||
result = self._run("openai-codex", "codex-model", api_key_present=False, oauth_present=True)
|
||||
assert result["chat_ready"] is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. get_onboarding_status: minimax-cn fully configured → completed=True
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestOnboardingStatusUnsupportedProvider:
|
||||
|
||||
def _make_status(self, chat_ready: bool, provider: str = "minimax-cn"):
|
||||
import api.onboarding as mod
|
||||
fake_config_path = pathlib.Path("/tmp/_test_572_config.yaml")
|
||||
cfg = {"model": {"provider": provider, "default": "MiniMax-M2.7"}}
|
||||
runtime = {
|
||||
"chat_ready": chat_ready,
|
||||
"provider_configured": True,
|
||||
"provider_ready": chat_ready,
|
||||
"setup_state": "ready" if chat_ready else "provider_incomplete",
|
||||
"provider_note": "test",
|
||||
"current_provider": provider,
|
||||
"current_model": "MiniMax-M2.7",
|
||||
"current_base_url": None,
|
||||
"env_path": "/tmp/.env",
|
||||
}
|
||||
with (
|
||||
mock.patch.object(mod, "load_settings", return_value={}),
|
||||
mock.patch.object(mod, "get_config", return_value=cfg),
|
||||
mock.patch.object(mod, "verify_hermes_imports", return_value=(True, [], {})),
|
||||
mock.patch.object(mod, "_status_from_runtime", return_value=runtime),
|
||||
mock.patch.object(mod, "load_workspaces", return_value=[]),
|
||||
mock.patch.object(mod, "get_last_workspace", return_value=None),
|
||||
mock.patch.object(mod, "get_available_models", return_value=[]),
|
||||
mock.patch.object(mod, "_get_config_path", return_value=fake_config_path),
|
||||
mock.patch.object(pathlib.Path, "exists", return_value=True),
|
||||
):
|
||||
return mod.get_onboarding_status()
|
||||
|
||||
def test_minimax_cn_chat_ready_skips_wizard(self):
|
||||
"""minimax-cn + chat_ready=True + config.yaml exists → wizard must NOT fire."""
|
||||
result = self._make_status(chat_ready=True)
|
||||
assert result["completed"] is True, (
|
||||
"Wizard fired for minimax-cn user with valid config! "
|
||||
"config.yaml + chat_ready=True must auto-complete onboarding regardless of provider."
|
||||
)
|
||||
|
||||
def test_minimax_cn_not_ready_shows_wizard(self):
|
||||
"""minimax-cn + chat_ready=False → wizard fires so user can fix it."""
|
||||
result = self._make_status(chat_ready=False)
|
||||
assert result["completed"] is False
|
||||
|
||||
def test_current_is_oauth_set_for_unsupported_provider(self):
|
||||
"""setup.current_is_oauth must be True for minimax-cn (not in quick-setup list)."""
|
||||
result = self._make_status(chat_ready=True)
|
||||
assert result["setup"]["current_is_oauth"] is True, (
|
||||
"current_is_oauth should be True for providers not in _SUPPORTED_PROVIDER_SETUPS"
|
||||
)
|
||||
25
tests/test_issue_code_syntax_highlight.py
Normal file
25
tests/test_issue_code_syntax_highlight.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""Regression tests for fenced code block syntax highlighting."""
|
||||
from pathlib import Path
|
||||
|
||||
UI_JS = Path(__file__).resolve().parent.parent / "static" / "ui.js"
|
||||
|
||||
|
||||
def _read_ui_js() -> str:
|
||||
return UI_JS.read_text()
|
||||
|
||||
|
||||
def test_fenced_code_blocks_add_prism_language_class():
|
||||
js = _read_ui_js()
|
||||
assert 'class="language-${esc(normalizedLang)}"' in js, (
|
||||
"Fenced code blocks should add Prism language-* classes so syntax highlighting works"
|
||||
)
|
||||
|
||||
|
||||
def test_fenced_code_blocks_keep_existing_pre_header_layout():
|
||||
js = _read_ui_js()
|
||||
assert 'return `${h}<pre><code${langAttr}>${esc(code.replace(/\\n$/,' in js, (
|
||||
"The syntax-highlight fix should preserve the existing fenced code block layout"
|
||||
)
|
||||
assert '<div class="code-block">' not in js, (
|
||||
"This fix should not introduce a new wrapper around fenced code blocks"
|
||||
)
|
||||
232
tests/test_issues_373_374_375.py
Normal file
232
tests/test_issues_373_374_375.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""
|
||||
Tests for issues #373, #374, and #375.
|
||||
|
||||
#373: Chat silently swallows errors — no feedback when agent fails to respond
|
||||
#374: Remove stale OpenAI models from default list (gpt-4o, o3)
|
||||
#375: Model dropdown should fetch live models from provider
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
STREAMING_PY = (REPO / "api" / "streaming.py").read_text(encoding="utf-8")
|
||||
CONFIG_PY = (REPO / "api" / "config.py").read_text(encoding="utf-8")
|
||||
ROUTES_PY = (REPO / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
MESSAGES_JS = (REPO / "static" / "messages.js").read_text(encoding="utf-8")
|
||||
UI_JS = (REPO / "static" / "ui.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Issue #373: Silent error detection ──────────────────────────────────────
|
||||
|
||||
class TestSilentErrorDetection:
|
||||
"""streaming.py must emit apperror when agent returns no assistant reply."""
|
||||
|
||||
def test_streaming_detects_no_assistant_reply(self):
|
||||
"""streaming.py must check if any assistant message was produced."""
|
||||
assert "_assistant_added" in STREAMING_PY, (
|
||||
"streaming.py must check whether an assistant message was produced (#373)"
|
||||
)
|
||||
|
||||
def test_streaming_emits_apperror_on_no_response(self):
|
||||
"""streaming.py must emit apperror event when agent produced no reply."""
|
||||
assert "no_response" in STREAMING_PY, (
|
||||
"streaming.py must emit apperror with type='no_response' for silent failures (#373)"
|
||||
)
|
||||
|
||||
def test_streaming_returns_early_after_apperror(self):
|
||||
"""streaming.py must return after emitting apperror (not also emit done)."""
|
||||
# The return statement must come after the put('apperror') for no_response
|
||||
no_resp_pos = STREAMING_PY.find("'no_response'")
|
||||
return_pos = STREAMING_PY.find("return # Don't emit done", no_resp_pos)
|
||||
assert no_resp_pos != -1, "no_response type not found in streaming.py"
|
||||
assert return_pos != -1, (
|
||||
"streaming.py must return after emitting apperror to prevent also emitting done (#373)"
|
||||
)
|
||||
assert return_pos > no_resp_pos
|
||||
|
||||
def test_streaming_detects_auth_error_in_result(self):
|
||||
"""streaming.py must detect auth errors from the result object."""
|
||||
assert "_is_auth" in STREAMING_PY, (
|
||||
"streaming.py must detect auth errors in silent failures (#373)"
|
||||
)
|
||||
assert "auth_mismatch" in STREAMING_PY, (
|
||||
"streaming.py must emit auth_mismatch type for auth failures (#373)"
|
||||
)
|
||||
|
||||
def test_messages_js_done_handler_detects_no_reply(self):
|
||||
"""messages.js done handler must show an error if no assistant reply arrived."""
|
||||
# Check for either the variable name or the inlined check pattern
|
||||
has_no_reply_guard = (
|
||||
"hasAssistantReply" in MESSAGES_JS
|
||||
or ("role==='assistant'" in MESSAGES_JS and "No response received" in MESSAGES_JS)
|
||||
)
|
||||
assert has_no_reply_guard, (
|
||||
"messages.js done handler must detect zero assistant replies (#373)"
|
||||
)
|
||||
assert "No response received" in MESSAGES_JS, (
|
||||
"messages.js must show 'No response received' inline message (#373)"
|
||||
)
|
||||
|
||||
def test_messages_js_handles_no_response_apperror_type(self):
|
||||
"""messages.js apperror handler must recognise the no_response type."""
|
||||
assert "isNoResponse" in MESSAGES_JS or "no_response" in MESSAGES_JS, (
|
||||
"messages.js apperror handler must handle type='no_response' (#373)"
|
||||
)
|
||||
|
||||
def test_messages_js_no_response_label(self):
|
||||
"""messages.js must show a distinct label for no_response errors."""
|
||||
assert "No response received" in MESSAGES_JS, (
|
||||
"messages.js must display 'No response received' label for no_response errors (#373)"
|
||||
)
|
||||
|
||||
|
||||
# ── Issue #374: Stale model list cleanup ─────────────────────────────────────
|
||||
|
||||
class TestStaleModelListCleanup:
|
||||
"""gpt-4o and o3 must be removed from the primary OpenAI model lists."""
|
||||
|
||||
def test_gpt4o_removed_from_fallback_models(self):
|
||||
"""_FALLBACK_MODELS must not contain gpt-4o (issue #374)."""
|
||||
fallback_block_start = CONFIG_PY.find("_FALLBACK_MODELS = [")
|
||||
fallback_block_end = CONFIG_PY.find("]", fallback_block_start)
|
||||
fallback_block = CONFIG_PY[fallback_block_start:fallback_block_end]
|
||||
assert "gpt-4o" not in fallback_block, (
|
||||
"_FALLBACK_MODELS still contains gpt-4o — remove it per issue #374"
|
||||
)
|
||||
|
||||
def test_o3_removed_from_fallback_models(self):
|
||||
"""_FALLBACK_MODELS must not contain o3 (issue #374)."""
|
||||
fallback_block_start = CONFIG_PY.find("_FALLBACK_MODELS = [")
|
||||
fallback_block_end = CONFIG_PY.find("]", fallback_block_start)
|
||||
fallback_block = CONFIG_PY[fallback_block_start:fallback_block_end]
|
||||
assert '"o3"' not in fallback_block and "'o3'" not in fallback_block, (
|
||||
"_FALLBACK_MODELS still contains o3 — remove it per issue #374"
|
||||
)
|
||||
|
||||
def test_gpt4o_removed_from_provider_models_openai(self):
|
||||
"""_PROVIDER_MODELS['openai'] must not contain gpt-4o (issue #374)."""
|
||||
openai_start = CONFIG_PY.find('"openai": [')
|
||||
openai_end = CONFIG_PY.find("],", openai_start)
|
||||
openai_block = CONFIG_PY[openai_start:openai_end]
|
||||
assert "gpt-4o" not in openai_block, (
|
||||
"_PROVIDER_MODELS['openai'] still contains gpt-4o — remove per issue #374"
|
||||
)
|
||||
|
||||
def test_o3_removed_from_provider_models_openai(self):
|
||||
"""_PROVIDER_MODELS['openai'] must not contain o3 (issue #374)."""
|
||||
openai_start = CONFIG_PY.find('"openai": [')
|
||||
openai_end = CONFIG_PY.find("],", openai_start)
|
||||
openai_block = CONFIG_PY[openai_start:openai_end]
|
||||
assert '"o3"' not in openai_block and "'o3'" not in openai_block, (
|
||||
"_PROVIDER_MODELS['openai'] still contains o3 — remove per issue #374"
|
||||
)
|
||||
|
||||
def test_fallback_still_has_gpt54_mini(self):
|
||||
"""_FALLBACK_MODELS must still contain gpt-5.4-mini (not over-trimmed)."""
|
||||
assert "gpt-5.4-mini" in CONFIG_PY, (
|
||||
"_FALLBACK_MODELS must keep gpt-5.4-mini as primary OpenAI model (#374)"
|
||||
)
|
||||
|
||||
def test_fallback_has_gpt54(self):
|
||||
"""_FALLBACK_MODELS must contain gpt-5.4-mini as the primary OpenAI option."""
|
||||
from api.config import _FALLBACK_MODELS
|
||||
ids = [m["id"] for m in _FALLBACK_MODELS]
|
||||
assert any("gpt-5.4-mini" in mid for mid in ids), (
|
||||
"_FALLBACK_MODELS must include gpt-5.4-mini as the primary OpenAI option"
|
||||
)
|
||||
|
||||
def test_copilot_list_unchanged(self):
|
||||
"""Copilot provider model list should still include gpt-4o (it's a valid Copilot model)."""
|
||||
copilot_start = CONFIG_PY.find('"copilot": [')
|
||||
copilot_end = CONFIG_PY.find("],", copilot_start)
|
||||
if copilot_start == -1:
|
||||
return # No copilot list — that's fine
|
||||
copilot_block = CONFIG_PY[copilot_start:copilot_end]
|
||||
assert "gpt-4o" in copilot_block, (
|
||||
"Copilot provider model list should keep gpt-4o (it's available via Copilot) (#374)"
|
||||
)
|
||||
|
||||
|
||||
# ── Issue #375: Live model fetching ─────────────────────────────────────────
|
||||
|
||||
class TestLiveModelFetching:
|
||||
"""Backend and frontend must support live model fetching from provider APIs."""
|
||||
|
||||
def test_live_models_endpoint_exists_in_routes(self):
|
||||
"""routes.py must have a /api/models/live endpoint (#375)."""
|
||||
assert "/api/models/live" in ROUTES_PY, (
|
||||
"routes.py must define /api/models/live endpoint (#375)"
|
||||
)
|
||||
|
||||
def test_live_models_handler_function_exists(self):
|
||||
"""routes.py must define _handle_live_models() function (#375)."""
|
||||
assert "def _handle_live_models(" in ROUTES_PY, (
|
||||
"routes.py must define _handle_live_models() for live model fetching (#375)"
|
||||
)
|
||||
|
||||
def test_live_models_handler_validates_scheme(self):
|
||||
"""_handle_live_models must validate URL scheme to prevent file:// injection (B310)."""
|
||||
assert "nosec B310" in ROUTES_PY or ("scheme" in ROUTES_PY and "http" in ROUTES_PY), (
|
||||
"_handle_live_models must validate URL scheme before urlopen (#375)"
|
||||
)
|
||||
|
||||
def test_live_models_handler_has_ssrf_guard(self):
|
||||
"""_handle_live_models must guard against SSRF (private IP access)."""
|
||||
assert "ssrf_blocked" in ROUTES_PY or ("is_private" in ROUTES_PY and "live" in ROUTES_PY), (
|
||||
"_handle_live_models must have SSRF protection for private IP ranges (#375)"
|
||||
)
|
||||
|
||||
def test_live_models_all_providers_handled_via_agent(self):
|
||||
"""_handle_live_models must delegate to provider_model_ids() which handles all
|
||||
providers gracefully — live fetch where possible, static fallback otherwise.
|
||||
The old 'not_supported' return for Anthropic/Google is superseded: those
|
||||
providers now return live or static model lists via the agent delegate."""
|
||||
assert "provider_model_ids" in ROUTES_PY, (
|
||||
"_handle_live_models must delegate to hermes_cli.models.provider_model_ids() "
|
||||
"so all providers are handled uniformly (#375 upgrade)"
|
||||
)
|
||||
|
||||
def test_frontend_has_fetch_live_models_function(self):
|
||||
"""ui.js must define _fetchLiveModels() for background live model loading (#375)."""
|
||||
assert "function _fetchLiveModels(" in UI_JS or "async function _fetchLiveModels(" in UI_JS, (
|
||||
"ui.js must define _fetchLiveModels() function (#375)"
|
||||
)
|
||||
|
||||
def test_frontend_live_models_cache_exists(self):
|
||||
"""ui.js must cache live model responses to avoid redundant API calls (#375)."""
|
||||
assert "_liveModelCache" in UI_JS, (
|
||||
"ui.js must use _liveModelCache to avoid re-fetching on every dropdown open (#375)"
|
||||
)
|
||||
|
||||
def test_frontend_calls_live_models_after_static_load(self):
|
||||
"""populateModelDropdown must call _fetchLiveModels after rendering the static list (#375)."""
|
||||
assert "_fetchLiveModels" in UI_JS, (
|
||||
"populateModelDropdown must call _fetchLiveModels for background update (#375)"
|
||||
)
|
||||
|
||||
def test_frontend_live_fetch_only_adds_new_models(self):
|
||||
"""_fetchLiveModels must not duplicate models already in the static list (#375)."""
|
||||
assert "existingIds" in UI_JS, (
|
||||
"_fetchLiveModels must track existing model IDs to avoid duplicates (#375)"
|
||||
)
|
||||
|
||||
def test_frontend_live_fetch_covers_all_providers(self):
|
||||
"""_fetchLiveModels no longer skips any provider — all providers return
|
||||
live or fallback models via provider_model_ids() on the backend (#375 upgrade)."""
|
||||
# The old skip list (anthropic, google, gemini) must be gone from the guard
|
||||
skip_guard_pos = UI_JS.find("includes(provider)")
|
||||
if skip_guard_pos != -1:
|
||||
guard_line = UI_JS[max(0,skip_guard_pos-100):skip_guard_pos+50]
|
||||
assert "anthropic" not in guard_line, (
|
||||
"_fetchLiveModels must not skip anthropic — backend now handles it (#375 upgrade)"
|
||||
)
|
||||
|
||||
def test_live_models_endpoint_wired_in_routes(self):
|
||||
"""The /api/models/live path must be handled in handle_get()."""
|
||||
# Find handle_get and check our route appears inside it
|
||||
handle_get_pos = ROUTES_PY.find("def handle_get(")
|
||||
live_route_pos = ROUTES_PY.find('"/api/models/live"')
|
||||
assert handle_get_pos != -1 and live_route_pos != -1
|
||||
assert live_route_pos > handle_get_pos, (
|
||||
"/api/models/live must be inside handle_get() (#375)"
|
||||
)
|
||||
262
tests/test_language_precedence.py
Normal file
262
tests/test_language_precedence.py
Normal file
@@ -0,0 +1,262 @@
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import textwrap
|
||||
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text(encoding="utf-8")
|
||||
BOOT_JS = (REPO_ROOT / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
PANELS_JS = (REPO_ROOT / "static" / "panels.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _run_i18n_case(script_expr: str) -> dict:
|
||||
wrapped_expr = f"(() => ({script_expr}))()"
|
||||
script = textwrap.dedent(
|
||||
f"""
|
||||
const fs = require('fs');
|
||||
const vm = require('vm');
|
||||
const src = fs.readFileSync({json.dumps(str(REPO_ROOT / "static" / "i18n.js"))}, 'utf8');
|
||||
const storage = {{}};
|
||||
const ctx = {{
|
||||
localStorage: {{
|
||||
getItem: (k) => Object.prototype.hasOwnProperty.call(storage, k) ? storage[k] : null,
|
||||
setItem: (k, v) => {{ storage[k] = String(v); }},
|
||||
}},
|
||||
document: {{
|
||||
documentElement: {{ lang: '' }},
|
||||
querySelectorAll: () => [],
|
||||
}},
|
||||
}};
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(src, ctx);
|
||||
const out = vm.runInContext({json.dumps(wrapped_expr)}, ctx);
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
"""
|
||||
)
|
||||
proc = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def _extract_call_arglists(src: str, fn_name: str) -> list[str]:
|
||||
token = f"{fn_name}("
|
||||
out = []
|
||||
search_from = 0
|
||||
|
||||
while True:
|
||||
start = src.find(token, search_from)
|
||||
if start < 0:
|
||||
return out
|
||||
|
||||
i = start + len(token)
|
||||
depth = 1
|
||||
in_single = False
|
||||
in_double = False
|
||||
in_backtick = False
|
||||
escape = False
|
||||
|
||||
while i < len(src):
|
||||
ch = src[i]
|
||||
|
||||
if escape:
|
||||
escape = False
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_single:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "'":
|
||||
in_single = False
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_double:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_double = False
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if in_backtick:
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "`":
|
||||
in_backtick = False
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if ch == "'":
|
||||
in_single = True
|
||||
elif ch == '"':
|
||||
in_double = True
|
||||
elif ch == "`":
|
||||
in_backtick = True
|
||||
elif ch == "(":
|
||||
depth += 1
|
||||
elif ch == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
out.append(src[start + len(token) : i])
|
||||
break
|
||||
i += 1
|
||||
|
||||
search_from = start + len(token)
|
||||
|
||||
|
||||
def _split_top_level_args(arg_src: str) -> list[str]:
|
||||
args = []
|
||||
cur = []
|
||||
paren = 0
|
||||
brace = 0
|
||||
bracket = 0
|
||||
in_single = False
|
||||
in_double = False
|
||||
in_backtick = False
|
||||
escape = False
|
||||
|
||||
for ch in arg_src:
|
||||
if escape:
|
||||
cur.append(ch)
|
||||
escape = False
|
||||
continue
|
||||
|
||||
if in_single:
|
||||
cur.append(ch)
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "'":
|
||||
in_single = False
|
||||
continue
|
||||
|
||||
if in_double:
|
||||
cur.append(ch)
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == '"':
|
||||
in_double = False
|
||||
continue
|
||||
|
||||
if in_backtick:
|
||||
cur.append(ch)
|
||||
if ch == "\\":
|
||||
escape = True
|
||||
elif ch == "`":
|
||||
in_backtick = False
|
||||
continue
|
||||
|
||||
if ch == "'":
|
||||
in_single = True
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == '"':
|
||||
in_double = True
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == "`":
|
||||
in_backtick = True
|
||||
cur.append(ch)
|
||||
continue
|
||||
|
||||
if ch == "(":
|
||||
paren += 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == ")":
|
||||
paren -= 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == "{":
|
||||
brace += 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == "}":
|
||||
brace -= 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == "[":
|
||||
bracket += 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
if ch == "]":
|
||||
bracket -= 1
|
||||
cur.append(ch)
|
||||
continue
|
||||
|
||||
if ch == "," and paren == 0 and brace == 0 and bracket == 0:
|
||||
args.append("".join(cur).strip())
|
||||
cur = []
|
||||
continue
|
||||
|
||||
cur.append(ch)
|
||||
|
||||
if cur:
|
||||
args.append("".join(cur).strip())
|
||||
return args
|
||||
|
||||
|
||||
def _has_precedence_call(src: str, first_arg: str) -> bool:
|
||||
expected_second = {
|
||||
"localStorage.getItem('hermes-lang')",
|
||||
'localStorage.getItem("hermes-lang")',
|
||||
}
|
||||
for arg_src in _extract_call_arglists(src, "resolvePreferredLocale"):
|
||||
args = _split_top_level_args(arg_src)
|
||||
if len(args) < 2:
|
||||
continue
|
||||
first = re.sub(r"\s+", "", args[0])
|
||||
second = re.sub(r"\s+", "", args[1])
|
||||
if first == first_arg and second in expected_second:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def test_i18n_exposes_locale_resolvers():
|
||||
assert "function resolveLocale(" in I18N_JS
|
||||
assert "function resolvePreferredLocale(" in I18N_JS
|
||||
|
||||
|
||||
def test_locale_alias_resolution_and_precedence_logic():
|
||||
result = _run_i18n_case(
|
||||
"""
|
||||
{
|
||||
zhCn: resolveLocale('zh-CN'),
|
||||
zhTw: resolveLocale('zh_TW'),
|
||||
enUs: resolveLocale('EN-us'),
|
||||
esMx: resolveLocale('es-MX'),
|
||||
bad: resolveLocale('xx-YY'),
|
||||
preferred1: resolvePreferredLocale('zh-CN', 'en'),
|
||||
preferred2: resolvePreferredLocale('xx-YY', 'zh-Hant'),
|
||||
preferred3: resolvePreferredLocale('', 'xx-YY'),
|
||||
}
|
||||
"""
|
||||
)
|
||||
assert result["zhCn"] == "zh"
|
||||
assert result["zhTw"] == "zh-Hant"
|
||||
assert result["enUs"] == "en"
|
||||
assert result["esMx"] == "es"
|
||||
assert result["bad"] is None
|
||||
assert result["preferred1"] == "zh"
|
||||
assert result["preferred2"] == "zh-Hant"
|
||||
assert result["preferred3"] == "en"
|
||||
|
||||
|
||||
def test_set_locale_normalizes_alias_and_persists_canonical_key():
|
||||
result = _run_i18n_case(
|
||||
"""
|
||||
{
|
||||
...(setLocale('zh-CN'), {}),
|
||||
saved: localStorage.getItem('hermes-lang'),
|
||||
htmlLang: document.documentElement.lang,
|
||||
}
|
||||
"""
|
||||
)
|
||||
assert result["saved"] == "zh"
|
||||
assert result["htmlLang"] == "zh-CN"
|
||||
|
||||
|
||||
def test_boot_and_settings_panel_use_shared_locale_precedence():
|
||||
assert _has_precedence_call(BOOT_JS, "s.language")
|
||||
assert _has_precedence_call(PANELS_JS, "settings.language")
|
||||
68
tests/test_login_locale.py
Normal file
68
tests/test_login_locale.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
|
||||
|
||||
def get_raw(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return r.read().decode(), r.status
|
||||
|
||||
|
||||
def post(path, body=None):
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(
|
||||
BASE + path, data=data, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
def _current_language():
|
||||
settings, status = get("/api/settings")
|
||||
assert status == 200
|
||||
return settings.get("language") or "en"
|
||||
|
||||
|
||||
def test_login_page_uses_simplified_chinese_for_zh_cn_alias():
|
||||
prev_lang = _current_language()
|
||||
try:
|
||||
saved, status = post("/api/settings", {"language": "zh-CN"})
|
||||
assert status == 200
|
||||
assert saved.get("language") == "zh-CN"
|
||||
html, status2 = get_raw("/login")
|
||||
assert status2 == 200
|
||||
assert 'lang="zh-CN"' in html
|
||||
assert "\u767b\u5f55" in html
|
||||
assert "\u8f93\u5165\u5bc6\u7801\u7ee7\u7eed\u4f7f\u7528" in html
|
||||
finally:
|
||||
restored, restore_status = post("/api/settings", {"language": prev_lang})
|
||||
assert restore_status == 200
|
||||
assert restored.get("language") == prev_lang
|
||||
|
||||
|
||||
def test_login_page_uses_traditional_chinese_for_zh_hant():
|
||||
prev_lang = _current_language()
|
||||
try:
|
||||
saved, status = post("/api/settings", {"language": "zh-Hant"})
|
||||
assert status == 200
|
||||
assert saved.get("language") == "zh-Hant"
|
||||
html, status2 = get_raw("/login")
|
||||
assert status2 == 200
|
||||
assert 'lang="zh-TW"' in html
|
||||
assert "\u8f38\u5165\u5bc6\u78bc\u7e7c\u7e8c\u4f7f\u7528" in html
|
||||
assert "\u5bc6\u78bc\u932f\u8aa4" in html
|
||||
finally:
|
||||
restored, restore_status = post("/api/settings", {"language": prev_lang})
|
||||
assert restore_status == 200
|
||||
assert restored.get("language") == prev_lang
|
||||
216
tests/test_media_inline.py
Normal file
216
tests/test_media_inline.py
Normal file
@@ -0,0 +1,216 @@
|
||||
"""
|
||||
Tests for feat #450: MEDIA: token inline rendering in web UI chat.
|
||||
|
||||
Covers:
|
||||
1. /api/media endpoint: serves local image files by absolute path
|
||||
2. /api/media endpoint: rejects paths outside allowed roots (path traversal)
|
||||
3. /api/media endpoint: 404 for non-existent files
|
||||
4. /api/media endpoint: auth gate when auth is enabled
|
||||
5. renderMd() MEDIA: stash/restore logic (static JS analysis)
|
||||
6. /api/media endpoint: integration test via live server (requires 8788)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from tests._pytest_port import BASE, TEST_STATE_DIR
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent
|
||||
UI_JS = (REPO_ROOT / "static" / "ui.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
# ── Static analysis: renderMd MEDIA stash ────────────────────────────────────
|
||||
|
||||
class TestMediaRenderMdStash(unittest.TestCase):
|
||||
"""Verify the MEDIA: stash/restore logic exists in ui.js."""
|
||||
|
||||
def test_media_stash_defined(self):
|
||||
self.assertIn("media_stash", UI_JS,
|
||||
"media_stash array must be defined in renderMd()")
|
||||
|
||||
def test_media_token_regex(self):
|
||||
self.assertIn("MEDIA:", UI_JS,
|
||||
"MEDIA: token regex must be present in renderMd()")
|
||||
|
||||
def test_media_restore_produces_img_tag(self):
|
||||
self.assertIn("msg-media-img", UI_JS,
|
||||
"restore pass must produce <img class='msg-media-img'>")
|
||||
|
||||
def test_media_restore_produces_download_link(self):
|
||||
self.assertIn("msg-media-link", UI_JS,
|
||||
"restore pass must produce download link for non-image files")
|
||||
|
||||
def test_media_api_url_pattern(self):
|
||||
self.assertIn("api/media?path=", UI_JS,
|
||||
"renderMd must build api/media?path=... URL for local files")
|
||||
|
||||
def test_media_stash_uses_null_byte_token(self):
|
||||
self.assertIn("\\x00D", UI_JS,
|
||||
"MEDIA stash must use null-byte token (\\x00D) to avoid conflicts")
|
||||
|
||||
def test_media_stash_runs_before_fence_stash(self):
|
||||
media_pos = UI_JS.find("media_stash")
|
||||
fence_pos = UI_JS.find("fence_stash")
|
||||
self.assertGreater(fence_pos, media_pos,
|
||||
"media_stash must be defined before fence_stash in renderMd()")
|
||||
|
||||
def test_image_extension_regex_covers_common_types(self):
|
||||
# The JS source has these extensions in a regex like /\.png|jpg|.../i
|
||||
# Check for the extension strings (without the dot, which may be escaped as \.)
|
||||
for ext in ["png", "jpg", "jpeg", "gif", "webp"]:
|
||||
self.assertIn(ext, UI_JS,
|
||||
f"Image extension {ext} must be in the MEDIA img-check regex")
|
||||
|
||||
def test_http_url_media_rendered_as_img(self):
|
||||
# renderMd should treat MEDIA:https://... as an <img>
|
||||
# In the JS source, the regex is /^https?:\/\//i (escaped)
|
||||
self.assertTrue(
|
||||
"https?:" in UI_JS or "http" in UI_JS,
|
||||
"MEDIA: restore must handle HTTPS URLs",
|
||||
)
|
||||
|
||||
def test_zoom_toggle_on_click(self):
|
||||
self.assertIn("msg-media-img--full", UI_JS,
|
||||
"Clicking the image must toggle msg-media-img--full class for zoom")
|
||||
|
||||
|
||||
# ── Static analysis: CSS ──────────────────────────────────────────────────────
|
||||
|
||||
class TestMediaCSS(unittest.TestCase):
|
||||
|
||||
CSS = (REPO_ROOT / "static" / "style.css").read_text(encoding="utf-8")
|
||||
|
||||
def test_msg_media_img_class_defined(self):
|
||||
self.assertIn(".msg-media-img", self.CSS)
|
||||
|
||||
def test_msg_media_img_max_width(self):
|
||||
# Should have a max-width to prevent huge images breaking layout
|
||||
idx = self.CSS.find(".msg-media-img{")
|
||||
self.assertGreater(idx, 0)
|
||||
rule = self.CSS[idx:idx+200]
|
||||
self.assertIn("max-width", rule)
|
||||
|
||||
def test_msg_media_img_full_class_defined(self):
|
||||
self.assertIn(".msg-media-img--full", self.CSS,
|
||||
"Full-size toggle class must exist for zoom-on-click")
|
||||
|
||||
def test_msg_media_link_class_defined(self):
|
||||
self.assertIn(".msg-media-link", self.CSS,
|
||||
"Download link style must be defined for non-image media")
|
||||
|
||||
|
||||
# ── Backend: /api/media endpoint (unit-level, no server needed) ─────────────
|
||||
|
||||
class TestMediaEndpointUnit(unittest.TestCase):
|
||||
"""Test route registration and handler logic via imports."""
|
||||
|
||||
def test_handle_media_function_exists(self):
|
||||
from api import routes
|
||||
self.assertTrue(
|
||||
hasattr(routes, "_handle_media"),
|
||||
"_handle_media must be defined in api/routes.py",
|
||||
)
|
||||
|
||||
def test_api_media_route_registered(self):
|
||||
"""The GET dispatch must include the /api/media path."""
|
||||
routes_src = (REPO_ROOT / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
self.assertIn('"/api/media"', routes_src,
|
||||
'/api/media must be registered in the GET route dispatch')
|
||||
|
||||
def test_allowed_roots_include_tmp(self):
|
||||
"""Handler must allow /tmp so screenshot paths work."""
|
||||
routes_src = (REPO_ROOT / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
self.assertIn('/tmp', routes_src,
|
||||
'/tmp must be in the allowed roots list for /api/media')
|
||||
|
||||
def test_svg_forces_download(self):
|
||||
""".svg must not be served inline (XSS risk)."""
|
||||
routes_src = (REPO_ROOT / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
# SVG should be in _DOWNLOAD_TYPES or explicitly excluded from inline
|
||||
self.assertIn("image/svg+xml", routes_src,
|
||||
"SVG MIME type must be handled (forced download) in _handle_media")
|
||||
|
||||
def test_non_image_forces_download(self):
|
||||
"""Non-image files should be forced to download, not served inline."""
|
||||
routes_src = (REPO_ROOT / "api" / "routes.py").read_text(encoding="utf-8")
|
||||
self.assertIn("_INLINE_IMAGE_TYPES", routes_src,
|
||||
"_INLINE_IMAGE_TYPES whitelist must exist in _handle_media")
|
||||
|
||||
|
||||
# ── Integration tests: live server on TEST_PORT ───────────────────────────────
|
||||
# No collection-time skip guard — conftest.py starts the server via its
|
||||
# autouse session fixture BEFORE tests run. A collection-time check always
|
||||
# sees no server and turns every test into a skip. Instead we assert
|
||||
# reachability inside setUp() so failures are loud errors, not silent skips.
|
||||
|
||||
|
||||
class TestMediaEndpointIntegration(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
try:
|
||||
urllib.request.urlopen(BASE + "/health", timeout=5)
|
||||
except Exception as exc:
|
||||
self.fail(f"Test server at {BASE} is not reachable: {exc}")
|
||||
|
||||
def _get(self, path):
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return r.read(), r.status, r.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.read(), e.code, e.headers
|
||||
|
||||
def test_no_path_returns_400(self):
|
||||
_, status, _ = self._get("/api/media")
|
||||
self.assertEqual(status, 400)
|
||||
|
||||
def test_nonexistent_file_returns_404(self):
|
||||
_, status, _ = self._get("/api/media?path=/tmp/__hermes_nonexistent_12345.png")
|
||||
self.assertEqual(status, 404)
|
||||
|
||||
def test_path_outside_allowed_root_rejected(self):
|
||||
# /etc/passwd is outside allowed roots
|
||||
_, status, _ = self._get("/api/media?path=/etc/passwd")
|
||||
self.assertIn(status, {403, 404})
|
||||
|
||||
def test_valid_png_served_with_image_mime(self):
|
||||
"""Create a 1-pixel PNG in /tmp and verify it's served correctly."""
|
||||
# Minimal valid 1x1 transparent PNG (67 bytes)
|
||||
png_bytes = (
|
||||
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01'
|
||||
b'\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00'
|
||||
b'\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82'
|
||||
)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".png", prefix="hermes_test_", dir="/tmp", delete=False
|
||||
) as f:
|
||||
f.write(png_bytes)
|
||||
tmp_path = f.name
|
||||
try:
|
||||
body, status, headers = self._get(
|
||||
f"/api/media?path={urllib.request.quote(tmp_path)}"
|
||||
)
|
||||
self.assertEqual(status, 200, f"Expected 200, got {status}")
|
||||
ct = headers.get("Content-Type", "")
|
||||
self.assertIn("image/png", ct, f"Expected image/png, got {ct}")
|
||||
self.assertEqual(body, png_bytes)
|
||||
finally:
|
||||
pathlib.Path(tmp_path).unlink(missing_ok=True)
|
||||
|
||||
def test_path_traversal_rejected(self):
|
||||
_, status, _ = self._get(
|
||||
"/api/media?path=" + urllib.request.quote("/tmp/../../etc/passwd")
|
||||
)
|
||||
self.assertIn(status, {403, 404})
|
||||
|
||||
def test_health_check_still_works(self):
|
||||
"""Sanity: server is up and /health works."""
|
||||
body, status, _ = self._get("/health")
|
||||
self.assertEqual(status, 200)
|
||||
d = json.loads(body)
|
||||
self.assertEqual(d["status"], "ok")
|
||||
278
tests/test_mobile_layout.py
Normal file
278
tests/test_mobile_layout.py
Normal file
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
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 sidebar navigation stays available on phones
|
||||
- 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_sidebar_nav_present():
|
||||
"""Sidebar top navigation tabs must be present."""
|
||||
assert 'class="sidebar-nav"' in HTML, \
|
||||
".sidebar-nav missing from index.html"
|
||||
assert ".sidebar-nav{" in CSS or ".sidebar-nav {" in CSS, \
|
||||
".sidebar-nav CSS rule missing from style.css"
|
||||
|
||||
|
||||
def test_mobile_does_not_hide_sidebar_nav():
|
||||
"""Phone breakpoint must keep the sidebar top navigation visible."""
|
||||
mobile_block = re.search(r'@media\(max-width:640px\)\{(.*)\n\s*\}', CSS, re.DOTALL)
|
||||
assert mobile_block, "Missing @media(max-width:640px) block in style.css"
|
||||
assert ".sidebar-nav{display:none" not in mobile_block.group(1).replace(" ", ""), \
|
||||
".sidebar-nav must stay visible on mobile"
|
||||
|
||||
|
||||
def test_mobile_files_button_present():
|
||||
"""Mobile files toggle button (#btnWorkspacePanelToggle.workspace-toggle-btn) must be in HTML and CSS."""
|
||||
assert 'id="btnWorkspacePanelToggle"' in HTML, \
|
||||
"#btnWorkspacePanelToggle missing from index.html"
|
||||
assert "workspace-toggle-btn" in CSS, \
|
||||
".workspace-toggle-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."""
|
||||
# Accept handleWorkspaceClose() (two-step close: file→browse→closed), or the
|
||||
# lower-level functions directly. handleWorkspaceClose is preferred because
|
||||
# it dismisses a file preview first before closing the panel.
|
||||
has_close = (
|
||||
'onclick="handleWorkspaceClose()"' in HTML or
|
||||
'onclick="closeWorkspacePanel()"' in HTML or
|
||||
'onclick="toggleWorkspacePanel()"' in HTML
|
||||
)
|
||||
assert has_close, \
|
||||
"handleWorkspaceClose() or closeWorkspacePanel() 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"
|
||||
|
||||
|
||||
def test_new_conversation_closes_mobile_sidebar():
|
||||
"""New conversation must close the mobile drawer so the chat pane is visible immediately."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
click_line = next((ln for ln in boot_js.splitlines() if "$('btnNewChat').onclick" in ln), "")
|
||||
assert click_line, "btnNewChat onclick handler missing from static/boot.js"
|
||||
assert "closeMobileSidebar" in click_line, \
|
||||
"btnNewChat handler must closeMobileSidebar() after creating the new session"
|
||||
|
||||
shortcut_line = next((ln for ln in boot_js.splitlines() if "e.key==='k'" in ln or "e.key === 'k'" in ln), "")
|
||||
assert shortcut_line, "Cmd/Ctrl+K new chat shortcut missing from static/boot.js"
|
||||
shortcut_block = "\n".join(boot_js.splitlines()[boot_js.splitlines().index(shortcut_line):boot_js.splitlines().index(shortcut_line)+4])
|
||||
assert "closeMobileSidebar" in shortcut_block, \
|
||||
"Cmd/Ctrl+K new chat shortcut must closeMobileSidebar() after creating the new session"
|
||||
|
||||
|
||||
# ── Viewport and scroll safety ────────────────────────────────────────────────
|
||||
|
||||
def test_body_overflow_hidden():
|
||||
"""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_flex_parents_allow_message_scroller_to_shrink():
|
||||
"""The top-level flex containers must opt into min-height:0 so .messages can scroll on mobile.
|
||||
|
||||
Mobile Safari/Chrome can trap scroll when a flex child with overflow:auto sits inside
|
||||
parents whose min-height remains auto. Both .layout and .main need min-height:0.
|
||||
"""
|
||||
assert re.search(r'\.layout\{[^}]*min-height:0', CSS), \
|
||||
".layout must set min-height:0 so the chat column can shrink and scroll"
|
||||
assert re.search(r'\.main\{[^}]*min-height:0', CSS), \
|
||||
".main must set min-height:0 so .messages remains scrollable while busy"
|
||||
|
||||
|
||||
def test_messages_touch_scrolling_hints_present():
|
||||
"""The messages scroller must advertise touch-friendly scrolling behavior.
|
||||
|
||||
On mobile browsers, momentum scrolling and explicit pan-y/overscroll behavior help
|
||||
prevent the chat area from feeling locked while the app body itself stays overflow:hidden.
|
||||
"""
|
||||
assert re.search(r'\.messages\{[^}]*-webkit-overflow-scrolling:\s*touch', CSS), \
|
||||
".messages must enable -webkit-overflow-scrolling:touch for mobile momentum scroll"
|
||||
assert re.search(r'\.messages\{[^}]*touch-action:\s*pan-y', CSS), \
|
||||
".messages must set touch-action:pan-y so vertical swipe gestures scroll the transcript"
|
||||
assert re.search(r'\.messages\{[^}]*overscroll-behavior-y:\s*contain', CSS), \
|
||||
".messages must contain vertical overscroll so the transcript keeps the gesture"
|
||||
|
||||
|
||||
def test_100dvh_viewport_height():
|
||||
"""Layout must use 100dvh (dynamic viewport height) for correct mobile sizing.
|
||||
|
||||
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"
|
||||
|
||||
|
||||
|
||||
# ── Sidebar tabs on mobile ───────────────────────────────────────────────────
|
||||
|
||||
def test_profiles_sidebar_tab_present():
|
||||
"""Sidebar tab strip must include Profiles."""
|
||||
assert 'class="nav-tab" data-panel="profiles"' in HTML, \
|
||||
"Sidebar nav must have a Profiles tab"
|
||||
|
||||
|
||||
def test_mobile_bottom_nav_removed():
|
||||
"""The old fixed mobile bottom nav should not be present anymore."""
|
||||
assert "mobile-bottom-nav" not in HTML, \
|
||||
"mobile-bottom-nav markup should be removed from index.html"
|
||||
assert "mobile-bottom-nav" not in CSS, \
|
||||
"mobile-bottom-nav CSS should be removed from style.css"
|
||||
|
||||
|
||||
# ── Mobile Enter key inserts newline (PR #315, fixes #269) ───────────────────
|
||||
|
||||
def test_mobile_enter_newline_condition_present():
|
||||
"""boot.js keydown handler must detect touch-primary devices via pointer:coarse."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
assert "pointer:coarse" in boot_js, \
|
||||
"boot.js must use pointer:coarse media query for mobile Enter detection"
|
||||
|
||||
|
||||
def test_mobile_enter_newline_uses_match_media():
|
||||
"""boot.js must call matchMedia for pointer detection, not a hardcoded flag."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
assert "matchMedia('(pointer:coarse)')" in boot_js or 'matchMedia("(pointer:coarse)")' in boot_js, \
|
||||
"boot.js must use matchMedia('(pointer:coarse)') for mobile detection"
|
||||
|
||||
|
||||
def test_mobile_enter_newline_only_overrides_enter_default():
|
||||
"""Mobile newline override must only apply when _sendKey is the default 'enter'."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
# The _mobileDefault check must gate on _sendKey==='enter' so ctrl+enter users aren't affected
|
||||
assert "_sendKey===" in boot_js and "'enter'" in boot_js, \
|
||||
"Mobile newline fallback must check window._sendKey==='enter' to avoid overriding user preference"
|
||||
|
||||
|
||||
def test_mobile_enter_does_not_affect_desktop_logic():
|
||||
"""The mobile Enter override must not alter the existing else branch for desktop users."""
|
||||
boot_js = (REPO / "static" / "boot.js").read_text(encoding="utf-8")
|
||||
# The else branch (desktop, sends on Enter without Shift) must still be present
|
||||
assert "if(!e.shiftKey){e.preventDefault();send();" in boot_js, \
|
||||
"Desktop Enter-to-send logic (else branch) must still be present in boot.js"
|
||||
425
tests/test_model_resolver.py
Normal file
425
tests/test_model_resolver.py
Normal file
@@ -0,0 +1,425 @@
|
||||
"""
|
||||
Tests for resolve_model_provider() model routing logic.
|
||||
Verifies that model IDs are correctly resolved to (model, provider, base_url)
|
||||
tuples for different provider configurations.
|
||||
"""
|
||||
import api.config as config
|
||||
|
||||
|
||||
def _resolve_with_config(model_id, provider=None, base_url=None, default=None, custom_providers=None):
|
||||
"""Helper: temporarily set config.cfg model/custom provider sections, call resolve, restore."""
|
||||
old_cfg = dict(config.cfg)
|
||||
model_cfg = {}
|
||||
if provider:
|
||||
model_cfg['provider'] = provider
|
||||
if base_url:
|
||||
model_cfg['base_url'] = base_url
|
||||
if default:
|
||||
model_cfg['default'] = default
|
||||
config.cfg['model'] = model_cfg if model_cfg else {}
|
||||
if custom_providers is not None:
|
||||
config.cfg['custom_providers'] = custom_providers
|
||||
try:
|
||||
return config.resolve_model_provider(model_id)
|
||||
finally:
|
||||
config.cfg.clear()
|
||||
config.cfg.update(old_cfg)
|
||||
|
||||
|
||||
# ── OpenRouter prefix handling ────────────────────────────────────────────
|
||||
|
||||
def test_openrouter_free_keeps_full_path():
|
||||
"""openrouter/free must NOT be stripped to 'free' when provider is openrouter."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'openrouter/free', provider='openrouter',
|
||||
base_url='https://openrouter.ai/api/v1',
|
||||
)
|
||||
assert model == 'openrouter/free', f"Expected 'openrouter/free', got '{model}'"
|
||||
assert provider == 'openrouter'
|
||||
|
||||
|
||||
def test_openrouter_model_with_provider_prefix():
|
||||
"""anthropic/claude-sonnet-4.6 via openrouter keeps full path."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'anthropic/claude-sonnet-4.6', provider='openrouter',
|
||||
base_url='https://openrouter.ai/api/v1',
|
||||
)
|
||||
assert model == 'anthropic/claude-sonnet-4.6'
|
||||
assert provider == 'openrouter'
|
||||
|
||||
|
||||
# ── Direct provider prefix stripping ─────────────────────────────────────
|
||||
|
||||
def test_anthropic_prefix_stripped_for_direct_api():
|
||||
"""anthropic/claude-sonnet-4.6 strips prefix when provider is anthropic."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'anthropic/claude-sonnet-4.6', provider='anthropic',
|
||||
)
|
||||
assert model == 'claude-sonnet-4.6'
|
||||
assert provider == 'anthropic'
|
||||
|
||||
|
||||
def test_openai_prefix_stripped_for_direct_api():
|
||||
"""openai/gpt-5.4-mini strips prefix when provider is openai."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'openai/gpt-5.4-mini', provider='openai',
|
||||
)
|
||||
assert model == 'gpt-5.4-mini'
|
||||
assert provider == 'openai'
|
||||
|
||||
|
||||
# ── Cross-provider routing ───────────────────────────────────────────────
|
||||
|
||||
def test_cross_provider_routes_through_openrouter():
|
||||
"""Picking openai model when config is anthropic routes via openrouter."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'openai/gpt-5.4-mini', provider='anthropic',
|
||||
)
|
||||
assert model == 'openai/gpt-5.4-mini'
|
||||
assert provider == 'openrouter'
|
||||
assert base_url is None # openrouter uses its own endpoint
|
||||
|
||||
|
||||
# ── Bare model names ─────────────────────────────────────────────────────
|
||||
|
||||
def test_bare_model_uses_config_provider():
|
||||
"""A model name without / uses the config provider and base_url."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'gemma-4-26B', provider='custom',
|
||||
base_url='http://192.168.1.160:4000',
|
||||
)
|
||||
assert model == 'gemma-4-26B'
|
||||
assert provider == 'custom'
|
||||
assert base_url == 'http://192.168.1.160:4000'
|
||||
|
||||
|
||||
def test_empty_model_returns_config_defaults():
|
||||
"""Empty model string returns config provider and base_url."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'', provider='anthropic',
|
||||
)
|
||||
assert model == ''
|
||||
assert provider == 'anthropic'
|
||||
|
||||
|
||||
# ── @provider:model hint routing (Issue #138 v2) ────────────────────────
|
||||
|
||||
def test_provider_hint_routes_to_specific_provider():
|
||||
"""@minimax:MiniMax-M2.7 routes to minimax provider directly."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'@minimax:MiniMax-M2.7', provider='anthropic',
|
||||
)
|
||||
assert model == 'MiniMax-M2.7'
|
||||
assert provider == 'minimax'
|
||||
assert base_url is None # resolve_runtime_provider will fill this
|
||||
|
||||
|
||||
def test_provider_hint_zai():
|
||||
"""@zai:GLM-5 routes to zai provider directly."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'@zai:GLM-5', provider='openai',
|
||||
)
|
||||
assert model == 'GLM-5'
|
||||
assert provider == 'zai'
|
||||
|
||||
|
||||
def test_provider_hint_deepseek():
|
||||
"""@deepseek:deepseek-chat routes to deepseek provider."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'@deepseek:deepseek-chat', provider='anthropic',
|
||||
)
|
||||
assert model == 'deepseek-chat'
|
||||
assert provider == 'deepseek'
|
||||
|
||||
|
||||
def test_slash_prefix_non_default_still_routes_openrouter():
|
||||
"""minimax/MiniMax-M2.7 (old format) still routes through openrouter."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'minimax/MiniMax-M2.7', provider='anthropic',
|
||||
)
|
||||
assert model == 'minimax/MiniMax-M2.7'
|
||||
assert provider == 'openrouter'
|
||||
|
||||
|
||||
def test_custom_provider_model_with_slash_routes_to_named_custom_provider():
|
||||
"""Slash-containing custom endpoint model IDs must not be mistaken for OpenRouter models."""
|
||||
model, provider, base_url = _resolve_with_config(
|
||||
'google/gemma-4-26b-a4b',
|
||||
provider='openrouter',
|
||||
base_url='https://openrouter.ai/api/v1',
|
||||
custom_providers=[{
|
||||
'name': 'Local LM Studio',
|
||||
'base_url': 'http://lmstudio.local:1234/v1',
|
||||
'model': 'google/gemma-4-26b-a4b',
|
||||
}],
|
||||
)
|
||||
assert model == 'google/gemma-4-26b-a4b'
|
||||
assert provider == 'custom:local-lm-studio'
|
||||
assert base_url == 'http://lmstudio.local:1234/v1'
|
||||
|
||||
|
||||
# ── get_available_models() @provider: hint behaviour ──────────────────────
|
||||
|
||||
def _available_models_with_provider(provider):
|
||||
"""Helper: temporarily set active_provider in config."""
|
||||
old_cfg = dict(config.cfg)
|
||||
config.cfg['model'] = {'provider': provider}
|
||||
try:
|
||||
return config.get_available_models()
|
||||
finally:
|
||||
config.cfg.clear()
|
||||
config.cfg.update(old_cfg)
|
||||
|
||||
|
||||
def test_non_default_provider_models_use_hint_prefix():
|
||||
"""With anthropic as default, minimax model IDs should use @minimax: prefix."""
|
||||
result = _available_models_with_provider('anthropic')
|
||||
groups = {g['provider']: g['models'] for g in result['groups']}
|
||||
if 'MiniMax' in groups:
|
||||
for m in groups['MiniMax']:
|
||||
assert m['id'].startswith('@minimax:'), (
|
||||
f"Expected @minimax: prefix, got: {m['id']!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_no_duplicate_when_default_model_is_prefixed():
|
||||
"""Issue #147 Bug 2: 'anthropic/claude-opus-4.6' as default_model must not
|
||||
inject a duplicate alongside the existing bare 'claude-opus-4.6' entry in
|
||||
the same provider group."""
|
||||
import api.config as _cfg
|
||||
old_cfg = dict(_cfg.cfg)
|
||||
_cfg.cfg['model'] = {
|
||||
'provider': 'anthropic',
|
||||
'default': 'anthropic/claude-opus-4.6',
|
||||
}
|
||||
try:
|
||||
result = _cfg.get_available_models()
|
||||
norm = lambda mid: mid.split('/', 1)[-1] if '/' in mid else mid
|
||||
# Check each group individually: no group should have two entries that
|
||||
# normalize to the same bare model name
|
||||
for g in result['groups']:
|
||||
bare_ids = [norm(m['id']) for m in g['models']]
|
||||
duplicates = [mid for mid in set(bare_ids) if bare_ids.count(mid) > 1]
|
||||
assert not duplicates, (
|
||||
f"Provider group '{g['provider']}' has duplicate models after normalization: "
|
||||
f"{duplicates}\nFull group: {[m['id'] for m in g['models']]}"
|
||||
)
|
||||
finally:
|
||||
_cfg.cfg.clear()
|
||||
_cfg.cfg.update(old_cfg)
|
||||
|
||||
|
||||
def test_default_provider_models_not_prefixed():
|
||||
"""The active provider's models remain bare (no @prefix added)."""
|
||||
import api.config as _cfg
|
||||
raw_anthropic_ids = {m['id'] for m in _cfg._PROVIDER_MODELS.get('anthropic', [])}
|
||||
result = _available_models_with_provider('anthropic')
|
||||
groups = {g['provider']: g['models'] for g in result['groups']}
|
||||
if 'Anthropic' in groups:
|
||||
returned_ids = {m['id'] for m in groups['Anthropic']}
|
||||
for bare_id in raw_anthropic_ids:
|
||||
assert bare_id in returned_ids, (
|
||||
f"_PROVIDER_MODELS entry '{bare_id}' is missing from the Anthropic group"
|
||||
)
|
||||
|
||||
|
||||
# ── get_available_models(): phantom "Custom" group regression ─────────────
|
||||
#
|
||||
# When the user has model.provider set to a real provider (e.g. openai-codex)
|
||||
# AND a model.base_url set, hermes_cli reports the 'custom' pseudo-provider as
|
||||
# authenticated. The WebUI picker must NOT build a separate "Custom" group in
|
||||
# that case — the base_url belongs to the active provider.
|
||||
|
||||
def _available_models_with_full_cfg(provider, default, base_url):
|
||||
"""Helper: set model.provider, model.default, model.base_url at once.
|
||||
|
||||
Clears model-override env vars (HERMES_MODEL, OPENAI_MODEL, LLM_MODEL)
|
||||
during the call so the real hermes profile environment doesn't leak into
|
||||
the test and override the fixture's default model.
|
||||
"""
|
||||
import os
|
||||
import api.config as _cfg
|
||||
old_cfg = dict(_cfg.cfg)
|
||||
_cfg.cfg['model'] = {
|
||||
'provider': provider,
|
||||
'default': default,
|
||||
'base_url': base_url,
|
||||
}
|
||||
# Clear model-override env vars to prevent the real profile from leaking in
|
||||
_model_env_keys = ('HERMES_MODEL', 'OPENAI_MODEL', 'LLM_MODEL')
|
||||
_saved_env = {k: os.environ.pop(k, None) for k in _model_env_keys}
|
||||
try:
|
||||
return _cfg.get_available_models()
|
||||
finally:
|
||||
_cfg.cfg.clear()
|
||||
_cfg.cfg.update(old_cfg)
|
||||
for k, v in _saved_env.items():
|
||||
if v is not None:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_no_phantom_custom_group_when_active_provider_is_set(monkeypatch):
|
||||
"""Issue: with provider=openai-codex + base_url set, gpt-5.4 was landing
|
||||
under a phantom "Custom" group instead of the "OpenAI Codex" group."""
|
||||
import sys, types
|
||||
|
||||
# Force hermes_cli to report both the real provider and the phantom
|
||||
# 'custom' as authenticated, simulating what list_available_providers()
|
||||
# returns when base_url is configured.
|
||||
fake_mod = types.ModuleType('hermes_cli.models')
|
||||
fake_mod.list_available_providers = lambda: [
|
||||
{'id': 'openai-codex', 'authenticated': True},
|
||||
{'id': 'custom', 'authenticated': True},
|
||||
]
|
||||
fake_auth = types.ModuleType('hermes_cli.auth')
|
||||
fake_auth.get_auth_status = lambda pid: {'key_source': 'env'}
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.models', fake_mod)
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.auth', fake_auth)
|
||||
|
||||
result = _available_models_with_full_cfg(
|
||||
provider='openai-codex',
|
||||
default='gpt-5.4',
|
||||
base_url='https://chatgpt.com/backend-api/codex',
|
||||
)
|
||||
group_names = [g['provider'] for g in result['groups']]
|
||||
assert 'Custom' not in group_names, (
|
||||
f"Phantom 'Custom' group present; full groups: {group_names}"
|
||||
)
|
||||
|
||||
|
||||
def test_default_model_lands_under_active_provider_group(monkeypatch):
|
||||
"""The configured default_model must appear under the active provider's
|
||||
display group, even when the model isn't in _PROVIDER_MODELS[provider]
|
||||
AND the active provider isn't the alphabetical first detected provider.
|
||||
|
||||
Regression guard for a hyphen-vs-space bug in the "ensure default_model
|
||||
appears" post-pass: the substring check `active_provider.lower() in
|
||||
g.get('provider', '').lower()` was failing for 'openai-codex' vs
|
||||
display name 'OpenAI Codex' (hyphen vs. space), silently falling back
|
||||
to groups[0] — which, when another provider sorted earlier
|
||||
alphabetically (e.g. 'anthropic'), placed gpt-5.4 in the WRONG group.
|
||||
"""
|
||||
import sys, types
|
||||
fake_mod = types.ModuleType('hermes_cli.models')
|
||||
fake_mod.list_available_providers = lambda: [
|
||||
{'id': 'anthropic', 'authenticated': True}, # sorts before openai-codex
|
||||
{'id': 'openai-codex', 'authenticated': True},
|
||||
{'id': 'custom', 'authenticated': True},
|
||||
]
|
||||
fake_auth = types.ModuleType('hermes_cli.auth')
|
||||
fake_auth.get_auth_status = lambda pid: {'key_source': 'env'}
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.models', fake_mod)
|
||||
monkeypatch.setitem(sys.modules, 'hermes_cli.auth', fake_auth)
|
||||
|
||||
result = _available_models_with_full_cfg(
|
||||
provider='openai-codex',
|
||||
default='gpt-5.4',
|
||||
base_url='https://chatgpt.com/backend-api/codex',
|
||||
)
|
||||
groups = {g['provider']: [m['id'] for m in g['models']] for g in result['groups']}
|
||||
assert 'OpenAI Codex' in groups, f"OpenAI Codex group missing: {list(groups)}"
|
||||
assert 'gpt-5.4' in groups['OpenAI Codex'], (
|
||||
f"gpt-5.4 not in OpenAI Codex group; contents: {groups['OpenAI Codex']}"
|
||||
)
|
||||
# And crucially, it must NOT have landed in the alphabetically-first
|
||||
# group (Anthropic) via the fallback path.
|
||||
assert 'gpt-5.4' not in groups.get('Anthropic', []), (
|
||||
f"gpt-5.4 leaked into Anthropic group via fallback: {groups.get('Anthropic')}"
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
)
|
||||
# Fix #433: provider prefix is now stripped for custom endpoints so stale
|
||||
# prefixed model IDs from previous sessions do not break custom endpoint routing.
|
||||
assert model == 'gemma-4-26b-a4b', (
|
||||
"Model name prefix should be stripped for custom base_url endpoint, 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)
|
||||
)
|
||||
354
tests/test_onboarding_existing_config.py
Normal file
354
tests/test_onboarding_existing_config.py
Normal file
@@ -0,0 +1,354 @@
|
||||
"""Tests for fix: onboarding wizard must not fire when Hermes is already configured.
|
||||
|
||||
Issue #420 — existing Hermes users (config.yaml present + chat_ready) were
|
||||
shown the first-run wizard because the only gate was settings.onboarding_completed.
|
||||
|
||||
Covers:
|
||||
(a) config.yaml present + chat_ready=True → completed=True (no wizard)
|
||||
(b) no config.yaml → completed=False (wizard fires)
|
||||
(c) apply_onboarding_setup refuses to overwrite an existing config without
|
||||
confirm_overwrite=True
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
# Skip tests that call apply_onboarding_setup → _save_yaml_config when PyYAML is missing
|
||||
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")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit tests — no live server needed, test logic directly via imports
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_status(*, config_exists: bool, chat_ready: bool, onboarding_done: bool = False):
|
||||
"""Call get_onboarding_status() with a controlled filesystem + settings."""
|
||||
import importlib
|
||||
|
||||
# Import fresh copies each call so module-level state doesn't bleed across
|
||||
import api.onboarding as mod
|
||||
|
||||
fake_config_path = pathlib.Path("/tmp/_test_config.yaml")
|
||||
|
||||
settings = {"onboarding_completed": onboarding_done}
|
||||
|
||||
# Build a minimal runtime dict that get_onboarding_status() would produce
|
||||
# from _status_from_runtime. We only need the keys the gate checks.
|
||||
runtime = {
|
||||
"chat_ready": chat_ready,
|
||||
"provider_configured": chat_ready,
|
||||
"provider_ready": chat_ready,
|
||||
"setup_state": "ready" if chat_ready else "needs_provider",
|
||||
"provider_note": "test note",
|
||||
"current_provider": "openrouter" if chat_ready else None,
|
||||
"current_model": "anthropic/claude-sonnet-4.6" if chat_ready else None,
|
||||
"current_base_url": None,
|
||||
"env_path": "/tmp/.hermes_test/.env",
|
||||
}
|
||||
|
||||
with (
|
||||
mock.patch.object(mod, "load_settings", return_value=settings),
|
||||
mock.patch.object(mod, "get_config", return_value={}),
|
||||
mock.patch.object(
|
||||
mod,
|
||||
"verify_hermes_imports",
|
||||
return_value=(chat_ready, [], {}),
|
||||
),
|
||||
mock.patch.object(mod, "_status_from_runtime", return_value=runtime),
|
||||
mock.patch.object(mod, "load_workspaces", return_value=[]),
|
||||
mock.patch.object(mod, "get_last_workspace", return_value=None),
|
||||
mock.patch.object(mod, "get_available_models", return_value=[]),
|
||||
mock.patch.object(mod, "_get_config_path", return_value=fake_config_path),
|
||||
mock.patch.object(pathlib.Path, "exists") as mock_exists,
|
||||
):
|
||||
# Make Path(_get_config_path()).exists() return config_exists
|
||||
mock_exists.return_value = config_exists
|
||||
result = mod.get_onboarding_status()
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class TestOnboardingGate:
|
||||
def test_config_exists_and_chat_ready_returns_completed_true(self):
|
||||
"""Primary fix: existing valid config → wizard must NOT fire."""
|
||||
result = _make_status(config_exists=True, chat_ready=True)
|
||||
assert result["completed"] is True, (
|
||||
"Wizard fired for existing Hermes user! "
|
||||
"config.yaml + chat_ready must auto-complete onboarding."
|
||||
)
|
||||
|
||||
def test_no_config_returns_completed_false(self):
|
||||
"""Fresh install with no config → wizard should fire."""
|
||||
result = _make_status(config_exists=False, chat_ready=False)
|
||||
assert result["completed"] is False, (
|
||||
"Fresh install must show the wizard (completed should be False)."
|
||||
)
|
||||
|
||||
def test_config_exists_but_not_chat_ready_still_shows_wizard(self):
|
||||
"""Broken/incomplete config (config.yaml exists but chat_ready=False) →
|
||||
still show wizard so the user can fix it."""
|
||||
result = _make_status(config_exists=True, chat_ready=False)
|
||||
# Should NOT be auto-completed — config is present but broken
|
||||
assert result["completed"] is False, (
|
||||
"Broken config (chat_ready=False) must still show the wizard."
|
||||
)
|
||||
|
||||
def test_onboarding_done_flag_always_respected(self):
|
||||
"""If user already completed onboarding in settings, never show wizard."""
|
||||
result = _make_status(config_exists=False, chat_ready=False, onboarding_done=True)
|
||||
assert result["completed"] is True
|
||||
|
||||
def test_config_exists_always_exposed_in_system(self):
|
||||
"""config_exists must still appear in the response system block."""
|
||||
result = _make_status(config_exists=True, chat_ready=True)
|
||||
assert "config_exists" in result["system"]
|
||||
assert result["system"]["config_exists"] is True
|
||||
|
||||
|
||||
class TestApplyOnboardingSetupGuard:
|
||||
"""Fix #2: apply_onboarding_setup must not silently overwrite config.yaml."""
|
||||
|
||||
def _call_setup(self, body: dict, config_yaml_exists: bool):
|
||||
import api.onboarding as mod
|
||||
|
||||
fake_config_path = pathlib.Path("/tmp/_test_config.yaml")
|
||||
|
||||
with (
|
||||
mock.patch.object(mod, "_get_config_path", return_value=fake_config_path),
|
||||
mock.patch.object(pathlib.Path, "exists", return_value=config_yaml_exists),
|
||||
):
|
||||
return mod.apply_onboarding_setup(body)
|
||||
|
||||
def test_setup_blocked_when_config_exists_without_confirm(self):
|
||||
"""Must return an error dict (not raise) if config.yaml exists and no confirm_overwrite."""
|
||||
result = self._call_setup(
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "test-key",
|
||||
},
|
||||
config_yaml_exists=True,
|
||||
)
|
||||
assert isinstance(result, dict), "Expected a dict response, not an exception"
|
||||
assert result.get("error") == "config_exists", (
|
||||
f"Expected error='config_exists', got: {result}"
|
||||
)
|
||||
assert result.get("requires_confirm") is True
|
||||
|
||||
@_needs_yaml
|
||||
def test_setup_allowed_with_confirm_overwrite(self):
|
||||
"""With confirm_overwrite=True, setup may proceed (will hit real logic)."""
|
||||
import api.onboarding as mod
|
||||
|
||||
fake_config_path = pathlib.Path("/tmp/_test_config_confirm.yaml")
|
||||
fake_config_path.unlink(missing_ok=True) # start clean
|
||||
try:
|
||||
# Without patching Path.exists, use a non-existent path so it won't block
|
||||
result = mod.apply_onboarding_setup(
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "test-key-confirm",
|
||||
"confirm_overwrite": True,
|
||||
}
|
||||
)
|
||||
# Should NOT return config_exists error
|
||||
if isinstance(result, dict):
|
||||
assert result.get("error") != "config_exists", (
|
||||
"confirm_overwrite=True should bypass the config-exists guard."
|
||||
)
|
||||
finally:
|
||||
fake_config_path.unlink(missing_ok=True)
|
||||
|
||||
@_needs_yaml
|
||||
def test_setup_allowed_when_no_config_exists(self):
|
||||
"""Fresh install: no config.yaml → setup proceeds normally (no blocking error)."""
|
||||
import api.onboarding as mod
|
||||
|
||||
fake_config_path = pathlib.Path("/tmp/_test_config_fresh.yaml")
|
||||
fake_config_path.unlink(missing_ok=True)
|
||||
try:
|
||||
with mock.patch.object(mod, "_get_config_path", return_value=fake_config_path):
|
||||
result = mod.apply_onboarding_setup(
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "test-key-fresh",
|
||||
}
|
||||
)
|
||||
if isinstance(result, dict):
|
||||
assert result.get("error") != "config_exists"
|
||||
finally:
|
||||
fake_config_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration tests — require the live test server on port 8788
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def _http_get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
|
||||
|
||||
def _http_post(path, body=None):
|
||||
req = urllib.request.Request(
|
||||
BASE + path,
|
||||
data=json.dumps(body or {}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
def _server_hermes_home() -> pathlib.Path:
|
||||
data, _ = _http_get("/api/onboarding/status")
|
||||
env_path = data.get("system", {}).get("env_path", "")
|
||||
if env_path:
|
||||
return pathlib.Path(env_path).parent
|
||||
return pathlib.Path(os.environ.get("HERMES_WEBUI_TEST_STATE_DIR", str(pathlib.Path.home() / ".hermes" / "webui-mvp-test")))
|
||||
|
||||
|
||||
def _server_reachable() -> bool:
|
||||
try:
|
||||
_http_get("/health")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# No collection-time skip guard — conftest.py starts the server via its
|
||||
# autouse session fixture BEFORE tests run. A collection-time check always
|
||||
# sees no server and turns every test into a skip. Server reachability is
|
||||
# asserted inside the _require_server fixture instead so failures are loud.
|
||||
|
||||
|
||||
class TestOnboardingGateIntegration:
|
||||
"""Live-server integration tests for the onboarding gate fix."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _require_server(self):
|
||||
"""Assert server is reachable at test runtime (not collection time)."""
|
||||
if not _server_reachable():
|
||||
pytest.fail(f"Test server at {BASE} is not reachable")
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean(self):
|
||||
hermes_home = _server_hermes_home()
|
||||
for rel in ("config.yaml", ".env"):
|
||||
(hermes_home / rel).unlink(missing_ok=True)
|
||||
yield
|
||||
for rel in ("config.yaml", ".env"):
|
||||
(hermes_home / rel).unlink(missing_ok=True)
|
||||
# Force the server to reload its in-memory config after file deletion.
|
||||
# apply_onboarding_setup() calls reload_config() which caches provider
|
||||
# state in the server process. Deleting files on disk does not clear
|
||||
# that cache — the next test would see provider_configured=True.
|
||||
# GET /api/personalities always calls reload_config(), giving us a
|
||||
# cheap way to flush the cache without a server restart.
|
||||
try:
|
||||
_http_get("/api/personalities")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def test_no_config_wizard_fires(self):
|
||||
"""No config.yaml → completed=False."""
|
||||
data, status = _http_get("/api/onboarding/status")
|
||||
assert status == 200
|
||||
assert data["completed"] is False
|
||||
|
||||
@_needs_yaml
|
||||
def test_existing_config_and_chat_ready_skips_wizard(self):
|
||||
"""Write a valid config.yaml + .env → completed must be True."""
|
||||
import yaml
|
||||
|
||||
hermes_home = _server_hermes_home()
|
||||
# Write a real config.yaml
|
||||
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
|
||||
(hermes_home / "config.yaml").write_text(
|
||||
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
|
||||
)
|
||||
# Write a fake API key so provider_ready (and thus chat_ready) fires
|
||||
# — but only when hermes_cli imports are available
|
||||
data, _ = _http_get("/api/onboarding/status")
|
||||
if data["system"]["hermes_found"] and data["system"]["imports_ok"]:
|
||||
(hermes_home / ".env").write_text(
|
||||
"OPENROUTER_API_KEY=test-existing-key\n", encoding="utf-8"
|
||||
)
|
||||
data, status = _http_get("/api/onboarding/status")
|
||||
assert status == 200
|
||||
assert data["completed"] is True, (
|
||||
"Existing config + chat_ready must auto-complete onboarding."
|
||||
)
|
||||
else:
|
||||
# Agent not installed: chat_ready is always False, so wizard still
|
||||
# fires — that is the correct behaviour (can't verify readiness).
|
||||
assert data["completed"] is False
|
||||
|
||||
@_needs_yaml
|
||||
def test_setup_blocked_for_existing_config(self):
|
||||
"""POST /api/onboarding/setup must return config_exists error if config.yaml exists."""
|
||||
import yaml
|
||||
|
||||
hermes_home = _server_hermes_home()
|
||||
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
|
||||
(hermes_home / "config.yaml").write_text(
|
||||
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
|
||||
)
|
||||
|
||||
data, status = _http_post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "test-key",
|
||||
},
|
||||
)
|
||||
assert status == 200
|
||||
assert data.get("error") == "config_exists", (
|
||||
f"Expected config_exists guard. Got: {data}"
|
||||
)
|
||||
assert data.get("requires_confirm") is True
|
||||
|
||||
@_needs_yaml
|
||||
def test_setup_allowed_with_confirm_overwrite(self):
|
||||
"""POST /api/onboarding/setup with confirm_overwrite=True succeeds."""
|
||||
import yaml
|
||||
|
||||
hermes_home = _server_hermes_home()
|
||||
cfg = {"model": {"provider": "openrouter", "default": "anthropic/claude-sonnet-4.6"}}
|
||||
(hermes_home / "config.yaml").write_text(
|
||||
yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8"
|
||||
)
|
||||
|
||||
data, status = _http_post(
|
||||
"/api/onboarding/setup",
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"model": "anthropic/claude-sonnet-4.6",
|
||||
"api_key": "test-key",
|
||||
"confirm_overwrite": True,
|
||||
},
|
||||
)
|
||||
assert status == 200
|
||||
assert data.get("error") != "config_exists", (
|
||||
"confirm_overwrite=True must bypass the guard."
|
||||
)
|
||||
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
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
# 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()
|
||||
184
tests/test_onboarding_network.py
Normal file
184
tests/test_onboarding_network.py
Normal file
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Tests: onboarding /api/onboarding/setup network restriction logic (issue #390).
|
||||
|
||||
Covers:
|
||||
1. Request from 127.0.0.1 (loopback) is allowed without auth
|
||||
2. Request from RFC-1918 private IP (172.x, 192.168.x, 10.x) is allowed without auth
|
||||
3. Request from public IP is blocked without auth → 403
|
||||
4. X-Forwarded-For loopback IP is trusted → allowed
|
||||
5. X-Forwarded-For private IP is trusted → allowed
|
||||
6. X-Forwarded-For public IP → still blocked
|
||||
7. X-Real-IP loopback → allowed
|
||||
8. HERMES_WEBUI_ONBOARDING_OPEN=1 bypasses the check entirely
|
||||
9. Auth enabled → check skipped, any IP allowed
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest.mock
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import pytest
|
||||
|
||||
REPO = pathlib.Path(__file__).parent.parent
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unit tests — directly test the IP-resolution + guard logic in routes.py
|
||||
# without needing a live server. We replicate the logic to keep tests fast
|
||||
# and independent of server startup.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _is_local_from_handler(
|
||||
raw_ip: str,
|
||||
xff: str = "",
|
||||
xri: str = "",
|
||||
auth_enabled: bool = False,
|
||||
open_env: bool = False,
|
||||
) -> bool | str:
|
||||
"""
|
||||
Mirror of the onboarding IP check in api/routes.py.
|
||||
Returns True if the request would be allowed, False if blocked,
|
||||
or the error message string if blocked.
|
||||
"""
|
||||
import ipaddress
|
||||
|
||||
if auth_enabled or open_env:
|
||||
return True
|
||||
|
||||
_xff = xff.split(",")[0].strip() if xff else ""
|
||||
_xri = xri.strip()
|
||||
_ip_str = _xff or _xri or raw_ip
|
||||
try:
|
||||
addr = ipaddress.ip_address(_ip_str)
|
||||
is_local = addr.is_loopback or addr.is_private
|
||||
except ValueError:
|
||||
is_local = False
|
||||
|
||||
return is_local
|
||||
|
||||
|
||||
class TestOnboardingIPLogic:
|
||||
"""Unit tests for the IP-resolution logic (no live server needed)."""
|
||||
|
||||
def test_loopback_allowed(self):
|
||||
assert _is_local_from_handler("127.0.0.1") is True
|
||||
|
||||
def test_ipv6_loopback_allowed(self):
|
||||
assert _is_local_from_handler("::1") is True
|
||||
|
||||
def test_private_172_allowed(self):
|
||||
"""Docker bridge addresses (172.17.x.x) must be allowed."""
|
||||
assert _is_local_from_handler("172.17.0.1") is True
|
||||
|
||||
def test_private_192168_allowed(self):
|
||||
assert _is_local_from_handler("192.168.1.100") is True
|
||||
|
||||
def test_private_10_allowed(self):
|
||||
assert _is_local_from_handler("10.0.0.5") is True
|
||||
|
||||
def test_public_ip_blocked(self):
|
||||
assert _is_local_from_handler("8.8.8.8") is False
|
||||
|
||||
def test_xff_loopback_trusted(self):
|
||||
"""Reverse proxy sets X-Forwarded-For to 127.0.0.1 — should be allowed."""
|
||||
assert _is_local_from_handler("172.20.0.1", xff="127.0.0.1") is True
|
||||
|
||||
def test_xff_private_trusted(self):
|
||||
"""Reverse proxy sets X-Forwarded-For to LAN IP — should be allowed."""
|
||||
assert _is_local_from_handler("172.20.0.1", xff="192.168.1.50") is True
|
||||
|
||||
def test_xff_public_blocked(self):
|
||||
"""Public IP in X-Forwarded-For should still be blocked."""
|
||||
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8") is False
|
||||
|
||||
def test_xff_first_entry_used(self):
|
||||
"""X-Forwarded-For may have multiple IPs; only the first (client) is used."""
|
||||
# First entry is private → allowed
|
||||
assert _is_local_from_handler("172.20.0.1", xff="10.0.0.1, 172.20.0.1") is True
|
||||
# First entry is public → blocked
|
||||
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8, 172.20.0.1") is False
|
||||
|
||||
def test_xreal_ip_loopback_trusted(self):
|
||||
"""X-Real-IP loopback → allowed."""
|
||||
assert _is_local_from_handler("172.20.0.1", xri="127.0.0.1") is True
|
||||
|
||||
def test_xreal_ip_private_trusted(self):
|
||||
assert _is_local_from_handler("172.20.0.1", xri="10.1.2.3") is True
|
||||
|
||||
def test_xff_takes_priority_over_xri(self):
|
||||
"""X-Forwarded-For wins over X-Real-IP when both present."""
|
||||
# XFF says public, XRI says local → blocked (XFF takes priority)
|
||||
assert _is_local_from_handler("172.20.0.1", xff="8.8.8.8", xri="127.0.0.1") is False
|
||||
|
||||
def test_open_env_bypasses_check(self):
|
||||
"""HERMES_WEBUI_ONBOARDING_OPEN=1 allows any IP."""
|
||||
assert _is_local_from_handler("8.8.8.8", open_env=True) is True
|
||||
|
||||
def test_auth_enabled_bypasses_check(self):
|
||||
"""When auth is enabled, IP check is skipped entirely."""
|
||||
assert _is_local_from_handler("8.8.8.8", auth_enabled=True) is True
|
||||
|
||||
def test_invalid_ip_blocked(self):
|
||||
"""Malformed IP in header → treated as non-local → blocked."""
|
||||
assert _is_local_from_handler("not-an-ip") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration tests — hit the live test server at test server port
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.integration
|
||||
class TestOnboardingSetupEndpoint:
|
||||
"""
|
||||
Integration tests for /api/onboarding/setup.
|
||||
These require the test server running on test server port.
|
||||
"""
|
||||
|
||||
def _post(self, path: str, data: dict, headers: dict | None = None) -> tuple[int, dict]:
|
||||
payload = json.dumps(data).encode()
|
||||
req = urllib.request.Request(
|
||||
BASE + path,
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json", **(headers or {})},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return r.status, json.loads(r.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read())
|
||||
|
||||
def test_loopback_request_allowed(self):
|
||||
"""
|
||||
Requests from 127.0.0.1 (which is what the test server sees) should
|
||||
pass the IP check. We confirm no 403 is returned.
|
||||
"""
|
||||
# The test server runs on 127.0.0.1:{TEST_PORT} so client_address[0] is 127.0.0.1.
|
||||
# A valid setup payload with a mock provider should not be rejected for IP reasons.
|
||||
# We patch apply_onboarding_setup to avoid actually writing any config.
|
||||
import unittest.mock
|
||||
with unittest.mock.patch("api.onboarding.apply_onboarding_setup", return_value={"ok": True}):
|
||||
status, body = self._post(
|
||||
"/api/onboarding/setup",
|
||||
{"provider": "anthropic", "model": "claude-sonnet-4.6", "api_key": "test-key"},
|
||||
)
|
||||
# Should not be 403 (IP blocked). May be 200 or another error from apply logic.
|
||||
assert status != 403, f"Got 403 — IP check incorrectly blocked loopback. Body: {body}"
|
||||
|
||||
def test_xff_loopback_header_respected(self):
|
||||
"""
|
||||
Simulated reverse proxy: raw TCP is 127.0.0.1 but X-Forwarded-For is also
|
||||
127.0.0.1. Should be allowed.
|
||||
"""
|
||||
import unittest.mock
|
||||
with unittest.mock.patch("api.onboarding.apply_onboarding_setup", return_value={"ok": True}):
|
||||
status, body = self._post(
|
||||
"/api/onboarding/setup",
|
||||
{"provider": "anthropic", "model": "claude-sonnet-4.6", "api_key": "test-key"},
|
||||
headers={"X-Forwarded-For": "127.0.0.1"},
|
||||
)
|
||||
assert status != 403, f"Got 403 with XFF=127.0.0.1. Body: {body}"
|
||||
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
|
||||
121
tests/test_opencode_providers.py
Normal file
121
tests/test_opencode_providers.py
Normal file
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
Tests for OpenCode Zen and OpenCode Go provider support.
|
||||
Verifies provider registration in display/model catalogs and
|
||||
env-var fallback detection.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
import api.config as config
|
||||
|
||||
|
||||
# ── Provider registration ─────────────────────────────────────────────
|
||||
|
||||
def test_opencode_zen_in_provider_display():
|
||||
assert "opencode-zen" in config._PROVIDER_DISPLAY
|
||||
assert config._PROVIDER_DISPLAY["opencode-zen"] == "OpenCode Zen"
|
||||
|
||||
|
||||
def test_opencode_go_in_provider_display():
|
||||
assert "opencode-go" in config._PROVIDER_DISPLAY
|
||||
assert config._PROVIDER_DISPLAY["opencode-go"] == "OpenCode Go"
|
||||
|
||||
|
||||
def test_opencode_zen_in_provider_models():
|
||||
assert "opencode-zen" in config._PROVIDER_MODELS
|
||||
ids = [m["id"] for m in config._PROVIDER_MODELS["opencode-zen"]]
|
||||
assert "claude-opus-4-6" in ids
|
||||
assert "gpt-5.4-pro" in ids
|
||||
assert "glm-5.1" in ids
|
||||
|
||||
|
||||
def test_opencode_go_in_provider_models():
|
||||
assert "opencode-go" in config._PROVIDER_MODELS
|
||||
ids = [m["id"] for m in config._PROVIDER_MODELS["opencode-go"]]
|
||||
assert "glm-5.1" in ids
|
||||
assert "glm-5" in ids
|
||||
assert "mimo-v2-pro" in ids
|
||||
|
||||
|
||||
# ── Env-var fallback detection ────────────────────────────────────────
|
||||
|
||||
def _models_with_env_key(monkeypatch, env_var, expected_provider_display):
|
||||
"""Helper: fake hermes_cli unavailable, set an env var, check detection."""
|
||||
# Force the env-var fallback path by making hermes_cli import fail
|
||||
fake_mod = types.ModuleType("hermes_cli.models")
|
||||
fake_mod.list_available_providers = None # will raise on call
|
||||
monkeypatch.setitem(sys.modules, "hermes_cli.models", fake_mod)
|
||||
monkeypatch.delattr(fake_mod, "list_available_providers")
|
||||
|
||||
old_cfg = dict(config.cfg)
|
||||
config.cfg["model"] = {}
|
||||
config.cfg.pop("custom_providers", None)
|
||||
monkeypatch.setenv(env_var, "test-key")
|
||||
try:
|
||||
result = config.get_available_models()
|
||||
providers = [g["provider"] for g in result["groups"]]
|
||||
assert expected_provider_display in providers, (
|
||||
f"Expected {expected_provider_display} in {providers}"
|
||||
)
|
||||
finally:
|
||||
config.cfg.clear()
|
||||
config.cfg.update(old_cfg)
|
||||
|
||||
|
||||
def test_opencode_zen_detected_via_env_key(monkeypatch):
|
||||
_models_with_env_key(monkeypatch, "OPENCODE_ZEN_API_KEY", "OpenCode Zen")
|
||||
|
||||
|
||||
def test_opencode_go_detected_via_env_key(monkeypatch):
|
||||
_models_with_env_key(monkeypatch, "OPENCODE_GO_API_KEY", "OpenCode Go")
|
||||
|
||||
|
||||
def test_openai_codex_model_catalog_includes_gpt54():
|
||||
"""openai-codex catalog must include gpt-5.4 and the standard Codex lineup."""
|
||||
assert "openai-codex" in config._PROVIDER_MODELS
|
||||
ids = [m["id"] for m in config._PROVIDER_MODELS["openai-codex"]]
|
||||
assert "gpt-5.4" in ids, f"gpt-5.4 missing from openai-codex catalog: {ids}"
|
||||
assert "gpt-5.4-mini" in ids, f"gpt-5.4-mini missing from openai-codex catalog: {ids}"
|
||||
assert "gpt-5.3-codex" in ids, f"gpt-5.3-codex missing from openai-codex catalog: {ids}"
|
||||
assert "gpt-5.2-codex" in ids, f"gpt-5.2-codex missing from openai-codex catalog: {ids}"
|
||||
|
||||
|
||||
def test_openai_codex_display_name():
|
||||
"""openai-codex must have a human-readable display name."""
|
||||
assert "openai-codex" in config._PROVIDER_DISPLAY
|
||||
assert config._PROVIDER_DISPLAY["openai-codex"] == "OpenAI Codex"
|
||||
|
||||
|
||||
def test_live_models_handler_delegates_to_provider_model_ids():
|
||||
"""_handle_live_models must delegate to the agent's provider_model_ids()
|
||||
rather than maintain its own per-provider fetch logic.
|
||||
"""
|
||||
import pathlib
|
||||
routes_src = (pathlib.Path(__file__).parent.parent / "api" / "routes.py").read_text()
|
||||
assert "provider_model_ids" in routes_src, (
|
||||
"_handle_live_models must call hermes_cli.models.provider_model_ids() "
|
||||
"to delegate all provider-specific live-fetch logic to the agent"
|
||||
)
|
||||
# The old per-provider base_url hardcoding should be gone
|
||||
assert "https://api.openai.com/v1" not in routes_src, (
|
||||
"_handle_live_models must not hardcode api.openai.com — "
|
||||
"provider resolution is handled by the agent"
|
||||
)
|
||||
assert "not_supported" not in routes_src, (
|
||||
"_handle_live_models must not return not_supported for any provider — "
|
||||
"provider_model_ids() falls back to static list automatically"
|
||||
)
|
||||
|
||||
|
||||
def test_live_models_ui_no_longer_skips_any_provider():
|
||||
"""_fetchLiveModels in ui.js must not exclude any provider from live fetching.
|
||||
Previously anthropic, google, and gemini were skipped — now provider_model_ids()
|
||||
handles them all (with graceful fallback to static lists).
|
||||
"""
|
||||
import pathlib
|
||||
ui_src = (pathlib.Path(__file__).parent.parent / "static" / "ui.js").read_text()
|
||||
# The old exclusion list must be gone
|
||||
assert "includes(provider)" not in ui_src or "anthropic" not in ui_src[:ui_src.find("includes(provider)")+100], (
|
||||
"_fetchLiveModels must not skip anthropic, google, or gemini — "
|
||||
"the backend now returns live models for all providers"
|
||||
)
|
||||
175
tests/test_orphaned_tool_messages.py
Normal file
175
tests/test_orphaned_tool_messages.py
Normal file
@@ -0,0 +1,175 @@
|
||||
"""Tests for _sanitize_messages_for_api() orphaned-tool-message stripping.
|
||||
|
||||
Regression for issue #534: strictly-conformant providers (Mercury-2/Inception,
|
||||
newer OpenAI models) reject histories containing tool-role messages whose
|
||||
tool_call_id has no matching tool_calls entry in a prior assistant message.
|
||||
"""
|
||||
import sys
|
||||
import pathlib
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from api.streaming import _sanitize_messages_for_api
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _asst_with_tool_call(call_id="call-1", call_id_key="id"):
|
||||
return {
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{"type": "function", call_id_key: call_id, "function": {"name": "terminal", "arguments": "{}"}}],
|
||||
"_ts": 12345, # extra field that should be stripped
|
||||
}
|
||||
|
||||
|
||||
def _tool_result(call_id="call-1"):
|
||||
return {"role": "tool", "tool_call_id": call_id, "content": "ok", "_ts": 12345}
|
||||
|
||||
|
||||
def _user(text="hello"):
|
||||
return {"role": "user", "content": text, "_ts": 12345}
|
||||
|
||||
|
||||
def _asst(text="hi"):
|
||||
return {"role": "assistant", "content": text, "_ts": 12345}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: normal valid histories are preserved
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_valid_tool_roundtrip_preserved():
|
||||
"""A linked assistant→tool pair must be kept intact."""
|
||||
msgs = [_user(), _asst_with_tool_call("call-1"), _tool_result("call-1"), _asst()]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert roles == ["user", "assistant", "tool", "assistant"]
|
||||
|
||||
|
||||
def test_extra_fields_stripped():
|
||||
"""Non-API fields (_ts etc.) are always stripped."""
|
||||
msgs = [_user(), _asst()]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
for m in result:
|
||||
assert "_ts" not in m
|
||||
|
||||
|
||||
def test_valid_history_without_tool_messages_unchanged():
|
||||
"""Plain user/assistant history with no tool calls is passed through unchanged."""
|
||||
msgs = [_user("a"), _asst("b"), _user("c"), _asst("d")]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
assert len(result) == 4
|
||||
assert all(m["role"] in ("user", "assistant") for m in result)
|
||||
|
||||
|
||||
def test_multiple_valid_tool_calls_preserved():
|
||||
"""Multiple linked tool_call_ids in one assistant message are all preserved."""
|
||||
asst = {
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [
|
||||
{"type": "function", "id": "call-1", "function": {"name": "f1", "arguments": "{}"}},
|
||||
{"type": "function", "id": "call-2", "function": {"name": "f2", "arguments": "{}"}},
|
||||
],
|
||||
}
|
||||
msgs = [_user(), asst, _tool_result("call-1"), _tool_result("call-2"), _asst()]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert roles == ["user", "assistant", "tool", "tool", "assistant"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: orphaned tool messages are dropped
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_orphaned_tool_message_dropped():
|
||||
"""A tool message with no matching assistant tool_call is dropped."""
|
||||
msgs = [_user(), _asst(), _tool_result("call-orphan")]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert "tool" not in roles
|
||||
assert roles == ["user", "assistant"]
|
||||
|
||||
|
||||
def test_tool_message_missing_tool_call_id_dropped():
|
||||
"""A tool message with no tool_call_id at all is dropped."""
|
||||
msg = {"role": "tool", "content": "result"}
|
||||
msgs = [_user(), _asst_with_tool_call("call-1"), msg]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert "tool" not in roles
|
||||
|
||||
|
||||
def test_partially_orphaned_tool_messages():
|
||||
"""In a mixed batch, only the orphaned tool messages are dropped."""
|
||||
asst = _asst_with_tool_call("call-valid")
|
||||
msgs = [
|
||||
_user(),
|
||||
asst,
|
||||
_tool_result("call-valid"), # linked → kept
|
||||
_tool_result("call-ghost"), # orphaned → dropped
|
||||
_asst(),
|
||||
]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert roles == ["user", "assistant", "tool", "assistant"]
|
||||
# The kept tool message has the right call_id
|
||||
tool_msgs = [m for m in result if m["role"] == "tool"]
|
||||
assert tool_msgs[0]["tool_call_id"] == "call-valid"
|
||||
|
||||
|
||||
def test_orphaned_tool_only_history():
|
||||
"""A history consisting only of orphaned tool messages returns empty."""
|
||||
msgs = [_tool_result("dangling-1"), _tool_result("dangling-2")]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
assert result == []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: Anthropic 'call_id' field name (not OpenAI 'id')
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_anthropic_call_id_field_recognized():
|
||||
"""Anthropic tool calls use 'call_id' not 'id' — both must be recognized."""
|
||||
asst = _asst_with_tool_call("call-anthropic", call_id_key="call_id")
|
||||
msgs = [_user(), asst, _tool_result("call-anthropic"), _asst()]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
roles = [m["role"] for m in result]
|
||||
assert roles == ["user", "assistant", "tool", "assistant"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests: edge cases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_empty_messages_list():
|
||||
assert _sanitize_messages_for_api([]) == []
|
||||
|
||||
|
||||
def test_non_dict_messages_skipped():
|
||||
"""Non-dict items in the messages list are silently ignored."""
|
||||
msgs = ["not a dict", None, _user("hi"), 42]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
assert len(result) == 1
|
||||
assert result[0]["role"] == "user"
|
||||
|
||||
|
||||
def test_tool_calls_none_does_not_crash():
|
||||
"""An assistant message with tool_calls=None is handled without crashing."""
|
||||
asst = {"role": "assistant", "content": "hello", "tool_calls": None}
|
||||
msgs = [_user(), asst, _tool_result("call-1")]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
# call-1 has no valid parent (tool_calls=None → no IDs registered) → dropped
|
||||
roles = [m["role"] for m in result]
|
||||
assert "tool" not in roles
|
||||
|
||||
|
||||
def test_system_messages_preserved():
|
||||
"""System messages are always preserved."""
|
||||
msgs = [{"role": "system", "content": "You are helpful."}, _user(), _asst()]
|
||||
result = _sanitize_messages_for_api(msgs)
|
||||
assert result[0]["role"] == "system"
|
||||
67
tests/test_profile_env_isolation.py
Normal file
67
tests/test_profile_env_isolation.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_profile_switch_clears_previous_profile_env_vars(monkeypatch, tmp_path):
|
||||
base = tmp_path / ".hermes"
|
||||
(base / "profiles" / "p1").mkdir(parents=True)
|
||||
(base / "profiles" / "p2").mkdir(parents=True)
|
||||
(base / "profiles" / "p1" / ".env").write_text(
|
||||
"OPENAI_API_KEY=secret-from-p1\nCUSTOM_TOKEN=token-from-p1\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
monkeypatch.setenv("HERMES_BASE_HOME", str(base))
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
monkeypatch.delenv("CUSTOM_TOKEN", raising=False)
|
||||
|
||||
sys.modules.pop("api.profiles", None)
|
||||
profiles = importlib.import_module("api.profiles")
|
||||
profiles = importlib.reload(profiles)
|
||||
|
||||
profiles.init_profile_state()
|
||||
profiles.switch_profile("p1")
|
||||
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p1"
|
||||
assert os.environ.get("CUSTOM_TOKEN") == "token-from-p1"
|
||||
|
||||
profiles.switch_profile("p2")
|
||||
assert os.environ.get("OPENAI_API_KEY") is None
|
||||
assert os.environ.get("CUSTOM_TOKEN") is None
|
||||
assert profiles.get_active_profile_name() == "p2"
|
||||
|
||||
|
||||
def test_profile_switch_replaces_overlapping_keys(monkeypatch, tmp_path):
|
||||
base = tmp_path / ".hermes"
|
||||
(base / "profiles" / "p1").mkdir(parents=True)
|
||||
(base / "profiles" / "p2").mkdir(parents=True)
|
||||
(base / "profiles" / "p1" / ".env").write_text(
|
||||
"OPENAI_API_KEY=secret-from-p1\nONLY_P1=one\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(base / "profiles" / "p2" / ".env").write_text(
|
||||
"OPENAI_API_KEY=secret-from-p2\nONLY_P2=two\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
monkeypatch.setenv("HERMES_BASE_HOME", str(base))
|
||||
monkeypatch.delenv("HERMES_HOME", raising=False)
|
||||
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
||||
monkeypatch.delenv("ONLY_P1", raising=False)
|
||||
monkeypatch.delenv("ONLY_P2", raising=False)
|
||||
|
||||
sys.modules.pop("api.profiles", None)
|
||||
profiles = importlib.import_module("api.profiles")
|
||||
profiles = importlib.reload(profiles)
|
||||
|
||||
profiles.init_profile_state()
|
||||
profiles.switch_profile("p1")
|
||||
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p1"
|
||||
assert os.environ.get("ONLY_P1") == "one"
|
||||
|
||||
profiles.switch_profile("p2")
|
||||
assert os.environ.get("OPENAI_API_KEY") == "secret-from-p2"
|
||||
assert os.environ.get("ONLY_P1") is None
|
||||
assert os.environ.get("ONLY_P2") == "two"
|
||||
63
tests/test_profile_path_security.py
Normal file
63
tests/test_profile_path_security.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).parent.parent.resolve()
|
||||
if str(REPO_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
|
||||
def _reload_profiles_module(base_home: Path):
|
||||
os.environ["HERMES_BASE_HOME"] = str(base_home)
|
||||
os.environ["HERMES_HOME"] = str(base_home)
|
||||
|
||||
for name in ["api.config", "api.profiles"]:
|
||||
if name in sys.modules:
|
||||
del sys.modules[name]
|
||||
|
||||
profiles = importlib.import_module("api.profiles")
|
||||
return profiles
|
||||
|
||||
|
||||
def test_switch_profile_rejects_path_traversal():
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
temp_root = Path(td)
|
||||
base = temp_root / ".hermes"
|
||||
(base / "profiles").mkdir(parents=True)
|
||||
(temp_root / "escape-target").mkdir()
|
||||
|
||||
profiles = _reload_profiles_module(base)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
profiles.switch_profile("../../escape-target")
|
||||
|
||||
|
||||
def test_delete_profile_rejects_path_traversal():
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
temp_root = Path(td)
|
||||
base = temp_root / ".hermes"
|
||||
(base / "profiles").mkdir(parents=True)
|
||||
(temp_root / "escape-target").mkdir()
|
||||
|
||||
profiles = _reload_profiles_module(base)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
profiles.delete_profile_api("../../escape-target")
|
||||
|
||||
|
||||
def test_switch_profile_allows_valid_profile_name():
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
temp_root = Path(td)
|
||||
base = temp_root / ".hermes"
|
||||
profile_dir = base / "profiles" / "demo"
|
||||
profile_dir.mkdir(parents=True)
|
||||
|
||||
profiles = _reload_profiles_module(base)
|
||||
result = profiles.switch_profile("demo")
|
||||
|
||||
assert result["active"] == "demo"
|
||||
assert Path(os.environ["HERMES_HOME"]).resolve() == profile_dir.resolve()
|
||||
313
tests/test_provider_mismatch.py
Normal file
313
tests/test_provider_mismatch.py
Normal file
@@ -0,0 +1,313 @@
|
||||
"""
|
||||
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()
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
|
||||
# ── Model switch toast (#419) ─────────────────────────────────────────────────
|
||||
|
||||
class TestModelSwitchToast:
|
||||
"""Toast appears when user switches model during an active session."""
|
||||
|
||||
def test_toast_in_model_select_onchange(self):
|
||||
"""modelSelect.onchange must show a toast when S.messages is non-empty."""
|
||||
src = _read("static/boot.js")
|
||||
# Find the onchange block
|
||||
idx = src.find("modelSelect').onchange")
|
||||
assert idx != -1, "modelSelect.onchange not found in boot.js"
|
||||
block = src[idx:idx + 1100]
|
||||
assert "Model change takes effect in your next conversation" in block, (
|
||||
"modelSelect.onchange must show a toast when switching model mid-session"
|
||||
)
|
||||
|
||||
def test_toast_guards_on_messages_length(self):
|
||||
"""Toast must only fire when there are existing messages (active session)."""
|
||||
src = _read("static/boot.js")
|
||||
idx = src.find("Model change takes effect in your next conversation")
|
||||
assert idx != -1
|
||||
# Look back 200 chars for the S.messages guard
|
||||
surrounding = src[max(0, idx - 200):idx + 50]
|
||||
assert "S.messages" in surrounding and ".length" in surrounding, (
|
||||
"Model switch toast must be gated on S.messages.length > 0"
|
||||
)
|
||||
|
||||
def test_toast_uses_show_toast_not_alert(self):
|
||||
"""Toast must use showToast(), not alert()."""
|
||||
src = _read("static/boot.js")
|
||||
idx = src.find("Model change takes effect in your next conversation")
|
||||
assert idx != -1
|
||||
surrounding = src[max(0, idx - 50):idx + 100]
|
||||
assert "showToast" in surrounding, "Must use showToast() not alert()"
|
||||
assert "alert(" not in surrounding, "Must not use alert()"
|
||||
|
||||
def test_toast_has_typeof_showtoast_guard(self):
|
||||
"""Toast call must guard typeof showToast to be safe during boot."""
|
||||
src = _read("static/boot.js")
|
||||
idx = src.find("Model change takes effect in your next conversation")
|
||||
assert idx != -1
|
||||
surrounding = src[max(0, idx - 100):idx + 50]
|
||||
assert "typeof showToast" in surrounding, (
|
||||
"showToast call must be guarded with typeof check"
|
||||
)
|
||||
@@ -5,6 +5,7 @@ These tests exist specifically to prevent those bugs from silently returning.
|
||||
Each test is tagged with the sprint/commit where the bug was found and fixed.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import time
|
||||
import urllib.error
|
||||
@@ -12,7 +13,7 @@ import urllib.request
|
||||
import urllib.parse
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
def get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
@@ -104,7 +105,7 @@ def test_session_with_tool_calls_in_json_loads_ok(cleanup_test_sessions):
|
||||
sid = make_session(cleanup_test_sessions)
|
||||
|
||||
# Manually inject tool_calls into the session's JSON file
|
||||
sessions_dir = pathlib.Path.home() / ".hermes" / "webui-mvp-test" / "sessions"
|
||||
sessions_dir = pathlib.Path(os.environ.get("HERMES_WEBUI_TEST_STATE_DIR", str(pathlib.Path.home() / ".hermes" / "webui-mvp-test"))) / "sessions"
|
||||
session_file = sessions_dir / f"{sid}.json"
|
||||
if session_file.exists():
|
||||
d = json.loads(session_file.read_text())
|
||||
@@ -226,8 +227,8 @@ def test_loadSession_resets_busy_state_for_idle_session(cleanup_test_sessions):
|
||||
src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
# The fix adds explicit S.busy=false in the non-inflight else branch
|
||||
assert "S.busy=false;" in src, "sessions.js loadSession must set S.busy=false when loading a non-inflight session"
|
||||
# btnSend must be explicitly re-enabled
|
||||
assert "$('btnSend').disabled=false;" in src, "sessions.js loadSession must enable btnSend for non-inflight sessions"
|
||||
# btnSend state must be refreshed via updateSendBtn
|
||||
assert "updateSendBtn()" in src, "sessions.js loadSession must call updateSendBtn for non-inflight sessions"
|
||||
|
||||
|
||||
def test_done_handler_guards_setbusy_with_inflight_check(cleanup_test_sessions):
|
||||
@@ -241,6 +242,24 @@ def test_done_handler_guards_setbusy_with_inflight_check(cleanup_test_sessions):
|
||||
assert "INFLIGHT[S.session.session_id]" in src, "messages.js must guard setBusy(false) with INFLIGHT check for current session"
|
||||
|
||||
|
||||
def test_refresh_handler_does_not_drop_tool_messages_needed_by_todos(cleanup_test_sessions):
|
||||
"""Todo panel state must survive session reload/refresh.
|
||||
The UI can hide tool-role messages from the visible transcript, but it must not
|
||||
destroy the raw session messages because loadTodos reconstructs state from the
|
||||
latest todo tool output.
|
||||
"""
|
||||
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
ui_src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
panels_src = (REPO_ROOT / "static/panels.js").read_text()
|
||||
|
||||
assert "data.session.messages=(data.session.messages||[]).filter(" not in sessions_src, \
|
||||
"sessions.js must not overwrite raw session.messages when filtering transcript display"
|
||||
assert "S.messages = (data.session.messages || []).filter(" not in ui_src, \
|
||||
"ui.js refreshSession must not rebuild S.messages by discarding tool messages from the raw session payload"
|
||||
assert "const sourceMessages = (S.session && Array.isArray(S.session.messages) && S.session.messages.length) ? S.session.messages : S.messages;" in panels_src, \
|
||||
"loadTodos must prefer raw S.session.messages so todo state survives reloads"
|
||||
|
||||
|
||||
def test_cancel_button_not_cleared_across_sessions(cleanup_test_sessions):
|
||||
"""R7c: The Cancel button and activeStreamId must only be cleared when the
|
||||
done/error event belongs to the currently viewed session.
|
||||
@@ -286,9 +305,16 @@ 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]
|
||||
# Use 1200 chars to accommodate any validation/guard code added
|
||||
# before the SESSION_INDEX_FILE.unlink() call (e.g. session_id
|
||||
# character checks, path traversal guards).
|
||||
delete_block = text[delete_idx:delete_idx+1200]
|
||||
assert "SESSION_INDEX_FILE" in delete_block, \
|
||||
f"{label} session/delete must invalidate SESSION_INDEX_FILE"
|
||||
return
|
||||
@@ -348,12 +374,12 @@ def test_respond_approval_uses_approval_session_id(cleanup_test_sessions):
|
||||
assert "_approvalSessionId" in fn_body, "respondApproval must read _approvalSessionId, not S.session.session_id"
|
||||
|
||||
|
||||
# ── R11: Activity bar shows cross-session tool status ─────────────────────
|
||||
# ── R11: Tool progress must not use shared status chrome ──────────────────
|
||||
|
||||
def test_tool_status_only_shown_for_current_session(cleanup_test_sessions):
|
||||
"""R11: The activity bar setStatus() call in the tool SSE handler must only
|
||||
fire when the user is viewing the session that triggered the tool.
|
||||
When missing, session A's tool names would appear in session B's activity bar.
|
||||
"""R11: Tool progress should not drive the global status bar or composer
|
||||
status. Live tool cards in the current conversation are the authoritative
|
||||
progress UI, which avoids cross-session status leakage entirely.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
# Sprint 12: handler moved into _wireSSE(source)
|
||||
@@ -362,14 +388,10 @@ def test_tool_status_only_shown_for_current_session(cleanup_test_sessions):
|
||||
tool_idx = src.find("es.addEventListener('tool'")
|
||||
assert tool_idx >= 0
|
||||
tool_block = src[tool_idx:tool_idx+400]
|
||||
# setStatus must be inside the activeSid guard, not before it
|
||||
status_pos = tool_block.find("setStatus(")
|
||||
guard_pos = tool_block.find("S.session.session_id===activeSid")
|
||||
assert guard_pos >= 0, "tool handler must guard with activeSid check"
|
||||
# The guard must appear BEFORE or AROUND the setStatus call
|
||||
# (status only fires for the current session)
|
||||
assert status_pos > tool_block.find("activeSid"), \
|
||||
"setStatus in tool handler must be inside the activeSid guard"
|
||||
assert "setStatus(" not in tool_block, \
|
||||
"tool handler should not use the global activity/status bar"
|
||||
assert "setComposerStatus(" not in tool_block, \
|
||||
"tool handler should not use composer status for tool progress"
|
||||
|
||||
# ── R12: Live tool cards lost on switch-away and switch-back ──────────────
|
||||
|
||||
@@ -401,7 +423,7 @@ def test_done_handler_sets_busy_false_before_renderMessages(cleanup_test_session
|
||||
if done_idx < 0:
|
||||
done_idx = src.find("es.addEventListener('done'")
|
||||
assert done_idx >= 0
|
||||
done_block = src[done_idx:done_idx+1500]
|
||||
done_block = src[done_idx:done_idx+2500]
|
||||
# S.busy=false must appear before renderMessages() within the done handler
|
||||
busy_pos = done_block.find("S.busy=false;")
|
||||
render_pos = done_block.find("renderMessages()")
|
||||
@@ -440,7 +462,166 @@ def test_newSession_clears_live_tool_cards(cleanup_test_sessions):
|
||||
assert "clearLiveToolCards" in new_sess_body, "newSession() must call clearLiveToolCards() to clear stale live cards"
|
||||
|
||||
|
||||
# ── R16: Stack traces must not leak to clients in 500 responses ────────────
|
||||
def test_newSession_resets_busy_state_for_fresh_chat(cleanup_test_sessions):
|
||||
"""R15b: newSession() must reset the viewed chat to idle state.
|
||||
Without this, starting a second chat while another session is streaming leaves
|
||||
S.busy=true, so the first send in the new chat gets incorrectly queued.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
new_sess_idx = src.find("async function newSession(")
|
||||
assert new_sess_idx >= 0
|
||||
next_fn = src.find("async function ", new_sess_idx + 10)
|
||||
new_sess_body = src[new_sess_idx:next_fn]
|
||||
assert "S.busy=false;" in new_sess_body, \
|
||||
"newSession() must clear S.busy so a fresh chat is immediately sendable"
|
||||
assert "S.activeStreamId=null;" in new_sess_body, \
|
||||
"newSession() must clear the active stream id for the newly viewed chat"
|
||||
assert "updateQueueBadge(S.session.session_id);" in new_sess_body, \
|
||||
"newSession() must refresh the badge for the new session rather than leaving the old session's queue badge visible"
|
||||
|
||||
|
||||
def test_session_scoped_message_queue_frontend_wiring(cleanup_test_sessions):
|
||||
"""R15bb: queued follow-ups must stay attached to their originating session.
|
||||
The frontend should use a session-keyed queue store and drain only the active
|
||||
session's queued messages when that session becomes idle.
|
||||
"""
|
||||
ui_src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
messages_src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
assert "const SESSION_QUEUES" in ui_src
|
||||
assert "function queueSessionMessage" in ui_src
|
||||
assert "function shiftQueuedSessionMessage" in ui_src
|
||||
assert "const sid=S.session&&S.session.session_id;" in ui_src
|
||||
assert "const next=sid?shiftQueuedSessionMessage(sid):null;" in ui_src
|
||||
assert "queueSessionMessage(S.session.session_id" in messages_src
|
||||
assert "updateQueueBadge(S.session.session_id);" in messages_src
|
||||
assert "updateQueueBadge(sid);" in sessions_src
|
||||
|
||||
|
||||
def test_chat_start_persists_pending_turn_metadata_for_reload_recovery(cleanup_test_sessions):
|
||||
"""R15c: chat/start must expose enough pending-turn metadata for a reload to
|
||||
rebuild the in-flight conversation instead of showing a blank session.
|
||||
"""
|
||||
routes_src = (REPO_ROOT / "api/routes.py").read_text()
|
||||
assert 's.active_stream_id = stream_id' in routes_src
|
||||
assert 's.pending_user_message = msg' in routes_src
|
||||
assert 's.pending_attachments = attachments' in routes_src
|
||||
assert '"active_stream_id": getattr(s, "active_stream_id", None)' in routes_src
|
||||
assert '"pending_user_message": getattr(s, "pending_user_message", None)' in routes_src
|
||||
|
||||
|
||||
def test_reload_path_restores_pending_message_and_reattaches_live_stream(cleanup_test_sessions):
|
||||
"""R15d: the frontend reload path must show the pending user turn and
|
||||
reattach to the live SSE stream after loadSession().
|
||||
"""
|
||||
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
ui_src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
messages_src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
assert 'getPendingSessionMessage' in ui_src
|
||||
assert 'pending_user_message' in ui_src
|
||||
assert 'function attachLiveStream' in messages_src
|
||||
assert 'const pendingMsg=typeof getPendingSessionMessage' in sessions_src
|
||||
assert 'const activeStreamId=data.session.active_stream_id||null;' in sessions_src
|
||||
assert 'attachLiveStream(sid, activeStreamId' in sessions_src
|
||||
assert 'if (S.activeStreamId && S.activeStreamId === streamId) return;' in ui_src
|
||||
|
||||
|
||||
# ── R16: Switching away/back must preserve live partial assistant output ─────
|
||||
|
||||
|
||||
def test_live_stream_tokens_persist_partial_assistant_for_session_switch(cleanup_test_sessions):
|
||||
"""R16: in-flight assistant text must be mirrored into INFLIGHT session state,
|
||||
and the live stream must rebind to the rebuilt DOM after switching away and back.
|
||||
Without this, partial assistant output disappears until the final done payload lands.
|
||||
"""
|
||||
messages_src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
ui_src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
|
||||
assert "content:assistantText" in messages_src, \
|
||||
"messages.js must persist the partial assistant text into INFLIGHT state"
|
||||
assert "_live:true" in messages_src, \
|
||||
"messages.js must mark the persisted in-flight assistant row so renderMessages can re-anchor it"
|
||||
assert "syncInflightAssistantMessage();" in messages_src, \
|
||||
"token handler must update INFLIGHT state before checking the active session"
|
||||
assert "assistantRow&&!assistantRow.isConnected" in messages_src, \
|
||||
"live stream must drop stale detached assistant DOM references after session switches"
|
||||
assert "data-live-assistant" in ui_src, \
|
||||
"renderMessages must preserve a live-assistant DOM anchor when rebuilding the thread"
|
||||
|
||||
|
||||
def test_inflight_session_state_tracks_live_tool_cards_per_session(cleanup_test_sessions):
|
||||
"""R16b: live tool cards must be stored on the in-flight session, not only in the
|
||||
global S.toolCalls array, so switching chats does not lose or misattach them.
|
||||
"""
|
||||
messages_src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
|
||||
assert "INFLIGHT[activeSid].toolCalls.push(tc);" in messages_src, \
|
||||
"tool SSE handler must persist live tool calls onto the in-flight session"
|
||||
assert "S.toolCalls=(INFLIGHT[sid].toolCalls||[]);" in sessions_src, \
|
||||
"loadSession() must restore live tool calls from the in-flight session state"
|
||||
|
||||
|
||||
def test_loadSession_inflight_sets_busy_before_renderMessages(cleanup_test_sessions):
|
||||
"""R16c: loading an in-flight session must mark it busy before renderMessages().
|
||||
Otherwise renderMessages() treats S.toolCalls as settled history cards and the
|
||||
same tool call appears once inline and once in the live tool host after a
|
||||
session switch.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
inflight_idx = src.find("if(INFLIGHT[sid]){")
|
||||
assert inflight_idx >= 0, "INFLIGHT branch not found in loadSession"
|
||||
inflight_block = src[inflight_idx:inflight_idx+700]
|
||||
busy_pos = inflight_block.find("S.busy=true;")
|
||||
render_pos = inflight_block.find("renderMessages();appendThinking();")
|
||||
assert busy_pos >= 0, "loadSession INFLIGHT branch must set S.busy=true"
|
||||
assert render_pos >= 0, "loadSession INFLIGHT branch must call renderMessages()"
|
||||
assert busy_pos < render_pos, \
|
||||
"loadSession must set S.busy=true before renderMessages() to avoid duplicate tool cards"
|
||||
|
||||
|
||||
def test_streaming_bridge_accepts_current_tool_progress_callback_signature(cleanup_test_sessions):
|
||||
"""R17: api/streaming.py must accept the current Hermes agent callback contract.
|
||||
The agent now calls tool_progress_callback(event_type, name, preview, args, **kwargs).
|
||||
If the WebUI bridge only accepts (name, preview, args), live tool updates silently vanish.
|
||||
"""
|
||||
src = (REPO_ROOT / "api/streaming.py").read_text()
|
||||
assert "def on_tool(*cb_args, **cb_kwargs):" in src, \
|
||||
"streaming.py must accept variable callback args for tool progress events"
|
||||
assert "reasoning_callback=on_reasoning" in src, \
|
||||
"streaming.py must wire the agent's reasoning callback into the SSE bridge"
|
||||
assert "put('tool_complete'" in src or 'put("tool_complete"' in src, \
|
||||
"streaming.py must emit live tool completion SSE events"
|
||||
|
||||
|
||||
def test_messages_js_supports_live_reasoning_and_tool_completion(cleanup_test_sessions):
|
||||
"""R18: messages.js must render live reasoning and react to tool completion events.
|
||||
Without these handlers, the operator only sees generic Thinking… or nothing
|
||||
until the final done snapshot redraws the whole turn.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
assert "let reasoningText=''" in src, \
|
||||
"messages.js must track streamed reasoning text separately from assistant text"
|
||||
assert "source.addEventListener('reasoning'" in src or 'source.addEventListener("reasoning"' in src, \
|
||||
"messages.js must listen for live reasoning SSE events"
|
||||
assert "source.addEventListener('tool_complete'" in src or 'source.addEventListener("tool_complete"' in src, \
|
||||
"messages.js must listen for live tool completion SSE events"
|
||||
assert "function _parseStreamState()" in src, \
|
||||
"messages.js must parse live stream state into reasoning + visible answer"
|
||||
|
||||
|
||||
def test_ui_js_can_upgrade_thinking_spinner_into_live_reasoning_card(cleanup_test_sessions):
|
||||
"""R19: ui.js must be able to replace the placeholder thinking spinner with
|
||||
streamed reasoning text while a turn is in progress.
|
||||
"""
|
||||
src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
assert "function _thinkingMarkup(text='')" in src or 'function _thinkingMarkup(text="")' in src, \
|
||||
"ui.js must centralize thinking row markup so it can switch between spinner and live text"
|
||||
assert "function updateThinking(text=''){appendThinking(text);}" in src or 'function updateThinking(text=""){appendThinking(text);}' in src, \
|
||||
"ui.js must expose an updateThinking helper for live reasoning rendering"
|
||||
|
||||
|
||||
# ── R17: Stack traces must not leak to clients in 500 responses ────────────
|
||||
|
||||
def test_500_response_has_no_trace_field():
|
||||
"""R16: HTTP 500 responses must not include a 'trace' field.
|
||||
@@ -472,3 +653,45 @@ 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"
|
||||
|
||||
|
||||
def test_reload_recovery_persists_durable_inflight_state(cleanup_test_sessions):
|
||||
"""Reload recovery must persist a durable per-session inflight snapshot.
|
||||
Without these helpers, loadSession() references loadInflightState() but a full
|
||||
browser reload has no saved state to hydrate, so recovery silently no-ops.
|
||||
"""
|
||||
ui_src = (REPO_ROOT / "static/ui.js").read_text()
|
||||
messages_src = (REPO_ROOT / "static/messages.js").read_text()
|
||||
sessions_src = (REPO_ROOT / "static/sessions.js").read_text()
|
||||
|
||||
assert "const INFLIGHT_STATE_KEY = 'hermes-webui-inflight-state'" in ui_src
|
||||
assert "function saveInflightState(sid, state)" in ui_src
|
||||
assert "function loadInflightState(sid, streamId)" in ui_src
|
||||
assert "function clearInflightState(sid)" in ui_src
|
||||
assert "saveInflightState(activeSid" in messages_src, \
|
||||
"messages.js must persist live stream snapshots while a turn is in flight"
|
||||
assert "clearInflightState(activeSid)" in messages_src, \
|
||||
"messages.js must clear durable inflight snapshots when the run ends/errors/cancels"
|
||||
assert "const stored=loadInflightState(sid, activeStreamId);" in sessions_src, \
|
||||
"loadSession() must hydrate in-flight state from durable browser storage on reload"
|
||||
|
||||
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")
|
||||
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
# 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
|
||||
155
tests/test_session_sidebar_relative_time.py
Normal file
155
tests/test_session_sidebar_relative_time.py
Normal file
@@ -0,0 +1,155 @@
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import textwrap
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
SESSIONS_JS = (REPO_ROOT / "static" / "sessions.js").read_text(encoding="utf-8")
|
||||
STYLE_CSS = (REPO_ROOT / "static" / "style.css").read_text(encoding="utf-8")
|
||||
I18N_JS = (REPO_ROOT / "static" / "i18n.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _extract_function(source: str, name: str) -> str:
|
||||
marker = f"function {name}"
|
||||
start = source.index(marker)
|
||||
brace_start = source.index("{", start)
|
||||
depth = 0
|
||||
for idx in range(brace_start, len(source)):
|
||||
ch = source[idx]
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start : idx + 1]
|
||||
raise AssertionError(f"Could not extract {name}")
|
||||
|
||||
|
||||
def _run_session_time_case(script_body: str) -> dict:
|
||||
functions = "\n\n".join(
|
||||
_extract_function(SESSIONS_JS, name)
|
||||
for name in (
|
||||
"_localDayOrdinal",
|
||||
"_sessionCalendarBoundaries",
|
||||
"_formatSessionDate",
|
||||
"_formatRelativeSessionTime",
|
||||
"_sessionTimeBucketLabel",
|
||||
)
|
||||
)
|
||||
script = textwrap.dedent(
|
||||
f"""
|
||||
process.env.TZ = 'UTC';
|
||||
const translations = {{
|
||||
session_time_unknown: 'Unknown',
|
||||
session_time_just_now: 'just now',
|
||||
session_time_minutes_ago: (n) => `${{n}} minute${{n === 1 ? '' : 's'}} ago`,
|
||||
session_time_hours_ago: (n) => `${{n}} hour${{n === 1 ? '' : 's'}} ago`,
|
||||
session_time_days_ago: (n) => `${{n}} day${{n === 1 ? '' : 's'}} ago`,
|
||||
session_time_last_week: 'last week',
|
||||
session_time_bucket_today: 'Today',
|
||||
session_time_bucket_yesterday: 'Yesterday',
|
||||
session_time_bucket_this_week: 'This week',
|
||||
session_time_bucket_last_week: 'Last week',
|
||||
session_time_bucket_older: 'Older',
|
||||
}};
|
||||
function t(key, ...args) {{
|
||||
const val = translations[key];
|
||||
return typeof val === 'function' ? val(...args) : val;
|
||||
}}
|
||||
{functions}
|
||||
{script_body}
|
||||
"""
|
||||
)
|
||||
proc = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def test_session_sidebar_js_has_dynamic_relative_time_helpers():
|
||||
assert "function _sessionCalendarBoundaries" in SESSIONS_JS
|
||||
assert "function _formatRelativeSessionTime" in SESSIONS_JS
|
||||
assert "function _sessionTimeBucketLabel" in SESSIONS_JS
|
||||
assert "session_time_bucket_last_week" in SESSIONS_JS
|
||||
assert "session_time_bucket_this_week" in SESSIONS_JS
|
||||
assert "session_time_bucket_older" in SESSIONS_JS
|
||||
|
||||
|
||||
def test_session_sidebar_renders_relative_time_and_meta_rows():
|
||||
# session-time element was removed from sessions.js in v0.50.40 to
|
||||
# give session titles full width — the CSS class is kept but set to display:none.
|
||||
# session-meta / metaBits were removed when we dropped message-count, model, and
|
||||
# source-tag badges from the sidebar (design round 2).
|
||||
assert "orderedSessions" in SESSIONS_JS
|
||||
assert ".session-time" in STYLE_CSS
|
||||
assert ".session-title-row" in STYLE_CSS
|
||||
assert ".session-item.active .session-title" in STYLE_CSS
|
||||
assert "|| _sessionTimeBucketLabel" not in SESSIONS_JS
|
||||
assert "const ONE_DAY=86400000;" not in SESSIONS_JS
|
||||
|
||||
|
||||
def test_relative_time_uses_calendar_boundaries_and_year_for_old_sessions():
|
||||
result = _run_session_time_case(
|
||||
"""
|
||||
const now = Date.UTC(2026, 3, 15, 1, 0, 0);
|
||||
const mondayLate = Date.UTC(2026, 3, 13, 23, 0, 0);
|
||||
const oldSession = Date.UTC(2024, 2, 5, 12, 0, 0);
|
||||
process.stdout.write(JSON.stringify({
|
||||
relative: _formatRelativeSessionTime(mondayLate, now),
|
||||
bucket: _sessionTimeBucketLabel(mondayLate, now),
|
||||
oldDate: _formatRelativeSessionTime(oldSession, now),
|
||||
}));
|
||||
"""
|
||||
)
|
||||
assert result["relative"] == "2 days ago"
|
||||
assert result["bucket"] == "This week"
|
||||
assert "2024" in result["oldDate"]
|
||||
|
||||
|
||||
def test_relative_time_today_bucket():
|
||||
"""Session from 2 hours ago should bucket as 'Today'."""
|
||||
result = _run_session_time_case(
|
||||
"""
|
||||
const now = Date.UTC(2026, 3, 15, 14, 0, 0);
|
||||
const twoHoursAgo = now - 2 * 60 * 60 * 1000;
|
||||
process.stdout.write(JSON.stringify({
|
||||
relative: _formatRelativeSessionTime(twoHoursAgo, now),
|
||||
bucket: _sessionTimeBucketLabel(twoHoursAgo, now),
|
||||
}));
|
||||
"""
|
||||
)
|
||||
assert result["relative"] == "2 hours ago"
|
||||
assert result["bucket"] == "Today"
|
||||
|
||||
|
||||
def test_relative_time_handles_just_now_and_dst_safe_yesterday_boundary():
|
||||
result = _run_session_time_case(
|
||||
"""
|
||||
const now = Date.UTC(2026, 2, 9, 12, 0, 0);
|
||||
const justNow = now - 30 * 1000;
|
||||
const yesterday = Date.UTC(2026, 2, 8, 23, 30, 0);
|
||||
process.stdout.write(JSON.stringify({
|
||||
justNow: _formatRelativeSessionTime(justNow, now),
|
||||
yesterday: _formatRelativeSessionTime(yesterday, now),
|
||||
yesterdayBucket: _sessionTimeBucketLabel(yesterday, now),
|
||||
}));
|
||||
"""
|
||||
)
|
||||
assert result["justNow"] == "just now"
|
||||
assert result["yesterday"] == "Yesterday"
|
||||
assert result["yesterdayBucket"] == "Yesterday"
|
||||
|
||||
|
||||
def test_relative_time_strings_are_localized_in_english_and_spanish_bundles():
|
||||
for key in (
|
||||
"session_time_unknown",
|
||||
"session_time_just_now",
|
||||
"session_time_minutes_ago",
|
||||
"session_time_hours_ago",
|
||||
"session_time_days_ago",
|
||||
"session_time_last_week",
|
||||
"session_time_bucket_today",
|
||||
"session_time_bucket_yesterday",
|
||||
"session_time_bucket_this_week",
|
||||
"session_time_bucket_last_week",
|
||||
"session_time_bucket_older",
|
||||
):
|
||||
assert key in I18N_JS
|
||||
66
tests/test_session_summary_redaction.py
Normal file
66
tests/test_session_summary_redaction.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent.parent))
|
||||
|
||||
_needs_server = pytest.mark.usefixtures("test_server")
|
||||
from tests._pytest_port import BASE
|
||||
_FULL_SECRET = "sk-" + ("B" * 24)
|
||||
|
||||
|
||||
def _get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def _write_session_with_secret_title():
|
||||
from tests.conftest import TEST_STATE_DIR
|
||||
|
||||
sid = "sec_summary_" + uuid.uuid4().hex[:8]
|
||||
sessions_dir = TEST_STATE_DIR / "sessions"
|
||||
sessions_dir.mkdir(parents=True, exist_ok=True)
|
||||
now = time.time()
|
||||
(sessions_dir / f"{sid}.json").write_text(json.dumps({
|
||||
"session_id": sid,
|
||||
"title": f"session with {_FULL_SECRET}",
|
||||
"workspace": "/tmp",
|
||||
"model": "test",
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
"pinned": False,
|
||||
"archived": False,
|
||||
"project_id": None,
|
||||
"profile": "default",
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"estimated_cost": None,
|
||||
"personality": None,
|
||||
"messages": [],
|
||||
"tool_calls": [],
|
||||
}))
|
||||
return sid
|
||||
|
||||
|
||||
@_needs_server
|
||||
def test_api_sessions_search_redacts_titles(test_server):
|
||||
sid = _write_session_with_secret_title()
|
||||
data = _get("/api/sessions/search?q=" + urllib.parse.quote("B" * 24))
|
||||
dump = json.dumps(data)
|
||||
assert sid in dump
|
||||
assert _FULL_SECRET not in dump
|
||||
|
||||
|
||||
@_needs_server
|
||||
def test_api_sessions_list_redacts_secret_titles(test_server):
|
||||
sid = _write_session_with_secret_title()
|
||||
data = _get("/api/sessions")
|
||||
dump = json.dumps(data)
|
||||
assert sid in dump
|
||||
assert _FULL_SECRET not in dump
|
||||
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}"
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Sprint 1 test suite for the Hermes Web UI.
|
||||
|
||||
Tests use the ISOLATED test server running on http://127.0.0.1:8788.
|
||||
Tests use the ISOLATED test server. Port is auto-derived per worktree (see conftest.py).
|
||||
Production server (port 8787) and your real conversations are never touched.
|
||||
Start the server before running:
|
||||
<repo>/start.sh
|
||||
@@ -27,7 +27,7 @@ import pathlib
|
||||
# Allow importing server modules directly for unit tests
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).parent.parent.parent))
|
||||
|
||||
BASE = "http://127.0.0.1:8788" # test server (isolated from production)
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
@@ -145,10 +145,13 @@ def test_session_update():
|
||||
"""Create session, update workspace and model, verify persisted."""
|
||||
data, _ = post("/api/session/new", {})
|
||||
sid = data["session"]["session_id"]
|
||||
current_ws = pathlib.Path(data["session"]["workspace"])
|
||||
child_ws = current_ws / f"session-update-{uuid.uuid4().hex[:6]}"
|
||||
child_ws.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
updated, status = post("/api/session/update", {
|
||||
"session_id": sid,
|
||||
"workspace": "/tmp",
|
||||
"workspace": str(child_ws),
|
||||
"model": "anthropic/claude-sonnet-4.6"
|
||||
})
|
||||
assert status == 200
|
||||
|
||||
@@ -4,7 +4,7 @@ Sprint 10 Tests: server.py split, cancel endpoint, cron history, tool card polis
|
||||
import json, pathlib, urllib.error, urllib.request, urllib.parse
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
def get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
@@ -94,7 +94,7 @@ def test_cancel_button_in_html(cleanup_test_sessions):
|
||||
def test_cancel_function_in_boot_js(cleanup_test_sessions):
|
||||
src, _ = get_text("/static/boot.js")
|
||||
assert "async function cancelStream(" in src
|
||||
assert "/api/chat/cancel" in src
|
||||
assert "api/chat/cancel" in src
|
||||
|
||||
# ── Cron history ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -107,7 +107,7 @@ def test_crons_output_limit_param(cleanup_test_sessions):
|
||||
def test_cron_history_button_in_panels_js(cleanup_test_sessions):
|
||||
src, _ = get_text("/static/panels.js")
|
||||
assert "loadCronHistory" in src
|
||||
assert "All runs" in src
|
||||
assert "cron_all_runs" in src # i18n key (was hardcoded 'All runs' before i18n hardening)
|
||||
|
||||
def test_cron_output_snippet_helper(cleanup_test_sessions):
|
||||
src, _ = get_text("/static/panels.js")
|
||||
|
||||
@@ -4,7 +4,7 @@ Sprint 11 Tests: multi-provider model support, streaming smoothness, routes extr
|
||||
import json, pathlib, urllib.error, urllib.request, urllib.parse
|
||||
REPO_ROOT = pathlib.Path(__file__).parent.parent.resolve()
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
def get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
|
||||
@@ -3,7 +3,7 @@ Sprint 12 Tests: settings panel, session pinning, session import, SSE reconnect.
|
||||
"""
|
||||
import json, pathlib, urllib.error, urllib.request, urllib.parse
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
|
||||
@@ -3,7 +3,7 @@ Sprint 13 Tests: cron recent endpoint, session duplicate, background alerts.
|
||||
"""
|
||||
import json, pathlib, urllib.error, urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
@@ -107,14 +107,16 @@ def test_workspace_add_rejects_nonexistent():
|
||||
assert status == 400
|
||||
|
||||
def test_workspace_add_accepts_real_dir():
|
||||
"""Adding a real directory succeeds."""
|
||||
import tempfile
|
||||
tmp = tempfile.mkdtemp()
|
||||
"""Adding a real directory under the trusted workspace root succeeds."""
|
||||
d, _ = post("/api/session/new", {})
|
||||
root = pathlib.Path(d["session"]["workspace"])
|
||||
tmp = root / "trusted-add-test"
|
||||
tmp.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
d, status = post("/api/workspaces/add", {"path": tmp, "name": "test-ws"})
|
||||
d, status = post("/api/workspaces/add", {"path": str(tmp), "name": "test-ws"})
|
||||
assert status == 200
|
||||
assert d["ok"] is True
|
||||
finally:
|
||||
post("/api/workspaces/remove", {"path": tmp})
|
||||
post("/api/workspaces/remove", {"path": str(tmp)})
|
||||
import shutil
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
@@ -3,7 +3,7 @@ Sprint 14 Tests: file rename, folder create, session archive, session tags, merm
|
||||
"""
|
||||
import json, os, pathlib, shutil, tempfile, urllib.error, urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
from tests._pytest_port import BASE
|
||||
|
||||
|
||||
def get(path):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user