Skip to content

The agent that grows with you

fix(desktop): reopen a gateway group by name after a restart, never fork it

Teknium976ac86132e6
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 d2ff3ffb8dd..67c5ba158e6 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
@@ -131,6 +131,9 @@ function pendingCreation() {
request.mockImplementation(async (_route, method, params) => {
if (method === 'groups.capabilities') {return { driver: true, persistent_process: true }}
+ // A legacy room with no gateway room of its name yet (#140805 lookup answers empty).
+ if (method === 'groups.list') {return { rooms: [], next_offset: null }}
+
if (method === 'groups.create') {
const room = { room_id: params.room_id, name: params.name, members: params.members }
serverRooms.set(room.room_id, room)
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx
index d5eef20cd18..8652f97300a 100644
--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx
@@ -14,6 +14,43 @@ export function registerCanonicalGroup(route: CanonicalGroupRoute, room: Canonic
return key
}
+/** The route a `canonical:<connection>:<profile>:<room_id>` key was minted on, or null for a name. */
+export function parseCanonicalGroupKey(key: string): (CanonicalGroupRoute & { roomId: string }) | null {
+ const match = /^canonical:([^:]*):([^:]*):(.+)$/.exec(key)
+
+ if (!match) {return null}
+
+ try {
+ return { connectionId: decodeURIComponent(match[1]), profile: decodeURIComponent(match[2]), roomId: match[3] }
+ } catch {
+ return null
+ }
+}
+
+/** #140805: bindings live in memory, so after a restart a group opened by name
+ * (roster row) or by a restored `canonical:` tab key misses. Resolve it against
+ * the gateway's `groups.list` and alias the existing room under the key the
+ * caller used. Returns null only when the authority answered and holds no such
+ * room; a failed lookup THROWS, so the caller fails closed (retry, never mint).
+ * Same-name forks resolve to the most recently updated room (list order). */
+export async function resolveCanonicalGroup(
+ route: CanonicalGroupRoute,
+ group: string
+): Promise<CanonicalGroupBinding | null> {
+ const parsed = parseCanonicalGroupKey(group)
+ const authority = parsed ? { connectionId: parsed.connectionId, profile: parsed.profile } : route
+ const { rooms } = await discoverCanonicalGroups(authority)
+ const room = parsed ? rooms.find(r => r.room_id === parsed.roomId) : rooms.find(r => r.name === group)
+
+ if (!room) {return null}
+
+ registerCanonicalGroup(authority, room)
+ const binding = { ...authority, roomId: room.room_id, roomName: room.name }
+ $canonicalGroupBindings.set({ ...$canonicalGroupBindings.get(), [group]: binding })
+
+ return binding
+}
+
export function CanonicalGroupList({ onOpen }: { onOpen: (key: string) => void }) {
const labels = useCanonicalGroupLabels()
const connectionId = useValue(host.state.connectionId)
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
new file mode 100644
index 00000000000..96e8224a447
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-reopen-by-name.test.tsx
@@ -0,0 +1,136 @@
+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 { $canonicalGroupBindings } from './canonical-group-registry'
+import { $botMeta } from './data'
+import { $groupChats, $groupChatWorkspace } from './group-chat'
+import type * as GroupChatParts from './group-chat-parts'
+import { GroupChatWorkspace } from './group-chat-view'
+import { translateBots } from './i18n-test-helper'
+
+// #140805: after a Desktop restart the in-memory room_id-keyed bindings are
+// empty, so opening a group by NAME (roster row, restored tab) used to reach
+// the gate whose only action minted a fresh room via groups.create.
+const { request, notify, openWorkspace } = vi.hoisted(() => ({ request: vi.fn(), notify: vi.fn(), openWorkspace: vi.fn() }))
+vi.mock('@hermes/plugin-sdk', async importOriginal => {
+ const sdk = await importOriginal<typeof HermesSdk>()
+ const { en } = await import('@/i18n/en')
+
+ return {
+ ...sdk,
+ gatewayActivationEpoch: () => 1,
+ 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-parts', async importOriginal => ({
+ ...await importOriginal<typeof GroupChatParts>(),
+ 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 members = roster.map(m => ({ member_id: m.name, profile: m.name, handle: m.name }))
+const original = { room_id: 'room-original', name: 'Team', members }
+
+beforeEach(() => {
+ 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)
+ Element.prototype.scrollIntoView = vi.fn()
+})
+afterEach(() => {
+ cleanup()
+ localStorage.clear()
+ vi.restoreAllMocks()
+})
+
+function gateway(list: (params: Record<string, unknown>) => unknown) {
+ request.mockImplementation(async (_route, method, params) => {
+ if (method === 'groups.capabilities') {return { driver: true, persistent_process: true }}
+
+ if (method === 'groups.list') {return list(params)}
+
+ if (method === 'groups.create') {return { room: { room_id: params.room_id, name: params.name, members: params.members } }}
+
+ if (method === 'groups.state') {return { room: { ...original, latest_seq: 0 }, driver_status: {} }}
+
+ if (method === 'groups.log') {return { events: [] }}
+
+ throw new Error(`Unexpected RPC: ${method}`)
+ })
+}
+
+const methods = () => request.mock.calls.map(call => call[1])
+
+it('adopts the existing gateway room by name instead of minting a fork', async () => {
+ gateway(() => ({ rooms: [{ room_id: 'other', name: 'Elsewhere', members }, original], next_offset: null }))
+ await act(async () => { render(<GroupChatWorkspace group="Team" members={roster} />) })
+ expect(methods()).not.toContain('groups.create')
+ expect(screen.queryByRole('button', { name: 'Start gateway group' })).toBeNull()
+ const stateCall = request.mock.calls.find(call => call[1] === 'groups.state')
+ expect(stateCall?.[2]).toMatchObject({ room_id: 'room-original' })
+})
+
+it('adopts a restored canonical tab key whose binding was lost with the restart', async () => {
+ gateway(() => ({ rooms: [original], next_offset: null }))
+ await act(async () => { render(<GroupChatWorkspace group="canonical:local:default:room-original" members={[]} />) })
+ expect(methods()).not.toContain('groups.create')
+ expect(request.mock.calls.find(call => call[1] === 'groups.state')?.[2]).toMatchObject({ room_id: 'room-original' })
+})
+
+it('fails closed with a retry when the room lookup fails: retry, never mint', async () => {
+ let fail = true
+ gateway(() => {
+ if (fail) {throw new Error('gateway warming up')}
+
+ return { rooms: [original], next_offset: null }
+ })
+ await act(async () => { render(<GroupChatWorkspace group="Team" members={roster} />) })
+ expect(screen.getByRole('alert').textContent).toContain('gateway warming up')
+ const start = screen.queryByRole('button', { name: 'Start gateway group' }) as HTMLButtonElement | null
+ expect(start === null || start.disabled).toBe(true)
+
+ if (start) {await act(async () => { fireEvent.click(start) })}
+ expect(methods()).not.toContain('groups.create')
+
+ fail = false
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Retry' })) })
+ expect(methods()).not.toContain('groups.create')
+ expect(request.mock.calls.find(call => call[1] === 'groups.state')?.[2]).toMatchObject({ room_id: 'room-original' })
+})
+
+it('still offers to start a gateway group for a legacy room with no gateway room of that name', async () => {
+ gateway(() => ({ rooms: [{ room_id: 'other', name: 'Elsewhere', members }], next_offset: null }))
+ await act(async () => { render(<GroupChatWorkspace group="Team" members={roster} />) })
+ const start = screen.getByRole('button', { name: 'Start gateway group' }) as HTMLButtonElement
+ expect(start.disabled).toBe(false)
+ await act(async () => { fireEvent.click(start) })
+ expect(methods().filter(m => m === 'groups.create')).toHaveLength(1)
+})
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 29094b43ea9..16d57830955 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -42,7 +42,7 @@ 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 { $canonicalGroupBindings, parseCanonicalGroupKey, registerCanonicalGroup, resolveCanonicalGroup } from './canonical-group-registry'
import { CanonicalGroupWorkspace } from './canonical-group-workspace'
import { canonicalGroupRequest, createCanonicalGroup } from './canonical-groups'
import {
@@ -593,6 +593,27 @@ function GroupExecutionGate(props: GroupChatWorkspaceProps) {
const mode = capability?.source === source ? capability.mode : 'checking'
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
+ // #140805: 'found' means the binding was adopted and the workspace re-renders
+ // onto it; only 'missing' (the authority answered, no such room) may offer creation.
+ const [lookup, setLookup] = useState<{ source: string; status: 'pending' | 'missing' | 'failed' } | null>(null)
+ const [lookupAttempt, setLookupAttempt] = useState(0)
+ const lookupStatus = lookup?.source === source ? lookup.status : 'pending'
+ useEffect(() => {
+ if (mode !== 'canonical') {return}
+ let cancelled = false
+ setLookup({ source, status: 'pending' })
+ setError('')
+ void resolveCanonicalGroup({ connectionId: connectionId ?? '', profile }, props.group)
+ .then(binding => { if (!cancelled && !binding) {setLookup({ source, status: 'missing' })} })
+ .catch(e => {
+ if (!cancelled) {
+ setLookup({ source, status: 'failed' })
+ setError(e instanceof Error ? e.message : String(e))
+ }
+ })
+
+ return () => { cancelled = true }
+ }, [mode, source, props.group, lookupAttempt, connectionId, profile])
useEffect(() => {
let cancelled = false
setCapability(null)
@@ -618,16 +639,28 @@ function GroupExecutionGate(props: GroupChatWorkspaceProps) {
if (mode === 'legacy') {return <LegacyGroupChatWorkspace {...props} />}
+ // A `canonical:` key names an existing room; it never seeds a new one.
+ const canCreate = mode === 'canonical' && lookupStatus === 'missing' && parseCanonicalGroupKey(props.group) === null
+
+ const message = mode !== 'canonical'
+ ? mode === 'unavailable' ? b.canonical.driverUnavailable : 'Checking group driver…'
+ : lookupStatus === 'pending' ? 'Opening gateway group…'
+ : lookupStatus === 'failed' ? 'Could not look up this group on the gateway. Try again.'
+ : canCreate ? 'This is a legacy Desktop room. Start a gateway-owned group with these members; the old history stays here and is not replayed.'
+ : 'This gateway group no longer exists.'
+
return <div className="grid gap-3 p-3">
<h2>{props.group}</h2>
- <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>
+ <p>{message}</p>
{error && <p role="alert">{error}</p>}
- <Button disabled={mode !== 'canonical' || busy} onClick={() => {
+ {mode === 'canonical' && lookupStatus !== 'pending' && !canCreate &&
+ <Button onClick={() => setLookupAttempt(value => value + 1)} variant="secondary">Retry</Button>}
+ <Button disabled={!canCreate || busy} onClick={() => {
const route = { connectionId: connectionId ?? '', profile }
const sourceCurrent = groupCreationSource(route, activationEpoch)
- if (mode !== 'canonical' || !sourceCurrent()) {
+ if (!canCreate || !sourceCurrent()) {
setError(b.canonical.driverUnavailable)
return