Skip to content

The agent that grows with you

fix(desktop): make the gateway activation epoch observable for group capability probes

KarMateam55552edb46e3ab1f
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts
index 88784158459..2820e6441f0 100644
--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts
@@ -1,4 +1,4 @@
-import { gatewayActivationEpoch, host, useValue } from '@hermes/plugin-sdk'
+import { gatewayActivationEpoch, host, useGatewayActivationEpoch, useValue } from '@hermes/plugin-sdk'
import { useEffect, useState } from 'react'
import { canonicalGroupRequest } from './canonical-groups'
@@ -73,7 +73,7 @@ export function useGroupCapability(active: boolean) {
const connectionId = useValue(host.state.connectionId)
const profile = useValue(host.state.profile)
const gateway = useValue(host.state.gateway)
- const activationEpoch = gatewayActivationEpoch()
+ const activationEpoch = useGatewayActivationEpoch()
const source = JSON.stringify([connectionId, profile, gateway, activationEpoch])
const [capability, setCapability] = useState<GroupCapabilityState | null>(null)
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-capability-gates.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-capability-gates.test.tsx
index cb1ad4480b1..eb84d7b7cda 100644
--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-capability-gates.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-capability-gates.test.tsx
@@ -2,6 +2,7 @@ import type * as HermesSdk from '@hermes/plugin-sdk'
import { host } from '@hermes/plugin-sdk'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { WritableAtom } from 'nanostores'
+import { useSyncExternalStore } from 'react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { CANONICAL_GROUP_LOCALES } from './canonical-group-locales'
@@ -17,7 +18,7 @@ import { translateBots } from './i18n-test-helper'
import { renderRosterToolbar } from './roster-pane-toolbar'
import type { RosterRow } from './types'
-const { request, notify, openWorkspace, activation } = vi.hoisted(() => ({ request: vi.fn(), notify: vi.fn(), openWorkspace: vi.fn(), activation: { epoch: 1 } }))
+const { request, notify, openWorkspace, activation } = vi.hoisted(() => ({ request: vi.fn(), notify: vi.fn(), openWorkspace: vi.fn(), activation: { epoch: 1, listeners: new Set<() => void>() } }))
vi.mock('@hermes/plugin-sdk', async importOriginal => {
const sdk = await importOriginal<typeof HermesSdk>()
const { en } = await import('@/i18n/en')
@@ -25,6 +26,17 @@ vi.mock('@hermes/plugin-sdk', async importOriginal => {
return {
...sdk,
gatewayActivationEpoch: () => activation.epoch,
+ // The hook subscribes, like the real store: an epoch that moves re-renders its readers.
+ useGatewayActivationEpoch: () => useSyncExternalStore(
+ listener => {
+ activation.listeners.add(listener)
+
+ return () => {
+ activation.listeners.delete(listener)
+ }
+ },
+ () => activation.epoch
+ ),
host: {
...sdk.host, requestProfile: request, notify, openWorkspace,
request: (method: string, params?: Record<string, unknown>) => request(null, method, params),
@@ -359,6 +371,7 @@ function moveSource(kind: 'profile' | 'gateway' | 'same-route-activation') {
if (kind === 'same-route-activation') {
activation.epoch++
+ activation.listeners.forEach(listener => listener())
state.profile.set('default')
}
}
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-reopen-by-name.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-reopen-by-name.test.tsx
index c33f9b34f9d..8a997890317 100644
--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-reopen-by-name.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-reopen-by-name.test.tsx
@@ -24,6 +24,7 @@ vi.mock('@hermes/plugin-sdk', async importOriginal => {
return {
...sdk,
gatewayActivationEpoch: () => 1,
+ useGatewayActivationEpoch: () => 1,
host: {
...sdk.host, requestProfile: request, notify, openWorkspace,
request: (method: string, params?: Record<string, unknown>) => request(null, method, params),
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
index ef9ba68ddb2..29275eba27c 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -24,7 +24,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
- gatewayActivationEpoch,
host,
Input,
queryClient,
@@ -32,6 +31,7 @@ import {
RowButton,
Tip,
ToggleRow,
+ useGatewayActivationEpoch,
useI18n,
useValue
} from '@hermes/plugin-sdk'
@@ -603,7 +603,7 @@ function GroupExecutionGate(props: GroupChatWorkspaceProps) {
const connectionId = useValue(host.state.connectionId)
const profile = useValue(host.state.profile)
const gateway = useValue(host.state.gateway)
- const activationEpoch = gatewayActivationEpoch()
+ const activationEpoch = useGatewayActivationEpoch()
const source = JSON.stringify([connectionId, profile, gateway, activationEpoch])
const [capability, setCapability] = useState<{ source: string; mode: GroupExecutionMode } | null>(null)
const mode = capability?.source === source ? capability.mode : 'checking'
diff --git a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts
index 637c0399f36..8d681dd0f78 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts
@@ -474,6 +474,7 @@ export async function pluginSdkMock(host: Record<string, unknown>) {
createBudgetedLoop: undefined,
gatewayActivationEpoch: () => 0,
GlyphSpinner: () => null,
+ useGatewayActivationEpoch: () => 0,
host,
randomUuid,
CapabilitiesView: undefined,
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index e88a75eeb87..de411600f93 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1890,7 +1890,7 @@ export {
type TranscriptDirectiveProps
} from '@/lib/transcript-directives'
export { cn } from '@/lib/utils'
-export { gatewayActivationEpoch } from '@/store/gateway'
+export { gatewayActivationEpoch, useGatewayActivationEpoch } from '@/store/gateway'
/** THE unread store behind `SessionStatusDot`'s emerald dot. A plugin that
* learns out-of-band that a session produced something the user hasn't seen
* (a roster poll's activity watermark, say) writes HERE rather than keeping
diff --git a/apps/desktop/src/store/gateway-activation-epoch-groups.test.tsx b/apps/desktop/src/store/gateway-activation-epoch-groups.test.tsx
new file mode 100644
index 00000000000..0ce2368e91c
--- /dev/null
+++ b/apps/desktop/src/store/gateway-activation-epoch-groups.test.tsx
@@ -0,0 +1,210 @@
+// A real gateway activation can move the activation epoch WITHOUT moving the
+// connectionId / profile / gateway atoms (the primary fast path in
+// ensureGatewayForProfile). Group-capability consumers key their answer on that
+// epoch, so they must re-render and re-probe when it moves; otherwise a healthy
+// `groups.capabilities` answer is discarded by its own fence and the UI stays in
+// `checking` forever (New Group Chat: two bots ticked, Create disabled, no warning).
+// No mock of the epoch: the real beginGatewayActivation runs.
+import type * as HermesSdk from '@hermes/plugin-sdk'
+import { host } from '@hermes/plugin-sdk'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { groupCreationSource, useGroupCapability } from '@/plugins/hermes-bots/canonical-group-capabilities'
+import { CreateGroupChatDialog } from '@/plugins/hermes-bots/create-dialog'
+import { GroupChatWorkspace } from '@/plugins/hermes-bots/group-chat-view'
+import { ensureGatewayForProfile, gatewayActivationEpoch } from '@/store/gateway'
+
+const { request } = vi.hoisted(() => ({ request: vi.fn() }))
+
+vi.mock('@hermes/plugin-sdk', async importOriginal => {
+ const sdk = await importOriginal<typeof HermesSdk>()
+ const { en } = await import('@/i18n/en')
+ const { translateBots } = await import('@/plugins/hermes-bots/i18n-test-helper')
+
+ return {
+ ...sdk,
+ host: {
+ ...sdk.host,
+ requestProfile: request,
+ connections: vi.fn(async () => []),
+ state: {
+ ...sdk.host.state,
+ connectionId: sdk.atom('remote-1'),
+ profile: sdk.atom('default'),
+ gateway: sdk.atom('open')
+ }
+ },
+ useI18n: () => ({ locale: 'en', t: en }),
+ usePluginI18n: () => translateBots
+ }
+})
+vi.mock('@/plugins/hermes-bots/group-chat-parts', async importOriginal => ({
+ ...(await importOriginal<any>()),
+ GroupImageControls: () => null
+}))
+
+const FEATURES = [
+ 'authority_epoch',
+ 'coordinator_fencing',
+ 'room_identity',
+ 'monotonic_log',
+ 'idempotent_send',
+ 'replayable_disband',
+ 'typed_events',
+ 'actor_identity',
+ 'log_replication',
+ 'authority_takeover'
+]
+
+const METHODS = ['capabilities', 'list', 'create', 'state', 'send', 'stop', 'retry', 'approve'].map(m => `groups.${m}`)
+
+const payload = { driver: true, persistent_process: true, protocol_version: 2, features: FEATURES, methods: METHODS }
+
+const roster = [
+ { name: 'alpha', connectionId: 'remote-1' },
+ { name: 'beta', connectionId: 'remote-1' }
+]
+
+const route = { connectionId: 'remote-1', profile: 'default' }
+const state = host.state as any
+const capCalls = () => request.mock.calls.filter(call => call[1] === 'groups.capabilities').length
+const createButton = () => screen.getByRole('button', { name: 'Create Group (2)' }) as HTMLButtonElement
+
+let latest: any
+
+function Hook() {
+ latest = useGroupCapability(true)
+
+ return <output>{latest.mode}</output>
+}
+
+function deferred() {
+ let resolve!: (value: unknown) => void
+ const promise = new Promise(r => (resolve = r))
+
+ return { promise, resolve }
+}
+
+// The primary fast path bumps the epoch and changes no atom the hooks subscribe to.
+const activate = () =>
+ act(async () => {
+ await ensureGatewayForProfile('default')
+ })
+
+const sleep = (ms: number) =>
+ act(async () => {
+ await new Promise(r => setTimeout(r, ms))
+ })
+
+function tickAll() {
+ for (const checkbox of screen.getAllByRole('checkbox')) {
+ fireEvent.click(checkbox)
+ }
+}
+
+beforeEach(() => {
+ state.connectionId.set('remote-1')
+ state.profile.set('default')
+ state.gateway.set('open')
+ request.mockReset()
+ Element.prototype.scrollIntoView = vi.fn()
+ Element.prototype.hasPointerCapture = vi.fn(() => false)
+ Element.prototype.releasePointerCapture = vi.fn()
+})
+
+afterEach(() => {
+ cleanup()
+ localStorage.clear()
+})
+
+it('a primary-route activation moves only the epoch, not the atoms the hooks watch', async () => {
+ const epoch = gatewayActivationEpoch()
+ const before = [state.connectionId.get(), state.profile.get(), state.gateway.get()]
+
+ await activate()
+
+ expect(gatewayActivationEpoch()).toBe(epoch + 1)
+ expect([state.connectionId.get(), state.profile.get(), state.gateway.get()]).toEqual(before)
+})
+
+it('an activation while the capability probe is in flight does not strand the hook in checking', async () => {
+ const first = deferred()
+ request.mockReturnValueOnce(first.promise).mockResolvedValue(payload)
+ render(<Hook />)
+
+ await activate()
+ await act(async () => {
+ first.resolve(payload)
+ await first.promise
+ })
+
+ await waitFor(() => expect(latest.mode).toBe('canonical'), { timeout: 2000 })
+ expect(capCalls()).toBe(2)
+})
+
+it('after an activation the hook re-probes once and keeps the stale-answer fence intact', async () => {
+ request.mockResolvedValue(payload)
+ render(<Hook />)
+ await waitFor(() => expect(latest.mode).toBe('canonical'))
+ expect(capCalls()).toBe(1)
+ const firstEpoch = latest.capability.activationEpoch
+
+ await activate()
+
+ await waitFor(() => expect(capCalls()).toBe(2), { timeout: 2000 })
+ await waitFor(() => expect(latest.mode).toBe('canonical'))
+ expect(groupCreationSource(route, latest.capability.activationEpoch)()).toBe(true)
+ expect(groupCreationSource(route, firstEpoch)()).toBe(false)
+ await sleep(80)
+ expect(capCalls()).toBe(2)
+})
+
+it('New Group Chat enables Create after an activation lands mid-probe', async () => {
+ const pending = deferred()
+ request.mockReturnValueOnce(pending.promise).mockResolvedValue(payload)
+ render(<CreateGroupChatDialog onClose={vi.fn()} open roster={roster} />)
+ tickAll()
+
+ await activate()
+ await act(async () => {
+ pending.resolve(payload)
+ await pending.promise
+ })
+
+ await waitFor(() => expect(createButton().disabled).toBe(false), { timeout: 2000 })
+})
+
+it('New Group Chat stays creatable after an activation that follows a healthy answer', async () => {
+ request.mockResolvedValue(payload)
+ render(<CreateGroupChatDialog onClose={vi.fn()} open roster={roster} />)
+ tickAll()
+ await waitFor(() => expect(createButton().disabled).toBe(false))
+
+ await activate()
+
+ await waitFor(() => expect(capCalls()).toBe(2), { timeout: 2000 })
+ await waitFor(() => expect(createButton().disabled).toBe(false))
+})
+
+it('the existing-room execution gate re-probes after an activation, then settles', async () => {
+ request.mockImplementation(async (_route: unknown, method: string) => {
+ if (method === 'groups.capabilities') {
+ return payload
+ }
+
+ return method === 'groups.list' ? { rooms: [], next_offset: null } : {}
+ })
+ render(<GroupChatWorkspace group="Existing" members={roster as any} />)
+ await sleep(200)
+ const before = capCalls()
+
+ await activate()
+ await sleep(300)
+
+ const after = capCalls()
+ expect(after).toBeGreaterThan(before)
+ expect(after - before).toBeLessThanOrEqual(2)
+ await sleep(300)
+ expect(capCalls()).toBe(after)
+})
diff --git a/apps/desktop/src/store/gateway-activation-epoch.ts b/apps/desktop/src/store/gateway-activation-epoch.ts
new file mode 100644
index 00000000000..734390b1de9
--- /dev/null
+++ b/apps/desktop/src/store/gateway-activation-epoch.ts
@@ -0,0 +1,31 @@
+import { useStore } from '@nanostores/react'
+import { atom } from 'nanostores'
+
+const EPOCH_KEY = Symbol.for('hermes.desktop.gatewayActivationEpoch')
+
+// Same dev-HMR rule as the gateway registry state: a re-evaluated module must
+// hand back the SAME atom, or existing subscribers are orphaned. Production has
+// no `import.meta.hot`, so this is a plain module-local atom there.
+function epochAtom() {
+ if (import.meta.hot) {
+ const store = globalThis as unknown as { [EPOCH_KEY]?: ReturnType<typeof atom<number>> }
+
+ return (store[EPOCH_KEY] ??= atom<number>(0))
+ }
+
+ return atom<number>(0)
+}
+
+/** The gateway activation epoch: bumped on every active route selection,
+ * including same-profile source swaps. store/gateway.ts's
+ * beginGatewayActivation is its only writer; read it imperatively with
+ * `gatewayActivationEpoch()`. */
+export const $gatewayActivationEpoch = epochAtom()
+
+/** `gatewayActivationEpoch()` for a component. A render that keys on the epoch
+ * MUST read it here: a plain getter call is a read nothing subscribes to, so a
+ * memoized render (the React Compiler) keeps the epoch it first saw while an
+ * activation moves it underneath without touching connection/profile/gateway. */
+export function useGatewayActivationEpoch(): number {
+ return useStore($gatewayActivationEpoch)
+}
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index dc82cef6ce8..9886b651884 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -30,11 +30,13 @@ import {
SOURCE_SWITCH_DIAL_TIMEOUT_MS,
withTimeout
} from '@/lib/with-timeout'
+import { $gatewayActivationEpoch } from '@/store/gateway-activation-epoch'
import { isMissingConnectionError, isMissingProfileError } from '@/store/gateway-dial-failures'
import { notifyError, RECOVERY_ACTIONS } from '@/store/notifications'
import { markNativeNotifyBaseline } from '@/store/notify-baseline'
import { setConnection, setGatewayState } from '@/store/session'
import { stampSecondaryProfileOwner } from '@/store/session-event-provenance'
+export { useGatewayActivationEpoch } from '@/store/gateway-activation-epoch'
// ── Multi-profile gateway routing ──────────────────────────────────────────
// Concurrent sessions across profiles need concurrent sockets: the renderer's
@@ -222,7 +224,6 @@ interface GatewayRegistryState {
primaryConnectionMode: 'local' | 'remote' | null
primaryProfile: string
activeKey: string
- activationEpoch: number
secondaries: Map<string, Secondary>
// Auth rejection outlives the disposable socket, including background request leases.
reauthFailures: Map<string, { connectionId: string | null; error: Error }>
@@ -251,7 +252,6 @@ function createRegistryState(): GatewayRegistryState {
primaryConnectionMode: null,
primaryProfile: initialGatewayProfile(),
activeKey: initialGatewayProfile(),
- activationEpoch: 0,
secondaries: new Map<string, Secondary>(),
reauthFailures: new Map(),
dialFailures: new Map(),
@@ -530,7 +530,7 @@ export function isActivePrimary(): boolean {
/** Changes on every active route selection, including same-profile source swaps. */
export function gatewayActivationEpoch(): number {
- return Number.isFinite(g.activationEpoch) ? g.activationEpoch : 0
+ return Number.isFinite($gatewayActivationEpoch.get()) ? $gatewayActivationEpoch.get() : 0
}
export function activeGateway(): HermesGateway | null {
@@ -636,9 +636,9 @@ function setActive(profile: string): void {
}
function beginGatewayActivation(): number {
- g.activationEpoch = gatewayActivationEpoch() + 1
+ $gatewayActivationEpoch.set(gatewayActivationEpoch() + 1)
- return g.activationEpoch
+ return $gatewayActivationEpoch.get()
}
function applyActive(profile: string, activationEpoch: number): boolean {