The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): do not raise AttributeError while another profile is starting
Adolaniumf968aa730462
diff --git a/gateway/session_ancillary.py b/gateway/session_ancillary.pyindex ba940b91828..b6ced3b2d5a 100644--- a/gateway/session_ancillary.py+++ b/gateway/session_ancillary.py@@ -190,7 +190,7 @@ def _reachable_upload_home(connection, raw_home) -> bool:homes = {connection.authority.profile_id}if connection.host_scoped:registry = getattr(getattr(connection.authority, 'runner', None), 'session_authorities', None)- homes |= {sibling.profile_id for sibling in (registry or ())}+ homes |= {sibling.profile_id for sibling in (registry or ()) if sibling is not None}try:target = Path(raw_home).resolve()return any(Path(home).resolve() == target for home in homes)diff --git a/gateway/session_authorities.py b/gateway/session_authorities.pyindex fedeca50e45..83987ed9774 100644--- a/gateway/session_authorities.py+++ b/gateway/session_authorities.py@@ -11,6 +11,7 @@ scoped or not, exactly as before."""from __future__ import annotations+import asynciofrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -26,6 +27,9 @@ class SessionAuthorities:self.launch_key = hermes_home_key(launch_home)self._by_key: dict[str, object] = {}self._names: dict[str, str | None] = {}+ # Set when a None slot is filled or dropped. Hot-serve publishes the slot before+ # the authority exists, and a host-scoped attach waits on this instead of reading it.+ self._starting: dict[str, asyncio.Event] = {}# A multiplexing runtime (configured, or one that ever served a second home) keeps the# scoped-lookup contract after its secondaries are removed: an unserved home is None.self.multiplexed = bool(multiplexed)@@ -36,15 +40,23 @@ class SessionAuthorities:raise RuntimeError(f'duplicate session authority for {home}')self._by_key[key] = authorityself._names[key] = name+ if authority is None:+ self._starting[key] = asyncio.Event()if key != self.launch_key:self.multiplexed = True+ def _finish_start(self, key) -> None:+ event = self._starting.pop(key, None)+ if event is not None:+ event.set()+def replace(self, home, authority) -> None:"""Fill the slot reserved by ``add(home, None, name=...)`` once the authority exists."""key = hermes_home_key(home)if key not in self._by_key or self._by_key[key] is not None:raise RuntimeError(f'no reserved session authority slot for {home}')self._by_key[key] = authority+ self._finish_start(key)def remove(self, home):"""Drop *home*'s slot (a parked boot, a hot-unserved profile); returns the authority or None.@@ -53,7 +65,25 @@ class SessionAuthorities:if key == self.launch_key:raise RuntimeError('the launch session authority cannot be removed')self._names.pop(key, None)- return self._by_key.pop(key, None)+ removed = self._by_key.pop(key, None)+ self._finish_start(key)+ return removed++ def starting(self, profile):+ """Event for the unbuilt slot *profile* names, or None when nothing is waiting on it.++ ``replace`` and ``remove`` set the event. A waiter then routes against the registry+ as it stands: the new authority, or no such profile."""+ from hermes_cli.profiles import profile_matches_home+ for key, authority in list(self._by_key.items()):+ if authority is not None:+ continue+ event = self._starting.get(key)+ if event is None or event.is_set():+ continue+ if profile_matches_home(profile, Path(key)):+ return event+ return Nonedef profile_name(self, authority):"""Served profile name for *authority*; None for the launch profile (its adapters arediff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 40251f0b234..84a2eaa8521 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -157,6 +157,10 @@ class AuthorityConnection:raise RuntimeStoreError('profile_mismatch')registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)for sibling in (registry or ()):+ # The slot is reserved before the authority exists. Skip it; a host-scoped+ # attach waits in ``_routed_connection`` instead of reading ``profile_id`` here.+ if sibling is None:+ continueif sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):connection = self._siblings.get(sibling.profile_id)# A re-served profile is a new authority under the same id: never keep routing to@@ -168,6 +172,18 @@ class AuthorityConnection:return connectionraise RuntimeStoreError('profile_mismatch')+ async def _routed_connection(self, profile):+ """Sibling connection for *profile*, after a host-scoped attach's in-progress start.++ Hot-serve reserves the slot as None while ``initialize_session_authority`` is still+ awaiting. The Desktop shared socket and the dashboard gate wait for that start.+ A profile-bound grant does not: ``_sibling_for`` refuses it as a mismatch."""+ if self.host_scoped:+ registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)+ while registry is not None and (pending := registry.starting(profile)) is not None:+ await pending.wait()+ return self._sibling_for(profile)+def handlers(self):"""Method → handler for every verb ``dispatch`` serves outside the group controls; eachname is declared in ``tui_gateway/contracts`` (``METHODS`` or ``CANONICAL_METHODS``)."""@@ -261,7 +277,7 @@ class AuthorityConnection:profile = params.get('profile')if isinstance(profile, str) and profile:try:- routed = self._sibling_for(profile)+ routed = await self._routed_connection(profile)except RuntimeStoreError as exc:_log_refusal(getattr(self.actor, 'profile_id', None), method, exc)return {'jsonrpc': '2.0', 'id': rid, 'error': {diff --git a/tests/gateway/test_sibling_attach_while_profile_starting.py b/tests/gateway/test_sibling_attach_while_profile_starting.pynew file mode 100644index 00000000000..7b045b5c664--- /dev/null+++ b/tests/gateway/test_sibling_attach_while_profile_starting.py@@ -0,0 +1,99 @@+"""A host-scoped attach while another profile is still starting.++Hot-serve reserves the profile's registry slot before its authority exists. A shared+socket (Desktop, gateway-hosted Webapp) must still open a session on a profile that is+already running, and the attach to the profile being started must wait for that start+and then succeed.+"""+import asyncio+from pathlib import Path++import pytest++from tests.gateway.test_session_authorities_multiplex import _reserve_homes, _runner+from tests.gateway.test_ticket_profile_scope import _Transport+++async def test_host_attach_waits_while_another_profile_is_starting(tmp_path, monkeypatch):+ from gateway import session_authority+ from gateway.run_runtime import initialize_gateway_runtime, serve_profile_runtime+ from gateway.runtime_ownership import process_ownership+ from gateway.session_authorities import authority_for_profile_id, owner_scope+ from gateway.session_controls import AuthorityConnection++ root, homes = _reserve_homes(tmp_path, monkeypatch, names=('alpha',))+ alpha_home = homes[1][1]+ beta_home = root / 'profiles' / 'beta'+ beta_home.mkdir(parents=True, mode=0o700)+ (beta_home / 'config.yaml').write_text('{}')+ process_ownership.reserve([*(home for _, home in homes), beta_home])+ entered, release = asyncio.Event(), asyncio.Event()+ connection = runner = None+ serve_task = beta_task = None+ try:+ runner = _runner(root, homes)+ await initialize_gateway_runtime(runner)+ real_initialize = session_authority.initialize_session_authority++ async def hold_initialize(*args, **kwargs):+ entered.set()+ await release.wait()+ return await real_initialize(*args, **kwargs)++ monkeypatch.setattr(session_authority, 'initialize_session_authority', hold_initialize)+ serve_task = asyncio.create_task(serve_profile_runtime(runner, 'beta', beta_home))+ await asyncio.wait_for(entered.wait(), timeout=30)+ assert beta_home in runner.session_authorities+ assert runner.session_authorities.for_home(beta_home) is None++ store = runner.session_ticket_store+ ticket = store.mint(profile_id=str(root.resolve()), subject='uid:desk', purpose='interactive', scope='host')+ grant = store.redeem(ticket, profile_id=None, purpose='interactive')+ launch = authority_for_profile_id(runner, grant['profile_id'])+ identity = {'user_id': grant['subject'], 'provider': 'local', 'profile_id': grant['profile_id'],+ 'instance_id': grant['instance_id'], 'capabilities': grant['capabilities'],+ 'native_bootstrap': True, 'profile_scope': 'host'}+ with owner_scope(launch):+ connection = AuthorityConnection(launch, _Transport(), identity, operator=True)++ async def create(profile, request_id):+ with owner_scope(launch):+ return await connection.dispatch({'id': request_id, 'method': 'session.create', 'params': {+ 'profile': profile, 'request_id': request_id, 'source': 'cli', 'cwd': str(tmp_path),+ 'model': 'm', 'toolsets': []}})++ alpha = await create('alpha', 'alpha-while-beta-starts')+ assert 'result' in alpha, alpha+ alpha_authority = runner.session_authorities.for_home(alpha_home)+ assert alpha['result']['session_id'] in alpha_authority.sessions++ beta_task = asyncio.create_task(create('beta', 'beta-while-starting'))+ await asyncio.sleep(0) # one turn: the attach either waits or raises+ if beta_task.done():+ exc = beta_task.exception()+ raise AssertionError(f'attach while beta is still starting finished early: {exc!r}')++ release.set()+ served, beta = await asyncio.gather(serve_task, beta_task)+ assert 'result' in beta, beta+ assert beta['result']['session_id'] in served.sessions+ assert alpha['result']['session_id'] in alpha_authority.sessions+ finally:+ release.set()+ for task in (serve_task, beta_task):+ if task is None:+ continue+ if not task.done():+ await asyncio.wait([task], timeout=30)+ if task.done() and not task.cancelled():+ task.exception()+ if connection is not None:+ with owner_scope(connection.authority):+ await connection.close()+ for authority in list(getattr(runner, 'session_authorities', None) or []):+ db = getattr(authority, 'db', None)+ if db is not None:+ db.close()+ for home in [*(path for _, path in homes), beta_home]:+ process_ownership.release(Path(home))