The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: restore durable hosted group sends before enabling input
Tekniumd31621559f82
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsxindex 3bbc8728cff..c5178281b7f 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-registry.tsx@@ -1,6 +1,7 @@import { atom, Button, host, useValue } from '@hermes/plugin-sdk'import { useEffect, useState } from 'react'+import { useCanonicalGroupLabels } from './canonical-group-labels'import { captureCanonicalGroupRoute, discoverCanonicalGroups } from './canonical-groups'import type { CanonicalGroupBinding, CanonicalGroupRoute, CanonicalRoom } from './canonical-groups'@@ -14,6 +15,7 @@ export function registerCanonicalGroup(route: CanonicalGroupRoute, room: Canonic}export function CanonicalGroupList({ onOpen }: { onOpen: (key: string) => void }) {+ const labels = useCanonicalGroupLabels()const connectionId = useValue(host.state.connectionId)const profile = useValue(host.state.profile)const [rooms, setRooms] = useState<Array<{ key: string; name: string }>>([])@@ -34,7 +36,7 @@ export function CanonicalGroupList({ onOpen }: { onOpen: (key: string) => void }}, [connectionId, profile, refresh])return <div className="grid gap-1 px-2">- <Button onClick={() => setRefresh(value => value + 1)} variant="ghost">Refresh gateway groups</Button>+ <Button onClick={() => setRefresh(value => value + 1)} variant="ghost">{labels.refreshGroups}</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.tsxindex 181e81b28b8..b5c1242bdb2 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx@@ -2,21 +2,99 @@ 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'+import { afterEach, beforeEach, 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()+ const { en } = await import('@/i18n/en')+ const { CANONICAL_GROUP_LOCALES } = await import('./canonical-group-locales')return { ...await pluginSdkMock(gateway.host), atom, useValue: useStore,+ useI18n: () => ({ t: en }),+ usePluginI18n: () => (key: string) => CANONICAL_GROUP_LOCALES.en[key.replace('canonical.', '') as keyof typeof CANONICAL_GROUP_LOCALES.en] ?? key,Button: (p: ComponentProps<'button'>) => <button {...p} />,host: { ...gateway.host, requestProfile: request } }})import { registerCanonicalGroup } from './canonical-group-registry'+import { prepareCanonicalGroupSend, readCanonicalGroupSend } from './canonical-group-send'import { CanonicalGroupWorkspace } from './canonical-group-workspace'import { GroupChatWorkspace } from './group-chat-view'-afterEach(() => { cleanup(); request.mockReset() })+const originalDesktop = window.hermesDesktop+beforeEach(() => { Object.defineProperty(window, 'hermesDesktop', { configurable: true, writable: true, value: undefined }) })+afterEach(() => { cleanup(); request.mockReset(); localStorage.clear(); window.hermesDesktop = originalDesktop })++it('restores a frozen send after remount and retires only its acknowledged exact retry', async () => {+ const binding = { connectionId: 'remote', profile: 'team', roomId: 'restore' }+ const entry = await prepareCanonicalGroupSend(binding, { text: 'Original', attachments: [{ path: '/owner/image.png', mime_type: 'image/png' }] })+ request.mockImplementation(async (_route, method) => {+ if (method === 'groups.state') {return { room: { name: 'Room' }, driver_status: {} }}++ if (method === 'groups.log') {return { events: [] }}++ if (method === 'groups.send') {throw new Error('lost ACK')}++ return {}+ })+ const first = render(<CanonicalGroupWorkspace binding={binding} />)+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('Original'))+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).disabled).toBe(true)+ expect(request.mock.calls.some(c => c[1] === 'groups.send')).toBe(false)+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))+ await screen.findByText('lost ACK')+ expect(await readCanonicalGroupSend(binding)).toEqual(entry)+ first.unmount()+ render(<CanonicalGroupWorkspace binding={binding} />)+ await screen.findByRole('button', { name: 'Retry' })+ request.mockImplementation(async (_route, method) => method === 'groups.state'+ ? { room: { name: 'Room' }, driver_status: {} } : method === 'groups.log' ? { events: [] } : {})+ await waitFor(() => expect((screen.getByRole('button', { name: 'Retry' }) as HTMLButtonElement).disabled).toBe(false))+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))+ await waitFor(async () => expect(await readCanonicalGroupSend(binding)).toBeUndefined())+ const sends = request.mock.calls.filter(c => c[1] === 'groups.send')+ expect(sends).toHaveLength(2)++ for (const call of sends) {+ expect(call[0]).toMatchObject({ connectionId: binding.connectionId, targetProfile: binding.profile })+ expect(call[2]).toEqual({ ...entry.params, profile: binding.profile })+ }+})++it('blocks Send until journal restore and durable preparation complete', async () => {+ let releaseRead!: (value: string) => void+ let releaseWrite!: () => void+ const journal: Record<string, unknown> = {}++ const native = {+ read: vi.fn().mockImplementationOnce(() => new Promise<string>(resolve => { releaseRead = resolve }))+ .mockImplementation(async () => JSON.stringify(journal)),+ update: vi.fn(async (key: string, value: string | null) => {+ await new Promise<void>(resolve => { releaseWrite = resolve })++ if (value === null) {delete journal[key]} else {journal[key] = JSON.parse(value)}+ })+ }++ window.hermesDesktop = { preparedSubmissions: native } as unknown as typeof window.hermesDesktop+ request.mockImplementation(async (_route, method) => method === 'groups.state'+ ? { room: { name: 'Room' }, driver_status: {} } : method === 'groups.log' ? { events: [] } : {})+ render(<CanonicalGroupWorkspace binding={{ connectionId: 'remote', profile: 'team', roomId: 'new' }} />)+ await screen.findByText('Room')+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'New text' } })+ expect((screen.getByRole('button', { name: 'Send' }) as HTMLButtonElement).disabled).toBe(true)+ releaseRead('{}')+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).disabled).toBe(false))+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'New text' } })+ fireEvent.click(screen.getByRole('button', { name: 'Send' }))+ await waitFor(() => expect(native.update).toHaveBeenCalled())+ expect(request.mock.calls.some(c => c[1] === 'groups.send')).toBe(false)+ releaseWrite()+ await waitFor(() => expect(request.mock.calls.some(c => c[1] === 'groups.send')).toBe(true))+ await waitFor(() => expect(native.update).toHaveBeenCalledTimes(2))+ releaseWrite()+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(''))+})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 }diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsxindex 295baf3de24..66087f74e6c 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.tsx@@ -1,6 +1,9 @@import { Button } from '@hermes/plugin-sdk'import { useEffect, useRef, useState } from 'react'+import { useCanonicalGroupLabels } from './canonical-group-labels'+import { prepareCanonicalGroupSend, readCanonicalGroupSend, retireCanonicalGroupSend } from './canonical-group-send'+import type { PreparedCanonicalGroupSend } from './canonical-group-send'import { actCanonicalGroup, canonicalGroupRequest } from './canonical-groups'import type { CanonicalGroupBinding, CanonicalPendingAction } from './canonical-groups'@@ -14,20 +17,43 @@ export function CanonicalGroupWorkspace({ binding, visible = true, onBack }: {return <CanonicalRoomView binding={binding} key={JSON.stringify(binding)} onBack={onBack} visible={visible} />}-function CanonicalRoomView({ binding, visible, onBack }: {+function CanonicalRoomView({ binding: initialBinding, visible, onBack }: {binding: CanonicalGroupBinding; visible: boolean; onBack?: () => void}) {+ const [binding] = useState(() => ({ ...initialBinding }))+ const labels = useCanonicalGroupLabels()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 [attachments, setAttachments] = useState<Record<string, unknown>[]>([])+ const [restored, setRestored] = useState(false)+ const [pending, setPending] = useState<PreparedCanonicalGroupSend | null>(null)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)++ // eslint-disable-next-line no-restricted-syntax -- journal hydration and mounted lifetime, not a reactive store mirror+ useEffect(() => {+ alive.current = true+ let cancelled = false+ void readCanonicalGroupSend(binding).then(entry => {+ if (cancelled) {return}++ if (entry) {+ setPending(entry)+ setDraft(String(entry.params.payload.text ?? ''))+ setAttachments((entry.params.payload.attachments as Record<string, unknown>[] | undefined) ?? [])+ }++ setRestored(true)+ }).catch(e => { if (!cancelled) {setError(e instanceof Error ? e.message : String(e))} })++ return () => { cancelled = true; alive.current = false; revision.current++ }+ }, [binding])const refresh = async () => {const version = ++revision.current@@ -42,7 +68,7 @@ function CanonicalRoomView({ binding, visible, onBack }: {if (!page.has_more) {break}const next = page.events.at(-1)?.seq- if (!next || next <= cursor) {throw new Error('Invalid room log cursor')}+ if (!next || next <= cursor) {throw new Error(labels.invalidLogCursor)}cursor = next}@@ -53,10 +79,7 @@ function CanonicalRoomView({ binding, visible, onBack }: {}}- // eslint-disable-next-line no-restricted-syntax -- mounted lifetime guard, not a reactive store mirroruseEffect(() => {- alive.current = true-if (!visible) {return}let cancelled = falselet timer: ReturnType<typeof setTimeout>@@ -69,7 +92,7 @@ function CanonicalRoomView({ binding, visible, onBack }: {void poll()- return () => { cancelled = true; alive.current = false; revision.current++; clearTimeout(timer) }+ return () => { cancelled = true; revision.current++; clearTimeout(timer) }// The keyed parent freezes the authority binding for this lifetime.// eslint-disable-next-line react-hooks/exhaustive-deps}, [visible])@@ -80,11 +103,31 @@ function CanonicalRoomView({ binding, visible, onBack }: {setBusy(true)setError('')- try { await operation(); await refresh() }+ try { await operation();++ if (alive.current) {await refresh()} }catch (e) { if (alive.current) {setError(e instanceof Error ? e.message : String(e))} }- finally { busyRef.current = false;+ finally {+ busyRef.current = false- if (alive.current) {setBusy(false)} }+ if (alive.current) {setBusy(false)}+ }+ }++ const send = () => {+ if (!restored || busyRef.current || !state?.driver_status || (!pending && !draft.trim() && !attachments.length)) {return}+ void mutate(async () => {+ const exact = pending ?? await prepareCanonicalGroupSend(binding, { text: draft, attachments })++ if (!alive.current) {return}+ setPending(exact)+ setDraft(String(exact.params.payload.text ?? ''))+ setAttachments((exact.params.payload.attachments as Record<string, unknown>[] | undefined) ?? [])+ await canonicalGroupRequest(exact.binding, 'groups.send', exact.params)+ await retireCanonicalGroupSend(exact.binding, exact.params.event_id)++ if (alive.current) {setPending(null); setDraft(''); setAttachments([])}+ })}const act = (action: CanonicalPendingAction, choice?: 'once' | 'deny') =>@@ -92,50 +135,31 @@ function CanonicalRoomView({ binding, visible, onBack }: {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>+ {onBack && <Button onClick={onBack}>{labels.back}</Button>}+ <h2>{state?.room.name || labels.loadingGroup}</h2>+ <Button disabled={busy || !state?.driver_status} onClick={() => void mutate(() => canonicalGroupRequest(binding, 'groups.stop', { room_id: binding.roomId, cancel_id: crypto.randomUUID() }))}>{labels.stop}</Button></header>- {readError && <div role="alert">{readError}<Button onClick={() => void refresh().catch(e => setReadError(String(e)))}>Refresh</Button></div>}+ {readError && <div role="alert">{readError}<Button onClick={() => void refresh().catch(e => setReadError(String(e)))}>{labels.refresh}</Button></div>}{error && <div role="alert">{error}</div>}- {state && !state.driver_status && <p>Group driver unavailable. Update or reconnect the owning gateway.</p>}+ {state && !state.driver_status && <p>{labels.driverUnavailable}</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></>}+ {action.kind === 'discard' && <Button disabled={busy} onClick={() => setDiscard({ ...action })}>{labels.discard}</Button>}+ {action.kind === 'retry' && <Button disabled={busy} onClick={() => void act({ ...action })}>{labels.retry}</Button>}+ {action.kind === 'approval' && <><Button disabled={busy} onClick={() => void act({ ...action }, 'once')}>{labels.allowOnce}</Button><Button disabled={busy} onClick={() => void act({ ...action }, 'deny')}>{labels.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>+ {discard && <div aria-label={labels.discardUnknown} role="alertdialog">+ <p>{labels.discardWarning}</p>+ <Button disabled={busy} onClick={() => { const exact = discard; setDiscard(null); void act(exact) }}>{labels.confirmDiscard}</Button>+ <Button onClick={() => setDiscard(null)}>{labels.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>+ {pending && <p role="status">{labels.restoredPendingSend}</p>}+ <form className="flex gap-2" onSubmit={event => { event.preventDefault(); send() }}>+ <textarea aria-label={labels.groupMessage} className="min-w-0 flex-1" disabled={!restored || busy || !!pending} onChange={e => setDraft(e.target.value)} value={draft} />+ <Button disabled={!restored || busy || (!pending && !draft.trim() && !attachments.length) || !state?.driver_status} type="submit">{pending ? labels.retry : labels.send}</Button></form></section>}