The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): group Send prepares and retires its room slot atomically at the native journal
Teknium4149282e4946
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 71ff3b825c6..c5ab6019597 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -432,7 +432,9 @@ contextBridge.exposeInMainWorld('hermesDesktop', {},preparedSubmissions: {read: () => ipcRenderer.invoke('hermes:prepared-submissions:read'),- update: (key, entry) => ipcRenderer.invoke('hermes:prepared-submissions:update', key, entry)+ update: (key, entry) => ipcRenderer.invoke('hermes:prepared-submissions:update', key, entry),+ compareAndSet: (key, expected, entry) =>+ ipcRenderer.invoke('hermes:prepared-submissions:compare-and-set', key, expected, entry)},zoom: {// Current zoom of this window, as { level, percent }.diff --git a/apps/desktop/electron/prepared-submissions.ts b/apps/desktop/electron/prepared-submissions.tsindex cf4ab92d8f7..a7a3b43ec5f 100644--- a/apps/desktop/electron/prepared-submissions.ts+++ b/apps/desktop/electron/prepared-submissions.ts@@ -37,19 +37,33 @@ export function preparedJournal(userData: string, origin: string) {return {}}+ const write = (journal: Record<string, unknown>, key: string, entry: unknown | null) => {+ if (entry === null) {delete journal[key]}+ else {Object.defineProperty(journal, key, { value: entry, enumerable: true, configurable: true })}++ fs.mkdirSync(userData, { recursive: true })+ // Same private atomic replacement used for native connection settings.+ // Return only after write+rename: process termination cannot lose an ACKed+ // entry to Chromium's deferred localStorage commit. Not a power-loss promise.+ writeSecretFileAtomic(file, JSON.stringify(journal), { encoding: 'utf8' })+ }+return {read,update(key: string, entry: unknown | null) {+ write(read(), key, entry)+ },+ /** Replace `key` only while it still holds exactly `expected` (null = absent): create-if-absent+ * and compare-and-delete in one synchronous main-process step, so windows sharing the origin's+ * journal cannot interleave between the check and the write. Returns the record now stored. */+ compareAndSet(key: string, expected: unknown | null, entry: unknown | null): { applied: boolean; current: unknown | null } {const journal = read()+ const current = Object.hasOwn(journal, key) ? journal[key] : null- if (entry === null) {delete journal[key]}- else {Object.defineProperty(journal, key, { value: entry, enumerable: true, configurable: true })}+ if (JSON.stringify(current) !== JSON.stringify(expected)) {return { applied: false, current }}+ write(journal, key, entry)- fs.mkdirSync(userData, { recursive: true })- // Same private atomic replacement used for native connection settings.- // Return only after write+rename: process termination cannot lose an ACKed- // entry to Chromium's deferred localStorage commit. Not a power-loss promise.- writeSecretFileAtomic(file, JSON.stringify(journal), { encoding: 'utf8' })+ return { applied: true, current: entry }}}}@@ -66,4 +80,14 @@ export function registerPreparedSubmissions() {store(event).update(key, entry === null ? null : JSON.parse(entry))})+ ipcMain.handle('hermes:prepared-submissions:compare-and-set', (event, key: string, expected: string | null, entry: string | null) => {+ if (typeof key !== 'string' || [expected, entry].some(value => value !== null && typeof value !== 'string')) {+ throw new Error('Invalid prepared submission comparison')+ }++ const parse = (value: string | null) => value === null ? null : JSON.parse(value)+ const { applied, current } = store(event).compareAndSet(key, parse(expected), parse(entry))++ return { applied, current: current === null ? null : JSON.stringify(current) }+ })}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 73d92a34b35..a8cc2612b8d 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -432,6 +432,13 @@ declare global {preparedSubmissions?: {read: () => Promise<string>update: (key: string, entry: string | null) => Promise<void>+ /** Atomic in the main process: replace `key` only while it holds exactly `expected`+ * (null = absent). `current` is the record stored afterwards. Group Send requires it. */+ compareAndSet?: (+ key: string,+ expected: string | null,+ entry: string | null+ ) => Promise<{ applied: boolean; current: string | null }>}zoom?: {get: () => Promise<{ level: number; percent: number }>diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-send-windows.test.ts b/apps/desktop/src/plugins/hermes-bots/canonical-group-send-windows.test.tsnew file mode 100644index 00000000000..32ab763f492--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send-windows.test.ts@@ -0,0 +1,90 @@+// @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'++// The real Electron-main journal owner, reached through its real IPC handlers; only ipcMain/app are faked.+const main = vi.hoisted(() => ({ userData: '', handlers: new Map<string, (...args: unknown[]) => unknown>() }))+vi.mock('electron', () => ({+ app: { getPath: () => main.userData },+ ipcMain: { handle: (name: string, handler: (...args: unknown[]) => unknown) => main.handlers.set(name, handler) }+}))+const nativeModule = '../../../electron/prepared-submissions'+const { preparedJournal, registerPreparedSubmissions } = await import(/* @vite-ignore */ nativeModule)+import { prepareCanonicalGroupSend, readCanonicalGroupSend, retireCanonicalGroupSend } from './canonical-group-send'++const binding = { connectionId: 'local', profile: 'default', roomId: 'room-a' }+const origin = 'http://localhost:5174'+afterEach(() => vi.unstubAllGlobals())++/** Every renderer window of the origin reaches the one main-process journal over IPC. Each call+ * takes an IPC hop each way; `hold` parks one window's next mutation until released. */+function windows() {+ main.userData = fs.mkdtempSync(path.join(os.tmpdir(), 'group-send-windows-'))+ main.handlers.clear()+ registerPreparedSubmissions()+ const event = { sender: {}, senderFrame: { url: `${origin}/index.html` } }+ const hop = () => new Promise(resolve => setImmediate(resolve))+ let held: Promise<void> | undefined++ const ipc = (channel: string) => async (...args: unknown[]) => {+ await hop()+ const handler = main.handlers.get(`hermes:prepared-submissions:${channel}`)!++ if (channel !== 'read' && held) { const gate = held; held = undefined; await gate }+ const result = handler(event, ...args)+ await hop()++ return result+ }++ const preparedSubmissions = { read: ipc('read'), update: ipc('update'), compareAndSet: ipc('compare-and-set') }+ vi.stubGlobal('window', { hermesDesktop: { preparedSubmissions } })++ return {+ durable: () => preparedJournal(main.userData, origin).read() as Record<string, { params: { event_id: string } }>,+ holdNextMutation: () => { let release!: () => void; held = new Promise<void>(r => { release = r });++ return release },+ cleanup: () => fs.rmSync(main.userData, { recursive: true, force: true })+ }+}++test('two windows preparing one room slot at once acknowledge the single durable winner', async () => {+ const rig = windows()++ try {+ const [a, b] = await Promise.all([+ prepareCanonicalGroupSend(binding, { text: 'from window A' }),+ prepareCanonicalGroupSend(binding, { text: 'from window B' })+ ])++ const stored = Object.values(rig.durable())+ expect(stored).toHaveLength(1)+ // Each acknowledged preparation names the durable record, so a reload recovers what was sent.+ expect(a.params.event_id).toBe(stored[0].params.event_id)+ expect(b.params.event_id).toBe(stored[0].params.event_id)+ expect(await readCanonicalGroupSend(binding)).toEqual(a)+ } finally { rig.cleanup() }+})++test('a delayed ACK for a retired intent cannot delete the newer intent another window prepared', async () => {+ const rig = windows()++ try {+ const a = await prepareCanonicalGroupSend(binding, { text: 'first' })+ await retireCanonicalGroupSend(binding, 'wrong-id')+ expect(Object.values(rig.durable()).map(entry => entry.params.event_id)).toEqual([a.params.event_id])+ const release = rig.holdNextMutation()+ const delayed = retireCanonicalGroupSend(binding, a.params.event_id) // window A's ACK, parked at main+ await new Promise(resolve => setTimeout(resolve, 20))+ await retireCanonicalGroupSend(binding, a.params.event_id) // window B's ACK for the same send+ const b = await prepareCanonicalGroupSend(binding, { text: 'second' })+ release()+ await delayed+ expect(Object.values(rig.durable()).map(entry => entry.params.event_id)).toEqual([b.params.event_id])+ expect(await readCanonicalGroupSend(binding)).toEqual(b)+ } finally { rig.cleanup() }+})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.tsindex b1e06c2a902..55fa7e1816f 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.test.ts@@ -21,7 +21,11 @@ test('uncertain sends reopen with exact identity and attachments, isolated by auconst 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))+ update: async (key: string, entry: string | null) => journal.update(key, entry === null ? null : JSON.parse(entry)),+ compareAndSet: async (key: string, expected: string | null, entry: string | null) => {+ const { applied, current } = journal.compareAndSet(key, expected && JSON.parse(expected), entry && JSON.parse(entry))+ return { applied, current: current === null ? null : JSON.stringify(current) }+ }} } })}try {@@ -52,7 +56,11 @@ test('native journal acknowledgement gates send and a failed write cannot downgrlet entered!: () => voidconst 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 native = { read: async () => '{}', compareAndSet: vi.fn(async (_key: string, _expected: string | null, entry: string | null) => {+ entered()+ await gate+ return { applied: true, current: entry }+ }) }const browserWrite = vi.fn()vi.stubGlobal('window', { hermesDesktop: { preparedSubmissions: native }, localStorage: { setItem: browserWrite } })const send = vi.fn()@@ -62,7 +70,7 @@ test('native journal acknowledgement gates send and a failed write cannot downgracknowledge()await pendingexpect(send).toHaveBeenCalledOnce()- native.update.mockRejectedValueOnce(new Error('disk full'))+ native.compareAndSet.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.tsindex a8fd95ac2bc..def4b362a63 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-send.ts@@ -22,6 +22,7 @@ function journalKey(binding: CanonicalGroupBinding): string {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) || '{}')@@ -33,28 +34,40 @@ async function readJournal(): Promise<Record<string, PreparedCanonicalGroupSend>return parsed as Record<string, PreparedCanonicalGroupSend>}-async function update(key: string, entry: PreparedCanonicalGroupSend | null): Promise<void> {+/** Replace `key` only while it holds exactly `expected` (null = absent); returns the stored record.+ * Native: one IPC op the Electron main process applies atomically, so every window of the origin+ * is serialized at the journal owner — renderer locks cannot order separate windows. */+async function compareAndSet(+ key: string,+ expected: string | null,+ entry: string | null+): Promise<{ applied: boolean; current: string | null }> {const native = window.hermesDesktop?.preparedSubmissions+ // Await private atomic-file publication before the caller may send. Never+ // downgrade a native write failure to Chromium's deferred localStorage.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))+ // An older preload has no atomic op: refuse rather than fall back to a racy read-then-write.+ if (!native.compareAndSet) {throw new Error('Group Send needs an updated Desktop; restart Hermes Desktop')}- return+ return native.compareAndSet(key, expected, entry)}// Browser-only fallback guarantees reload recovery, not process-crash safety.const journal = await readJournal()+ const current = Object.hasOwn(journal, key) ? JSON.stringify(journal[key]) : null++ if (current !== (expected === null ? null : JSON.stringify(JSON.parse(expected)))) {return { applied: false, current }}+if (entry === null) {delete journal[key]}- else {journal[key] = entry}+ else {journal[key] = JSON.parse(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]+ return { applied: true, current: entry }+}+function validEntry(binding: CanonicalGroupBinding, key: string, entry: PreparedCanonicalGroupSend | undefined) {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')@@ -63,16 +76,26 @@ export async function readCanonicalGroupSend(binding: CanonicalGroupBinding): Prreturn entry}+export async function readCanonicalGroupSend(binding: CanonicalGroupBinding): Promise<PreparedCanonicalGroupSend | undefined> {+ const key = journalKey(binding)++ return validEntry(binding, key, (await readJournal())[key])+}+// 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.+// Create-if-absent at the journal owner: when another window won the slot first,+// every caller converges on that durable winner instead of acking its own ID.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: {@@ -81,14 +104,18 @@ export async function prepareCanonicalGroupSend(payload: { ...payload, thread_id: payload.thread_id ?? eventId }}}))- await update(journalKey(binding), entry)- return entry+ const key = journalKey(binding)+ const { current } = await compareAndSet(key, null, JSON.stringify(entry))++ return validEntry(binding, key, current === null ? undefined : JSON.parse(current)) ?? 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.+// exact event and payload. Compare-and-delete at the journal owner: a delayed or+// wrong ACK whose intent was already replaced (fresh event_id) deletes nothing.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)}++ if (entry?.params.event_id === eventId) {await compareAndSet(journalKey(binding), JSON.stringify(entry), null)}}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 b5c1242bdb2..220dcadfcef 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@@ -69,10 +69,12 @@ it('blocks Send until journal restore and durable preparation complete', async (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) => {+ compareAndSet: vi.fn(async (key: string, _expected: string | null, value: string | null) => {await new Promise<void>(resolve => { releaseWrite = resolve })if (value === null) {delete journal[key]} else {journal[key] = JSON.parse(value)}++ return { applied: true, current: value }})}@@ -87,11 +89,11 @@ it('blocks Send until journal restore and durable preparation complete', async (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())+ await waitFor(() => expect(native.compareAndSet).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))+ await waitFor(() => expect(native.compareAndSet).toHaveBeenCalledTimes(2))releaseWrite()await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(''))})