The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): hold the create guard until the route catches up to the new session
Brooklyn Nicholsonb68f28804fc2
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 4850d90e243..a0517fdb7aa 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -583,6 +583,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {onFreshDraftRouteIntent: clearRoutedSessionIntent,requestGateway,resetViewSync,+ routedSessionId,runtimeIdByStoredSessionIdRef,selectedStoredSessionId,selectedStoredSessionIdRef,diff --git a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx b/apps/desktop/src/app/session/hooks/default-new-session.test.tsxindex 34524b10684..df629e4b87c 100644--- a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx+++ b/apps/desktop/src/app/session/hooks/default-new-session.test.tsx@@ -64,6 +64,7 @@ function mountActions() {navigate,requestGateway,resetViewSync: vi.fn(),+ routedSessionId: null,runtimeIdByStoredSessionIdRef: ref(new Map()),selectedStoredSessionId: null,selectedStoredSessionIdRef: ref<string | null>(null),diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsxindex 8c2973fe6d0..0e2efc65ed3 100644--- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx+++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx@@ -321,6 +321,7 @@ function Harness({navigate: vi.fn() as never,requestGateway,resetViewSync: cache.resetViewSync,+ routedSessionId: null,runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,selectedStoredSessionId,selectedStoredSessionIdRef: cache.selectedStoredSessionIdRef,diff --git a/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsxindex 542a63201c5..fc954261b38 100644--- a/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx+++ b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx@@ -84,7 +84,8 @@ function mount(snapshot: SessionResumeResult) {getRouteToken: () => 'A',getRoutedStoredSessionId: () => null,navigate: vi.fn(),- requestGateway+ requestGateway,+ routedSessionId: null})const stream = useMessageStream({diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsxindex cf454267ce7..85139d96c1b 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx@@ -49,6 +49,150 @@ describe('useRouteResume', () => {vi.restoreAllMocks()})+ it('does not resume stale routed session A while the create guard holds selection on B (#66057)', () => {+ // createBackendSessionForSend updates refs/atoms to B and navigates, but the+ // router can still report A for a tick. While creatingSessionRef is true,+ // stuckOnRoutedSession must NOT treat that as "stranded on A" and call+ // resumeSession(A) (jump-back bug).+ const resumeSession = vi.fn(async () => undefined)+ const startFreshSessionDraft = vi.fn()+ const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-B' }+ const creatingSessionRef = { current: true }+ const runtimeIdByStoredSessionIdRef = { current: new Map([['session-B', 'runtime-B']]) }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-B' }++ const { rerender } = render(+ <RouteResumeHarness+ activeSessionId="runtime-A"+ activeSessionIdRef={{ current: 'runtime-A' }}+ creatingSessionRef={{ current: false }}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-A"+ resumeSession={resumeSession}+ routedSessionId="session-A"+ runtimeIdByStoredSessionIdRef={{ current: new Map([['session-A', 'runtime-A']]) }}+ selectedStoredSessionId="session-A"+ selectedStoredSessionIdRef={{ current: 'session-A' }}+ startFreshSessionDraft={startFreshSessionDraft}+ />+ )++ expect(resumeSession).not.toHaveBeenCalled()++ // Simulate post-create: refs/atoms already on B, route still on A, create+ // guard still held until the router catches up.+ rerender(+ <RouteResumeHarness+ activeSessionId="runtime-B"+ activeSessionIdRef={activeSessionIdRef}+ creatingSessionRef={creatingSessionRef}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-A"+ resumeSession={resumeSession}+ routedSessionId="session-A"+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionId="session-B"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ startFreshSessionDraft={startFreshSessionDraft}+ />+ )++ expect(resumeSession).not.toHaveBeenCalled()+ })++ it('holds the create guard until the route catches up to the created session (#66057)', () => {+ // While creatingSessionRef is true, even the stale-route + moved-selection+ // shape must not resume. (Belt + guard: selectionMovedAheadOfRoute alone+ // also blocks; this asserts the creatingSessionRef gate still works.)+ const resumeSession = vi.fn(async () => undefined)+ const startFreshSessionDraft = vi.fn()+ const creatingSessionRef = { current: true }+ const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-B' }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-B' }++ render(+ <RouteResumeHarness+ activeSessionId="runtime-B"+ activeSessionIdRef={activeSessionIdRef}+ creatingSessionRef={creatingSessionRef}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-A"+ resumeSession={resumeSession}+ routedSessionId="session-A"+ runtimeIdByStoredSessionIdRef={{ current: new Map([['session-B', 'runtime-B']]) }}+ selectedStoredSessionId="session-B"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ startFreshSessionDraft={startFreshSessionDraft}+ />+ )++ expect(resumeSession).not.toHaveBeenCalled()+ })++ it('recovers by resuming A after create timeout when the route never catches up to B', () => {+ // Post-timeout shape: creatingSessionRef false, selection/active on B, route+ // still on A. selectionMovedAheadOfRoute must NOT keep blocking once the+ // pending-create hold is gone — stuckOnRoutedSession should resume A so+ // ChatView leaves its route/selection mismatch loading state.+ const resumeSession = vi.fn(async () => undefined)+ const startFreshSessionDraft = vi.fn()+ const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-A' }+ const creatingSessionRef = { current: false }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-A' }++ const { rerender } = render(+ <RouteResumeHarness+ activeSessionId="runtime-A"+ activeSessionIdRef={activeSessionIdRef}+ creatingSessionRef={creatingSessionRef}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-A"+ resumeSession={resumeSession}+ routedSessionId="session-A"+ runtimeIdByStoredSessionIdRef={{ current: new Map([['session-A', 'runtime-A']]) }}+ selectedStoredSessionId="session-A"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ startFreshSessionDraft={startFreshSessionDraft}+ />+ )++ expect(resumeSession).not.toHaveBeenCalled()++ // Create moved selection/runtime to B; safety timeout already released the+ // guard; router never left A.+ activeSessionIdRef.current = 'runtime-B'+ selectedStoredSessionIdRef.current = 'session-B'+ creatingSessionRef.current = false+ rerender(+ <RouteResumeHarness+ activeSessionId="runtime-B"+ activeSessionIdRef={activeSessionIdRef}+ creatingSessionRef={creatingSessionRef}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-A"+ resumeSession={resumeSession}+ routedSessionId="session-A"+ runtimeIdByStoredSessionIdRef={{ current: new Map([['session-B', 'runtime-B']]) }}+ selectedStoredSessionId="session-B"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ startFreshSessionDraft={startFreshSessionDraft}+ />+ )++ expect(resumeSession).toHaveBeenCalledTimes(1)+ expect(resumeSession).toHaveBeenCalledWith('session-A', true)+ })+it('does not re-resume the old session during a /:sid -> /new transition', () => {const resumeSession = vi.fn(async () => undefined)const startFreshSessionDraft = vi.fn()diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.tsindex 9cffa97e724..81e11622d1f 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts@@ -150,7 +150,26 @@ export function useRouteResume({// pathname flips to / (same null+/:sid signature). freshDraftReady is the// discriminator: it's true while heading into a blank new chat, false when// genuinely stranded on a routed session.- const stuckOnRoutedSession = routedSessionId !== selectedStoredSessionIdRef.current && !freshDraftReady+ //+ // Also must NOT fire when create/fork already moved selection + runtime to+ // a new session B while the router still shows stale A (#66057). That looks+ // "stuck on A" but resuming A yanks the UI back off the new chat.+ //+ // Scope this suppression to an active pending-create hold only. Once+ // creatingSessionRef drops (route caught up, user left, or the safety+ // timeout), a lingering A-route / B-selection mismatch must be able to+ // self-heal via stuckOnRoutedSession — otherwise ChatView stays in its+ // route/selection loading state forever after a stuck navigate.+ const selectionMovedAheadOfRoute =+ creatingSessionRef.current &&+ Boolean(selectedStoredSessionIdRef.current) &&+ selectedStoredSessionIdRef.current !== routedSessionId &&+ Boolean(activeSessionIdRef.current)++ const stuckOnRoutedSession =+ routedSessionId !== selectedStoredSessionIdRef.current &&+ !freshDraftReady &&+ !selectionMovedAheadOfRoute// Resume when the route meaningfully changed, the gateway just opened, or// we're stranded on a routed session that never loaded. The first twodiff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 41c20060df2..629aaa670f2 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@@ -221,10 +221,10 @@ function Harness({navigate: navigate as never,requestGateway,resetViewSync: vi.fn(),+ routedSessionId: null,runtimeIdByStoredSessionIdRef: runtimeIdByStoredSessionIdRefOverride ?? ref(new Map<string, string>()),selectedStoredSessionId,- selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride ?? ref(selectedStoredSessionId),- sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),+ selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride ?? ref(selectedStoredSessionId), sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),syncSessionStateToView: vi.fn(),updateSessionState: updateSessionStateOverride ?? (() => ({}) as ClientSessionState)})@@ -566,6 +566,7 @@ function StoredIdRotationHarness({navigate: navigate as never,requestGateway: async () => ({}) as never,resetViewSync: vi.fn(),+ routedSessionId: getRoutedStoredSessionId(),runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),selectedStoredSessionId: selectedStoredSessionIdRef.current,selectedStoredSessionIdRef,@@ -1323,8 +1324,8 @@ function ResumeHarness({navigate: vi.fn() as never,requestGateway,resetViewSync: vi.fn(),- runtimeIdByStoredSessionIdRef: runtimeMapRef,- selectedStoredSessionId,+ routedSessionId: null,+ runtimeIdByStoredSessionIdRef: runtimeMapRef, selectedStoredSessionId,selectedStoredSessionIdRef: ref<string | null>(selectedStoredSessionId),sessionStateByRuntimeIdRef: stateMapRef,holdSessionTranscriptView: runtimeId => {@@ -2416,6 +2417,7 @@ function BranchHarness({navigate: navigate as never,requestGateway,resetViewSync: vi.fn(),+ routedSessionId: null,runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),selectedStoredSessionId,selectedStoredSessionIdRef,@@ -6129,3 +6131,243 @@ describe('routed fresh chat keeps its exact owner across turns', () => {expect($freshDraftKey.get()).toBe(before)})})++describe('createBackendSessionForSend creatingSessionRef hold (#66057)', () => {+ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ $newChatProfile.set(null)+ $activeGatewayProfile.set('default')+ setCurrentCwd('')+ setNewChatWorkspaceTarget(undefined)+ vi.restoreAllMocks()+ })++ function GuardHarness({+ creatingSessionRef,+ navigate,+ onReady,+ requestGateway,+ routeId,+ selectedStoredSessionIdRef+ }: {+ creatingSessionRef: MutableRefObject<boolean>+ navigate: (...args: never[]) => unknown+ onReady: (create: () => Promise<string | null>) => void+ requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>+ routeId: null | string+ selectedStoredSessionIdRef: MutableRefObject<null | string>+ }) {+ const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })+ const actions = useSessionActions({+ activeSessionId: null,+ activeSessionIdRef: ref<string | null>(null),+ busyRef: ref(false),+ creatingSessionRef,+ ensureSessionState: () => ({}) as ClientSessionState,+ getRouteToken: () => 'token',+ getRoutedStoredSessionId: () => routeId,+ navigate: navigate as never,+ requestGateway,+ resetViewSync: vi.fn(),+ routedSessionId: routeId,+ runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),+ selectedStoredSessionId: selectedStoredSessionIdRef.current,+ selectedStoredSessionIdRef,+ sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),+ syncSessionStateToView: vi.fn(),+ updateSessionState: () => ({}) as ClientSessionState+ })++ useEffect(() => {+ onReady(() => actions.createBackendSessionForSend())+ }, [actions, onReady])++ return null+ }++ it('keeps creatingSessionRef true until routedSessionId catches up to the created stored id', async () => {+ const creatingSessionRef: MutableRefObject<boolean> = { current: false }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: null }+ const navigate = vi.fn()+ let routedSessionId: null | string = 'session-A'++ const requestGateway = async <T,>(method: string): Promise<T> => {+ if (method === 'session.create') {+ return { session_id: 'rt-new', stored_session_id: 'stored-new' } as T+ }++ return {} as T+ }++ let create: (() => Promise<string | null>) | null = null+ const { rerender } = render(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={fn => (create = fn)}+ requestGateway={requestGateway}+ routeId={routedSessionId}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ await waitFor(() => expect(create).not.toBeNull())++ await act(async () => {+ await create!()+ })++ expect(navigate).toHaveBeenCalled()+ expect(creatingSessionRef.current).toBe(true)+ expect(selectedStoredSessionIdRef.current).toBe('stored-new')++ // Route still stale on A — guard must stay up (not a user navigation away).+ rerender(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={() => undefined}+ requestGateway={requestGateway}+ routeId="session-A"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ expect(creatingSessionRef.current).toBe(true)++ // Router catches up to the created stored id — release the guard.+ routedSessionId = 'stored-new'+ rerender(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={() => undefined}+ requestGateway={requestGateway}+ routeId={routedSessionId}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ expect(creatingSessionRef.current).toBe(false)+ })++ it('clears creatingSessionRef when navigate throws', async () => {+ const creatingSessionRef: MutableRefObject<boolean> = { current: false }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: null }+ const navigate = vi.fn(() => {+ throw new Error('navigate failed')+ })++ let create: (() => Promise<string | null>) | null = null+ render(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={fn => (create = fn)}+ requestGateway={async method => {+ if (method === 'session.create') {+ return { session_id: 'rt-new', stored_session_id: 'stored-new' } as never+ }++ return {} as never+ }}+ routeId="session-A"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ await waitFor(() => expect(create).not.toBeNull())++ await act(async () => {+ await create!()+ })++ expect(navigate).toHaveBeenCalled()+ expect(creatingSessionRef.current).toBe(false)+ })++ it('clears creatingSessionRef when the route moves to a different session than pending', async () => {+ const creatingSessionRef: MutableRefObject<boolean> = { current: false }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: null }+ const navigate = vi.fn()++ const requestGateway = async <T,>(method: string): Promise<T> => {+ if (method === 'session.create') {+ return { session_id: 'rt-new', stored_session_id: 'stored-new' } as T+ }++ return {} as T+ }++ let create: (() => Promise<string | null>) | null = null+ const { rerender } = render(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={fn => (create = fn)}+ requestGateway={requestGateway}+ routeId="session-A"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ await waitFor(() => expect(create).not.toBeNull())++ await act(async () => {+ await create!()+ })+ expect(creatingSessionRef.current).toBe(true)++ // User clicked another session while create navigate was still pending.+ rerender(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={() => undefined}+ requestGateway={requestGateway}+ routeId="session-C"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ expect(creatingSessionRef.current).toBe(false)+ })++ it('clears creatingSessionRef via safety timeout if the route never catches up', async () => {+ const creatingSessionRef: MutableRefObject<boolean> = { current: false }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: null }+ const navigate = vi.fn()++ let create: (() => Promise<string | null>) | null = null+ render(+ <GuardHarness+ creatingSessionRef={creatingSessionRef}+ navigate={navigate}+ onReady={fn => (create = fn)}+ requestGateway={async method => {+ if (method === 'session.create') {+ return { session_id: 'rt-new', stored_session_id: 'stored-new' } as never+ }++ return {} as never+ }}+ routeId="session-A"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ await waitFor(() => expect(create).not.toBeNull())++ // Arm the pending timeout under fake timers so we can advance deterministically.+ vi.useFakeTimers()+ await act(async () => {+ await create!()+ })+ expect(creatingSessionRef.current).toBe(true)+ expect(navigate).toHaveBeenCalledTimes(1)++ // Route stays on A forever — safety timeout must retry navigate (reconcile)+ // and drop the guard so use-route-resume can self-heal if the route still+ // never moves.+ await act(async () => {+ await vi.advanceTimersByTimeAsync(3_000)+ })+ expect(creatingSessionRef.current).toBe(false)+ expect(navigate).toHaveBeenCalledTimes(2)+ expect(navigate).toHaveBeenLastCalledWith('/stored-new', { replace: true })+ })+})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.tsindex 8416102dc93..51b851783fe 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@@ -214,6 +214,10 @@ interface SessionActionsOptions {onFreshDraftRouteIntent?: () => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>resetViewSync: () => void+ // Live route session id from the router. Used to drop creatingSessionRef only+ // after navigate to a freshly created/forked stored id has actually landed+ // (setTimeout(0) cleared the guard before the route caught up — #66057).+ routedSessionId: string | nullruntimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>selectedStoredSessionId: string | nullselectedStoredSessionIdRef: MutableRefObject<string | null>@@ -262,6 +266,10 @@ function branchCreateKey({})}+// How long we keep creatingSessionRef after create/fork navigate before giving up+// if the router never lands on the pending stored id (stuck navigate / lost race).+const CREATE_GUARD_RELEASE_MS = 3_000+// Reflect a stored row's persisted token counts into the live usage atom// (total is derived, so callers can't drift it out of sync with input/output).function applyStoredUsage(stored: { input_tokens?: number | null; output_tokens?: number | null }) {@@ -464,6 +472,7 @@ export function useSessionActions({onFreshDraftRouteIntent,requestGateway,resetViewSync,+ routedSessionId,runtimeIdByStoredSessionIdRef,selectedStoredSessionId,selectedStoredSessionIdRef,@@ -478,6 +487,97 @@ export function useSessionActions({const coldDisplayReadsRef = useRef(new Map<string, symbol>())const branchCreateFlightsRef = useRef(new Map<string, Promise<SessionCreateResponse>>())+ // Stored id we just created/forked and navigated to. creatingSessionRef stays+ // true until routedSessionId + selection both agree on this id — clearing via+ // setTimeout(0) let use-route-resume resume the stale route as "stuck" (#66057).+ const pendingCreatedStoredSessionIdRef = useRef<string | null>(null)+ // Route id at the moment we armed pending (often the stale previous session).+ // Distinguishes "router still lagging on A" from "user navigated to C".+ const pendingCreatedFromRouteRef = useRef<string | null>(null)+ const pendingGuardTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)++ const releaseCreatingSessionGuard = useCallback(() => {+ if (pendingGuardTimeoutRef.current != null) {+ clearTimeout(pendingGuardTimeoutRef.current)+ pendingGuardTimeoutRef.current = null+ }++ pendingCreatedStoredSessionIdRef.current = null+ pendingCreatedFromRouteRef.current = null+ creatingSessionRef.current = false+ }, [creatingSessionRef])++ // Arm the create/fork hold: keep creatingSessionRef until the route lands on+ // `storedId`, the user leaves for another route, navigate throws, or the+ // safety timeout fires (so a stuck router can't block resumes forever).+ const armPendingCreatedSession = useCallback(+ (storedId: string) => {+ pendingCreatedStoredSessionIdRef.current = storedId+ pendingCreatedFromRouteRef.current = routedSessionId++ if (pendingGuardTimeoutRef.current != null) {+ clearTimeout(pendingGuardTimeoutRef.current)+ }++ pendingGuardTimeoutRef.current = setTimeout(() => {+ pendingGuardTimeoutRef.current = null++ if (pendingCreatedStoredSessionIdRef.current !== storedId) {+ return+ }++ // Route never caught up. Retry navigate so ChatView can leave the+ // route/selection mismatch loading state; then drop the guard so+ // use-route-resume can self-heal to the URL if navigate still fails.+ try {+ navigate(sessionRoute(storedId), { replace: true })+ } catch {+ // Ignore — release below still unblocks recovery.+ }++ releaseCreatingSessionGuard()+ }, CREATE_GUARD_RELEASE_MS)+ },+ [navigate, releaseCreatingSessionGuard, routedSessionId]+ )++ useEffect(+ () => () => {+ if (pendingGuardTimeoutRef.current != null) {+ clearTimeout(pendingGuardTimeoutRef.current)+ }+ },+ []+ )++ // Drop the create/fork guard once the router catches up — or if the user+ // navigates somewhere other than the pending id (left the pre-create route).+ useEffect(() => {+ const pending = pendingCreatedStoredSessionIdRef.current++ if (!creatingSessionRef.current || !pending) {+ return+ }++ if (routedSessionId === pending && selectedStoredSessionIdRef.current === pending) {+ releaseCreatingSessionGuard()++ return+ }++ const fromRoute = pendingCreatedFromRouteRef.current++ if (routedSessionId !== fromRoute && routedSessionId !== pending) {+ releaseCreatingSessionGuard()+ }+ }, [+ creatingSessionRef,+ releaseCreatingSessionGuard,+ routedSessionId,+ selectedStoredSessionId,+ selectedStoredSessionIdRef+ ])+// Follow auto-compression's stored-id rotation only while the exact runtime,// selection, and route intent still belong to the rotating conversation.// The previous implementation carried only the next stored id and navigated@@ -810,7 +910,16 @@ export function useSessionActions({// to this chat now (#114122); the composer moves it on scope swap.announceNewSessionDraftKey(stored)createOverrides?.onComposerScopeAssigned?.(stored)- navigate(sessionRoute(stored), { replace: true })+ // Hold creatingSessionRef until the route lands on `stored` (release+ // effect above). setTimeout(0) raced use-route-resume back onto the+ // previous session (#66057).+ armPendingCreatedSession(stored)++ try {+ navigate(sessionRoute(stored), { replace: true })+ } catch {+ releaseCreatingSessionGuard()+ }// Other windows (e.g. the main window when this is the pop-out) can't// see this session until they re-pull the shared list.broadcastSessionsChanged()@@ -839,17 +948,21 @@ export function useSessionActions({return created.session_id} finally {- window.setTimeout(() => {+ // Keep the guard up while a navigate to the new stored id is pending;+ // otherwise clear immediately (abort, error, or create without stored id).+ if (!pendingCreatedStoredSessionIdRef.current) {creatingSessionRef.current = false- }, 0)+ }}},[activeSessionIdRef,+ armPendingCreatedSession,creatingSessionRef,ensureSessionState,getRouteToken,navigate,+ releaseCreatingSessionGuard,requestGateway,resetViewSync,selectedStoredSessionIdRef,@@ -2710,13 +2823,16 @@ export function useSessionActions({return true} catch (err) {+ // Navigate throw or earlier failure after arming pending — never leave+ // creatingSessionRef stuck true.+ releaseCreatingSessionGuard()notifyError(err, copy.branchFailed)return false} finally {- window.setTimeout(() => {+ if (!pendingCreatedStoredSessionIdRef.current) {creatingSessionRef.current = false- }, 0)+ }}},[diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/remove-archived-session.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions/remove-archived-session.test.tsxindex b7b9c53c6b8..b5e9b543474 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/remove-archived-session.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions/remove-archived-session.test.tsx@@ -69,6 +69,7 @@ function Harness({ onReady }: { onReady: (handle: Handle) => void }) {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),diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/unarchive-session.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions/unarchive-session.test.tsxindex 38b2db1e7ad..c3cb42b4b7b 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/unarchive-session.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions/unarchive-session.test.tsx@@ -69,6 +69,7 @@ function Harness({ onReady }: { onReady: (handle: Handle) => void }) {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),diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsxindex 2b868fb7f4c..8833c80cfc9 100644--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx@@ -379,6 +379,7 @@ function RotationHarness({ activeSessionId, onReady, selectedStoredSessionId }:navigate: vi.fn() as never,requestGateway: async () => ({}) as never,resetViewSync: cache.resetViewSync,+ routedSessionId: null,runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,selectedStoredSessionId,selectedStoredSessionIdRef,diff --git a/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx b/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsxindex 9857fbc9b77..fb6be25ee0e 100644--- a/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx+++ b/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx@@ -109,7 +109,8 @@ async function mountWithPendingReplay() {getRouteToken: () => 'A',getRoutedStoredSessionId: () => null,navigate: vi.fn(),- requestGateway+ requestGateway,+ routedSessionId: null})const stream = useMessageStream({diff --git a/apps/desktop/src/app/session/hooks/wrong-session-closeout.test.tsx b/apps/desktop/src/app/session/hooks/wrong-session-closeout.test.tsxindex d2ebf89d751..9dca1168446 100644--- a/apps/desktop/src/app/session/hooks/wrong-session-closeout.test.tsx+++ b/apps/desktop/src/app/session/hooks/wrong-session-closeout.test.tsx@@ -82,6 +82,7 @@ function Harness() {getRouteToken: () => `${routedStoredId ? sessionRoute(routedStoredId) : '/'}::`,getRoutedStoredSessionId: () => routedStoredId,navigate: navigate as never,+ routedSessionId: null,requestGateway,selectedStoredSessionId})