The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): roster never crosses profiles and one hung backend never freezes the rest
Tekniumf8bcc73c79b2
diff --git a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.tsindex db4cb21f22f..4b0e0f41504 100644--- a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts@@ -42,7 +42,13 @@ vi.mock('@/store/session-states', async importOriginal => ({vi.mock('@/store/session-request-router', async importOriginal => ({...(await importOriginal<typeof RequestRouter>()),- requestForSessionProfile: (owner: unknown) => h.request(owner)+ requestForSessionProfile: (+ owner: unknown,+ _ambient: unknown,+ _method: string,+ _params: unknown,+ timeoutMs?: number+ ) => h.request(owner, timeoutMs)}))const { $gateway } = await import('@/store/gateway')@@ -110,20 +116,75 @@ describe('useLiveWorkRoster', () => {expect(callsFor('bot2')).toBe(1)})- it('interval ticks skip a cold idle owner but keep reading one whose last read showed work', async () => {+ it('interval ticks skip a cold idle owner and re-dial a cold busy one once a minute', async () => {withRows({ idle: 'idle', busy: 'busy' })h.request.mockImplementation(async (owner: unknown) =>owner === 'busy' ? { sessions: [{ session_id: 'busy', subagents: 1 }] } : { sessions: [] })renderHook(() => useLiveWorkRoster())await tick(0)- await tick()- await tick()+ await tick(50_000)+ expect(callsFor('busy')).toBe(1)+ await tick(10_000)+ expect(callsFor('busy')).toBe(2)+ await tick(60_000)expect(callsFor('idle')).toBe(1)expect(callsFor('busy')).toBe(3)})+ it('a hung source never freezes the others: they keep publishing and clear when work ends', async () => {+ withRows({ hung: 'hung', live: 'live' })+ h.open.add('::hung').add('::live')+ let running = true+ h.request.mockImplementation((owner: unknown) => {+ if (owner === 'hung') {+ return new Promise(() => undefined)+ }++ return Promise.resolve({ sessions: owner === 'live' && running ? [{ session_id: 'job', background: 1 }] : [] })+ })+ renderHook(() => useLiveWorkRoster())+ await tick(0)+ expect($liveWorkRoster.get()['::live']?.sessions.job?.background).toBe(1)++ running = false+ await tick()+ expect($liveWorkRoster.get()['::live']?.sessions).toEqual({})+ // The hung read is never stacked, and it rides a one-tick timeout.+ expect(callsFor('hung')).toBe(1)+ expect(h.request.mock.calls.find(c => c[0] === 'hung')?.[1]).toBe(10_000)+ })++ it('window focus respects an active backoff and coalesces bursts', async () => {+ withRows({ flaky: 'flaky' })+ h.request.mockImplementation(async (owner: unknown) => {+ if (owner === 'flaky') {+ throw new Error('socket closed')+ }++ return { sessions: [] }+ })+ renderHook(() => useLiveWorkRoster())+ await tick(0)+ await tick(5_000)++ act(() => {+ window.dispatchEvent(new Event('focus'))+ })+ await tick(0)+ expect(callsFor('flaky')).toBe(1)+ expect(callsFor('ambient')).toBe(2)++ await tick(1_000)+ act(() => {+ window.dispatchEvent(new Event('focus'))+ window.dispatchEvent(new Event('focus'))+ })+ await tick(0)+ expect(callsFor('ambient')).toBe(2)+ })+it('keeps retrying a source through transient failures until it recovers', async () => {withRows({ flaky: 'flaky' })h.open.add('::flaky')diff --git a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.tsindex c4282d533cc..2f8ac4bee64 100644--- a/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.ts@@ -10,6 +10,10 @@ import { isSessionOwnerRoute, requestForSessionProfile, type SessionOwnerScope }import { knownOwnerForSession } from '@/store/session-states'const POLL_MS = 10_000+// A closed socket whose last read showed work is re-dialed this often, not every tick.+const COLD_BUSY_MS = 60_000+// Window focus re-reads every source at most this often (alt-tab bursts).+const FOCUS_MIN_GAP_MS = 5_000const MAX_BACKOFF_MS = 5 * 60_000interface RosterResult {@@ -38,8 +42,10 @@ function rosterSources(): Map<string, RosterSource> {const ambientKey = isActivePrimary() ? gatewayRouteState(null, activeGatewayProfileKey()).key : 'ambient'const sources = new Map<string, RosterSource>([[ambientKey, { open: true, owner: undefined }]])+ // One row list per tick, each owner resolved against its own row: resolving+ // through the whole list per row made a tick O(rows²).for (const row of ownerLookupSessionRows()) {- const owner = knownOwnerForSession(row.id)+ const owner = knownOwnerForSession(row.id, [row])if (!owner) {continue@@ -58,12 +64,13 @@ function rosterSources(): Map<string, RosterSource> {/** App-level hydration of `$liveWorkRoster` (sidebar rows not on screen, and* every row after a reload / socket reconnect): one `subagent.roster` read per* backend on connect and window focus, then every 10 s while the window is- * visible. Interval ticks are passive: after a source's first read on this- * connection they read only sockets already open (plus sources whose last read- * showed live work, so a finished child clears), never re-dialing an idle- * historical owner every tick just to learn nothing runs there. A- * backend without the RPC stops for this connection; any other failure backs- * off and keeps retrying, so a recovered socket comes back on its own. */+ * visible. Each source reads and publishes on its own, with a one-tick request+ * timeout, so a hung backend never freezes the other sources' rows. Interval+ * ticks are passive: after a source's first read on this connection they read+ * only sockets already open, plus a closed one whose last read showed work once+ * a minute (so a finished child clears without re-dialing every tick). A backend+ * without the RPC stops for this connection; any other failure backs off (focus+ * included) and keeps retrying, so a recovered socket comes back on its own. */export function useLiveWorkRoster() {const gatewayState = useStore($gatewayState)@@ -76,25 +83,28 @@ export function useLiveWorkRoster() {}let cancelled = false- let pending = false+ let lastHydrate = -Infinity+ let current = new Set<string>()+ const inFlight = new Set<string>()const unsupported = new Set<string>()- // Sources read at least once on this connection: rows that load after the- // connect (the session list, a newly shown profile) get their first read.- const read = new Set<string>()+ // When each source was last asked on this connection: rows that load after+ // the connect (the session list, a newly shown profile) get their first read.+ const sentAt = new Map<string, number>()const backoff = new Map<string, { failures: number; until: number }>()const readSource = async (key: string, owner: SessionOwnerScope, ambient: ReturnType<typeof ambientRequestFor>) => {- const sentAt = Date.now()- read.add(key)+ const at = Date.now()+ sentAt.set(key, at)+ inFlight.add(key)try {- const result = await requestForSessionProfile<RosterResult>(owner, ambient, 'subagent.roster', {})+ const result = await requestForSessionProfile<RosterResult>(owner, ambient, 'subagent.roster', {}, POLL_MS)+ backoff.delete(key)- if (!cancelled) {- setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [], sentAt)+ // A source whose rows left the sidebar mid-read stays pruned.+ if (!cancelled && current.has(key)) {+ setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [], at)}-- backoff.delete(key)} catch (error) {if (isMissingRpcMethod(error)) {unsupported.add(key)@@ -106,62 +116,65 @@ export function useLiveWorkRoster() {if (!cancelled) {setLiveWorkRosterSource(key, null)}+ } finally {+ inFlight.delete(key)}}- const refresh = async (hydrate: boolean) => {+ const refresh = (hydrate: boolean) => {const gateway = $gateway.get()- if (cancelled || pending || !gateway) {+ if (cancelled || !gateway) {return}- pending = trueconst ambient = ambientRequestFor(gateway)const sources = rosterSources()const roster = $liveWorkRoster.get()const now = Date.now()+ current = new Set(sources.keys())- try {- await Promise.all(- [...sources].map(([key, { open, owner }]) => {- const due = hydrate || now >= (backoff.get(key)?.until ?? 0)- const warm = hydrate || open || !read.has(key) || rosterSourceHasWork(roster, key)+ // Owners whose rows left the sidebar stop contributing.+ for (const key of Object.keys(roster)) {+ if (!current.has(key)) {+ setLiveWorkRosterSource(key, null)+ }+ }- return unsupported.has(key) || !due || !warm ? undefined : readSource(key, owner, ambient)- })- )+ for (const [key, { open, owner }] of sources) {+ const last = sentAt.get(key)+ const due = !inFlight.has(key) && !unsupported.has(key) && now >= (backoff.get(key)?.until ?? 0)- if (cancelled) {- return- }+ const warm =+ hydrate || open || last === undefined || (rosterSourceHasWork(roster, key) && now - last >= COLD_BUSY_MS)- // Owners whose rows left the sidebar stop contributing.- for (const key of Object.keys($liveWorkRoster.get())) {- if (!sources.has(key)) {- setLiveWorkRosterSource(key, null)- }+ if (due && warm) {+ void readSource(key, owner, ambient)}- } finally {- pending = false}}- void refresh(true)+ const hydrate = () => {+ if (Date.now() - lastHydrate >= FOCUS_MIN_GAP_MS) {+ lastHydrate = Date.now()+ refresh(true)+ }+ }++ hydrate()const timer = window.setInterval(() => {if (document.visibilityState === 'visible') {- void refresh(false)+ refresh(false)}}, POLL_MS)- const onFocus = () => void refresh(true)- window.addEventListener('focus', onFocus)+ window.addEventListener('focus', hydrate)return () => {cancelled = truewindow.clearInterval(timer)- window.removeEventListener('focus', onFocus)+ window.removeEventListener('focus', hydrate)}}, [gatewayState])}diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 93809ba4ecd..e97d45ffe61 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1764,7 +1764,7 @@ export function openTileGatewayScopes(): Set<string> {* Returns undefined when no owner is known — the caller fails closed* (assertSessionOwnerResolved), never falls to "active".*/-export function knownOwnerForSession(sessionId: null | string | undefined): SessionOwnerScope {+export function knownOwnerForSession(sessionId: null | string | undefined, rows = ownerLookupSessionRows()) {if (!sessionId) {return undefined}@@ -1774,7 +1774,7 @@ export function knownOwnerForSession(sessionId: null | string | undefined): Sessconst durable =sessionTileOwner(storedSessionId) ??getSessionOwnerHint(storedSessionId) ??- knownSessionOwner(ownerLookupSessionRows(), storedSessionId)+ knownSessionOwner(rows, storedSessionId)if (isSessionOwnerRoute(durable)) {return durablediff --git a/tests/tui_gateway/test_subagent_roster_profiles.py b/tests/tui_gateway/test_subagent_roster_profiles.pynew file mode 100644index 00000000000..e75251c6011--- /dev/null+++ b/tests/tui_gateway/test_subagent_roster_profiles.py@@ -0,0 +1,76 @@+"""``subagent.roster`` across two profiles served by one process: a background process lights only the+conversation of the profile that owns it, even when the other profile's store holds an identical route."""++import threading+from pathlib import Path++import pytest++ROUTE = "agent:main:telegram:dm:42" # unmultiplexed / legacy route: identical in every profile's store+++def two_profiles(tmp_path, monkeypatch):+ from agent import secret_scope+ from hermes_state import SessionDB+ from tools import delegate_tool_registry as reg+ from tools.process_registry import process_registry+ from tui_gateway import launch_profile_policy, server++ launch = tmp_path / "launch-home"+ bot2 = launch / "profiles" / "bot2"+ bot2.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(launch))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", False)+ monkeypatch.setattr(launch_profile_policy, "_snapshot", None)+ monkeypatch.setattr(server, "_hermes_home", launch)+ monkeypatch.setattr(server, "_served_profile_homes", set())++ launch_db = SessionDB(db_path=launch / "state.db")+ launch_db.create_session("default-conv", source="telegram", session_key=ROUTE)+ bot2_db = SessionDB(db_path=bot2 / "state.db")+ bot2_db.create_session("bot2-legacy", source="telegram", session_key=ROUTE)+ bot2_db.create_session("bot2-conv", source="telegram", session_key="agent:bot2:telegram:dm:42")+ bot2_db.close()+ monkeypatch.setattr(server, "_get_db", lambda: launch_db)+ monkeypatch.setattr(reg, "_active_subagents", {})+ monkeypatch.setattr(reg, "_active_subagents_lock", threading.RLock())++ procs = {}+ monkeypatch.setattr(process_registry, "list_sessions", lambda **_: [{"session_id": k} for k in procs])+ monkeypatch.setattr(process_registry, "get", procs.get)++ def spawn(pid, *, parent="", key=ROUTE):+ from tools.process_registry import ProcessSession+ procs[pid] = ProcessSession(id=pid, command="sleep 90", session_key=key, parent_session_id=parent)++ def roster(profile=None):+ params = {"profile": profile} if profile else {}+ resp = server.handle_request({"jsonrpc": "2.0", "id": 1, "method": "subagent.roster", "params": params})+ return {e["session_id"]: e["background"] for e in resp["result"]["sessions"]}++ yield spawn, roster+ launch_db.close()+++def test_a_stored_parent_id_is_authoritative_across_profiles(two_profiles):+ """The default profile's process names its conversation; the identical legacy route in bot2's store+ must not light bot2's row."""+ spawn, roster = two_profiles+ spawn("proc_default", parent="default-conv")++ assert roster("bot2") == {}+ assert roster() == {"default-conv": 1}+ assert roster("bot2") == {}+++def test_route_fallback_is_fenced_to_the_profile_namespace(two_profiles):+ """Without a stored parent id the route decides, but only inside the requested profile's namespace:+ an unnamespaced route is the launch profile's, a namespaced one its own profile's."""+ spawn, roster = two_profiles+ spawn("proc_legacy")+ spawn("proc_bot2", key="agent:bot2:telegram:dm:42")++ assert roster("bot2") == {"bot2-conv": 1}+ assert roster() == {"default-conv": 1}diff --git a/tui_gateway/methods_subagents.py b/tui_gateway/methods_subagents.pyindex da153478d5e..04f8e822884 100644--- a/tui_gateway/methods_subagents.py+++ b/tui_gateway/methods_subagents.py@@ -73,7 +73,7 @@ def _live_work_owners():from tools.process_registry import process_registrywith _active_subagents_lock:- owners = [("subagents", (str(r.get("owner_agent_session_id") or ""),))+ owners = [("subagents", (str(r.get("owner_agent_session_id") or ""), ""))for r in _active_subagents.values() if not r.get("depth")]for entry in process_registry.list_sessions():proc = process_registry.get(entry.get("session_id"))@@ -83,18 +83,32 @@ def _live_work_owners():return owners-def _stored_owner(db, candidates):- """The first candidate stored in ``db`` (the requested profile's state.db), resolving a gateway route key- to the conversation row that carries it; "" when none is ours."""- for key in filter(None, candidates):- if db.get_session(key):- return key- parts = key.split(":")- if len(parts) >= 3 and parts[0] == "agent":- row = db.find_latest_gateway_session_for_peer(source=parts[2], session_key=key)- if row and row.get("id"):- return str(row["id"])- return ""+def _route_namespaces(profile_home):+ """Session-key namespaces (the ``agent:<ns>`` segment) a route of the requested profile can carry.+ Multiplexed routes are namespaced per profile; ``agent:main`` is also every unmultiplexed and legacy+ route, so it is trusted for a named profile only when that profile is the sole one this process hosts."""+ from gateway.session import _session_key_namespace+ from gateway.session_authorities import served_profile_name++ own = _session_key_namespace(served_profile_name(profile_home or _hermes_home)).split(":", 1)[1]+ sole = profile_home is None and not _served_profile_homes+ return {own, "main"} if sole else {own}+++def _stored_owner(db, owner_ids, namespaces):+ """The conversation in ``db`` (the requested profile's state.db) that owns a piece of work; "" when none+ is ours. A stored id (child lineage, process ``parent_session_id``) is authoritative: present here or+ not ours. Only a process without one falls back to its route key, fenced to this profile's namespaces,+ since an identical route (a legacy ``agent:main`` key, the same DM in two profiles) can sit in another+ profile's store."""+ stored_id, route = owner_ids+ if stored_id:+ return stored_id if db.get_session(stored_id) else ""+ parts = route.split(":")+ if len(parts) < 3 or parts[0] != "agent" or parts[1] not in namespaces:+ return ""+ row = db.find_latest_gateway_session_for_peer(source=parts[2], session_key=route)+ return str(row["id"]) if row and row.get("id") else ""@method("subagent.roster")@@ -114,11 +128,12 @@ def _(rid, params):if home := connection_profile_home():scope = {"profile": Path(home).name}counts = {}+ namespaces = _route_namespaces(_profile_home(scope.get("profile")))with _profile_db(scope) as db:if db is None:return _ok(rid, {"sessions": []})- for kind, candidates in owners:- if sid := _stored_owner(db, candidates):+ for kind, owner_ids in owners:+ if sid := _stored_owner(db, owner_ids, namespaces):counts.setdefault(sid, {"subagents": 0, "background": 0})[kind] += 1return _ok(rid, {"sessions": [{"session_id": sid, **c} for sid, c in counts.items()]})