Skip to content

The agent that grows with you

feat: connect Desktop groups to canonical driver controls

Teknium3c2c9d470a7a
diff --git a/apps/desktop/docs/canonical-groups.md b/apps/desktop/docs/canonical-groups.md
new file mode 100644
index 00000000000..9b67d90fc8c
--- /dev/null
+++ b/apps/desktop/docs/canonical-groups.md
@@ -0,0 +1,9 @@
+# Gateway-owned groups in Desktop
+
+Bot Mode lists gateway rooms separately from legacy renderer rooms. Refresh gateway groups reloads the selected connection/profile's canonical room list. Opening a room captures that exact authority; changing the foreground profile does not retarget its controls.
+
+With `groups.capabilities.driver` enabled, the existing creation dialog creates a canonical group. Only same-authority local-profile members are supported; Desktop connection descriptors are not peer grants. Existing legacy rooms offer **Start gateway group** instead of renderer-owned execution. This starts a new room and deliberately does not replay legacy history.
+
+The gateway owns the log and work. Desktop reads `groups.state` and `groups.log`, sends through `groups.send`, and stops through `groups.stop`. Pending actions come only from `driver_status.pending_actions`. Discard requires explicit confirmation that prior side effects are not undone; Retry and approvals retain the exact member/task/generation/request identity. Errors remain visible and no failed canonical mutation falls back to hidden-session submission.
+
+This initial canonical workspace is text-only. Rename, disband, membership editing and attachments are not offered here. Room discovery is durable on the gateway rather than replicated through Desktop ui_meta. Ambiguous send retries preserve their event identity while the workspace remains mounted; native crash-safe group-send journaling is not implemented.
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx
new file mode 100644
index 00000000000..3bbc8728cff
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx
@@ -0,0 +1,41 @@
+import { atom, Button, host, useValue } from '@hermes/plugin-sdk'
+import { useEffect, useState } from 'react'
+
+import { captureCanonicalGroupRoute, discoverCanonicalGroups } from './canonical-groups'
+import type { CanonicalGroupBinding, CanonicalGroupRoute, CanonicalRoom } from './canonical-groups'
+
+export const $canonicalGroupBindings = atom<Record<string, CanonicalGroupBinding>>({})
+
+export function registerCanonicalGroup(route: CanonicalGroupRoute, room: CanonicalRoom): string {
+ const key = `canonical:${encodeURIComponent(route.connectionId)}:${encodeURIComponent(route.profile)}:${room.room_id}`
+ $canonicalGroupBindings.set({ ...$canonicalGroupBindings.get(), [key]: { ...route, roomId: room.room_id } })
+
+ return key
+}
+
+export function CanonicalGroupList({ onOpen }: { onOpen: (key: string) => void }) {
+ const connectionId = useValue(host.state.connectionId)
+ const profile = useValue(host.state.profile)
+ const [rooms, setRooms] = useState<Array<{ key: string; name: string }>>([])
+ const [error, setError] = useState('')
+ const [refresh, setRefresh] = useState(0)
+ useEffect(() => {
+ let cancelled = false
+ setRooms([])
+ setError('')
+ void (async () => {
+ const route = captureCanonicalGroupRoute()
+ const result = await discoverCanonicalGroups(route)
+
+ if (!cancelled) {setRooms(result.rooms.map(room => ({ key: registerCanonicalGroup(route, room), name: room.name })))}
+ })().catch(e => { if (!cancelled) {setError(e instanceof Error ? e.message : String(e))} })
+
+ return () => { cancelled = true }
+ }, [connectionId, profile, refresh])
+
+ return <div className="grid gap-1 px-2">
+ <Button onClick={() => setRefresh(value => value + 1)} variant="ghost">Refresh gateway groups</Button>
+ {error && <p role="alert">{error}</p>}
+ {rooms.map(room => <Button key={room.key} onClick={() => onOpen(room.key)} variant="ghost">{room.name}</Button>)}
+ </div>
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx
new file mode 100644
index 00000000000..181e81b28b8
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx
@@ -0,0 +1,62 @@
+import { useStore } from '@nanostores/react'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { atom } from 'nanostores'
+import type { ComponentProps } from 'react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+const request = vi.hoisted(() => vi.fn())
+vi.mock('@hermes/plugin-sdk', async () => {
+ const { pluginSdkMock, createGroupGateway } = await import('./group-test-utils')
+ const gateway = createGroupGateway()
+
+ return { ...await pluginSdkMock(gateway.host), atom, useValue: useStore,
+ Button: (p: ComponentProps<'button'>) => <button {...p} />,
+ host: { ...gateway.host, requestProfile: request } }
+})
+import { registerCanonicalGroup } from './canonical-group-registry'
+import { CanonicalGroupWorkspace } from './canonical-group-workspace'
+import { GroupChatWorkspace } from './group-chat-view'
+afterEach(() => { cleanup(); request.mockReset() })
+
+it('captures exact pending attempts through confirmation and never retargets or retries unknown work', async () => {
+ const action = { kind: 'discard', member_id: 'worker', task_id: 'old-task', execution_generation: 7 }
+ request.mockImplementation(async (_route, method) => {
+ if (method === 'groups.state') {return { room: { name: 'Room' }, driver_status: { pending_actions: [action] } }}
+
+ if (method === 'groups.log') {return { events: [], has_more: false }}
+
+ if (method === 'groups.discard') {throw new Error('stale_attempt')}
+
+ return {}
+ })
+ render(<CanonicalGroupWorkspace binding={{ connectionId: 'remote', profile: 'team', roomId: 'ack-room' }} />)
+ fireEvent.click(await screen.findByRole('button', { name: 'Discard' }))
+ expect(screen.getByText(/Side effects may already have occurred/)).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
+ action.execution_generation = 8
+ fireEvent.click(screen.getByRole('button', { name: 'Confirm discard' }))
+ await screen.findByText('stale_attempt')
+ const call = request.mock.calls.find(c => c[1] === 'groups.discard')!
+ expect(call[0]).toMatchObject({ connectionId: 'remote', targetProfile: 'team' })
+ expect(call[2]).toEqual({ room_id: 'ack-room', member_id: 'worker', task_id: 'old-task', execution_generation: 7, profile: 'team' })
+ expect(request.mock.calls.every(c => c[1].startsWith('groups.'))).toBe(true)
+})
+
+it('reads back retry on the same authority and sends only through the group driver', async () => {
+ request.mockImplementation(async (_route, method) => {
+ if (method === 'groups.state') {return { room: { name: 'Room' }, driver_status: { pending_actions: [{ kind: 'retry', member_id: 'w', task_id: 't', execution_generation: 2 }] } }}
+
+ if (method === 'groups.log') {return { events: [{ seq: 1, kind: 'message', payload: { text: 'Owner reply' } }], has_more: false }}
+
+ return {}
+ })
+ const group = registerCanonicalGroup({ connectionId: 'local', profile: 'default' }, { room_id: 'r', name: 'Room', members: [] })
+ render(<GroupChatWorkspace group={group} members={[]} />)
+ fireEvent.click(await screen.findByRole('button', { name: 'Retry' }))
+ await waitFor(() => expect(request.mock.calls.filter(c => c[1] === 'groups.state').length).toBeGreaterThan(1))
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Hello' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Send' }))
+ await waitFor(() => expect(request.mock.calls.some(c => c[1] === 'groups.send')).toBe(true))
+ expect(screen.getByText('Owner reply')).toBeTruthy()
+ expect(request.mock.calls.every(c => c[1].startsWith('groups.'))).toBe(true)
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx
new file mode 100644
index 00000000000..295baf3de24
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx
@@ -0,0 +1,141 @@
+import { Button } from '@hermes/plugin-sdk'
+import { useEffect, useRef, useState } from 'react'
+
+import { actCanonicalGroup, canonicalGroupRequest } from './canonical-groups'
+import type { CanonicalGroupBinding, CanonicalPendingAction } from './canonical-groups'
+
+interface RoomEvent { seq: number; kind: string; payload: { text?: string; content?: string }; actor?: { member_id?: string } }
+interface RoomState { room: { name: string }; driver_status?: { pending_actions?: CanonicalPendingAction[] } }
+
+export function CanonicalGroupWorkspace({ binding, visible = true, onBack }: {
+ binding: CanonicalGroupBinding; visible?: boolean; onBack?: () => void
+}) {
+ // Remount on identity changes: old polls and pending confirmations never cross rooms.
+ return <CanonicalRoomView binding={binding} key={JSON.stringify(binding)} onBack={onBack} visible={visible} />
+}
+
+function CanonicalRoomView({ binding, visible, onBack }: {
+ binding: CanonicalGroupBinding; visible: boolean; onBack?: () => void
+}) {
+ const [state, setState] = useState<RoomState | null>(null)
+ const [events, setEvents] = useState<RoomEvent[]>([])
+ const [error, setError] = useState('')
+ const [readError, setReadError] = useState('')
+ const [draft, setDraft] = useState('')
+ const [busy, setBusy] = useState(false)
+ const busyRef = useRef(false)
+ const alive = useRef(true)
+ const [discard, setDiscard] = useState<CanonicalPendingAction | null>(null)
+ const revision = useRef(0)
+ const prepared = useRef<{ text: string; eventId: string } | null>(null)
+
+ const refresh = async () => {
+ const version = ++revision.current
+ const snapshot = await canonicalGroupRequest<RoomState>(binding, 'groups.state', { room_id: binding.roomId })
+ const log: RoomEvent[] = []
+ let cursor = 0
+
+ for (;;) {
+ const page = await canonicalGroupRequest<{ events: RoomEvent[]; has_more?: boolean; next_seq?: number }>(binding, 'groups.log', { room_id: binding.roomId, since_seq: cursor, limit: 100 })
+ log.push(...page.events)
+
+ if (!page.has_more) {break}
+ const next = page.events.at(-1)?.seq
+
+ if (!next || next <= cursor) {throw new Error('Invalid room log cursor')}
+ cursor = next
+ }
+
+ if (alive.current && version === revision.current) {
+ setState(snapshot)
+ setEvents(log)
+ setReadError('')
+ }
+ }
+
+ // eslint-disable-next-line no-restricted-syntax -- mounted lifetime guard, not a reactive store mirror
+ useEffect(() => {
+ alive.current = true
+
+ if (!visible) {return}
+ let cancelled = false
+ let timer: ReturnType<typeof setTimeout>
+
+ const poll = async () => {
+ try { await refresh() } catch (e) { if (!cancelled) {setReadError(String(e instanceof Error ? e.message : e))} }
+
+ if (!cancelled) {timer = setTimeout(() => void poll(), 2000)}
+ }
+
+ void poll()
+
+ return () => { cancelled = true; alive.current = false; revision.current++; clearTimeout(timer) }
+ // The keyed parent freezes the authority binding for this lifetime.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [visible])
+
+ const mutate = async (operation: () => Promise<unknown>) => {
+ if (busyRef.current) {return}
+ busyRef.current = true
+ setBusy(true)
+ setError('')
+
+ try { await operation(); await refresh() }
+ catch (e) { if (alive.current) {setError(e instanceof Error ? e.message : String(e))} }
+ finally { busyRef.current = false;
+
+ if (alive.current) {setBusy(false)} }
+ }
+
+ const act = (action: CanonicalPendingAction, choice?: 'once' | 'deny') =>
+ mutate(() => actCanonicalGroup(binding, action, choice))
+
+ return <section className="flex h-full min-h-0 flex-col gap-3 p-3">
+ <header className="flex items-center gap-2">
+ {onBack && <Button onClick={onBack}>Back</Button>}
+ <h2>{state?.room.name || 'Loading group…'}</h2>
+ <Button disabled={busy || !state?.driver_status} onClick={() => void mutate(() => canonicalGroupRequest(binding, 'groups.stop', { room_id: binding.roomId, cancel_id: crypto.randomUUID() }))}>Stop</Button>
+ </header>
+ {readError && <div role="alert">{readError}<Button onClick={() => void refresh().catch(e => setReadError(String(e)))}>Refresh</Button></div>}
+ {error && <div role="alert">{error}</div>}
+ {state && !state.driver_status && <p>Group driver unavailable. Update or reconnect the owning gateway.</p>}
+ <div className="min-h-0 flex-1 overflow-auto" role="log">
+ {events.map(event => <div className="whitespace-pre-wrap py-2" key={event.seq}>{event.actor?.member_id && <strong>{event.actor.member_id}: </strong>}{event.payload.text || event.payload.content || event.kind}</div>)}
+ </div>
+ {(state?.driver_status?.pending_actions || []).map(action => <div className="flex items-center gap-2" key={`${action.kind}:${action.task_id}:${action.execution_generation}`}>
+ <span>{action.member_id}</span>
+ {action.kind === 'discard' && <Button disabled={busy} onClick={() => setDiscard({ ...action })}>Discard</Button>}
+ {action.kind === 'retry' && <Button disabled={busy} onClick={() => void act({ ...action })}>Retry</Button>}
+ {action.kind === 'approval' && <><Button disabled={busy} onClick={() => void act({ ...action }, 'once')}>Allow once</Button><Button disabled={busy} onClick={() => void act({ ...action }, 'deny')}>Deny</Button></>}
+ </div>)}
+ {discard && <div aria-label="Discard unknown work" role="alertdialog">
+ <p>Side effects may already have occurred. Discarding does not undo them.</p>
+ <Button disabled={busy} onClick={() => { const exact = discard; setDiscard(null); void act(exact) }}>Confirm discard</Button>
+ <Button onClick={() => setDiscard(null)}>Cancel</Button>
+ </div>}
+ <form className="flex gap-2" onSubmit={event => {
+ event.preventDefault()
+
+ if (!draft.trim() || busyRef.current || !state?.driver_status) {return}
+ const text = draft
+
+ if (prepared.current && prepared.current.text !== text) {
+ setError('The previous send is unconfirmed. Retry its original text before sending another message.')
+
+ return
+ }
+
+ prepared.current ||= { text, eventId: crypto.randomUUID() }
+ const eventId = prepared.current.eventId
+ void mutate(async () => {
+ await canonicalGroupRequest(binding, 'groups.send', { room_id: binding.roomId, event_id: eventId, payload: { text, thread_id: eventId } })
+ prepared.current = null
+
+ if (alive.current) {setDraft(current => current === text ? '' : current)}
+ })
+ }}>
+ <textarea aria-label="Group message" className="min-w-0 flex-1" onChange={e => setDraft(e.target.value)} value={draft} />
+ <Button disabled={busy || !draft.trim() || !state?.driver_status} type="submit">Send</Button>
+ </form>
+ </section>
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts
new file mode 100644
index 00000000000..68b35fabf6b
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-groups.test.ts
@@ -0,0 +1,96 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+
+const host = vi.hoisted(() => ({
+ requestProfile: vi.fn(),
+ request: vi.fn(),
+ state: { connectionId: { get: vi.fn() }, profile: { get: vi.fn() } }
+}))
+
+vi.mock('@hermes/plugin-sdk', () => ({ host }))
+
+import { actCanonicalGroup, canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup, discoverCanonicalGroups } from './canonical-groups'
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ host.state.connectionId.get.mockReturnValue('source-a')
+ host.state.profile.get.mockReturnValue('default')
+})
+
+it('pins discovery and every subsequent request to its captured authority, including empty filtered pages', async () => {
+ const route = captureCanonicalGroupRoute()
+ const room = { room_id: 'room-a', name: 'Team', members: [] }
+ host.state.connectionId.get.mockReturnValue('source-b')
+ host.state.profile.get.mockReturnValue('other')
+ host.requestProfile.mockResolvedValueOnce({ driver: false })
+ .mockResolvedValueOnce({ rooms: [], next_offset: 100 })
+ .mockResolvedValueOnce({ rooms: [room], next_offset: null })
+ expect(await discoverCanonicalGroups(route)).toEqual({ driver: false, rooms: [room] })
+ expect(host.requestProfile.mock.calls.map(call => [call[1], call[2]])).toEqual([
+ ['groups.capabilities', { profile: 'default' }],
+ ['groups.list', { profile: 'default', limit: 100, offset: 0 }],
+ ['groups.list', { profile: 'default', limit: 100, offset: 100 }]
+ ])
+
+ for (const [target] of host.requestProfile.mock.calls) {
+ expect(target).toMatchObject({ connectionId: 'source-a', profile: 'default', targetProfile: 'default' })
+ }
+
+ host.requestProfile.mockRejectedValueOnce(new Error('owner disconnected'))
+ await expect(canonicalGroupRequest(route, 'groups.state', { room_id: room.room_id })).rejects.toThrow('owner disconnected')
+ await expect(canonicalGroupRequest({ ...route, connectionId: '' }, 'groups.list', {})).rejects.toThrow()
+ await expect(canonicalGroupRequest(route, 'groups.list', { profile: 'other' })).rejects.toThrow()
+ host.requestProfile.mockResolvedValueOnce({ driver: true }).mockResolvedValueOnce({ rooms: [], next_offset: 0 })
+ await expect(discoverCanonicalGroups(route)).rejects.toThrow('pagination')
+ expect(host.request).not.toHaveBeenCalled()
+})
+
+it('creates only same-authority rosters and dispatches exact advertised attempt identities without inference', async () => {
+ const route = captureCanonicalGroupRoute()
+
+ const members = [
+ { name: 'alice', handle: 'alice', connectionId: 'source-a', display_name: 'Alice' },
+ { name: 'desktop-bob', handle: 'bob', connectionId: 'source-a', targetProfile: 'bob' }
+ ]
+
+ host.requestProfile.mockImplementation(async (_route, method, params) => method === 'groups.create'
+ ? { room: { room_id: params.room_id, name: params.name, members: params.members } } : { accepted: true })
+ const { binding, room } = await createCanonicalGroup(route, 'Team', members)
+ expect(binding).toEqual({ ...route, roomId: room.room_id })
+ expect(room.room_id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
+ expect(room.members).toEqual([
+ { member_id: 'alice', profile: 'alice', handle: 'alice', display_name: 'Alice', target: { kind: 'local', profile: 'alice' } },
+ { member_id: 'bob', profile: 'bob', handle: 'bob', target: { kind: 'local', profile: 'bob' } }
+ ])
+
+ for (const invalid of [
+ [{ ...members[0], connectionId: 'source-b' }, members[1]],
+ [{ ...members[0], remoteSource: true, connectionId: undefined }, members[1]],
+ [{ ...members[0], route: { connectionId: 'source-b', profile: 'alice', targetProfile: 'alice', mode: 'remote' as const } }, members[1]],
+ [members[0]], [members[0], members[0]]
+ ]) {await expect(createCanonicalGroup(route, 'Team', invalid)).rejects.toThrow()}
+
+ expect(host.requestProfile).toHaveBeenCalledTimes(1)
+ host.requestProfile.mockClear()
+ const identity = { member_id: 'alice', task_id: 'task:original', execution_generation: 7 }
+
+ for (const kind of ['retry', 'discard']) {
+ await actCanonicalGroup(binding, { kind, ...identity, request_id: 'not-for-this-method' })
+ expect(host.requestProfile).toHaveBeenLastCalledWith(expect.objectContaining(route), `groups.${kind}`, {
+ profile: route.profile, room_id: binding.roomId, ...identity
+ })
+ }
+
+ await actCanonicalGroup(binding, { kind: 'approval', ...identity, request_id: 'request:original' }, 'deny')
+ expect(host.requestProfile).toHaveBeenLastCalledWith(expect.objectContaining(route), 'groups.approve', {
+ profile: route.profile, room_id: binding.roomId, ...identity, request_id: 'request:original', choice: 'deny'
+ })
+ const count = host.requestProfile.mock.calls.length
+
+ for (const action of [
+ { kind: 'approval', ...identity }, { kind: 'retry', ...identity, execution_generation: 0 },
+ { kind: 'unknown', ...identity }, { kind: 'toString', ...identity }, { kind: 'discard', ...identity, task_id: '' }
+ ]) {await expect(actCanonicalGroup(binding, action)).rejects.toThrow()}
+
+ expect(host.requestProfile).toHaveBeenCalledTimes(count)
+ expect(host.request).not.toHaveBeenCalled()
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts b/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts
new file mode 100644
index 00000000000..487b88cfd8e
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-groups.ts
@@ -0,0 +1,176 @@
+import { host } from '@hermes/plugin-sdk'
+
+import type { GroupMember } from './types'
+
+export interface CanonicalGroupRoute {
+ connectionId: string
+ profile: string
+}
+
+export interface CanonicalGroupBinding extends CanonicalGroupRoute {
+ roomId: string
+}
+
+export interface CanonicalRoomMember {
+ member_id: string
+ profile: string
+ handle: string
+ display_name?: string
+ target?: Record<string, unknown>
+}
+
+export interface CanonicalRoom {
+ room_id: string
+ name: string
+ members: CanonicalRoomMember[]
+ disbanded_at?: number | null
+}
+
+export interface CanonicalPendingAction {
+ kind: string
+ member_id: string
+ task_id: string
+ execution_generation: number
+ request_id?: string
+}
+
+function requireRoute(route: CanonicalGroupRoute): void {
+ if (!route.connectionId?.trim() || !route.profile?.trim()) {
+ throw new Error('Canonical groups require an explicit connection and profile')
+ }
+}
+
+export function captureCanonicalGroupRoute(): CanonicalGroupRoute {
+ const connectionId = host.state.connectionId.get()
+
+ if (connectionId === null) {throw new Error('Canonical groups require an explicit connection')}
+ const route = { connectionId, profile: host.state.profile.get() }
+ requireRoute(route)
+
+ return route
+}
+
+export async function canonicalGroupRequest<T>(
+ route: CanonicalGroupRoute,
+ method: string,
+ params: Record<string, unknown> = {}
+): Promise<T> {
+ requireRoute(route)
+
+ if (params.profile !== undefined && params.profile !== route.profile) {
+ throw new Error('Canonical group profile does not match its authority')
+ }
+
+ // The descriptor overload never falls back to the foreground gateway.
+ return host.requestProfile<T>({
+ connectionId: route.connectionId,
+ profile: route.profile,
+ targetProfile: route.profile,
+ mode: route.connectionId === 'local' ? 'local' : 'remote'
+ }, method, { ...params, profile: route.profile })
+}
+
+export async function discoverCanonicalGroups(
+ route: CanonicalGroupRoute
+): Promise<{ driver: boolean; rooms: CanonicalRoom[] }> {
+ const capabilities = await canonicalGroupRequest<{ driver: boolean }>(route, 'groups.capabilities')
+ const rooms: CanonicalRoom[] = []
+ let offset = 0
+
+ for (;;) {
+ const page = await canonicalGroupRequest<{ rooms: CanonicalRoom[]; next_offset: number | null }>(
+ route, 'groups.list', { limit: 100, offset }
+ )
+
+ rooms.push(...page.rooms)
+
+ if (page.next_offset === null) {break}
+
+ if (!Number.isSafeInteger(page.next_offset) || page.next_offset <= offset) {
+ throw new Error('Invalid canonical group pagination cursor')
+ }
+
+ offset = page.next_offset
+ }
+
+ return { driver: capabilities.driver === true, rooms }
+}
+
+export async function createCanonicalGroup(
+ route: CanonicalGroupRoute,
+ name: string,
+ members: GroupMember[]
+): Promise<{ binding: CanonicalGroupBinding; room: CanonicalRoom }> {
+ requireRoute(route)
+
+ if (!name.trim() || members.length < 2 || members.length > 6) {
+ throw new Error('A canonical group needs a name and two to six members')
+ }
+
+ const profiles = new Set<string>()
+ const handles = new Set(['all', 'everyone'])
+
+ const roster = members.map(member => {
+ const connectionId = member.route?.connectionId ?? member.connectionId
+
+ if ((connectionId !== undefined && connectionId !== route.connectionId) ||
+ (member.connectionId !== undefined && member.connectionId !== route.connectionId) ||
+ (connectionId === undefined && member.remoteSource)) {
+ throw new Error('Group members must belong to the same authority connection')
+ }
+
+ const profile = member.route?.targetProfile ?? member.targetProfile ?? member.name
+ const handle = member.handle ?? profile
+
+ if (!profile.trim() || !handle.trim() || profiles.has(profile.toLowerCase()) || handles.has(handle.toLowerCase())) {
+ throw new Error('Group members need unique profiles and non-reserved handles')
+ }
+
+ profiles.add(profile.toLowerCase())
+ handles.add(handle.toLowerCase())
+
+ return {
+ member_id: profile, profile, handle,
+ target: { kind: 'local', profile },
+ ...(member.display_name ? { display_name: member.display_name } : {})
+ }
+ })
+
+ const { room } = await canonicalGroupRequest<{ room: CanonicalRoom }>(route, 'groups.create', {
+ room_id: crypto.randomUUID(), name, members: roster
+ })
+
+ return { binding: { ...route, roomId: room.room_id }, room }
+}
+
+export async function actCanonicalGroup(
+ binding: CanonicalGroupBinding,
+ action: CanonicalPendingAction,
+ choice?: 'once' | 'deny'
+): Promise<Record<string, unknown>> {
+ const methods: Record<string, string> = { retry: 'groups.retry', discard: 'groups.discard', approval: 'groups.approve' }
+ const method = Object.hasOwn(methods, action.kind) ? methods[action.kind] : undefined
+
+ if (!method || !binding.roomId || !action.member_id || !action.task_id ||
+ !Number.isSafeInteger(action.execution_generation) || action.execution_generation < 1) {
+ throw new Error('Invalid canonical group pending action')
+ }
+
+ const params: Record<string, unknown> = {
+ room_id: binding.roomId,
+ member_id: action.member_id,
+ task_id: action.task_id,
+ execution_generation: action.execution_generation
+ }
+
+ if (action.kind === 'approval') {
+ if (!action.request_id || (choice !== 'once' && choice !== 'deny')) {
+ throw new Error('Approval requires its exact request ID and an explicit choice')
+ }
+
+ params.request_id = action.request_id
+ params.choice = choice
+ }
+
+ return canonicalGroupRequest(binding, method, params)
+}
diff --git a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
index 27a23a1a8cd..61204d78157 100644
--- a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx
@@ -43,6 +43,8 @@ import { isBackfilledFacePng } from './avatar-image'
import { AvatarPicker } from './avatar-picker'
import { $selectedBot } from './bot-state'
import { createCanonicalChat } from './canonical-chat'
+import { registerCanonicalGroup } from './canonical-group-registry'
+import { canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup } from './canonical-groups'
import { $botMeta, botHandle, botRosterKey, filterBots, ROSTER_KEY, saveBotMeta } from './data'
import { labeled, ResizableFrame } from './dialog-parts'
import { GROUP_CHAT_MAX_MEMBERS, mintGroupRoomId, uniqueGroupChatName, updateGroupChat } from './group-chat'
@@ -1156,13 +1158,31 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
const canCreate = selected.length >= 2 && Boolean(name.trim() || selected.length)
- const create = () => {
+ const creating = useRef(false)
+
+ const create = async () => {
+ if (creating.current) {return}
+ creating.current = true
+
+ try {
const base = (name.trim() || placeholder).slice(0, 64)
if (selected.length < 2 || !base) {
return
}
+ const route = captureCanonicalGroupRoute()
+ const capabilities = await canonicalGroupRequest<{ driver: boolean }>(route, 'groups.capabilities')
+
+ if (capabilities.driver) {
+ const created = await createCanonicalGroup(route, base, durableGroupChatMembers(selected))
+ const key = registerCanonicalGroup(route, created.room)
+ onClose()
+ onCreated?.(key)
+
+ return
+ }
+
// Creating a group is always a FRESH room. Without this, re-creating a
// group under an existing name (easy — the default name is just the
// member names) silently reopens the old room with its full log, which
@@ -1206,6 +1226,9 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea
})
onClose()
onCreated?.(groupName)
+ } catch (error) {
+ host.notify({ kind: 'error', message: error instanceof Error ? error.message : String(error) })
+ } finally { creating.current = false }
}
return (
diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-timeline.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-timeline.test.tsx
index 15da62626e2..646ac2fb7a6 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-timeline.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-timeline.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render } from '@testing-library/react'
+import { cleanup, render, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { afterEach, expect, it, vi } from 'vitest'
@@ -58,6 +58,7 @@ it('keeps every public member reply readable in room arrival order across interl
$groupChats.set({ Room: { log, watermarks: {}, sessions: {} } })
const { container } = render(<GroupChatWorkspace group="Room" members={[]} />)
+ await waitFor(() => expect(container.textContent).toContain('Build request'))
const text = container.textContent || ''
let previous = -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 c93ca55793c..26e5257d768 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx
@@ -38,6 +38,9 @@ import { useEffect, useMemo, useRef, useState } from 'react'
import { avatarColor, botAppearance, BotFace } from './avatar'
import { isBackfilledFacePng } from './avatar-image'
+import { $canonicalGroupBindings, registerCanonicalGroup } from './canonical-group-registry'
+import { CanonicalGroupWorkspace } from './canonical-group-workspace'
+import { canonicalGroupRequest, captureCanonicalGroupRoute, createCanonicalGroup } from './canonical-groups'
import {
$botMeta,
$lastRoster,
@@ -456,7 +459,48 @@ interface GroupChatWorkspaceProps {
visible?: boolean
}
-export function GroupChatWorkspace({ group, members, onBack, visible = true }: GroupChatWorkspaceProps) {
+export function GroupChatWorkspace(props: GroupChatWorkspaceProps) {
+ const bindings = useValue($canonicalGroupBindings)
+ const binding = bindings[props.group]
+
+ if (binding) {return <CanonicalGroupWorkspace binding={binding} onBack={props.onBack} visible={props.visible} />}
+
+ return <GroupExecutionGate {...props} />
+}
+
+function GroupExecutionGate(props: GroupChatWorkspaceProps) {
+ const connectionId = useValue(host.state.connectionId)
+ const profile = useValue(host.state.profile)
+ const [driver, setDriver] = useState<boolean | null>(null)
+ 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))} })
+
+ return () => { cancelled = true }
+ }, [connectionId, profile])
+
+ if (driver === false) {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>
+ {error && <p role="alert">{error}</p>}
+ <Button disabled={!driver || busy} onClick={() => {
+ 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))
+ }}>Start gateway group</Button>
+ </div>
+}
+
+function LegacyGroupChatWorkspace({ group, members, onBack, visible = true }: GroupChatWorkspaceProps) {
const b = useBots()
const rooms: Record<string, GroupChatRoom> = useValue($groupChats)
const allMeta: Record<string, BotMeta> = useValue($botMeta)
diff --git a/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx
index 352d88638eb..f631b8ccd61 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx
@@ -7,7 +7,8 @@ import type { GroupMember } from './types'
const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))
vi.mock('@hermes/plugin-sdk', async () => {
- const { pluginSdkMock } = await import('./group-test-utils')
+ const { pluginSdkMock, createGroupGateway } = await import('./group-test-utils')
+ Object.assign(host, createGroupGateway().host)
const base = await pluginSdkMock(host)
return {
@@ -161,6 +162,6 @@ describe('durable group holds', () => {
render(<GroupChatWorkspace group="Core" members={MEMBERS} />)
- expect(screen.getByRole('status').textContent).toContain('Paused: Research')
+ expect((await screen.findByRole('status')).textContent).toContain('Paused: Research')
})
})
diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
index da258c74745..9b95748bfec 100644
--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts
@@ -419,6 +419,8 @@ export async function stopGroupThread(group: string, thread: null | string, memb
* Watermarks are per thread+member (`${thread}::${memberKey}`), so parallel
* topics never eat each other's deltas. */
export async function runGroupChatRounds(group: string, members: GroupMember[], thread: string) {
+ if (group.startsWith('canonical:')) {throw new Error('Canonical rooms are driven by the gateway')}
+
const binding = followGroupChat(group, name => {
group = name
})
@@ -661,6 +663,7 @@ export function sendToGroupChat(
thread?: null | string,
images?: Attachment[]
): null | string {
+ if (group.startsWith('canonical:')) {throw new Error('Canonical rooms are driven by the gateway')}
const trimmed = String(text || '').trim()
const attached = Array.isArray(images) ? images.filter((img: Attachment) => img && img.data) : []
diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
index e52f51ee4c9..e9562a1c49b 100644
--- a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx
@@ -15,6 +15,7 @@ import {
parseRosterKey,
saveSelectedRosterBot
} from './bot-state'
+import { CanonicalGroupList } from './canonical-group-registry'
/**
* The Bots pane itself: the roster's selection reconciliation, the
* workspace-ownership reads its lifecycle keys off, and the pane that lists
@@ -450,6 +451,7 @@ export function BotsPane() {
return (
<div className="flex h-full flex-col">
+ <CanonicalGroupList onOpen={openGroupChat} />
{renderRosterToolbar({
b,
activityToasts,