The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: route REST sidebar edits through the shared authority
Tekniumeb329d21ba95
diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.pyindex e6a0e54dc0b..3166f500538 100644--- a/hermes_cli/web_models.py+++ b/hermes_cli/web_models.py@@ -236,6 +236,9 @@ class SessionImport(BaseModel):profile: Optional[str] = Noneclass SessionRename(BaseModel):+ request_id: Optional[str] = None+ expected_revision: Optional[int] = None+ expected_generation: Optional[int] = Nonetitle: Optional[str] = Nonearchived: Optional[bool] = Nonehidden: Optional[bool] = None # also used by cross-profile reconciliationdiff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex b7673ceb2be..d116fa763c4 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -603,46 +603,15 @@ async def backfill_session_owner_profiles(body: SessionOwnerBackfill):return {"ok": True, "stamped": stamped, "profile": stamp}-# PATCH /api/sessions/{id} flag -> SessionDB setter, applied in this order.-_RENAME_FLAG_SETTERS = (- ("archived", lambda db, sid, v: db.set_session_archived(sid, v)),- ("hidden", lambda db, sid, v: db.set_session_hidden(sid, v)),- ("pinned", lambda db, sid, v: db.set_session_pinned(sid, v)),- ("unread", lambda db, sid, v: db.set_session_read(sid, read=not v)),-)--@manage_router.patch("/api/sessions/{session_id}")-async def rename_session_endpoint(session_id: str, body: SessionRename):- """Update ``title`` (empty clears) and/or the flags; ``pinned`` exempts from- the auto-archive sweep, ``unread=False`` marks read up to now."""- flags = [flag for flag, _ in _RENAME_FLAG_SETTERS]-- def _update(db):- sid = _resolve_session_id(db, session_id)- if not sid:- raise HTTPException(status_code=404, detail=_NOT_FOUND)- if body.title is None and all(getattr(body, f) is None for f in flags):- raise HTTPException(- status_code=400,- detail="Nothing to update; provide 'title', 'archived', 'hidden', 'pinned', and/or 'unread'.",- )- if body.title is not None:- try:- db.set_session_title(sid, body.title or "")- except ValueError as e:- # Title too long, invalid characters, or already in use.- raise HTTPException(status_code=400, detail=str(e))- result = {"ok": True, "title": None}- for flag, setter in _RENAME_FLAG_SETTERS:- value = getattr(body, flag)- if value is not None:- setter(db, sid, value)- result[flag] = bool(value)- result["title"] = db.get_session_title(sid) or ""- return result-- return _with_db(body.profile, _update, read_only=False)+async def rename_session_endpoint(session_id: str, body: SessionRename, request: Request):+ """Title and sidebar flags share one authoritative revision and receipt."""+ from hermes_cli.web_server_sessions import _mutate_session_request+ payload = {key: getattr(body, key) for key in ('title', 'archived', 'hidden', 'pinned', 'unread')+ if getattr(body, key) is not None}+ return await _mutate_session_request(request, body.profile, session_id,+ request_id=body.request_id, expected_revision=body.expected_revision,+ expected_generation=body.expected_generation, operation='sidebar', payload=payload)def _compact_json(obj) -> str:diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.pyindex 5dd2e38340d..c857c080035 100644--- a/hermes_cli/web_server_sessions.py+++ b/hermes_cli/web_server_sessions.py@@ -66,6 +66,56 @@ def _session_latest_descendant(session_id: str, db):return current, path+async def _mutate_session_request(request, profile, session_id, *, request_id,+ expected_revision, operation, payload, expected_generation=None):+ """Resolve the authenticated principal and owner; never open a second writer."""+ from fastapi import HTTPException+ from gateway.session_contract import Principal, SessionRef+ from gateway.session_mutations import mutate_session+ from hermes_state_runtime import RuntimeStoreError+ from hermes_cli.web_server import _has_valid_session_token+ from hermes_cli.web_server_cron import _cron_profile_home+ from hermes_state import _default_db_path+ import sqlite3++ native = getattr(request.state, 'native_http_principal', None)+ session = getattr(request.state, 'session', None)+ if native is not None:+ subject = native['subject']+ elif session is not None:+ subject = session.user_id+ elif not getattr(request.app.state, 'auth_required', False) and _has_valid_session_token(request):+ subject = 'dashboard-token'+ else:+ raise HTTPException(status_code=401, detail='Unauthorized')+ authority = getattr(request.app.state, 'session_authority', None)+ if authority is None:+ raise HTTPException(status_code=503, detail='session_authority_unavailable')+ home = Path(_cron_profile_home(profile)[1]) if profile else Path(_default_db_path()).parent+ if home.resolve() != Path(authority.db.db_path).parent.resolve():+ raise HTTPException(status_code=403, detail='profile_mismatch')+ if native is not None and native['profile_id'] != authority.profile_id:+ raise HTTPException(status_code=403, detail='profile_mismatch')+ if request_id is None or expected_revision is None:+ raise HTTPException(status_code=409, detail='mutation_identity_required')+ actor = Principal(subject, authority.profile_id,+ frozenset({'session:read', 'session:control', 'session:create'}), 'http')+ params = dict(session_id=session_id, request_id=request_id, expected_revision=expected_revision,+ operation=operation, payload=payload)+ if expected_generation is not None:+ params['expected_generation'] = expected_generation+ try:+ return await mutate_session(authority, actor, SessionRef(authority.profile_id, session_id), params)+ except RuntimeStoreError as exc:+ status = {'permission_denied': 403, 'profile_mismatch': 403, 'not_found': 404,+ 'invalid_params': 400, 'runtime_draining': 503}.get(exc.reason, 409)+ raise HTTPException(status_code=status, detail=exc.reason) from exc+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ except sqlite3.Error as exc:+ raise HTTPException(status_code=503, detail='storage_unavailable') from exc++def _session_db_read_probe_statements() -> tuple:"""Probe the declared schema without reconciling it on a browsing request."""from hermes_state_schema import schema_read_probe_statementsdiff --git a/tests/hermes_cli/test_session_mutation_http.py b/tests/hermes_cli/test_session_mutation_http.pynew file mode 100644index 00000000000..4450ac5dbda--- /dev/null+++ b/tests/hermes_cli/test_session_mutation_http.py@@ -0,0 +1,81 @@+"""Real HTTP and WS clients share the owner revision and retry receipt."""+import asyncio+import json+import socket+from types import SimpleNamespace++import httpx+import pytest+import uvicorn+from fastapi import FastAPI, WebSocket+from gateway.session_authority import LiveSession, SessionAuthority+from gateway.session_controls import AuthorityConnection+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch+++async def test_http_and_ws_clients_compete_for_one_revision(tmp_path, monkeypatch):+ from hermes_cli.web_routers.sessions import manage_router+ from hermes_cli import web_server as web+ monkeypatch.setattr(web, '_SESSION_TOKEN', 'fixture-token')+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr('hermes_state._default_db_path', lambda: tmp_path / 'state.db')+ app = FastAPI()+ app.state.auth_required = False+ app.include_router(manage_router)+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('session-fixture', source='test')+ epoch = begin_runtime_epoch(db, instance_id='owner')+ authority = SessionAuthority(SimpleNamespace(_draining=False), profile_id=str(tmp_path), instance_id='owner', db=db, epoch=epoch)+ authority.sessions['session-fixture'] = LiveSession(None, 'route')+ app.state.session_authority = authority++ @app.websocket('/ws')+ async def ws_route(ws: WebSocket):+ if ws.query_params.get('token') != 'fixture-token':+ await ws.close(code=4401)+ return+ await ws.accept()+ connection = AuthorityConnection(authority, object(), {'user_id': 'dashboard-token'})+ try:+ request = await ws.receive_json()+ await ws.send_json(await connection.dispatch(request))+ finally:+ await connection.close()++ listener = socket.socket()+ listener.bind(('127.0.0.1', 0))+ port = listener.getsockname()[1]+ server = uvicorn.Server(uvicorn.Config(app, lifespan='off', log_level='error'))+ task = asyncio.create_task(server.serve(sockets=[listener]))+ try:+ async with httpx.AsyncClient(base_url=f'http://127.0.0.1:{port}') as client:+ for _ in range(200):+ if server.started:+ break+ await asyncio.sleep(.01)+ assert server.started+ body = {'request_id': 'edit', 'expected_revision': 0, 'title': 'Title', 'pinned': True}+ first = await client.patch('/api/sessions/session-fixture?token=fixture-token', json=body, headers={'Authorization': 'Bearer fixture-token'})+ assert first.status_code == 200, first.text+ assert first.json()['revision'] == 1+ import websockets+ async with websockets.connect(f'ws://127.0.0.1:{port}/ws?token=fixture-token') as ws:+ await ws.send(json.dumps({'id': 1, 'method': 'session.mutate', 'params': {+ 'session_id': 'session-fixture', 'request_id': 'competitor', 'expected_revision': 0,+ 'operation': 'sidebar', 'payload': {'title': 'Stale'}}}))+ competing = json.loads(await ws.recv())+ assert competing['error']['message'] == 'revision_conflict'+ retry = await client.patch('/api/sessions/session-fixture?token=fixture-token', json=body, headers={'Authorization': 'Bearer fixture-token'})+ assert retry.json() == first.json()+ denied = await client.patch('/api/sessions/session-fixture', json=body)+ assert denied.status_code == 401+ foreign = await client.patch('/api/sessions/session-fixture?token=fixture-token', json=body | {'profile': 'other'}, headers={'Authorization': 'Bearer fixture-token'})+ assert foreign.status_code in (400, 403, 404)+ assert db.get_session('session-fixture')['runtime_revision'] == 1+ assert db.get_session('session-fixture')['title'] == 'Title'+ finally:+ server.should_exit = True+ await asyncio.wait_for(task, 10)+ listener.close()