Skip to content

The agent that grows with you

fix: prepare desktop session edits from owner snapshots

Tekniumc01a625c6896
diff --git a/apps/desktop/src/api/sessions-mutations.test.ts b/apps/desktop/src/api/sessions-mutations.test.ts
new file mode 100644
index 00000000000..90cf9b28e1e
--- /dev/null
+++ b/apps/desktop/src/api/sessions-mutations.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/legacy-session-owner-backfill', () => ({ maybeBackfillLegacySessionOwners: vi.fn() }))
+vi.mock('@/store/transcript-tail', () => ({ recordTranscriptTail: vi.fn() }))
+vi.mock('./client', async importOriginal => ({
+ ...await importOriginal<typeof import('./client')>(), hermesApi: vi.fn()
+}))
+import { hermesApi, setApiRequestConnection, setApiRequestProfile } from './client'
+import { deleteSession, renameSession, setSessionArchived, setSessionPinnedRemote, setSessionUnreadRemote } from './sessions'
+
+beforeEach(() => { vi.mocked(hermesApi).mockReset(); setApiRequestConnection('owner'); setApiRequestProfile('work') })
+
+it('uses owner snapshots and preserves the exact delete identity after a lost reply', async () => {
+ let lost = true
+ const writes: unknown[] = []
+ vi.mocked(hermesApi).mockImplementation(async request => {
+ if (!request.method || request.method === 'GET') {
+ return { exists: true, runtime_revision: 12, runtime_generation: 8 } as never
+ }
+ writes.push(request)
+ if (lost) { lost = false; throw new Error('network disconnected after commit') }
+ return { deleted_ids: ['delete-me'], revision: 13 } as never
+ })
+ const owner = { connectionId: 'server', profile: 'work' }
+ await expect(deleteSession('delete-me', owner)).rejects.toThrow('network disconnected')
+ setApiRequestConnection('unrelated')
+ await deleteSession('delete-me', owner)
+ expect(writes).toHaveLength(2)
+ expect(writes[1]).toEqual(writes[0])
+ const request = writes[0] as { path: string; connectionId: string }
+ const url = new URL(request.path, 'http://localhost')
+ expect(request.connectionId).toBe('server')
+ expect(url.searchParams.get('expected_revision')).toBe('12')
+ expect(url.searchParams.get('expected_generation')).toBe('8')
+ expect(url.searchParams.get('request_id')).toBeTruthy()
+})
+
+it('all sidebar mutations use real counters and surface conflicts without a blind write', async () => {
+ const calls = [() => renameSession('sidebar', 'name', 'work'),
+ () => setSessionArchived('sidebar', true, 'work'), () => setSessionPinnedRemote('sidebar', false, 'work'),
+ () => setSessionUnreadRemote('sidebar', true, 'work')]
+ vi.mocked(hermesApi).mockImplementation(async request => {
+ if (!request.method || request.method === 'GET') {
+ return { exists: true, runtime_revision: 19, runtime_generation: 4 } as never
+ }
+ expect(request.body).toMatchObject({ expected_revision: 19, expected_generation: 4,
+ request_id: expect.any(String), profile: 'work' })
+ throw new Error('revision_conflict')
+ })
+ for (const invoke of calls) { await expect(invoke()).rejects.toThrow('revision_conflict') }
+ vi.mocked(hermesApi).mockReset().mockResolvedValue({ exists: true } as never)
+ await expect(renameSession('unknown-counter', 'name')).rejects.toThrow(/snapshot/)
+ expect(hermesApi).toHaveBeenCalledTimes(1)
+})
diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.ts
index 0bbf3dadaf3..b216d699dac 100644
--- a/apps/desktop/src/api/sessions.test.ts
+++ b/apps/desktop/src/api/sessions.test.ts
@@ -29,56 +29,56 @@ describe('deleteSession profile scoping', () => {
// opened its own default state.db, missed the row, and returned
// {ok:true, already_absent:true} — the row vanished optimistically but was
// never deleted and came back on refresh. The URL must carry ?profile=.
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
// Mirrors the real capabilityScoped for an object owner (remote-stamped row).
vi.mocked(client.capabilityScoped).mockReturnValue({ profile: 'tommy', connectionId: 'hermes-pi' })
await deleteSession('sess-1', { connectionId: 'hermes-pi', profile: 'tommy' })
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'DELETE',
- path: '/api/sessions/sess-1?profile=tommy',
+ path: expect.stringContaining('/api/sessions/sess-1?profile=tommy'),
connectionId: 'hermes-pi',
profile: 'tommy'
})
})
it('scopes the DELETE to the owning profile in the URL (bare string owner)', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
// Bare-string owner: capabilityScoped resolves it to a profile scope.
vi.mocked(client.capabilityScoped).mockReturnValue({ profile: 'tommy' })
await deleteSession('sess-2', 'tommy')
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'DELETE',
- path: '/api/sessions/sess-2?profile=tommy'
+ path: expect.stringContaining('/api/sessions/sess-2?profile=tommy')
})
})
it('omits the profile query when no owner is known', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await deleteSession('sess-3')
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'DELETE',
- path: '/api/sessions/sess-3'
+ path: expect.stringContaining('/api/sessions/sess-3')
})
- expect((hermesApi.mock.calls[0][0] as { path: string }).path).not.toContain('profile=')
+ expect((hermesApi.mock.calls.filter(([request]) => request.method)[0][0] as { path: string }).path).not.toContain('profile=')
})
it('keeps an explicit local pin routed to the local pool', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
// capabilityScoped drops a 'local' connection id by design; sessionScoped
// must re-add it so the request stays pinned to this device.
vi.mocked(client.capabilityScoped).mockReturnValue({ profile: 'tommy' })
await deleteSession('sess-4', { connectionId: 'local', profile: 'tommy' })
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'DELETE',
- path: '/api/sessions/sess-4?profile=tommy',
+ path: expect.stringContaining('/api/sessions/sess-4?profile=tommy'),
connectionId: 'local',
profile: 'tommy'
})
@@ -91,11 +91,11 @@ describe('setSessionArchived profile scoping', () => {
// from body.profile, so archiving a foreign-profile session must send it in
// the body, not only as request.profile (Electron routing), or on a remote
// gateway the archive lands on the wrong state.db and silently no-ops.
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await setSessionArchived('sess-a', true, 'tommy')
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'PATCH',
path: '/api/sessions/sess-a',
profile: 'tommy',
@@ -104,11 +104,11 @@ describe('setSessionArchived profile scoping', () => {
})
it('omits the profile from the body when none is given', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await setSessionArchived('sess-b', false)
- const req = hermesApi.mock.calls[0][0] as { body: Record<string, unknown> }
+ const req = hermesApi.mock.calls.filter(([request]) => request.method)[0][0] as { body: Record<string, unknown> }
expect(req).toMatchObject({ method: 'PATCH', body: { archived: false } })
expect(req.body).not.toHaveProperty('profile')
})
@@ -116,11 +116,11 @@ describe('setSessionArchived profile scoping', () => {
describe('setSessionPinnedRemote / setSessionUnreadRemote profile scoping', () => {
it('carries the owning profile in the pin PATCH body', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await setSessionPinnedRemote('sess-p', true, 'tommy')
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'PATCH',
path: '/api/sessions/sess-p',
profile: 'tommy',
@@ -129,11 +129,11 @@ describe('setSessionPinnedRemote / setSessionUnreadRemote profile scoping', () =
})
it('carries the owning profile in the unread PATCH body', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await setSessionUnreadRemote('sess-u', true, 'tommy')
- expect(hermesApi.mock.calls[0][0]).toMatchObject({
+ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({
method: 'PATCH',
path: '/api/sessions/sess-u',
profile: 'tommy',
@@ -142,11 +142,11 @@ describe('setSessionPinnedRemote / setSessionUnreadRemote profile scoping', () =
})
it('omits the profile from the body when none is given', async () => {
- hermesApi.mockResolvedValue({ ok: true } as never)
+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)
await setSessionPinnedRemote('sess-p2', false)
- const req = hermesApi.mock.calls[0][0] as { body: Record<string, unknown> }
+ const req = hermesApi.mock.calls.filter(([request]) => request.method)[0][0] as { body: Record<string, unknown> }
expect(req).toMatchObject({ method: 'PATCH', body: { pinned: false } })
expect(req.body).not.toHaveProperty('profile')
})
diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.ts
index 61368921bc9..b32f9f0db4e 100644
--- a/apps/desktop/src/api/sessions.ts
+++ b/apps/desktop/src/api/sessions.ts
@@ -1,3 +1,4 @@
+import { createSessionMutationClient, type SessionMutationSnapshot } from '../../../shared/src/session-http-mutations'
import { isMissingRestEndpoint } from '@/lib/gateway-rpc'
import { maybeBackfillLegacySessionOwners } from '@/lib/legacy-session-owner-backfill'
import { stampRowsWithOwningConnection } from '@/lib/session-owner-stamp'
@@ -320,54 +321,37 @@ export async function listSidebarSessions(req: SidebarSessionsRequest): Promise<
}
}
-// Mutations take the owning `profile` so Electron can route them to the correct
-// remote backend or local profile scope. Omit for the current/default profile.
+const runSessionMutation = createSessionMutationClient()
+
+function mutateSessionHttp<T>(id: string, method: 'PATCH' | 'DELETE', payload: Record<string, unknown>, profile?: ProfileScope): Promise<T> {
+ const scope = { connectionId: getApiRequestConnection() || 'local', ...sessionScoped(profile) }
+ const path = `/api/sessions/${encodeURIComponent(id)}`
+ const query = new URLSearchParams(scope.profile ? { profile: scope.profile } : {})
+ const suffix = query.size ? `?${query}` : ''
+ const key = JSON.stringify([scope, id, method, payload])
+ return runSessionMutation(key,
+ () => hermesApi<SessionMutationSnapshot>({ ...scope, path: `${path}/mutation-snapshot${suffix}` }),
+ identity => {
+ if (method === 'DELETE') {
+ const params = new URLSearchParams(query)
+ for (const [name, value] of Object.entries(identity)) { params.set(name, String(value)) }
+ return hermesApi<T>({ ...scope, path: `${path}?${params}`, method })
+ }
+ return hermesApi<T>({ ...scope, path, method,
+ body: { ...payload, ...identity, ...(scope.profile ? { profile: scope.profile } : {}) } })
+ })
+}
+
export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Carry the owning profile IN THE PATCH BODY, mirroring renameSession — the
- // backend reads its target DB from body.profile (_open_session_db_for_profile).
- // Passing it only as request.profile (Electron routing) is not enough on a
- // remote gateway with no remoteProfile alias: the archive lands on the wrong
- // (default) state.db, no-ops on a missing row, and the archived/unarchived
- // state silently fails to stick — the same class as the unscoped DELETE.
- return hermesApi<{ ok: boolean }>({
- ...(profile ? { profile } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { archived, ...(profile ? { profile } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { archived }, profile)
}
-// Mirror a sidebar pin to the backend "keep" flag so the sessions.auto_archive
-// sweep (which runs backend-side, blind to Desktop localStorage) never hides a
-// pinned chat. Best-effort: the sidebar stays localStorage-driven for its own
-// display; this only feeds the backend policy.
export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Owning profile in the PATCH body (see setSessionArchived / renameSession):
- // the handler reads its target DB from body.profile, so a remote/foreign
- // profile's pin must travel in the body or it no-ops on the wrong state.db.
- return hermesApi<{ ok: boolean }>({
- ...(profile ? { profile } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { pinned, ...(profile ? { profile } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { pinned }, profile)
}
-// Mirror a sidebar unread toggle to the backend read-state watermark
-// (sessions.last_read_at via SessionDB.set_session_read). Same profile
-// routing as the other session mutations: a remote session's row lives only
-// on its remote host, so the owning profile must travel with the request.
export function setSessionUnreadRemote(id: string, unread: boolean, profile?: string | null): Promise<{ ok: boolean }> {
- // Owning profile in the PATCH body (see setSessionArchived / renameSession):
- // the handler reads its target DB from body.profile, so a remote/foreign
- // profile's unread toggle must travel in the body or it no-ops on the wrong
- // state.db.
- return hermesApi<{ ok: boolean }>({
- ...(profile ? { profile } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { unread, ...(profile ? { profile } : {}) }
- })
+ return mutateSessionHttp(id, 'PATCH', { unread }, profile)
}
export function searchSessions(query: string): Promise<SessionSearchResponse> {
@@ -564,36 +548,9 @@ export async function getAllSessionMessages(
}
export function deleteSession(id: string, profile?: ProfileScope): Promise<{ ok: boolean }> {
- // Scope the DELETE to the owning profile IN THE URL, mirroring getSession /
- // getSessionMessages. Passing the profile only via request.profile (which the
- // Electron main process consumes for backend routing) is NOT enough: on a
- // remote gateway whose connection has no remoteProfile alias, the main-process
- // path rewrite leaves the URL unscoped, so the backend opens its OWN (default)
- // state.db, fails to find another profile's session, and returns
- // {ok:true, already_absent:true}. The row then vanishes optimistically but was
- // never deleted and reappears on the next sidebar refresh — the "All Profiles
- // delete doesn't stick" report. The endpoint already honours ?profile=
- // (get/rename/messages all send it); DELETE was the one mutation that dropped
- // it after the api/ split. request.profile stays on for per-profile remote
- // override + global-remote routing (both re-read/re-append the param).
- const suffix = sessionScopeQuery(profile)
-
- return hermesApi<{ ok: boolean }>({
- ...sessionScoped(profile),
- path: `/api/sessions/${encodeURIComponent(id)}${suffix}`,
- method: 'DELETE'
- })
+ return mutateSessionHttp(id, 'DELETE', {}, profile)
}
-export function renameSession(
- id: string,
- title: string,
- profile?: string | null
-): Promise<{ ok: boolean; title: string }> {
- return hermesApi<{ ok: boolean; title: string }>({
- ...(profile ? { profile } : {}),
- path: `/api/sessions/${encodeURIComponent(id)}`,
- method: 'PATCH',
- body: { title, ...(profile ? { profile } : {}) }
- })
+export function renameSession(id: string, title: string, profile?: string | null): Promise<{ ok: boolean; title: string }> {
+ return mutateSessionHttp(id, 'PATCH', { title }, profile)
}
diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts
index ec9b94ada61..34195c75acf 100644
--- a/apps/desktop/src/hermes.test.ts
+++ b/apps/desktop/src/hermes.test.ts
@@ -193,6 +193,7 @@ describe('Hermes REST helpers', () => {
it('preserves ambient and explicit-local ownership for session and profile requests', async () => {
setApiRequestConnection('remote-a')
+ api.mockResolvedValue({ ...emptySessionsResponse, exists: true, runtime_revision: 9, runtime_generation: 2 })
await getSession('ambient-session')
await getSessionMessages('ambient-session')
diff --git a/apps/shared/src/session-http-mutations.ts b/apps/shared/src/session-http-mutations.ts
new file mode 100644
index 00000000000..d60149f6fa3
--- /dev/null
+++ b/apps/shared/src/session-http-mutations.ts
@@ -0,0 +1,51 @@
+export interface SessionMutationSnapshot {
+ session_id: string
+ exists: boolean
+ runtime_revision: number
+ runtime_generation: number | null
+}
+
+export interface SessionMutationIdentity {
+ request_id: string
+ expected_revision: number
+ expected_generation?: number
+}
+
+/** Keep an ambiguous write's identity until the same intent is acknowledged.
+ * Keys include the captured destination and payload; neither retries nor a
+ * profile switch may silently refresh the precondition of a possibly committed edit.
+ */
+export function createSessionMutationClient() {
+ const pending = new Map<string, Promise<SessionMutationIdentity>>()
+
+ return async function mutate<T>(key: string, read: () => Promise<SessionMutationSnapshot>,
+ send: (identity: SessionMutationIdentity) => Promise<T>, importing = false): Promise<T> {
+ let prepared = pending.get(key)
+ if (!prepared) {
+ prepared = read().then(snapshot => {
+ if (typeof snapshot?.exists !== 'boolean' || !Number.isSafeInteger(snapshot.runtime_revision)
+ || snapshot.runtime_revision < 0 || (!importing && !snapshot.exists)
+ || (snapshot.exists && (!Number.isSafeInteger(snapshot.runtime_generation) || snapshot.runtime_generation! < 0))) {
+ throw new Error('Session mutation snapshot unavailable; refresh before trying again')
+ }
+ return { request_id: crypto.randomUUID(), expected_revision: snapshot.runtime_revision,
+ ...(snapshot.exists ? { expected_generation: snapshot.runtime_generation! } : {}) }
+ })
+ pending.set(key, prepared)
+ }
+ let identity: SessionMutationIdentity
+ try { identity = await prepared } catch (error) { pending.delete(key); throw error }
+ try {
+ const result = await send(identity)
+ pending.delete(key)
+ return result
+ } catch (error) {
+ // These responses definitively rejected the write. Show the conflict;
+ // only a later explicit user action may read a new precondition.
+ if (/revision_conflict|stale_generation|permission_denied|profile_mismatch|invalid_params|admission_conflict|session_busy|retained_receipts|runtime_coordination_required/.test(String(error))) {
+ pending.delete(key)
+ }
+ throw error
+ }
+ }
+}
diff --git a/tests/hermes_cli/test_session_mutation_snapshot.py b/tests/hermes_cli/test_session_mutation_snapshot.py
new file mode 100644
index 00000000000..e8f1148c004
--- /dev/null
+++ b/tests/hermes_cli/test_session_mutation_snapshot.py
@@ -0,0 +1,37 @@
+"""HTTP mutation preparation reads the owner's exact persisted counters."""
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from gateway.session_authority import SessionAuthority
+from hermes_cli.web_routers.sessions import manage_router
+from hermes_state import SessionDB
+from hermes_state_runtime import begin_runtime_epoch
+
+
+async def test_snapshot_reports_real_counters_and_absent_import_anchor(tmp_path, monkeypatch):
+ from hermes_cli import web_server
+ monkeypatch.setattr(web_server, '_SESSION_TOKEN', 'snapshot-token')
+ monkeypatch.setattr('hermes_state._default_db_path', lambda: tmp_path / 'state.db')
+ app = FastAPI()
+ app.include_router(manage_router)
+ with SessionDB(db_path=tmp_path / 'state.db') as db:
+ db.create_session('snapshot-session', source='cli')
+ db._execute_write(lambda c: c.execute('UPDATE sessions SET runtime_revision=7, runtime_generation=3'))
+ app.state.session_authority = SessionAuthority(SimpleNamespace(_draining=False),
+ profile_id=str(tmp_path), instance_id='snapshot-owner', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='snapshot-owner'))
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://localhost') as client:
+ path = '/api/sessions/snapshot-session/mutation-snapshot'
+ assert (await client.get(path)).status_code == 401
+ client.headers['Authorization'] = 'Bearer snapshot-token'
+ result = await client.get(path)
+ assert result.status_code == 200, result.text
+ assert result.json() == {'session_id': 'snapshot-session', 'exists': True,
+ 'runtime_revision': 7, 'runtime_generation': 3}
+ absent = await client.get('/api/sessions/new-import/mutation-snapshot')
+ assert absent.json() == {'session_id': 'new-import', 'exists': False,
+ 'runtime_revision': 0, 'runtime_generation': None}