Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca06fd5533 | ||
|
|
7ddd896b36 | ||
|
|
f109910b58 | ||
|
|
b784fff104 | ||
|
|
d9293c6097 | ||
|
|
669412cbc9 | ||
|
|
c1a9324f35 | ||
|
|
cbf82898cb | ||
|
|
fb916d1f7e | ||
|
|
9452f56821 | ||
|
|
95645d651e | ||
|
|
2f281cbbd7 | ||
|
|
537337a158 | ||
|
|
8075442200 | ||
|
|
ebdd955578 | ||
|
|
1a4793848e | ||
|
|
8ed206657c | ||
|
|
06e1f11070 | ||
|
|
089dd7e3de | ||
|
|
0875dddbff | ||
|
|
85557381ec | ||
|
|
4a1bf20b67 | ||
|
|
ceb091d6b1 | ||
|
|
f9f56da484 | ||
|
|
b0da4db0d2 | ||
|
|
d899115d26 | ||
|
|
241357595d | ||
|
|
1375ce0634 | ||
|
|
0a39a64387 | ||
|
|
f6e58ef2ad | ||
|
|
2864c2b691 | ||
|
|
96547f68a3 | ||
|
|
a9ae0b0a83 |
110
CHANGELOG.md
110
CHANGELOG.md
@@ -1,8 +1,112 @@
|
||||
# Hermes Web UI -- Changelog
|
||||
|
||||
> Living document. Updated at the end of every sprint.
|
||||
> Source: <repo>/
|
||||
> Repository: https://github.com/<your-username>/hermes-webui
|
||||
> Repository: https://github.com/nesquena/hermes-webui
|
||||
|
||||
---
|
||||
|
||||
## [v0.17.2] Model Update
|
||||
*April 2, 2026*
|
||||
|
||||
### Enhancements
|
||||
- **GLM-5.1 added to Z.AI model list.** New model available in the dropdown
|
||||
for Z.AI provider users. (Fixes #17)
|
||||
|
||||
---
|
||||
|
||||
## [v0.17.1] Security + Bug Fixes
|
||||
*April 2, 2026 | 237 tests*
|
||||
|
||||
### Security
|
||||
- **Path traversal in static file server.** `_serve_static()` now sandboxes
|
||||
resolved paths inside `static/` via `.relative_to()`. Previously
|
||||
`GET /static/../../.hermes/config.yaml` could expose API keys.
|
||||
- **XSS in markdown renderer.** All captured groups in bold, italic, headings,
|
||||
blockquotes, list items, table cells, and link labels now run through `esc()`
|
||||
before `innerHTML` insertion.
|
||||
- **Skill category path traversal.** Category param validated to reject `/`
|
||||
and `..` to prevent writing outside `~/.hermes/skills/`.
|
||||
- **Debug endpoint locked to localhost.** `/api/approval/inject_test` returns
|
||||
404 to any non-loopback client.
|
||||
- **CDN resources pinned with SRI hashes.** PrismJS and Mermaid tags now have
|
||||
`integrity` + `crossorigin` attributes. Mermaid pinned to `@10.9.3`.
|
||||
- **Project color CSS injection.** Color field validated against
|
||||
`^#[0-9a-fA-F]{3,8}$` to prevent `style.background` injection.
|
||||
- **Project name length limit.** Capped at 128 chars, empty-after-strip rejected.
|
||||
|
||||
### Bug Fixes
|
||||
- **OpenRouter model routing regression.** `resolve_model_provider()` was
|
||||
incorrectly stripping provider prefixes from OpenRouter model IDs (e.g.
|
||||
`openai/gpt-5.4-mini` became `gpt-5.4-mini` with provider `openai`),
|
||||
causing AIAgent to look for OPENAI_API_KEY and crash. Fix: only strip
|
||||
prefix when `config.provider` explicitly matches that direct-API provider.
|
||||
- **Project picker invisible.** Dropdown was clipped by `.session-item`
|
||||
`overflow:hidden`. Now appended to `document.body` with `position:fixed`.
|
||||
- **Project picker stretched full width.** Added `max-width:220px;
|
||||
width:max-content` to constrain the fixed-positioned picker.
|
||||
- **No way to create project from picker.** Added "+ New project" item at
|
||||
the bottom of the picker dropdown.
|
||||
- **Folder button undiscoverable.** Now shows persistently (blue, 60%
|
||||
opacity) when session belongs to a project.
|
||||
- **Picker event listener leak.** `removeEventListener` added to all picker
|
||||
item onclick handlers.
|
||||
- **Redundant sys.path.insert calls removed.** Two cron handler imports no
|
||||
longer prepend the agent dir (already on sys.path via config.py).
|
||||
|
||||
---
|
||||
|
||||
## [v0.17] Sprint 15 -- Session Projects + Code Copy + Tool Card Toggle
|
||||
*April 1, 2026 | 237 tests*
|
||||
|
||||
### Features
|
||||
- **Session projects.** Named groups for organizing sessions. A project filter
|
||||
bar (subtle chips) sits between the search input and the session list. Each
|
||||
project has a name and color. Click a chip to filter; "All" shows everything.
|
||||
Create inline (+), rename (double-click), delete (right-click). Assign sessions
|
||||
via folder icon button with dropdown picker. Projects stored in `projects.json`.
|
||||
Session model gains `project_id` field. 5 new API endpoints.
|
||||
- **Code block copy button.** Every code block gets a "Copy" button in the
|
||||
language header bar (or top-right for plain blocks). Click copies to clipboard,
|
||||
shows "Copied!" for 1.5s.
|
||||
- **Tool card expand/collapse.** When a message has 2+ tool cards, "Expand all /
|
||||
Collapse all" toggle appears above the card group.
|
||||
|
||||
---
|
||||
|
||||
## [v0.16.2] Model List Updates + base_url Passthrough
|
||||
*April 1, 2026 | 247 tests*
|
||||
|
||||
### Bug Fixes
|
||||
- **MiniMax model list updated.** Replaced stale ABAB 6.5 models with current
|
||||
MiniMax-M2.7, M2.7-highspeed, M2.5, M2.5-highspeed, M2.1 lineup matching
|
||||
hermes-agent upstream. (Fixes #6)
|
||||
- **Z.AI/GLM model list updated.** Replaced GLM-4 series with current GLM-5,
|
||||
GLM-5 Turbo, GLM-4.7, GLM-4.5, GLM-4.5 Flash lineup.
|
||||
- **base_url passthrough to AIAgent.** `resolve_model_provider()` now reads
|
||||
`base_url` from config.yaml and passes it to AIAgent, so providers with
|
||||
custom endpoints (MiniMax, Z.AI, local LLMs) route to the correct API.
|
||||
|
||||
---
|
||||
|
||||
## [v0.16.1] Community Fixes -- Mobile + Auth + Provider Routing
|
||||
*April 1, 2026 | 247 tests*
|
||||
|
||||
Community contributions from @deboste, reviewed and refined.
|
||||
|
||||
### Bug Fixes
|
||||
- **Mobile responsive layout.** Comprehensive `@media(max-width:640px)` rules
|
||||
for topbar, messages, composer, tool cards, approval cards, and settings modal.
|
||||
Uses `100dvh` with `100vh` fallback to fix composer cutoff on mobile browsers.
|
||||
Textarea `font-size:16px` prevents iOS/Android auto-zoom on focus.
|
||||
- **Reverse proxy basic auth support.** All `fetch()` and `EventSource` URLs now
|
||||
constructed via `new URL(path, location.origin)` to strip embedded credentials
|
||||
per Fetch spec. `credentials:'include'` on fetch, `withCredentials:true` on
|
||||
EventSource ensure auth headers are forwarded through reverse proxies.
|
||||
- **Model provider routing.** New `resolve_model_provider()` helper in
|
||||
`api/config.py` strips provider prefix from dropdown model IDs (e.g.
|
||||
`anthropic/claude-sonnet-4.6` → `claude-sonnet-4.6`) and passes the correct
|
||||
`provider` to AIAgent. Handles cross-provider selection by matching against
|
||||
known direct-API providers.
|
||||
|
||||
---
|
||||
|
||||
@@ -405,4 +509,4 @@ Three-panel layout: sessions sidebar, chat area, workspace panel.
|
||||
|
||||
---
|
||||
|
||||
*Last updated: Sprint 14, March 31, 2026 | Tests: 224/224*
|
||||
*Last updated: v0.16.2, April 1, 2026 | Tests: 247*
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
# Hermes Web UI
|
||||
|
||||
A lightweight, dark-themed browser interface for Hermes.
|
||||
Full parity with the CLI experience -- everything you can do from a terminal,
|
||||
[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 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.
|
||||
|
||||
@@ -16,6 +18,8 @@ This gives you nearly **1:1 parity with Hermes CLI from a convenient web UI** wh
|
||||
|
||||
## Quick start
|
||||
|
||||
First, you need to install and configure [Hermes Agent](https://hermes-agent.nousresearch.com/). Once installed:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/nesquena/hermes-webui.git hermes-webui
|
||||
cd hermes-webui
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
> Goal: Full 1:1 parity with the Hermes CLI experience via a clean dark web UI.
|
||||
> Everything you can do from the CLI terminal, you can do from this UI.
|
||||
>
|
||||
> Last updated: Sprint 14 (March 30, 2026)
|
||||
> Tests: 226/226 passing
|
||||
> Last updated: Sprint 15 (April 1, 2026)
|
||||
> Tests: 237 passing
|
||||
> Source: <repo>/
|
||||
|
||||
---
|
||||
@@ -30,6 +30,8 @@
|
||||
| Sprint 11 | Multi-provider models + streaming | Dynamic model dropdown (any Hermes provider), smooth scroll pinning, routes extracted to api/routes.py (server.py 704→76 lines) | 201 |
|
||||
| Sprint 12 | Settings + reliability + session QoL | Settings panel (gear icon, settings.json), SSE auto-reconnect, pin sessions, import session from JSON | 211 |
|
||||
| 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 |
|
||||
|
||||
---
|
||||
|
||||
@@ -103,6 +105,7 @@
|
||||
- [x] Import session from JSON (Sprint 12)
|
||||
- [x] Pin/star sessions to top of list (Sprint 12)
|
||||
- [x] Duplicate session (Sprint 13)
|
||||
- [x] Session projects / folders (Sprint 15)
|
||||
|
||||
### Workspace Management
|
||||
- [x] Add workspace with path validation (must be existing directory)
|
||||
|
||||
125
SPRINTS.md
125
SPRINTS.md
@@ -146,7 +146,7 @@ to daily friction.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 14 -- Visual Polish + Workspace Ops + Session Organization
|
||||
## Sprint 14 -- Visual Polish + Workspace Ops + Session Organization (COMPLETED)
|
||||
|
||||
**Theme:** Polish the visual experience, close workspace file gaps, and
|
||||
organize sessions properly.
|
||||
@@ -169,60 +169,63 @@ organize sessions properly.
|
||||
sessions hidden from sidebar by default. "Show N archived" toggle at top
|
||||
of list. `POST /api/session/archive` endpoint.
|
||||
|
||||
### Candidates for next sprints
|
||||
- Workspace reorder (drag-and-drop)
|
||||
- View skill linked files
|
||||
- Voice input via Whisper
|
||||
- Subagent delegation cards (enhanced tool card rendering)
|
||||
|
||||
**Tests:** ~12 new. Total: ~233.
|
||||
**Hermes CLI parity impact:** Medium (file rename, folder create)
|
||||
**Claude parity impact:** Medium (Mermaid, tags, archive)
|
||||
|
||||
---
|
||||
|
||||
## Sprint 15 -- Project Organization + Session Management
|
||||
## Sprint 15 -- Session Projects + Code Copy + Tool Card Toggle (COMPLETED)
|
||||
|
||||
**Theme:** Organize work the way you think, not just chronologically.
|
||||
Plus two quick UX wins for code and agentic workflows.
|
||||
|
||||
**Why now:** After 100+ sessions the sidebar is a flat chronological list.
|
||||
Finding sessions from 2 weeks ago, or keeping a "MyProject" workspace separate
|
||||
from personal work, requires the search box. This is the biggest remaining
|
||||
daily organizational gap vs. Claude's project folders.
|
||||
Finding sessions from 2 weeks ago, or keeping work separated by project,
|
||||
requires the search box. Session projects are the single biggest remaining
|
||||
organizational gap vs. Claude's project folders.
|
||||
|
||||
### Track A: Bugs
|
||||
- Session search content scan (depth=5) is slow on large session histories.
|
||||
Add server-side caching of search index.
|
||||
- Date group headers ("Today / Yesterday / Earlier") use updated_at which can
|
||||
be misleading for sessions touched by automated title-setting. Use created_at
|
||||
for initial grouping, updated_at for sort order.
|
||||
- None.
|
||||
|
||||
### Track B: Features
|
||||
- **Session folders / projects:** A "Projects" section above the session list.
|
||||
Each project is a named group. Sessions can be dragged into projects or
|
||||
assigned via right-click. Stored in `projects.json`. Projects collapse/expand.
|
||||
This is the single biggest Claude parity feature missing.
|
||||
- ~~Pin sessions~~ (DONE Sprint 12)
|
||||
- ~~Import session from JSON~~ (DONE Sprint 12)
|
||||
|
||||
### Deferred to later sprints
|
||||
- Session tags / labels
|
||||
- Archive sessions
|
||||
- Rename file / Create folder (can be done through the agent)
|
||||
- Toolset control per session
|
||||
- Virtual scroll for session list
|
||||
- **Session projects:** Named groups for organizing sessions. A project
|
||||
filter bar (subtle chips) sits between the search input and the session
|
||||
list. Each project has a name and color. Click a chip to filter sessions
|
||||
to that project; "All" shows everything. Create projects inline (+
|
||||
button), rename (double-click chip), delete (right-click). Assign
|
||||
sessions via folder icon button (hover-reveal) with a dropdown picker.
|
||||
Projects stored in `projects.json`. Session model gains `project_id`
|
||||
field (null = unassigned). Fully backward-compatible with existing
|
||||
sessions. Endpoints: `GET /api/projects`, `POST /api/projects/create`,
|
||||
`POST /api/projects/rename`, `POST /api/projects/delete`,
|
||||
`POST /api/session/move`.
|
||||
- **Code block copy button:** Every code block gets a "Copy" button.
|
||||
Positioned in the language header bar (or top-right corner for plain
|
||||
code blocks). Click copies code to clipboard, shows "Copied!" for 1.5s.
|
||||
- **Tool card expand/collapse:** When a message has 2+ tool cards, an
|
||||
"Expand all / Collapse all" toggle appears above the card group.
|
||||
Scoped per message group, not global.
|
||||
|
||||
### Track C: Architecture
|
||||
- Session index v2: extend `_index.json` to include `project_id` field.
|
||||
Rebuild on session save. Enables fast client-side filtering without disk reads.
|
||||
- `projects.json` flat file storage for project list (same pattern as
|
||||
`workspaces.json` and `settings.json`).
|
||||
- `project_id` field on Session model with backward-compatible null default.
|
||||
- `_index.json` includes `project_id` for fast client-side filtering.
|
||||
|
||||
**Tests:** ~16 new. Total: ~241.
|
||||
**Tests:** 13 new. Total: ~237.
|
||||
**Hermes CLI parity impact:** Low (CLI has no session organization)
|
||||
**Claude parity impact:** Very High (projects are a core Claude concept)
|
||||
|
||||
### Candidates for next sprints
|
||||
- Workspace reorder (drag-and-drop)
|
||||
- View skill linked files
|
||||
- Voice input via Whisper
|
||||
- Subagent delegation cards (enhanced tool card rendering)
|
||||
|
||||
---
|
||||
|
||||
## Sprint 15 -- Artifacts + Code Execution
|
||||
## Sprint 16 -- Artifacts + Code Execution
|
||||
|
||||
**Theme:** See outputs, not just text.
|
||||
|
||||
@@ -265,7 +268,7 @@ feels like. It also directly enables the Hermes "code execution cell" feature
|
||||
|
||||
---
|
||||
|
||||
## Sprint 16 -- Voice + Multimodal Input
|
||||
## Sprint 17 -- Voice + Multimodal Input
|
||||
|
||||
**Theme:** Input beyond the keyboard.
|
||||
|
||||
@@ -303,7 +306,7 @@ file uploads, not clipboard screenshots into the conversation directly).
|
||||
|
||||
---
|
||||
|
||||
## Sprint 17 -- Subagent Visibility + Agentic Transparency
|
||||
## Sprint 18 -- Subagent Visibility + Agentic Transparency
|
||||
|
||||
**Theme:** Watch Hermes think, not just respond.
|
||||
|
||||
@@ -343,7 +346,7 @@ what's happening. This is the last major "CLI feels better" gap for power users.
|
||||
|
||||
---
|
||||
|
||||
## Sprint 18 -- Auth, HTTPS, and Production Hardening
|
||||
## Sprint 19 -- Auth, HTTPS, and Production Hardening
|
||||
|
||||
**Theme:** Make this safe to leave running.
|
||||
|
||||
@@ -380,7 +383,7 @@ address.
|
||||
|
||||
## Feature Parity Summary
|
||||
|
||||
### After Sprint 17 (Hermes CLI parity: complete)
|
||||
### After Sprint 18 (Hermes CLI parity: complete)
|
||||
|
||||
| CLI Feature | Status |
|
||||
|-------------|--------|
|
||||
@@ -395,16 +398,16 @@ address.
|
||||
| Session history | Done (v0.3) |
|
||||
| Workspace switching | Done (v0.7) |
|
||||
| Model selection | Done (v0.3) |
|
||||
| Multi-provider model support | Sprint 11 |
|
||||
| Multi-provider model support | Done (Sprint 11) |
|
||||
| Toolset control | Sprint 12 |
|
||||
| Settings persistence | Sprint 12 |
|
||||
| Subagent visibility | Sprint 17 |
|
||||
| Background task monitor | Sprint 17 |
|
||||
| Code execution (Jupyter) | Sprint 15 |
|
||||
| Cron completion alerts | Sprint 13 |
|
||||
| Virtual scroll (perf) | Sprint 13 |
|
||||
| Settings persistence | Done (Sprint 12) |
|
||||
| Subagent visibility | Sprint 18 |
|
||||
| Background task monitor | Sprint 18 |
|
||||
| Code execution (Jupyter) | Sprint 16 |
|
||||
| Cron completion alerts | Done (Sprint 13) |
|
||||
| Virtual scroll (perf) | Deferred |
|
||||
|
||||
### After Sprint 18 (Claude parity: ~90% complete)
|
||||
### After Sprint 19 (Claude parity: ~90% complete)
|
||||
|
||||
| Claude Feature | Status |
|
||||
|----------------|--------|
|
||||
@@ -416,19 +419,19 @@ address.
|
||||
| Tool use visibility | Done (v0.11) |
|
||||
| Edit/regenerate messages | Done (v0.10) |
|
||||
| Session management | Done (v0.6) |
|
||||
| Artifacts (HTML/SVG preview) | Sprint 15 |
|
||||
| Code execution inline | Sprint 15 |
|
||||
| Mermaid diagrams | Sprint 15 |
|
||||
| Projects / folders | Sprint 14 |
|
||||
| Pinned/starred sessions | Sprint 14 |
|
||||
| Reasoning display | Sprint 17 |
|
||||
| Voice input | Sprint 16 |
|
||||
| TTS playback | Sprint 16 |
|
||||
| Notifications | Sprint 13 |
|
||||
| Settings panel | Sprint 12 |
|
||||
| Auth / login | Sprint 18 |
|
||||
| HTTPS | Sprint 18 |
|
||||
| Mobile layout | Sprint 18 |
|
||||
| Artifacts (HTML/SVG preview) | Sprint 16 |
|
||||
| Code execution inline | Sprint 16 |
|
||||
| Mermaid diagrams | Done (Sprint 14) |
|
||||
| Projects / folders | Done (Sprint 15) |
|
||||
| Pinned/starred sessions | Done (Sprint 12) |
|
||||
| Reasoning display | Sprint 18 |
|
||||
| Voice input | Sprint 17 |
|
||||
| TTS playback | Sprint 17 |
|
||||
| Notifications | Done (Sprint 13) |
|
||||
| Settings panel | Done (Sprint 12) |
|
||||
| Auth / login | Sprint 19 |
|
||||
| HTTPS | Sprint 19 |
|
||||
| Mobile layout | Done (v0.16.1) |
|
||||
| Sharing / public URLs | Not planned (requires server infra) |
|
||||
| Claude-specific features | Not replicable (Projects AI, artifacts sync) |
|
||||
|
||||
@@ -445,6 +448,6 @@ address.
|
||||
|
||||
---
|
||||
|
||||
*Last updated: March 30, 2026*
|
||||
*Current version: v0.13 | 201 tests*
|
||||
*Next sprint: Sprint 14 (visual polish + small QoL)*
|
||||
*Last updated: April 1, 2026*
|
||||
*Current version: v0.17 | 237 tests*
|
||||
*Next sprint: Sprint 16 (Artifacts + Code Execution)*
|
||||
|
||||
144
api/config.py
144
api/config.py
@@ -39,6 +39,7 @@ WORKSPACES_FILE = STATE_DIR / 'workspaces.json'
|
||||
SESSION_INDEX_FILE = SESSION_DIR / '_index.json'
|
||||
SETTINGS_FILE = STATE_DIR / 'settings.json'
|
||||
LAST_WORKSPACE_FILE = STATE_DIR / 'last_workspace.txt'
|
||||
PROJECTS_FILE = STATE_DIR / 'projects.json'
|
||||
|
||||
# ── Hermes agent directory discovery ─────────────────────────────────────────
|
||||
def _discover_agent_dir() -> Path:
|
||||
@@ -262,6 +263,7 @@ _PROVIDER_DISPLAY = {
|
||||
'zai': 'Z.AI / GLM', 'kimi-coding': 'Kimi / Moonshot', 'deepseek': 'DeepSeek',
|
||||
'minimax': 'MiniMax', 'google': 'Google', 'meta-llama': 'Meta Llama',
|
||||
'huggingface': 'HuggingFace', 'alibaba': 'Alibaba',
|
||||
'ollama': 'Ollama', 'lmstudio': 'LM Studio',
|
||||
}
|
||||
|
||||
# Well-known models per provider (used to populate dropdown for direct API providers)
|
||||
@@ -295,9 +297,12 @@ _PROVIDER_MODELS = {
|
||||
{'id': 'gemini-2.5-pro', 'label': 'Gemini 2.5 Pro (via Nous)'},
|
||||
],
|
||||
'zai': [
|
||||
{'id': 'glm-4-plus', 'label': 'GLM-4 Plus'},
|
||||
{'id': 'glm-4-air', 'label': 'GLM-4 Air'},
|
||||
{'id': 'glm-z1-flash', 'label': 'GLM-Z1 Flash'},
|
||||
{'id': 'glm-5.1', 'label': 'GLM-5.1'},
|
||||
{'id': 'glm-5', 'label': 'GLM-5'},
|
||||
{'id': 'glm-5-turbo', 'label': 'GLM-5 Turbo'},
|
||||
{'id': 'glm-4.7', 'label': 'GLM-4.7'},
|
||||
{'id': 'glm-4.5', 'label': 'GLM-4.5'},
|
||||
{'id': 'glm-4.5-flash', 'label': 'GLM-4.5 Flash'},
|
||||
],
|
||||
'kimi-coding': [
|
||||
{'id': 'moonshot-v1-8k', 'label': 'Moonshot v1 8k'},
|
||||
@@ -306,12 +311,53 @@ _PROVIDER_MODELS = {
|
||||
{'id': 'kimi-latest', 'label': 'Kimi Latest'},
|
||||
],
|
||||
'minimax': [
|
||||
{'id': 'abab6.5s-chat', 'label': 'MiniMax ABAB 6.5S'},
|
||||
{'id': 'abab6.5g-chat', 'label': 'MiniMax ABAB 6.5G'},
|
||||
{'id': 'MiniMax-M2.7', 'label': 'MiniMax M2.7'},
|
||||
{'id': 'MiniMax-M2.7-highspeed', 'label': 'MiniMax M2.7 Highspeed'},
|
||||
{'id': 'MiniMax-M2.5', 'label': 'MiniMax M2.5'},
|
||||
{'id': 'MiniMax-M2.5-highspeed', 'label': 'MiniMax M2.5 Highspeed'},
|
||||
{'id': 'MiniMax-M2.1', 'label': 'MiniMax M2.1'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def resolve_model_provider(model_id: str):
|
||||
"""Resolve bare model name, provider, and base_url for AIAgent.
|
||||
|
||||
Model IDs from the dropdown may include a provider prefix
|
||||
(e.g. 'anthropic/claude-sonnet-4.6'). Direct-API providers expect
|
||||
bare model names, while OpenRouter expects the full provider/model path.
|
||||
|
||||
Also reads base_url from config.yaml so providers with custom endpoints
|
||||
(e.g. MiniMax, Z.AI) are routed correctly.
|
||||
|
||||
Returns (model, provider, base_url) where provider and base_url may be None.
|
||||
"""
|
||||
config_provider = None
|
||||
config_base_url = None
|
||||
model_cfg = cfg.get('model', {})
|
||||
if isinstance(model_cfg, dict):
|
||||
config_provider = model_cfg.get('provider')
|
||||
config_base_url = model_cfg.get('base_url')
|
||||
|
||||
model_id = (model_id or '').strip()
|
||||
if not model_id:
|
||||
return model_id, config_provider, config_base_url
|
||||
|
||||
if '/' in model_id:
|
||||
prefix, bare = model_id.split('/', 1)
|
||||
# If prefix matches config provider, strip it and use that provider directly
|
||||
if config_provider and prefix == config_provider:
|
||||
return bare, config_provider, config_base_url
|
||||
# If the config provider is openrouter (or unset/None), pass the full
|
||||
# provider/model string through -- OpenRouter uses this as its model ID.
|
||||
# Only strip the prefix and switch to a direct-API provider when the
|
||||
# config is explicitly set to that direct provider.
|
||||
if config_provider and config_provider != 'openrouter' and prefix in _PROVIDER_MODELS:
|
||||
return bare, prefix, None
|
||||
|
||||
return model_id, config_provider, config_base_url
|
||||
|
||||
|
||||
def get_available_models() -> dict:
|
||||
"""
|
||||
Return available models grouped by provider.
|
||||
@@ -319,7 +365,8 @@ def get_available_models() -> dict:
|
||||
Discovery order:
|
||||
1. Read config.yaml 'model' section for active provider info
|
||||
2. Check for known API keys in env or ~/.hermes/.env
|
||||
3. Fall back to hardcoded model list (OpenRouter-style)
|
||||
3. Fetch models from custom endpoint if base_url is configured
|
||||
4. Fall back to hardcoded model list (OpenRouter-style)
|
||||
|
||||
Returns: {
|
||||
'active_provider': str|None,
|
||||
@@ -338,6 +385,7 @@ def get_available_models() -> dict:
|
||||
elif isinstance(model_cfg, dict):
|
||||
active_provider = model_cfg.get('provider')
|
||||
cfg_default = model_cfg.get('default', '')
|
||||
cfg_base_url = model_cfg.get('base_url', '')
|
||||
if cfg_default:
|
||||
default_model = cfg_default
|
||||
|
||||
@@ -398,6 +446,73 @@ def get_available_models() -> dict:
|
||||
if all_env.get('DEEPSEEK_API_KEY'):
|
||||
detected_providers.add('deepseek')
|
||||
|
||||
# 3. Fetch models from custom endpoint if base_url is configured
|
||||
auto_detected_models = []
|
||||
if cfg_base_url:
|
||||
try:
|
||||
import ipaddress
|
||||
import urllib.request
|
||||
|
||||
# Normalize the base_url and build models endpoint
|
||||
base_url = cfg_base_url.strip()
|
||||
if base_url.endswith('/v1'):
|
||||
endpoint_url = base_url[:-3] + '/models'
|
||||
else:
|
||||
endpoint_url = base_url + '/v1/models'
|
||||
|
||||
# Detect provider from base_url
|
||||
provider = 'custom'
|
||||
parsed = urlparse(base_url if '://' in base_url else f'http://{base_url}')
|
||||
host = (parsed.netloc or parsed.path).lower()
|
||||
|
||||
if parsed.hostname:
|
||||
try:
|
||||
addr = ipaddress.ip_address(parsed.hostname)
|
||||
if addr.is_private or addr.is_loopback or addr.is_link_local:
|
||||
if 'ollama' in host or '127.0.0.1' in host or 'localhost' in host:
|
||||
provider = 'ollama'
|
||||
elif 'lmstudio' in host or 'lm-studio' in host:
|
||||
provider = 'lmstudio'
|
||||
else:
|
||||
provider = 'local'
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Resolve API key from environment
|
||||
headers = {}
|
||||
api_key_vars = ('HERMES_API_KEY', 'HERMES_OPENAI_API_KEY', 'OPENAI_API_KEY',
|
||||
'LOCAL_API_KEY', 'OPENROUTER_API_KEY', 'API_KEY')
|
||||
for key in api_key_vars:
|
||||
api_key = os.getenv(key)
|
||||
if api_key:
|
||||
headers['Authorization'] = f'Bearer {api_key}'
|
||||
break
|
||||
|
||||
# Fetch model list from endpoint
|
||||
req = urllib.request.Request(endpoint_url, method='GET')
|
||||
for k, v in headers.items():
|
||||
req.add_header(k, v)
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
data = json.loads(response.read().decode('utf-8'))
|
||||
|
||||
# Handle both OpenAI-compatible and llama.cpp response formats
|
||||
models_list = []
|
||||
if 'data' in data and isinstance(data['data'], list):
|
||||
models_list = data['data']
|
||||
elif 'models' in data and isinstance(data['models'], list):
|
||||
models_list = data['models']
|
||||
|
||||
for model in models_list:
|
||||
if not isinstance(model, dict):
|
||||
continue
|
||||
model_id = model.get('id', '') or model.get('name', '') or model.get('model', '')
|
||||
model_name = model.get('name', '') or model.get('model', '') or model_id
|
||||
if model_id and model_name:
|
||||
auto_detected_models.append({'id': model_id, 'label': model_name})
|
||||
detected_providers.add(provider.lower())
|
||||
except Exception as e:
|
||||
logger.debug(f"Failed to fetch models from custom endpoint: {e}")
|
||||
|
||||
# 5. Build model groups
|
||||
if detected_providers:
|
||||
for pid in sorted(detected_providers):
|
||||
@@ -414,11 +529,18 @@ def get_available_models() -> dict:
|
||||
'models': _PROVIDER_MODELS[pid],
|
||||
})
|
||||
else:
|
||||
# Unknown provider with key -- add a placeholder with the default model
|
||||
groups.append({
|
||||
'provider': provider_name,
|
||||
'models': [{'id': default_model, 'label': default_model.split('/')[-1]}],
|
||||
})
|
||||
# Unknown provider -- use auto-detected models if available,
|
||||
# otherwise fall back to default model placeholder
|
||||
if auto_detected_models:
|
||||
groups.append({
|
||||
'provider': provider_name,
|
||||
'models': auto_detected_models,
|
||||
})
|
||||
else:
|
||||
groups.append({
|
||||
'provider': provider_name,
|
||||
'models': [{'id': default_model, 'label': default_model.split('/')[-1]}],
|
||||
})
|
||||
else:
|
||||
# No providers detected -- use fallback grouped list
|
||||
by_provider = {}
|
||||
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
import api.config as _cfg
|
||||
from api.config import (
|
||||
SESSION_DIR, SESSION_INDEX_FILE, SESSIONS, SESSIONS_MAX,
|
||||
LOCK, DEFAULT_WORKSPACE, DEFAULT_MODEL
|
||||
LOCK, DEFAULT_WORKSPACE, DEFAULT_MODEL, PROJECTS_FILE
|
||||
)
|
||||
from api.workspace import get_last_workspace
|
||||
|
||||
@@ -34,8 +34,8 @@ def _write_session_index():
|
||||
|
||||
|
||||
class Session:
|
||||
def __init__(self, session_id=None, title='Untitled', workspace=str(DEFAULT_WORKSPACE), model=DEFAULT_MODEL, messages=None, created_at=None, updated_at=None, tool_calls=None, pinned=False, archived=False, **kwargs):
|
||||
self.session_id = session_id or uuid.uuid4().hex[:12]; self.title = title; self.workspace = str(Path(workspace).expanduser().resolve()); self.model = model; self.messages = messages or []; self.tool_calls = tool_calls or []; self.created_at = created_at or time.time(); self.updated_at = updated_at or time.time(); self.pinned = bool(pinned); self.archived = bool(archived)
|
||||
def __init__(self, session_id=None, title='Untitled', workspace=str(DEFAULT_WORKSPACE), model=DEFAULT_MODEL, messages=None, created_at=None, updated_at=None, tool_calls=None, pinned=False, archived=False, project_id=None, **kwargs):
|
||||
self.session_id = session_id or uuid.uuid4().hex[:12]; self.title = title; self.workspace = str(Path(workspace).expanduser().resolve()); self.model = model; self.messages = messages or []; self.tool_calls = tool_calls or []; self.created_at = created_at or time.time(); self.updated_at = updated_at or time.time(); self.pinned = bool(pinned); self.archived = bool(archived); self.project_id = project_id or None
|
||||
@property
|
||||
def path(self): return SESSION_DIR / f'{self.session_id}.json'
|
||||
def save(self): self.updated_at = time.time(); self.path.write_text(json.dumps(self.__dict__, ensure_ascii=False, indent=2), encoding='utf-8'); _write_session_index()
|
||||
@@ -44,7 +44,7 @@ class Session:
|
||||
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): return {'session_id': self.session_id, 'title': self.title, 'workspace': self.workspace, 'model': self.model, 'message_count': len(self.messages), 'created_at': self.created_at, 'updated_at': self.updated_at, 'pinned': self.pinned, 'archived': self.archived}
|
||||
def compact(self): return {'session_id': self.session_id, 'title': self.title, 'workspace': self.workspace, 'model': self.model, 'message_count': len(self.messages), 'created_at': self.created_at, 'updated_at': self.updated_at, 'pinned': self.pinned, 'archived': self.archived, 'project_id': self.project_id}
|
||||
|
||||
def get_session(sid):
|
||||
with LOCK:
|
||||
@@ -114,3 +114,19 @@ def title_from(messages, fallback='Untitled'):
|
||||
if text:
|
||||
return text[:64]
|
||||
return fallback
|
||||
|
||||
|
||||
# ── Project helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
def load_projects():
|
||||
"""Load project list from disk. Returns list of project dicts."""
|
||||
if not PROJECTS_FILE.exists():
|
||||
return []
|
||||
try:
|
||||
return json.loads(PROJECTS_FILE.read_text(encoding='utf-8'))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def save_projects(projects):
|
||||
"""Write project list to disk."""
|
||||
PROJECTS_FILE.write_text(json.dumps(projects, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -23,6 +23,7 @@ from api.helpers import require, bad, safe_resolve, j, t, read_body
|
||||
from api.models import (
|
||||
Session, get_session, new_session, all_sessions, title_from,
|
||||
_write_session_index, SESSION_INDEX_FILE,
|
||||
load_projects, save_projects,
|
||||
)
|
||||
from api.workspace import (
|
||||
load_workspaces, save_workspaces, get_last_workspace, set_last_workspace,
|
||||
@@ -93,6 +94,9 @@ def handle_get(handler, parsed):
|
||||
if parsed.path == '/api/sessions':
|
||||
return j(handler, {'sessions': all_sessions()})
|
||||
|
||||
if parsed.path == '/api/projects':
|
||||
return j(handler, {'projects': load_projects()})
|
||||
|
||||
if parsed.path == '/api/session/export':
|
||||
return _handle_session_export(handler, parsed)
|
||||
|
||||
@@ -129,11 +133,13 @@ def handle_get(handler, parsed):
|
||||
return _handle_approval_pending(handler, parsed)
|
||||
|
||||
if parsed.path == '/api/approval/inject_test':
|
||||
# Loopback-only: used by automated tests; blocked from any remote client
|
||||
if handler.client_address[0] != '127.0.0.1':
|
||||
return j(handler, {'error': 'not found'}, status=404)
|
||||
return _handle_approval_inject(handler, parsed)
|
||||
|
||||
# ── Cron API (GET) ──
|
||||
if parsed.path == '/api/crons':
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
from cron.jobs import list_jobs
|
||||
return j(handler, {'jobs': list_jobs(include_disabled=True)})
|
||||
|
||||
@@ -324,6 +330,72 @@ def handle_post(handler, parsed):
|
||||
s.save()
|
||||
return j(handler, {'ok': True, 'session': s.compact()})
|
||||
|
||||
# ── Session move to project (POST) ──
|
||||
if parsed.path == '/api/session/move':
|
||||
try: require(body, 'session_id')
|
||||
except ValueError as e: return bad(handler, str(e))
|
||||
try: s = get_session(body['session_id'])
|
||||
except KeyError: return bad(handler, 'Session not found', 404)
|
||||
s.project_id = body.get('project_id') or None
|
||||
s.save()
|
||||
return j(handler, {'ok': True, 'session': s.compact()})
|
||||
|
||||
# ── Project CRUD (POST) ──
|
||||
if parsed.path == '/api/projects/create':
|
||||
try: require(body, 'name')
|
||||
except ValueError as e: return bad(handler, str(e))
|
||||
import re as _re
|
||||
name = body['name'].strip()[:128]
|
||||
if not name: return bad(handler, 'name required')
|
||||
color = body.get('color')
|
||||
if color and not _re.match(r'^#[0-9a-fA-F]{3,8}$', color):
|
||||
return bad(handler, 'Invalid color format')
|
||||
projects = load_projects()
|
||||
proj = {'project_id': uuid.uuid4().hex[:12], 'name': name, 'color': color, 'created_at': time.time()}
|
||||
projects.append(proj)
|
||||
save_projects(projects)
|
||||
return j(handler, {'ok': True, 'project': proj})
|
||||
|
||||
if parsed.path == '/api/projects/rename':
|
||||
try: require(body, 'project_id', 'name')
|
||||
except ValueError as e: return bad(handler, str(e))
|
||||
import re as _re
|
||||
projects = load_projects()
|
||||
proj = next((p for p in projects if p['project_id'] == body['project_id']), None)
|
||||
if not proj: return bad(handler, 'Project not found', 404)
|
||||
proj['name'] = body['name'].strip()[:128]
|
||||
if 'color' in body:
|
||||
color = body['color']
|
||||
if color and not _re.match(r'^#[0-9a-fA-F]{3,8}$', color):
|
||||
return bad(handler, 'Invalid color format')
|
||||
proj['color'] = color
|
||||
save_projects(projects)
|
||||
return j(handler, {'ok': True, 'project': proj})
|
||||
|
||||
if parsed.path == '/api/projects/delete':
|
||||
try: require(body, 'project_id')
|
||||
except ValueError as e: return bad(handler, str(e))
|
||||
projects = load_projects()
|
||||
proj = next((p for p in projects if p['project_id'] == body['project_id']), None)
|
||||
if not proj: return bad(handler, 'Project not found', 404)
|
||||
projects = [p for p in projects if p['project_id'] != body['project_id']]
|
||||
save_projects(projects)
|
||||
# Unassign all sessions that belonged to this project
|
||||
if SESSION_INDEX_FILE.exists():
|
||||
try:
|
||||
index = json.loads(SESSION_INDEX_FILE.read_text(encoding='utf-8'))
|
||||
for entry in index:
|
||||
if entry.get('project_id') == body['project_id']:
|
||||
try:
|
||||
s = get_session(entry['session_id'])
|
||||
s.project_id = None
|
||||
s.save()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return j(handler, {'ok': True})
|
||||
|
||||
# ── Session import from JSON (POST) ──
|
||||
if parsed.path == '/api/session/import':
|
||||
return _handle_session_import(handler, body)
|
||||
@@ -334,7 +406,14 @@ def handle_post(handler, parsed):
|
||||
# ── GET route helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
def _serve_static(handler, parsed):
|
||||
static_file = Path(__file__).parent.parent / parsed.path.lstrip('/')
|
||||
static_root = (Path(__file__).parent.parent / 'static').resolve()
|
||||
# Strip the leading '/static/' prefix, then resolve and sandbox
|
||||
rel = parsed.path[len('/static/'):]
|
||||
static_file = (static_root / rel).resolve()
|
||||
try:
|
||||
static_file.relative_to(static_root)
|
||||
except ValueError:
|
||||
return j(handler, {'error': 'not found'}, status=404)
|
||||
if not static_file.exists() or not static_file.is_file():
|
||||
return j(handler, {'error': 'not found'}, status=404)
|
||||
ext = static_file.suffix.lower()
|
||||
@@ -486,6 +565,7 @@ def _handle_approval_pending(handler, parsed):
|
||||
|
||||
|
||||
def _handle_approval_inject(handler, parsed):
|
||||
"""Inject a fake pending approval -- loopback-only, used by automated tests."""
|
||||
qs = parse_qs(parsed.query)
|
||||
sid = qs.get('session_id', [''])[0]
|
||||
key = qs.get('pattern_key', ['test_pattern'])[0]
|
||||
@@ -524,7 +604,6 @@ def _handle_cron_recent(handler, parsed):
|
||||
qs = parse_qs(parsed.query)
|
||||
since = float(qs.get('since', ['0'])[0])
|
||||
try:
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
from cron.jobs import list_jobs
|
||||
jobs = list_jobs(include_disabled=True)
|
||||
completions = []
|
||||
@@ -629,7 +708,10 @@ def _handle_chat_sync(handler, body):
|
||||
try:
|
||||
from run_agent import AIAgent
|
||||
with CHAT_LOCK:
|
||||
agent = AIAgent(model=s.model, platform='cli', quiet_mode=True,
|
||||
from api.config import resolve_model_provider
|
||||
_model, _provider, _base_url = resolve_model_provider(s.model)
|
||||
agent = AIAgent(model=_model, provider=_provider, base_url=_base_url,
|
||||
platform='cli', quiet_mode=True,
|
||||
enabled_toolsets=CLI_TOOLSETS, session_id=s.session_id)
|
||||
workspace_ctx = f"[Workspace: {s.workspace}]\n"
|
||||
workspace_system_msg = (
|
||||
@@ -868,6 +950,8 @@ def _handle_skill_save(handler, body):
|
||||
if not skill_name or '/' in skill_name or '..' in skill_name:
|
||||
return bad(handler, 'Invalid skill name')
|
||||
category = body.get('category', '').strip()
|
||||
if category and ('/' in category or '..' in category):
|
||||
return bad(handler, 'Invalid category')
|
||||
from tools.skills_tool import SKILLS_DIR
|
||||
if category:
|
||||
skill_dir = SKILLS_DIR / category / skill_name
|
||||
|
||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
||||
from api.config import (
|
||||
STREAMS, STREAMS_LOCK, CANCEL_FLAGS, CLI_TOOLSETS,
|
||||
_get_session_agent_lock, _set_thread_env, _clear_thread_env,
|
||||
resolve_model_provider,
|
||||
)
|
||||
|
||||
# Lazy import to avoid circular deps -- hermes-agent is on sys.path via api/config.py
|
||||
@@ -99,8 +100,11 @@ def _run_agent_streaming(session_id, msg_text, model, workspace, stream_id, atta
|
||||
|
||||
if AIAgent is None:
|
||||
raise ImportError("AIAgent not available -- check that hermes-agent is on sys.path")
|
||||
resolved_model, resolved_provider, resolved_base_url = resolve_model_provider(model)
|
||||
agent = AIAgent(
|
||||
model=model,
|
||||
model=resolved_model,
|
||||
provider=resolved_provider,
|
||||
base_url=resolved_base_url,
|
||||
platform='cli',
|
||||
quiet_mode=True,
|
||||
enabled_toolsets=CLI_TOOLSETS,
|
||||
|
||||
@@ -2,7 +2,7 @@ async function cancelStream(){
|
||||
const streamId = S.activeStreamId;
|
||||
if(!streamId) return;
|
||||
try{
|
||||
await fetch(`/api/chat/cancel?stream_id=${encodeURIComponent(streamId)}`);
|
||||
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);}
|
||||
|
||||
@@ -6,14 +6,14 @@
|
||||
<title>Hermes</title>
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<!-- 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">
|
||||
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js" defer></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js" defer></script>
|
||||
<link 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.2</div></div></div>
|
||||
<div class="sidebar-header"><div class="logo">H</div><div><h1 style="margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em">Hermes</h1><div style="font-size:10px;color:var(--muted);opacity:.8;margin-top:1px">v0.17.1</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>
|
||||
|
||||
@@ -169,7 +169,7 @@ async function send(){
|
||||
const st=await api(`/api/chat/stream/status?stream_id=${encodeURIComponent(streamId)}`);
|
||||
if(st.active){
|
||||
setStatus('Reconnected');
|
||||
_wireSSE(new EventSource(`/api/chat/stream?stream_id=${encodeURIComponent(streamId)}`));
|
||||
_wireSSE(new EventSource(new URL(`/api/chat/stream?stream_id=${encodeURIComponent(streamId)}`,location.origin).href,{withCredentials:true}));
|
||||
return;
|
||||
}
|
||||
}catch(_){}
|
||||
@@ -214,7 +214,7 @@ async function send(){
|
||||
if(!S.session||!INFLIGHT[S.session.session_id]){setBusy(false);setStatus('Error: Connection lost');}
|
||||
}
|
||||
|
||||
_wireSSE(new EventSource(`/api/chat/stream?stream_id=${encodeURIComponent(streamId)}`));
|
||||
_wireSSE(new EventSource(new URL(`/api/chat/stream?stream_id=${encodeURIComponent(streamId)}`,location.origin).href,{withCredentials:true}));
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -56,12 +56,18 @@ async function loadSession(sid){
|
||||
let _allSessions = []; // cached for search filter
|
||||
let _renamingSid = null; // session_id currently being renamed (blocks list re-renders)
|
||||
let _showArchived = false; // toggle to show archived sessions
|
||||
let _allProjects = []; // cached project list
|
||||
let _activeProject = null; // project_id filter (null = show all)
|
||||
|
||||
async function renderSessionList(){
|
||||
try{
|
||||
if(!($('sessionSearch').value||'').trim()) _contentSearchResults = [];
|
||||
const data=await api('/api/sessions');
|
||||
_allSessions = data.sessions||[];
|
||||
const [sessData, projData] = await Promise.all([
|
||||
api('/api/sessions'),
|
||||
api('/api/projects'),
|
||||
]);
|
||||
_allSessions = sessData.sessions||[];
|
||||
_allProjects = projData.projects||[];
|
||||
renderSessionListFromCache(); // no-ops if rename is in progress
|
||||
}catch(e){console.warn('renderSessionList',e);}
|
||||
}
|
||||
@@ -94,10 +100,49 @@ function renderSessionListFromCache(){
|
||||
// Merge content matches (deduped): content matches appended after title matches
|
||||
const titleIds=new Set(titleMatches.map(s=>s.session_id));
|
||||
const allMatched=q?[...titleMatches,..._contentSearchResults.filter(s=>!titleIds.has(s.session_id))]:titleMatches;
|
||||
// Filter by active project
|
||||
const projectFiltered=_activeProject?allMatched.filter(s=>s.project_id===_activeProject):allMatched;
|
||||
// Filter archived unless toggle is on
|
||||
const sessions=_showArchived?allMatched:allMatched.filter(s=>!s.archived);
|
||||
const archivedCount=allMatched.filter(s=>s.archived).length;
|
||||
const sessions=_showArchived?projectFiltered:projectFiltered.filter(s=>!s.archived);
|
||||
const archivedCount=projectFiltered.filter(s=>s.archived).length;
|
||||
const list=$('sessionList');list.innerHTML='';
|
||||
// Project filter bar (only when projects exist)
|
||||
if(_allProjects.length>0){
|
||||
const bar=document.createElement('div');
|
||||
bar.className='project-bar';
|
||||
// "All" chip
|
||||
const allChip=document.createElement('span');
|
||||
allChip.className='project-chip'+(!_activeProject?' active':'');
|
||||
allChip.textContent='All';
|
||||
allChip.onclick=()=>{_activeProject=null;renderSessionListFromCache();};
|
||||
bar.appendChild(allChip);
|
||||
// Project chips
|
||||
for(const p of _allProjects){
|
||||
const chip=document.createElement('span');
|
||||
chip.className='project-chip'+(p.project_id===_activeProject?' active':'');
|
||||
if(p.color){
|
||||
const dot=document.createElement('span');
|
||||
dot.className='color-dot';
|
||||
dot.style.background=p.color;
|
||||
chip.appendChild(dot);
|
||||
}
|
||||
const nameSpan=document.createElement('span');
|
||||
nameSpan.textContent=p.name;
|
||||
chip.appendChild(nameSpan);
|
||||
chip.onclick=()=>{_activeProject=p.project_id;renderSessionListFromCache();};
|
||||
chip.ondblclick=(e)=>{e.stopPropagation();_startProjectRename(p,chip);};
|
||||
chip.oncontextmenu=(e)=>{e.preventDefault();_confirmDeleteProject(p);};
|
||||
bar.appendChild(chip);
|
||||
}
|
||||
// Create button
|
||||
const addBtn=document.createElement('button');
|
||||
addBtn.className='project-create-btn';
|
||||
addBtn.textContent='+';
|
||||
addBtn.title='New project';
|
||||
addBtn.onclick=(e)=>{e.stopPropagation();_startProjectCreate(bar,addBtn);};
|
||||
bar.appendChild(addBtn);
|
||||
list.appendChild(bar);
|
||||
}
|
||||
// Show/hide archived toggle if there are archived sessions
|
||||
if(archivedCount>0){
|
||||
const toggle=document.createElement('div');
|
||||
@@ -106,6 +151,13 @@ function renderSessionListFromCache(){
|
||||
toggle.onclick=()=>{_showArchived=!_showArchived;renderSessionListFromCache();};
|
||||
list.appendChild(toggle);
|
||||
}
|
||||
// Empty state for active project filter
|
||||
if(_activeProject&&sessions.length===0){
|
||||
const empty=document.createElement('div');
|
||||
empty.style.cssText='padding:20px 14px;color:var(--muted);font-size:12px;text-align:center;opacity:.7;';
|
||||
empty.textContent='No sessions in this project yet.';
|
||||
list.appendChild(empty);
|
||||
}
|
||||
// Separate pinned from unpinned
|
||||
const pinned=sessions.filter(s=>s.pinned);
|
||||
const unpinned=sessions.filter(s=>!s.pinned);
|
||||
@@ -233,7 +285,22 @@ function renderSessionListFromCache(){
|
||||
const trash=document.createElement('button');
|
||||
trash.className='session-trash';trash.innerHTML='🗑';trash.title='Delete';
|
||||
trash.onclick=async(e)=>{e.stopPropagation();e.preventDefault();await deleteSession(s.session_id);};
|
||||
el.appendChild(pin);el.appendChild(title);el.appendChild(archive);el.appendChild(dup);el.appendChild(trash);
|
||||
// Project move button (folder icon)
|
||||
const move=document.createElement('button');
|
||||
move.className='session-action-btn'+(s.project_id?' has-project':'');move.innerHTML='📂';move.title='Move to project';
|
||||
move.onclick=async(e)=>{e.stopPropagation();e.preventDefault();_showProjectPicker(s,move);};
|
||||
// Project dot indicator
|
||||
if(s.project_id){
|
||||
const proj=_allProjects.find(p=>p.project_id===s.project_id);
|
||||
if(proj){
|
||||
const dot=document.createElement('span');
|
||||
dot.className='session-project-dot';
|
||||
dot.style.background=proj.color||'var(--blue)';
|
||||
dot.title=proj.name;
|
||||
title.appendChild(dot);
|
||||
}
|
||||
}
|
||||
el.appendChild(pin);el.appendChild(title);el.appendChild(move);el.appendChild(archive);el.appendChild(dup);el.appendChild(trash);
|
||||
|
||||
// Use a click timer to distinguish single-click (navigate) from double-click (rename).
|
||||
// This prevents loadSession from firing on the first click of a double-click,
|
||||
@@ -241,7 +308,7 @@ function renderSessionListFromCache(){
|
||||
let _clickTimer=null;
|
||||
el.onclick=async(e)=>{
|
||||
if(_renamingSid) return; // ignore while any rename is active
|
||||
if([trash,dup,archive].some(b=>e.target===b||b.contains(e.target))) return;
|
||||
if([trash,dup,archive,move].some(b=>e.target===b||b.contains(e.target))) return;
|
||||
clearTimeout(_clickTimer);
|
||||
_clickTimer=setTimeout(async()=>{
|
||||
_clickTimer=null;
|
||||
@@ -284,4 +351,145 @@ async function deleteSession(sid){
|
||||
await renderSessionList();
|
||||
}
|
||||
|
||||
// ── Project helpers ─────────────────────────────────────────────────────
|
||||
|
||||
const PROJECT_COLORS=['#7cb9ff','#f5c542','#e94560','#50c878','#c084fc','#fb923c','#67e8f9','#f472b6'];
|
||||
|
||||
function _showProjectPicker(session, anchorEl){
|
||||
// Close any existing picker
|
||||
document.querySelectorAll('.project-picker').forEach(p=>p.remove());
|
||||
const picker=document.createElement('div');
|
||||
picker.className='project-picker';
|
||||
// Close on outside click
|
||||
const close=(e)=>{if(!picker.contains(e.target)&&e.target!==anchorEl){picker.remove();document.removeEventListener('click',close);}};
|
||||
// "No project" option
|
||||
const none=document.createElement('div');
|
||||
none.className='project-picker-item'+(!session.project_id?' active':'');
|
||||
none.textContent='No project';
|
||||
none.onclick=async()=>{
|
||||
document.removeEventListener('click',close);
|
||||
picker.remove();
|
||||
await api('/api/session/move',{method:'POST',body:JSON.stringify({session_id:session.session_id,project_id:null})});
|
||||
session.project_id=null;
|
||||
renderSessionListFromCache();
|
||||
showToast('Removed from project');
|
||||
};
|
||||
picker.appendChild(none);
|
||||
// Project options
|
||||
for(const p of _allProjects){
|
||||
const item=document.createElement('div');
|
||||
item.className='project-picker-item'+(session.project_id===p.project_id?' active':'');
|
||||
if(p.color){
|
||||
const dot=document.createElement('span');
|
||||
dot.className='color-dot';
|
||||
dot.style.cssText='width:6px;height:6px;border-radius:50%;background:'+p.color+';flex-shrink:0;';
|
||||
item.appendChild(dot);
|
||||
}
|
||||
const name=document.createElement('span');
|
||||
name.textContent=p.name;
|
||||
item.appendChild(name);
|
||||
item.onclick=async()=>{
|
||||
document.removeEventListener('click',close);
|
||||
picker.remove();
|
||||
await api('/api/session/move',{method:'POST',body:JSON.stringify({session_id:session.session_id,project_id:p.project_id})});
|
||||
session.project_id=p.project_id;
|
||||
renderSessionListFromCache();
|
||||
showToast('Moved to '+p.name);
|
||||
};
|
||||
picker.appendChild(item);
|
||||
}
|
||||
// "+ New project" item
|
||||
const createItem=document.createElement('div');
|
||||
createItem.className='project-picker-item project-picker-create';
|
||||
createItem.textContent='+ New project';
|
||||
createItem.onclick=async()=>{
|
||||
picker.remove();
|
||||
document.removeEventListener('click',close);
|
||||
const name=prompt('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})});
|
||||
if(res.project){
|
||||
_allProjects.push(res.project);
|
||||
await api('/api/session/move',{method:'POST',body:JSON.stringify({session_id:session.session_id,project_id:res.project.project_id})});
|
||||
session.project_id=res.project.project_id;
|
||||
await renderSessionList();
|
||||
showToast('Created "'+res.project.name+'" and moved session');
|
||||
}
|
||||
};
|
||||
picker.appendChild(createItem);
|
||||
// Position picker on document.body to avoid overflow:hidden clipping
|
||||
document.body.appendChild(picker);
|
||||
const rect=anchorEl.getBoundingClientRect();
|
||||
picker.style.position='fixed';
|
||||
picker.style.zIndex='999';
|
||||
const spaceBelow=window.innerHeight-rect.bottom;
|
||||
if(spaceBelow<160&&rect.top>160){
|
||||
picker.style.bottom=(window.innerHeight-rect.top+4)+'px';
|
||||
picker.style.top='auto';
|
||||
}else{
|
||||
picker.style.top=(rect.bottom+4)+'px';
|
||||
picker.style.bottom='auto';
|
||||
}
|
||||
const pickerW=160;
|
||||
let left=rect.right-pickerW;
|
||||
if(left<8) left=8;
|
||||
picker.style.left=left+'px';
|
||||
setTimeout(()=>document.addEventListener('click',close),0);
|
||||
}
|
||||
|
||||
function _startProjectCreate(bar, addBtn){
|
||||
const inp=document.createElement('input');
|
||||
inp.className='project-create-input';
|
||||
inp.placeholder='Project name';
|
||||
const finish=async(save)=>{
|
||||
if(save&&inp.value.trim()){
|
||||
const color=PROJECT_COLORS[_allProjects.length%PROJECT_COLORS.length];
|
||||
await api('/api/projects/create',{method:'POST',body:JSON.stringify({name:inp.value.trim(),color})});
|
||||
await renderSessionList();
|
||||
showToast('Project created');
|
||||
}else{
|
||||
inp.replaceWith(addBtn);
|
||||
}
|
||||
};
|
||||
inp.onkeydown=(e)=>{
|
||||
if(e.key==='Enter'){e.preventDefault();finish(true);}
|
||||
if(e.key==='Escape'){e.preventDefault();finish(false);}
|
||||
};
|
||||
inp.onblur=()=>finish(false);
|
||||
addBtn.replaceWith(inp);
|
||||
setTimeout(()=>inp.focus(),10);
|
||||
}
|
||||
|
||||
function _startProjectRename(proj, chip){
|
||||
const inp=document.createElement('input');
|
||||
inp.className='project-create-input';
|
||||
inp.value=proj.name;
|
||||
const finish=async(save)=>{
|
||||
if(save&&inp.value.trim()&&inp.value.trim()!==proj.name){
|
||||
await api('/api/projects/rename',{method:'POST',body:JSON.stringify({project_id:proj.project_id,name:inp.value.trim()})});
|
||||
await renderSessionList();
|
||||
showToast('Project renamed');
|
||||
}else{
|
||||
renderSessionListFromCache();
|
||||
}
|
||||
};
|
||||
inp.onkeydown=(e)=>{
|
||||
if(e.key==='Enter'){e.preventDefault();finish(true);}
|
||||
if(e.key==='Escape'){e.preventDefault();finish(false);}
|
||||
};
|
||||
inp.onblur=()=>finish(false);
|
||||
inp.onclick=(e)=>e.stopPropagation();
|
||||
chip.replaceWith(inp);
|
||||
setTimeout(()=>{inp.focus();inp.select();},10);
|
||||
}
|
||||
|
||||
async function _confirmDeleteProject(proj){
|
||||
if(!confirm('Delete project "'+proj.name+'"? Sessions will be unassigned but not deleted.')){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');
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
--text:#e8e8f0;--muted:#8888aa;--accent:#e94560;--blue:#7cb9ff;--gold:#c9a84c;--code-bg:#0d1117;
|
||||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;font-size:14px;line-height:1.6;
|
||||
}
|
||||
body{background:var(--bg);color:var(--text);height:100vh;overflow:hidden;display:flex;}
|
||||
.layout{display:flex;width:100%;height:100vh;}
|
||||
body{background:var(--bg);color:var(--text);height:100vh;height:100dvh;overflow:hidden;display:flex;}
|
||||
.layout{display:flex;width:100%;height:100vh;height:100dvh;}
|
||||
.sidebar{width:300px;background:var(--sidebar);border-right:1px solid var(--border);display:flex;flex-direction:column;overflow:hidden;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);}
|
||||
@@ -235,7 +235,39 @@
|
||||
::-webkit-scrollbar-track{background:transparent}
|
||||
::-webkit-scrollbar-thumb{background:rgba(255,255,255,.1);border-radius:99px;transition:background .2s}
|
||||
::-webkit-scrollbar-thumb:hover{background:rgba(255,255,255,.22)}
|
||||
@media(max-width:900px){.rightpanel{display:none}}@media(max-width:640px){.sidebar{display:none}}
|
||||
@media(max-width:900px){.rightpanel{display:none}}
|
||||
@media(max-width:640px){
|
||||
.sidebar{display:none}
|
||||
/* Topbar: stack title + chips vertically, allow wrapping */
|
||||
.topbar{padding:8px 12px;gap:6px;flex-wrap:wrap;}
|
||||
.topbar-left{min-width:0;flex:1 1 100%;}
|
||||
.topbar-title{font-size:14px;}
|
||||
.topbar-meta{font-size:10px;}
|
||||
.topbar-chips{flex-wrap:wrap;gap:4px;}
|
||||
.topbar-chips .chip,.topbar-chips .ws-chip,.topbar-chips button{font-size:11px!important;padding:3px 8px!important;}
|
||||
/* Messages area */
|
||||
.messages-inner{padding:12px 10px 20px;}
|
||||
.msg-body{padding-left:0;max-width:100%;}
|
||||
.msg-role{font-size:12px;}
|
||||
/* Composer */
|
||||
.composer-wrap{padding:8px 10px 12px!important;}
|
||||
.composer-box{border-radius:12px;}
|
||||
.composer-box textarea{font-size:16px;min-height:40px;}
|
||||
.send-btn{padding:6px 14px;font-size:13px;}
|
||||
/* Empty state */
|
||||
.empty-state h2{font-size:18px;}
|
||||
.empty-state p{font-size:13px;}
|
||||
.suggestion-grid{max-width:100%!important;}
|
||||
.suggestion-btn{font-size:12px;padding:8px 10px;}
|
||||
/* Approval card */
|
||||
.approval-card{padding:0 10px 8px;}
|
||||
.approval-btns{gap:6px;}
|
||||
.approval-btn{padding:5px 10px;font-size:11px;}
|
||||
/* Tool cards */
|
||||
.tool-card{margin-left:0!important;font-size:12px;}
|
||||
/* Settings modal */
|
||||
.settings-panel{width:95vw;max-width:95vw;}
|
||||
}
|
||||
|
||||
/* ── Workspace dropdown (topbar) ── */
|
||||
.ws-chip{user-select:none;}
|
||||
@@ -472,6 +504,8 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
.session-dup,.session-action-btn{background:none;border:none;color:var(--muted);font-size:11px;cursor:pointer;opacity:0;transition:opacity .15s;padding:2px 4px;flex-shrink:0;}
|
||||
.session-item:hover .session-dup,.session-item:hover .session-action-btn{opacity:1;}
|
||||
.session-dup:hover,.session-action-btn:hover{color:var(--text);}
|
||||
.session-action-btn.has-project{opacity:.6;color:var(--blue);}
|
||||
.session-item:hover .session-action-btn.has-project{opacity:1;}
|
||||
|
||||
/* ── Cron alert badge ── */
|
||||
.cron-badge{position:absolute;top:2px;right:2px;background:#e53e3e;color:#fff;font-size:9px;font-weight:700;min-width:14px;height:14px;line-height:14px;text-align:center;border-radius:7px;padding:0 3px;}
|
||||
@@ -497,4 +531,30 @@ body.resizing{user-select:none;cursor:col-resize;}
|
||||
.mermaid-rendered{background:transparent;padding:8px 0;}
|
||||
.mermaid-rendered svg{max-width:100%;height:auto;}
|
||||
|
||||
/* ── 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: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-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:140px;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);}
|
||||
.project-picker-item.active{color:var(--blue);}
|
||||
.project-picker-create{color:var(--blue);opacity:.7;border-top:1px solid var(--border2);margin-top:2px;padding-top:6px;}
|
||||
.project-picker-create:hover{opacity:1;background:rgba(124,185,255,.08);}
|
||||
.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:hover{background:rgba(255,255,255,.12);color:var(--text);}
|
||||
|
||||
/* ── Tool card expand/collapse toggle ── */
|
||||
.tool-cards-toggle{margin:4px 0 2px 40px;display:flex;gap:8px;}
|
||||
.tool-cards-toggle button{background:none;border:none;color:var(--blue);font-size:10px;cursor:pointer;opacity:.6;padding:0;}
|
||||
.tool-cards-toggle button:hover{opacity:1;text-decoration:underline;}
|
||||
|
||||
.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;}
|
||||
|
||||
78
static/ui.js
78
static/ui.js
@@ -11,7 +11,7 @@ async function populateModelDropdown(){
|
||||
const sel=$('modelSelect');
|
||||
if(!sel) return;
|
||||
try{
|
||||
const data=await fetch('/api/models').then(r=>r.json());
|
||||
const data=await fetch(new URL('/api/models',location.origin).href,{credentials:'include'}).then(r=>r.json());
|
||||
if(!data.groups||!data.groups.length) return; // keep HTML defaults
|
||||
// Clear existing options
|
||||
sel.innerHTML='';
|
||||
@@ -88,12 +88,12 @@ function renderMd(raw){
|
||||
});
|
||||
s=s.replace(/```([\w+-]*)\n?([\s\S]*?)```/g,(_,lang,code)=>{const h=lang?`<div class="pre-header">${esc(lang)}</div>`:'';return `${h}<pre><code>${esc(code.replace(/\n$/,''))}</code></pre>`;});
|
||||
s=s.replace(/`([^`\n]+)`/g,(_,c)=>`<code>${esc(c)}</code>`);
|
||||
s=s.replace(/\*\*\*(.+?)\*\*\*/g,'<strong><em>$1</em></strong>');
|
||||
s=s.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>');
|
||||
s=s.replace(/\*([^*\n]+)\*/g,'<em>$1</em>');
|
||||
s=s.replace(/^### (.+)$/gm,'<h3>$1</h3>').replace(/^## (.+)$/gm,'<h2>$1</h2>').replace(/^# (.+)$/gm,'<h1>$1</h1>');
|
||||
s=s.replace(/\*\*\*(.+?)\*\*\*/g,(_,t)=>`<strong><em>${esc(t)}</em></strong>`);
|
||||
s=s.replace(/\*\*(.+?)\*\*/g,(_,t)=>`<strong>${esc(t)}</strong>`);
|
||||
s=s.replace(/\*([^*\n]+)\*/g,(_,t)=>`<em>${esc(t)}</em>`);
|
||||
s=s.replace(/^### (.+)$/gm,(_,t)=>`<h3>${esc(t)}</h3>`).replace(/^## (.+)$/gm,(_,t)=>`<h2>${esc(t)}</h2>`).replace(/^# (.+)$/gm,(_,t)=>`<h1>${esc(t)}</h1>`);
|
||||
s=s.replace(/^---+$/gm,'<hr>');
|
||||
s=s.replace(/^> (.+)$/gm,'<blockquote>$1</blockquote>');
|
||||
s=s.replace(/^> (.+)$/gm,(_,t)=>`<blockquote>${esc(t)}</blockquote>`);
|
||||
// B8: improved list handling supporting up to 2 levels of indentation
|
||||
s=s.replace(/((?:^(?: )?[-*+] .+\n?)+)/gm,block=>{
|
||||
const lines=block.trimEnd().split('\n');
|
||||
@@ -101,8 +101,8 @@ function renderMd(raw){
|
||||
for(const l of lines){
|
||||
const indent=/^ {2,}/.test(l);
|
||||
const text=l.replace(/^ {0,4}[-*+] /,'');
|
||||
if(indent) html+=`<li style="margin-left:16px">${text}</li>`;
|
||||
else html+=`<li>${text}</li>`;
|
||||
if(indent) html+=`<li style="margin-left:16px">${esc(text)}</li>`;
|
||||
else html+=`<li>${esc(text)}</li>`;
|
||||
}
|
||||
return html+'</ul>';
|
||||
});
|
||||
@@ -111,19 +111,19 @@ function renderMd(raw){
|
||||
let html='<ol>';
|
||||
for(const l of lines){
|
||||
const text=l.replace(/^ {0,4}\d+\. /,'');
|
||||
html+=`<li>${text}</li>`;
|
||||
html+=`<li>${esc(text)}</li>`;
|
||||
}
|
||||
return html+'</ol>';
|
||||
});
|
||||
s=s.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,'<a href="$2" target="_blank" rel="noopener">$1</a>');
|
||||
s=s.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,(_,label,url)=>`<a href="${esc(url)}" target="_blank" rel="noopener">${esc(label)}</a>`);
|
||||
// Tables: | col | col | header row followed by | --- | --- | separator then data rows
|
||||
s=s.replace(/((?:^\|.+\|\n?)+)/gm,block=>{
|
||||
const rows=block.trim().split('\n').filter(r=>r.trim());
|
||||
if(rows.length<2)return block;
|
||||
const isSep=r=>/^\|[\s|:-]+\|$/.test(r.trim());
|
||||
if(!isSep(rows[1]))return block;
|
||||
const parseRow=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<td>${c.trim()}</td>`).join('');
|
||||
const parseHeader=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<th>${c.trim()}</th>`).join('');
|
||||
const parseRow=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<td>${esc(c.trim())}</td>`).join('');
|
||||
const parseHeader=r=>r.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>`<th>${esc(c.trim())}</th>`).join('');
|
||||
const header=`<tr>${parseHeader(rows[0])}</tr>`;
|
||||
const body=rows.slice(2).map(r=>`<tr>${parseRow(r)}</tr>`).join('');
|
||||
return `<table><thead>${header}</thead><tbody>${body}</tbody></table>`;
|
||||
@@ -374,13 +374,29 @@ function renderMessages(){
|
||||
}
|
||||
const frag=document.createDocumentFragment();
|
||||
for(const tc of cards){frag.appendChild(buildToolCard(tc));}
|
||||
// Add expand/collapse toggle for groups with 2+ cards
|
||||
if(cards.length>=2){
|
||||
const toggle=document.createElement('div');
|
||||
toggle.className='tool-cards-toggle';
|
||||
// Collect card elements before they get moved to DOM
|
||||
const cardEls=Array.from(frag.querySelectorAll('.tool-card'));
|
||||
const expandBtn=document.createElement('button');
|
||||
expandBtn.textContent='Expand all';
|
||||
expandBtn.onclick=()=>cardEls.forEach(c=>c.classList.add('open'));
|
||||
const collapseBtn=document.createElement('button');
|
||||
collapseBtn.textContent='Collapse all';
|
||||
collapseBtn.onclick=()=>cardEls.forEach(c=>c.classList.remove('open'));
|
||||
toggle.appendChild(expandBtn);
|
||||
toggle.appendChild(collapseBtn);
|
||||
frag.insertBefore(toggle,frag.firstChild);
|
||||
}
|
||||
if(insertBefore) inner.insertBefore(frag,insertBefore);
|
||||
else inner.appendChild(frag);
|
||||
}
|
||||
}
|
||||
scrollToBottom();
|
||||
// Apply syntax highlighting after DOM is built
|
||||
requestAnimationFrame(()=>{highlightCode();renderMermaidBlocks();});
|
||||
requestAnimationFrame(()=>{highlightCode();addCopyButtons();renderMermaidBlocks();});
|
||||
// Refresh todo panel if it's currently open
|
||||
if(typeof loadTodos==='function' && document.getElementById('panelTodos') && document.getElementById('panelTodos').classList.contains('active')){
|
||||
loadTodos();
|
||||
@@ -558,6 +574,36 @@ function highlightCode(container) {
|
||||
Prism.highlightAllUnder(el);
|
||||
}
|
||||
|
||||
function addCopyButtons(container){
|
||||
const el=container||$('msgInner');
|
||||
if(!el) return;
|
||||
el.querySelectorAll('pre > code').forEach(codeEl=>{
|
||||
const pre=codeEl.parentElement;
|
||||
if(pre.querySelector('.code-copy-btn')) return;
|
||||
const btn=document.createElement('button');
|
||||
btn.className='code-copy-btn';
|
||||
btn.textContent='Copy';
|
||||
btn.onclick=(e)=>{
|
||||
e.stopPropagation();
|
||||
navigator.clipboard.writeText(codeEl.textContent).then(()=>{
|
||||
btn.textContent='Copied!';
|
||||
setTimeout(()=>{btn.textContent='Copy';},1500);
|
||||
});
|
||||
};
|
||||
const header=pre.previousElementSibling;
|
||||
if(header&&header.classList.contains('pre-header')){
|
||||
header.style.display='flex';
|
||||
header.style.justifyContent='space-between';
|
||||
header.style.alignItems='center';
|
||||
header.appendChild(btn);
|
||||
}else{
|
||||
pre.style.position='relative';
|
||||
btn.style.cssText='position:absolute;top:6px;right:6px;';
|
||||
pre.appendChild(btn);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let _mermaidLoading=false;
|
||||
let _mermaidReady=false;
|
||||
|
||||
@@ -568,7 +614,9 @@ function renderMermaidBlocks(){
|
||||
if(!_mermaidLoading){
|
||||
_mermaidLoading=true;
|
||||
const script=document.createElement('script');
|
||||
script.src='https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js';
|
||||
script.src='https://cdn.jsdelivr.net/npm/mermaid@10.9.3/dist/mermaid.min.js';
|
||||
script.integrity='sha384-R63zfMfSwJF4xCR11wXii+QUsbiBIdiDzDbtxia72oGWfkT7WHJfmD/I/eeHPJyT';
|
||||
script.crossOrigin='anonymous';
|
||||
script.onload=()=>{
|
||||
if(typeof mermaid!=='undefined'){
|
||||
mermaid.initialize({startOnLoad:false,theme:'dark',themeVariables:{
|
||||
@@ -745,7 +793,7 @@ async function uploadPendingFiles(){
|
||||
const f=S.pendingFiles[i];const fd=new FormData();
|
||||
fd.append('session_id',S.session.session_id);fd.append('file',f,f.name);
|
||||
try{
|
||||
const res=await fetch('/api/upload',{method:'POST',body:fd});
|
||||
const res=await fetch(new URL('/api/upload',location.origin).href,{method:'POST',credentials:'include',body:fd});
|
||||
if(!res.ok){const err=await res.text();throw new Error(err);}
|
||||
const data=await res.json();
|
||||
if(data.error)throw new Error(data.error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
async function api(path,opts={}){
|
||||
const res=await fetch(path,{headers:{'Content-Type':'application/json'},...opts});
|
||||
const url=new URL(path,location.origin);
|
||||
const res=await fetch(url.href,{credentials:'include',headers:{'Content-Type':'application/json'},...opts});
|
||||
if(!res.ok)throw new Error(await res.text());
|
||||
const ct=res.headers.get('content-type')||'';
|
||||
return ct.includes('application/json')?res.json():res.text();
|
||||
|
||||
234
tests/test_sprint15.py
Normal file
234
tests/test_sprint15.py
Normal file
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
Sprint 15 Tests: session projects (CRUD, move, backward compat).
|
||||
"""
|
||||
import json, urllib.error, urllib.request
|
||||
|
||||
BASE = "http://127.0.0.1:8788"
|
||||
|
||||
|
||||
def get(path):
|
||||
with urllib.request.urlopen(BASE + path, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
|
||||
|
||||
def post(path, body=None):
|
||||
data = json.dumps(body or {}).encode()
|
||||
req = urllib.request.Request(BASE + path, data=data,
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.loads(r.read()), r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
return json.loads(e.read()), e.code
|
||||
|
||||
|
||||
def make_session(created_list):
|
||||
d, _ = post("/api/session/new", {})
|
||||
sid = d["session"]["session_id"]
|
||||
created_list.append(sid)
|
||||
return sid, d["session"]
|
||||
|
||||
|
||||
def make_project(created_list, name="Test Project", color=None):
|
||||
body = {"name": name}
|
||||
if color:
|
||||
body["color"] = color
|
||||
d, status = post("/api/projects/create", body)
|
||||
assert status == 200
|
||||
pid = d["project"]["project_id"]
|
||||
created_list.append(pid)
|
||||
return pid, d["project"]
|
||||
|
||||
|
||||
def cleanup_projects(project_ids):
|
||||
for pid in project_ids:
|
||||
try:
|
||||
post("/api/projects/delete", {"project_id": pid})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── Project CRUD ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_create_project():
|
||||
"""Creating a project returns a valid project dict."""
|
||||
pids = []
|
||||
try:
|
||||
pid, proj = make_project(pids, "My Project", "#7cb9ff")
|
||||
assert pid and len(pid) == 12
|
||||
assert proj["name"] == "My Project"
|
||||
assert proj["color"] == "#7cb9ff"
|
||||
assert "created_at" in proj
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
|
||||
|
||||
def test_list_projects_empty():
|
||||
"""Listing projects when none exist returns empty list."""
|
||||
d, status = get("/api/projects")
|
||||
assert status == 200
|
||||
assert isinstance(d["projects"], list)
|
||||
|
||||
|
||||
def test_list_projects():
|
||||
"""Listing projects returns created projects."""
|
||||
pids = []
|
||||
try:
|
||||
make_project(pids, "Alpha")
|
||||
make_project(pids, "Beta")
|
||||
d, status = get("/api/projects")
|
||||
assert status == 200
|
||||
names = [p["name"] for p in d["projects"]]
|
||||
assert "Alpha" in names
|
||||
assert "Beta" in names
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
|
||||
|
||||
def test_rename_project():
|
||||
"""Renaming a project updates its name."""
|
||||
pids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Old Name")
|
||||
d, status = post("/api/projects/rename", {"project_id": pid, "name": "New Name"})
|
||||
assert status == 200
|
||||
assert d["project"]["name"] == "New Name"
|
||||
# Verify via list
|
||||
dl, _ = get("/api/projects")
|
||||
names = [p["name"] for p in dl["projects"]]
|
||||
assert "New Name" in names
|
||||
assert "Old Name" not in names
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
|
||||
|
||||
def test_delete_project():
|
||||
"""Deleting a project removes it from the list."""
|
||||
pids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Doomed")
|
||||
d, status = post("/api/projects/delete", {"project_id": pid})
|
||||
assert status == 200
|
||||
assert d["ok"] is True
|
||||
dl, _ = get("/api/projects")
|
||||
assert all(p["project_id"] != pid for p in dl["projects"])
|
||||
pids.clear() # already deleted
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
|
||||
|
||||
def test_delete_project_unassigns_sessions():
|
||||
"""Deleting a project unassigns all sessions that belonged to it."""
|
||||
pids = []
|
||||
sids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Temp Project")
|
||||
sid, _ = make_session(sids)
|
||||
# Assign session to project
|
||||
post("/api/session/move", {"session_id": sid, "project_id": pid})
|
||||
# Verify assigned
|
||||
sd, _ = get(f"/api/session?session_id={sid}")
|
||||
assert sd["session"].get("project_id") == pid
|
||||
# Delete project
|
||||
post("/api/projects/delete", {"project_id": pid})
|
||||
pids.clear()
|
||||
# Verify session is unassigned
|
||||
sd2, _ = get(f"/api/session?session_id={sid}")
|
||||
assert sd2["session"].get("project_id") is None
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
for s in sids:
|
||||
post("/api/session/delete", {"session_id": s})
|
||||
|
||||
|
||||
def test_create_project_requires_name():
|
||||
"""Creating a project without a name returns 400."""
|
||||
d, status = post("/api/projects/create", {})
|
||||
assert status == 400
|
||||
|
||||
|
||||
def test_delete_nonexistent_project():
|
||||
"""Deleting a project that doesn't exist returns 404."""
|
||||
d, status = post("/api/projects/delete", {"project_id": "nonexistent99"})
|
||||
assert status == 404
|
||||
|
||||
|
||||
# ── Session move ─────────────────────────────────────────────────────────
|
||||
|
||||
def test_session_move_to_project():
|
||||
"""Moving a session to a project sets its project_id."""
|
||||
pids = []
|
||||
sids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Work")
|
||||
sid, _ = make_session(sids)
|
||||
d, status = post("/api/session/move", {"session_id": sid, "project_id": pid})
|
||||
assert status == 200
|
||||
assert d["session"]["project_id"] == pid
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
for s in sids:
|
||||
post("/api/session/delete", {"session_id": s})
|
||||
|
||||
|
||||
def test_session_move_to_unassigned():
|
||||
"""Moving a session to null project unassigns it."""
|
||||
pids = []
|
||||
sids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Temp")
|
||||
sid, _ = make_session(sids)
|
||||
# Assign then unassign
|
||||
post("/api/session/move", {"session_id": sid, "project_id": pid})
|
||||
d, status = post("/api/session/move", {"session_id": sid, "project_id": None})
|
||||
assert status == 200
|
||||
assert d["session"]["project_id"] is None
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
for s in sids:
|
||||
post("/api/session/delete", {"session_id": s})
|
||||
|
||||
|
||||
def test_session_project_in_list():
|
||||
"""Session list includes project_id for assigned sessions."""
|
||||
pids = []
|
||||
sids = []
|
||||
try:
|
||||
pid, _ = make_project(pids, "Listed")
|
||||
sid, _ = make_session(sids)
|
||||
# Give it a title so it shows in list (non-empty Untitled sessions are hidden)
|
||||
post("/api/session/rename", {"session_id": sid, "title": "Project Test Session"})
|
||||
post("/api/session/move", {"session_id": sid, "project_id": pid})
|
||||
dl, _ = get("/api/sessions")
|
||||
match = [s for s in dl["sessions"] if s["session_id"] == sid]
|
||||
assert len(match) == 1
|
||||
assert match[0]["project_id"] == pid
|
||||
finally:
|
||||
cleanup_projects(pids)
|
||||
for s in sids:
|
||||
post("/api/session/delete", {"session_id": s})
|
||||
|
||||
|
||||
# ── Backward compat ──────────────────────────────────────────────────────
|
||||
|
||||
def test_compact_includes_project_id():
|
||||
"""New session compact dict includes project_id as null."""
|
||||
sids = []
|
||||
try:
|
||||
sid, sess = make_session(sids)
|
||||
# Give it a title so it appears in the list
|
||||
post("/api/session/rename", {"session_id": sid, "title": "Compat Test"})
|
||||
dl, _ = get("/api/sessions")
|
||||
match = [s for s in dl["sessions"] if s["session_id"] == sid]
|
||||
assert len(match) == 1
|
||||
assert "project_id" in match[0]
|
||||
assert match[0]["project_id"] is None
|
||||
finally:
|
||||
for s in sids:
|
||||
post("/api/session/delete", {"session_id": s})
|
||||
|
||||
|
||||
def test_session_move_requires_session_id():
|
||||
"""Moving without session_id returns 400."""
|
||||
d, status = post("/api/session/move", {"project_id": "abc"})
|
||||
assert status == 400
|
||||
Reference in New Issue
Block a user