Skip to content

The agent that grows with you

fix(desktop): follow verified focused session rotations

Mohamad Kanso903898df9b7e
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 5ec44e62886..35fa627da46 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -9,7 +9,8 @@ import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'
import { NO_PROJECT_ID } from '@/app/chat/sidebar/projects/workspace-groups'
import { resolveSessionRpcOwner } from '@/app/contrib/wiring-routing'
import { $terminalTakeover, setTerminalTakeover } from '@/app/right-sidebar/store'
-import { noteActiveTreeGroup, revealTreePane } from '@/components/pane-shell/tree/store'
+import { group } from '@/components/pane-shell/tree/model'
+import { $activeTreeGroup, $layoutTree, noteActiveTreeGroup, revealTreePane } from '@/components/pane-shell/tree/store'
import {
deleteSession,
getAllSessionMessages,
@@ -574,12 +575,51 @@ function StoredIdRotationHarness({
return null
}
+function StoredIdRotationProducerHarness({
+ getRoutedStoredSessionId,
+ navigate,
+ onCache
+}: {
+ getRoutedStoredSessionId: () => null | string
+ navigate: (to: string, options?: { replace?: boolean }) => void
+ onCache: (cache: ReturnType<typeof useSessionStateCache>) => void
+}) {
+ const activeSessionId = useStore($activeSessionId)
+ const selectedStoredSessionId = useStore($selectedStoredSessionId)
+ const busyRef = useRef(false)
+
+ const cache = useSessionStateCache({
+ activeSessionId,
+ busyRef,
+ selectedStoredSessionId,
+ setAwaitingResponse,
+ setBusy,
+ setMessages
+ })
+
+ onCache(cache)
+
+ return (
+ <StoredIdRotationHarness
+ activeSessionIdRef={cache.activeSessionIdRef}
+ getRoutedStoredSessionId={getRoutedStoredSessionId}
+ navigate={navigate}
+ selectedStoredSessionIdRef={cache.selectedStoredSessionIdRef}
+ />
+ )
+}
+
describe('active stored-session id rotation routing', () => {
afterEach(() => {
cleanup()
setActiveSessionId(null)
setActiveSessionStoredIdRotation(null)
setSelectedStoredSessionId(null)
+ setSessions([])
+ $sessionTiles.set([])
+ $layoutTree.set(null)
+ $activeTreeGroup.set(null)
+ window.history.pushState({}, '', '/')
vi.restoreAllMocks()
})
@@ -641,6 +681,94 @@ describe('active stored-session id rotation routing', () => {
clearAllSessionStates()
})
+ it('follows a proven rotation when its unloaded successor already has focus', async () => {
+ const previousId = 'stored-A'
+ const nextId = 'stored-A-next'
+ const runtimeId = 'runtime-A'
+ const navigate = vi.fn()
+ let cache: ReturnType<typeof useSessionStateCache> | undefined
+
+ setSessions([])
+ setSelectedStoredSessionId(previousId)
+ setActiveSessionId(runtimeId)
+ window.history.pushState({}, '', `/#/${previousId}`)
+
+ render(
+ <StoredIdRotationProducerHarness
+ getRoutedStoredSessionId={() => previousId}
+ navigate={navigate}
+ onCache={value => {
+ cache = value
+ }}
+ />
+ )
+
+ expect(cache).toBeDefined()
+
+ act(() => {
+ // The real cache emits the rotation while the previous session still
+ // owns focus, then the successor tile takes focus before React runs the
+ // route-follow effect. The refreshed row is still missing at that point.
+ cache!.updateSessionState(runtimeId, state => state, previousId)
+ cache!.updateSessionState(runtimeId, state => state, nextId)
+ setSessions([])
+ $sessionTiles.set([{ storedSessionId: nextId } as never])
+ $layoutTree.set(
+ group(['workspace', `session-tile:${nextId}`], {
+ active: `session-tile:${nextId}`,
+ id: 'grp-main'
+ })
+ )
+ $activeTreeGroup.set('grp-main')
+ })
+
+ await waitFor(() => expect($selectedStoredSessionId.get()).toBe(nextId))
+ expect(navigate).toHaveBeenCalledWith(sessionRoute(nextId), { replace: true })
+ expect($activeSessionStoredIdRotation.get()).toBeNull()
+ })
+
+ it('does not follow a rotation when an unrelated tile has focus', async () => {
+ const previousId = 'stored-A'
+ const nextId = 'stored-A-next'
+ const unrelatedId = 'stored-C'
+ const runtimeId = 'runtime-A'
+ const navigate = vi.fn()
+ let cache: ReturnType<typeof useSessionStateCache> | undefined
+
+ setSessions([])
+ setSelectedStoredSessionId(previousId)
+ setActiveSessionId(runtimeId)
+ window.history.pushState({}, '', `/#/${previousId}`)
+
+ render(
+ <StoredIdRotationProducerHarness
+ getRoutedStoredSessionId={() => previousId}
+ navigate={navigate}
+ onCache={value => {
+ cache = value
+ }}
+ />
+ )
+
+ act(() => {
+ cache!.updateSessionState(runtimeId, state => state, previousId)
+ cache!.updateSessionState(runtimeId, state => state, nextId)
+ setSessions([])
+ $sessionTiles.set([{ storedSessionId: unrelatedId } as never])
+ $layoutTree.set(
+ group(['workspace', `session-tile:${unrelatedId}`], {
+ active: `session-tile:${unrelatedId}`,
+ id: 'grp-main'
+ })
+ )
+ $activeTreeGroup.set('grp-main')
+ })
+
+ await waitFor(() => expect($activeSessionStoredIdRotation.get()).toBeNull())
+ expect($selectedStoredSessionId.get()).toBe(previousId)
+ expect(navigate).not.toHaveBeenCalled()
+ })
+
it('keeps draft on the previous tip when the new tip row is not loaded yet', async () => {
const tipBefore = 'tip-root'
const tipAfter = 'tip-new-unloaded'
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index b631e36ba81..80c59febf98 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -80,6 +80,7 @@ import {
$yoloActive,
getCurrentModelSource,
getSessionOwnerHint,
+ idsShareLineage,
type NewChatWorkspaceTarget,
resolveComposerSessionKey,
sessionPinId,
@@ -123,6 +124,7 @@ import {
type SessionProfileRoute
} from '@/store/session-request-router'
import {
+ $focusedStoredSessionId,
$sessionTiles,
closeSessionTile,
dropSessionState,
@@ -500,12 +502,24 @@ export function useSessionActions({
const selectedStoredSessionId = selectedStoredSessionIdRef.current
const routedStoredSessionId = getRoutedStoredSessionId()
+ const previousId = storedIdRotation.previousStoredSessionId
+ const nextId = storedIdRotation.nextStoredSessionId
+ const sessions = $sessions.get()
+ const focusedStoredSessionId = $focusedStoredSessionId.get()
+
+ // A tile can adopt the exact successor before the refreshed sessions list
+ // contains it. The rotation itself proves that this focus is the same live
+ // runtime; unrelated focused chats still fail the foreground check.
+ const focusedOnRotatedLineage = Boolean(
+ focusedStoredSessionId &&
+ (focusedStoredSessionId === nextId || idsShareLineage(focusedStoredSessionId, nextId, sessions))
+ )
if (
activeSessionIdRef.current !== storedIdRotation.runtimeSessionId ||
- selectedStoredSessionId !== storedIdRotation.previousStoredSessionId ||
- (routedStoredSessionId !== null && routedStoredSessionId !== storedIdRotation.previousStoredSessionId) ||
- !isSessionInForeground(storedIdRotation.previousStoredSessionId)
+ selectedStoredSessionId !== previousId ||
+ (routedStoredSessionId !== null && routedStoredSessionId !== previousId) ||
+ (!isSessionInForeground(previousId) && !focusedOnRotatedLineage)
) {
return
}
@@ -516,9 +530,6 @@ export function useSessionActions({
// live editor text on a brief remount. If the new tip row is not in
// $sessions yet, resolveComposerSessionKey falls back to the tip id — prefer
// the previous id (usually the lineage root) in that gap.
- const previousId = storedIdRotation.previousStoredSessionId
- const nextId = storedIdRotation.nextStoredSessionId
- const sessions = $sessions.get()
const resolvedNext = resolveComposerSessionKey(nextId, sessions)
const durableKey =