The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): journal canonical group sends before admission
Teknium3d1cb4e0e88d
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.test.tsnew file mode 100644index 00000000000..b1e06c2a902--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.test.ts@@ -0,0 +1,69 @@+// @vitest-environment node+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++import { afterEach, expect, test, vi } from 'vitest'++vi.mock('electron', () => ({ app: {}, ipcMain: {} }))+// Keep native implementation out of the renderer TypeScript project while+// exercising the real atomic-file implementation in this Node fixture.+const nativeModule = '../../../electron/prepared-submissions'+const { preparedJournal } = await import(/* @vite-ignore */ nativeModule)+import { prepareCanonicalGroupSend, readCanonicalGroupSend, retireCanonicalGroupSend } from './canonical-group-send'++const binding = { connectionId: 'remote-a', profile: 'profile-a', roomId: 'room-a' }+afterEach(() => vi.unstubAllGlobals())++test('uncertain sends reopen with exact identity and attachments, isolated by authority, until matching ACK retirement', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'group-send-journal-'))+ const reopen = () => {+ const journal = preparedJournal(dir, 'http://localhost:5174')+ vi.stubGlobal('window', { hermesDesktop: { preparedSubmissions: {+ read: async () => JSON.stringify(journal.read()),+ update: async (key: string, entry: string | null) => journal.update(key, entry === null ? null : JSON.parse(entry))+ } } })+ }+ try {+ reopen()+ const payload = { text: 'Ω\n exact', attachments: [{ path: '/owner/cache/image.png', mime_type: 'image/png' }] }+ const prepared = await prepareCanonicalGroupSend(binding, payload)+ expect(prepared.params.event_id).toBeTruthy()+ expect(prepared.params.payload.thread_id).toBe(prepared.params.event_id)+ const expected = JSON.parse(JSON.stringify(prepared))+ payload.attachments[0].path = '/mutated'+ reopen() // The server ACK was lost; no retirement has happened.+ expect(await readCanonicalGroupSend(binding)).toEqual(expected)+ expect(await prepareCanonicalGroupSend(binding, { text: 'new draft must not replace uncertain input' })).toEqual(expected)+ for (const other of [{ ...binding, profile: 'other' }, { ...binding, roomId: 'other' }, { ...binding, connectionId: 'other' }]) {+ expect(await readCanonicalGroupSend(other)).toBeUndefined()+ }+ await retireCanonicalGroupSend(binding, 'stale-ack')+ expect(await readCanonicalGroupSend(binding)).toEqual(expected)+ await retireCanonicalGroupSend(binding, expected.params.event_id)+ reopen()+ expect(await readCanonicalGroupSend(binding)).toBeUndefined()+ expect((await prepareCanonicalGroupSend(binding, { text: 'fresh intent' })).params.event_id).not.toBe(expected.params.event_id)+ } finally { fs.rmSync(dir, { recursive: true, force: true }) }+})++test('native journal acknowledgement gates send and a failed write cannot downgrade to browser storage', async () => {+ let acknowledge!: () => void+ let entered!: () => void+ const writing = new Promise<void>(resolve => { entered = resolve })+ const gate = new Promise<void>(resolve => { acknowledge = resolve })+ const native = { read: async () => '{}', update: vi.fn(() => { entered(); return gate }) }+ const browserWrite = vi.fn()+ vi.stubGlobal('window', { hermesDesktop: { preparedSubmissions: native }, localStorage: { setItem: browserWrite } })+ const send = vi.fn()+ const pending = prepareCanonicalGroupSend(binding, { text: 'before network' }).then(send)+ await writing+ expect(send).not.toHaveBeenCalled()+ acknowledge()+ await pending+ expect(send).toHaveBeenCalledOnce()+ native.update.mockRejectedValueOnce(new Error('disk full'))+ await expect(prepareCanonicalGroupSend(binding, { text: 'blocked' }).then(send)).rejects.toThrow('disk full')+ expect(send).toHaveBeenCalledOnce()+ expect(browserWrite).not.toHaveBeenCalled()+})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.tsnew file mode 100644index 00000000000..a8fd95ac2bc--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts@@ -0,0 +1,94 @@+import type { CanonicalGroupBinding } from './canonical-groups'++const STORAGE_KEY = 'hermes.desktop.canonicalGroupSends.v1'++export interface PreparedCanonicalGroupSend {+ binding: CanonicalGroupBinding+ params: {+ room_id: string+ event_id: string+ payload: Record<string, unknown>+ }+}++function journalKey(binding: CanonicalGroupBinding): string {+ if (![binding.connectionId, binding.profile, binding.roomId].every(value => typeof value === 'string' && value.trim())) {+ throw new Error('Canonical group Send requires an explicit connection, profile and room')+ }++ // A separate namespace inside the existing origin-scoped native journal.+ return JSON.stringify(['canonical-group-send-v1', binding.connectionId, binding.profile, binding.roomId])+}++async function readJournal(): Promise<Record<string, PreparedCanonicalGroupSend>> {+ const native = window.hermesDesktop?.preparedSubmissions+ const parsed: unknown = JSON.parse(native+ ? await native.read()+ : window.localStorage.getItem(STORAGE_KEY) || '{}')++ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('Invalid canonical group Send journal')+ }++ return parsed as Record<string, PreparedCanonicalGroupSend>+}++async function update(key: string, entry: PreparedCanonicalGroupSend | null): Promise<void> {+ const native = window.hermesDesktop?.preparedSubmissions++ if (native) {+ // Await private atomic-file publication before the caller may send. Never+ // downgrade a native write failure to Chromium's deferred localStorage.+ await native.update(key, entry === null ? null : JSON.stringify(entry))++ return+ }++ // Browser-only fallback guarantees reload recovery, not process-crash safety.+ const journal = await readJournal()+ if (entry === null) {delete journal[key]}+ else {journal[key] = entry}+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(journal))+}++export async function readCanonicalGroupSend(binding: CanonicalGroupBinding): Promise<PreparedCanonicalGroupSend | undefined> {+ const key = journalKey(binding)+ const entry = (await readJournal())[key]++ if (entry && (journalKey(entry.binding) !== key || entry.params.room_id !== binding.roomId ||+ !entry.params.event_id || !entry.params.payload || typeof entry.params.payload !== 'object')) {+ throw new Error('Invalid canonical group Send entry')+ }++ return entry+}++// One unresolved intent per room. This is not an automatic outbox: callers show+// the recovered payload and explicitly retry it rather than silently replacing it.+export async function prepareCanonicalGroupSend(+ binding: CanonicalGroupBinding,+ payload: Record<string, unknown>+): Promise<PreparedCanonicalGroupSend> {+ const existing = await readCanonicalGroupSend(binding)+ if (existing) {return existing}++ const eventId = crypto.randomUUID()+ const entry: PreparedCanonicalGroupSend = JSON.parse(JSON.stringify({+ binding,+ params: {+ room_id: binding.roomId,+ event_id: eventId,+ payload: { ...payload, thread_id: payload.thread_id ?? eventId }+ }+ }))+ await update(journalKey(binding), entry)++ return entry+}++// Call only after a definitive groups.send ACK; timeout/unknown retains the+// exact event and payload. A delayed ACK cannot retire a newer intent.+export async function retireCanonicalGroupSend(binding: CanonicalGroupBinding, eventId: string): Promise<void> {+ const entry = await readCanonicalGroupSend(binding)+ if (entry?.params.event_id === eventId) {await update(journalKey(binding), null)}+}