Skip to content

The agent that grows with you

fix(desktop): roster lights background-only rows, every owner, and stops churn

Teknium345278667349
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index 3a6710d4209..0d0e5006575 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -23,7 +23,8 @@ import {
import { createClientSessionState } from '@/lib/chat-runtime'
import { sessionListFingerprint, sessionMessagesSignature } from '@/lib/session-signatures'
import { latestSessionTodos, latestSessionTodoSnapshot } from '@/lib/todos'
-import { pendingSessionReplay, sharedPrimaryRoute } from '@/store/gateway'
+import { pendingSessionReplay } from '@/store/gateway'
+import { sharedPrimaryRoute } from '@/store/gateway-shared-route'
import { $sidebarShowArchived } from '@/store/layout'
import { $changeEventsAvailable, $cronChangeTick, $projectsChangeTick, $sessionsChangeTick } from '@/store/live-sync'
import { $onBattery, batteryPollInterval } from '@/store/power'
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.ts
new file mode 100644
index 00000000000..db4cb21f22f
--- /dev/null
+++ b/apps/desktop/src/app/contrib/hooks/use-live-work-roster.test.ts
@@ -0,0 +1,188 @@
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { HermesGateway } from '@/hermes'
+import type * as GatewayStore from '@/store/gateway'
+import { $liveWorkRoster } from '@/store/live-work-roster'
+import type * as SessionStore from '@/store/session'
+import type * as RequestRouter from '@/store/session-request-router'
+import type * as SessionStates from '@/store/session-states'
+
+import { useLiveWorkRoster } from './use-live-work-roster'
+
+const h = vi.hoisted(() => ({
+ owners: new Map<string, unknown>(),
+ open: new Set<string>(),
+ request: vi.fn(),
+ rows: [] as { id: string }[]
+}))
+
+// Route identity as gateway.ts derives it: the launch profile in any spelling
+// rides the window primary; anything else is its own scope, open or cold.
+vi.mock('@/store/gateway', async importOriginal => ({
+ ...(await importOriginal<typeof GatewayStore>()),
+ activeGatewayProfileKey: () => 'default',
+ gatewayRouteState: (connectionId: null | string, profile: string) => {
+ const key = (profile || 'default') === 'default' ? 'primary:default' : `${connectionId ?? ''}::${profile}`
+
+ return { key, open: key === 'primary:default' || h.open.has(key) }
+ },
+ isActivePrimary: () => true
+}))
+
+vi.mock('@/store/session', async importOriginal => ({
+ ...(await importOriginal<typeof SessionStore>()),
+ ownerLookupSessionRows: () => h.rows
+}))
+
+vi.mock('@/store/session-states', async importOriginal => ({
+ ...(await importOriginal<typeof SessionStates>()),
+ knownOwnerForSession: (id: string) => h.owners.get(id)
+}))
+
+vi.mock('@/store/session-request-router', async importOriginal => ({
+ ...(await importOriginal<typeof RequestRouter>()),
+ requestForSessionProfile: (owner: unknown) => h.request(owner)
+}))
+
+const { $gateway } = await import('@/store/gateway')
+const { $gatewayState } = await import('@/store/session')
+
+const ownerOf = (call: unknown[]) => JSON.stringify(call[0] ?? 'ambient')
+const callsFor = (owner: unknown) => h.request.mock.calls.filter(c => ownerOf(c) === JSON.stringify(owner)).length
+
+async function tick(ms = 10_000) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms)
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ h.owners.clear()
+ h.open.clear()
+ h.rows = []
+ h.request.mockReset()
+ h.request.mockResolvedValue({ sessions: [] })
+ $gateway.set({ request: vi.fn() } as unknown as HermesGateway)
+ $gatewayState.set('open')
+ $liveWorkRoster.set({})
+})
+
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+ $gateway.set(null)
+ $liveWorkRoster.set({})
+})
+
+function withRows(owners: Record<string, unknown>) {
+ h.rows = Object.keys(owners).map(id => ({ id }))
+ Object.entries(owners).forEach(([id, owner]) => h.owners.set(id, owner))
+}
+
+describe('useLiveWorkRoster', () => {
+ it('asks the launch profile once a tick however many spellings its rows carry', async () => {
+ withRows({ a: 'default', b: { connectionId: 'local', profile: 'default' } })
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+
+ expect(h.request).toHaveBeenCalledTimes(1)
+ await tick()
+ expect(h.request).toHaveBeenCalledTimes(2)
+ })
+
+ it('gives an owner whose rows load after the connect its first read on the next tick', async () => {
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+ withRows({ late: 'late' })
+ await tick()
+ await tick()
+
+ expect(callsFor('late')).toBe(1)
+ })
+
+ it('reads owners that only have cron or messaging rows', async () => {
+ withRows({ cronRow: 'bot2' })
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+
+ expect(callsFor('bot2')).toBe(1)
+ })
+
+ it('interval ticks skip a cold idle owner but keep reading one whose last read showed work', 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()
+
+ expect(callsFor('idle')).toBe(1)
+ expect(callsFor('busy')).toBe(3)
+ })
+
+ it('keeps retrying a source through transient failures until it recovers', async () => {
+ withRows({ flaky: 'flaky' })
+ h.open.add('::flaky')
+ let failures = 4
+ h.request.mockImplementation(async (owner: unknown) => {
+ if (owner === 'flaky' && failures-- > 0) {
+ throw new Error('socket closed')
+ }
+
+ return { sessions: owner === 'flaky' ? [{ session_id: 's', subagents: 1 }] : [] }
+ })
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+ // Backoff 20 s, 40 s, 80 s, 160 s: five reads in five minutes, not thirty.
+ await tick(5 * 60_000)
+
+ expect(callsFor('flaky')).toBe(5)
+ expect($liveWorkRoster.get()['::flaky']?.sessions.s?.subagents).toBe(1)
+ await tick()
+ expect(callsFor('flaky')).toBe(6)
+ })
+
+ it('stops for good only on a backend without the RPC', async () => {
+ withRows({ old: 'old' })
+ h.open.add('::old')
+ h.request.mockImplementation(async (owner: unknown) => {
+ if (owner === 'old') {
+ throw Object.assign(new Error('method not found'), { code: -32601 })
+ }
+
+ return { sessions: [] }
+ })
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+ await tick(10 * 60_000)
+
+ expect(callsFor('old')).toBe(1)
+ })
+
+ it('a read from a superseded connection never prunes buckets the new one published', async () => {
+ withRows({ x: 'x' })
+ let finishOld: (value: unknown) => void = () => undefined
+ h.request.mockImplementation((owner: unknown) =>
+ owner === 'x' ? new Promise(resolve => (finishOld = resolve)) : Promise.resolve({ sessions: [] })
+ )
+ renderHook(() => useLiveWorkRoster())
+ await tick(0)
+
+ act(() => $gatewayState.set('closed'))
+ withRows({ y: 'y' })
+ h.rows = [{ id: 'y' }]
+ h.request.mockImplementation(async (owner: unknown) =>
+ owner === 'y' ? { sessions: [{ session_id: 'live', subagents: 1 }] } : { sessions: [] }
+ )
+ act(() => $gatewayState.set('open'))
+ await tick(0)
+ expect($liveWorkRoster.get()['::y']).toBeDefined()
+
+ await act(async () => finishOld({ sessions: [] }))
+ expect($liveWorkRoster.get()['::y']).toBeDefined()
+ })
+})
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.ts
index c583b05cd6e..c4282d533cc 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
@@ -1,33 +1,54 @@
import { useStore } from '@nanostores/react'
import { useEffect } from 'react'
-import { $gateway } from '@/store/gateway'
-import { $liveWorkRoster, setLiveWorkRosterSource } from '@/store/live-work-roster'
-import { $gatewayState, $sessions } from '@/store/session'
+import { isMissingRpcMethod } from '@/lib/gateway-rpc'
+import { $gateway, activeGatewayProfileKey, gatewayRouteState, isActivePrimary } from '@/store/gateway'
+import { $liveWorkRoster, rosterSourceHasWork, setLiveWorkRosterSource } from '@/store/live-work-roster'
+import { $gatewayState, ownerLookupSessionRows } from '@/store/session'
import { ambientRequestFor } from '@/store/session-gone-latch'
-import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
+import { isSessionOwnerRoute, requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
import { knownOwnerForSession } from '@/store/session-states'
const POLL_MS = 10_000
-const MAX_FAILURES = 3
-const AMBIENT = 'ambient'
+const MAX_BACKOFF_MS = 5 * 60_000
interface RosterResult {
sessions?: unknown[]
}
-/** Every backend owner the sidebar shows rows for. The ambient socket answers
- * for the launch profile; a row owned by another profile (or connection) is
- * asked on the same route its own session RPCs take, so each backend only
- * reports conversations stored in that profile. */
-function rosterSources(): Map<string, SessionOwnerScope> {
- const sources = new Map<string, SessionOwnerScope>([[AMBIENT, undefined]])
+interface RosterSource {
+ open: boolean
+ owner: SessionOwnerScope
+}
- for (const row of $sessions.get()) {
+const routeOf = (owner: SessionOwnerScope) =>
+ isSessionOwnerRoute(owner)
+ ? gatewayRouteState(owner.connectionId, owner.profile)
+ : gatewayRouteState(null, String(owner ?? ''))
+
+/** Every backend the sidebar shows rows for (recents, cron and messaging rows
+ * alike), keyed by the socket a read would ride, so one backend is asked once
+ * however many spellings its owner has (the launch profile used to be asked
+ * three times a tick). The ambient socket answers for the active profile; a row owned by another profile (or connection) is asked on
+ * the route its own session RPCs take, so each backend only reports
+ * conversations stored in that profile. */
+function rosterSources(): Map<string, RosterSource> {
+ // The ambient read carries no profile, so it shares a key only when it IS the
+ // window primary answering for its own profile.
+ const ambientKey = isActivePrimary() ? gatewayRouteState(null, activeGatewayProfileKey()).key : 'ambient'
+ const sources = new Map<string, RosterSource>([[ambientKey, { open: true, owner: undefined }]])
+
+ for (const row of ownerLookupSessionRows()) {
const owner = knownOwnerForSession(row.id)
- if (owner) {
- sources.set(JSON.stringify(owner), owner)
+ if (!owner) {
+ continue
+ }
+
+ const route = routeOf(owner)
+
+ if (!sources.has(route.key)) {
+ sources.set(route.key, { open: route.open, owner })
}
}
@@ -35,10 +56,14 @@ function rosterSources(): Map<string, SessionOwnerScope> {
}
/** App-level hydration of `$liveWorkRoster` (sidebar rows not on screen, and
- * every row after a reload / socket reconnect): one `subagent.roster` read
- * per backend owner on connect and every 10 s while the window is visible.
- * A source that keeps failing (an older backend without the RPC) stops until
- * the next reconnect or window focus, so it never hot-loops. */
+ * 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. */
export function useLiveWorkRoster() {
const gatewayState = useStore($gatewayState)
@@ -52,9 +77,39 @@ export function useLiveWorkRoster() {
let cancelled = false
let pending = false
- const failures = new Map<string, number>()
+ 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>()
+ 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)
+
+ try {
+ const result = await requestForSessionProfile<RosterResult>(owner, ambient, 'subagent.roster', {})
+
+ if (!cancelled) {
+ setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [], sentAt)
+ }
+
+ backoff.delete(key)
+ } catch (error) {
+ if (isMissingRpcMethod(error)) {
+ unsupported.add(key)
+ } else {
+ const failures = (backoff.get(key)?.failures ?? 0) + 1
+ backoff.set(key, { failures, until: Date.now() + Math.min(POLL_MS * 2 ** failures, MAX_BACKOFF_MS) })
+ }
+
+ if (!cancelled) {
+ setLiveWorkRosterSource(key, null)
+ }
+ }
+ }
- const refresh = async () => {
+ const refresh = async (hydrate: boolean) => {
const gateway = $gateway.get()
if (cancelled || pending || !gateway) {
@@ -64,32 +119,23 @@ export function useLiveWorkRoster() {
pending = true
const ambient = ambientRequestFor(gateway)
const sources = rosterSources()
+ const roster = $liveWorkRoster.get()
+ const now = Date.now()
try {
await Promise.all(
- [...sources].map(async ([key, owner]) => {
- if ((failures.get(key) ?? 0) >= MAX_FAILURES) {
- return
- }
-
- try {
- const result = await requestForSessionProfile<RosterResult>(owner, ambient, 'subagent.roster', {})
-
- if (!cancelled) {
- setLiveWorkRosterSource(key, Array.isArray(result?.sessions) ? result.sessions : [])
- }
-
- failures.delete(key)
- } catch {
- failures.set(key, (failures.get(key) ?? 0) + 1)
-
- if (!cancelled) {
- setLiveWorkRosterSource(key, null)
- }
- }
+ [...sources].map(([key, { open, owner }]) => {
+ const due = hydrate || now >= (backoff.get(key)?.until ?? 0)
+ const warm = hydrate || open || !read.has(key) || rosterSourceHasWork(roster, key)
+
+ return unsupported.has(key) || !due || !warm ? undefined : readSource(key, owner, ambient)
})
)
+ if (cancelled) {
+ return
+ }
+
// Owners whose rows left the sidebar stop contributing.
for (const key of Object.keys($liveWorkRoster.get())) {
if (!sources.has(key)) {
@@ -101,25 +147,21 @@ export function useLiveWorkRoster() {
}
}
- void refresh()
+ void refresh(true)
const timer = window.setInterval(() => {
if (document.visibilityState === 'visible') {
- void refresh()
+ void refresh(false)
}
}, POLL_MS)
- const retry = () => {
- failures.clear()
- void refresh()
- }
-
- window.addEventListener('focus', retry)
+ const onFocus = () => void refresh(true)
+ window.addEventListener('focus', onFocus)
return () => {
cancelled = true
window.clearInterval(timer)
- window.removeEventListener('focus', retry)
+ window.removeEventListener('focus', onFocus)
}
}, [gatewayState])
}
diff --git a/apps/desktop/src/store/composer-status.ts b/apps/desktop/src/store/composer-status.ts
index 88340930a11..e43e2b430a1 100644
--- a/apps/desktop/src/store/composer-status.ts
+++ b/apps/desktop/src/store/composer-status.ts
@@ -6,7 +6,7 @@ import { type TodoItem, type TodoStatus, todoTree } from '@/lib/todos'
import { $gateway } from './gateway'
import { $goalsBySession, type GoalStatus } from './goals'
-import { $liveWorkRoster, rosterLiveIds } from './live-work-roster'
+import { $liveWorkRoster, noteEventFed, rosterLiveIds } from './live-work-roster'
import { dispatchNativeNotification } from './native-notifications'
import { notifyError } from './notifications'
import { isSessionGone, isSessionGoneForBackgroundPolling, markSessionGone, noteRuntimeAlive } from './runtime-gone'
@@ -52,6 +52,8 @@ export interface ComposerStatusItem {
// Writable source for background work, synced from the gateway's process
// registry (`terminal(background=true)` spawns) via `process.list`.
export const $backgroundStatusBySession = atom<Record<string, ComposerStatusItem[]>>({})
+// When each list was written: the freshness the live-work roster compares against.
+const backgroundWrittenAt = new WeakMap<readonly ComposerStatusItem[], number>()
// Stored session ids that have at least one RUNNING background process. The
// sidebar row reads this for a hollow dot — distinct from the filled dot of an
@@ -70,28 +72,27 @@ export const $backgroundRunningSessionIds = computed(
[$backgroundStatusBySession, $sessionStates, $sessions, $liveWorkRoster],
(bg, states, sessions, roster) => {
const ids = new Set<string>()
- const covered = new Set<string>()
+ const eventFedAt = new Map<string, number>()
for (const [runtimeId, items] of Object.entries(bg)) {
if (items.length === 0) {
continue
}
- const running = items.some(i => i.state === 'running')
-
// Same fresh-chat fallback as the working/attention projections: before a
// conversation is persisted its runtime id is the id surfaces key on.
- for (const alias of lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)) {
- covered.add(alias)
+ const aliases = lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)
+ noteEventFed(eventFedAt, aliases, backgroundWrittenAt.get(items) ?? -Infinity)
- if (running) {
+ if (items.some(i => i.state === 'running')) {
+ for (const alias of aliases) {
ids.add(alias)
}
}
}
- // Rows no mounted tile feeds (off screen, or every row after a reload).
- for (const alias of rosterLiveIds(roster, 'background', covered, sessions)) {
+ // Rows no current event feed speaks for (off screen, every row after a reload).
+ for (const alias of rosterLiveIds(roster, 'background', eventFedAt, sessions)) {
ids.add(alias)
}
@@ -293,6 +294,7 @@ const writeBackground = (sid: string, items: ComposerStatusItem[]) => {
if (items.length > 0) {
next[sid] = items
+ backgroundWrittenAt.set(items, Date.now())
} else {
delete next[sid]
}
diff --git a/apps/desktop/src/store/gateway-shared-route.ts b/apps/desktop/src/store/gateway-shared-route.ts
new file mode 100644
index 00000000000..f27535612af
--- /dev/null
+++ b/apps/desktop/src/store/gateway-shared-route.ts
@@ -0,0 +1,51 @@
+import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'
+
+// True when `profile`'s backend route resolves to the SHARED primary backend
+// (global-remote case 3 in resolveProfileBackendRoute). Both shared-primary and
+// pooled descriptors carry `profile` so WebSocket URL minting targets the right
+// profile. `sharedPrimary` is the explicit discriminator; treating every tagged
+// descriptor as shared strands local/own-remote pooled profiles on the default
+// socket. Dialing a second socket at the shared descriptor is wrong — over SSH
+// the second dial fails (tunnel/token are per-backend) and the closed socket
+// poisons the active gateway with "not connected" even though the primary is
+// open right next to it.
+export async function sharedPrimaryRoute(profile: string): Promise<boolean> {
+ const desktop = window.hermesDesktop
+
+ if (!desktop) {
+ return false
+ }
+
+ try {
+ // Unbounded IPC round-trip into main (#93454) — a wedge here must reject
+ // like any other failure, not hang the route decision forever, since
+ // every caller (gatewayForProfile → requestGatewayForProfile/Agent) awaits
+ // this before it can fall back to dialing a secondary.
+ const conn = await withTimeout(
+ desktop.getConnection(profile),
+ RECONNECT_ATTEMPT_TIMEOUT_MS,
+ `Timed out resolving the shared-primary route for profile "${profile}"`
+ )
+
+ return Boolean(conn && typeof conn === 'object' && (conn as { sharedPrimary?: boolean }).sharedPrimary === true)
+ } catch {
+ return false
+ }
+}
+
+// Scopes whose last route resolution rode the primary socket (shared primary /
+// shared remote). A HINT for passive readers only (gateway.ts gatewayRouteState);
+// requests still resolve the route per call.
+const primaryRiders = new Set<string>()
+
+export function notePrimaryRider(scope: string, rides: boolean): boolean {
+ if (rides) {
+ primaryRiders.add(scope)
+ } else {
+ primaryRiders.delete(scope)
+ }
+
+ return rides
+}
+
+export const isPrimaryRider = (scope: string): boolean => primaryRiders.has(scope)
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index f6d269f10d6..397baed6b07 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -33,6 +33,7 @@ import {
import { $gatewayActivationEpoch } from '@/store/gateway-activation-epoch'
import { isMissingConnectionError, isMissingProfileError } from '@/store/gateway-dial-failures'
import { $primaryGatewayRoute } from '@/store/gateway-primary-route'
+import { isPrimaryRider, notePrimaryRider, sharedPrimaryRoute } from '@/store/gateway-shared-route'
import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'
import { markNativeNotifyBaseline } from '@/store/notify-baseline'
import { setConnection, setGatewayState } from '@/store/session'
@@ -316,6 +317,21 @@ export function activeGatewayProfileKey(): string {
return g.$activeProfile.get()
}
+/** Never dials or asks main: the socket a request for (connectionId, profile)
+ * would ride (`primary:<profile>` for the window primary and profiles known to
+ * share its backend, else the pooled scope) and whether it is open right now. */
+export function gatewayRouteState(connectionId: null | string, profile: string): { key: string; open: boolean } {
+ const key = normKey(profile)
+ const scope = registryBackendScopeKey(connectionId, key)
+ const onPrimary = key === g.primaryProfile && (scope === key || isPrimaryRegistryRoute(connectionId, key))
+
+ if (onPrimary || isPrimaryRider(scope)) {
+ return { key: `primary:${key}`, open: isOpen(g.primaryGateway) }
+ }
+
+ return { key: scope, open: isOpen(g.secondaries.get(scope)?.gateway ?? null) }
+}
+
export function configureGatewayRegistry(cfg: RegistryConfig): void {
g.config = cfg
}
@@ -1100,39 +1116,6 @@ function createSecondary(profile: string, connectionId: null | string = null): S
return entry
}
-// True when `profile`'s backend route resolves to the SHARED primary backend
-// (global-remote case 3 in resolveProfileBackendRoute). Both shared-primary and
-// pooled descriptors carry `profile` so WebSocket URL minting targets the right
-// profile. `sharedPrimary` is the explicit discriminator; treating every tagged
-// descriptor as shared strands local/own-remote pooled profiles on the default
-// socket. Dialing a second socket at the shared descriptor is wrong — over SSH
-// the second dial fails (tunnel/token are per-backend) and the closed socket
-// poisons the active gateway with "not connected" even though the primary is
-// open right next to it.
-export async function sharedPrimaryRoute(profile: string): Promise<boolean> {
- const desktop = window.hermesDesktop
-
- if (!desktop) {
- return false
- }
-
- try {
- // Unbounded IPC round-trip into main (#93454) — a wedge here must reject
- // like any other failure, not hang the route decision forever, since
- // every caller (gatewayForProfile → requestGatewayForProfile/Agent) awaits
- // this before it can fall back to dialing a secondary.
- const conn = await withTimeout(
- desktop.getConnection(profile),
- RECONNECT_ATTEMPT_TIMEOUT_MS,
- `Timed out resolving the shared-primary route for profile "${profile}"`
- )
-
- return Boolean(conn && typeof conn === 'object' && (conn as { sharedPrimary?: boolean }).sharedPrimary === true)
- } catch {
- return false
- }
-}
-
// Resolve and open `profile`'s socket WITHOUT changing the active gateway.
// Shared global-remote profiles intentionally return the primary socket plus a
// request-scope flag; dedicated local/remote profiles use their pooled socket.
@@ -1156,7 +1139,7 @@ async function gatewayForProfile(
throw new Error(`Backend for "${key}" is reconnecting; retry after it settles.`)
}
- if (await sharedPrimaryRoute(key)) {
+ if (notePrimaryRider(key, await sharedPrimaryRoute(key))) {
return { gateway: g.primaryGateway, key, release: noRelease, scopeProfile: true }
}
@@ -1294,7 +1277,7 @@ export async function requestGatewayForAgent<T>(
return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal, { spawnPriority })
}
- if (await ridesPrimaryBackend(connectionId, key)) {
+ if (notePrimaryRider(scope, await ridesPrimaryBackend(connectionId, key))) {
traceAgentRoute(scope, 'primary-shared')
return requestOnPrimaryGateway<T>(method, { ...params, profile: key }, timeoutMs, signal)
diff --git a/apps/desktop/src/store/live-work-roster.test.ts b/apps/desktop/src/store/live-work-roster.test.ts
index 32d46e4c8c7..8ed30368057 100644
--- a/apps/desktop/src/store/live-work-roster.test.ts
+++ b/apps/desktop/src/store/live-work-roster.test.ts
@@ -1,14 +1,17 @@
import { afterEach, describe, expect, it } from 'vitest'
+import { $backgroundRunningSessionIds, $backgroundStatusBySession } from './composer-status'
import { $liveWorkRoster, setLiveWorkRosterSource } from './live-work-roster'
import { $delegatingSessionIds } from './session-dot-state'
import { $subagentsBySession, type SubagentProgress } from './subagents'
-const child = (status: SubagentProgress['status']) => ({ id: 'c1', index: 0, status }) as unknown as SubagentProgress
+const child = (status: SubagentProgress['status'], updatedAt: number) =>
+ ({ id: 'c1', index: 0, status, updatedAt }) as unknown as SubagentProgress
afterEach(() => {
$liveWorkRoster.set({})
$subagentsBySession.set({})
+ $backgroundStatusBySession.set({})
})
describe('backend roster feeds rows no mounted tile speaks for', () => {
@@ -18,10 +21,24 @@ describe('backend roster feeds rows no mounted tile speaks for', () => {
expect($delegatingSessionIds.get()).toContain('off-screen')
})
- it('keeps a live event-fed entry authoritative over a stale roster count', () => {
- setLiveWorkRosterSource('ambient', [{ session_id: 'open-pane', subagents: 1, background: 0 }])
- $subagentsBySession.set({ 'open-pane': [child('completed')] })
+ it('keeps an event-fed entry newer than the roster read authoritative', () => {
+ setLiveWorkRosterSource('ambient', [{ session_id: 'open-pane', subagents: 1, background: 0 }], 1_000)
+ $subagentsBySession.set({ 'open-pane': [child('completed', 2_000)] })
expect($delegatingSessionIds.get()).not.toContain('open-pane')
})
+
+ it('never lets retained child history hide work a newer roster read saw', () => {
+ $subagentsBySession.set({ 'old-pane': [child('completed', 1_000)] })
+ setLiveWorkRosterSource('ambient', [{ session_id: 'old-pane', subagents: 1, background: 0 }], 2_000)
+
+ expect($delegatingSessionIds.get()).toContain('old-pane')
+ })
+
+ it('never lets a retained background list hide a process a newer roster read saw', () => {
+ $backgroundStatusBySession.set({ 'old-pane': [{ id: 'p1', state: 'done', title: 'sleep', type: 'background' }] })
+ setLiveWorkRosterSource('ambient', [{ session_id: 'old-pane', subagents: 0, background: 1 }])
+
+ expect($backgroundRunningSessionIds.get()).toContain('old-pane')
+ })
})
diff --git a/apps/desktop/src/store/live-work-roster.ts b/apps/desktop/src/store/live-work-roster.ts
index 12aee2c92d2..301887651bd 100644
--- a/apps/desktop/src/store/live-work-roster.ts
+++ b/apps/desktop/src/store/live-work-roster.ts
@@ -10,18 +10,24 @@ import { lineageAliases } from './session'
// screen, and every row right after a reload or socket reconnect, read idle
// while children ran. Keyed by STORED session id (the backend reports the
// durable conversation id), one bucket per backend source so a failing source
-// never wipes another's rows.
+// never wipes another's rows. Each bucket carries the time its read was SENT,
+// so an event-fed entry is authoritative only when it is newer than that read.
export interface LiveWorkCounts {
background: number
subagents: number
}
-export type LiveWorkRoster = Record<string, Record<string, LiveWorkCounts>>
+export interface LiveWorkBucket {
+ at: number
+ sessions: Record<string, LiveWorkCounts>
+}
+
+export type LiveWorkRoster = Record<string, LiveWorkBucket>
export const $liveWorkRoster = atom<LiveWorkRoster>({})
-export function setLiveWorkRosterSource(source: string, entries: readonly unknown[] | null) {
+export function setLiveWorkRosterSource(source: string, entries: readonly unknown[] | null, at = Date.now()) {
const current = $liveWorkRoster.get()
if (!entries) {
@@ -52,21 +58,24 @@ export function setLiveWorkRosterSource(source: string, entries: readonly unknow
bucket[sid] = { background: Number(row.background) || 0, subagents: Number(row.subagents) || 0 }
}
- $liveWorkRoster.set({ ...current, [source]: bucket })
+ $liveWorkRoster.set({ ...current, [source]: { at, sessions: bucket } })
}
-/** Stored ids (all lineage aliases) the roster says have `kind` running,
- * minus conversations a live, event-fed entry already speaks for: those
- * entries carry richer per-child state and stay authoritative. */
+/** Stored ids (all lineage aliases) the roster says have `kind` running.
+ * `eventFedAt` maps each alias an event-fed entry speaks for to when that
+ * entry last heard from the backend: an entry NEWER than the roster read stays
+ * authoritative (a child that finished after the read was sent), while an older
+ * one (retained history from a pane that stopped listening) never hides work
+ * the roster saw start since. */
export function rosterLiveIds(
roster: LiveWorkRoster,
kind: keyof LiveWorkCounts,
- liveCovered: ReadonlySet<string>,
+ eventFedAt: ReadonlyMap<string, number>,
sessions: Parameters<typeof lineageAliases>[1]
): string[] {
const ids = new Set<string>()
- for (const bucket of Object.values(roster)) {
+ for (const { at, sessions: bucket } of Object.values(roster)) {
for (const [storedId, counts] of Object.entries(bucket)) {
if (counts[kind] <= 0) {
continue
@@ -74,7 +83,7 @@ export function rosterLiveIds(
const aliases = lineageAliases(storedId, sessions)
- if (aliases.some(alias => liveCovered.has(alias))) {
+ if (aliases.some(alias => (eventFedAt.get(alias) ?? -Infinity) >= at)) {
continue
}
@@ -86,3 +95,14 @@ export function rosterLiveIds(
return [...ids]
}
+
+/** Record `at` for every alias, keeping the freshest stamp per alias. */
+export function noteEventFed(eventFedAt: Map<string, number>, aliases: readonly string[], at: number) {
+ for (const alias of aliases) {
+ eventFedAt.set(alias, Math.max(at, eventFedAt.get(alias) ?? -Infinity))
+ }
+}
+
+/** True when the source's last read reported any live work. */
+export const rosterSourceHasWork = (roster: LiveWorkRoster, source: string) =>
+ Object.values(roster[source]?.sessions ?? {}).some(c => c.subagents > 0 || c.background > 0)
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index cd34d5a0bd6..980c20715bc 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -28,7 +28,7 @@ import { computed } from 'nanostores'
import { stableArray, stableRecord } from '@/lib/stable-array'
import { $backgroundRunningSessionIds } from './composer-status'
-import { $liveWorkRoster, rosterLiveIds } from './live-work-roster'
+import { $liveWorkRoster, noteEventFed, rosterLiveIds } from './live-work-roster'
import { $pausedQueueSessionIds } from './owner-queue-reconcile'
import { $messagingSessions, $sessions, $unreadFinishedSessionIds, lineageAliases } from './session'
import {
@@ -54,7 +54,7 @@ export const $delegatingSessionIds = computed(
[$subagentsBySession, $sessionStates, $sessions, $liveWorkRoster],
(bySession, states, sessions, roster) => {
const ids = new Set<string>()
- const covered = new Set<string>()
+ const eventFedAt = new Map<string, number>()
for (const [runtimeId, items] of Object.entries(bySession)) {
if (items.length === 0) {
@@ -62,19 +62,17 @@ export const $delegatingSessionIds = computed(
}
const aliases = lineageAliases(states[runtimeId]?.storedSessionId ?? runtimeId, sessions)
- const active = activeSubagentCount(items) > 0
+ noteEventFed(eventFedAt, aliases, Math.max(...items.map(item => item.updatedAt || 0)))
- for (const alias of aliases) {
- covered.add(alias)
-
- if (active) {
+ if (activeSubagentCount(items) > 0) {
+ for (const alias of aliases) {
ids.add(alias)
}
}
}
- // Rows no mounted tile feeds (off screen, or every row after a reload).
- for (const alias of rosterLiveIds(roster, 'subagents', covered, sessions)) {
+ // Rows no current event feed speaks for (off screen, every row after a reload).
+ for (const alias of rosterLiveIds(roster, 'subagents', eventFedAt, sessions)) {
ids.add(alias)
}
diff --git a/tests/tui_gateway/test_subagent_roster.py b/tests/tui_gateway/test_subagent_roster.py
index c3820451725..4787d04e3ed 100644
--- a/tests/tui_gateway/test_subagent_roster.py
+++ b/tests/tui_gateway/test_subagent_roster.py
@@ -44,3 +44,20 @@ def test_roster_omits_conversations_stored_in_another_profile(roster):
active["c1"] = {"subagent_id": "c1", "depth": 0, "owner_agent_session_id": "other-profile-sid"}
assert json.dumps(call()) == "{}"
+
+
+def test_roster_resolves_a_background_process_route_key_to_its_stored_conversation(roster, monkeypatch):
+ """On the gateway path a ``terminal(background=true)`` process carries the conversation's ROUTE
+ (``agent:main:local:dm:...``) as its ``session_key``, not the stored id; the roster still reports it
+ under the stored conversation that route belongs to, so a background-only row lights after a reload."""
+ from tools.process_registry import ProcessSession, process_registry
+ from tui_gateway import server
+
+ _, call = roster
+ route = "agent:main:local:dm:desktop-chat-1"
+ server._get_db().create_session("local-abc123", source="local", session_key=route)
+ proc = ProcessSession(id="proc_route", command="sleep 90", session_key=route)
+ monkeypatch.setattr(process_registry, "list_sessions", lambda **_: [{"session_id": proc.id}])
+ monkeypatch.setattr(process_registry, "get", lambda pid: proc if pid == proc.id else None)
+
+ assert call() == {"local-abc123": {"session_id": "local-abc123", "subagents": 0, "background": 1}}
diff --git a/tui_gateway/methods_subagents.py b/tui_gateway/methods_subagents.py
index f9544f54aba..da153478d5e 100644
--- a/tui_gateway/methods_subagents.py
+++ b/tui_gateway/methods_subagents.py
@@ -63,25 +63,38 @@ def _(rid, params):
})
-def _live_work_by_conversation():
- """{durable conversation id: {"subagents": n, "background": m}} over the whole process: top-level live
- children keyed by ``owner_agent_session_id`` (the same durable spine completion delivery routes by), running
- background processes by their registry ``session_key``."""
+def _live_work_owners():
+ """``(kind, owner candidates)`` for every live top-level child and running background process in this
+ process. A child names its durable conversation (``owner_agent_session_id``, the spine completion delivery
+ routes by). A process names the conversation that spawned it (``parent_session_id``, from
+ ``HERMES_SESSION_ID``) and its routing ``session_key``, which on the gateway path is a route
+ (``agent:main:local:dm:...``), never a stored id."""
from tools.delegate_tool_registry import _active_subagents, _active_subagents_lock
from tools.process_registry import process_registry
- counts = {}
with _active_subagents_lock:
- owners = [str(r.get("owner_agent_session_id") or "") for r in _active_subagents.values()
- if not r.get("depth")]
- for sid in filter(None, owners):
- counts.setdefault(sid, {"subagents": 0, "background": 0})["subagents"] += 1
+ 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"))
- key = str(getattr(proc, "session_key", "") or "") if proc is not None else ""
- if key and not getattr(proc, "exited", True):
- counts.setdefault(key, {"subagents": 0, "background": 0})["background"] += 1
- return counts
+ if proc is not None and not getattr(proc, "exited", True):
+ owners.append(("background", (str(getattr(proc, "parent_session_id", "") or ""),
+ str(getattr(proc, "session_key", "") or ""))))
+ 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 ""
@method("subagent.roster")
@@ -91,8 +104,8 @@ def _(rid, params):
for a row that is not open or for any row right after a renderer reload; this read needs neither. One
process hosts several profiles, so only conversations stored in the requested profile's state.db are
returned — a caller never learns another profile's session ids."""
- counts = _live_work_by_conversation()
- if not counts:
+ owners = _live_work_owners()
+ if not owners:
return _ok(rid, {"sessions": []})
scope = params if isinstance(params, dict) else {}
if not str(scope.get("profile") or "").strip():
@@ -100,11 +113,14 @@ def _(rid, params):
from tui_gateway.ws_legacy_fallback import connection_profile_home
if home := connection_profile_home():
scope = {"profile": Path(home).name}
+ counts = {}
with _profile_db(scope) as db:
if db is None:
return _ok(rid, {"sessions": []})
- owned = [sid for sid in counts if db.get_session(sid)]
- return _ok(rid, {"sessions": [{"session_id": sid, **counts[sid]} for sid in owned]})
+ for kind, candidates in owners:
+ if sid := _stored_owner(db, candidates):
+ counts.setdefault(sid, {"subagents": 0, "background": 0})[kind] += 1
+ return _ok(rid, {"sessions": [{"session_id": sid, **c} for sid, c in counts.items()]})
def _failed_delegations(session_id, owner):