The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): avoid unpin writes racing session removal
Mikhail Tarasov18a1ca43ea5c
diff --git a/apps/desktop/src/api/sessions-mutations.test.ts b/apps/desktop/src/api/sessions-mutations.test.tsindex ef687e71d0e..c33b021f7e4 100644--- a/apps/desktop/src/api/sessions-mutations.test.ts+++ b/apps/desktop/src/api/sessions-mutations.test.ts@@ -115,7 +115,7 @@ it('sidebar edits fall back to the base write only when the backend lacks the feawait setSessionUnreadRemote('old', false, 'work')await deleteSession('old', { connectionId: 'server', profile: 'work' })expect(writes.map(write => [write.method, write.body])).toEqual([- ['PATCH', { title: 'name', profile: 'work' }], ['PATCH', { archived: true, profile: 'work' }],+ ['PATCH', { title: 'name', profile: 'work' }], ['PATCH', { archived: true, pinned: false, profile: 'work' }],['PATCH', { pinned: true, profile: 'work' }], ['PATCH', { unread: false, profile: 'work' }], ['DELETE', undefined]])expect(new URL(writes[4].path, 'http://localhost').search).toBe('?profile=work')@@ -151,7 +151,7 @@ it('sidebar edits on an older headless serve fall back to the base write', asyncawait setSessionUnreadRemote('ssh', false, 'work')await deleteSession('ssh', { connectionId: 'server', profile: 'work' })expect(writes.map(write => [write.method, write.body])).toEqual([- ['PATCH', { title: 'name', profile: 'work' }], ['PATCH', { archived: true, profile: 'work' }],+ ['PATCH', { title: 'name', profile: 'work' }], ['PATCH', { archived: true, pinned: false, profile: 'work' }],['PATCH', { pinned: true, profile: 'work' }], ['PATCH', { unread: false, profile: 'work' }], ['DELETE', undefined]])// FastAPI's bare 404 is no route verdict: it keeps the fenced path and writes nothing.diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.tsindex 8f2dcfef6e2..7bdaff9c7d3 100644--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@ -135,7 +135,7 @@ describe('setSessionArchived profile scoping', () => {method: 'PATCH',path: '/api/sessions/sess-a',profile: 'tommy',- body: { archived: true, profile: 'tommy' }+ body: { archived: true, pinned: false, profile: 'tommy' }})})@@ -165,6 +165,7 @@ describe('setSessionArchived profile scoping', () => {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')+ expect(req.body).not.toHaveProperty('pinned')})})diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.tsindex cfd28017d80..b92ab645fba 100644--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@ -421,7 +421,7 @@ function mutateSessionHttp<T>(id: string, method: 'PATCH' | 'DELETE', payload: R}export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> {- return mutateSessionHttp(id, 'PATCH', { archived }, sessionWriteProfile(profile))+ return mutateSessionHttp(id, 'PATCH', { archived, ...(archived ? { pinned: false } : {}) }, sessionWriteProfile(profile))}export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> {diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/pinned-session-removal.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions/pinned-session-removal.test.tsxnew file mode 100644index 00000000000..1864f8c8b1c--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/pinned-session-removal.test.tsx@@ -0,0 +1,143 @@+// Regression for #139350: optimistic pin cleanup must not race the fenced removal.+import { act, cleanup, render } from '@testing-library/react'+import type { MutableRefObject } from 'react'+import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'++import { deleteSession, type SessionInfo, setSessionArchived, setSessionPinnedRemote } from '@/hermes'+import { $pinnedSessionIds } from '@/store/layout'+import { $sessions, setSessions } from '@/store/session'+import { resetSessionPinMirror, watchSessionPins } from '@/store/session-pin-sync'+import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-removal'++import type { ClientSessionState } from '../../../types'++import { useSessionActions } from './index'++vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ deleteSession: vi.fn(),+ setSessionArchived: vi.fn(),+ setSessionPinnedRemote: vi.fn().mockResolvedValue({ ok: true })+}))++type Handle = Pick<ReturnType<typeof useSessionActions>, 'archiveSession' | 'removeSession'>++function Harness({ onReady }: { onReady: (handle: Handle) => void }) {+ const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })++ const actions = useSessionActions({+ activeSessionId: null,+ activeSessionIdRef: ref<string | null>(null),+ busyRef: ref(false),+ creatingSessionRef: ref(false),+ ensureSessionState: () => ({}) as ClientSessionState,+ getRouteToken: () => 'token',+ getRoutedStoredSessionId: () => null,+ navigate: vi.fn() as never,+ requestGateway: vi.fn().mockResolvedValue(undefined),+ resetViewSync: vi.fn(),+ routedSessionId: null,+ runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),+ selectedStoredSessionId: null,+ selectedStoredSessionIdRef: ref<string | null>(null),+ sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),+ syncSessionStateToView: vi.fn(),+ updateSessionState: () => ({}) as ClientSessionState+ })++ onReady(actions)++ return null+}++beforeAll(() => {+ window.hermesDesktop = {} as typeof window.hermesDesktop+ watchSessionPins()+})++beforeEach(() => {+ resetSessionPinMirror()+ setSessions([])+ $pinnedSessionIds.set([])+ $removedSessionIds.set(new Set())+ $sessionMutationsInFlight.set(new Set())+ vi.clearAllMocks()+ // Pins use the lineage root while archive/delete targets the current tip.+ setSessions([+ {+ id: 'tip',+ _lineage_root_id: 'root',+ pinned: true,+ profile: 'work',+ message_count: 2,+ source: 'desktop',+ started_at: 1,+ title: 'pinned chat'+ } as SessionInfo+ ])+ expect($pinnedSessionIds.get()).toEqual(['root'])+})++afterEach(() => {+ cleanup()+ resetSessionPinMirror()+ setSessions([])+ $pinnedSessionIds.set([])+ $removedSessionIds.set(new Set())+ $sessionMutationsInFlight.set(new Set())+})++it.each(['archiveSession', 'removeSession'] as const)('%s does not issue a competing unpin', async action => {+ let handle!: Handle+ render(+ <Harness+ onReady={value => {+ handle = value+ }}+ />+ )+ const mutate = action === 'archiveSession' ? vi.mocked(setSessionArchived) : vi.mocked(deleteSession)+ let resolve!: (value: { ok: boolean }) => void+ mutate.mockImplementation(+ () =>+ new Promise(done => {+ resolve = done+ })+ )++ await act(async () => {+ const removal = handle[action]('tip')+ // The row disappears immediately while the single server mutation is pending.+ expect($sessions.get()).toEqual([])+ expect($pinnedSessionIds.get()).toEqual([])+ expect(setSessionPinnedRemote).not.toHaveBeenCalled()+ resolve({ ok: true })+ await removal+ })++ expect(mutate).toHaveBeenCalledTimes(1)+ expect($pinnedSessionIds.get()).toEqual([])+ expect(setSessionPinnedRemote).not.toHaveBeenCalled()+})++it.each(['archiveSession', 'removeSession'] as const)(+ '%s restores a rejected removal without rewriting its pin',+ async action => {+ let handle!: Handle+ render(+ <Harness+ onReady={value => {+ handle = value+ }}+ />+ )+ const mutate = action === 'archiveSession' ? vi.mocked(setSessionArchived) : vi.mocked(deleteSession)+ mutate.mockRejectedValue(new Error('permission_denied'))++ await act(() => handle[action]('tip'))++ expect($sessions.get().map(row => row.id)).toEqual(['tip'])+ expect($pinnedSessionIds.get()).toEqual(['root'])+ expect(setSessionPinnedRemote).not.toHaveBeenCalled()+ }+)diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.tsindex 339bf3652ab..8495251bdab 100644--- a/apps/desktop/src/store/session-pin-sync.ts+++ b/apps/desktop/src/store/session-pin-sync.ts@@ -37,6 +37,7 @@ import {setMessagingSessions,setSessions} from '@/store/session'+import { isSessionRemovalPending } from '@/store/session-removal'import type { SessionInfo } from '@/types/hermes'// pin ids we've successfully PATCHed pinned=true this session.@@ -332,7 +333,12 @@ function reconcileInner(): void {if (!current.has(id)) {mirrored.delete(id)pending.delete(id)- void writePin(id, false, profileFor(id)).catch(() => {})++ // Removal owns the durable write; a separate unpin would race its+ // revision snapshot. Archive clears the pin in the same PATCH.+ if (!isSessionRemovalPending(id)) {+ void writePin(id, false, profileFor(id)).catch(() => {})+ }}}