The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): re-read the sidebar when a same-route activation voids the page
brooklyn!02b07ac1abb2
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.reactivation.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.reactivation.test.tsxnew file mode 100644index 00000000000..d026ab692c2--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.reactivation.test.tsx@@ -0,0 +1,70 @@+import { act, renderHook } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import type { SessionInfo, SidebarSessionsResponse } from '@/hermes'+import { ensureGatewayForAgent, setPrimaryGateway, setPrimaryGatewayConnection } from '@/store/gateway'+import { $sessions, setSessions } from '@/store/session'++import { deferred } from '../../../test/deferred'++import { useSessionListActions } from './use-session-list-actions'++// Real gateway registry, stubbed transport: the activation epoch here is the+// one production bumps, not a test double.+const listSidebarSessions = vi.fn()++vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getCronJobs: vi.fn(async () => []),+ listSidebarSessions: (...args: unknown[]) => listSidebarSessions(...args)+}))++const row = (id: string): SessionInfo =>+ ({+ id,+ last_active: 1000,+ message_count: 3,+ profile: 'default',+ source: 'desktop',+ started_at: 900,+ title: `Chat ${id}`+ }) as SessionInfo++const page = (sessions: SessionInfo[]): SidebarSessionsResponse => ({+ recents: { sessions },+ cron: { sessions: [] },+ messaging: { sessions: [] }+})++afterEach(() => setSessions([]))++// #67600 / #88866: resuming a default-profile chat on the local source routes+// through ensureGatewayAgent('local', 'default'). That activation lands on the+// socket the window already shows, so no route atom moves and no effect asks+// for the list again; the sidebar page in flight at that moment is the only+// one the window gets.+it('keeps the default-profile sidebar when the active route is re-activated mid-refresh', async () => {+ const primary = { connectionState: 'open', request: vi.fn(async () => ({})) }+ setPrimaryGateway(primary as never, 'default')+ setPrimaryGatewayConnection({ connectionId: 'local', mode: 'local' } as never)++ const pending = deferred<SidebarSessionsResponse>()+ const rows = [row('a'), row('b')]+ listSidebarSessions.mockReturnValueOnce(pending.promise).mockResolvedValue(page(rows))++ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))+ let refresh!: Promise<void>++ act(() => {+ refresh = result.current.refreshSessions()+ })++ await ensureGatewayForAgent('local', 'default')++ await act(async () => {+ pending.resolve(page(rows))+ await refresh+ })++ expect($sessions.get().map(session => session.id)).toEqual(['a', 'b'])+})diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsxindex 7c22c63b370..bec573ccd65 100644--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx@@ -413,9 +413,11 @@ describe('refreshSessions identity + loading hygiene', () => {}})- it('clears initial loading after a failed source activation advances the gateway epoch', async () => {+ it('re-reads for the current route after a failed source activation advances the gateway epoch', async () => {const pending = deferred<SidebarSessionsResponse>()- listSidebarSessions.mockReturnValue(pending.promise)+ listSidebarSessions+ .mockReturnValueOnce(pending.promise)+ .mockResolvedValueOnce(sidebar({ sessions: [row('current')] }))const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))let refresh!: Promise<void>@@ -427,8 +429,10 @@ describe('refreshSessions identity + loading hygiene', () => {expect($sessionsLoading.get()).toBe(true)// A source dial owns a new activation epoch even when it fails and leaves- // the previous source active. Its in-flight session response is stale, but- // it still owns the initial loading state and must release that state.+ // the previous source active. Its in-flight response is stale and must not+ // publish, but nothing else re-requests the list when the route atoms did+ // not move, so the refresh re-reads under the new epoch and releases the+ // initial loading state itself.gatewayScope.epoch += 1await act(async () => {@@ -436,9 +440,56 @@ describe('refreshSessions identity + loading hygiene', () => {await refresh})- expect($sessions.get()).toEqual([])+ expect(listSidebarSessions).toHaveBeenCalledTimes(2)+ expect($sessions.get().map(session => session.id)).toEqual(['current'])expect($sessionsLoading.get()).toBe(false)})++ // #67600 / #88866: re-activating the route the window is already on (a+ // resume or rail click through ensureGatewayAgent('local', 'default'))+ // advances the epoch without changing any route atom, so no effect fires a+ // follow-up refresh. The in-flight 200-with-rows page used to be discarded+ // and the sidebar stayed on "No sessions" until the user re-selected the+ // profile.+ it('fills the sidebar when a same-route re-activation lands mid-refresh', async () => {+ const pending = deferred<SidebarSessionsResponse>()+ const rows = [row('a'), row('b')]+ listSidebarSessions.mockReturnValueOnce(pending.promise).mockResolvedValueOnce(sidebar({ sessions: rows }))+ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ let refresh!: Promise<void>++ act(() => {+ refresh = result.current.refreshSessions()+ })++ gatewayScope.epoch += 1++ await act(async () => {+ pending.resolve(sidebar({ sessions: rows }))+ await refresh+ })++ expect($sessions.get().map(session => session.id)).toEqual(['a', 'b'])+ })++ it('does not re-read a refresh a newer one already superseded', async () => {+ const older = deferred<SidebarSessionsResponse>()+ listSidebarSessions.mockReturnValueOnce(older.promise).mockResolvedValueOnce(sidebar({ sessions: [row('newer')] }))+ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ const olderRefresh = result.current.refreshSessions()+ gatewayScope.epoch += 1++ await act(async () => {+ await result.current.refreshSessions()+ older.resolve(sidebar({ sessions: [row('older')] }))+ await olderRefresh+ })++ expect(listSidebarSessions).toHaveBeenCalledTimes(2)+ expect($sessions.get().map(session => session.id)).toEqual(['newer'])+ })})describe('refreshSessions batches slices into one request', () => {@@ -812,4 +863,22 @@ describe('messaging profile scope', () => {expect(listAllProfileSessions).not.toHaveBeenCalled()expect($messagingPlatformTotals.get()).toEqual({ 'work:signal': 12 })})++ it('re-reads the messaging slice when a same-route re-activation lands mid-refresh', async () => {+ const pending = deferred<{ sessions: SessionInfo[]; total: number }>()+ const rows = [row('tg', { source: 'telegram' })]+ listAllProfileSessions.mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ sessions: rows, total: 1 })+ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ const refresh = result.current.refreshMessagingSessions()+ gatewayScope.epoch += 1++ await act(async () => {+ pending.resolve({ sessions: rows, total: 1 })+ await refresh+ })++ expect(listAllProfileSessions).toHaveBeenCalledTimes(2)+ expect($messagingSessions.get().map(session => session.id)).toEqual(['tg'])+ })})diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts b/apps/desktop/src/app/session/hooks/use-session-list-actions.tsindex fb62d381cbb..a29f6babea7 100644--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts@@ -126,7 +126,6 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg/** Refresh the active profile's messaging-platform sidebar slice. */const refreshMessagingSessions = useCallback(async () => {const sessionProfile = sidebarProfileForScope(profileScope)- const activationEpoch = gatewayActivationEpoch()// A callback captured before a profile switch may still be queued by an// event subscription. Do not let it start a request against the old scope.@@ -137,16 +136,27 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst requestId = refreshMessagingSessionsRequestRef.current + 1refreshMessagingSessionsRequestRef.current = requestId- try {- const result = await listAllProfileSessions(MESSAGING_SECTION_LIMIT, 1, 'exclude', 'recent', sessionProfile, {+ const owns = () =>+ refreshMessagingSessionsRequestRef.current === requestId &&+ sidebarProfileForScope(profileScopeRef.current) === sessionProfile++ const fetchPage = () =>+ listAllProfileSessions(MESSAGING_SECTION_LIMIT, 1, 'exclude', 'recent', sessionProfile, {excludeSources: MESSAGING_EXCLUDED_SOURCES})- if (- refreshMessagingSessionsRequestRef.current !== requestId ||- sidebarProfileForScope(profileScopeRef.current) !== sessionProfile ||- gatewayActivationEpoch() !== activationEpoch- ) {+ try {+ let activationEpoch = gatewayActivationEpoch()+ let result = await fetchPage()++ // Same re-read as refreshSessions: a mid-request activation voids this+ // page, and nothing else asks again when the route atoms did not move.+ while (owns() && gatewayActivationEpoch() !== activationEpoch) {+ activationEpoch = gatewayActivationEpoch()+ result = await fetchPage()+ }++ if (!owns()) {return}@@ -167,7 +177,6 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst loadMoreMessagingForPlatform = useCallback(async (platform: string) => {const sessionProfile = sidebarProfileForScope(profileScope)- const activationEpoch = gatewayActivationEpoch()if (sidebarProfileForScope(profileScopeRef.current) !== sessionProfile) {return@@ -183,27 +192,31 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst inPlatform = (s: SessionInfo) => normalizeSessionSource(s.source) === platform && inProfile(s)const loaded = $messagingSessions.get().filter(inPlatform).length+ const owns = () =>+ loadMoreMessagingRequestRef.current[requestKey] === requestId &&+ sidebarProfileForScope(profileScopeRef.current) === sessionProfile++ const fetchPage = () =>+ listAllProfileSessions(loaded + SIDEBAR_SESSIONS_PAGE_SIZE, 1, 'exclude', 'recent', sessionProfile, {+ source: platform+ })+let resulttry {- result = await listAllProfileSessions(- loaded + SIDEBAR_SESSIONS_PAGE_SIZE,- 1,- 'exclude',- 'recent',- sessionProfile,- { source: platform }- )+ let activationEpoch = gatewayActivationEpoch()+ result = await fetchPage()++ while (owns() && gatewayActivationEpoch() !== activationEpoch) {+ activationEpoch = gatewayActivationEpoch()+ result = await fetchPage()+ }} catch {// Non-fatal: leave the platform's loaded rows and total unchanged.return}- if (- loadMoreMessagingRequestRef.current[requestKey] !== requestId ||- sidebarProfileForScope(profileScopeRef.current) !== sessionProfile ||- gatewayActivationEpoch() !== activationEpoch- ) {+ if (!owns()) {return}@@ -244,7 +257,6 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst refreshSessions = useCallback(async (shouldPublish: () => boolean = () => true) => {const sessionProfile = sidebarProfileForScope(profileScope)- const activationEpoch = gatewayActivationEpoch()if (!shouldPublish() || sidebarProfileForScope(profileScopeRef.current) !== sessionProfile) {return@@ -262,6 +274,11 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgsetSessionsLoading(true)}+ const owns = () =>+ shouldPublish() &&+ refreshSessionsRequestRef.current === requestId &&+ sidebarProfileForScope(profileScopeRef.current) === sessionProfile+try {const limit = $sessionsLimit.get()@@ -278,21 +295,33 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg// Batched: one request opens each profile DB once and returns all three// source-scoped slices, instead of three separate listAllProfileSessions// calls that each reopened + re-counted every profile DB per refresh.- const result = await listSidebarSessions({- recentsProfile: sessionProfile,- recentsLimit: limit,- recentsExclude: SIDEBAR_EXCLUDED_SOURCES,- cronLimit: CRON_SECTION_LIMIT,- messagingLimit: MESSAGING_SECTION_LIMIT,- messagingExclude: MESSAGING_EXCLUDED_SOURCES- })+ const fetchPage = () =>+ listSidebarSessions({+ recentsProfile: sessionProfile,+ recentsLimit: limit,+ recentsExclude: SIDEBAR_EXCLUDED_SOURCES,+ cronLimit: CRON_SECTION_LIMIT,+ messagingLimit: MESSAGING_SECTION_LIMIT,+ messagingExclude: MESSAGING_EXCLUDED_SOURCES+ })++ let activationEpoch = gatewayActivationEpoch()+ let result = await fetchPage()++ // A gateway activation that landed mid-request voids this page: it may+ // describe the source the window just left. But every activation bumps+ // the epoch, including a re-activation of the route already in front+ // (a resume or profile click through ensureGatewayAgent), and those+ // move no route atom, so no effect asks for the list again. Dropping+ // the page there left the sidebar on "No sessions" while the backend+ // held the rows (#67600). Still the newest refresh for this scope, so+ // re-read under the current epoch instead.+ while (owns() && gatewayActivationEpoch() !== activationEpoch) {+ activationEpoch = gatewayActivationEpoch()+ result = await fetchPage()+ }- if (- shouldPublish() &&- refreshSessionsRequestRef.current === requestId &&- sidebarProfileForScope(profileScopeRef.current) === sessionProfile &&- gatewayActivationEpoch() === activationEpoch- ) {+ if (owns()) {const recents = result.recentssetCorruptSessionStores(result.storage)