Skip to content

The agent that grows with you

fix(desktop): edit old chats and run the owner backfill over per-profile native grants

Teknium32959d1884b7
diff --git a/gateway/session_listing.py b/gateway/session_listing.py
index c78e94f0d98..c2a88f54142 100644
--- a/gateway/session_listing.py
+++ b/gateway/session_listing.py
@@ -18,7 +18,7 @@ def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):
db = authority.db
sessions, offset = [], 0
while len(sessions) < limit:
- rows = db.list_sessions_rich(sources=['cli', 'tui', 'gui'], limit=200, offset=offset,
+ rows = db.list_sessions_rich(sources=['cli', 'tui', 'gui', 'desktop'], limit=200, offset=offset,
order_by_last_active=True, compact_rows=True, include_hidden=include_hidden)
for row in rows:
sid = db.get_compression_tip(row['id']) or row['id']
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 27c2a7ee7cb..1f175e13be1 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -872,8 +872,20 @@ async def delete_session_endpoint(session_id: str, request: Request, profile: Op
return result
+def _owner_db_for(request: Request, profile: Optional[str]):
+ """The live owner's own store for *profile* when a composed gateway serves it, else None."""
+ runner = getattr(request.app.state, "gateway_runner", None)
+ if runner is None:
+ return None
+ from gateway.session_authorities import authority_for_home
+ from hermes_state import _default_db_path
+ home = Path(_cron_profile_home(profile)[1]) if profile else Path(_default_db_path()).parent
+ authority = authority_for_home(runner, home)
+ return getattr(authority, "db", None)
+
+
@manage_router.post("/api/sessions/owner-backfill")
-async def backfill_session_owner_profiles(body: SessionOwnerBackfill):
+async def backfill_session_owner_profiles(body: SessionOwnerBackfill, request: Request):
"""Stamp legacy ``profile_name = NULL`` rows with the serving-profile identity.
A multi-connection Desktop fails closed on unowned rows. Each ``state.db``
@@ -891,9 +903,15 @@ async def backfill_session_owner_profiles(body: SessionOwnerBackfill):
with http_failure(
"POST /api/sessions/owner-backfill failed", 500, detail="Internal server error"):
- stamped = await asyncio.to_thread(
- _with_db, body.profile, lambda db: db.backfill_null_session_profiles(stamp),
- read_only=False)
+ owner_db = _owner_db_for(request, body.profile)
+ if owner_db is not None:
+ # A live gateway owns this store: it is the only writer (the offline maintenance lock
+ # would 409 every Desktop boot), so the idempotent stamp runs on its own connection.
+ stamped = await asyncio.to_thread(owner_db.backfill_null_session_profiles, stamp)
+ else:
+ stamped = await asyncio.to_thread(
+ _with_db, body.profile, lambda db: db.backfill_null_session_profiles(stamp),
+ read_only=False)
if stamped:
_log.info(
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index f8706bc83fd..fd6eddc6d3c 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -4,6 +4,7 @@
import logging
import asyncio
import time
+from contextlib import contextmanager
from pathlib import Path
from typing import Dict, Optional
@@ -117,9 +118,33 @@ 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')
+ if native is not None:
+ # One transport per verified native request, so the grant's own profile can claim its old
+ # local history exactly as over the native socket (``require_history_claim``); a shared
+ # 'http' id never can.
+ import uuid
+ return authority, Principal(subject, authority.profile_id, capabilities, 'native-http:' + uuid.uuid4().hex)
return authority, Principal(subject, authority.profile_id, capabilities, 'http')
+@contextmanager
+def _native_history_transport(request, authority, actor):
+ """Bind a verified native HTTP actor as a native legacy transport for one mutation."""
+ native = None
+ if authority is not None and str(getattr(actor, 'transport_id', '')).startswith('native-http:'):
+ native = getattr(request.state, 'native_http_principal', None)
+ if native is None:
+ yield
+ return
+ from gateway.session_local_migration import bind_native_transport, unbind_native_transport
+ bind_native_transport(authority, actor, {'provider': 'local', 'profile_id': authority.profile_id,
+ 'instance_id': native['instance_id']})
+ try:
+ yield
+ finally:
+ unbind_native_transport(authority, actor)
+
+
def _mutate_offline_store(profile, actor, params):
"""Standalone edit: the receipt transaction on this process's single shared writer.
@@ -179,7 +204,8 @@ async def _mutate_session_request(request, profile, session_id, *, request_id,
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)
+ with _native_history_transport(request, authority, actor):
+ 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/hermes_state_mutation_binding.py b/hermes_state_mutation_binding.py
index bc864bd9808..a2329bfc575 100644
--- a/hermes_state_mutation_binding.py
+++ b/hermes_state_mutation_binding.py
@@ -5,6 +5,20 @@ from hermes_state_runtime import RuntimeStoreError
BINDING_PREFIX = 'gateway.history_control.v1.'
+def _history_sources():
+ """Local surfaces whose unrouted rows are owner history: every source the native resume adopts
+ (``LEGACY_LOCAL_SOURCES``: old ``desktop`` chats and ``oneshot``/``tool`` CLI runs too) plus imports.
+ A row resume can adopt must also take a sidebar edit (pin/archive/hide/rename)."""
+ from hermes_state_local_migration import LEGACY_LOCAL_SOURCES
+ return LEGACY_LOCAL_SOURCES | {'import'}
+
+
+def _owner_user(row):
+ """The row's owner identity; main's Desktop Nous-account label is not one (see validate_legacy_row)."""
+ from hermes_state_local_migration import legacy_account_label
+ return None if legacy_account_label(dict(row)) else row['user_id']
+
+
def import_history_control(conn, actor, session_ids):
binding = json.dumps([actor.profile_id, actor.subject], separators=(',', ':'))
for sid in session_ids:
@@ -27,9 +41,9 @@ def authorize_history(conn, actor, session_id, *, claim=False):
if saved[0] != binding:
raise RuntimeStoreError('permission_denied')
return True
- if row['source'] not in {'cli', 'tui', 'gui', 'import'}:
+ if row['source'] not in _history_sources():
return False
- if row['user_id'] and row['user_id'] != actor.subject:
+ if _owner_user(row) and row['user_id'] != actor.subject:
raise RuntimeStoreError('permission_denied')
if 'session:create' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
@@ -62,4 +76,4 @@ def same_history_owner(conn, anchor_id, session_id):
if binding != history_binding(conn, anchor_id):
return False
return binding is not None or (
- row['source'] in {'cli', 'tui', 'gui', 'import'} and row['user_id'] in (None, '', anchor['user_id']))
+ row['source'] in _history_sources() and _owner_user(row) in (None, '', anchor['user_id']))
diff --git a/tests/gateway/test_legacy_desktop_source.py b/tests/gateway/test_legacy_desktop_source.py
new file mode 100644
index 00000000000..44e21e72c80
--- /dev/null
+++ b/tests/gateway/test_legacy_desktop_source.py
@@ -0,0 +1,37 @@
+"""Every old local row the native resume adopts also takes a sidebar edit (#106742).
+
+The resume adopts main's ``desktop`` chats (including those stamped with the signed-in Nous account)
+and ``oneshot``/``tool`` CLI runs, but ``authorize_history`` (pin/archive/hide/rename) only knew
+``cli``/``tui``/``gui``, so the same rows answered ``permission_denied`` on every sidebar edit.
+"""
+from gateway.session_contract import Principal
+from hermes_state import SessionDB
+from hermes_state_local_migration import validate_legacy_row
+from hermes_state_mutation_binding import authorize_history, same_history_owner
+
+
+def test_rows_the_resume_adopts_take_sidebar_edits(tmp_path):
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ try:
+ for sid, source, user_id in (('old-desktop', 'desktop', None), ('old-oneshot', 'oneshot', None),
+ ('old-desktop-nous', 'desktop', 'nous:account'),
+ ('old-desktop-foreign', 'desktop', 'telegram:42'),
+ ('old-cli-nous', 'cli', 'nous:account'), ('api-row', 'api_server', None)):
+ db.create_session(sid, source=source, user_id=user_id)
+ actor = Principal('uid:1', str(tmp_path), frozenset({'session:read', 'session:create'}), 'native-http:x')
+ with db._read_ctx() as conn:
+ for sid in ('old-desktop', 'old-oneshot', 'old-desktop-nous'):
+ validate_legacy_row(db, db.get_session(sid)) # the resume adopts it ...
+ assert authorize_history(conn, actor, sid) is True, sid # ... so it takes an edit.
+ assert same_history_owner(conn, 'old-desktop', 'old-desktop-nous') is True
+ # A real foreign identity, a Nous stamp on a non-Desktop row and API rows stay refused.
+ for sid in ('old-desktop-foreign', 'old-cli-nous'):
+ try:
+ authorize_history(conn, actor, sid)
+ except Exception as exc:
+ assert getattr(exc, 'reason', None) == 'permission_denied', (sid, exc)
+ else:
+ raise AssertionError(sid)
+ assert authorize_history(conn, actor, 'api-row') is False
+ finally:
+ db.close()
diff --git a/tests/gateway/test_native_http_per_profile_edits.py b/tests/gateway/test_native_http_per_profile_edits.py
new file mode 100644
index 00000000000..91947d52221
--- /dev/null
+++ b/tests/gateway/test_native_http_per_profile_edits.py
@@ -0,0 +1,119 @@
+"""Old local rows take the Desktop's sidebar edits over each profile's own native grant (#106742).
+
+main's Desktop pinned, archived and renamed old chats in every profile. With per-profile native
+grants the Bots sweep and the sidebar PATCH each row with a grant minted for the profile its body
+names, but the REST actor was a shared ``'http'`` transport, never a native legacy transport, so
+``require_history_claim`` refused every unclaimed pre-upgrade row (403 permission_denied), and
+``authorize_history`` did not count ``desktop``/``oneshot`` rows as local history at all.
+"""
+import asyncio
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import time
+import uuid
+
+import httpx
+import pytest
+from websockets.asyncio.client import connect
+
+from tests.gateway.test_normal_runtime_boot import control
+
+
+def _seed(home, rows):
+ """Rows as the pre-authority clients wrote them: no route, no owner binding."""
+ from hermes_state import SessionDB
+ db = SessionDB(db_path=home / 'state.db')
+ try:
+ for sid, source, user_id in rows:
+ db.create_session(sid, source=source, user_id=user_id)
+ db.append_message(sid, 'user', 'OLD_' + sid)
+ db.append_message(sid, 'assistant', 'REPLY_' + sid)
+ finally:
+ db.close()
+
+
+def test_per_profile_grants_edit_old_local_rows_of_their_own_profile(tmp_path):
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ model = {'model': {'provider': 'custom', 'default': 'm', 'base_url': 'http://127.0.0.1:1/v1'},
+ 'auxiliary': {'title_generation': {'enabled': False}}}
+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': True}, **model}))
+ beta = home / 'profiles' / 'beta'
+ beta.mkdir(parents=True)
+ (beta / 'config.yaml').write_text(json.dumps(model))
+ _seed(home, [('old-desktop-root', 'desktop', None), ('old-tui-root', 'tui', None)])
+ _seed(beta, [('old-desktop-beta', 'desktop', None), ('old-oneshot-beta', 'oneshot', None),
+ ('old-desktop-nous', 'desktop', 'nous:account'), ('old-desktop-foreign', 'desktop', 'telegram:42')])
+ root = Path(__file__).resolve().parents[2]
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ PYTHONUNBUFFERED='1')
+ with (tmp_path / 'gateway.log').open('w+') as log:
+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ try:
+ deadline, descriptor = time.monotonic() + 60, {}
+ while process.poll() is None and time.monotonic() < deadline:
+ try:
+ descriptor = control(home, 'identify')
+ if descriptor.get('state') == 'ready':
+ break
+ except (OSError, ValueError):
+ pass
+ time.sleep(.1)
+ log.seek(0)
+ assert descriptor.get('state') == 'ready', (descriptor, log.read())
+ homes = {'default': str(home.resolve()), 'beta': str(beta.resolve())}
+
+ def ticket(profile, purpose='native-http'):
+ return control(home, 'session-ticket', {'profile_id': homes[profile], 'purpose': purpose,
+ 'instance_id': descriptor['instance_id']})['ticket']
+
+ def grant(profile):
+ return {'X-Hermes-Gateway-Ticket': ticket(profile)}
+
+ with httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:
+ def pin(sid, profile, minted_for):
+ snap = client.get(f'/api/sessions/{sid}/mutation-snapshot', params={'profile': profile},
+ headers=grant(minted_for))
+ if snap.status_code != 200:
+ return snap.status_code
+ return client.patch(f'/api/sessions/{sid}', headers=grant(minted_for), json={
+ 'profile': profile, 'pinned': True, 'request_id': uuid.uuid4().hex,
+ 'expected_revision': snap.json()['runtime_revision']}).status_code
+
+ # Each old local row, in each profile, through a grant for that profile (403 before).
+ for sid, profile in (('old-desktop-root', 'default'), ('old-tui-root', 'default'),
+ ('old-desktop-beta', 'beta'), ('old-oneshot-beta', 'beta'),
+ ('old-desktop-nous', 'beta')):
+ assert pin(sid, profile, profile) == 200, (sid, profile)
+ # The grant still reaches only its own profile, and a foreign identity stays refused.
+ assert pin('old-desktop-beta', 'beta', 'default') == 403
+ assert pin('old-desktop-foreign', 'beta', 'beta') == 403
+
+ async def stored_picker():
+ async with connect(descriptor['api_origin'].replace('http:', 'ws:') + '/api/ws', subprotocols=[
+ 'hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket('default', 'interactive')]) as ws:
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.list',
+ 'params': {'scope': 'stored', 'limit': 50}}))
+ while (reply := json.loads(await asyncio.wait_for(ws.recv(), 30))).get('id') != 1:
+ pass
+ return reply
+ listed = asyncio.run(stored_picker())
+ # The resume picker offers old Desktop chats like main's listing did (tui only before).
+ assert {s['session_id'] for s in listed['result']['sessions']} == {
+ 'old-desktop-root', 'old-tui-root'}, listed
+ finally:
+ if process.poll() is None:
+ process.send_signal(signal.SIGINT)
+ try:
+ process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
diff --git a/tests/gateway/test_owner_backfill_live_owner.py b/tests/gateway/test_owner_backfill_live_owner.py
new file mode 100644
index 00000000000..2aad5873d26
--- /dev/null
+++ b/tests/gateway/test_owner_backfill_live_owner.py
@@ -0,0 +1,72 @@
+"""Desktop's per-boot owner backfill no longer 409s against the live owner (#106742 live sweep row 24).
+
+``POST /api/sessions/owner-backfill`` took the offline maintenance lock, which a running gateway
+always holds, so every Desktop boot logged a 409 "Exclusive maintenance refused". With a composed
+gateway the idempotent stamp runs on the owner's own store instead.
+"""
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import time
+
+import httpx
+import pytest
+
+from tests.gateway.test_normal_runtime_boot import control
+
+
+def test_owner_backfill_runs_on_the_live_owner(tmp_path):
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ model = {'model': {'provider': 'custom', 'default': 'm', 'base_url': 'http://127.0.0.1:1/v1'},
+ 'auxiliary': {'title_generation': {'enabled': False}}}
+ (home / 'config.yaml').write_text(json.dumps({'gateway': {'multiplex_profiles': True}, **model}))
+ work = home / 'profiles' / 'work'
+ work.mkdir(parents=True)
+ (work / 'config.yaml').write_text(json.dumps(model))
+ root = Path(__file__).resolve().parents[2]
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'TIRITH_ENABLED') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ PYTHONUNBUFFERED='1')
+ with (tmp_path / 'gateway.log').open('w+') as log:
+ process = subprocess.Popen([sys.executable, '-m', 'gateway.run'], cwd=root, env=env,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
+ try:
+ deadline, descriptor = time.monotonic() + 60, {}
+ while process.poll() is None and time.monotonic() < deadline:
+ try:
+ descriptor = control(home, 'identify')
+ if descriptor.get('state') == 'ready':
+ break
+ except (OSError, ValueError):
+ pass
+ time.sleep(.1)
+ log.seek(0)
+ assert descriptor.get('state') == 'ready', (descriptor, log.read())
+
+ def headers(profile_home):
+ # The Desktop mints each profile's own native grant (the profile its body names).
+ return {'X-Hermes-Gateway-Ticket': control(home, 'session-ticket', {
+ 'profile_id': str(profile_home.resolve()), 'instance_id': descriptor['instance_id'],
+ 'purpose': 'native-http'})['ticket']}
+ with httpx.Client(base_url=descriptor['api_origin'], trust_env=False, timeout=30) as client:
+ for body, owner, owner_home in (({}, 'default', home), ({'profile': 'work'}, 'work', work)):
+ response = client.post('/api/sessions/owner-backfill', json=body, headers=headers(owner_home))
+ assert response.status_code == 200, (body, response.text)
+ assert response.json()['profile'] == owner and response.json()['stamped'] == 0
+ # A grant still reaches only its own profile.
+ assert client.post('/api/sessions/owner-backfill', json={'profile': 'work'},
+ headers=headers(home)).status_code == 403
+ finally:
+ if process.poll() is None:
+ process.send_signal(signal.SIGINT)
+ try:
+ process.wait(timeout=20)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)