Skip to content

The agent that grows with you

fix: address pr comments pt1

Maciej Lisiewski40158fa61653
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index e898159a693..62fd6a37198 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -1189,18 +1189,15 @@ def get_cached_context_length(model: str, base_url: str, *, bedrock_confirmed: b
return length
-@locked_context_cache
def _invalidate_cached_context_length(model: str, base_url: str) -> None:
"""Drop a stale entry and its probe cooldown using the persisted cache URL.
Bedrock callers without a runtime endpoint must pass ``bedrock://``, as
the resolver does; a blank URL addresses the distinct generic cache key.
+ In-process caches are dropped unconditionally; only the file update takes the cache lock.
"""
+ from agent.model_metadata_cache import drop_context_cache_rows
key = _context_cache_key(model, base_url)
- document = _load_context_cache_document()
- cache = document.get("context_lengths") or {}
- confirmed = document.get("bedrock_confirmed_v1") or {}
- confirmed = confirmed if isinstance(confirmed, dict) else {}
# Also drop the in-memory TTL probe entries, or the next resolution inside the TTL window reuses the stale value.
bare, stripped = _strip_provider_prefix(model), (base_url or "").rstrip("/")
_LOCAL_CTX_PROBE_CACHE.pop((bare, stripped), None)
@@ -1212,16 +1209,7 @@ def _invalidate_cached_context_length(model: str, base_url: str) -> None:
if memo_key[:2] == (hermes_home_key(), stripped) and memo_key[2] in (model, bare):
_BEDROCK_PROBE_FAILURE_CACHE.pop(memo_key, None)
# Every key shape get_cached_context_length consults.
- stale_keys = {key, f"{model}@{base_url}", f"{key}/"}
- if not any(k in cache or k in confirmed for k in stale_keys):
- return
- for k in stale_keys:
- cache.pop(k, None)
- confirmed.pop(k, None)
- try:
- _write_context_cache(cache, confirmed)
- except Exception as e:
- logger.debug("Failed to invalidate context length cache entry %s: %s", key, e)
+ drop_context_cache_rows({key, f"{model}@{base_url}", f"{key}/"}, key)
def get_next_probe_tier(current_length: int) -> Optional[int]:
diff --git a/agent/model_metadata_cache.py b/agent/model_metadata_cache.py
index c3aa390960c..fa73711c3cc 100644
--- a/agent/model_metadata_cache.py
+++ b/agent/model_metadata_cache.py
@@ -49,3 +49,24 @@ def locked_context_cache(fn):
return None
return fn(*args, **kwargs)
return wrapper
+
+
+@locked_context_cache
+def drop_context_cache_rows(stale_keys: set[str], label: str) -> None:
+ """Remove every key shape of one cached entry (and its Bedrock provenance) under the cache lock.
+
+ Only the file update is locked: callers evict their in-process probe caches unconditionally."""
+ from agent.model_metadata import _load_context_cache_document # facade seam: tests patch it there
+ document = _load_context_cache_document()
+ cache = document.get("context_lengths") or {}
+ confirmed = document.get("bedrock_confirmed_v1") or {}
+ confirmed = confirmed if isinstance(confirmed, dict) else {}
+ if not any(k in cache or k in confirmed for k in stale_keys):
+ return
+ for k in stale_keys:
+ cache.pop(k, None)
+ confirmed.pop(k, None)
+ try:
+ _write_context_cache(cache, confirmed)
+ except Exception:
+ logger.debug("Failed to invalidate context length cache entry %s", label, exc_info=True)
diff --git a/agent/session_activity.py b/agent/session_activity.py
index 1a3ec55a766..5e26a4b7c8a 100644
--- a/agent/session_activity.py
+++ b/agent/session_activity.py
@@ -136,6 +136,11 @@ class AwakeIdleMeter:
"""Return *idle_s* minus the sleep observed since the agent's last activity."""
wall, mono = time.time(), time.monotonic()
slept_s = max(0.0, (wall - self._wall) - (mono - self._mono))
+ # Activity since the previous sample (it is younger than the sampling interval) makes all
+ # earlier credit predate it. A rarely sampled meter (stale-agent eviction samples only
+ # when a message arrives) would otherwise keep charging old sleep against new idle time.
+ if idle_s < wall - self._wall:
+ self._asleep_s = 0.0
self._asleep_s += slept_s
self._wall, self._mono = wall, mono
# The idle sample may predate sleep observed by these clock reads. Keep that new
diff --git a/apps/desktop/src/app/messaging/index.test.tsx b/apps/desktop/src/app/messaging/index.test.tsx
index f46b712cf57..5ee615f9d0b 100644
--- a/apps/desktop/src/app/messaging/index.test.tsx
+++ b/apps/desktop/src/app/messaging/index.test.tsx
@@ -58,7 +58,7 @@ vi.mock('@/store/gateway', () => ({
openGatewayForProfile: vi.fn(async () => undefined)
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
vi.mock('@/lib/external-link', () => ({
openExternalLink: (href: string) => openExternalLink(href)
diff --git a/apps/desktop/src/app/settings/profile-scope.test.tsx b/apps/desktop/src/app/settings/profile-scope.test.tsx
index 6a4680660c1..ce247ebbd1e 100644
--- a/apps/desktop/src/app/settings/profile-scope.test.tsx
+++ b/apps/desktop/src/app/settings/profile-scope.test.tsx
@@ -18,7 +18,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { $activeGatewayProfile, $profiles } = await import('@/store/profile')
const { $settingsScopeOverride } = await import('@/store/settings-scope')
diff --git a/apps/desktop/src/app/starmap/index.tsx b/apps/desktop/src/app/starmap/index.tsx
index 28d825ac850..b4c33c4ae5f 100644
--- a/apps/desktop/src/app/starmap/index.tsx
+++ b/apps/desktop/src/app/starmap/index.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from 'react'
import { PageLoader } from '@/components/page-loader'
import { useI18n } from '@/i18n'
-import { $starmapError, $starmapGraph, $starmapLoading, loadStarmapGraph } from '@/store/starmap'
+import { $starmapError, $starmapGraph, $starmapLoading, watchStarmapGraph } from '@/store/starmap'
import type { StarmapGraph } from '@/types/hermes'
import { Panel, PanelEmpty } from '../overlays/panel'
@@ -26,9 +26,8 @@ export function StarmapView({ onClose }: { onClose: () => void }) {
// whenever a fresh profile graph loads in.
const [imported, setImported] = useState<StarmapGraph | null>(null)
- useEffect(() => {
- void loadStarmapGraph()
- }, [])
+ // Loads on open and reloads after a profile/gateway switch while the view stays open.
+ useEffect(() => watchStarmapGraph(), [])
// Drop a stale import when the underlying profile graph changes out from under it.
useEffect(() => {
diff --git a/apps/desktop/src/plugin-socket-scope.test.ts b/apps/desktop/src/plugin-socket-scope.test.ts
index e78eef2cd7c..c377b2de8a3 100644
--- a/apps/desktop/src/plugin-socket-scope.test.ts
+++ b/apps/desktop/src/plugin-socket-scope.test.ts
@@ -31,7 +31,7 @@ vi.mock('@/hermes', async importOriginal => {
}
})
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { pluginSocket, setApiRequestConnection, setApiRequestProfile } = await import('@/hermes')
const { closeSecondaryGateways, configureGatewayRegistry, setPrimaryGateway } = await import('@/store/gateway')
diff --git a/apps/desktop/src/store/gateway-switch.test.ts b/apps/desktop/src/store/gateway-switch.test.ts
index b6cf8a18230..ed2229f8385 100644
--- a/apps/desktop/src/store/gateway-switch.test.ts
+++ b/apps/desktop/src/store/gateway-switch.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { $apiRequestScope, setApiRequestConnection } from '@/api/client'
import { $sessionsLimit, resetSessionsLimit, SIDEBAR_SESSIONS_PAGE_SIZE } from '@/store/layout'
import { $projectScope, ALL_PROJECTS } from '@/store/project-scope'
import {
@@ -23,6 +24,7 @@ import {
setSessionsLoading
} from '@/store/session'
import { $stalledSessionIds } from '@/store/session-states'
+import { $starmapGraph, watchStarmapGraph } from '@/store/starmap'
import { $retainedTodosBySession, restoreSessionTodosFromSnapshot } from '@/store/todos'
import {
$transcriptTailBySessionId,
@@ -30,6 +32,7 @@ import {
recordTranscriptTail,
transcriptTailState
} from '@/store/transcript-tail'
+import type { StarmapGraph } from '@/types/hermes'
import {
$gatewaySwitching,
@@ -40,6 +43,18 @@ import {
wipeSessionListsForGatewaySwitch
} from './gateway-switch'
+// Each star map fetch records the connection requests route to when it is issued.
+const { starmapFetchScopes } = vi.hoisted(() => ({ starmapFetchScopes: [] as Array<null | string> }))
+
+vi.mock(import('@/hermes'), async importOriginal => ({
+ ...(await importOriginal()),
+ getStarmapGraph: () => {
+ starmapFetchScopes.push($apiRequestScope.get().connectionId)
+
+ return new Promise(() => undefined)
+ }
+}))
+
vi.mock('@/lib/query-client', () => ({
invalidateProfileScopedQueries: vi.fn()
}))
@@ -149,6 +164,42 @@ describe('wipeSessionListsForGatewaySwitch', () => {
expect(invalidateProfileListFetches).toHaveBeenCalled()
})
+
+ it("drops the outgoing backend's star map so the next open (or an open view) scans the new one", () => {
+ $starmapGraph.set({ edges: [], nodes: [{ id: 'old-backend-skill' }] } as unknown as StarmapGraph)
+
+ wipeSessionListsForGatewaySwitch()
+
+ expect($starmapGraph.get()).toBeNull()
+ })
+})
+
+describe('star map across a connection switch', () => {
+ afterEach(() => {
+ $gatewaySwitching.set(false)
+ setApiRequestConnection(null)
+ })
+
+ // A -> B with the same profile name: no profile change follows to reload it, so the switch
+ // itself must, and only once requests route to B.
+ it('reloads an open star map from the new connection only after the switch ends', async () => {
+ setApiRequestConnection('conn-a')
+ const unwatch = watchStarmapGraph()
+
+ try {
+ await vi.waitFor(() => expect(starmapFetchScopes).toEqual(['conn-a']))
+
+ const token = beginGatewaySwitch()
+ expect(starmapFetchScopes).toEqual(['conn-a'])
+
+ setApiRequestConnection('conn-b')
+ endGatewaySwitch(token)
+
+ expect(starmapFetchScopes).toEqual(['conn-a', 'conn-b'])
+ } finally {
+ unwatch()
+ }
+ })
})
describe('beginGatewaySwitch / endGatewaySwitch — the shared switch commit point (#93937)', () => {
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index c4d73d07535..fa62a6cda71 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -33,6 +33,7 @@ import {
import { clearAllSessionControl } from '@/store/session-control'
import { resetSessionPinMirror } from '@/store/session-pin-sync'
import { clearAllSessionStates } from '@/store/session-states'
+import { reloadOpenStarmapGraph, resetStarmapGraph } from '@/store/starmap'
import { clearAllSessionTodos } from '@/store/todos'
import { clearTranscriptTailPaging } from '@/store/transcript-tail'
import { clearTranscriptTails } from '@/store/transcript-tail-cache'
@@ -138,6 +139,9 @@ export function endGatewaySwitch(token?: GatewaySwitchToken): void {
}
$gatewaySwitching.set(false)
+ // The wipe reset the star map while the outgoing source was still active; requests now route
+ // to whichever source the switch left active, so an open view reloads against it.
+ reloadOpenStarmapGraph()
}
/**
@@ -213,6 +217,9 @@ export function wipeSessionListsForGatewaySwitch(): void {
setSessionProfilesUsage({})
setCronSessions([])
invalidateCronJobsRequests()
+ // The star map is a scan of the outgoing backend's skills and memory; an open view reloads it
+ // when the switch ends (endGatewaySwitch), not here: the outgoing source is still active.
+ resetStarmapGraph()
setCronJobs([])
setMessagingSessions([])
setMessagingListServer(null)
diff --git a/apps/desktop/src/store/kanban-connection-scope.test.ts b/apps/desktop/src/store/kanban-connection-scope.test.ts
index 772d22431a2..3b2fd04c751 100644
--- a/apps/desktop/src/store/kanban-connection-scope.test.ts
+++ b/apps/desktop/src/store/kanban-connection-scope.test.ts
@@ -30,7 +30,7 @@ vi.mock('@/hermes', async importOriginal => {
}
}
})
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { getApiRequestConnection, setApiRequestConnection, setApiRequestProfile } = await import('@/api/client')
const { queryClient } = await import('@/lib/query-client')
diff --git a/apps/desktop/src/store/profile-agent-activation.test.ts b/apps/desktop/src/store/profile-agent-activation.test.ts
index 426db8e39b5..113cd7336b3 100644
--- a/apps/desktop/src/store/profile-agent-activation.test.ts
+++ b/apps/desktop/src/store/profile-agent-activation.test.ts
@@ -42,7 +42,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph }))
const { $activeGatewayProfile, ensureGatewayAgent, ensureGatewayProfile } = await import('./profile')
diff --git a/apps/desktop/src/store/profile-cache.test.ts b/apps/desktop/src/store/profile-cache.test.ts
index 2e46a39c8ed..19b62ab1626 100644
--- a/apps/desktop/src/store/profile-cache.test.ts
+++ b/apps/desktop/src/store/profile-cache.test.ts
@@ -8,7 +8,7 @@ import type { ProfileInfo } from '@/types/hermes'
vi.mock('@/store/gateway', () => ({ $gateway: atom(null) }))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { $profiles, $profilesByConnection, invalidateProfileListFetches, refreshActiveProfile, refreshProfiles } =
await import('./profile')
diff --git a/apps/desktop/src/store/profile-select-source.test.ts b/apps/desktop/src/store/profile-select-source.test.ts
index 2c223965a6a..d00e2e06fe9 100644
--- a/apps/desktop/src/store/profile-select-source.test.ts
+++ b/apps/desktop/src/store/profile-select-source.test.ts
@@ -31,7 +31,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph }))
const { $activeGatewayProfile, newSessionInProfile, selectProfile } = await import('./profile')
diff --git a/apps/desktop/src/store/profile-share.test.ts b/apps/desktop/src/store/profile-share.test.ts
index 985564e9342..f8c54d309a8 100644
--- a/apps/desktop/src/store/profile-share.test.ts
+++ b/apps/desktop/src/store/profile-share.test.ts
@@ -20,7 +20,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { applyDesktopOverlay, buildDesktopOverlay, exportProfileBundle } = await import('./profile-share')
const { $profileColors, setProfileColor } = await import('./profile')
diff --git a/apps/desktop/src/store/profile.test.ts b/apps/desktop/src/store/profile.test.ts
index 104b6b07273..cc320476c52 100644
--- a/apps/desktop/src/store/profile.test.ts
+++ b/apps/desktop/src/store/profile.test.ts
@@ -32,7 +32,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph }))
const {
$activeGatewayProfile,
diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.ts
index f034de3dcba..e43adff9f37 100644
--- a/apps/desktop/src/store/profile.ts
+++ b/apps/desktop/src/store/profile.ts
@@ -30,7 +30,7 @@ import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override
import { exitProjectScope } from '@/store/project-scope'
import { $connection, clearComposerSelectionOwner, setComposerSelectionOwner, setConnection } from '@/store/session'
import type { SessionOwnerRoute } from '@/store/session-request-router'
-import { resetStarmapGraph } from '@/store/starmap'
+import { reloadOpenStarmapGraph, resetStarmapGraph } from '@/store/starmap'
import type { ProfileInfo } from '@/types/hermes'
// Canonical key for a profile: trimmed, empty → "default". Used everywhere we
@@ -467,6 +467,8 @@ $activeGatewayProfile.subscribe(value => {
// every profile switch.
invalidateProfileScopedQueries()
resetStarmapGraph()
+ // setApiRequestProfile above already routes requests to the new profile.
+ reloadOpenStarmapGraph()
// /api/profiles now routes to a different backend: strand any in-flight
// profile-list fetch so the previous backend's late answer can't clobber
// the rail (the #85731 class — same guard as the connection-apply wipe).
diff --git a/apps/desktop/src/store/settings-scope.test.ts b/apps/desktop/src/store/settings-scope.test.ts
index 72682265d8e..8e21afdc1b1 100644
--- a/apps/desktop/src/store/settings-scope.test.ts
+++ b/apps/desktop/src/store/settings-scope.test.ts
@@ -16,7 +16,7 @@ vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn()
}))
vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))
-vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))
+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))
const { $activeGatewayProfile, $profiles } = await import('./profile')
diff --git a/apps/desktop/src/store/starmap.test.ts b/apps/desktop/src/store/starmap.test.ts
index 75520668368..20da9545321 100644
--- a/apps/desktop/src/store/starmap.test.ts
+++ b/apps/desktop/src/store/starmap.test.ts
@@ -13,8 +13,15 @@ vi.mock('@/hermes', () => ({
})
}))
-const { $starmapError, $starmapGraph, $starmapLoading, loadStarmapGraph, resetStarmapGraph } =
- await import('./starmap')
+const {
+ $starmapError,
+ $starmapGraph,
+ $starmapLoading,
+ loadStarmapGraph,
+ reloadOpenStarmapGraph,
+ resetStarmapGraph,
+ watchStarmapGraph
+} = await import('./starmap')
const graph = (id: string): StarmapGraph => ({ edges: [], nodes: [{ id }] }) as unknown as StarmapGraph
@@ -76,4 +83,66 @@ describe('loadStarmapGraph', () => {
expect(fetches).toHaveLength(1)
expect($starmapGraph.get()?.nodes.map(node => node.id)).toEqual(['cached-node'])
})
+
+ // Nothing else reloads after a profile or gateway switch: the view loads on mount only.
+ it('reloads an open star map after a reset strands its first load', async () => {
+ const unwatch = watchStarmapGraph()
+
+ try {
+ expect(fetches).toHaveLength(1)
+ resetStarmapGraph()
+ reloadOpenStarmapGraph()
+ expect(fetches).toHaveLength(2)
+
+ fetches[1].resolve(graph('current-node'))
+ fetches[0].resolve(graph('previous-node'))
+ await vi.waitFor(() => expect($starmapGraph.get()?.nodes.map(node => node.id)).toEqual(['current-node']))
+ expect($starmapLoading.get()).toBe(false)
+ } finally {
+ unwatch()
+ }
+ })
+
+ it('reloads an open star map that already showed the previous scope', async () => {
+ const unwatch = watchStarmapGraph()
+
+ try {
+ fetches[0].resolve(graph('previous-node'))
+ await vi.waitFor(() => expect($starmapGraph.get()).not.toBeNull())
+ resetStarmapGraph()
+ reloadOpenStarmapGraph()
+
+ expect($starmapGraph.get()).toBeNull()
+ expect(fetches).toHaveLength(2)
+ fetches[1].resolve(graph('current-node'))
+ await vi.waitFor(() => expect($starmapGraph.get()?.nodes.map(node => node.id)).toEqual(['current-node']))
+ } finally {
+ unwatch()
+ }
+ })
+
+ it('does not fetch on a reset while the star map is closed', () => {
+ const unwatch = watchStarmapGraph()
+ unwatch()
+ fetches.shift()?.resolve(graph('closed'))
+
+ resetStarmapGraph()
+ reloadOpenStarmapGraph()
+
+ expect(fetches).toHaveLength(0)
+ })
+
+ // A gateway switch resets before the new connection is active: a fetch started by the reset
+ // would ask the outgoing backend, and the reset's own epoch would accept that answer.
+ it('does not fetch from the reset itself, even while the star map is open', () => {
+ const unwatch = watchStarmapGraph()
+
+ try {
+ expect(fetches).toHaveLength(1)
+ resetStarmapGraph()
+ expect(fetches).toHaveLength(1)
+ } finally {
+ unwatch()
+ }
+ })
})
diff --git a/apps/desktop/src/store/starmap.ts b/apps/desktop/src/store/starmap.ts
index a7c08179487..55bbacb76d0 100644
--- a/apps/desktop/src/store/starmap.ts
+++ b/apps/desktop/src/store/starmap.ts
@@ -73,7 +73,9 @@ export function evictStarmapNode(id: string): () => void {
return () => $starmapGraph.set(prev)
}
-/** Drop the cache so the next open refetches against the now-active profile. */
+/** Drop the cache (and strand any in-flight load) so the next load scans the new scope. Does not
+ * reload: a gateway switch resets before the new connection is active; callers reload an open
+ * view once the new request scope is published (reloadOpenStarmapGraph). */
export function resetStarmapGraph(): void {
starmapEpoch += 1
inflight = null
@@ -82,3 +84,24 @@ export function resetStarmapGraph(): void {
// The stranded load no longer owns the spinner; a fresh load re-raises it.
$starmapLoading.set(false)
}
+
+let openStarmapViews = 0
+
+/** Reload a mounted Star Map view after a reset, once requests route to the new scope. A view
+ * loads on mount only, so nothing else would refetch it. */
+export function reloadOpenStarmapGraph(): void {
+ if (openStarmapViews > 0) {
+ void loadStarmapGraph()
+ }
+}
+
+/** Load the graph for a mounted Star Map view and keep it loaded across profile/gateway resets
+ * while the view stays open. Returns the unmount cleanup. */
+export function watchStarmapGraph(): () => void {
+ openStarmapViews += 1
+ void loadStarmapGraph()
+
+ return () => {
+ openStarmapViews -= 1
+ }
+}
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 28a16f9fe5e..5a49fdd5a0e 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -81,7 +81,14 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
# Rate-limit ALL pairing responses (code or rejection) so a burst of DMs doesn't spam.
if pairing_store._is_rate_limited(platform_name, source.user_id):
return
- code = pairing_store.generate_code(platform_name, source.user_id, source.user_name or "")
+ # Off the event loop: the store edit waits on a cross-process lock (dashboard, CLI).
+ try:
+ code = await asyncio.to_thread(
+ pairing_store.generate_code, platform_name, source.user_id, source.user_name or "",
+ )
+ except (OSError, TimeoutError):
+ logger.warning("Could not record a pairing code on %s", platform_name, exc_info=True)
+ return
adapter = self._delivery_adapter_for(source)
if code:
reply = pairing_code_reply(platform_name, code, pairing_profile_arg(pairing_store))
@@ -102,7 +109,12 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
pairing_store = self._pairing_store_for(source)
if pairing_store is None or pairing_store.has_recent_decline(platform_name, source.user_id):
return
- pairing_store.record_decline(platform_name, source.user_id)
+ # Off the event loop (the stamp waits on a cross-process lock); no stamp → no dedupe → silent.
+ try:
+ await asyncio.to_thread(pairing_store.record_decline, platform_name, source.user_id)
+ except (OSError, TimeoutError):
+ logger.warning("Could not record an unauthorized-DM decline on %s", platform_name, exc_info=True)
+ return
adapter = self._delivery_adapter_for(source)
if not adapter:
return
@@ -1843,11 +1855,12 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
return transcript, f'"{transcript}"'
async def _enrich_message_with_transcription(
- self, user_text: str, audio_paths: list[str]
+ self, user_text: str, audio_paths: list[str], clip_memo: Optional[dict] = None
) -> tuple[str, list[str]]:
"""Transcribe voice clips with the configured STT provider and prepend the transcripts →
``(enriched_text, successful_transcripts)``; the transcripts (input order; empty if every clip
- failed or STT is disabled) let callers echo them back before the agent loop."""
+ failed or STT is disabled) let callers echo them back before the agent loop. ``clip_memo``
+ (path → ``_transcribe_one_clip`` result) skips clips an earlier pass already transcribed."""
from gateway.run import _probe_audio_duration
audio_paths = list(dict.fromkeys(audio_paths))
if not getattr(self.config, "stt_enabled", True):
@@ -1871,10 +1884,15 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
successful_transcripts: list[str] = []
for path in audio_paths:
try:
- logger.debug("Transcribing user voice: %s", path)
- transcript, note = await self._transcribe_one_clip(
- path, transcribe_audio, transcribe_audio_local_fallback,
- )
+ if clip_memo is not None and path in clip_memo:
+ transcript, note = clip_memo[path]
+ else:
+ logger.debug("Transcribing user voice: %s", path)
+ transcript, note = await self._transcribe_one_clip(
+ path, transcribe_audio, transcribe_audio_local_fallback,
+ )
+ if clip_memo is not None:
+ clip_memo[path] = (transcript, note)
if transcript is not None:
successful_transcripts.append(transcript)
enriched_parts.append(note)
@@ -1906,13 +1924,21 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
if not audio_paths:
return user_text if user_text is not None else (getattr(event, "text", None) or None), []
text = user_text if user_text is not None else (getattr(event, "text", "") or "")
- enriched_text, successful_transcripts = await self._enrich_message_with_transcription(text, audio_paths)
+ # Per-clip results outlive the merged-event cache below (a merge drops only that), so every
+ # re-run — this loop's or the drain path's — transcribes just the newly merged clips.
+ clip_memo = getattr(event, "_gateway_pending_stt_clips", None)
+ if clip_memo is None:
+ clip_memo = {}
+ event._gateway_pending_stt_clips = clip_memo
+ enriched_text, successful_transcripts = await self._enrich_message_with_transcription(text, audio_paths, clip_memo)
# A voice note merged in during the await dropped a cache that did not exist yet; re-run on
# the merged media rather than publish a transcript that silently omits the new note.
while self._pending_event_audio_paths(event) != audio_paths:
audio_paths = self._pending_event_audio_paths(event)
text = user_text if user_text is not None else (getattr(event, "text", "") or "")
- enriched_text, successful_transcripts = await self._enrich_message_with_transcription(text, audio_paths)
+ enriched_text, successful_transcripts = await self._enrich_message_with_transcription(
+ text, audio_paths, clip_memo,
+ )
event._gateway_pending_stt_text = enriched_text
event._gateway_pending_stt_transcripts = list(successful_transcripts)
return enriched_text, successful_transcripts
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index a4ddeb23fb8..f4b3fad0252 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -110,16 +110,24 @@ def _head_sha(root: Path) -> str:
return head if _SHA.fullmatch(head) else ""
+def _publish_gateway_exit_code(code: int) -> None:
+ """Temp + rename with the stdlib only (the takeover runs before app imports are safe): the
+ gateway watcher polls ``.update_exit_code`` and reads an empty file as exit 1."""
+ from hermes_constants import get_hermes_home
+
+ marker = get_hermes_home() / ".update_exit_code"
+ temporary = marker.with_name(marker.name + ".tmp")
+ temporary.write_text(f"{code}\n", encoding="utf-8")
+ os.replace(temporary, marker)
+
+
def _record_failure(request: dict, result: Path, code: int, detail: str) -> None:
from hermes_cli import update_receipt
- from hermes_cli.runtime_state import _atomic_bytes
- from hermes_constants import get_hermes_home
update_receipt.record_step("historical_takeover", False, detail)
saved = update_receipt.finalize_pending_update_receipt(code, detail)
if request.get("gateway_mode"):
- # Atomic: the gateway watcher polls this file and reads an empty one as exit 1.
- _atomic_bytes(get_hermes_home() / ".update_exit_code", f"{code}\n".encode())
+ _publish_gateway_exit_code(code)
result.write_text(json.dumps({"receipt_handled": saved is not None, "resume_handled": False}), encoding="utf-8")
@@ -209,10 +217,7 @@ def _record_owed_finish(request: dict, result: Path, detail: str) -> None:
saved = update_receipt.finalize_pending_update_receipt(0, f"committed; finishing steps owed: {detail}")
if request.get("gateway_mode"):
with suppress(Exception): # health: allow BLE001 -- post-commit boundary: see above
- from hermes_cli.runtime_state import _atomic_bytes
- from hermes_constants import get_hermes_home
-
- _atomic_bytes(get_hermes_home() / ".update_exit_code", b"0\n")
+ _publish_gateway_exit_code(0)
with suppress(OSError): # no result file: the old updater keeps its own receipt and resumes
result.write_text(json.dumps({"receipt_handled": saved is not None, "resume_handled": False}),
encoding="utf-8")
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index d8910d415ae..2064f0d36d5 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -2169,16 +2169,23 @@ def clear_provider_models_cache(provider: Optional[str] = None) -> None:
# a stale signed-out probe past an explicit refresh.
global _copilot_acp_session_memo
_copilot_acp_session_memo = None
- if provider is None:
- path = _provider_models_cache_path()
- if path.exists():
- path.unlink()
- return
- cache = _load_provider_models_cache()
- normalized = _normalized_cache_slug(provider)
- if normalized in cache:
- del cache[normalized]
- _save_provider_models_cache(cache)
+ from hermes_cli.models_cache_lock import write_under_cache_lock
+ path = _provider_models_cache_path()
+
+ # Under the cache lock like every other writer: a locked writer that loaded the cache
+ # before this clear would otherwise save its snapshot after it, bringing the row back.
+ def clear_file() -> None:
+ if provider is None:
+ if path.exists():
+ path.unlink()
+ return
+ cache = _load_provider_models_cache()
+ normalized = _normalized_cache_slug(provider)
+ if normalized in cache:
+ del cache[normalized]
+ _save_provider_models_cache(cache)
+
+ write_under_cache_lock(path, clear_file)
except Exception:
pass
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 36f94e34b9c..5c7ea487613 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -39,9 +39,9 @@ _LIST_GATEWAY_UNITS = [
def _write_gateway_update_exit_code(ok: bool) -> None:
- from hermes_cli.runtime_state import _atomic_bytes
from hermes_cli.update_cmd import get_hermes_home
from hermes_cli.update_receipt import committed_success
+ from pm.filesystem import durable_write_bytes
# A run whose receipt already closed as a success is never reported failed (C3, review
# regression 3): the command boundary's catch-alls call this with False.
@@ -49,7 +49,7 @@ def _write_gateway_update_exit_code(ok: bool) -> None:
path = get_hermes_home() / ".update_exit_code"
with suppress(OSError):
# Atomic: the gateway watcher polls this file and reads an empty one as exit 1.
- _atomic_bytes(path, b"0" if ok else b"1")
+ durable_write_bytes(path, b"0" if ok else b"1")
def _fleet_restart_pending_marker_path() -> Path:
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index 41c09ee09c5..5f9b7b6a4aa 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -84,7 +84,8 @@ def _pairing_store(profile: Optional[str] = None):
@router.get("/api/pairing")
async def list_pairing(profile: Optional[str] = None):
store = _pairing_store(profile)
- return {"pending": store.list_pending(), "approved": store.list_approved()}
+ # Pairing edits wait on a cross-process lock (gateway, CLI): never on the server's event loop.
+ return {"pending": await asyncio.to_thread(store.list_pending), "approved": store.list_approved()}
@router.post("/api/pairing/approve")
@@ -99,7 +100,10 @@ async def approve_pairing(body: PairingApprove):
raise HTTPException(status_code=400, detail="platform and request_id or code are required")
by_request_id = bool(body.request_id) or store.looks_like_request_id(target)
- result = store.approve_request(platform, target) if by_request_id else store.approve_code(platform, target.upper())
+ if by_request_id:
+ result = await asyncio.to_thread(store.approve_request, platform, target)
+ else:
+ result = await asyncio.to_thread(store.approve_code, platform, target.upper())
if result:
return {"ok": True, "user": result}
# Lockout only gates the code path — a stale request id must not surface
@@ -119,14 +123,14 @@ async def revoke_pairing(body: PairingRevoke):
platform = (body.platform or "").lower().strip()
if not platform or not body.user_id:
raise HTTPException(status_code=400, detail="platform and user_id are required")
- if store.revoke(platform, body.user_id):
+ if await asyncio.to_thread(store.revoke, platform, body.user_id):
return {"ok": True}
raise HTTPException(status_code=404, detail=f"User {body.user_id} not found in approved list for {platform}.")
@router.post("/api/pairing/clear-pending")
async def clear_pending_pairing(profile: Optional[str] = None):
- return {"ok": True, "cleared": _pairing_store(profile).clear_pending()}
+ return {"ok": True, "cleared": await asyncio.to_thread(_pairing_store(profile).clear_pending)}
# --- Webhooks: same JSON store as the CLI (hermes_cli.webhook); the adapter
diff --git a/mcp_serve.py b/mcp_serve.py
index 31a852a43e0..1ced8c328d6 100644
--- a/mcp_serve.py
+++ b/mcp_serve.py
@@ -13,6 +13,7 @@ import json
import logging
import os
import re
+import sqlite3
import sys
import threading
import time
@@ -21,8 +22,6 @@ from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional
-from utils import file_signature, mtime_is_racy
-
logger = logging.getLogger("hermes.mcp_serve")
# mcp 2.0 removed `mcp.server.fastmcp`; `mcp.server.MCPServer` keeps the same
@@ -51,24 +50,43 @@ def _get_sessions_dir() -> Path:
return _hermes_home() / "sessions"
-def _read_state_db_sig() -> tuple:
- """Per-file stat signature of state.db and its WAL. In WAL mode a commit lands in
- state.db-wal and leaves state.db untouched until a checkpoint, so the main file alone misses it."""
- entries = []
- for name in ("state.db", "state.db-wal"):
- try:
- st = (_hermes_home() / name).stat()
- except OSError: # missing file included
- continue
- entries.append((name, *file_signature(st)))
- return tuple(entries)
+class _StateDbVersion:
+ """``PRAGMA data_version`` of state.db on a private read-only connection.
+ The value changes whenever ANY other connection commits — WAL commits included, same mtime
+ tick included — and stays put otherwise, for about a microsecond per read. A stat signature
+ of state.db (+ WAL) misses same-tick commits unless every recent mtime forces a full poll,
+ which keeps a busy gateway's bridge in permanent full-poll mode. ``read`` returns None when
+ the database is absent or unreadable; the caller then polls unconditionally."""
-def _settled_state_db_sig(sig: tuple) -> Optional[tuple]:
- """``sig``, or None (never equal to a read) while a file's mtime may still hide a same-tick commit."""
- if any(mtime_is_racy(entry[1]) for entry in sig):
- return None
- return sig
+ def __init__(self):
+ self._path: Optional[Path] = None
+ self._conn: Optional[sqlite3.Connection] = None
+
+ def read(self) -> Optional[int]:
+ path = _hermes_home() / "state.db"
+ try:
+ conn = self._conn
+ if conn is None or self._path != path:
+ self.close()
+ if not path.exists():
+ return None
+ # Polled from the bridge thread, baselined from the starter's. read_only_db_uri:
+ # a raw f"file:{path}" URI breaks on '#', '?' or '%xx' in HERMES_HOME.
+ from hermes_state_holders import read_only_db_uri
+ conn = sqlite3.connect(read_only_db_uri(path), uri=True, check_same_thread=False)
+ self._conn = conn
+ self._path = path
+ return conn.execute("PRAGMA data_version").fetchone()[0]
+ except sqlite3.Error:
+ self.close()
+ return None
+
+ def close(self) -> None:
+ if self._conn is not None:
+ self._conn.close()
+ self._conn = None
+ self._path = None
def _read_json(path: Path):
@@ -290,7 +308,8 @@ class EventBridge:
self._thread: Optional[threading.Thread] = None
self._last_poll_timestamps: dict[str, float] = {} # session_key -> unix timestamp
self._pending_approvals: dict[str, dict] = {} # populated from events
- self._state_db_sig: Optional[tuple] = () # skip polling work when state.db (+ WAL) is unchanged
+ self._db_version = _StateDbVersion()
+ self._state_db_version: Optional[int] = None # skip polling work when state.db is unchanged
self._cached_sessions_index: dict = {}
def start(self):
@@ -314,6 +333,7 @@ class EventBridge:
self._new_event.set()
if self._thread:
self._thread.join(timeout=5)
+ self._db_version.close()
logger.debug("EventBridge stopped")
def _matching(self, after_cursor: int, session_key: Optional[str], limit: int) -> list[dict]:
@@ -373,7 +393,7 @@ class EventBridge:
if not db:
return
try:
- self._state_db_sig = _settled_state_db_sig(_read_state_db_sig())
+ self._state_db_version = self._db_version.read()
try:
self._cached_sessions_index = _load_sessions_index()
except Exception:
@@ -410,17 +430,17 @@ class EventBridge:
def _poll_once(self, db):
"""Check for new messages across all sessions.
- One state.db (+ WAL) stat check gates all work, making 200ms polling nearly free.
+ One state.db ``data_version`` read gates all work, making 200ms polling nearly free.
The routing index lives in the same database as the messages, so a new
- conversation and its first message land under a single signature change (no
+ conversation and its first message land in a single commit (no
dual-file race that could drop brand-new conversations).
See #8925, #9006.
"""
- db_sig = _read_state_db_sig()
- if db_sig == self._state_db_sig:
+ version = self._db_version.read()
+ if version is not None and version == self._state_db_version:
return
- self._state_db_sig = _settled_state_db_sig(db_sig)
+ self._state_db_version = version
# Refresh the index on every change tick: one indexed query, never lags messages.
self._cached_sessions_index = _load_sessions_index()
diff --git a/tests/agent/test_model_metadata_cache.py b/tests/agent/test_model_metadata_cache.py
index 1ba8f55d716..cfd71a942a0 100644
--- a/tests/agent/test_model_metadata_cache.py
+++ b/tests/agent/test_model_metadata_cache.py
@@ -49,3 +49,30 @@ def test_concurrent_cache_writers_keep_each_others_entries(monkeypatch, first_wr
assert mm.get_cached_context_length("model-b", "https://b.example/v1") == 64_000
assert mm.get_cached_context_length("model-a", "https://a.example/v1") == expected_a
+
+
+def test_invalidation_evicts_in_process_probe_caches_when_the_lock_is_unavailable(monkeypatch):
+ """Only the file update needs the cross-process lock: a stale in-process probe result must be
+ dropped even when that lock cannot be taken, or the next resolution reuses it for its TTL."""
+ import contextlib
+
+ import hermes_cli.auth as auth_module
+ from hermes_constants import hermes_home_key
+
+ base_url = "https://a.example/v1"
+ mm._LOCAL_CTX_PROBE_CACHE[("model-a", base_url)] = (200_000, 0.0)
+ mm._LOCAL_CTX_PROBE_CACHE[("ollama_show", "model-a", base_url)] = (200_000, 0.0)
+ mm._BEDROCK_PROBE_FAILURE_CACHE[(hermes_home_key(), base_url, "model-a", "us-east-1")] = 0.0
+
+ @contextlib.contextmanager
+ def wedged_lock(*_args, **_kwargs):
+ raise TimeoutError("Timed out waiting for the context length cache lock")
+ yield
+
+ monkeypatch.setattr(auth_module, "_file_lock", wedged_lock)
+
+ mm._invalidate_cached_context_length("model-a", base_url)
+
+ assert ("model-a", base_url) not in mm._LOCAL_CTX_PROBE_CACHE
+ assert ("ollama_show", "model-a", base_url) not in mm._LOCAL_CTX_PROBE_CACHE
+ assert not [k for k in mm._BEDROCK_PROBE_FAILURE_CACHE if k[1:3] == (base_url, "model-a")]
diff --git a/tests/gateway/test_busy_session_ack.py b/tests/gateway/test_busy_session_ack.py
index 8b70fa20781..0841b77fe75 100644
--- a/tests/gateway/test_busy_session_ack.py
+++ b/tests/gateway/test_busy_session_ack.py
@@ -4,7 +4,7 @@ Verifies that users get an immediate status response instead of total silence
when the agent is working on a task. See PR fix for the @Lonely__MH report.
"""
import time
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, patch
import pytest
@@ -256,7 +256,7 @@ class TestBusySessionAck:
await runner._handle_active_session_busy_message(event, sk)
runner._enrich_message_with_transcription.assert_awaited_once_with(
- "", ["/tmp/follow-up.ogg"]
+ "", ["/tmp/follow-up.ogg"], ANY
)
agent.steer.assert_called_once()
injected = agent.steer.call_args.args[0]
diff --git a/tests/gateway/test_gateway_watchdog_host_sleep.py b/tests/gateway/test_gateway_watchdog_host_sleep.py
index b4055b1e057..907f6f5dec4 100644
--- a/tests/gateway/test_gateway_watchdog_host_sleep.py
+++ b/tests/gateway/test_gateway_watchdog_host_sleep.py
@@ -138,3 +138,28 @@ def test_stale_agent_eviction_ignores_host_sleep(clock, monkeypatch):
runner._hm_evict_idle_stale_agent("k")
assert evicted_at_read == [2]
+
+
+def test_stale_agent_eviction_drops_sleep_credit_once_the_agent_was_active_again(clock, monkeypatch):
+ """Eviction samples the meter only when a message arrives. Sleep before the agent's
+ post-resume activity must not keep discounting the idle time that followed that activity."""
+ monkeypatch.setenv("HERMES_AGENT_TIMEOUT", str(TIMEOUT_S))
+ turn = TurnState(ctx=TurnContext(), started_ts=clock.wall)
+
+ def work_after_resume_then_idle(c):
+ c.awake(10.0)
+ agent._origin = c.wall # the agent's last activity
+ c.awake(TIMEOUT_S)
+
+ agent = _ScriptedAgent(clock, [lambda c: c.sleep(SLEEP_S), work_after_resume_then_idle])
+ turn.agent = agent
+ runner = object.__new__(GatewayRunner)
+ runner._peek_session_state = lambda _key: SimpleNamespace(turn=turn)
+ evicted_at_read = []
+ runner._hm_evict_running_agent = lambda _key, _reason: evicted_at_read.append(agent.reads)
+
+ runner._hm_evict_idle_stale_agent("k")
+ assert evicted_at_read == []
+
+ runner._hm_evict_idle_stale_agent("k")
+ assert evicted_at_read == [2]
diff --git a/tests/gateway/test_pairing_reply_off_loop.py b/tests/gateway/test_pairing_reply_off_loop.py
new file mode 100644
index 00000000000..84b78243707
--- /dev/null
+++ b/tests/gateway/test_pairing_reply_off_loop.py
@@ -0,0 +1,123 @@
+"""Unauthorized-DM pairing replies must not block the gateway event loop on the pairing lock.
+
+``PairingStore`` edits hold a cross-process flock (the dashboard and the ``hermes pairing`` CLI
+mutate the same files). Waiting on it inline in an async handler stalls every chat the gateway
+serves for up to the lock timeout, then raises a ``TimeoutError`` the handler never handled.
+"""
+
+import asyncio
+import threading
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import Platform
+from gateway.pairing import PairingStore
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+from tests.lock_contention import watch_file_lock_contention
+
+
+def _runner(store, adapter):
+ runner = object.__new__(GatewayRunner)
+ runner._pairing_store_for = lambda _source: store
+ runner._delivery_adapter_for = lambda _source: adapter
+ runner.config = None
+ return runner
+
+
+def _source(user_id="stranger"):
+ return SessionSource(platform=Platform.TELEGRAM, chat_id="1", chat_type="dm", user_id=user_id)
+
+
+class _OtherProcessHoldsTheLock:
+ """Holds the pairing file lock from another thread until ``release()``; a backstop timer frees
+ it if the test dies first."""
+
+ def __init__(self):
+ self._locked = threading.Event()
+ self._release = threading.Event()
+ self._thread = threading.Thread(target=self._hold)
+ self._backstop = threading.Timer(30.0, self._release.set)
+
+ def _hold(self):
+ with PairingStore()._locked():
+ self._locked.set()
+ self._release.wait()
+
+ def __enter__(self):
+ self._thread.start()
+ assert self._locked.wait(5)
+ self._backstop.start()
+ return self
+
+ def release(self):
+ self._release.set()
+
+ def __exit__(self, *exc):
+ self._backstop.cancel()
+ self._release.set()
+ self._thread.join(5)
+
+
[email protected]("handler", ["_hm_offer_pairing_code", "_hm_send_unauthorized_decline"])
+async def test_waiting_on_the_pairing_lock_does_not_stall_the_event_loop(monkeypatch, handler):
+ """While the pairing edit waits on another process's lock, the handler is parked at an await
+ and this coroutine keeps running on the same loop. Inline, the handler's first step would
+ hold the loop until the lock wait timed out, and be done by the time this coroutine resumes."""
+ contended = watch_file_lock_contention(monkeypatch)
+ adapter = AsyncMock()
+ runner = _runner(PairingStore(), adapter)
+
+ with _OtherProcessHoldsTheLock() as holder:
+ task = asyncio.create_task(getattr(runner, handler)(_source()))
+ assert await asyncio.to_thread(contended.wait, 15), "the pairing edit never reached the lock"
+ assert not task.done(), "the handler ran the lock wait on the event loop"
+ holder.release()
+ await asyncio.wait_for(task, 15)
+
+ adapter.send.assert_awaited_once()
+
+
[email protected]("handler, method", [
+ ("_hm_offer_pairing_code", "generate_code"),
+ ("_hm_send_unauthorized_decline", "record_decline"),
+])
+async def test_a_pairing_lock_timeout_stays_silent(monkeypatch, handler, method):
+ store = PairingStore()
+
+ def timed_out(*_args, **_kwargs):
+ raise TimeoutError("Timed out waiting for the pairing store lock")
+
+ monkeypatch.setattr(store, method, timed_out)
+ adapter = AsyncMock()
+
+ await getattr(_runner(store, adapter), handler)(_source())
+
+ adapter.send.assert_not_awaited()
+
+
+def test_an_approval_check_does_not_wait_behind_an_edit_blocked_on_the_file_lock(monkeypatch):
+ """Message admission calls ``is_approved`` on the event loop. A pairing edit offloaded to a worker
+ that is still waiting for another process's file lock must not hold the store's thread lock
+ meanwhile, or that synchronous check stalls the loop for the whole wait."""
+ contended = watch_file_lock_contention(monkeypatch)
+ store = PairingStore()
+ checked = threading.Event()
+
+ with _OtherProcessHoldsTheLock():
+ worker = threading.Thread(target=store.generate_code, args=("telegram", "stranger"))
+ worker.start()
+ assert contended.wait(15), "the pairing edit never reached the lock"
+ checker = threading.Thread(target=lambda: store.is_approved("telegram", "someone-else") or checked.set())
+ checker.start()
+ # The holder never lets go before this answer: behind the edit's thread lock it never comes.
+ answered = checked.wait(10)
+ edit_still_waiting = worker.is_alive()
+ worker.join(15)
+ checker.join(15)
+
+ assert edit_still_waiting
+ assert answered, "is_approved waited behind an edit blocked on the file lock"
diff --git a/tests/gateway/test_telegram_voice_v0_regressions.py b/tests/gateway/test_telegram_voice_v0_regressions.py
index 1b59fbaef8e..0bebba25304 100644
--- a/tests/gateway/test_telegram_voice_v0_regressions.py
+++ b/tests/gateway/test_telegram_voice_v0_regressions.py
@@ -290,7 +290,7 @@ async def test_voice_note_merged_during_pending_stt_is_transcribed():
stt_started = asyncio.Event()
release = asyncio.Event()
- async def fake_enrich(text, paths):
+ async def fake_enrich(text, paths, _clip_memo=None):
stt_started.set()
await release.wait()
transcripts = [f"<{Path(p).name}>" for p in paths]
@@ -324,7 +324,7 @@ async def test_caption_of_voice_note_merged_during_pending_stt_is_kept():
stt_started = asyncio.Event()
release = asyncio.Event()
- async def fake_enrich(text, paths):
+ async def fake_enrich(text, paths, _clip_memo=None):
stt_started.set()
await release.wait()
transcripts = [f"<{Path(p).name}>" for p in paths]
@@ -351,3 +351,35 @@ async def test_caption_of_voice_note_merged_during_pending_stt_is_kept():
assert "<B.ogg>" in text
assert "first caption" in text
assert "second caption" in text
+
+
+async def test_burst_of_merged_voice_notes_transcribes_each_clip_once():
+ """STT is paid and delays the interrupt: a re-run after a merge must transcribe only the new
+ clips, and so must the drain path's re-run after a later merge drops the cached result."""
+ from gateway.platforms.base import merge_pending_message_event
+
+ runner = _runner()
+ source = _source()
+ pending = {}
+ merge_pending_message_event(pending, "k", _voice_event(source, ["/tmp/A.ogg"]))
+ event = pending["k"]
+ burst = ["/tmp/B.ogg", "/tmp/C.ogg", "/tmp/D.ogg"]
+ calls = []
+
+ async def fake_clip(path, *_stt):
+ calls.append(Path(path).name)
+ if burst: # the next note of the burst arrives while this clip is being transcribed
+ merge_pending_message_event(pending, "k", _voice_event(source, [burst.pop(0)]))
+ await asyncio.sleep(0)
+ return f"<{Path(path).name}>", f"<{Path(path).name}>"
+
+ runner._transcribe_one_clip = fake_clip
+ _, transcripts = await runner._transcribe_pending_audio_event_once(event)
+ assert transcripts == ["<A.ogg>", "<B.ogg>", "<C.ogg>", "<D.ogg>"]
+
+ merge_pending_message_event(pending, "k", _voice_event(source, ["/tmp/E.ogg"]))
+ _, drain_transcripts = await runner._transcribe_pending_audio_event_once(event)
+
+ assert drain_transcripts == ["<A.ogg>", "<B.ogg>", "<C.ogg>", "<D.ogg>", "<E.ogg>"]
+ assert calls == ["A.ogg", "B.ogg", "C.ogg", "D.ogg", "E.ogg"]
diff --git a/tests/hermes_cli/test_model_cache_parallel_prefetch.py b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
index aad2568fbd1..c0a2777743e 100644
--- a/tests/hermes_cli/test_model_cache_parallel_prefetch.py
+++ b/tests/hermes_cli/test_model_cache_parallel_prefetch.py
@@ -12,6 +12,8 @@ from __future__ import annotations
import time
from unittest.mock import patch
+import pytest
+
# ---------------------------------------------------------------------------
# Thread-safe cache entry update (hermes_cli/models.py)
# ---------------------------------------------------------------------------
@@ -73,6 +75,52 @@ class TestStoreCacheEntry:
assert p in cache, f"{p} was lost in concurrent write"
assert cache[p]["models"] == [f"model_{p}"]
+ @pytest.mark.parametrize("cleared", ["openrouter", None])
+ def test_clear_is_not_undone_by_a_concurrent_locked_write(self, tmp_path, monkeypatch, cleared):
+ """``--refresh`` clears under the same lock: a writer that loaded the cache before the clear
+ must not save its snapshot afterwards and bring the cleared row back."""
+ import threading
+
+ import hermes_cli.models as mod
+ from hermes_cli.models_cache_lock import write_under_cache_lock
+
+ import hermes_cli.models_cache_lock as cache_lock_module
+ from tests.lock_contention import ContentionObservedLock, watch_file_lock_contention
+ from tests.waiting import wait_until
+
+ cache_path = tmp_path / "provider_models_cache.json"
+ monkeypatch.setattr(mod, "_provider_models_cache_path", lambda: cache_path)
+ contended = watch_file_lock_contention(monkeypatch)
+ # In-process writers meet the thread lock first, other processes the file lock.
+ thread_lock = ContentionObservedLock()
+ monkeypatch.setattr(cache_lock_module, "_thread_lock", thread_lock)
+ mod._save_provider_models_cache({
+ "openrouter": mod._cache_entry("fp", ["or/model"]),
+ "anthropic": mod._cache_entry("fp", ["claude"]),
+ })
+ loaded = threading.Event()
+ release = threading.Event()
+
+ def slow_write(): # _store_cache_entry's write, paused between its read and its save
+ cache = mod._load_provider_models_cache()
+ loaded.set()
+ release.wait(5)
+ cache["anthropic"] = mod._cache_entry("fp", ["claude-new"])
+ mod._save_provider_models_cache(cache)
+
+ writer = threading.Thread(target=write_under_cache_lock, args=(cache_path, slow_write))
+ writer.start()
+ assert loaded.wait(5)
+ clearer = threading.Thread(target=mod.clear_provider_models_cache, args=(cleared,))
+ clearer.start()
+ wait_until(lambda: not clearer.is_alive() or contended.is_set() or thread_lock.contended.is_set(),
+ what="the clear finished or blocked on the cache lock")
+ release.set()
+ writer.join(5)
+ clearer.join(5)
+
+ assert "openrouter" not in mod._load_provider_models_cache()
+
# ---------------------------------------------------------------------------
# Parallel prefetch (hermes_cli/model_switch.py)
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_update_exit_code_publication.py b/tests/hermes_cli/test_update_exit_code_publication.py
index bbb1454417e..482fa1a7ae3 100644
--- a/tests/hermes_cli/test_update_exit_code_publication.py
+++ b/tests/hermes_cli/test_update_exit_code_publication.py
@@ -84,3 +84,23 @@ def test_takeover_owed_finish_never_exposes_an_empty_exit_code(home, tmp_path, q
_record_owed_finish({"gateway_mode": True}, tmp_path / "result.json", "child missing")
assert "" not in seen
assert marker.read_text(encoding="utf-8").strip() == "0"
+
+
[email protected]("recorder", ["failure", "owed_finish"])
+def test_takeover_records_without_runtime_state_or_pm(home, tmp_path, quiet_receipt, monkeypatch, recorder):
+ """The takeover bootstraps before the app is importable; its recorders must still write
+ result.json and the gateway exit code when hermes_cli.runtime_state (→ pm) cannot be imported."""
+ import sys
+
+ from hermes_cli import _update_takeover
+
+ for module in ("hermes_cli.runtime_state", "pm", "pm.filesystem"):
+ monkeypatch.setitem(sys.modules, module, None)
+ result = tmp_path / "result.json"
+ if recorder == "failure":
+ _update_takeover._record_failure({"gateway_mode": True}, result, 3, "boom")
+ else:
+ _update_takeover._record_owed_finish({"gateway_mode": True}, result, "child missing")
+
+ assert result.exists()
+ assert (home / ".update_exit_code").read_text(encoding="utf-8").strip() == ("3" if recorder == "failure" else "0")
diff --git a/tests/test_mcp_serve.py b/tests/test_mcp_serve.py
index f4007424ffb..c30997b56da 100644
--- a/tests/test_mcp_serve.py
+++ b/tests/test_mcp_serve.py
@@ -1048,9 +1048,6 @@ class TestEventBridgePollE2E:
monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: None)
db = TestDB()
bridge = mcp_serve.EventBridge()
- # Files written within the racy-tick window are always re-read; settle them first.
- settled = time.time_ns() - 60 * 1_000_000_000
- os.utime(db_path, ns=(settled, settled))
# First poll — should process
bridge._poll_once(db)
@@ -1177,10 +1174,8 @@ class TestEventBridgePollE2E:
}]
bridge = mcp_serve.EventBridge()
- # Bridge has never seen this db state (mtime differs) and has an
- # empty cached index — exactly the state after a new conversation's
- # first write.
- bridge._state_db_sig = ()
+ # Bridge has never seen this db state and has an empty cached index —
+ # exactly the state after a new conversation's first write.
assert bridge._cached_sessions_index == {}
bridge._poll_once(DB())
@@ -1300,17 +1295,12 @@ class TestEventBridgePollE2E:
commit_message("user", "before baseline", 100.0)
bridge = mcp_serve.EventBridge()
bridge._establish_baseline()
- # Settle every file, then let one poll record that settled signature.
- settled = time.time_ns() - 60 * 1_000_000_000
- for name in ("state.db", "state.db-wal"):
- os.utime(tmp_path / name, ns=(settled, settled))
bridge._poll_once(db)
assert bridge.poll_events(after_cursor=0)["events"] == []
for i in range(5):
commit_message("assistant", f"reply {i} after baseline", 101.0 + i)
# No checkpoint ran: the main database file is untouched by these commits.
- os.utime(tmp_path / "state.db", ns=(settled, settled))
bridge._poll_once(db)
finally:
db.close()
@@ -1319,31 +1309,78 @@ class TestEventBridgePollE2E:
assert [e["content"] for e in events] == [f"reply {i} after baseline" for i in range(5)]
def test_commit_in_the_baseline_mtime_tick_is_delivered(self, tmp_path, monkeypatch):
- """A commit in the same coarse mtime tick as the bridge's stat leaves the
- database files' signature unchanged, so a fresh signature must not count as
- 'nothing changed' (racily clean)."""
+ """A commit in the same coarse mtime tick as the baseline leaves every stat field the
+ same; the gate must still see it."""
import mcp_serve
+ from hermes_state import SessionDB
- now = time.time_ns()
- for name in ("state.db", "state.db-wal"):
- (tmp_path / name).write_bytes(b"\0" * 4096)
- os.utime(tmp_path / name, ns=(now, now))
- monkeypatch.setattr(mcp_serve, "_load_sessions_index", lambda: {
- "agent:main:telegram:dm:tick": {"session_id": "sid-tick", "platform": "telegram"},
- })
- store = [{"id": 1, "role": "user", "content": "before baseline", "timestamp": 100.0}]
-
- class DB:
- def get_messages(self, sid):
- return list(store)
-
- monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: DB())
- bridge = mcp_serve.EventBridge()
- bridge._establish_baseline()
+ db = SessionDB(tmp_path / "state.db")
+ try:
+ db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:tick",
+ chat_id="tick", chat_type="dm")
+ db.append_message("s1", role="user", content="before baseline")
+ monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: db)
+ bridge = mcp_serve.EventBridge()
+ bridge._establish_baseline()
+ pinned = {name: (tmp_path / name).stat().st_mtime_ns for name in ("state.db", "state.db-wal")}
- # Committed within the baseline's mtime tick: no stat field the bridge reads moved.
- store.append({"id": 2, "role": "assistant", "content": "same tick", "timestamp": 101.0})
- bridge._poll_once(DB())
+ db.append_message("s1", role="assistant", content="same tick")
+ for name, mtime_ns in pinned.items():
+ os.utime(tmp_path / name, ns=(mtime_ns, mtime_ns))
+ bridge._poll_once(db)
+ finally:
+ db.close()
events = bridge.poll_events(after_cursor=0)["events"]
assert [e["content"] for e in events] == ["same tick"]
+
+ def test_one_commit_costs_one_full_poll(self, tmp_path, monkeypatch):
+ """Every full poll loads each active session's transcript. An isolated commit must open
+ the gate exactly once: a gate that distrusts recent mtimes re-polls for seconds after every
+ write, and a gateway writing that often keeps the bridge in permanent full-poll mode."""
+ import mcp_serve
+ from hermes_state import SessionDB
+
+ db = SessionDB(tmp_path / "state.db")
+ try:
+ db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:cost",
+ chat_id="cost", chat_type="dm")
+ monkeypatch.setattr(mcp_serve, "_get_session_db", lambda: db)
+ bridge = mcp_serve.EventBridge()
+ bridge._establish_baseline()
+ full_polls = []
+ real_load = mcp_serve._load_sessions_index
+ monkeypatch.setattr(mcp_serve, "_load_sessions_index", lambda: full_polls.append(1) or real_load())
+
+ db.append_message("s1", role="user", content="one write")
+ for _ in range(10):
+ bridge._poll_once(db)
+ finally:
+ db.close()
+
+ assert len(full_polls) == 1
+ assert [e["content"] for e in bridge.poll_events(after_cursor=0)["events"]] == ["one write"]
+
+ @pytest.mark.parametrize("home_name", ["home#1", "home?x", "home%23"])
+ def test_the_version_gate_watches_the_real_db_under_a_uri_special_home(self, tmp_path, monkeypatch, home_name):
+ """``#``/``?``/``%xx`` in HERMES_HOME must not truncate or re-decode the read-only URI: the
+ gate would then watch some other (empty) database whose version never follows state.db."""
+ import hermes_constants
+ import mcp_serve
+ from hermes_state import SessionDB
+
+ home = tmp_path / home_name
+ home.mkdir()
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)
+ db = SessionDB(home / "state.db")
+ try:
+ gate = mcp_serve._StateDbVersion()
+ before = gate.read()
+ db.create_session("s1", "telegram", session_key="agent:main:telegram:dm:uri",
+ chat_id="uri", chat_type="dm")
+ after = gate.read()
+ gate.close()
+ finally:
+ db.close()
+
+ assert before is not None and after != before
diff --git a/tests/tools/test_modal_snapshot_isolation.py b/tests/tools/test_modal_snapshot_isolation.py
index 7952e5c46c8..d9098f4b4bf 100644
--- a/tests/tools/test_modal_snapshot_isolation.py
+++ b/tests/tools/test_modal_snapshot_isolation.py
@@ -294,3 +294,26 @@ def test_concurrent_snapshot_stores_keep_both_tasks(tmp_path, monkeypatch):
"direct:task-A": "im-AAAA",
"direct:task-B": "im-BBBB",
}
+
+
+def test_snapshot_store_update_proceeds_when_the_lock_is_unavailable(tmp_path, monkeypatch):
+ """A wedged or unsupported lock must not abort a sandbox lifecycle step: modal's restore
+ fallback deletes the failed snapshot id and then retries with the base image."""
+ import contextlib
+
+ import hermes_cli.auth as auth_module
+ import tools.environments.modal as modal_module
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes-home"))
+
+ @contextlib.contextmanager
+ def wedged_lock(*_args, **_kwargs):
+ raise TimeoutError("Timed out waiting for the snapshot store lock")
+ yield
+
+ modal_module._store_direct_snapshot("task-A", "im-AAAA")
+ monkeypatch.setattr(auth_module, "_file_lock", wedged_lock)
+
+ modal_module._delete_direct_snapshot("task-A", "im-AAAA")
+
+ assert json.loads(modal_module._snapshot_store().read_text(encoding="utf-8")) == {}
diff --git a/tools/environments/base.py b/tools/environments/base.py
index e52211817af..a74ebd2bff6 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -215,11 +215,21 @@ def _update_json_store(path: Path, update: Callable[[dict], None]) -> None:
"""Read-modify-write the JSON store at *path* under a cross-process lock.
Concurrent sandbox cleanups (delegate children, gateway sessions, the idle reaper) each
- record a snapshot id; an unlocked load/mutate/save lets one cleanup drop the other's entry."""
+ record a snapshot id; an unlocked load/mutate/save lets one cleanup drop the other's entry.
+ An unusable lock (no flock on the filesystem, a wedged holder) degrades to an unlocked
+ update: a sandbox lifecycle step (modal's restore fallback included) must not abort on it."""
+ from contextlib import ExitStack
+
from hermes_cli.auth import _file_lock
lock_path = path.with_name(f"{path.name}.lock")
- with _file_lock(lock_path, _JSON_STORE_LOCK_HOLDER, 10.0, f"Timed out waiting for the snapshot store lock ({path})"):
+ with ExitStack() as stack:
+ try:
+ stack.enter_context(_file_lock(
+ lock_path, _JSON_STORE_LOCK_HOLDER, 10.0, f"Timed out waiting for the snapshot store lock ({path})",
+ ))
+ except (OSError, TimeoutError):
+ logger.warning("Updating %s without its lock", path, exc_info=True)
data = _load_json_store(path)
before = dict(data)
update(data)