From 33b39f3f4b7aeb15e7f641ff5f4dcd59a041fd31 Mon Sep 17 00:00:00 2001 From: "Simplicio, Wesley (ext)" Date: Mon, 10 Aug 2026 17:18:45 -0300 Subject: [PATCH] fix(desktop): prove submit target belongs to selected session from both directions (#65328) Fail closed on missing ownership cache entries and prove runtime ownership forward+reverse against runtimeIdByStoredSessionIdRef before prompt.submit. Thread the ownership cache through main wiring and session-tile submit. Adds regression tests for forward mismatch, reverse-only proof, positive map control, and cache-miss resume. Closes #65328. --- .../src/app/chat/session-tile-actions.ts | 6 + apps/desktop/src/app/contrib/wiring.tsx | 1 + .../hooks/use-prompt-actions/index.test.tsx | 217 ++++++++++++++++++ .../session/hooks/use-prompt-actions/index.ts | 3 + .../hooks/use-prompt-actions/submit.ts | 36 +++ 5 files changed, 263 insertions(+) diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts index 48faa43cf2..112a805f95 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 }: Ses runtimeIdRef.current = runtimeId const 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.tsx index 7eeaeaa479..b670d83145 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.tsx index 7070f90d2b..2796d3edda 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 requestGateway: (method: string, params?: Record, timeoutMs?: number) => Promise resumeStoredSession?: (storedSessionId: string) => Promise | void + runtimeIdByStoredSessionIdRef?: MutableRefObject> seedMessages?: unknown[] selectedStoredSessionIdRef?: MutableRefObject 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> = + 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 }[] = [] + + const selectedStoredSessionIdRef: MutableRefObject = { current: STORED_SESSION_B } + const activeSessionIdRef: MutableRefObject = { current: RUNTIME_SESSION_A } + + const runtimeIdByStoredSessionIdRef: MutableRefObject> = { + current: new Map([[STORED_SESSION_B, 'rt-session-b-known']]) + } + + const requestGateway = vi.fn(async (method: string, params?: Record) => { + 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( + (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 }[] = [] + + const selectedStoredSessionIdRef: MutableRefObject = { current: STORED_SESSION_B } + const activeSessionIdRef: MutableRefObject = { current: RUNTIME_SESSION_A } + + const runtimeIdByStoredSessionIdRef: MutableRefObject> = { + current: new Map([['stored-project-old', RUNTIME_SESSION_A]]) + } + + const requestGateway = vi.fn(async (method: string, params?: Record) => { + 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( + (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 }[] = [] + + const selectedStoredSessionIdRef: MutableRefObject = { current: STORED_SESSION_B } + const activeSessionIdRef: MutableRefObject = { current: RUNTIME_SESSION_A } + const runtimeIdByStoredSessionIdRef: MutableRefObject> = { + current: new Map([[STORED_SESSION_B, RUNTIME_SESSION_A]]) + } + + const requestGateway = vi.fn(async (method: string, params?: Record) => { + calls.push({ method, params }) + + return {} as never + }) + + let handle: HarnessHandle | null = null + render( + (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 }[] = [] + const selectedStoredSessionIdRef: MutableRefObject = { current: STORED_SESSION_B } + const activeSessionIdRef: MutableRefObject = { current: RUNTIME_SESSION_A } + const runtimeIdByStoredSessionIdRef: MutableRefObject> = { current: new Map() } + + const requestGateway = vi.fn(async (method: string, params?: Record) => { + 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( + (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.ts index 709ea7026d..3fabb514c7 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 requestGateway: (method: string, params?: Record, timeoutMs?: number) => Promise resumeStoredSession: (storedSessionId: string) => Promise | void + runtimeIdByStoredSessionIdRef: MutableRefObject> selectedStoredSessionIdRef: MutableRefObject startFreshSessionDraft: () => void sttEnabled: 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.ts index 422d79ef64..52976138e1 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 | string getRouteToken: () => string requestGateway: GatewayRequest + runtimeIdByStoredSessionIdRef: MutableRefObject> resumeStoredSession: (storedSessionId: string) => Promise | void selectedStoredSessionIdRef: MutableRefObject 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,