The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): prove submit target belongs to selected session from both directions (#65328)
Simplicio, Wesley (ext)33b39f3f4b7a
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 48faa43cf21..112a805f950 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -111,6 +111,11 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: SesruntimeIdRef.current = runtimeIdconst storedIdRef = useRef(storedSessionId)storedIdRef.current = storedSessionId+ // A tile IS its session (see the comment on the useSubmitPrompt call below)+ // A tile owns one stable stored/runtime pair, so seed the shared ownership+ // cache explicitly rather than relying on the primary route cache.+ const runtimeIdByStoredSessionIdRef = useRef(new Map([[storedSessionId, runtimeId]]))+ runtimeIdByStoredSessionIdRef.current.set(storedSessionId, runtimeId)// Tile busy tracks the SESSION state, never the global $busy — and it must// read LIVE. A render-time snapshot goes stale (this hook's host doesn't@@ -223,6 +228,7 @@ export function useSessionTileActions({ runtimeId, scope, storedSessionId }: Ses// token is a stable constant (the guard never trips for a tile).getRouteToken: () => runtimeId,requestGateway,+ runtimeIdByStoredSessionIdRef,// Tile ids are always bound before this hook mounts, so routed recovery is// unreachable here; keep the shared submit contract explicit.resumeStoredSession: () => undefined,diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 7eeaeaa4797..b670d831455 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -584,6 +584,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {refreshSessions,requestGateway,resumeStoredSession: resumeSession,+ runtimeIdByStoredSessionIdRef,selectedStoredSessionIdRef,startFreshSessionDraft,sttEnabled,diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 7070f90d2bd..2796d3edda7 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -103,6 +103,7 @@ function Harness({refreshSessions,requestGateway,resumeStoredSession,+ runtimeIdByStoredSessionIdRef: runtimeIdByStoredSessionIdRefProp,seedMessages,selectedStoredSessionIdRef: selectedStoredSessionIdRefProp,storedSessionId,@@ -125,6 +126,7 @@ function Harness({refreshSessions: () => Promise<void>requestGateway: <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>resumeStoredSession?: (storedSessionId: string) => Promise<void> | void+ runtimeIdByStoredSessionIdRef?: MutableRefObject<Map<string, string>>seedMessages?: unknown[]selectedStoredSessionIdRef?: MutableRefObject<string | null>storedSessionId?: null | string@@ -141,6 +143,16 @@ function Harness({current: storedSessionId === undefined ? RUNTIME_SESSION_ID : storedSessionId}+ const defaultStoredSessionId = storedSessionId === undefined ? RUNTIME_SESSION_ID : storedSessionId+ const defaultRuntimeSessionId = activeSessionId === undefined ? RUNTIME_SESSION_ID : activeSessionId+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> =+ runtimeIdByStoredSessionIdRefProp ?? {+ current:+ defaultStoredSessionId && defaultRuntimeSessionId+ ? new Map([[defaultStoredSessionId, defaultRuntimeSessionId]])+ : new Map()+ }+const localBusyRef = busyRef ?? { current: false }const stateRef = useRef({@@ -164,6 +176,7 @@ function Harness({refreshSessions,requestGateway,resumeStoredSession: resumeStoredSession ?? (() => undefined),+ runtimeIdByStoredSessionIdRef,selectedStoredSessionIdRef,startFreshSessionDraft: () => undefined,sttEnabled: false,@@ -3347,6 +3360,7 @@ describe('usePromptActions sleep/wake session recovery', () => {refreshSessions={async () => undefined}requestGateway={requestGateway}resumeStoredSession={resumeStoredSession}+ runtimeIdByStoredSessionIdRef={{ current: new Map([[STORED_SESSION_ID, RECOVERED_SESSION_ID]]) }}selectedStoredSessionIdRef={selectedStoredSessionIdRef}storedSessionId={STORED_SESSION_ID}/>@@ -3378,6 +3392,7 @@ describe('usePromptActions sleep/wake session recovery', () => {refreshSessions={async () => undefined}requestGateway={requestGateway}resumeStoredSession={resumeStoredSession}+ runtimeIdByStoredSessionIdRef={{ current: new Map([[STORED_SESSION_ID, RECOVERED_SESSION_ID]]) }}selectedStoredSessionIdRef={selectedStoredSessionIdRef}storedSessionId={STORED_SESSION_ID}/>@@ -4226,6 +4241,208 @@ describe('usePromptActions busy-gateway churn tolerance (#64327)', () => {})})+describe('usePromptActions submit entry-time runtime ownership proof (#64789/#65328)', () => {+ const STORED_SESSION_B = 'stored-project-b'+ const RUNTIME_SESSION_A = 'rt-session-a'+ const RUNTIME_SESSION_B_RESUMED = 'rt-session-b-resumed'++ afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ })++ it('does not submit to runtime A when the cache proves B is bound to a different runtime (forward mismatch)', async () => {+ const calls: { method: string; params?: Record<string, unknown> }[] = []++ const selectedStoredSessionIdRef: MutableRefObject<string | null> = { current: STORED_SESSION_B }+ const activeSessionIdRef: MutableRefObject<string | null> = { current: RUNTIME_SESSION_A }++ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([[STORED_SESSION_B, 'rt-session-b-known']])+ }++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ calls.push({ method, params })++ if (method === 'session.resume') {+ return { session_id: RUNTIME_SESSION_B_RESUMED } as never+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ render(+ <Harness+ activeSessionId={RUNTIME_SESSION_A}+ activeSessionIdRef={activeSessionIdRef}+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ storedSessionId={STORED_SESSION_B}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ await handle!.submitText('ordinary text for the selected project B session')++ expect(calls.find(c => c.method === 'session.resume')?.params).toEqual({+ session_id: STORED_SESSION_B,+ source: 'desktop'+ })+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_A)+ ).toBeUndefined()+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_B_RESUMED)+ ).toBeDefined()+ })++ it('does not submit to runtime A when the cache proves A belongs to a DIFFERENT stored session (reverse proof, no forward entry for B)', async () => {+ // The failure mode a one-directional (stored -> runtime) lookup misses:+ // the cache has no entry for B at all (a forward miss looks like "no+ // conflict"), but A is definitively known to belong to some OTHER+ // stored session. A real-world trigger: the user is mid-conversation in+ // an old session (whose runtime is A, cached under stored-project-old),+ // then creates a fresh session B — if activeSessionIdRef hasn't been+ // re-homed to B's own runtime yet by the time submit fires, A must not+ // be accepted just because B itself was never cached.+ const calls: { method: string; params?: Record<string, unknown> }[] = []++ const selectedStoredSessionIdRef: MutableRefObject<string | null> = { current: STORED_SESSION_B }+ const activeSessionIdRef: MutableRefObject<string | null> = { current: RUNTIME_SESSION_A }++ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([['stored-project-old', RUNTIME_SESSION_A]])+ }++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ calls.push({ method, params })++ if (method === 'session.resume') {+ return { session_id: RUNTIME_SESSION_B_RESUMED } as never+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ render(+ <Harness+ activeSessionId={RUNTIME_SESSION_A}+ activeSessionIdRef={activeSessionIdRef}+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ storedSessionId={STORED_SESSION_B}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ await handle!.submitText('ordinary text for the freshly created project B session')++ expect(calls.find(c => c.method === 'session.resume')?.params).toEqual({+ session_id: STORED_SESSION_B,+ source: 'desktop'+ })+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_A)+ ).toBeUndefined()+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_B_RESUMED)+ ).toBeDefined()+ })++ it('still submits directly when the cache positively maps the selected session to the runtime', async () => {+ // Direct submit is safe only when the cache explicitly proves the selected+ // stored session owns the active runtime.+ const calls: { method: string; params?: Record<string, unknown> }[] = []++ const selectedStoredSessionIdRef: MutableRefObject<string | null> = { current: STORED_SESSION_B }+ const activeSessionIdRef: MutableRefObject<string | null> = { current: RUNTIME_SESSION_A }+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([[STORED_SESSION_B, RUNTIME_SESSION_A]])+ }++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ calls.push({ method, params })++ return {} as never+ })++ let handle: HarnessHandle | null = null+ render(+ <Harness+ activeSessionId={RUNTIME_SESSION_A}+ activeSessionIdRef={activeSessionIdRef}+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ storedSessionId={STORED_SESSION_B}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ await handle!.submitText('first message in a genuinely fresh session')++ expect(calls.some(c => c.method === 'session.resume')).toBe(false)+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_A)+ ).toBeDefined()+ })++ it('resumes the selected session when its ownership cache entry is missing', async () => {+ const calls: { method: string; params?: Record<string, unknown> }[] = []+ const selectedStoredSessionIdRef: MutableRefObject<string | null> = { current: STORED_SESSION_B }+ const activeSessionIdRef: MutableRefObject<string | null> = { current: RUNTIME_SESSION_A }+ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = { current: new Map() }++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ calls.push({ method, params })++ if (method === 'session.resume') {+ return { session_id: RUNTIME_SESSION_B_RESUMED } as never+ }++ return {} as never+ })++ let handle: HarnessHandle | null = null+ render(+ <Harness+ activeSessionId={RUNTIME_SESSION_A}+ activeSessionIdRef={activeSessionIdRef}+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ storedSessionId={STORED_SESSION_B}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ await handle!.submitText('message after an ownership-cache miss')++ expect(calls.find(c => c.method === 'session.resume')?.params).toEqual({+ session_id: STORED_SESSION_B,+ source: 'desktop'+ })+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_A)+ ).toBeUndefined()+ expect(+ calls.find(c => c.method === 'prompt.submit' && c.params?.session_id === RUNTIME_SESSION_B_RESUMED)+ ).toBeDefined()+ })+})+describe('usePromptActions eager attachment upload (drop-time)', () => {afterEach(() => {cleanup()diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 709ea7026dd..3fabb514c7b 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@ -235,6 +235,7 @@ interface PromptActionsOptions {refreshSessions: () => Promise<void>requestGateway: <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>resumeStoredSession: (storedSessionId: string) => Promise<void> | void+ runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>selectedStoredSessionIdRef: MutableRefObject<string | null>startFreshSessionDraft: () => voidsttEnabled: boolean@@ -266,6 +267,7 @@ export function usePromptActions({refreshSessions,requestGateway,resumeStoredSession,+ runtimeIdByStoredSessionIdRef,selectedStoredSessionIdRef,startFreshSessionDraft,sttEnabled,@@ -482,6 +484,7 @@ export function usePromptActions({getRuntimeIdForStoredSession,getRouteToken,requestGateway,+ runtimeIdByStoredSessionIdRef,resumeStoredSession,selectedStoredSessionIdRef,syncAttachmentsForSubmit,diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 422d79ef64f..52976138e1c 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -60,6 +60,7 @@ interface SubmitPromptDeps {getRuntimeIdForStoredSession: (storedSessionId: string) => null | stringgetRouteToken: () => stringrequestGateway: GatewayRequest+ runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>resumeStoredSession: (storedSessionId: string) => Promise<void> | voidselectedStoredSessionIdRef: MutableRefObject<string | null>syncAttachmentsForSubmit: (@@ -105,6 +106,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {getRuntimeIdForStoredSession,getRouteToken,requestGateway,+ runtimeIdByStoredSessionIdRef,resumeStoredSession,selectedStoredSessionIdRef,syncAttachmentsForSubmit,@@ -429,6 +431,39 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {sessionId = null}+ // Entry-time consistency check (#64789/#65328): activeSessionId is a+ // render-closure value that can already be stale relative to the+ // currently selected stored session by the time submit fires (e.g. a+ // fast reselect, or a new-chat draft's active ref not yet re-homed).+ // The #54527 drift guard only catches divergence that happens AFTER+ // this point, so an already-diverged runtime/stored pair sails+ // through it. Prove membership from BOTH directions against the same+ // cache rather than trusting an absent forward entry as "no+ // conflict" — a bare forward miss can't rule out the runtime being+ // known to belong to a DIFFERENT stored session (the failure mode a+ // one-directional check misses): if either direction disagrees,+ // activeSessionId is not trustworthy and the resume-by-stored-id path+ // below re-establishes the correct runtime id instead of silently+ // sending to the wrong one.+ const ownershipStoredSessionId = options?.sessionId ? null : targetStoredSessionId++ if (sessionId && ownershipStoredSessionId) {+ const provenRuntimeId = runtimeIdByStoredSessionIdRef.current.get(ownershipStoredSessionId)+ // A selected stored session requires positive ownership proof. A cache+ // miss is therefore unsafe too: the active runtime may belong to an+ // entirely different stored session, so resume the selected id instead+ // of sending to an unverified runtime.+ const knownMismatch = provenRuntimeId !== sessionId++ const runtimeOwnedByOtherStored = Array.from(runtimeIdByStoredSessionIdRef.current.entries()).some(+ ([storedId, runtimeId]) => runtimeId === sessionId && storedId !== ownershipStoredSessionId+ )++ if (knownMismatch || runtimeOwnedByOtherStored) {+ sessionId = null+ }+ }+if (sessionId) {seedOptimistic(sessionId)} else if (targetIsCurrentView()) {@@ -743,6 +778,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {getRuntimeIdForStoredSession,getRouteToken,requestGateway,+ runtimeIdByStoredSessionIdRef,resumeStoredSession,scope,selectedStoredSessionIdRef,