The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): gate Group Chat creation on a classified, still-current source
David Dudok de Witd598b74c5187
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.tsnew file mode 100644index 00000000000..5541e662b6c--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-capabilities.ts@@ -0,0 +1,43 @@+import { gatewayActivationEpoch, host } from '@hermes/plugin-sdk'++export type GroupExecutionMode = 'canonical' | 'legacy' | 'unavailable'++export function groupExecutionMode(value: unknown): GroupExecutionMode {+ if (!value || typeof value !== 'object' || Array.isArray(value)) {+ return 'unavailable'+ }++ const capability = value as Record<string, unknown>+ const { driver, persistent_process, features, methods } = capability++ if (features !== undefined && (!Array.isArray(features) || features.some(feature => typeof feature !== 'string'))) {+ return 'unavailable'+ }++ if (methods !== undefined && (!Array.isArray(methods) || methods.some(method => typeof method !== 'string'))) {+ return 'unavailable'+ }++ if (driver === true) {return 'canonical'}++ // App-managed hosted owners can be nonpersistent, even when their driver stops.+ const ownsRooms = Object.hasOwn(capability, 'protocol_version') || Object.hasOwn(capability, 'authority_gateway_id')+ || methods?.includes('groups.create') || features?.includes('canonical_session_owner')++ if (driver === false && persistent_process === false && !ownsRooms) {+ return 'legacy'+ }++ return 'unavailable'+}++/** Fence a group-creation flow to the source that approved it. Pass the epoch the+ * capability was read under (default: now); the predicate turns false once the+ * connection, profile, socket or activation epoch moves, so a late result is+ * neither acted on nor published. */+export function groupCreationSource(route: { connectionId: string; profile: string },+ activationEpoch = gatewayActivationEpoch()) {+ return () => gatewayActivationEpoch() === activationEpoch &&+ route.connectionId === host.state.connectionId.get() &&+ route.profile === host.state.profile.get() && host.state.gateway.get() === 'open'+}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.tsxnew file mode 100644index 00000000000..d2ff3ffb8dd--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-capability-gates.test.tsx@@ -0,0 +1,214 @@+import type * as HermesSdk from '@hermes/plugin-sdk'+import { host } from '@hermes/plugin-sdk'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import type { WritableAtom } from 'nanostores'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { CANONICAL_GROUP_LOCALES } from './canonical-group-locales'+import { $canonicalGroupBindings } from './canonical-group-registry'+import { CreateGroupChatDialog } from './create-dialog'+import { $botMeta } from './data'+import { $groupChats, $groupChatWorkspace, updateGroupChat } from './group-chat'+import type * as GroupChatModule from './group-chat'+import type * as GroupChatParts from './group-chat-parts'+import { GroupChatWorkspace } from './group-chat-view'+import { translateBots } from './i18n-test-helper'++const { request, notify, openWorkspace, activation } = vi.hoisted(() => ({ request: vi.fn(), notify: vi.fn(), openWorkspace: vi.fn(), activation: { epoch: 1 } }))+vi.mock('@hermes/plugin-sdk', async importOriginal => {+ const sdk = await importOriginal<typeof HermesSdk>()+ const { en } = await import('@/i18n/en')++ return {+ ...sdk,+ gatewayActivationEpoch: () => activation.epoch,+ host: {+ ...sdk.host, requestProfile: request, notify, openWorkspace,+ request: (method: string, params?: Record<string, unknown>) => request(null, method, params),+ connections: vi.fn(async () => []),+ state: {+ ...sdk.host.state,+ connectionId: sdk.atom<string | null>('local'),+ profile: sdk.atom('default'),+ gateway: sdk.atom('open')+ }+ },+ useI18n: () => ({ locale: 'en', t: en }),+ usePluginI18n: () => translateBots+ }+})+vi.mock('./group-chat', async importOriginal => {+ const actual = await importOriginal<typeof GroupChatModule>()++ return {+ ...actual,+ // Keep actual local creation, but do not schedule the unrelated remote mirror.+ updateGroupChat: vi.fn((group, mutate) => actual.updateGroupChat(group, mutate, { sync: false }))+ }+})+vi.mock('./group-chat-parts', async importOriginal => ({+ ...await importOriginal<typeof GroupChatParts>(),+ // Avatar generation is unrelated to the capability decision; never request a model.+ GroupImageControls: () => null+}))++const state = {+ connectionId: host.state.connectionId as WritableAtom<string | null>,+ profile: host.state.profile as WritableAtom<string>,+ gateway: host.state.gateway as WritableAtom<string>+}++const roster = [{ name: 'alpha', connectionId: 'local' }, { name: 'beta', connectionId: 'local' }]+const unavailable = CANONICAL_GROUP_LOCALES.en.driverUnavailable++// Decision-relevant fields emitted by the actual canonical capabilities producer.+const canonicalUnavailable = {+ driver: false, persistent_process: true, features: ['room_identity', 'monotonic_log', 'replayable_disband']+}++// App-managed hosted capabilities keep their protocol/authority when the driver stops.+// Their RoomLink catalog deliberately reports persistent_process:false.+const appManagedUnavailable = {+ driver: false, persistent_process: false, protocol_version: 2,+ authority_gateway_id: 'installation:app-managed',+ features: ['authority_epoch', 'coordinator_fencing', 'room_identity', 'monotonic_log'],+ methods: ['groups.capabilities', 'groups.create', 'groups.state', 'groups.send']+}++const legacy = { driver: false, persistent_process: false }++const refused = [canonicalUnavailable, appManagedUnavailable, { ...legacy, methods: ['groups.create'] }, { driver: 'true', persistent_process: false }, null]++beforeEach(() => {+ activation.epoch = 1+ state.connectionId.set('local')+ state.profile.set('default')+ state.gateway.set('open')+ $canonicalGroupBindings.set({})+ $groupChats.set({})+ $groupChatWorkspace.set(null)+ $botMeta.set({})+ request.mockReset()+ notify.mockReset()+ openWorkspace.mockReset().mockReturnValue(() => undefined)+ vi.mocked(updateGroupChat).mockClear()+ Element.prototype.scrollIntoView = vi.fn()+ Element.prototype.hasPointerCapture = vi.fn(() => false)+ Element.prototype.releasePointerCapture = vi.fn()+})+afterEach(() => {+ cleanup()+ $groupChats.set({})+ localStorage.clear()+ vi.restoreAllMocks()+})++function answer(capabilities: unknown) {+ request.mockImplementation(async (_route, method, params) => {+ if (method === 'groups.capabilities') {return capabilities}++ if (method === 'groups.create') {return { room: { room_id: params.room_id, name: params.name, members: params.members } }}++ if (method === 'profiles.configure') {return {}}+ throw new Error(`Unexpected RPC: ${method}`)+ })+}++async function submitDialog() {+ const onCreated = vi.fn()+ const onClose = vi.fn()+ render(<CreateGroupChatDialog onClose={onClose} onCreated={onCreated} open roster={roster} />)++ for (const checkbox of screen.getAllByRole('checkbox')) {fireEvent.click(checkbox)}+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Create Group (2)' })) })++ return { onCreated, onClose }+}++function pendingCreation() {+ let finish!: () => void+ const serverRooms = new Map<string, unknown>()+ request.mockImplementation(async (_route, method, params) => {+ if (method === 'groups.capabilities') {return { driver: true, persistent_process: true }}++ if (method === 'groups.create') {+ const room = { room_id: params.room_id, name: params.name, members: params.members }+ serverRooms.set(room.room_id, room)++ return new Promise(resolve => { finish = () => resolve({ room }) })+ }++ throw new Error(`Unexpected RPC: ${method}`)+ })++ return { serverRooms, finish: () => finish() }+}++it.each(refused)('classifies %j as unavailable on both surfaces: no legacy renderer, no legacy creation', async value => {+ answer(value)+ await act(async () => { render(<GroupChatWorkspace group="Existing" members={roster} />) })+ expect(screen.getByText(unavailable)).toBeTruthy()+ expect(screen.queryByRole('textbox')).toBeNull()+ expect((screen.getByRole('button', { name: 'Start gateway group' }) as HTMLButtonElement).disabled).toBe(true)+ cleanup()++ const { onCreated, onClose } = await submitDialog()+ expect(notify).toHaveBeenCalledWith({ kind: 'error', message: unavailable })+ expect(onCreated).not.toHaveBeenCalled()+ expect(onClose).not.toHaveBeenCalled()+ expect(updateGroupChat).not.toHaveBeenCalled()+ expect($groupChats.get()).toEqual({})+ expect(request.mock.calls.map(call => call[1])).toEqual(['groups.capabilities', 'groups.capabilities'])+})++it('keeps positive classifications working: legacy renders and creates locally, canonical creates a gateway room', async () => {+ answer(legacy)+ await act(async () => { render(<GroupChatWorkspace group="Existing" members={roster} />) })+ expect(screen.getByRole('textbox')).toBeTruthy()+ cleanup()+ expect((await submitDialog()).onCreated).toHaveBeenCalledOnce()+ expect(updateGroupChat).toHaveBeenCalledOnce()+ cleanup()++ answer({ driver: true, persistent_process: true })+ const { onCreated } = await submitDialog()+ expect(onCreated).toHaveBeenCalledOnce()+ expect(Object.values($canonicalGroupBindings.get())).toHaveLength(1)+ expect(updateGroupChat).toHaveBeenCalledOnce()+ expect(request.mock.calls.filter(call => call[1] === 'groups.create')).toHaveLength(1)+})++function moveSource(kind: 'profile' | 'gateway' | 'same-route-activation') {+ if (kind === 'profile') {state.profile.set('other')}++ if (kind === 'gateway') {state.gateway.set('closed')}++ if (kind === 'same-route-activation') {+ activation.epoch+++ state.profile.set('default')+ }+}++it.each(['profile', 'gateway', 'same-route-activation'] as const)('dialog: a creation approved before the %s moved is kept on its owner and never published', async kind => {+ const pending = pendingCreation()+ const { onCreated, onClose } = await submitDialog()+ expect(pending.serverRooms.size).toBe(1)+ await act(async () => { moveSource(kind); pending.finish() })+ expect($canonicalGroupBindings.get()).toEqual({})+ expect(onCreated).not.toHaveBeenCalled()+ expect(onClose).not.toHaveBeenCalled()+ expect(pending.serverRooms.size).toBe(1)+ expect(request.mock.calls[1][0]).toMatchObject({ connectionId: 'local', profile: 'default' })+})++it.each(['profile', 'gateway', 'same-route-activation'] as const)('workspace: a capability read before the %s moved neither creates nor opens a room', async kind => {+ const pending = pendingCreation()+ await act(async () => { render(<GroupChatWorkspace group="Existing" members={roster} />) })+ const button = screen.getByRole('button', { name: 'Start gateway group' })+ expect((button as HTMLButtonElement).disabled).toBe(false)+ // Click after the source moved but before React re-renders: the stale capability must not create.+ await act(async () => { moveSource(kind); fireEvent.click(button) })+ expect(request.mock.calls.filter(call => call[1] === 'groups.create')).toHaveLength(0)+ expect(pending.serverRooms.size).toBe(0)+ expect(openWorkspace).not.toHaveBeenCalled()+})diff --git a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsxindex 61204d78157..390dc85d9e1 100644--- a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx+++ b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx@@ -43,6 +43,7 @@ import { isBackfilledFacePng } from './avatar-image'import { AvatarPicker } from './avatar-picker'import { $selectedBot } from './bot-state'import { createCanonicalChat } from './canonical-chat'+import { groupCreationSource, groupExecutionMode } from './canonical-group-capabilities'import { registerCanonicalGroup } from './canonical-group-registry'import { canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup } from './canonical-groups'import { $botMeta, botHandle, botRosterKey, filterBots, ROSTER_KEY, saveBotMeta } from './data'@@ -1172,10 +1173,20 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea}const route = captureCanonicalGroupRoute()- const capabilities = await canonicalGroupRequest<{ driver: boolean }>(route, 'groups.capabilities')+ const sourceCurrent = groupCreationSource(route)- if (capabilities.driver) {+ const capabilities = await canonicalGroupRequest<unknown>(route, 'groups.capabilities')+ const mode = groupExecutionMode(capabilities)++ if (!sourceCurrent() || mode === 'unavailable') {+ throw new Error(b.canonical.driverUnavailable)+ }++ if (mode === 'canonical') {const created = await createCanonicalGroup(route, base, durableGroupChatMembers(selected))++ // Creation already succeeded; leave it on its owner without adopting a stale result.+ if (!sourceCurrent()) {return}const key = registerCanonicalGroup(route, created.room)onClose()onCreated?.(key)diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsxindex b2c896bde44..1bafe615422 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx@@ -24,6 +24,7 @@ import {DialogFooter,DialogHeader,DialogTitle,+ gatewayActivationEpoch,host,Input,queryClient,@@ -38,9 +39,11 @@ import { useEffect, useMemo, useRef, useState } from 'react'import { avatarColor, botAppearance, BotFace } from './avatar'import { isBackfilledFacePng } from './avatar-image'+import { groupCreationSource, groupExecutionMode } from './canonical-group-capabilities'+import type { GroupExecutionMode } from './canonical-group-capabilities'import { $canonicalGroupBindings, registerCanonicalGroup } from './canonical-group-registry'import { CanonicalGroupWorkspace } from './canonical-group-workspace'-import { canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup } from './canonical-groups'+import { canonicalGroupRequest, createCanonicalGroup } from './canonical-groups'import {$botMeta,$lastRoster,@@ -468,33 +471,62 @@ export function GroupChatWorkspace(props: GroupChatWorkspaceProps) {}function GroupExecutionGate(props: GroupChatWorkspaceProps) {+ const b = useBots()const connectionId = useValue(host.state.connectionId)const profile = useValue(host.state.profile)- const [driver, setDriver] = useState<boolean | null>(null)+ const gateway = useValue(host.state.gateway)+ const activationEpoch = gatewayActivationEpoch()+ 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'const [error, setError] = useState('')const [busy, setBusy] = useState(false)useEffect(() => {let cancelled = false- setDriver(null)- void canonicalGroupRequest<{ driver: boolean }>(captureCanonicalGroupRoute(), 'groups.capabilities')- .then(result => { if (!cancelled) {setDriver(result.driver === true)} })- .catch(e => { if (!cancelled) {setError(String(e))} })+ setCapability(null)+ setError('')++ if (gateway !== 'open') {+ setCapability({ source, mode: 'unavailable' })++ return+ }++ void canonicalGroupRequest<unknown>({ connectionId: connectionId ?? '', profile }, 'groups.capabilities')+ .then(result => { if (!cancelled) {setCapability({ source, mode: groupExecutionMode(result) })} })+ .catch(e => {+ if (!cancelled) {+ setCapability({ source, mode: 'unavailable' })+ setError(String(e))+ }+ })return () => { cancelled = true }- }, [connectionId, profile])+ }, [connectionId, profile, gateway, source])- if (driver === false) {return <LegacyGroupChatWorkspace {...props} />}+ if (mode === 'legacy') {return <LegacyGroupChatWorkspace {...props} />}return <div className="grid gap-3 p-3"><h2>{props.group}</h2>- <p>{driver ? 'This is a legacy Desktop room. Start a gateway-owned group with these members; the old history stays here and is not replayed.' : 'Checking group driver…'}</p>+ <p>{mode === 'canonical' ? 'This is a legacy Desktop room. Start a gateway-owned group with these members; the old history stays here and is not replayed.' : mode === 'unavailable' ? b.canonical.driverUnavailable : 'Checking group driver…'}</p>{error && <p role="alert">{error}</p>}- <Button disabled={!driver || busy} onClick={() => {+ <Button disabled={mode !== 'canonical' || busy} onClick={() => {+ const route = { connectionId: connectionId ?? '', profile }++ const sourceCurrent = groupCreationSource(route, activationEpoch)++ if (mode !== 'canonical' || !sourceCurrent()) {+ setError(b.canonical.driverUnavailable)++ return+ }+setBusy(true)- const route = captureCanonicalGroupRoute()void createCanonicalGroup(route, props.group, props.members)- .then(({ room }) => openGroupChat(registerCanonicalGroup(route, room)))- .catch(e => setError(String(e))).finally(() => setBusy(false))+ .then(({ room }) => {+ if (sourceCurrent()) {openGroupChat(registerCanonicalGroup(route, room))}+ })+ .catch(e => { if (sourceCurrent()) {setError(String(e))} }).finally(() => setBusy(false))}}>Start gateway group</Button></div>}diff --git a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts b/apps/desktop/src/plugins/hermes-bots/group-test-utils.tsindex ff826a2b3d6..b65c1071027 100644--- a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts@@ -166,6 +166,11 @@ export function createGroupGateway(options: GatewayOptions = {}): ScriptedGatewa}const handle = async (method: string, params: Record<string, unknown>): Promise<unknown> => {+ // A legacy Desktop room: no hosted-room driver, nonpersistent owner.+ if (method === 'groups.capabilities') {+ return { driver: false, persistent_process: false }+ }+if (method === 'profiles.list') {return {profiles: [{ name: 'default', ui_meta: { ...uiMeta }, ui_meta_revisions: { ...uiMetaRevisions } }]@@ -431,6 +436,7 @@ export async function pluginSdkMock(host: Record<string, unknown>) {blobatarSvg: undefined,computed: nanostores.computed,createBudgetedLoop: undefined,+ gatewayActivationEpoch: () => 0,host,SkillsView: undefined,Streamdown: undefined,diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex ba3a1ab93df..f64b70d0a54 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -336,6 +336,7 @@ export const DEFAULT_SESSION_HYDRATION_TIMEOUT_MS = 20_000* and paint durable history. Bot Mode opts into one retry, so its effective* ceiling is two bounded attempts rather than an unbounded wait. */export const BOT_CHAT_SESSION_HYDRATION_TIMEOUT_MS = 60_000+let openSessionGeneration = 0export interface PluginOpenSessionOptions {@@ -1740,6 +1741,7 @@ export {type TranscriptDirectiveProps} from '@/lib/transcript-directives'export { cn } from '@/lib/utils'+export { gatewayActivationEpoch } 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 keepingdiff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex 619923bc177..24ec449c583 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -486,6 +486,13 @@ host.state.profile // ReadableAtom<string>host.state.viewport // ReadableAtom<{ width, height, narrow }>```+`gatewayActivationEpoch` is a named SDK export: `import { gatewayActivationEpoch } from '@hermes/plugin-sdk'`.+It reads the canonical activation counter, which changes on every active route+selection, including same-profile source swaps. Capture `const epoch = gatewayActivationEpoch()`+alongside the route before asynchronous work, then check both the captured route+and `gatewayActivationEpoch() === epoch` before mutation or UI publication. This+read-only counter is not a credential, permission grant, or durable gateway/session identity.+`host.state.gateway` is the WebSocket connection, not whether a chat turn isrunning. A session can be mid-turn while the socket is `open`; another sessioncan be idle at the same time. Disable composer or plugin actions from the