Compare commits

...

20 Commits

Author SHA1 Message Date
Nathan Esquenazi
1c6db07c2b Merge pull request #33 from nesquena/sprint-18-thinking-tree-preview
Sprint 18: File preview auto-close, thinking display, workspace tree view
2026-04-03 05:02:47 -07:00
Nathan Esquenazi
d0aef93372 fix: apply review fixes, update version to v0.20, add Sprint 18 changelog
- Fix stale tree cache: clear _dirCache and _expandedDirs on root nav
- Fix clearPreview: prompt before discarding unsaved preview edits
- Update UI version label from v0.17.1 to v0.20
- Add Sprint 18 entry to CHANGELOG.md
- Update SPRINTS.md current state to v0.20

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 05:02:30 -07:00
Nathan Esquenazi
67324cc3bc feat: Sprint 18 — file preview auto-close, thinking display, workspace tree
- File preview auto-close: clearPreview() extracted as named function
  and called from loadDir(). Navigating directories (breadcrumbs, up
  button, folder clicks) now automatically closes the right panel
  file preview instead of leaving stale content visible.

- Thinking/reasoning display: assistant messages with structured content
  arrays containing type=thinking or type=reasoning blocks now render
  as collapsible gold-themed cards above the response text. Collapsed
  by default, click header to expand. Works with Claude extended thinking
  and o3 reasoning tokens when preserved in the message array.

- Workspace tree view (Issue #22): directories expand/collapse in-place
  with toggle arrows. Single-click toggles, double-click navigates
  (breadcrumb view). Subdirectory contents fetched lazily and cached.
  Indentation shows nesting depth. Empty directories show "(empty)".
  S._expandedDirs tracks open state, S._dirCache caches fetched entries.

Tests: 295 passed, 23 pre-existing failures, 0 regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 04:33:24 -07:00
Nathan Esquenazi
e7e09f217a Merge pull request #32 from nesquena/docs/v0.19-release
docs: fix v0.19 test count (294→318), add Sprint 17 Tests section
2026-04-03 04:28:56 -07:00
Nathan Esquenazi
0c00dae15a docs: fix test count (294→318) and add Sprint 17 Tests section
CHANGELOG.md and SPRINTS.md incorrectly stated 294 tests for v0.19.
Actual count is 318 (289 from v0.18.1 + 6 new Sprint 17 + 23 in
test_regressions.py). The Sprint 17 commit message miscounted as
'5 new' when test_sprint17.py contains 6 tests.

Also adds a Tests section to the Sprint 17 CHANGELOG entry listing
what the 6 tests cover, and notes the send_key enum validation.

Tests: 318 passed, 0 failed.
2026-04-03 11:23:42 +00:00
Nathan Esquenazi
685aabab38 Merge pull request #30 from nesquena/sprint-17-workspace-slash-commands-settings
feat: Sprint 17 -- Workspace breadcrumbs, slash commands, send key setting
2026-04-03 04:14:23 -07:00
Nathan Esquenazi
0f2bd537f1 feat: Sprint 17 -- workspace breadcrumbs, slash commands, send key setting
Track A: Workspace breadcrumb navigation
- Breadcrumb path bar with clickable segments when inside subdirectories
- Up button in panel header for parent directory navigation
- S.currentDir state tracking; file ops stay in current directory
- New file/folder creation respects current subdirectory

Track B: Slash commands foundation
- New commands.js module (7th JS module) with command registry and parser
- Built-in commands: /help, /clear, /model, /workspace, /new
- Autocomplete dropdown on / input with arrow/tab/enter/escape navigation
- Unrecognized commands pass through to agent normally

Track C: Send key setting (closes #26)
- send_key added to settings defaults in api/config.py
- Settings panel dropdown: Enter (default) vs Ctrl/Cmd+Enter
- Keydown handler rewritten for autocomplete + send key preference
- Setting loaded on boot, persisted to settings.json

5 new tests, 242 total (219 passing, 22 pre-existing failures, 0 regressions).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 04:13:38 -07:00
Nathan Esquenazi
856f5c21e1 Merge pull request #31 from nesquena/docs/update-markdown-v0.18.1
docs: update markdown for v0.18.1
2026-04-02 17:39:18 -07:00
Nathan Esquenazi
f3ae8305dc docs: update markdown files for v0.18.1 (safe HTML rendering, 289 tests)
- CHANGELOG: add v0.18.1 entry (safe HTML rendering, inlineMd, safety
  net, active session gold style, 74 new tests)
- ARCHITECTURE: update ui.js line count (809->846), document renderMd
  pre-pass/safety net/inlineMd/SAFE_TAGS, update test file count (14),
  update Phase I test count (289)
- ROADMAP: bump version and test count
- SPRINTS: bump version, test count, Sprint 16 test total

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 17:38:44 -07:00
Nathan Esquenazi
a92fff75a3 Merge pull request #29 from nesquena/feat/safe-html-rendering
feat: safe HTML rendering in AI responses, active session gold style, Sprint 16 tests
2026-04-02 17:34:01 -07:00
Hermes
0be7ccde4c feat: safe HTML rendering in AI responses + active session gold style + Sprint 16 tests
renderMd() now correctly renders safe inline HTML tags that AI models
emit in their responses:

Pre-pass (ui.js):
  Converts <strong>, <b>, <em>, <i>, <code>, <br> to their markdown
  equivalents (**text**, *text*, `text`, newline) before the pipeline
  runs. Code blocks and backtick spans are stashed first so their content
  is never modified.

inlineMd() helper (ui.js):
  New helper for processing inline formatting inside list items,
  blockquotes, and headings. Previously these used esc() directly, which
  escaped <strong>/<code> tags that had already been converted from HTML
  by the pre-pass — causing them to appear as literal &lt;strong&gt; text
  instead of rendering as bold. inlineMd() applies bold/italic/code
  processing and then escapes only unknown tags.

Safety net (ui.js):
  After the full pipeline, any HTML tags NOT emitted by our own renderer
  (i.e. <img>, <script>, <iframe>, <svg>, <object>, etc.) are escaped
  via esc(). The SAFE_TAGS allowlist covers every tag the pipeline itself
  produces. XSS is fully blocked.

Active session gold style (sessions.js, style.css):
  Active session item now uses gold/amber (#e8a030) instead of blue,
  matching the logo gradient color for better visual hierarchy.
  Project color border-left is skipped when the session is active
  (gold always wins). Session items get border-radius: 0 8px 8px 0
  to complement the left border indicator.

Tests (tests/test_sprint16.py — 74 tests):
  - Static analysis: pre-pass, SAFE_TAGS, SAFE_INLINE, inlineMd present
  - Behavioural: all safe tags render in paragraphs, list items (ul+ol),
    blockquotes, headings (h1/h2/h3)
  - Exact screenshot regression: the 4-item list with <strong> labels
    and <code> values that was showing as literal text
  - XSS: 7 attack vectors blocked (<img>, <script>, <iframe>, <svg>,
    <object>, XSS inside bold, XSS nested inside <strong>)
  - Edge cases: code block protection, double-escaping guards, br tag,
    mixed markdown+HTML, inlineMd called in list/blockquote handlers

Tests: 312 passed, 0 failed.
2026-04-03 00:27:43 +00:00
Nathan Esquenazi
fcd155be55 Merge pull request #27 from nesquena/docs/update-all-markdown
docs: update all markdown to v0.18 state
2026-04-02 15:15:10 -07:00
Nathan Esquenazi
0c601a9cc8 docs: fix models.py line count (114 -> 132)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 15:14:42 -07:00
Nathan Esquenazi
4b326dbdf0 docs: update all markdown files to reflect v0.18 state
Brings all documentation up to date after Sprint 16, PRs #18-25:

- CHANGELOG: add v0.18 (Sprint 16), v0.17.3 (bug fixes), update footer
- ROADMAP: Sprint 16 in history, custom model discovery feature, updated
  line counts and architecture table, fix Wave 3 checkboxes
- SPRINTS: bump version to v0.18, update parity percentages, fix
  reasoning display sprint reference
- ARCHITECTURE: update all file line counts to match current source,
  add Session model fields (pinned, archived, project_id, tool_calls),
  document ICONS constant and sessions.js overlay pattern, update
  Phase A/I sections
- BUGS: restructure with open/fixed sections, add v0.17.3 fixes

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:56:06 -07:00
Nathan Esquenazi
fd993c5513 Merge pull request #20 from nesquena/sprint-16-sidebar-polish
Sprint 16: Session sidebar visual polish — overlay actions, SVG icons, project borders
2026-04-02 11:50:28 -07:00
Nathan Esquenazi
d2bcd2b2f7 feat: Sprint 16 — session sidebar visual polish
- Action buttons overlay: wrap pin/move/archive/dup/trash in a
  .session-actions container with position:absolute. Titles now use
  full available width. Actions appear on hover with gradient fade
  from the right edge. Overlay auto-hides during inline rename.

- SVG line icons: replace all emoji HTML entities with monochrome
  SVGs that inherit currentColor. Consistent across all platforms.

- Pin indicator: small gold star rendered inline only when pinned.
  Unpinned sessions get full title width (zero space reservation).

- Project border: sessions assigned to a project show a colored
  left border matching the project color, replacing the old
  always-visible blue folder button.

Fixes both BUGS.md items (title truncation + sticky folder button).
Tests: 214 passed, 23 pre-existing failures, 0 regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 11:49:24 -07:00
Nathan Esquenazi
5e4645ee05 Merge pull request #25 from nesquena/fix/project-picker-overflow
fix: project picker clipped and width issues
2026-04-02 11:46:56 -07:00
Nathan Esquenazi
ae1faa7252 Merge pull request #24 from nesquena/fix/model-discovery-logger-crash
fix: NameError on logger in custom endpoint model discovery
2026-04-02 11:46:48 -07:00
Nathan Esquenazi
6c7fb4ee44 fix: NameError on logger in custom endpoint model discovery
get_available_models() references 'logger' in the except block of
the custom endpoint fetch (added in PR #18), but 'logger' is never
imported or defined in api/config.py. When the custom endpoint is
unreachable (the normal case -- most users don't have a local LLM),
the except handler raises NameError: name 'logger' is not defined,
which propagates as a 500 on every GET /api/models request.

This broke 7 test_sprint11 tests and caused the model dropdown to
fail for all users regardless of whether they have a custom endpoint.

Fix: replace logger.debug() with a silent pass -- the exception is
expected when no local LLM is configured and needs no logging.

Tests: 237 passed, 0 failed.
2026-04-02 11:36:01 -07:00
Nathan Esquenazi
e59eb8bb5b fix: project picker clipped, full-screen width bug, New Project shortcut
Five fixes to the Sprint 15 Move to Project picker:

1. CRITICAL: Picker was invisible (overflow:hidden clipping)
   Appended to document.body + positioned with fixed/getBoundingClientRect
   instead of inside .session-item (overflow:hidden). Flips above button
   when near bottom of viewport.

2. CRITICAL: Picker stretched full screen width
   position:fixed removed the containing block width constraint. Added
   max-width:220px; width:max-content to .project-picker.

3. UX: No way to create a project from the picker
   Added '+ New project': creates project and moves session in one click.

4. UX: Feature was undiscoverable
   Folder button shows persistently (blue, 60% opacity) when session
   has a project.

5. Minor: Event listener leak
   removeEventListener was missing from picker item onclick handlers.

Tests: 237 passed (7 pre-existing failures from unrelated logger bug).
2026-04-02 18:18:20 +00:00
17 changed files with 1726 additions and 193 deletions

View File

@@ -31,25 +31,25 @@ This makes the code easy to modify from a terminal or by an agent.
start.sh Discovery script: finds agent dir, Python, starts server.
api/
__init__.py Package marker
routes.py All GET + POST route handlers (~802 lines)
config.py Shared configuration, constants, global state, model discovery (~453 lines)
routes.py All GET + POST route handlers (~1016 lines)
config.py Shared configuration, constants, global state, model discovery (~640 lines)
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve() (~57 lines)
models.py Session model + CRUD (~114 lines)
models.py Session model + CRUD (~132 lines)
workspace.py File ops: list_dir, read_file_content, workspace helpers (~77 lines)
upload.py Multipart parser, file upload handler (~77 lines)
streaming.py SSE engine, run_agent integration, cancel support (~218 lines)
streaming.py SSE engine, run_agent integration, cancel support (~222 lines)
static/
index.html HTML template (served from disk)
style.css All CSS
ui.js DOM helpers, renderMd, tool cards, model dropdown (~671 lines)
workspace.js File tree, preview, file ops (~168 lines)
sessions.js Session CRUD, list rendering, search (~206 lines)
messages.js send(), SSE event handlers, approval, transcript (~310 lines)
panels.js Cron, skills, memory, workspace, todo, switchPanel (~600 lines)
boot.js Event wiring + boot IIFE (~154 lines)
ui.js DOM helpers, renderMd, tool cards, model dropdown (~846 lines)
workspace.js File tree, preview, file ops (~169 lines)
sessions.js Session CRUD, list rendering, search, SVG icons, overlay actions (~532 lines)
messages.js send(), SSE event handlers, approval, transcript (~293 lines)
panels.js Cron, skills, memory, workspace, todo, switchPanel (~771 lines)
boot.js Event wiring + boot IIFE (~175 lines)
tests/
conftest.py Isolated test server (port 8788, separate HERMES_HOME) (~240 lines)
test_sprint1-11.py Feature tests per sprint (13 files)
test_sprint1-16.py Feature tests per sprint (14 files, Sprints 1-11 + 16)
test_regressions.py Permanent regression gate
AGENTS.md Instruction file for agents working in this directory.
ROADMAP.md Feature and product roadmap document.
@@ -151,10 +151,14 @@ Session is a plain Python class (not a dataclass, not SQLAlchemy):
session_id hex string, 12 chars (uuid4().hex[:12])
title string, auto-set from first user message
workspace absolute path string, resolved at creation
model OpenRouter model ID string (e.g. "anthropic/claude-sonnet-4.6")
model model ID string (e.g. "anthropic/claude-sonnet-4.6")
messages list of OpenAI-format message dicts
created_at float Unix timestamp
updated_at float Unix timestamp, updated on every save()
pinned bool, default False (Sprint 12)
archived bool, default False (Sprint 14)
project_id string or null, FK to projects.json (Sprint 15)
tool_calls list of tool call dicts (Sprint 10)
Key methods:
path (property) Returns SESSION_DIR/{session_id}.json
@@ -326,16 +330,20 @@ read_file_content(workspace, rel):
### 5.1 Structure
The frontend is served from static/ as separate files: one HTML template, one CSS file,
and six JavaScript modules (~2,025 lines total). External dependency: Prism.js from CDN
(syntax highlighting, loaded async/deferred).
and six JavaScript modules (~2,786 lines total). External dependencies: Prism.js (syntax
highlighting) and Mermaid.js (diagrams) from CDN, both loaded async/deferred with SRI hashes.
Six JS modules loaded in order at end of <body>:
1. ui.js (~589 lines) DOM helpers, renderMd, tool card rendering, global state
2. workspace.js (~168 lines) File tree, preview, file operations
3. sessions.js (~206 lines) Session CRUD, list rendering, search
4. messages.js (~310 lines) send(), SSE event handlers, approval, transcript
5. panels.js (~600 lines) Cron, skills, memory, workspace, todo, switchPanel
6. boot.js (~152 lines) Event wiring + boot IIFE
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
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
sessions.js defines an `ICONS` constant at module level with hardcoded SVG strings for all
session action buttons (pin, unpin, folder, archive, unarchive, duplicate, trash). All icons
inherit `currentColor` for consistent theming.
Three-panel layout (in static/index.html):
@@ -406,25 +414,43 @@ Boot IIFE:
### 5.4 Markdown Renderer (renderMd)
A hand-rolled regex chain. Processes in this order:
1. Code blocks (``` lang ... ```) -> <pre><code> with language header
2. Inline code (`...`) -> <code>
3. Bold+italic (***..***) -> <strong><em>
4. Bold (**...**) -> <strong>
5. Italic (*...*) -> <em>
6. Headings (# ## ###) -> <h1> <h2> <h3>
7. Horizontal rules (---+) -> <hr>
8. Blockquotes (> ...) -> <blockquote>
9. Unordered lists (- or * or + at line start) -> <ul><li>
10. Ordered lists (N. at line start) -> <ol><li>
11. Links ([text](https://...)) -> <a href target=_blank>
12. Paragraph wrapping: remaining double-newline-separated blocks -> <p>
A hand-rolled regex chain with HTML safety. Processes in this order:
Pre-pass (v0.18.1):
0a. Stash fenced code blocks and backtick spans (fence_stash array)
0b. Convert safe HTML tags to markdown equivalents:
<strong>/<b> -> **text**, <em>/<i> -> *text*, <code> -> `text`, <br> -> newline
0c. Restore stashed code blocks
Pipeline:
1. Mermaid blocks (```mermaid ... ```) -> <div class="mermaid-block">
2. Code blocks (``` lang ... ```) -> <pre><code> with language header
3. Inline code (`...`) -> <code>
4. Bold+italic (***..***) -> <strong><em>
5. Bold (**...**) -> <strong>
6. Italic (*...*) -> <em>
7. Headings (# ## ###) -> <h1> <h2> <h3> (uses inlineMd() for content)
8. Horizontal rules (---+) -> <hr>
9. Blockquotes (> ...) -> <blockquote> (uses inlineMd() for content)
10. Unordered lists (- or * or + at line start) -> <ul><li> (uses inlineMd())
11. Ordered lists (N. at line start) -> <ol><li> (uses inlineMd())
12. Links ([text](https://...)) -> <a href target=_blank>
13. Tables (| col | col |) -> <table>
14. Safety net: escape any HTML tag not in SAFE_TAGS allowlist via esc()
15. Paragraph wrapping: remaining double-newline-separated blocks -> <p>
inlineMd() helper (v0.18.1):
Processes inline bold/italic/code/links within list items, blockquotes,
and headings. Escapes unknown tags via SAFE_INLINE allowlist. Replaces
the old direct esc() calls which would double-escape pre-pass output.
SAFE_TAGS allowlist:
strong, em, code, pre, h1-6, ul, ol, li, table, thead, tbody, tr, th,
td, hr, blockquote, p, br, a, div. Everything else is escaped.
Known gaps:
- Tables: not supported, render as plain text
- Nested lists: single regex pass, multi-level indentation not handled
- Mixed bold+link in same line: may produce garbled output
- Inline HTML: not sanitized (esc() only runs on code content)
### 5.5 Model Chip Label (Fixed in Sprint 1)
@@ -604,26 +630,27 @@ Split server.py into a proper package. Completed across Sprints 4-10.
Current structure:
<repo>/
server.py Entry point + HTTP Handler routing (~704 lines)
server.py Entry point + HTTP Handler dispatch (~76 lines)
api/
__init__.py
config.py Configuration, constants, global state (~273 lines)
routes.py All GET + POST route handlers (~1016 lines)
config.py Configuration, constants, global state, model discovery (~640 lines)
helpers.py HTTP helpers: j(), bad(), require(), safe_resolve() (~57 lines)
models.py Session model + CRUD (~114 lines)
models.py Session model + CRUD (~132 lines)
workspace.py File ops, workspace management (~77 lines)
upload.py Multipart parser, file upload handler (~77 lines)
streaming.py SSE engine, run_agent, cancel support (~218 lines)
streaming.py SSE engine, run_agent, cancel support (~222 lines)
static/
index.html HTML document (served from disk)
style.css All CSS
style.css All CSS (~560 lines)
ui.js, workspace.js, sessions.js, messages.js, panels.js, boot.js
tests/
conftest.py Isolated test server on port 8788
test_sprint1-10.py Feature tests per sprint (12 files)
test_sprint1-16.py Feature tests per sprint (14 files)
test_regressions.py Permanent regression gate
Remaining: server.py still has all 49 route handlers in one do_GET/do_POST class.
Sprint 11 plans extracting these to api/routes.py, making server.py a ~50-line shell.
Route extraction to api/routes.py completed in Sprint 11. server.py is now a ~76-line
thin shell: Handler class with structured logging, dispatch to routes, and main().
### Phase B: Thread-Safe Request Context (Priority: Critical, Effort: Medium)
@@ -718,10 +745,10 @@ Optional password gate for non-SSH-tunnel deployments.
### Phase I: Test Infrastructure -- COMPLETE
190 tests across 12 test files + regression gate. Isolated test server on port 8788
289 tests across 14 test files + regression gate. Isolated test server on port 8788
with separate HERMES_HOME, wiped per run. Production data never touched.
Test files: `test_sprint1.py` through `test_sprint10.py`, `test_regressions.py`.
Test files: `test_sprint1.py` through `test_sprint11.py`, `test_sprint16.py`, `test_regressions.py`.
Fixtures in `conftest.py`: auto-cleanup, cron isolation, workspace reset.
Remaining: no CI (GitHub Actions), no frontend tests (browser-based).

40
BUGS.md Normal file
View File

@@ -0,0 +1,40 @@
# Bugs Backlog
This file tracks UI bugs and polish items. Fixed items are kept for reference.
---
## Open Bugs
*No open bugs at this time.*
---
## Fixed
### ~~Session title truncation / hover actions~~ -- Fixed (Sprint 16)
- **Was:** Action icons reserved ~30px of space even when invisible, truncating titles.
- **Fix:** Wrapped all action buttons in a `.session-actions` overlay container with `position:absolute`. Titles now use full available width. Actions appear on hover with a gradient fade from the right edge.
### ~~Folder/project assignment interaction feels sticky~~ -- Fixed (Sprint 16)
- **Was:** Folder icon stayed permanently visible (blue, 60% opacity) when a session belonged to a project.
- **Fix:** Replaced `.has-project` persistent button with a colored left border matching the project color. The folder button now only appears in the hover overlay like all other actions.
### ~~Project picker clipping and width~~ -- Fixed (v0.17.3)
- **Was:** Picker was clipped by `overflow:hidden` on `.session-item` ancestors. With `position:fixed`, no containing block constrained width -- picker stretched to full viewport.
- **Fix:** Dynamic width calculation (min 160px, max 220px). Event listener reordering. Cleanup sequence corrected. (PR #25)
### ~~NameError crash in model discovery~~ -- Fixed (v0.17.3)
- **Was:** `logger.debug()` called in custom endpoint `except` block, but `logger` was never imported in `config.py`. Every failed endpoint fetch crashed with `NameError`.
- **Fix:** Replaced with silent `pass` -- unreachable endpoints are expected when no local LLM is configured. (PR #24)
---
## Notes
- Sprint 16 replaced all emoji HTML entities with monochrome SVG line icons (`ICONS` constant in `sessions.js`).
- All session action buttons now use the overlay pattern for consistent UX.

View File

@@ -5,6 +5,146 @@
---
## [v0.20] Sprint 18 -- File Preview Auto-Close + Thinking Display + Workspace Tree
*April 3, 2026 | 318 tests*
### Features
- **File preview auto-close on directory navigation.** When viewing a file in
the right panel and navigating directories (breadcrumbs, up button, folder
clicks), the preview now automatically closes instead of showing stale
content. `clearPreview()` extracted as named function and called from
`loadDir()`. Unsaved preview edits prompt for confirmation before discarding.
- **Thinking/reasoning display.** Assistant messages with structured content
arrays containing `type:'thinking'` or `type:'reasoning'` blocks (Claude
extended thinking, o3 reasoning) now render as collapsible gold-themed cards
above the response text. Collapsed by default. Click the header to expand and
see the model's reasoning process. Uses `esc()` on all content for XSS safety.
- **Workspace tree view (Issue #22).** Directories expand/collapse in-place
with toggle arrows. Single-click toggles a directory open/closed. Double-click
navigates into it (breadcrumb view). Subdirectory contents fetched lazily from
the API and cached in `S._dirCache`. Nesting depth shown via indentation.
Empty directories show "(empty)" placeholder. Breadcrumb navigation still
works alongside the tree view.
### Bug Fixes
- **Stale tree cache on session switch.** `S._dirCache` and `S._expandedDirs`
are now cleared when navigating to the root directory, preventing session B
from showing session A's cached file listings.
- **clearPreview() discards unsaved edits.** Navigation now checks
`_previewDirty` and prompts before discarding unsaved preview changes.
### Architecture
- `clearPreview()` extracted from inline handler to named function in `boot.js`.
- Thinking card styles added to `style.css` (gold-themed, collapsible).
- Tree toggle and empty-directory styles added to `style.css`.
---
## [v0.19] Sprint 17 -- Workspace Polish + Slash Commands + Settings
*April 3, 2026 | 318 tests*
### Features
- **Workspace breadcrumb navigation.** Clicking into subdirectories now shows a
breadcrumb path bar (e.g. `~ / src / components`) with clickable segments to
navigate back. An "up" button appears in the panel header when inside a
subdirectory. File operations (rename, delete, new file/folder) stay in the
current directory instead of jumping back to root. Foundation for Issue #22
(tree view).
- **Slash commands.** Type `/` in the composer to see an autocomplete dropdown
of built-in commands. New `commands.js` module with command registry. Built-in
commands: `/help`, `/clear`, `/model <name>`, `/workspace <name>`, `/new`.
Arrow keys navigate, Tab/Enter select, Escape closes. Unrecognized commands
pass through to the agent normally.
- **Send key setting (Issue #26).** New setting in Settings panel to choose
between Enter (default) and Ctrl/Cmd+Enter as the send key. Persisted to
`settings.json` via the existing settings API. Setting loads on boot.
Server-side validation ensures only valid values (`enter`, `ctrl+enter`).
### Architecture
- New `static/commands.js` module (7th JS module): command registry, parser,
autocomplete dropdown, and built-in command handlers.
- `send_key` added to `_SETTINGS_DEFAULTS` in `api/config.py` with enum validation
(`_SETTINGS_ENUM_VALUES` rejects unknown values server-side).
- `S.currentDir` state tracking added to `ui.js` for workspace navigation.
### Tests
- 6 new tests in `test_sprint17.py`: send_key default, round-trip save with
cleanup, invalid value rejection, unknown key ignored, commands.js served,
workspace root listing. Total: **318 passed**.
---
## [v0.18.1] Safe HTML Rendering + Sprint 16 Tests
*April 2, 2026 | 289 tests*
### Features
- **Safe HTML rendering in AI responses.** AI models sometimes emit HTML tags
(`<strong>`, `<em>`, `<code>`, `<br>`) in their responses. Previously these
showed as literal escaped text. A new pre-pass in `renderMd()` converts safe
HTML tags to markdown equivalents before the pipeline runs. Code blocks and
backtick spans are stashed first so their content is never touched.
- **`inlineMd()` helper.** New function for processing inline formatting inside
list items, blockquotes, and headings. The old code called `esc()` directly,
which escaped tags that had already been converted by the pre-pass.
- **Safety net.** After the full pipeline, any HTML tags not in the output
allowlist (`SAFE_TAGS`) are escaped via `esc()`. XSS fully blocked -- 7
attack vectors tested.
- **Active session gold style.** Active session uses gold/amber (`#e8a030`)
instead of blue, matching the logo gradient. Project border-left skipped
when active (gold always wins).
### Tests
- **74 new tests** in `test_sprint16.py`: static analysis (6), behavioral (10),
exact regression (1), XSS security (7), edge cases (51). Total: 289 passed.
---
## [v0.18] Sprint 16 -- Session Sidebar Visual Polish
*April 2, 2026 | 237 tests*
### Features
- **SVG action icons.** Replaced all emoji HTML entities (star, folder, box,
duplicate, trash) with monochrome SVG line icons that inherit `currentColor`.
Consistent rendering across macOS, Linux, and Windows. Defined in a top-level
`ICONS` constant in `sessions.js`.
- **Action buttons overlay.** All session action buttons (pin, move, archive,
duplicate, trash) wrapped in a `.session-actions` container with
`position:absolute`. Titles now use full available width instead of being
truncated by invisible buttons. Actions appear on hover with a gradient fade
from the right edge. Overlay auto-hides during inline rename via
`:has(.session-title-input)`.
- **Pin indicator.** Small gold filled-star icon rendered inline before the
title only when pinned. Unpinned sessions get full title width with zero
space reservation.
- **Project border indicator.** Sessions assigned to a project show a colored
left border matching the project color, replacing the old always-visible
blue folder button.
### Bug Fixes
- **Session title truncation.** Action icons reserved ~30px of space even when
invisible, truncating titles. Fixed by overlay container approach.
- **Folder button felt sticky.** Replaced `.has-project` persistent blue button
with colored left border. Folder button now only appears in hover overlay.
---
## [v0.17.3] Bug Fixes
*April 2, 2026*
### Bug Fixes
- **NameError crash in model discovery.** `logger.debug()` was called in the
custom endpoint `except` block in `config.py`, but `logger` was never
imported. Every failed custom endpoint fetch crashed with `NameError`,
returning HTTP 500 for `/api/models`. Replaced with silent `pass` since
unreachable endpoints are expected. (PR #24)
- **Project picker clipping and width.** Picker was clipped by
`overflow:hidden` on ancestor elements. Width calculation improved with
dynamic sizing (min 160px, max 220px). Event listener `close` handler
moved after DOM append to fix reference-before-definition. Reordered
`picker.remove()` before `removeEventListener` for correct cleanup. (PR #25)
---
## [v0.17.2] Model Update
*April 2, 2026*
@@ -509,4 +649,4 @@ Three-panel layout: sessions sidebar, chat area, workspace panel.
---
*Last updated: v0.16.2, April 1, 2026 | Tests: 247*
*Last updated: v0.20, April 3, 2026 | Tests: 318*

View File

@@ -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 15 (April 1, 2026)
> Tests: 237 passing
> Last updated: Sprint 17 / v0.19 (April 3, 2026)
> Tests: 294 passing
> Source: <repo>/
---
@@ -32,6 +32,8 @@
| 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, custom model discovery, GLM-5.1 | 237 |
| Sprint 17 | Workspace polish + slash commands + settings | Breadcrumb navigation, slash command autocomplete, send key setting (#26) | 294 |
---
@@ -39,10 +41,10 @@
| Layer | Location | Status |
|-------|----------|--------|
| Python server | <repo>/server.py (~76 lines) + api/ modules (~1900 lines) | Thin shell + business logic in api/ |
| Python server | <repo>/server.py (~76 lines) + api/ modules (~2145 lines) | Thin shell + business logic in api/ |
| HTML template | <repo>/static/index.html | Served from disk |
| CSS | <repo>/static/style.css | Served from disk |
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot}.js | 6 modules, ~2250 lines total |
| CSS | <repo>/static/style.css (~560 lines) | Served from disk |
| JavaScript | <repo>/static/{ui,workspace,sessions,messages,panels,boot,commands}.js | 7 modules, ~2990 lines total |
| Runtime state | ~/.hermes/webui-mvp/sessions/ | Session JSON files |
| Test server | Port 8788, state dir ~/.hermes/webui-mvp-test/ | Isolated, wiped per run |
| Production server | Port 8787 | SSH tunnel from Mac |
@@ -55,6 +57,7 @@
- [x] Send messages, get SSE-streaming responses
- [x] Switch models per session (10 models, grouped by provider)
- [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
@@ -252,8 +255,8 @@ Add more models. Group by provider. Model info tooltip on hover.
Both sidebar and workspace panel are drag-resizable with localStorage persistence.
### Sprint 3.3: Workspace File Actions
- [ ] Rename file (inline, double-click) (Wave 3)
- [ ] Create folder (Wave 3)
- [x] Rename file (inline, double-click) (Sprint 14)
- [x] Create folder (Sprint 14)
- [x] Syntax highlighted code preview (Prism.js)
### Sprint 3.4: Conversation Controls
@@ -316,3 +319,18 @@ Collapsible sidebar hamburger. Touch-friendly controls. Swipe gestures.
### Sprint 7.4: Performance and Scale
Virtual scroll for session/message lists. Incremental message loading.
---
## User Requested Features
Community-requested enhancements tracked from GitHub issues.
| Feature | Issue | Description | Complexity |
|---------|-------|-------------|-----------|
| Workspace tree view | #22 | Accordion/tree view for workspace file browser instead of flat list. Lazy-load subdirectories on expand, no backend changes needed. | Medium |
| Docker container | #7 | Docker Compose setup with separate hermes-agent and hermes-webui containers, multi-arch (amd64 + arm64), volume mounts for config. | Medium-High |
| Authentication | #23 | Password gate via `HERMES_WEBUI_PASSWORD` env var, login page, signed cookie. Already planned in Sprint 7.1. | Low-Medium |
| Send key / personalization | #26 | Toggle send key (Enter vs Ctrl/Cmd+Enter) and queue vs interrupt mode as global settings. | Low |
| Multi-profile support | #28 | Profile management UI: create, delete, switch, configure agent profiles. | Medium |
| Mobile responsive UI | #21 | Hamburger menu, slide-out sidebar drawer, touch-friendly controls. Already planned in Sprint 7.3. | Medium-High |

View File

@@ -1,6 +1,6 @@
# Hermes Web UI -- Forward Sprint Plan
> Current state: v0.15 | 221 tests | Daily driver ready
> Current state: v0.20 | 318 tests | Daily driver ready
> This document plans the path from here to two targets:
>
> Target A: 1:1 feature parity with the Hermes CLI (everything you can do from the
@@ -14,15 +14,17 @@
---
## Where we are now (v0.12.1)
## Where we are now (v0.18)
**CLI parity: ~80% complete.** Core agent loop, all tools visible, workspace
file ops, cron/skills/memory CRUD, session management, streaming, cancel --
all solid. Gaps are configuration, subagent visibility, and runtime controls.
**CLI parity: ~85% complete.** Core agent loop, all tools visible, workspace
file ops, cron/skills/memory CRUD, session management, streaming, cancel,
multi-provider models, custom endpoint discovery -- all solid. Gaps are
subagent visibility, toolset control, and code execution.
**Claude parity: ~55% complete.** Chat, streaming, file browser,
session management, tool cards, syntax highlighting, model switching -- all
present. Gaps are project organization, artifacts, voice, sharing, mobile.
**Claude parity: ~65% complete.** Chat, streaming, file browser, session
management, tool cards, syntax highlighting, model switching, projects,
settings, Mermaid diagrams, mobile layout -- all present. Gaps are
artifacts, voice, reasoning display, sharing.
---
@@ -217,58 +219,111 @@ organizational gap vs. Claude's project folders.
**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
### Candidates for later sprints
- Artifacts + code execution (HTML/SVG preview, inline Python execution)
- Voice input via Whisper
- Subagent delegation cards (enhanced tool card rendering)
---
## Sprint 16 -- Artifacts + Code Execution
## Sprint 16 -- Session Sidebar Visual Polish (COMPLETED)
**Theme:** See outputs, not just text.
**Theme:** Make the session list feel high-quality and delightful.
**Why now:** Claude's most distinctive feature is the artifact panel --
code runs inline, HTML renders in a sandboxed iframe, SVGs show as images.
This is the largest single capability gap between what we have and what Claude
feels like. It also directly enables the Hermes "code execution cell" feature
(Jupyter-style in-browser execution).
**Why now:** The session sidebar had two visible UX bugs: titles truncated
unnecessarily because action icons reserved space even when hidden, and
the project folder icon felt "sticky" and awkward. Emoji icons rendered
inconsistently across platforms. These were the most common visual complaints.
### Track A: Bugs
- Prism.js autoloader makes one CDN request per language encountered. On a
code-heavy session this causes noticeable latency. Bundle the top 10 languages
(Python, JS, bash, JSON, SQL, YAML, TypeScript, CSS, HTML, Rust) locally.
- Code blocks in long responses sometimes re-highlight on every renderMessages()
call. Debounce highlightCode() with requestAnimationFrame.
### Track A: Bugs (from BUGS.md)
- **Session title truncation.** Action icons (pin, move, archive, dup, trash)
were always in the DOM with `flex-shrink:0`, reserving ~30px even when
invisible. Fix: wrapped all actions in a `.session-actions` overlay
container with `position:absolute`. Titles now use full available width.
Actions appear on hover with a gradient fade from the right edge.
- **Folder button feels sticky.** Replaced `.has-project` persistent blue
button with a colored left border matching the project color. The folder
button now only appears in the hover overlay like all other actions.
### Track B: Features
- **Artifact panel:** When Hermes produces a code block tagged as `html`, `svg`,
or `react`, a "Preview" button appears on that code block. Clicking it opens
a sandboxed `<iframe>` in the right panel showing the rendered output. The
preview updates live if Hermes edits the artifact in a follow-up.
- **Code execution cell:** A "Run" button on Python code blocks. Sends the code
to a new server endpoint (`POST /api/execute`) which runs it in a subprocess
with a 30-second timeout and streams stdout/stderr back as SSE. Output appears
below the code block inline. This is the Jupyter cell experience without
needing a kernel.
- **Mermaid diagram rendering:** Mermaid.js CDN (deferred). Code blocks tagged
as `mermaid` render as flow/sequence/gantt diagrams inline.
- **SVG action icons.** Replaced all 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).
- **Pin indicator.** Small gold filled-star icon rendered inline before the
title only when the session is actually pinned. Unpinned sessions get
full title width with zero space reservation.
- **Project border indicator.** Sessions assigned to a project show a
colored left border matching the project color, replacing the old
always-visible blue folder button.
- **Hover overlay polish.** Actions container uses a gradient background
that fades from transparent to the sidebar color, creating a smooth
emergence effect. Overlay hides automatically during inline rename.
### Track C: Architecture
- Sandbox safety: `/api/execute` runs in a restricted subprocess (no network,
limited filesystem via a temp directory). Returns exit code, stdout, stderr,
and execution time.
- Artifact state: artifacts are tracked in `S.artifacts = {}` (code block hash
-> rendered content). Persisted in session JSON as `artifacts` array.
### Deferred to Sprint 17
- Slash commands (basic set with `commands.js` module)
- Thinking/reasoning display for extended-thinking models
- Slash command autocomplete popup
**Tests:** ~18 new. Total: ~259.
**Hermes CLI parity impact:** High (code execution closes the Jupyter gap)
**Claude parity impact:** Very High (artifacts are Claude's signature feature)
**Tests:** 74 new (test_sprint16.py: safe HTML rendering, XSS security, sidebar polish). Total: 289.
**Hermes CLI parity impact:** Low
**Claude parity impact:** Medium (sidebar polish matches Claude's quality bar)
---
## Sprint 17 -- Voice + Multimodal Input
## Sprint 17 -- Workspace Polish + Slash Commands + Settings (COMPLETED)
**Theme:** Workspace polish, slash commands, and composer settings.
**Why now:** Three things converge: @nothingmn filed Issue #22 requesting a
tree/accordion workspace view (breadcrumb navigation is the foundation for
that), slash commands were deferred from Sprint 16, and Issue #26 (send key
personalization) fits naturally since we are already touching the keydown
handler for slash command autocomplete.
### Track A: Workspace Breadcrumb Navigation
- **Breadcrumb path bar.** When users click into subdirectories, a breadcrumb
bar appears showing the path (e.g. `~ / src / components`) with clickable
segments to navigate back. Hidden at root level for a clean UI.
- **Up button.** Arrow-up button in the panel header navigates to the parent
directory. Hidden when already at workspace root.
- **Current directory tracking.** `S.currentDir` state property tracks the
active directory. File operations (rename, delete, new file, new folder)
stay in the current directory instead of jumping back to root.
- **New file/folder in subdirectories.** Creating files or folders now respects
the current directory, creating them in the viewed subdirectory.
### Track B: Slash Commands Foundation
- **commands.js module.** New 7th JS module with command registry, parser,
autocomplete dropdown, and built-in command handlers.
- **Built-in commands:** `/help` (list commands), `/clear` (clear conversation),
`/model <name>` (switch model with fuzzy match), `/workspace <name>` (switch
workspace), `/new` (start new session).
- **Autocomplete dropdown.** Typing `/` in the composer shows a filtered
dropdown. Arrow keys navigate, Tab/Enter select, Escape closes. Positioned
above the composer using the workspace dropdown CSS pattern.
- **Transparent pass-through.** Unrecognized `/` commands pass through to the
agent normally (not intercepted).
### Track C: Send Key Setting (Issue #26)
- **`send_key` setting.** New setting in Settings panel: "Enter" (default) or
"Ctrl+Enter". Persisted to `settings.json`. Loaded on boot.
- **Keydown handler rewrite.** Combined handler for autocomplete navigation
and send key preference. When `ctrl+enter` is selected, plain Enter inserts
a newline and Ctrl/Cmd+Enter sends.
### Deferred to Sprint 18
- Thinking/reasoning display for extended-thinking models
- Voice input via Whisper
- Workspace tree/accordion view (full implementation of Issue #22)
**Tests:** 6 new (test_sprint17.py). Total: 318.
**Hermes CLI parity impact:** Low (slash commands add convenience)
**Claude parity impact:** Medium (workspace nav, slash commands match Claude UX)
---
## Sprint 18 -- Voice + Multimodal Input
**Theme:** Input beyond the keyboard.
@@ -403,7 +458,7 @@ address.
| Settings persistence | Done (Sprint 12) |
| Subagent visibility | Sprint 18 |
| Background task monitor | Sprint 18 |
| Code execution (Jupyter) | Sprint 16 |
| Code execution (Jupyter) | Sprint 17+ |
| Cron completion alerts | Done (Sprint 13) |
| Virtual scroll (perf) | Deferred |
@@ -419,8 +474,8 @@ address.
| Tool use visibility | Done (v0.11) |
| Edit/regenerate messages | Done (v0.10) |
| Session management | Done (v0.6) |
| Artifacts (HTML/SVG preview) | Sprint 16 |
| Code execution inline | Sprint 16 |
| Artifacts (HTML/SVG preview) | Sprint 17+ |
| Code execution inline | Sprint 17+ |
| Mermaid diagrams | Done (Sprint 14) |
| Projects / folders | Done (Sprint 15) |
| Pinned/starred sessions | Done (Sprint 12) |
@@ -448,6 +503,6 @@ address.
---
*Last updated: April 1, 2026*
*Current version: v0.17 | 237 tests*
*Next sprint: Sprint 16 (Artifacts + Code Execution)*
*Last updated: April 3, 2026*
*Current version: v0.19 | 318 tests*
*Next sprint: Sprint 18 (Voice + Multimodal Input)*

View File

@@ -510,8 +510,8 @@ def get_available_models() -> dict:
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}")
except Exception:
pass # custom endpoint unreachable or misconfigured -- fail silently
# 5. Build model groups
if detected_providers:
@@ -594,6 +594,7 @@ def _get_session_agent_lock(session_id: str) -> threading.Lock:
_SETTINGS_DEFAULTS = {
'default_model': DEFAULT_MODEL,
'default_workspace': str(DEFAULT_WORKSPACE),
'send_key': 'enter', # 'enter' or 'ctrl+enter'
}
def load_settings() -> dict:
@@ -609,12 +610,18 @@ def load_settings() -> dict:
return settings
_SETTINGS_ALLOWED_KEYS = set(_SETTINGS_DEFAULTS.keys())
_SETTINGS_ENUM_VALUES = {
'send_key': {'enter', 'ctrl+enter'},
}
def save_settings(settings: dict) -> dict:
"""Save settings to disk. Returns the merged settings. Ignores unknown keys."""
current = load_settings()
for k, v in settings.items():
if k in _SETTINGS_ALLOWED_KEYS:
# Validate enum-constrained keys
if k in _SETTINGS_ENUM_VALUES and v not in _SETTINGS_ENUM_VALUES[k]:
continue
current[k] = v
SETTINGS_FILE.write_text(
json.dumps(current, ensure_ascii=False, indent=2),

View File

@@ -43,14 +43,16 @@ $('importFileInput').onchange=async(e)=>{
}
};
// btnRefreshFiles is now panel-icon-btn in header (see HTML)
$('btnClearPreview').onclick=()=>{
$('previewArea').classList.remove('visible');
$('previewImg').src='';
$('previewMd').innerHTML='';
$('previewCode').textContent='';
$('previewPathText').textContent='';
$('fileTree').style.display='';
};
function clearPreview(){
const pa=$('previewArea');if(pa)pa.classList.remove('visible');
const pi=$('previewImg');if(pi)pi.src='';
const pm=$('previewMd');if(pm)pm.innerHTML='';
const pc=$('previewCode');if(pc)pc.textContent='';
const pp=$('previewPathText');if(pp)pp.textContent='';
const ft=$('fileTree');if(ft)ft.style.display='';
_previewCurrentPath='';_previewCurrentMode='';_previewDirty=false;
}
$('btnClearPreview').onclick=clearPreview;
// workspacePath click handler removed -- use topbar workspace chip dropdown instead
$('modelSelect').onchange=async()=>{
if(!S.session)return;
@@ -59,8 +61,37 @@ $('modelSelect').onchange=async()=>{
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();
};
$('msg').addEventListener('input',autoResize);
$('msg').addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();send();}});
$('msg').addEventListener('input',()=>{
autoResize();
const text=$('msg').value;
if(text.startsWith('/')&&text.indexOf('\n')===-1){
const prefix=text.slice(1);
const matches=getMatchingCommands(prefix);
if(matches.length)showCmdDropdown(matches); else hideCmdDropdown();
} else {
hideCmdDropdown();
}
});
$('msg').addEventListener('keydown',e=>{
// Autocomplete navigation when dropdown is open
const dd=$('cmdDropdown');
const dropdownOpen=dd&&dd.classList.contains('open');
if(dropdownOpen){
if(e.key==='ArrowUp'){e.preventDefault();navigateCmdDropdown(-1);return;}
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;}
}
// Send key: respect user preference
if(e.key==='Enter'){
if(window._sendKey==='ctrl+enter'){
if(e.ctrlKey||e.metaKey){e.preventDefault();send();}
} else {
if(!e.shiftKey){e.preventDefault();send();}
}
}
});
// B14: Cmd/Ctrl+K creates a new chat from anywhere
document.addEventListener('keydown',async e=>{
if((e.metaKey||e.ctrlKey)&&e.key==='k'){
@@ -151,6 +182,8 @@ document.querySelectorAll('.suggestion').forEach(btn=>{
})();
(async()=>{
// Load send key preference
try{const s=await api('/api/settings');window._sendKey=s.send_key||'enter';}catch(e){window._sendKey='enter';}
// Fetch available models from server and populate dropdown dynamically
await populateModelDropdown();
// Restore last-used model preference

156
static/commands.js Normal file
View File

@@ -0,0 +1,156 @@
// ── Slash commands ──────────────────────────────────────────────────────────
// Built-in commands intercepted before send(). Each command runs locally
// (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:'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},
];
function parseCommand(text){
if(!text.startsWith('/'))return null;
const parts=text.slice(1).split(/\s+/);
const name=parts[0].toLowerCase();
const args=parts.slice(1).join(' ').trim();
return {name,args};
}
function executeCommand(text){
const parsed=parseCommand(text);
if(!parsed)return false;
const cmd=COMMANDS.find(c=>c.name===parsed.name);
if(!cmd)return false;
cmd.fn(parsed.args);
return true;
}
function getMatchingCommands(prefix){
const q=prefix.toLowerCase();
return COMMANDS.filter(c=>c.name.startsWith(q));
}
// ── Command handlers ────────────────────────────────────────────────────────
function cmdHelp(){
const lines=COMMANDS.map(c=>{
const usage=c.arg?` <${c.arg}>`:'';
return ` /${c.name}${usage}${c.desc}`;
});
const msg={role:'assistant',content:'**Available commands:**\n'+lines.join('\n')};
S.messages.push(msg);
renderMessages();
showToast('Type / to see commands');
}
function cmdClear(){
if(!S.session)return;
S.messages=[];S.toolCalls=[];
clearLiveToolCards();
renderMessages();
$('emptyState').style.display='';
showToast('Conversation cleared');
}
async function cmdModel(args){
if(!args){showToast('Usage: /model <name>');return;}
const sel=$('modelSelect');
if(!sel)return;
const q=args.toLowerCase();
// Fuzzy match: find first option whose label or value contains the query
let match=null;
for(const opt of sel.options){
if(opt.value.toLowerCase().includes(q)||opt.textContent.toLowerCase().includes(q)){
match=opt.value;break;
}
}
if(!match){showToast(`No model matching "${args}"`);return;}
sel.value=match;
await sel.onchange();
showToast(`Switched to ${match}`);
}
async function cmdWorkspace(args){
if(!args){showToast('Usage: /workspace <name>');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);}
}
async function cmdNew(){
await newSession();
await renderSessionList();
$('msg').focus();
showToast('New session created');
}
// ── Autocomplete dropdown ───────────────────────────────────────────────────
let _cmdSelectedIdx=-1;
function showCmdDropdown(matches){
const dd=$('cmdDropdown');
if(!dd)return;
dd.innerHTML='';
_cmdSelectedIdx=-1;
for(let i=0;i<matches.length;i++){
const c=matches[i];
const el=document.createElement('div');
el.className='cmd-item';
el.dataset.idx=i;
const usage=c.arg?` <span class="cmd-item-arg">${esc(c.arg)}</span>`:'';
el.innerHTML=`<div class="cmd-item-name">/${esc(c.name)}${usage}</div><div class="cmd-item-desc">${esc(c.desc)}</div>`;
el.onmousedown=(e)=>{
e.preventDefault();
$('msg').value='/'+c.name+(c.arg?' ':'');
hideCmdDropdown();
$('msg').focus();
};
dd.appendChild(el);
}
dd.classList.add('open');
}
function hideCmdDropdown(){
const dd=$('cmdDropdown');
if(dd)dd.classList.remove('open');
_cmdSelectedIdx=-1;
}
function navigateCmdDropdown(dir){
const dd=$('cmdDropdown');
if(!dd)return;
const items=dd.querySelectorAll('.cmd-item');
if(!items.length)return;
items.forEach(el=>el.classList.remove('selected'));
_cmdSelectedIdx+=dir;
if(_cmdSelectedIdx<0)_cmdSelectedIdx=items.length-1;
if(_cmdSelectedIdx>=items.length)_cmdSelectedIdx=0;
items[_cmdSelectedIdx].classList.add('selected');
}
function selectCmdDropdownItem(){
const dd=$('cmdDropdown');
if(!dd)return;
const items=dd.querySelectorAll('.cmd-item');
if(_cmdSelectedIdx>=0&&_cmdSelectedIdx<items.length){
items[_cmdSelectedIdx].onmousedown({preventDefault:()=>{}});
} else if(items.length===1){
items[0].onmousedown({preventDefault:()=>{}});
}
hideCmdDropdown();
}

View File

@@ -13,7 +13,7 @@
<body>
<div class="layout">
<aside class="sidebar">
<div class="sidebar-header"><div class="logo">H</div><div><h1 style="margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em">Hermes</h1><div style="font-size:10px;color:var(--muted);opacity:.8;margin-top:1px">v0.17.1</div></div></div>
<div class="sidebar-header"><div class="logo">H</div><div><h1 style="margin:0;font-size:15px;font-weight:700;letter-spacing:-.01em">Hermes</h1><div style="font-size:10px;color:var(--muted);opacity:.8;margin-top:1px">v0.20</div></div></div>
<div class="sidebar-nav">
<button class="nav-tab active" data-panel="chat" data-label="Chat" onclick="switchPanel('chat')" title="Chat">&#128172;</button>
<button class="nav-tab" data-panel="tasks" data-label="Tasks" onclick="switchPanel('tasks')" title="Tasks">&#128197;</button>
@@ -206,6 +206,7 @@
</div>
</div>
<div class="composer-wrap" id="composerWrap">
<div class="cmd-dropdown" id="cmdDropdown"></div>
<div class="composer-box" id="composerBox">
<div class="drop-hint" id="dropHint">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><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>
@@ -236,12 +237,14 @@
<div class="panel-header">
<span>Workspace</span>
<div class="panel-actions">
<button class="panel-icon-btn" id="btnUpDir" title="Parent directory" onclick="navigateUp()" style="display:none">&#8593;</button>
<button class="panel-icon-btn" id="btnNewFile" title="New file" onclick="promptNewFile()">&#43;</button>
<button class="panel-icon-btn" id="btnNewFolder" title="New folder" onclick="promptNewFolder()">&#128193;</button>
<button class="panel-icon-btn" id="btnRefreshPanel" title="Refresh" onclick="if(S.session)loadDir('.')">&#8635;</button>
<button class="panel-icon-btn" id="btnRefreshPanel" title="Refresh" onclick="if(S.session)loadDir(S.currentDir)">&#8635;</button>
<button class="panel-icon-btn close-preview" id="btnClearPreview" title="Close preview">&#10005;</button>
</div>
</div>
<div class="breadcrumb-bar" id="breadcrumbBar" style="display:none"></div>
<div class="file-tree" id="fileTree"></div>
<div class="preview-area" id="previewArea">
<div class="preview-path" id="previewPath">
@@ -272,6 +275,13 @@
<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>
<button class="sm-btn" onclick="saveSettings()" style="margin-top:12px;width:100%;padding:8px;font-weight:600">Save Settings</button>
</div>
</div>
@@ -280,6 +290,7 @@
<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>

View File

@@ -1,6 +1,10 @@
async function send(){
const text=$('msg').value.trim();
if(!text&&!S.pendingFiles.length)return;
// Slash command intercept -- local commands handled without agent round-trip
if(text.startsWith('/')&&!S.pendingFiles.length&&executeCommand(text)){
$('msg').value='';autoResize();hideCmdDropdown();return;
}
// Don't send while an inline message edit is active
if(document.querySelector('.msg-edit-area'))return;
// If busy, queue the message instead of dropping it

View File

@@ -646,6 +646,9 @@ async function loadSettingsPanel(){
}catch(e){}
wsSel.value=settings.default_workspace||'';
}
// Send key preference
const sendKeySel=$('settingsSendKey');
if(sendKeySel) sendKeySel.value=settings.send_key||'enter';
}catch(e){
showToast('Failed to load settings: '+e.message);
}
@@ -654,11 +657,14 @@ async function loadSettingsPanel(){
async function saveSettings(){
const model=($('settingsModel')||{}).value;
const workspace=($('settingsWorkspace')||{}).value;
const sendKey=($('settingsSendKey')||{}).value;
const body={};
if(model) body.default_model=model;
if(workspace) body.default_workspace=workspace;
if(sendKey) body.send_key=sendKey;
try{
await api('/api/settings',{method:'POST',body:JSON.stringify(body)});
window._sendKey=sendKey||'enter';
showToast('Settings saved');
toggleSettings();
}catch(e){

View File

@@ -1,3 +1,14 @@
// ── Session action icons (SVG, monochrome, inherit currentColor) ──
const ICONS={
pin:'<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor" stroke="none"><polygon points="8,1.5 9.8,5.8 14.5,6.2 11,9.4 12,14 8,11.5 4,14 5,9.4 1.5,6.2 6.2,5.8"/></svg>',
unpin:'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><polygon points="8,2 9.8,6.2 14.2,6.2 10.7,9.2 12,13.8 8,11 4,13.8 5.3,9.2 1.8,6.2 6.2,6.2"/></svg>',
folder:'<svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3"><path d="M2 4.5h4l1.5 1.5H14v7H2z"/></svg>',
archive:'<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"/><line x1="6" y1="8.5" x2="10" y2="8.5"/></svg>',
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>',
};
async function newSession(flash){
MSG_QUEUE.length=0;updateQueueBadge();
S.toolCalls=[];
@@ -242,11 +253,35 @@ function renderSessionListFromCache(){
setTimeout(()=>{inp.focus();inp.select();},10);
};
const pin=document.createElement('span');
pin.className='session-pin'+(s.pinned?' pinned':'');
pin.innerHTML=s.pinned?'&#9733;':'&#9734;';
pin.title=s.pinned?'Unpin':'Pin to top';
pin.onclick=async(e)=>{
// Pin indicator (inline, only when pinned — no space reserved otherwise)
if(s.pinned){
const pinInd=document.createElement('span');
pinInd.className='session-pin-indicator';
pinInd.innerHTML=ICONS.pin;
el.appendChild(pinInd);
}
// Project indicator: colored left border (active item keeps its own gold color)
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)';
dot.title=proj.name;
title.appendChild(dot);
}
}
el.appendChild(title);
// Action buttons overlay (appears on hover with gradient fade)
const actions=document.createElement('div');
actions.className='session-actions';
// Pin toggle
const pinBtn=document.createElement('button');
pinBtn.className='act-pin'+(s.pinned?' pinned':'');
pinBtn.innerHTML=s.pinned?ICONS.pin:ICONS.unpin;
pinBtn.title=s.pinned?'Unpin':'Pin to top';
pinBtn.onclick=async(e)=>{
e.stopPropagation();e.preventDefault();
const newPinned=!s.pinned;
try{
@@ -256,8 +291,15 @@ function renderSessionListFromCache(){
renderSessionList();
}catch(err){showToast('Pin failed: '+err.message);}
};
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='session-action-btn';archive.innerHTML=s.archived?'&#9993;':'&#128230;';
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();
@@ -269,8 +311,10 @@ function renderSessionListFromCache(){
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='session-dup';dup.innerHTML='&#10697;';dup.title='Duplicate';
dup.className='act-dup';dup.innerHTML=ICONS.dup;dup.title='Duplicate';
dup.onclick=async(e)=>{
e.stopPropagation();e.preventDefault();
try{
@@ -282,25 +326,13 @@ function renderSessionListFromCache(){
}
}catch(err){showToast('Duplicate failed: '+err.message);}
};
actions.appendChild(dup);
// Trash
const trash=document.createElement('button');
trash.className='session-trash';trash.innerHTML='&#128465;';trash.title='Delete';
trash.className='act-trash';trash.innerHTML=ICONS.trash;trash.title='Delete';
trash.onclick=async(e)=>{e.stopPropagation();e.preventDefault();await deleteSession(s.session_id);};
// Project move button (folder icon)
const move=document.createElement('button');
move.className='session-action-btn'+(s.project_id?' has-project':'');move.innerHTML='&#128194;';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);
actions.appendChild(trash);
el.appendChild(actions);
// 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,
@@ -308,7 +340,7 @@ function renderSessionListFromCache(){
let _clickTimer=null;
el.onclick=async(e)=>{
if(_renamingSid) return; // ignore while any rename is active
if([trash,dup,archive,move].some(b=>e.target===b||b.contains(e.target))) return;
if(actions.contains(e.target)) return;
clearTimeout(_clickTimer);
_clickTimer=setTimeout(async()=>{
_clickTimer=null;
@@ -360,15 +392,13 @@ function _showProjectPicker(session, anchorEl){
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();
document.removeEventListener('click',close);
await api('/api/session/move',{method:'POST',body:JSON.stringify({session_id:session.session_id,project_id:null})});
session.project_id=null;
renderSessionListFromCache();
@@ -389,8 +419,8 @@ function _showProjectPicker(session, anchorEl){
name.textContent=p.name;
item.appendChild(name);
item.onclick=async()=>{
document.removeEventListener('click',close);
picker.remove();
document.removeEventListener('click',close);
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();
@@ -398,19 +428,21 @@ function _showProjectPicker(session, anchorEl){
};
picker.appendChild(item);
}
// "+ New project" item
// "+ New project" shortcut at the bottom
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);
// Prompt for name inline
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);
// Now move session into it
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();
@@ -418,11 +450,13 @@ function _showProjectPicker(session, anchorEl){
}
};
picker.appendChild(createItem);
// Position picker on document.body to avoid overflow:hidden clipping
// Append to body and position using getBoundingClientRect so it isn't clipped
// by overflow:hidden on .session-item ancestors
document.body.appendChild(picker);
const rect=anchorEl.getBoundingClientRect();
picker.style.position='fixed';
picker.style.zIndex='999';
// Prefer opening below; flip above if too close to bottom of viewport
const spaceBelow=window.innerHeight-rect.bottom;
if(spaceBelow<160&&rect.top>160){
picker.style.bottom=(window.innerHeight-rect.top+4)+'px';
@@ -431,10 +465,13 @@ function _showProjectPicker(session, anchorEl){
picker.style.top=(rect.bottom+4)+'px';
picker.style.bottom='auto';
}
const pickerW=160;
// Align right edge of picker with right edge of button; keep within viewport
const pickerW=Math.min(220,Math.max(160,picker.scrollWidth||160));
let left=rect.right-pickerW;
if(left<8) left=8;
picker.style.left=left+'px';
// Close on outside click
const close=(e)=>{if(!picker.contains(e.target)&&e.target!==anchorEl){picker.remove();document.removeEventListener('click',close);}};
setTimeout(()=>document.addEventListener('click',close),0);
}

View File

@@ -20,13 +20,21 @@
.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:8px;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;}
.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(124,185,255,0.1);color:var(--blue);border-left:2px solid var(--blue);padding-left:8px;}
.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-trash{flex-shrink:0;opacity:0;font-size:13px;color:var(--muted);background:none;border:none;cursor:pointer;padding:0 2px;line-height:1;transition:opacity .15s,color .15s;}
.session-item:hover .session-trash{opacity:1;}
.session-trash:hover{color:var(--accent)!important;}
/* ── 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;}
/* 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);}}
.session-item.new-flash{animation:newflash 1.4s ease-out forwards;}
.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;}
@@ -197,10 +205,20 @@
.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;}
.file-action-btn:hover{color:var(--accent);}
.close-preview{cursor:pointer;opacity:.6;}.close-preview:hover{opacity:1;}
/* Breadcrumb navigation */
.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-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: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;}
.file-item.file-empty{color:var(--muted);opacity:.5;font-style:italic;cursor:default;font-size:11px;}
.file-item.file-empty:hover{background:none;color:var(--muted);}
.preview-area{flex:1;overflow:auto;padding:14px;flex-direction:column;gap:8px;display:none;opacity:0;transition:opacity .15s;}
.preview-area.visible{display:flex;opacity:1;}
.preview-path{font-size:11px;color:var(--muted);padding-bottom:8px;border-bottom:1px solid var(--border);flex-shrink:0;}
@@ -289,6 +307,14 @@
.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:hover{background:rgba(255,255,255,.1);color:var(--text);}
/* ── 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.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);}
.cmd-item-name{font-size:13px;color:var(--text);font-weight:500;}
.cmd-item-arg{color:var(--muted);font-weight:400;font-style:italic;}
.cmd-item-desc{font-size:11px;color:var(--muted);margin-top:1px;}
.ws-action-btn.danger:hover{background:rgba(233,69,96,.12);color:var(--accent);border-color:rgba(233,69,96,.3);}
.ws-add-row{display:flex;gap:8px;align-items:center;padding:10px 0 4px;}
/* ── Message action buttons (copy, edit, retry) ── */
@@ -344,7 +370,7 @@
.msg-role > span{line-height:1;}
/* Composer wrap: slightly less padding on smaller heights */
.composer-wrap{border-top:1px solid rgba(255,255,255,.07);padding:10px 20px 14px;}
.composer-wrap{border-top:1px solid rgba(255,255,255,.07);padding:10px 20px 14px;position:relative;}
/* Cron status badges: pill shape refinement */
.cron-status{border-radius:99px;font-size:10px;letter-spacing:.04em;}
@@ -495,17 +521,9 @@ body.resizing{user-select:none;cursor:col-resize;}
.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 star ── */
.session-pin{font-size:12px;cursor:pointer;opacity:0;transition:opacity .15s;padding:2px 4px;flex-shrink:0;}
.session-item:hover .session-pin,.session-pin.pinned{opacity:1;}
.session-pin.pinned{color:#f5c542;}
/* ── Session duplicate button ── */
.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;}
/* ── Session pin indicator (inline, only when pinned) ── */
.session-pin-indicator{flex-shrink:0;color:#f5c542;line-height:1;display:flex;align-items:center;}
.session-pin-indicator svg{width:10px;height:10px;}
/* ── 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;}
@@ -540,7 +558,7 @@ body.resizing{user-select:none;cursor:col-resize;}
.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{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);}
.project-picker-item.active{color:var(--blue);}
@@ -557,4 +575,16 @@ body.resizing{user-select:none;cursor:col-resize;}
.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;}
/* ── Thinking/reasoning card ── */
.thinking-card{background:rgba(201,168,76,.06);border:1px solid rgba(201,168,76,.2);border-radius:10px;margin:4px 0 2px 40px;overflow:hidden;transition:border-color .15s;}
.thinking-card:hover{border-color:rgba(201,168,76,.35);}
.thinking-card-header{display:flex;align-items:center;gap:6px;padding:6px 12px;cursor:pointer;font-size:12px;color:var(--gold);user-select:none;}
.thinking-card-icon{font-size:14px;}
.thinking-card-label{font-weight:600;letter-spacing:.02em;}
.thinking-card-toggle{margin-left:auto;font-size:10px;transition:transform .15s;}
.thinking-card.open .thinking-card-toggle{transform:rotate(90deg);}
.thinking-card-body{display:none;padding:0 12px 10px;max-height:300px;overflow-y:auto;}
.thinking-card.open .thinking-card-body{display:block;}
.thinking-card-body pre{font-family:'SF Mono',ui-monospace,monospace;font-size:11px;line-height:1.5;color:var(--muted);white-space:pre-wrap;word-break:break-word;margin:0;}
.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;}

View File

@@ -1,4 +1,4 @@
const S={session:null,messages:[],entries:[],busy:false,pendingFiles:[],toolCalls:[],activeStreamId:null};
const S={session:null,messages:[],entries:[],busy:false,pendingFiles:[],toolCalls:[],activeStreamId:null,currentDir:'.'};
const INFLIGHT={}; // keyed by session_id while request in-flight
const MSG_QUEUE=[]; // messages queued while a request is in-flight
const $=id=>document.getElementById(id);
@@ -81,6 +81,22 @@ function getModelLabel(modelId){
function renderMd(raw){
let s=raw||'';
// Pre-pass: convert safe inline HTML tags the model may emit into their
// markdown equivalents so the pipeline can render them correctly.
// Only runs OUTSIDE fenced code blocks and backtick spans (stash + restore).
// Unsafe tags (anything not in the allowlist) are left as-is and will be
// HTML-escaped by esc() when they reach an innerHTML assignment -- no XSS risk.
const fence_stash=[];
s=s.replace(/(```[\s\S]*?```|`[^`\n]+`)/g,m=>{fence_stash.push(m);return '\x00F'+(fence_stash.length-1)+'\x00';});
// Safe tag → markdown equivalent (these produce the same output as **text** etc.)
s=s.replace(/<strong>([\s\S]*?)<\/strong>/gi,(_,t)=>'**'+t+'**');
s=s.replace(/<b>([\s\S]*?)<\/b>/gi,(_,t)=>'**'+t+'**');
s=s.replace(/<em>([\s\S]*?)<\/em>/gi,(_,t)=>'*'+t+'*');
s=s.replace(/<i>([\s\S]*?)<\/i>/gi,(_,t)=>'*'+t+'*');
s=s.replace(/<code>([^<]*?)<\/code>/gi,(_,t)=>'`'+t+'`');
s=s.replace(/<br\s*\/?>/gi,'\n');
// Restore stashed code blocks
s=s.replace(/\x00F(\d+)\x00/g,(_,i)=>fence_stash[+i]);
// Mermaid blocks: render as diagram containers (processed after DOM insertion)
s=s.replace(/```mermaid\n?([\s\S]*?)```/g,(_,code)=>{
const id='mermaid-'+Math.random().toString(36).slice(2,10);
@@ -88,12 +104,27 @@ 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>`);
// inlineMd: process bold/italic/code/links within a single line of text.
// Used inside list items and blockquotes where the text may already contain
// HTML from the pre-pass → bold pipeline, so we cannot call esc() directly.
function inlineMd(t){
t=t.replace(/\*\*\*(.+?)\*\*\*/g,(_,x)=>`<strong><em>${esc(x)}</em></strong>`);
t=t.replace(/\*\*(.+?)\*\*/g,(_,x)=>`<strong>${esc(x)}</strong>`);
t=t.replace(/\*([^*\n]+)\*/g,(_,x)=>`<em>${esc(x)}</em>`);
t=t.replace(/`([^`\n]+)`/g,(_,x)=>`<code>${esc(x)}</code>`);
t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g,(_,lb,u)=>`<a href="${esc(u)}" target="_blank" rel="noopener">${esc(lb)}</a>`);
// Escape any plain text that isn't already wrapped in a tag we produced
// by escaping bare < > that aren't part of our own tags
const SAFE_INLINE=/^<\/?(strong|em|code|a)([\s>]|$)/i;
t=t.replace(/<\/?[a-z][^>]*>/gi,tag=>SAFE_INLINE.test(tag)?tag:esc(tag));
return t;
}
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,(_,t)=>`<h3>${inlineMd(t)}</h3>`).replace(/^## (.+)$/gm,(_,t)=>`<h2>${inlineMd(t)}</h2>`).replace(/^# (.+)$/gm,(_,t)=>`<h1>${inlineMd(t)}</h1>`);
s=s.replace(/^---+$/gm,'<hr>');
s=s.replace(/^> (.+)$/gm,(_,t)=>`<blockquote>${esc(t)}</blockquote>`);
s=s.replace(/^> (.+)$/gm,(_,t)=>`<blockquote>${inlineMd(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 +132,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">${esc(text)}</li>`;
else html+=`<li>${esc(text)}</li>`;
if(indent) html+=`<li style="margin-left:16px">${inlineMd(text)}</li>`;
else html+=`<li>${inlineMd(text)}</li>`;
}
return html+'</ul>';
});
@@ -111,7 +142,7 @@ function renderMd(raw){
let html='<ol>';
for(const l of lines){
const text=l.replace(/^ {0,4}\d+\. /,'');
html+=`<li>${esc(text)}</li>`;
html+=`<li>${inlineMd(text)}</li>`;
}
return html+'</ol>';
});
@@ -128,6 +159,12 @@ function renderMd(raw){
const body=rows.slice(2).map(r=>`<tr>${parseRow(r)}</tr>`).join('');
return `<table><thead>${header}</thead><tbody>${body}</tbody></table>`;
});
// Escape any remaining HTML tags that are NOT from our own markdown output.
// Our pipeline only emits: <strong>,<em>,<code>,<pre>,<h1-6>,<ul>,<ol>,<li>,
// <table>,<thead>,<tbody>,<tr>,<th>,<td>,<hr>,<blockquote>,<p>,<br>,<a>,
// <div class="..."> (mermaid/pre-header). Everything else is untrusted input.
const SAFE_TAGS=/^<\/?(strong|em|code|pre|h[1-6]|ul|ol|li|table|thead|tbody|tr|th|td|hr|blockquote|p|br|a|div)([\s>]|$)/i;
s=s.replace(/<\/?[a-z][^>]*>/gi,tag=>SAFE_TAGS.test(tag)?tag:esc(tag));
const parts=s.split(/\n{2,}/);
s=parts.map(p=>{p=p.trim();if(!p)return '';if(/^<(h[1-6]|ul|ol|pre|hr|blockquote)/.test(p))return p;return `<p>${p.replace(/\n/g,'<br>')}</p>`;}).join('\n');
return s;
@@ -328,9 +365,20 @@ function renderMessages(){
for(let vi=0;vi<visWithIdx.length;vi++){
const {m,rawIdx}=visWithIdx[vi];
let content=m.content||'';
if(Array.isArray(content))content=content.filter(p=>p&&p.type==='text').map(p=>p.text||p.content||'').join('\n');
// Extract thinking/reasoning blocks from structured content (Claude extended thinking, o3)
let thinkingText='';
if(Array.isArray(content)){
thinkingText=content.filter(p=>p&&(p.type==='thinking'||p.type==='reasoning')).map(p=>p.thinking||p.reasoning||p.text||'').join('\n');
content=content.filter(p=>p&&p.type==='text').map(p=>p.text||p.content||'').join('\n');
}
const isUser=m.role==='user';
const isLastAssistant=!isUser&&vi===visWithIdx.length-1;
// Render thinking card before the assistant message (collapsed by default)
if(thinkingText&&!isUser){
const thinkRow=document.createElement('div');thinkRow.className='msg-row thinking-card-row';
thinkRow.innerHTML=`<div class="thinking-card"><div class="thinking-card-header" onclick="this.parentElement.classList.toggle('open')"><span class="thinking-card-icon">&#128161;</span><span class="thinking-card-label">Thinking</span><span class="thinking-card-toggle">&#9656;</span></div><div class="thinking-card-body"><pre>${esc(thinkingText)}</pre></div></div>`;
inner.appendChild(thinkRow);
}
const row=document.createElement('div');row.className='msg-row';
row.dataset.msgIdx=rawIdx;
let filesHtml='';
@@ -668,27 +716,88 @@ function fileIcon(name, type){
return '📄';
}
function renderBreadcrumb(){
const bar=$('breadcrumbBar');
const upBtn=$('btnUpDir');
if(!bar)return;
if(S.currentDir==='.'){
bar.style.display='none';
if(upBtn)upBtn.style.display='none';
return;
}
bar.style.display='flex';
if(upBtn)upBtn.style.display='';
bar.innerHTML='';
// Root segment
const root=document.createElement('span');
root.className='breadcrumb-seg breadcrumb-link';
root.textContent='~';
root.onclick=()=>loadDir('.');
bar.appendChild(root);
// Path segments
const parts=S.currentDir.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=()=>loadDir(target);
} else {
seg.className='breadcrumb-seg breadcrumb-current';
}
bar.appendChild(seg);
}
}
// Track expanded directories for tree view
if(!S._expandedDirs) S._expandedDirs=new Set();
// Cache of fetched directory contents: path -> entries[]
if(!S._dirCache) S._dirCache={};
function renderFileTree(){
const box=$('fileTree');box.innerHTML='';
for(const item of S.entries){
// Cache current dir entries
S._dirCache[S.currentDir||'.']=S.entries;
_renderTreeItems(box, S.entries, 0);
}
function _renderTreeItems(container, entries, depth){
for(const item of entries){
const el=document.createElement('div');el.className='file-item';
el.style.paddingLeft=(8+depth*16)+'px';
if(item.type==='dir'){
// Toggle arrow for directories
const arrow=document.createElement('span');
arrow.className='file-tree-toggle';
const isExpanded=S._expandedDirs.has(item.path);
arrow.textContent=isExpanded?'\u25BE':'\u25B8';
el.appendChild(arrow);
}
// Icon
const iconEl=document.createElement('span');
iconEl.className='file-icon';iconEl.textContent=fileIcon(item.name,item.type);
el.appendChild(iconEl);
// Name -- takes all remaining space, truncates with ellipsis
// Name
const nameEl=document.createElement('span');
nameEl.className='file-name';nameEl.textContent=item.name;nameEl.title='Double-click to rename';
// Inline rename on double-click
nameEl.ondblclick=(e)=>{
e.stopPropagation();
// For directories, double-click navigates (breadcrumb view)
if(item.type==='dir'){loadDir(item.path);return;}
const inp=document.createElement('input');
inp.className='file-rename-input';inp.value=item.name;
inp.onclick=(e2)=>e2.stopPropagation();
const finish=async(save)=>{
inp.onblur=null; // prevent double-call: Enter triggers blur after replaceWith
inp.onblur=null;
if(save){
const newName=inp.value.trim();
if(newName&&newName!==item.name){
@@ -697,7 +806,9 @@ function renderFileTree(){
session_id:S.session.session_id,path:item.path,new_name:newName
})});
showToast(`Renamed to ${newName}`);
await loadDir('.');
// Invalidate cache and re-render
delete S._dirCache[S.currentDir];
await loadDir(S.currentDir);
}catch(err){showToast('Rename failed: '+err.message);}
}
}
@@ -713,7 +824,7 @@ function renderFileTree(){
};
el.appendChild(nameEl);
// Size -- only for files, right-aligned, shrinks but never wraps
// Size -- only for files
if(item.type==='file'&&item.size){
const sizeEl=document.createElement('span');
sizeEl.className='file-size';
@@ -721,16 +832,52 @@ function renderFileTree(){
el.appendChild(sizeEl);
}
// Delete button -- for files, shown on hover
// Delete button -- for files
if(item.type==='file'){
const del=document.createElement('button');
del.className='file-del-btn';del.title='Delete';del.textContent='×';
del.className='file-del-btn';del.title='Delete';del.textContent='\u00d7';
del.onclick=async(e)=>{e.stopPropagation();await deleteWorkspaceFile(item.path,item.name);};
el.appendChild(del);
}
el.onclick=async()=>item.type==='dir'?loadDir(item.path):openFile(item.path);
box.appendChild(el);
if(item.type==='dir'){
// Single-click toggles expand/collapse
el.onclick=async(e)=>{
e.stopPropagation();
if(S._expandedDirs.has(item.path)){
S._expandedDirs.delete(item.path);
renderFileTree();
}else{
S._expandedDirs.add(item.path);
// Fetch children if not cached
if(!S._dirCache[item.path]){
try{
const data=await api(`/api/list?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(item.path)}`);
S._dirCache[item.path]=data.entries||[];
}catch(e2){S._dirCache[item.path]=[];}
}
renderFileTree();
}
};
}else{
el.onclick=async()=>openFile(item.path);
}
container.appendChild(el);
// Render children if directory is expanded
if(item.type==='dir'&&S._expandedDirs.has(item.path)){
const children=S._dirCache[item.path]||[];
if(children.length){
_renderTreeItems(container, children, depth+1);
}else{
const empty=document.createElement('div');
empty.className='file-item file-empty';
empty.style.paddingLeft=(8+(depth+1)*16)+'px';
empty.textContent='(empty)';
container.appendChild(empty);
}
}
}
}
@@ -742,7 +889,7 @@ async function deleteWorkspaceFile(relPath, name){
showToast(`Deleted ${name}`);
// Close preview if we just deleted the viewed file
if($('previewPathText').textContent===relPath)$('btnClearPreview').onclick();
await loadDir('.');
await loadDir(S.currentDir);
}catch(e){setStatus('Delete failed: '+e.message);}
}
@@ -750,12 +897,12 @@ async function promptNewFile(){
if(!S.session)return;
const name=prompt('New file name (e.g. notes.md):','');
if(!name||!name.trim())return;
const relPath=S.currentDir==='.'?name.trim():(S.currentDir+'/'+name.trim());
try{
await api('/api/file/create',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,path:name.trim(),content:''})});
await api('/api/file/create',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,path:relPath,content:''})});
showToast(`Created ${name.trim()}`);
await loadDir('.');
// Open the new file immediately
openFile(name.trim());
await loadDir(S.currentDir);
openFile(relPath);
}catch(e){setStatus('Create failed: '+e.message);}
}
@@ -763,10 +910,11 @@ async function promptNewFolder(){
if(!S.session)return;
const name=prompt('New folder name:','');
if(!name||!name.trim())return;
const relPath=S.currentDir==='.'?name.trim():(S.currentDir+'/'+name.trim());
try{
await api('/api/file/create-dir',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,path:name.trim()})});
await api('/api/file/create-dir',{method:'POST',body:JSON.stringify({session_id:S.session.session_id,path:relPath})});
showToast(`Created folder ${name.trim()}`);
await loadDir('.');
await loadDir(S.currentDir);
}catch(e){setStatus('Create folder failed: '+e.message);}
}

View File

@@ -9,11 +9,27 @@ async function api(path,opts={}){
async function loadDir(path){
if(!S.session)return;
try{
if(!path||path==='.'){ S._dirCache={}; if(S._expandedDirs)S._expandedDirs=new Set(); }
S.currentDir=path||'.';
const data=await api(`/api/list?session_id=${encodeURIComponent(S.session.session_id)}&path=${encodeURIComponent(path)}`);
S.entries=data.entries||[];renderFileTree();
S.entries=data.entries||[];renderBreadcrumb();renderFileTree();
if(typeof clearPreview==='function'){
if(typeof _previewDirty!=='undefined'&&_previewDirty){
if(confirm('You have unsaved changes in the preview. Discard and navigate?'))clearPreview();
}else{
clearPreview();
}
}
}catch(e){console.warn('loadDir',e);}
}
function navigateUp(){
if(!S.session||S.currentDir==='.')return;
const parts=S.currentDir.split('/');
parts.pop();
loadDir(parts.length?parts.join('/'):'.');
}
// File extension sets for preview routing (must match server-side sets)
const IMAGE_EXTS = new Set(['.png','.jpg','.jpeg','.gif','.svg','.webp','.ico','.bmp']);
const MD_EXTS = new Set(['.md','.markdown','.mdown']);

709
tests/test_sprint16.py Normal file
View File

@@ -0,0 +1,709 @@
"""
Sprint 16 Tests: safe HTML rendering in renderMd(), active session styling,
session sidebar polish (SVG icons, overlay actions).
"""
import html as _html
import pathlib
import re
import urllib.request
BASE = "http://127.0.0.1:8788"
REPO_ROOT = pathlib.Path(__file__).parent.parent
# ── Helpers ──────────────────────────────────────────────────────────────────
def get_text(path):
with urllib.request.urlopen(BASE + path, timeout=10) as r:
return r.read().decode("utf-8"), r.status
def esc(s):
"""Mirror of esc() in ui.js — HTML-escapes a string."""
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|div)([\s>]|$)",
re.I,
)
SAFE_INLINE = re.compile(r"^<\/?(strong|em|code|a)([\s>]|$)", re.I)
def inline_md(t):
"""Mirror of inlineMd() in ui.js — for use inside list items / blockquotes."""
t = re.sub(r"\*\*\*(.+?)\*\*\*", lambda m: "<strong><em>" + esc(m.group(1)) + "</em></strong>", t)
t = re.sub(r"\*\*(.+?)\*\*", lambda m: "<strong>" + esc(m.group(1)) + "</strong>", t)
t = re.sub(r"\*([^*\n]+)\*", lambda m: "<em>" + esc(m.group(1)) + "</em>", t)
t = re.sub(r"`([^`\n]+)`", lambda m: "<code>" + esc(m.group(1)) + "</code>", t)
t = re.sub(
r"\[([^\]]+)\]\((https?://[^\)]+)\)",
lambda m: f'<a href="{esc(m.group(2))}" target="_blank" rel="noopener">{esc(m.group(1))}</a>',
t,
)
t = re.sub(r"</?[a-zA-Z][^>]*>", lambda m: m.group() if SAFE_INLINE.match(m.group()) else esc(m.group()), t)
return t
def render_md(raw):
"""
Python mirror of renderMd() in static/ui.js.
Kept in sync with the JS implementation so tests catch regressions
if the JS logic drifts from the documented behaviour.
"""
s = raw or ""
# Pre-pass: stash code blocks/spans, convert safe HTML → markdown equivalents
fence_stash = []
def stash(m):
fence_stash.append(m.group())
return "\x00F" + str(len(fence_stash) - 1) + "\x00"
s = re.sub(r"(```[\s\S]*?```|`[^`\n]+`)", stash, s)
s = re.sub(r"<strong>([\s\S]*?)</strong>", lambda m: "**" + m.group(1) + "**", s, flags=re.I)
s = re.sub(r"<b>([\s\S]*?)</b>", lambda m: "**" + m.group(1) + "**", s, flags=re.I)
s = re.sub(r"<em>([\s\S]*?)</em>", lambda m: "*" + m.group(1) + "*", s, flags=re.I)
s = re.sub(r"<i>([\s\S]*?)</i>", lambda m: "*" + m.group(1) + "*", s, flags=re.I)
s = re.sub(r"<code>([^<]*?)</code>", lambda m: "`" + m.group(1) + "`", s, flags=re.I)
s = re.sub(r"<br\s*/?>", "\n", s, flags=re.I)
s = re.sub(r"\x00F(\d+)\x00", lambda m: fence_stash[int(m.group(1))], s)
# Fenced code blocks
def fenced(m):
lang, code = m.group(1), m.group(2).rstrip("\n")
h = f'<div class="pre-header">{esc(lang)}</div>' if lang else ""
return h + "<pre><code>" + esc(code) + "</code></pre>"
s = re.sub(r"```([\w+-]*)\n?([\s\S]*?)```", fenced, s)
s = re.sub(r"`([^`\n]+)`", lambda m: "<code>" + esc(m.group(1)) + "</code>", s)
# Inline formatting (top-level, outside list items)
s = re.sub(r"\*\*\*(.+?)\*\*\*", lambda m: "<strong><em>" + esc(m.group(1)) + "</em></strong>", s)
s = re.sub(r"\*\*(.+?)\*\*", lambda m: "<strong>" + esc(m.group(1)) + "</strong>", s)
s = re.sub(r"\*([^*\n]+)\*", lambda m: "<em>" + esc(m.group(1)) + "</em>", s)
# Block elements using inlineMd for their content
s = re.sub(r"^### (.+)$", lambda m: "<h3>" + inline_md(m.group(1)) + "</h3>", s, flags=re.M)
s = re.sub(r"^## (.+)$", lambda m: "<h2>" + inline_md(m.group(1)) + "</h2>", s, flags=re.M)
s = re.sub(r"^# (.+)$", lambda m: "<h1>" + inline_md(m.group(1)) + "</h1>", s, flags=re.M)
s = re.sub(r"^---+$", "<hr>", s, flags=re.M)
s = re.sub(r"^> (.+)$", lambda m: "<blockquote>" + inline_md(m.group(1)) + "</blockquote>", s, flags=re.M)
def handle_ul(block):
lines = block.strip().split("\n")
out = "<ul>"
for l in lines:
indent = bool(re.match(r"^ {2,}", l))
text = re.sub(r"^ {0,4}[-*+] ", "", l)
style = ' style="margin-left:16px"' if indent else ""
out += f"<li{style}>{inline_md(text)}</li>"
return out + "</ul>"
s = re.sub(r"((?:^(?: )?[-*+] .+\n?)+)", lambda m: handle_ul(m.group()), s, flags=re.M)
def handle_ol(block):
lines = block.strip().split("\n")
out = "<ol>"
for l in lines:
text = re.sub(r"^ {0,4}\d+\. ", "", l)
out += f"<li>{inline_md(text)}</li>"
return out + "</ol>"
s = re.sub(r"((?:^(?: )?\d+\. .+\n?)+)", lambda m: handle_ol(m.group()), s, flags=re.M)
# Safety net: escape unknown tags in remaining text
s = re.sub(r"</?[a-zA-Z][^>]*>", lambda m: m.group() if SAFE_TAGS.match(m.group()) else esc(m.group()), s)
# Paragraph wrap
parts = s.split("\n\n")
def wrap(p):
p = p.strip()
if not p: return ""
if re.match(r"^<(h[1-6]|ul|ol|pre|hr|blockquote)", p): return p
return "<p>" + p.replace("\n", "<br>") + "</p>"
s = "\n".join(wrap(p) for p in parts)
return s
# ── Static analysis: verify key structures exist in ui.js ────────────────────
def test_render_md_pre_pass_converts_strong(cleanup_test_sessions):
"""ui.js renderMd() must have pre-pass that converts <strong> to **."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
assert "<strong>" in code and "**" in code, "pre-pass for <strong> not found"
# Verify the specific conversion pattern
assert re.search(r"<strong>.*?\*\*", code, re.S), \
"renderMd pre-pass should convert <strong>...</strong> to **...**"
def test_render_md_has_safety_net(cleanup_test_sessions):
"""ui.js must have a safety-net that escapes unknown HTML tags after the pipeline."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
assert "SAFE_TAGS" in code, "SAFE_TAGS allowlist regex not found in ui.js"
assert "esc(tag)" in code, "safety-net esc(tag) call not found in ui.js"
def test_render_md_stashes_code_blocks(cleanup_test_sessions):
"""ui.js pre-pass must stash code blocks before replacing safe HTML tags."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
assert "fence_stash" in code, "fence_stash not found in renderMd pre-pass"
def test_render_md_handles_br_tag(cleanup_test_sessions):
"""ui.js must convert <br> to newline in pre-pass."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
assert re.search(r"<br\\s\*", code) or "<br" in code, "<br> handling not found"
def test_render_md_no_placeholder_remnants(cleanup_test_sessions):
"""Old Unicode placeholder approach (\\uE001-\\uE005) must be gone."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
for old_ph in ["\\uE001", "\\uE002", "\\uE003", "\\uE004", "\\uE005"]:
assert old_ph not in code, \
f"Old placeholder {old_ph} still present — broken implementation not cleaned up"
def test_render_md_safe_tag_allowlist_complete(cleanup_test_sessions):
"""SAFE_TAGS allowlist must include all tags the pipeline emits."""
src = REPO_ROOT / "static" / "ui.js"
code = src.read_text()
required = ["strong", "em", "code", "pre", "ul", "ol", "li",
"table", "blockquote", "hr", "br", "a", "div"]
safe_tags_match = re.search(r"SAFE_TAGS\s*=\s*/(.+?)/i", code)
assert safe_tags_match, "SAFE_TAGS regex not found"
pattern = safe_tags_match.group(1)
for tag in required:
assert tag in pattern, f"Tag '{tag}' missing from SAFE_TAGS allowlist"
# ── Behavioural: renderMd logic via Python mirror ─────────────────────────────
def test_render_md_markdown_bold(cleanup_test_sessions):
"""**word** markdown renders as <strong>word</strong>."""
out = render_md("Hello **world**")
assert "<strong>world</strong>" in out
def test_render_md_html_strong_passthrough(cleanup_test_sessions):
"""<strong>word</strong> in AI output renders as bold."""
out = render_md("Hello <strong>world</strong>")
assert "<strong>world</strong>" in out
def test_render_md_html_b_tag(cleanup_test_sessions):
"""<b>word</b> renders as <strong>word</strong>."""
out = render_md("Hello <b>world</b>")
assert "<strong>world</strong>" in out
def test_render_md_html_em_passthrough(cleanup_test_sessions):
"""<em>word</em> renders as italic."""
out = render_md("Hello <em>world</em>")
assert "<em>world</em>" in out
def test_render_md_html_i_tag(cleanup_test_sessions):
"""<i>word</i> renders as <em>word</em>."""
out = render_md("Hello <i>word</i>")
assert "<em>word</em>" in out
def test_render_md_html_code_passthrough(cleanup_test_sessions):
"""<code>text</code> renders as inline code."""
out = render_md("use <code>print()</code>")
assert "<code>print()</code>" in out
def test_render_md_html_br_becomes_newline(cleanup_test_sessions):
"""<br> in AI output becomes a newline (rendered as <br> inside <p> later)."""
out = render_md("line one<br>line two")
assert "line one\nline two" in out or "line one<br>line two" in out
def test_render_md_mixed_markdown_and_html(cleanup_test_sessions):
"""Markdown and HTML formatting can coexist in the same response."""
out = render_md("**markdown** and <strong>html</strong>")
assert "<strong>markdown</strong>" in out
assert "<strong>html</strong>" in out
def test_render_md_html_strong_in_list_item(cleanup_test_sessions):
"""THE SCREENSHOT BUG: <strong> tags inside list items must render as bold,
not as escaped literal text like &lt;strong&gt;."""
out = render_md(
"- <strong>All items</strong> get `border-radius: 0 8px 8px 0`\n"
"- <strong>Active item</strong> uses <code>#e8a030</code>\n"
"- <strong>Project items</strong> show their color\n"
"- <strong>Regular items</strong> stay muted"
)
assert "&lt;strong&gt;" not in out, \
"Escaped <strong> literal found in list output — bold not rendering"
assert "<strong>All items</strong>" in out
assert "<strong>Active item</strong>" in out
assert "<code>border-radius: 0 8px 8px 0</code>" in out
assert "<code>#e8a030</code>" in out
def test_render_md_exact_screenshot_content(cleanup_test_sessions):
"""Exact text from the ui-changes-unrendered-html-tags.png screenshot.
This is the canonical regression test for the inlineMd fix.
All four bullet points must render <strong> and <code> as HTML, not literal text."""
out = render_md(
"- <strong>All items</strong> now have <code>border-radius: 0 8px 8px 0</code>"
" \u2014 straight left edge everywhere, rounded on the right\n"
"- <strong>Active item</strong> is now gold/amber (<code>#e8a030</code>)"
" \u2014 same warm gold used in the logo \u2014 instead of blue,"
" so it stands out distinctly from everything else\n"
"- <strong>Project items</strong> still show their project color on the left"
" border, but only when they're not the active item (active always wins with gold)\n"
"- <strong>Regular items</strong> (no project) still have no left border color"
)
# None of the safe tags should appear as literal escaped text
assert "&lt;strong&gt;" not in out, \
"Literal &lt;strong&gt; found — <strong> is not rendering as bold"
assert "&lt;/strong&gt;" not in out, \
"Literal &lt;/strong&gt; found — closing tag is not rendering"
assert "&lt;code&gt;" not in out, \
"Literal &lt;code&gt; found — <code> is not rendering as inline code"
# Each item's bold label must render correctly
assert "<strong>All items</strong>" in out
assert "<strong>Active item</strong>" in out
assert "<strong>Project items</strong>" in out
assert "<strong>Regular items</strong>" in out
# The code spans in items 1 and 2 must render correctly
assert "<code>border-radius: 0 8px 8px 0</code>" in out
assert "<code>#e8a030</code>" in out
# The surrounding prose text must be preserved
assert "straight left edge everywhere" in out
assert "same warm gold used in the logo" in out
assert "active always wins with gold" in out
def test_render_md_markdown_bold_in_list_item(cleanup_test_sessions):
"""**bold** markdown inside list items must render as <strong>."""
out = render_md("- **First** item\n- **Second** item with `code`")
assert "<strong>First</strong>" in out
assert "<strong>Second</strong>" in out
assert "<code>code</code>" in out
def test_render_md_html_strong_in_blockquote(cleanup_test_sessions):
"""<strong> inside blockquote must render as bold."""
out = render_md("> <strong>Note:</strong> pay attention")
assert "&lt;strong&gt;" not in out
assert "<strong>Note:</strong>" in out
def test_render_md_html_strong_in_heading(cleanup_test_sessions):
"""<strong> inside a heading must render as bold."""
out = render_md("## <strong>Important</strong> Section")
assert "&lt;strong&gt;" not in out
assert "<strong>Important</strong>" in out
def test_render_md_xss_in_list_still_blocked(cleanup_test_sessions):
"""XSS attempts in list items must still be escaped."""
out = render_md("- <img src=x onerror=alert(1)> bad")
assert "<img" not in out
assert "&lt;img" in out
def test_render_md_xss_in_blockquote_still_blocked(cleanup_test_sessions):
"""XSS in blockquote must still be escaped."""
out = render_md("> <script>alert(1)</script>")
assert "<script>" not in out
assert "&lt;script" in out
def test_render_md_code_span_in_list_protected(cleanup_test_sessions):
"""Backtick code span in list item must escape its content."""
out = render_md("- Use `<br>` for breaks")
assert "<code>&lt;br&gt;</code>" in out
def test_render_md_code_block_protects_html(cleanup_test_sessions):
"""HTML inside a backtick code span must NOT be converted — shown as literal."""
out = render_md("keep `<strong>literal</strong>` safe")
assert "&lt;strong&gt;" in out, "HTML inside code span should be escaped"
assert "<strong>literal</strong>" not in out, "HTML inside code span should NOT render as bold"
def test_render_md_fenced_code_protects_html(cleanup_test_sessions):
"""HTML inside a fenced code block must not be converted by the pre-pass.
The fenced block is stashed before tag replacement runs, so the raw HTML
is preserved intact for the pipeline's esc() to escape when rendering
the <pre><code> block. We verify the stash/restore mechanism works by
checking the content is unchanged after the pre-pass (i.e. still contains
the original tag text, not converted to **not bold**)."""
src = "```\n<strong>not bold</strong>\n```"
out = render_md(src)
# Pre-pass stash preserves the raw content -- it should NOT have been
# converted to **not bold** (which would render as bold outside the fence)
assert "**not bold**" not in out, \
"Fenced code content was incorrectly converted to markdown by the pre-pass"
# The raw content should still be present (stash/restore worked)
assert "<strong>not bold</strong>" in out or "&lt;strong&gt;" in out, \
"Fenced code content was lost after stash/restore"
# ── Security: XSS must be blocked ─────────────────────────────────────────────
def test_render_md_xss_img_tag_escaped(cleanup_test_sessions):
"""<img src=x onerror=alert(1)> must be HTML-escaped, not rendered."""
out = render_md("<img src=x onerror=alert(1)>")
assert "<img" not in out, "Raw <img> tag must not appear in output"
assert "&lt;img" in out, "<img> must be HTML-escaped"
def test_render_md_xss_script_tag_escaped(cleanup_test_sessions):
"""<script>alert(1)</script> must be HTML-escaped."""
out = render_md("<script>alert(1)</script>")
assert "<script>" not in out, "Raw <script> tag must not appear in output"
assert "&lt;script" in out, "<script> must be HTML-escaped"
def test_render_md_xss_iframe_escaped(cleanup_test_sessions):
"""<iframe> must be HTML-escaped."""
out = render_md("<iframe src='evil.com'></iframe>")
assert "<iframe" not in out
assert "&lt;iframe" in out
def test_render_md_xss_svg_onerror_escaped(cleanup_test_sessions):
"""<svg onload=...> must be HTML-escaped."""
out = render_md("<svg onload=alert(1)>")
assert "<svg" not in out
assert "&lt;svg" in out
def test_render_md_xss_in_bold_text_escaped(cleanup_test_sessions):
"""**<img onerror=...>** — XSS inside markdown bold must be escaped."""
out = render_md("**<img src=x onerror=alert(1)>**")
assert "<img" not in out, "XSS inside **bold** must be escaped"
assert "&lt;img" in out
def test_render_md_xss_in_html_strong_escaped(cleanup_test_sessions):
"""<strong><img ...></strong> — nested XSS inside HTML strong must be escaped."""
out = render_md("<strong><img src=x onerror=alert(1)></strong>")
# <strong> converts to ** which then escapes the inner content via esc()
assert "<img" not in out, "XSS nested inside <strong> must be escaped"
def test_render_md_xss_object_tag_escaped(cleanup_test_sessions):
"""<object data=...> must be HTML-escaped."""
out = render_md("<object data='evil.swf'></object>")
assert "<object" not in out
assert "&lt;object" in out
# ── Sprint 16 sidebar: static structure checks ───────────────────────────────
# ── Exhaustive inlineMd / renderMd edge-case tests ───────────────────────────
# --- Unordered list variants ---
def test_list_bold_only(cleanup_test_sessions):
"""Single bold word in list item."""
out = render_md("- **bold**")
assert "<strong>bold</strong>" in out
assert "&lt;" not in out
def test_list_italic_only(cleanup_test_sessions):
"""Single italic word in list item."""
out = render_md("- *italic*")
assert "<em>italic</em>" in out
def test_list_code_only(cleanup_test_sessions):
"""Single code span in list item."""
out = render_md("- `code`")
assert "<code>code</code>" in out
def test_list_bold_and_code_mixed(cleanup_test_sessions):
"""Bold and code together in one list item."""
out = render_md("- **run** `pip install foo`")
assert "<strong>run</strong>" in out
assert "<code>pip install foo</code>" in out
def test_list_html_strong_and_code_mixed(cleanup_test_sessions):
"""HTML <strong> and <code> together — the exact screenshot scenario."""
out = render_md("- <strong>Key</strong>: use <code>value</code>")
assert "<strong>Key</strong>" in out
assert "<code>value</code>" in out
assert "&lt;strong&gt;" not in out
assert "&lt;code&gt;" not in out
def test_list_html_em(cleanup_test_sessions):
"""HTML <em> in list item renders as italic."""
out = render_md("- <em>emphasized</em> text")
assert "<em>emphasized</em>" in out
assert "&lt;em&gt;" not in out
def test_list_html_b_tag(cleanup_test_sessions):
"""HTML <b> in list item renders as bold."""
out = render_md("- <b>bold via b tag</b>")
assert "<strong>bold via b tag</strong>" in out
assert "&lt;b&gt;" not in out
def test_list_html_i_tag(cleanup_test_sessions):
"""HTML <i> in list item renders as italic."""
out = render_md("- <i>italic via i tag</i>")
assert "<em>italic via i tag</em>" in out
assert "&lt;i&gt;" not in out
def test_list_multiple_items_each_formatted(cleanup_test_sessions):
"""Multiple list items each with different formatting."""
out = render_md(
"- **bold item**\n"
"- *italic item*\n"
"- `code item`\n"
"- plain item"
)
assert "<strong>bold item</strong>" in out
assert "<em>italic item</em>" in out
assert "<code>code item</code>" in out
assert "<li>plain item</li>" in out
def test_list_item_bold_mid_sentence(cleanup_test_sessions):
"""Bold in middle of a list item sentence."""
out = render_md("- Set the **timeout** to 30 seconds")
assert "<strong>timeout</strong>" in out
assert "Set the" in out
assert "to 30 seconds" in out
def test_list_item_multiple_bold_spans(cleanup_test_sessions):
"""Multiple bold spans in one list item."""
out = render_md("- **A** and **B** are both important")
assert "<strong>A</strong>" in out
assert "<strong>B</strong>" in out
def test_ordered_list_bold(cleanup_test_sessions):
"""Bold text inside ordered list items."""
out = render_md("1. **First** step\n2. **Second** step\n3. Plain step")
assert "<ol>" in out
assert "<strong>First</strong>" in out
assert "<strong>Second</strong>" in out
assert "<li>Plain step</li>" in out
def test_ordered_list_html_strong(cleanup_test_sessions):
"""HTML <strong> inside ordered list items renders correctly."""
out = render_md("1. <strong>Install</strong> the package\n2. <strong>Configure</strong> the settings")
assert "<ol>" in out
assert "<strong>Install</strong>" in out
assert "<strong>Configure</strong>" in out
assert "&lt;strong&gt;" not in out
def test_ordered_list_code_spans(cleanup_test_sessions):
"""Code spans inside ordered list items."""
out = render_md("1. Run `npm install`\n2. Run `npm start`")
assert "<code>npm install</code>" in out
assert "<code>npm start</code>" in out
def test_indented_list_item_bold(cleanup_test_sessions):
"""Bold inside indented (nested) list item."""
out = render_md("- top level\n - **nested bold**")
assert "<strong>nested bold</strong>" in out
assert "margin-left:16px" in out
# --- Blockquote variants ---
def test_blockquote_plain(cleanup_test_sessions):
"""Plain blockquote wraps in <blockquote>."""
out = render_md("> simple quote")
assert "<blockquote>simple quote</blockquote>" in out
def test_blockquote_bold(cleanup_test_sessions):
"""**bold** inside blockquote renders correctly."""
out = render_md("> **important** note")
assert "<strong>important</strong>" in out
def test_blockquote_html_strong(cleanup_test_sessions):
"""<strong> inside blockquote renders as bold."""
out = render_md("> <strong>Warning:</strong> read this")
assert "<strong>Warning:</strong>" in out
assert "&lt;strong&gt;" not in out
def test_blockquote_code_span(cleanup_test_sessions):
"""Code span inside blockquote renders correctly."""
out = render_md("> Use `git commit` to save")
assert "<code>git commit</code>" in out
def test_blockquote_mixed_formatting(cleanup_test_sessions):
"""Mixed bold and code in blockquote."""
out = render_md("> **Note:** run `pip install foo` first")
assert "<strong>Note:</strong>" in out
assert "<code>pip install foo</code>" in out
def test_blockquote_xss_blocked(cleanup_test_sessions):
"""XSS in blockquote content must be escaped."""
out = render_md("> <img src=x onerror=alert(1)>")
assert "&lt;img" in out
assert "<img" not in out
# --- Heading variants ---
def test_heading_h1_bold(cleanup_test_sessions):
"""Bold inside h1 renders correctly."""
out = render_md("# **Main** Title")
assert "<h1><strong>Main</strong> Title</h1>" in out
def test_heading_h2_html_strong(cleanup_test_sessions):
"""HTML <strong> inside h2 renders correctly."""
out = render_md("## <strong>Section</strong> Name")
assert "<h2><strong>Section</strong> Name</h2>" in out
assert "&lt;strong&gt;" not in out
def test_heading_h3_code(cleanup_test_sessions):
"""Code span inside h3 renders correctly."""
out = render_md("### The `renderMd` function")
assert "<h3>The <code>renderMd</code> function</h3>" in out
def test_heading_xss_blocked(cleanup_test_sessions):
"""XSS attempt in heading must be escaped."""
out = render_md("## <script>alert(1)</script>")
assert "<script>" not in out
assert "&lt;script" in out
# --- Paragraph / top-level formatting ---
def test_paragraph_bold_renders(cleanup_test_sessions):
"""Bold in a plain paragraph renders correctly."""
out = render_md("The **quick brown fox** jumps.")
assert "<strong>quick brown fox</strong>" in out
def test_paragraph_html_strong_renders(cleanup_test_sessions):
"""HTML <strong> in a plain paragraph renders correctly."""
out = render_md("The <strong>quick brown fox</strong> jumps.")
assert "<strong>quick brown fox</strong>" in out
assert "&lt;strong&gt;" not in out
def test_paragraph_html_code_renders(cleanup_test_sessions):
"""HTML <code> in a plain paragraph renders correctly."""
out = render_md("Call <code>foo()</code> to start.")
assert "<code>foo()</code>" in out
assert "&lt;code&gt;" not in out
def test_paragraph_br_creates_line_break(cleanup_test_sessions):
"""<br> in paragraph becomes a line break inside <p>."""
out = render_md("Line one<br>Line two")
# br converts to \n which inside <p> becomes <br>
assert "Line one" in out and "Line two" in out
def test_multiple_paragraphs_separated(cleanup_test_sessions):
"""Double newline creates separate <p> elements."""
out = render_md("First paragraph.\n\nSecond paragraph.")
assert out.count("<p>") == 2
# --- Table variants ---
def test_table_structure_in_ui_js(cleanup_test_sessions):
"""ui.js must contain table rendering logic with thead/tbody structure."""
src = (REPO_ROOT / "static" / "ui.js").read_text()
assert "<table>" in src or "table>" in src, "table rendering not found in ui.js"
assert "thead" in src, "thead not found in table renderer"
assert "tbody" in src, "tbody not found in table renderer"
assert "parseRow" in src, "parseRow helper not found in table renderer"
# --- br tag specifically ---
def test_br_in_list_item(cleanup_test_sessions):
"""<br> inside a list item becomes a newline."""
out = render_md("- Line one<br>Line two")
assert "Line one" in out
assert "Line two" in out
def test_br_self_closing_in_paragraph(cleanup_test_sessions):
"""<br/> self-closing form is also handled."""
out = render_md("Before<br/>After")
assert "Before" in out and "After" in out
# --- No double-escaping ---
def test_no_double_escaping_ampersand(cleanup_test_sessions):
"""A literal & in text must become &amp; exactly once, not &amp;amp;."""
out = render_md("foo & bar")
assert "&amp;amp;" not in out
assert "&amp;" in out or "foo & bar" in out # either fine (paragraph wrap may not escape)
def test_no_double_escaping_lt_in_code(cleanup_test_sessions):
"""< inside a code span must become &lt; exactly once."""
out = render_md("`a < b`")
assert "&lt;lt;" not in out
assert "&lt;" in out
def test_strong_text_not_double_escaped(cleanup_test_sessions):
"""Content of <strong> must not be double-escaped."""
out = render_md("<strong>hello & world</strong>")
# The & inside strong content should be escaped once
assert "&amp;amp;" not in out
assert "<strong>" in out
# --- inlineMd helper present in source ---
def test_inline_md_helper_in_ui_js(cleanup_test_sessions):
"""ui.js must define inlineMd() helper function."""
src = (REPO_ROOT / "static" / "ui.js").read_text()
assert "function inlineMd(" in src, "inlineMd() helper not found in ui.js"
def test_inline_md_used_in_list_handler(cleanup_test_sessions):
"""List handler in ui.js must call inlineMd() not esc() for item text."""
src = (REPO_ROOT / "static" / "ui.js").read_text()
# Find the list block handler
ul_idx = src.find("html+='<ul>'") or src.find('html+=`<ul>`') or src.find("let html='<ul>'")
assert ul_idx >= 0 or "inlineMd(text)" in src, "inlineMd not called in list handler"
# Verify inlineMd is called, not bare esc
assert "inlineMd(text)" in src, "inlineMd(text) call not found — list items may not render formatting"
def test_inline_md_used_in_blockquote_handler(cleanup_test_sessions):
"""Blockquote handler in ui.js must call inlineMd() not esc() for content."""
src = (REPO_ROOT / "static" / "ui.js").read_text()
assert "inlineMd(t)" in src, "inlineMd not called in blockquote/heading handler"
def test_sessions_js_has_svg_icons(cleanup_test_sessions):
"""sessions.js must define ICONS object with SVG strings for sidebar buttons."""
src = REPO_ROOT / "static" / "sessions.js"
code = src.read_text()
assert "const ICONS=" in code or "const ICONS =" in code, "ICONS constant not found"
for icon in ["pin", "folder", "archive", "trash", "dup"]:
assert icon + ":" in code or f"'{icon}'" in code, f"ICONS.{icon} not found"
assert "<svg" in code, "SVG content not found in ICONS"
def test_sessions_js_has_overlay_actions(cleanup_test_sessions):
"""sessions.js must use .session-actions overlay div for action buttons."""
src = REPO_ROOT / "static" / "sessions.js"
code = src.read_text()
assert "session-actions" in code, ".session-actions overlay not found in sessions.js"
def test_style_css_has_session_actions_overlay(cleanup_test_sessions):
"""style.css must define .session-actions with position:absolute."""
src = REPO_ROOT / "static" / "style.css"
code = src.read_text()
assert ".session-actions" in code, ".session-actions not found in style.css"
assert "position:absolute" in code or "position: absolute" in code, \
".session-actions must use position:absolute for overlay"
def test_style_css_active_session_uses_gold(cleanup_test_sessions):
"""Active session style should use gold/amber color (#e8a030) not just blue."""
src = REPO_ROOT / "static" / "style.css"
code = src.read_text()
assert "#e8a030" in code, \
"Active session gold color (#e8a030) not found in style.css"
def test_sessions_js_active_skips_project_border(cleanup_test_sessions):
"""sessions.js must not override active session border-left with project color."""
src = REPO_ROOT / "static" / "sessions.js"
code = src.read_text()
# The fix: only set borderLeftColor if NOT the active session
assert "isActive" in code, "isActive check not found in sessions.js"
assert "borderLeftColor" in code, "borderLeftColor not found in sessions.js"

96
tests/test_sprint17.py Normal file
View File

@@ -0,0 +1,96 @@
"""
Sprint 17 Tests: send_key setting, commands.js static file, workspace subdir listing.
"""
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"]
# ── Settings: send_key ──────────────────────────────────────────────────────
def test_settings_send_key_default():
"""GET /api/settings returns send_key with default value 'enter'."""
data, status = get("/api/settings")
assert status == 200
assert data.get("send_key") == "enter"
def test_settings_save_send_key():
"""POST /api/settings with send_key persists and round-trips."""
try:
# Save ctrl+enter
_, status = post("/api/settings", {"send_key": "ctrl+enter"})
assert status == 200
# Verify it persisted
data, _ = get("/api/settings")
assert data["send_key"] == "ctrl+enter"
finally:
# Always restore default
post("/api/settings", {"send_key": "enter"})
data, _ = get("/api/settings")
assert data["send_key"] == "enter"
def test_settings_invalid_send_key_rejected():
"""POST /api/settings with invalid send_key value is silently ignored."""
# Set a known good value first
post("/api/settings", {"send_key": "enter"})
# Try to set an invalid value
data, status = post("/api/settings", {"send_key": "invalid_value"})
assert status == 200
# Should still be 'enter' (invalid value ignored)
assert data["send_key"] == "enter"
def test_settings_unknown_key_ignored():
"""POST /api/settings ignores unknown keys."""
data, status = post("/api/settings", {"unknown_key": "value", "send_key": "enter"})
assert status == 200
assert "unknown_key" not in data
# ── Static file: commands.js ────────────────────────────────────────────────
def test_static_commands_js_served():
"""GET /static/commands.js returns 200 and contains COMMANDS registry."""
req = urllib.request.Request(BASE + "/static/commands.js")
with urllib.request.urlopen(req, timeout=10) as r:
body = r.read().decode()
assert r.status == 200
assert "COMMANDS" in body
assert "executeCommand" in body
# ── Workspace: subdir listing ───────────────────────────────────────────────
def test_list_workspace_root():
"""GET /api/list with path=. returns entries for workspace root."""
created = []
sid, _ = make_session(created)
data, status = get(f"/api/list?session_id={sid}&path=.")
assert status == 200
assert "entries" in data
assert isinstance(data["entries"], list)