Skip to content

The agent that grows with you

fix(desktop): reject stale profile refreshes

David Dudok de Wit4f670a3f95c5
diff --git a/apps/desktop/src/app/chat/sidebar/profile-scope.test.ts b/apps/desktop/src/app/chat/sidebar/profile-scope.test.ts
index fdd1e1d9b29..14e73edb615 100644
--- a/apps/desktop/src/app/chat/sidebar/profile-scope.test.ts
+++ b/apps/desktop/src/app/chat/sidebar/profile-scope.test.ts
@@ -5,6 +5,7 @@ import type { SessionInfo } from '@/types/hermes'
import { filterSessionsByProfileScope } from './profile-scope'
+/** Build the smallest session row needed by the profile-scope tests. */
const row = (id: string, profile?: string): SessionInfo =>
({ id, message_count: 1, profile, source: 'signal', started_at: 0, title: id }) as SessionInfo
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.tsx
index fbaf3c7d79d..db676dbbd21 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
@@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { SessionInfo, SidebarSessionsResponse } from '@/hermes'
+import { $cronJobs, setCronJobs } from '@/store/cron'
import {
$cronSessions,
$messagingPlatformTotals,
@@ -57,12 +58,14 @@ const sidebar = (
const listSidebarSessions = vi.fn()
const listAllProfileSessions = vi.fn()
+const getCronJobs = vi.fn()
interface Deferred<T> {
promise: Promise<T>
resolve: (value: T) => void
}
+/** Create a promise whose completion order the stale-response tests control. */
function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void
@@ -75,7 +78,7 @@ function deferred<T>(): Deferred<T> {
vi.mock('@/hermes', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
- getCronJobs: vi.fn(async () => []),
+ getCronJobs: (...args: unknown[]) => getCronJobs(...args),
listAllProfileSessions: (...args: unknown[]) => listAllProfileSessions(...args),
listSidebarSessions: (...args: unknown[]) => listSidebarSessions(...args)
}))
@@ -89,9 +92,12 @@ vi.mock('@/store/projects', () => ({
}))
beforeEach(() => {
+ getCronJobs.mockReset()
+ getCronJobs.mockResolvedValue([])
listSidebarSessions.mockReset()
listAllProfileSessions.mockReset()
removed.ids = new Set()
+ setCronJobs([])
setSessions([])
setCronSessions([])
setMessagingSessions([])
@@ -101,6 +107,7 @@ beforeEach(() => {
})
afterEach(() => {
+ setCronJobs([])
setSessions([])
setCronSessions([])
setMessagingSessions([])
@@ -284,8 +291,67 @@ describe('refreshSessions batches slices into one request', () => {
)
})
+ it('does not start a refresh callback captured before a profile switch', async () => {
+ listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))
+
+ const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
+ initialProps: { profileScope: 'work' }
+ })
+
+ const staleRefresh = result.current.refreshSessions
+
+ rerender({ profileScope: 'personal' })
+
+ await act(async () => {
+ await staleRefresh()
+ })
+
+ expect(listSidebarSessions).not.toHaveBeenCalled()
+ })
+
+ it('ignores an in-flight sidebar response after the active profile changes', async () => {
+ const work = deferred<SidebarSessionsResponse>()
+ const personal = deferred<SidebarSessionsResponse>()
+
+ listSidebarSessions.mockImplementation(({ recentsProfile }) =>
+ recentsProfile === 'work' ? work.promise : personal.promise
+ )
+
+ const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
+ initialProps: { profileScope: 'work' }
+ })
+
+ const workRefresh = result.current.refreshSessions()
+
+ rerender({ profileScope: 'personal' })
+ const personalRefresh = result.current.refreshSessions()
+
+ await act(async () => {
+ personal.resolve(
+ sidebar(
+ { sessions: [row('personal-session', { profile: 'personal' })] },
+ [row('personal-cron', { profile: 'personal', source: 'cron' })],
+ [row('personal-signal', { profile: 'personal', source: 'signal' })]
+ )
+ )
+ await personalRefresh
+
+ work.resolve(
+ sidebar(
+ { sessions: [row('work-session', { profile: 'work' })] },
+ [row('work-cron', { profile: 'work', source: 'cron' })],
+ [row('work-telegram', { profile: 'work', source: 'telegram' })]
+ )
+ )
+ await workRefresh
+ })
+
+ expect($sessions.get().map(session => session.id)).toEqual(['personal-session'])
+ expect($cronSessions.get().map(session => session.id)).toEqual(['personal-cron'])
+ expect($messagingSessions.get().map(session => session.id)).toEqual(['personal-signal'])
+ })
+
it('scopes the cron-jobs fetch to the active profile (all → unified view)', async () => {
- const { getCronJobs } = await import('@/hermes')
listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] }))
const scoped = renderHook(() => useSessionListActions({ profileScope: 'work' }))
@@ -304,6 +370,33 @@ describe('refreshSessions batches slices into one request', () => {
expect(getCronJobs).toHaveBeenLastCalledWith('all')
})
+
+ it('ignores an out-of-order cron-jobs response from the previous profile', async () => {
+ const work = deferred<Array<{ enabled: boolean; id: string }>>()
+ const personal = deferred<Array<{ enabled: boolean; id: string }>>()
+
+ getCronJobs.mockImplementation((profile: string) => (profile === 'work' ? work.promise : personal.promise))
+
+ const { rerender, result } = renderHook(({ profileScope }) => useSessionListActions({ profileScope }), {
+ initialProps: { profileScope: 'work' }
+ })
+
+ const workRefresh = result.current.refreshCronJobs()
+
+ rerender({ profileScope: 'personal' })
+ const personalRefresh = result.current.refreshCronJobs()
+
+ await act(async () => {
+ personal.resolve([{ enabled: true, id: 'personal-job' }])
+ await personalRefresh
+
+ work.resolve([{ enabled: true, id: 'work-job' }])
+ await workRefresh
+ })
+
+ expect(getCronJobs.mock.calls.map(call => call[0])).toEqual(['work', 'personal'])
+ expect($cronJobs.get().map(job => job.id)).toEqual(['personal-job'])
+ })
})
describe('messaging profile scope', () => {
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.ts
index 72e497142db..9eece2d2ec4 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
@@ -102,15 +102,12 @@ interface UseSessionListActionsArgs {
export function useSessionListActions({ profileScope }: UseSessionListActionsArgs) {
const profileScopeRef = useRef(profileScope)
const loadMoreMessagingRequestRef = useRef<Record<string, number>>({})
+ const refreshCronJobsRequestRef = useRef(0)
const refreshMessagingSessionsRequestRef = useRef(0)
const refreshSessionsRequestRef = useRef(0)
profileScopeRef.current = profileScope
- // Messaging-platform sessions as their own slice, fetched separately from
- // local recents so each platform renders a self-managed section and never
- // competes with local chats for the recents page budget. Keep the fetch on
- // the sidebar's profile scope; otherwise a remote-profile switch leaks one
- // instance's Telegram/Signal sections into another instance's workspace.
+ /** Refresh the active profile's messaging-platform sidebar slice. */
const refreshMessagingSessions = useCallback(async () => {
const sessionProfile = messagingProfileFor(profileScope)
@@ -148,9 +145,7 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
}
}, [profileScope])
- // Page a single platform's section independently (mirrors the per-profile
- // pager): fetch that source's next window and merge it back in place, leaving
- // every other platform's rows untouched. Resolves the platform's exact total.
+ /** Page one messaging platform without replacing another platform's rows. */
const loadMoreMessagingForPlatform = useCallback(
async (platform: string) => {
const sessionProfile = messagingProfileFor(profileScope)
@@ -199,22 +194,32 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
[profileScope]
)
- // Cron *jobs* drive the sidebar "Cron jobs" section. Jobs are created
- // synchronously (agent tool call or the cron UI), so refreshing here right
- // after an agent turn surfaces a new job immediately; the interval poll keeps
- // next-run/state fresh as the scheduler advances them. Jobs live per-profile
- // on disk and the list endpoint aggregates 'all' by default, so scope the
- // fetch to the sidebar's profile scope — a concrete profile sees only its
- // own jobs; ALL_PROFILES keeps the unified view.
+ /** Refresh cron jobs only while the profile that requested them remains active. */
const refreshCronJobs = useCallback(async () => {
+ const sessionProfile = messagingProfileFor(profileScope)
+
+ if (messagingProfileFor(profileScopeRef.current) !== sessionProfile) {
+ return
+ }
+
+ const requestId = refreshCronJobsRequestRef.current + 1
+ refreshCronJobsRequestRef.current = requestId
+
try {
- await refreshCronJobsStore(messagingProfileFor(profileScope))
+ await refreshCronJobsStore(sessionProfile)
} catch {
// Non-fatal: the cron section just keeps its last-known jobs.
}
}, [profileScope])
+ /** Refresh every sidebar session slice without committing an obsolete profile response. */
const refreshSessions = useCallback(async () => {
+ const sessionProfile = messagingProfileFor(profileScope)
+
+ if (messagingProfileFor(profileScopeRef.current) !== sessionProfile) {
+ return
+ }
+
const requestId = refreshSessionsRequestRef.current + 1
refreshSessionsRequestRef.current = requestId
// The loading flag exists to drive the initial skeletons (they only render
@@ -240,8 +245,6 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
// with few recent sessions isn't windowed out of the cross-profile
// recency page and never inherits another profile's cron or messaging
// sections. ALL_PROFILES remains the explicit unified view.
- const sessionProfile = messagingProfileFor(profileScope)
-
// 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.
@@ -254,7 +257,10 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
messagingExclude: MESSAGING_EXCLUDED_SOURCES
})
- if (refreshSessionsRequestRef.current === requestId) {
+ if (
+ refreshSessionsRequestRef.current === requestId &&
+ messagingProfileFor(profileScopeRef.current) === sessionProfile
+ ) {
const recents = result.recents
// Drop rows the user just deleted/archived: a refresh can race an
@@ -319,7 +325,9 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
}
// Cron *jobs* are a distinct API (getCronJobs), not a session slice.
- void refreshCronJobs()
+ if (messagingProfileFor(profileScopeRef.current) === sessionProfile) {
+ void refreshCronJobs()
+ }
}, [profileScope, refreshCronJobs])
const loadMoreSessions = useCallback(async () => {