Skip to content

The agent that grows with you

fix(dashboard): standalone serve/dashboard session edits work again

Teknium5a46ec488e83
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index d84b6287124..7edfc60b039 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -584,7 +584,10 @@ async def get_session_detail(session_id: str, profile: Optional[str] = None):
async def get_session_mutation_snapshot(session_id: str, request: Request, profile: Optional[str] = None):
from hermes_cli.web_server_sessions import _session_mutation_context
authority, _actor = _session_mutation_context(request, profile)
- row = authority.db.get_session(session_id)
+ if authority is None: # standalone serve: the counters the offline receipt checks
+ row = await asyncio.to_thread(_with_db, profile, lambda db: db.get_session(session_id), read_only=True)
+ else:
+ row = authority.db.get_session(session_id)
# An absent import anchor has revision zero by the owner's storage contract,
# not by a client guessing after a failed or stale detail request.
return {'session_id': session_id, 'exists': row is not None,
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index c2227029392..88a751b2539 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -97,9 +97,15 @@ def _session_mutation_context(request, profile):
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
+ capabilities = frozenset({'session:read', 'session:control', 'session:create', 'session:operator'})
+ if authority is None:
+ if getattr(request.app.state, 'gateway_runner', None) is not None:
+ raise HTTPException(status_code=503, detail='session_authority_unavailable')
+ # Standalone ``serve``/``dashboard`` (no composed gateway; its owner cutover is a
+ # follow-up): the store is the owner. Same principal id form as a gateway authority's
+ # (``str(home)``), so import bindings written offline stay valid once one starts.
+ return None, Principal(subject, str(home.resolve()), capabilities, 'http')
# ``?profile=`` selects a served home; its own authority (not the launch one) owns the mutation.
from gateway.session_authorities import authority_for_home
runner = getattr(request.app.state, 'gateway_runner', None)
@@ -111,8 +117,41 @@ def _session_mutation_context(request, profile):
authority = owner
if native is not None and native['profile_id'] != authority.profile_id:
raise HTTPException(status_code=403, detail='profile_mismatch')
- return authority, Principal(subject, authority.profile_id,
- frozenset({'session:read', 'session:control', 'session:create', 'session:operator'}), 'http')
+ return authority, Principal(subject, authority.profile_id, capabilities, 'http')
+
+
+def _mutate_offline_store(profile, actor, params):
+ """Standalone edit: the receipt transaction on this process's single shared writer.
+
+ Runs under the exact owner lock (409 while any gateway owns the store, never a
+ second writer beside it); revision/generation/idle guards are the gateway's own.
+ """
+ from fastapi import HTTPException
+ from hermes_state_runtime import begin_runtime_epoch, mutate_runtime_session
+
+ def run():
+ db = _open_session_db_for_profile(profile, read_only=False)
+ try:
+ write_guard = None
+ if params['operation'] == 'import':
+ normalized, errors = db._validate_import_payload(params['payload']['sessions'])
+ if errors:
+ raise HTTPException(status_code=400, detail={'errors': errors})
+ from functools import partial
+ from hermes_state_mutation_binding import import_history_control
+ write_guard = partial(import_history_control, actor=actor,
+ session_ids=tuple(item['session']['id'] for item in normalized))
+ with db._read_ctx() as conn:
+ row = conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()
+ # The reservation held here is the ownership lock begin_runtime_epoch requires.
+ epoch = row[0] if row else begin_runtime_epoch(db, instance_id='dashboard-offline')
+ return mutate_runtime_session(db, epoch=epoch, principal_id=actor.subject,
+ expected_generation=params.get('expected_generation'), _authorize_write=write_guard,
+ **{key: params[key] for key in ('session_id', 'request_id', 'expected_revision',
+ 'operation', 'payload')})
+ finally:
+ db.close()
+ return _with_session_maintenance(profile, run)
async def _mutate_session_request(request, profile, session_id, *, request_id,
@@ -126,7 +165,7 @@ async def _mutate_session_request(request, profile, session_id, *, request_id,
from hermes_state_runtime import RuntimeStoreError
authority, actor = _session_mutation_context(request, profile)
- if operation == 'import':
+ if operation == 'import' and authority is not None:
_, errors = authority.db._validate_import_payload(payload['sessions'])
if errors:
raise HTTPException(status_code=400, detail={'errors': errors})
@@ -137,7 +176,10 @@ async def _mutate_session_request(request, profile, session_id, *, request_id,
if expected_generation is not None:
params['expected_generation'] = expected_generation
try:
- result = await mutate_session(authority, actor, SessionRef(authority.profile_id, session_id), params)
+ if authority is None:
+ result = await asyncio.to_thread(_mutate_offline_store, profile, actor, params)
+ else:
+ result = await mutate_session(authority, actor, SessionRef(authority.profile_id, session_id), params)
return {'ok': True, **result}
except RuntimeStoreError as exc:
status = {'permission_denied': 403, 'profile_mismatch': 403, 'not_found': 404,
diff --git a/tests/hermes_cli/test_session_mutation_standalone.py b/tests/hermes_cli/test_session_mutation_standalone.py
new file mode 100644
index 00000000000..87dfa033395
--- /dev/null
+++ b/tests/hermes_cli/test_session_mutation_standalone.py
@@ -0,0 +1,83 @@
+"""Standalone ``hermes serve``/``dashboard`` (no gateway authority) keeps session edits.
+
+The edit runs the gateway's receipt transaction on the process's single writer under the
+exact owner lock: revision/retry/idle guards hold, and a live owner refuses with 409.
+"""
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from gateway.runtime_ownership import ProfileOwnership
+from hermes_cli.web_routers.sessions import manage_router
+from hermes_state import SessionDB
+from hermes_state_runtime import admit_session_input, begin_runtime_epoch
+
+AUTH = {'Authorization': 'Bearer standalone-token'}
+
+
+def _standalone_app(tmp_path, monkeypatch):
+ from hermes_cli import web_server
+ monkeypatch.setattr(web_server, '_SESSION_TOKEN', 'standalone-token')
+ monkeypatch.setattr('hermes_state._default_db_path', lambda: tmp_path / 'state.db')
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ app = FastAPI()
+ app.include_router(manage_router)
+ return app
+
+
+async def test_standalone_edits_commit_with_owner_guards(tmp_path, monkeypatch):
+ app = _standalone_app(tmp_path, monkeypatch)
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('edit-me', source='cli')
+ db.create_session('busy', source='cli')
+ epoch = begin_runtime_epoch(db, instance_id='earlier-gateway')
+ admit_session_input(db, epoch=epoch, principal_id='p', session_id='busy', request_id='q',
+ payload={'text': 'hi'})
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost',
+ headers=AUTH) as client:
+ snap = await client.get('/api/sessions/edit-me/mutation-snapshot')
+ assert snap.status_code == 200, snap.text
+ assert snap.json()['runtime_revision'] == 0
+ body = {'request_id': 'r1', 'expected_revision': 0, 'title': 'Renamed', 'pinned': True}
+ first = await client.patch('/api/sessions/edit-me', json=body)
+ assert first.status_code == 200, first.text
+ assert first.json()['revision'] == 1
+ assert (await client.patch('/api/sessions/edit-me', json=body)).json() == first.json()
+ stale = await client.patch('/api/sessions/edit-me', json=body | {'request_id': 'r2', 'title': 'Stale'})
+ assert (stale.status_code, stale.json()['detail']) == (409, 'revision_conflict')
+ busy = await client.delete('/api/sessions/busy', params={
+ 'request_id': 'd0', 'expected_revision': 0, 'expected_generation': 0})
+ assert (busy.status_code, busy.json()['detail']) == (409, 'session_busy')
+ gone = await client.delete('/api/sessions/edit-me', params={
+ 'request_id': 'd1', 'expected_revision': 1, 'expected_generation': 0})
+ assert gone.status_code == 200, gone.text
+ assert gone.json()['deleted_ids'] == ['edit-me']
+ assert db.get_session('edit-me') is None
+ assert db.get_session('busy') is not None
+ # The existing epoch was reused, not advanced: a standalone edit never fences an owner.
+ assert db._conn.execute('SELECT epoch FROM runtime_epoch').fetchone()[0] == epoch
+
+
+async def test_standalone_edit_refuses_while_a_gateway_owns_the_store(tmp_path, monkeypatch):
+ app = _standalone_app(tmp_path, monkeypatch)
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('owned', source='cli')
+ owner = ProfileOwnership()
+ owner.reserve([tmp_path])
+ try:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app),
+ base_url='http://localhost', headers=AUTH) as client:
+ refused = await client.patch('/api/sessions/owned',
+ json={'request_id': 'r1', 'expected_revision': 0, 'title': 'X'})
+ assert refused.status_code == 409, refused.text
+ # A composed gateway whose authority is not up yet never falls back to a writer.
+ app.state.gateway_runner = object()
+ pending = await client.patch('/api/sessions/owned',
+ json={'request_id': 'r1', 'expected_revision': 0, 'title': 'X'})
+ assert (pending.status_code, pending.json()['detail']) == (503, 'session_authority_unavailable')
+ finally:
+ owner.close()
+ assert db.get_session('owned')['title'] is None
+ assert db.get_session('owned')['runtime_revision'] == 0