The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): scope new-session drift pins to their owning request
LeonardoLGDS5014f3a1a82a
diff --git a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.test.ts b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.test.tsindex 734a1cf56aa..c7b49f75bdb 100644--- a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.test.ts@@ -9,6 +9,7 @@ const registeredSubmitHandler = vi.hoisted(() => ({}))type SubmitTextForBridge = Parameters<typeof useQuickEntryBridge>[0]['submitText']+type SubmitTextToNewSessionForBridge = Parameters<typeof useQuickEntryBridge>[0]['submitTextToNewSession']vi.mock('@/store/quick-entry', async importOriginal => {const actual = await importOriginal<typeof import('@/store/quick-entry')>()@@ -57,14 +58,17 @@ describe('useQuickEntryBridge', () => {vi.clearAllMocks()})- async function renderBridge(submitText: SubmitTextForBridge = () => true) {+ async function renderBridge(+ submitText: SubmitTextForBridge = () => true,+ submitTextToNewSession: SubmitTextToNewSessionForBridge = async () => ({+ runtimeSessionId: 'runtime-new',+ sessionId: 'stored-new'+ })+ ) {function Harness() {useQuickEntryBridge({submitText,- submitTextToNewSession: async () => ({- runtimeSessionId: 'runtime-new',- sessionId: 'stored-new'- })+ submitTextToNewSession})return null@@ -111,6 +115,37 @@ describe('useQuickEntryBridge', () => {container.remove()})+ it('passes the correlation id as the new-session pin owner', async () => {+ const correlationId = 'new-submit-correlation'+ const ackSubmit = vi.fn()+ const submitTextToNewSession = vi.fn(async () => ({+ runtimeSessionId: 'runtime-new',+ sessionId: 'stored-new'+ }))+ window.hermesDesktop = {+ quickEntry: {+ ackSubmit,+ pushState: vi.fn()+ }+ } as unknown as typeof window.hermesDesktop++ const { container, submit } = await renderBridge(vi.fn(async () => true), submitTextToNewSession)++ await act(async () => {+ await submit({ correlationId, target: 'new', text: 'Send to a new chat' })+ })++ expect(submitTextToNewSession).toHaveBeenCalledWith('Send to a new chat', correlationId)+ expect(ackSubmit).toHaveBeenCalledTimes(1)+ expect(ackSubmit).toHaveBeenCalledWith(correlationId, {+ ok: true,+ runtimeSessionId: 'runtime-new',+ sessionId: 'stored-new'+ })++ container.remove()+ })+it('acknowledges a current-chat submit with no identity without inventing one', async () => {const correlationId = 'current-submit-no-identity'const ackSubmit = vi.fn()diff --git a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.tsindex 6a10e6c502e..da3a69abc83 100644--- a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts+++ b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts@@ -17,7 +17,10 @@ interface QuickEntryBridgeParams {text: string,options?: { onAccepted?: (identity: QuickEntryAcceptedIdentity) => void }) => Promise<boolean> | boolean- submitTextToNewSession: (text: string) => Promise<{ runtimeSessionId: string; sessionId: string }>+ submitTextToNewSession: (+ text: string,+ owner?: string+ ) => Promise<{ runtimeSessionId: string; sessionId: string }>}/** Exact session identity that accepted a prompt (runtime + durable stored id). */@@ -116,7 +119,7 @@ export function useQuickEntryBridge({// Create and submit as one route-neutral operation so drift cannot// orphan the new session (#85590).try {- const created = await submitNewRef.current(text)+ const created = await submitNewRef.current(text, correlationId)ack({ ok: true, runtimeSessionId: created.runtimeSessionId, sessionId: created.sessionId })} catch (error) {ack({ code: 'submit-failed', message: error instanceof Error ? error.message : String(error), ok: false, retryable: true })diff --git a/apps/desktop/src/app/session/hooks/session-context-drift.test.ts b/apps/desktop/src/app/session/hooks/session-context-drift.test.tsindex b76ee155485..fdcf6a73207 100644--- a/apps/desktop/src/app/session/hooks/session-context-drift.test.ts+++ b/apps/desktop/src/app/session/hooks/session-context-drift.test.ts@@ -1,8 +1,15 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it } from 'vitest'import { NEW_CHAT_ROUTE, sessionRoute, SETTINGS_ROUTE } from '../../routes'-import { routeTargetFromToken, sessionContextDrift } from './session-context-drift'+import {+ pinStoredSessionForOwner,+ pinnedOwnerCount,+ pinnedStoredSessionIdsForOwner,+ releaseStoredSessionPins,+ routeTargetFromToken,+ sessionContextDrift+} from './session-context-drift'const SESS_A = 'sess-a'const SESS_B = 'sess-b'@@ -27,31 +34,47 @@ describe('routeTargetFromToken', () => {})describe('sessionContextDrift', () => {- it('keeps a pinned atomic-submit session through drift, then restores normal drift behavior', () => {- const pinned = new Set(['sess-b'])+ afterEach(() => {+ releaseStoredSessionPins('owner-a')+ releaseStoredSessionPins('owner-b')+ })++ it('honors a pin only for its owner', () => {+ pinStoredSessionForOwner('owner-a', 'sess-b')++ const driftInputs = {+ nowRouteToken: routeToken(sessionRoute(SESS_B)),+ nowSelectedStoredId: SESS_B,+ startRouteToken: routeToken(sessionRoute(SESS_A)),+ startSelectedStoredId: SESS_A,+ submitTargetStoredId: null+ }expect(sessionContextDrift({- nowRouteToken: routeToken(sessionRoute(SESS_B)),- nowSelectedStoredId: SESS_B,- pinnedStoredSessionIds: pinned,- startRouteToken: routeToken(sessionRoute(SESS_A)),- startSelectedStoredId: SESS_A,- submitTargetStoredId: null+ ...driftInputs,+ pinOwner: 'owner-a'})).toBeNull()- pinned.delete(SESS_B)expect(sessionContextDrift({- nowRouteToken: routeToken(sessionRoute(SESS_B)),- nowSelectedStoredId: SESS_B,- pinnedStoredSessionIds: pinned,- startRouteToken: routeToken(sessionRoute(SESS_A)),- startSelectedStoredId: SESS_A,- submitTargetStoredId: null+ ...driftInputs,+ pinOwner: 'owner-b'})- ).toBe('route:sess-a->sess-b')+ ).toBe(`route:${SESS_A}->${SESS_B}`)+ expect(sessionContextDrift(driftInputs)).toBe(`route:${SESS_A}->${SESS_B}`)+ })++ it('releases only the named owner', () => {+ pinStoredSessionForOwner('owner-a', SESS_A)+ pinStoredSessionForOwner('owner-b', SESS_B)++ releaseStoredSessionPins('owner-a')++ expect(pinnedStoredSessionIdsForOwner('owner-a').size).toBe(0)+ expect(pinnedStoredSessionIdsForOwner('owner-b')).toContain(SESS_B)+ expect(pinnedOwnerCount()).toBe(1)})it('does not drift on search/hash-only route churn', () => {diff --git a/apps/desktop/src/app/session/hooks/session-context-drift.ts b/apps/desktop/src/app/session/hooks/session-context-drift.tsindex b35725d1595..b85ce0ee928 100644--- a/apps/desktop/src/app/session/hooks/session-context-drift.ts+++ b/apps/desktop/src/app/session/hooks/session-context-drift.ts@@ -56,13 +56,46 @@ interface SessionContextDriftArgs {* session that has ever compressed.*/submitTargetComposerScope?: string | null- /** Stored ids being re-homed by an atomic submit (#85590). */- pinnedStoredSessionIds?: ReadonlySet<string>+ /**+ * The owner token of the request this check belongs to. Only pins created by+ * the SAME owner are honored; omit to ignore pins entirely.+ */+ pinOwner?: string}-// A short-lived pin marks the session being re-homed by atomic quick submit;-// keeping it here lets every drift caller share the same narrow exception (#85590).-export const activePinnedStoredSessionIds = new Set<string>()+// Pins are OWNED (#85590 review): a drift check honors only pins created by the+// SAME owner token — the submit/route generation that created them — so an+// overlapping request can never suppress another request's drift detection.+const pinnedByOwner = new Map<string, Set<string>>()++/** Shared empty set: a non-owning caller allocates nothing. */+const NO_PINS: ReadonlySet<string> = new Set()++/** Mark `storedSessionId` as re-homed by `owner` until its terminal release. */+export function pinStoredSessionForOwner(owner: string, storedSessionId: string): void {+ const pinned = pinnedByOwner.get(owner)++ if (pinned) {+ pinned.add(storedSessionId)+ } else {+ pinnedByOwner.set(owner, new Set([storedSessionId]))+ }+}++/** Terminal release: the owner's request settled (accepted, failed, cancelled).+ * Route settlement is evidence, not a tick budget. */+export function releaseStoredSessionPins(owner: string): void {+ pinnedByOwner.delete(owner)+}++export function pinnedStoredSessionIdsForOwner(owner: string): ReadonlySet<string> {+ return pinnedByOwner.get(owner) ?? NO_PINS+}++/** Owners still holding a pin. Observability + tests. */+export function pinnedOwnerCount(): number {+ return pinnedByOwner.size+}/*** Decide whether the session context genuinely changed under an in-flight@@ -84,9 +117,9 @@ export function sessionContextDrift({submitTargetStoredId,composerScope,submitTargetComposerScope,- pinnedStoredSessionIds: pinnedIds+ pinOwner}: SessionContextDriftArgs): string | null {- const activePins = pinnedIds ?? activePinnedStoredSessionIds+ const activePins = pinOwner ? pinnedStoredSessionIdsForOwner(pinOwner) : NO_PINS// Composer prong: the composer's loaded scope disagrees with the resolved// submit target. Not a start/now comparison like the two prongs below — the// composer only hands us one snapshot per submit — but it belongs in thediff --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 38de0c4f3d2..e65ce929657 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@@ -108,7 +108,11 @@ import { deferred } from '../../../test/deferred'import { NEW_CHAT_ROUTE, sessionRoute } from '../../routes'import type { ClientSessionState } from '../../types'-import { activePinnedStoredSessionIds } from './session-context-drift'+import {+ pinnedOwnerCount,+ pinnedStoredSessionIdsForOwner,+ releaseStoredSessionPins+} from './session-context-drift'import { applySessionInfoStatePatch, sessionInfoStatePatch } from './use-message-stream/utils'import { captureSteeringSession } from './use-prompt-actions/steering-session'import { useSessionActions } from './use-session-actions'@@ -1059,17 +1063,21 @@ describe('startFreshSessionDraft', () => {})describe('submitTextToNewSession pin release', () => {+ beforeEach(() => {+ releaseStoredSessionPins('corr-1')+ releaseStoredSessionPins('owner-a')+ releaseStoredSessionPins('owner-b')+ })+afterEach(() => {- activePinnedStoredSessionIds.clear()cleanup()vi.restoreAllMocks()})- it('force-releases the pin when competing navigation prevents route settlement', async () => {- const stored = 'stored-quick-entry'+ it('releases the pin at the terminal transition instead of on ticks', async () => {const requestGateway = vi.fn(async (method: string) => {if (method === 'session.create') {- return { session_id: RUNTIME_SESSION_ID, stored_session_id: stored } as never+ return { session_id: RUNTIME_SESSION_ID, stored_session_id: 'stored-quick-entry' } as never}return {} as never@@ -1086,23 +1094,91 @@ describe('submitTextToNewSession pin release', () => {await waitFor(() => expect(handle).not.toBeNull())await act(async () => {- await handle!.submitTextToNewSession('quick entry')+ await handle!.submitTextToNewSession('quick entry', 'corr-1')})- await new Promise<void>(resolve => {- let ticks = 30- const tick = () => {- ticks -= 1- if (ticks === 0) {- resolve()- } else {- window.setTimeout(tick, 0)+ expect(pinnedStoredSessionIdsForOwner('corr-1').size).toBe(0)+ })++ it('concurrent new-session submissions keep distinct owner pins', async () => {+ const observations: Array<{ promptOwner: 'owner-a' | 'owner-b'; ownerA: string[]; ownerB: string[] }> = []+ const runtimeOwner = new Map<string, 'owner-a' | 'owner-b'>()+ const storedByOwner = {+ 'owner-a': 'stored-owner-a',+ 'owner-b': 'stored-owner-b'+ } as const+ let createCount = 0+ const releaseCreates = deferred<void>()+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'session.create') {+ createCount += 1++ const owner = params?.model === 'model-owner-a' ? 'owner-a' : 'owner-b'+ const runtimeSessionId = `runtime-${owner}`+ runtimeOwner.set(runtimeSessionId, owner)++ if (createCount < 2) {+ await releaseCreates.promise}++ return {+ session_id: runtimeSessionId,+ stored_session_id: storedByOwner[owner]+ } as never+ }++ if (method === 'prompt.submit') {+ const promptOwner = runtimeOwner.get(String(params?.session_id)) ?? 'owner-a'+ observations.push({+ promptOwner,+ ownerA: [...pinnedStoredSessionIdsForOwner('owner-a')],+ ownerB: [...pinnedStoredSessionIdsForOwner('owner-b')]+ })}- window.setTimeout(tick, 0)++ return {} as never})- expect(activePinnedStoredSessionIds.has(stored)).toBe(true)- await waitFor(() => expect(activePinnedStoredSessionIds.has(stored)).toBe(false), { timeout: 3000 })+ let handle: HarnessHandle | null = null++ render(+ <Harness+ getRoutedStoredSessionId={() => 'stored-other'}+ onReady={value => (handle = value)}+ requestGateway={requestGateway}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ let first!: Promise<{ runtimeSessionId: string; sessionId: string }>+ let second!: Promise<{ runtimeSessionId: string; sessionId: string }>+ act(() => {+ setCurrentModel('model-owner-a')+ first = handle!.submitTextToNewSession('a', 'owner-a')+ setCurrentModel('model-owner-b')+ second = handle!.submitTextToNewSession('b', 'owner-b')+ setCurrentModel('')+ })++ await waitFor(() => expect(createCount).toBe(2))++ await act(async () => {+ releaseCreates.resolve()+ await Promise.all([first, second])+ })++ expect(observations).toHaveLength(2)+ expect(observations.map(({ promptOwner }) => promptOwner).sort()).toEqual(['owner-a', 'owner-b'])+ for (const observation of observations) {+ const ownPins = observation.promptOwner === 'owner-a' ? observation.ownerA : observation.ownerB+ const otherPins = observation[observation.promptOwner === 'owner-a' ? 'ownerB' : 'ownerA']++ expect(ownPins).toContain(storedByOwner[observation.promptOwner])+ expect(ownPins).not.toContain(+ storedByOwner[observation.promptOwner === 'owner-a' ? 'owner-b' : 'owner-a']+ )+ expect(otherPins).not.toContain(storedByOwner[observation.promptOwner])+ }+ expect(pinnedOwnerCount()).toBe(0)})})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 0e78289b6a8..378db82ac69 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@@ -155,7 +155,7 @@ import type {import { navigateToWorkspacePage, NEW_CHAT_ROUTE, sessionRoute, SETTINGS_ROUTE } from '../../../routes'import type { ClientSessionState, SidebarNavItem } from '../../../types'-import { activePinnedStoredSessionIds, sessionContextDrift } from '../session-context-drift'+import { pinStoredSessionForOwner, releaseStoredSessionPins, sessionContextDrift } from '../session-context-drift'import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'@@ -971,14 +971,17 @@ export function useSessionActions({)const submitTextToNewSession = useCallback(- async (text: string): Promise<{ runtimeSessionId: string; sessionId: string }> => {+ async (text: string, owner?: string): Promise<{ runtimeSessionId: string; sessionId: string }> => {const params = await desktopSessionCreateParams(resolveNewSessionCwd())const created = await requestGateway<SessionCreateResponse>('session.create', params)const stored = created.stored_session_idif (!stored) {throw new Error('The new session did not return a stored id.')}- activePinnedStoredSessionIds.add(stored)+ // The owner is the requesting submit's correlation when the caller knows+ // it (quick entry); otherwise this call owns its own generation.+ const pinOwner = owner ?? `new-session-${created.session_id}`+ pinStoredSessionForOwner(pinOwner, stored)try {markSessionCreatedThisRun(stored)runtimeIdByStoredSessionIdRef.current.set(stored, created.session_id)@@ -988,28 +991,17 @@ export function useSessionActions({// atomic path cannot fall back to a route token (#85590).await requestGateway('prompt.submit', { session_id: created.session_id, text })navigate(sessionRoute(stored), { replace: true })- // WHY: An unbounded re-arm becomes a hot loop and leaks the pin when- // competing navigation wins before this session reaches the route.- // Issue #85590: bound the router settle window to avoid that failure.- let releaseAttempts = 60- const releasePin = () => {- if (getRoutedStoredSessionId() === stored || releaseAttempts === 0) {- activePinnedStoredSessionIds.delete(stored)- } else {- // WHY: 60 ticks is far beyond any real router settle window, so- // force-release after it rather than spin forever (issue #85590).- releaseAttempts -= 1- window.setTimeout(releasePin, 0)- }- }- releasePin()return { runtimeSessionId: created.session_id, sessionId: stored }} catch (error) {- activePinnedStoredSessionIds.delete(stored)throw error+ } finally {+ // Terminal transition for this owner: accepted, failed, or cancelled.+ // Owner-scoped pins cannot strand another request, so no tick budget is+ // needed to force-release.+ releaseStoredSessionPins(pinOwner)}},- [ensureSessionState, getRoutedStoredSessionId, navigate, requestGateway, runtimeIdByStoredSessionIdRef]+ [ensureSessionState, navigate, requestGateway, runtimeIdByStoredSessionIdRef])const selectSidebarItem = useCallback(