The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep steering recovery bound to its source chat
BearHuddlestondda88ecbac52
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 beefd9b04c1..253b1a28ecb 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@@ -68,6 +68,7 @@ import {type SurvivorUserRowIds} from './rewind'import { useSlashCommand } from './slash'+import { captureSteeringSession } from './steering-session'import { useSubmitPrompt } from './submit'import {blobToDataUrl,@@ -746,12 +747,20 @@ export function usePromptActions({const redirectPrompt = useCallback(async (rawText: string): Promise<boolean> => {const text = sanitizeComposerInput(rawText).trim()+// Ref, not the closure-captured prop — see cancelRun above. A redirect// reaches the live model mid-turn, so a stale target delivers the user's// correction into a conversation they are no longer looking at.- const sessionId = activeSessionIdRef.current+ const target = captureSteeringSession({+ activeSessionIdRef,+ selectedStoredSessionIdRef,+ runtimeIdByStoredSessionIdRef,+ getRoutedStoredSessionId,+ requestGateway,+ updateSessionState+ })- if (!text || !sessionId) {+ if (!text || !target) {return false}@@ -766,7 +775,9 @@ export function usePromptActions({// gateway, in arrival order: sealed already-streamed output above,// correction bubble below it, post-redirect deltas below that// (#73793, #83151).- const messageId = appendSessionTextMessage(id, 'user', text, undefined, { appendAfterActiveReply: true })+ const messageId = appendSessionTextMessage(id, 'user', text, target.storedSessionId, {+ appendAfterActiveReply: true+ })const discardOptimisticMessage = () =>updateSessionState(id, state => ({@@ -784,7 +795,10 @@ export function usePromptActions({})try {- const result = await requestGateway<SessionRedirectResponse>('session.redirect', { session_id: id, text })+ const result = await target.requestGateway<SessionRedirectResponse>('session.redirect', {+ session_id: id,+ text+ })if (result?.status === 'redirected') {triggerHaptic('submit')@@ -814,13 +828,7 @@ export function usePromptActions({// A stale runtime id after reconnect 404s ("session not found"): the// shared resolver resumes the stored session and retries once, so a// correction right after a reconnect isn't lost to the race.- const { result } = await withSessionNotFoundResume(sessionId, selectedStoredSessionIdRef.current, send, {- requestGateway,- onRecovered: recoveredId => {- activeSessionIdRef.current = recoveredId- setActiveSessionId(recoveredId)- }- })+ const { result } = await withSessionNotFoundResume(target.sessionId, target.storedSessionId, send, target)return result} catch {@@ -829,7 +837,15 @@ export function usePromptActions({return false},- [activeSessionIdRef, appendSessionTextMessage, requestGateway, selectedStoredSessionIdRef, updateSessionState]+ [+ activeSessionIdRef,+ appendSessionTextMessage,+ getRoutedStoredSessionId,+ requestGateway,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef,+ updateSessionState+ ])// A hidden note that lands mid-turn must reach the model without becoming a@@ -839,33 +855,42 @@ export function usePromptActions({const injectHiddenPrompt = useCallback(async (rawText: string): Promise<boolean> => {const text = sanitizeComposerInput(rawText).trim()- const sessionId = activeSessionIdRef.current- if (!text || !sessionId) {+ const target = captureSteeringSession({+ activeSessionIdRef,+ selectedStoredSessionIdRef,+ runtimeIdByStoredSessionIdRef,+ getRoutedStoredSessionId,+ requestGateway,+ updateSessionState+ })++ if (!text || !target) {return false}const send = async (id: string): Promise<boolean> => {- const response = await requestGateway<SessionRedirectResponse>('session.steer', { session_id: id, text })+ const response = await target.requestGateway<SessionRedirectResponse>('session.steer', { session_id: id, text })return response?.status === 'queued'}try {- const { result } = await withSessionNotFoundResume(sessionId, selectedStoredSessionIdRef.current, send, {- requestGateway,- onRecovered: recoveredId => {- activeSessionIdRef.current = recoveredId- setActiveSessionId(recoveredId)- }- })+ const { result } = await withSessionNotFoundResume(target.sessionId, target.storedSessionId, send, target)return result} catch {return false}},- [activeSessionIdRef, requestGateway, selectedStoredSessionIdRef]+ [+ activeSessionIdRef,+ getRoutedStoredSessionId,+ requestGateway,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef,+ updateSessionState+ ])// After a durable rewind the surviving bubbles' cached rowIds are stale (thediff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsxnew file mode 100644index 00000000000..8f7e444bb38--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx@@ -0,0 +1,427 @@+import { useStore } from '@nanostores/react'+import { QueryClient } from '@tanstack/react-query'+import { act, cleanup, render, waitFor } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import { createSessionRpcDispatcher } from '@/app/contrib/session-rpc-dispatcher'+import { sessionRoute } from '@/app/routes'+import { textPart } from '@/lib/chat-messages'+import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'+import {+ $activeSessionId,+ $activeSessionStoredIdRotation,+ $messages,+ $selectedStoredSessionId,+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setMessages,+ setSelectedStoredSessionId,+ setSessions+} from '@/store/session'+import { clearAllSessionStates } from '@/store/session-states'+import type { SessionInfo } from '@/types/hermes'++import { handleSessionInfoEvent } from '../use-message-stream/gateway-event/session-info'+import { useSessionStateCache } from '../use-session-state-cache'++import { clearSingleFlightSessionResumeState, registerRecoveredRuntime } from './single-flight-resume'++import { usePromptActions } from '.'++// Real prompt hooks, cache, ownership router, and dispatcher; only the external+// gateway edge is substituted. No test injects a corrupted ownership mapping.+vi.mock('@/store/gateway', async original => ({+ ...(await original<Record<string, unknown>>()),+ requestGatewayForAgent: vi.fn(),+ requestGatewayForProfile: vi.fn(),+ retainGatewayForSessionTurn: vi.fn(async () => () => undefined)+}))++const busyRef = { current: false }+let routedStoredId: string | null = 'stored-B'+let handle: { actions: ReturnType<typeof usePromptActions>; cache: ReturnType<typeof useSessionStateCache> }++function Harness() {+ const activeSessionId = useStore($activeSessionId)+ const selectedStoredSessionId = useStore($selectedStoredSessionId)++ const cache = useSessionStateCache({+ activeSessionId,+ selectedStoredSessionId,+ busyRef,+ setAwaitingResponse,+ setBusy,+ setMessages+ })++ const requestGateway = createSessionRpcDispatcher({+ ...cache,+ ambientRequest: async () => {+ throw new Error('unexpected ambient request')+ }+ })++ const actions = usePromptActions({+ activeSessionId,+ ...cache,+ busyRef,+ branchCurrentSession: async () => false,+ createBackendSessionForSend: async () => {+ throw new Error('unexpected create')+ },+ getRoutedStoredSessionId: () => routedStoredId,+ getRouteToken: () => `${routedStoredId ? sessionRoute(routedStoredId) : '/'}::`,+ handleSkinCommand: () => '',+ openMemoryGraph: () => undefined,+ refreshSessions: async () => undefined,+ requestGateway,+ resumeStoredSession: async () => {+ throw new Error('unexpected foreground resume')+ },+ startFreshSessionDraft: () => undefined,+ sttEnabled: false+ })++ handle = { actions, cache }++ return null+}++function seed() {+ routedStoredId = 'stored-B'+ busyRef.current = false+ // Same profile name on distinct backends: profile equality is not ownership.+ setSessions(+ ['A', 'B'].map(id => ({+ id: `stored-${id}`,+ connection_id: `connection-${id}`,+ profile: 'default',+ source: 'desktop',+ message_count: 1+ })) as SessionInfo[]+ )+ setSelectedStoredSessionId('stored-B')+ setActiveSessionId('rt-B')+ render(<Harness />)+ act(() => {+ for (const id of ['A', 'B']) {+ handle.cache.updateSessionState(+ `rt-${id}`,+ state => ({+ ...state,+ messages: [{ id: `history-${id}`, role: 'assistant', parts: [textPart(`history ${id}`)] }]+ }),+ `stored-${id}`+ )+ }+ })+}++function navigateToA() {+ act(() => {+ routedStoredId = 'stored-A'+ setSelectedStoredSessionId('stored-A')+ setActiveSessionId('rt-A')+ })+ act(() => {+ handle.cache.syncSessionStateToView('rt-A', handle.cache.sessionStateByRuntimeIdRef.current.get('rt-A')!)+ })+}++function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void++ const promise = new Promise<T>((yes, no) => {+ resolve = yes+ reject = no+ })++ return { promise, resolve, reject }+}++afterEach(() => {+ cleanup()+ clearAllSessionStates()+ clearSingleFlightSessionResumeState()+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setSessions([])+ setBusy(false)+ setAwaitingResponse(false)+ setMessages([])+ window.localStorage.clear()+ vi.clearAllMocks()+})++it.each(['redirectPrompt', 'injectHiddenPrompt'] as const)(+ '%s refuses a source whose route, selection, and runtime do not agree',+ async action => {+ vi.mocked(requestGatewayForAgent).mockResolvedValue({ status: 'queued' })+ seed()+ const originalB = handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B')+ // Route publication can precede both selection and runtime publication.+ routedStoredId = 'stored-A'+ await act(async () => {+ expect(await handle.actions[action]('not B input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B')).toBe(originalB)++ // Selection/route can also agree while the active runtime still lags.+ act(() => {+ setSelectedStoredSessionId('stored-A')+ })+ // Missing forward proof must not turn a known foreign runtime into A's.+ handle.cache.runtimeIdByStoredSessionIdRef.current.delete('stored-A')+ await act(async () => {+ expect(await handle.actions[action]('A input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.has('stored-A')).toBe(false)+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B')++ // A fresh draft must not steer the previous chat's still-live runtime.+ act(() => {+ routedStoredId = null+ setSelectedStoredSessionId(null)+ })+ await act(async () => {+ expect(await handle.actions[action]('new chat input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ }+)++const steeringActions = [+ { action: 'redirectPrompt' as const, method: 'session.redirect', status: 'redirected' },+ { action: 'redirectPrompt' as const, method: 'session.redirect', status: 'queued' },+ { action: 'injectHiddenPrompt' as const, method: 'session.steer', status: 'queued' }+]++const recoveryCases = (['before-stale-error', 'during-resume', 'stay'] as const).flatMap(navigation =>+ [false, true].flatMap(expiredRecovery => steeringActions.map(action => ({ ...action, navigation, expiredRecovery })))+)++it.each(recoveryCases)(+ '$action recovery ($status, $navigation, expired cache: $expiredRecovery) retains its owner without stealing another chat',+ async ({ action, method, status, navigation, expiredRecovery }) => {+ const first = deferred<unknown>()+ const resume = deferred<{ session_id: string }>()+ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connection, _profile, rpc, params) => {+ if (rpc === method && params?.session_id === 'rt-B') {+ return first.promise+ }++ if (rpc === 'session.resume') {+ return resume.promise+ }++ if (rpc === method && params?.session_id === 'rt-B-cached') {+ throw new Error('session not found')+ }++ if (rpc === method) {+ return { status }+ }++ if (rpc === 'prompt.submit') {+ return { status: 'streaming' }+ }++ throw new Error(`unexpected ${rpc}`)+ })+ seed()++ if (expiredRecovery) {+ registerRecoveredRuntime('stored-B', 'rt-B-cached')+ }++ let pending!: Promise<boolean>+ act(() => {+ pending = handle.actions[action]('B correction')+ })+ await waitFor(() =>+ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B',+ text: 'B correction'+ })+ )++ if (navigation === 'before-stale-error') {+ navigateToA()+ }++ await act(async () => {+ first.reject(new Error('session not found'))+ })+ await waitFor(() =>+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'connection-B',+ 'default',+ 'session.resume',+ expect.objectContaining({ session_id: 'stored-B' })+ )+ )++ if (expiredRecovery) {+ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B-cached',+ text: 'B correction'+ })+ expect($activeSessionId.get()).toBe(navigation === 'before-stale-error' ? 'rt-A' : 'rt-B-cached')+ }++ if (navigation === 'during-resume') {+ navigateToA()+ }++ await act(async () => {+ resume.resolve({ session_id: 'rt-B2' })+ expect(await pending).toBe(true)+ })++ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B2',+ text: 'B correction'+ })+ expect(requestGatewayForProfile).not.toHaveBeenCalled()+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-A')).toBe('rt-A')+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B2')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B2')?.storedSessionId).toBe('stored-B')++ const correctionRows = [...handle.cache.sessionStateByRuntimeIdRef.current.values()]+ .flatMap(state => state.messages)+ .filter(message => message.role === 'user')++ expect(correctionRows).toHaveLength(action === 'redirectPrompt' ? 1 : 0)+ expect($activeSessionId.get()).toBe(navigation === 'stay' ? 'rt-B2' : 'rt-A')+ expect(handle.cache.activeSessionIdRef.current).toBe($activeSessionId.get())+ expect($selectedStoredSessionId.get()).toBe(navigation === 'stay' ? 'stored-B' : 'stored-A')++ if (navigation === 'stay') {+ navigateToA()+ }++ expect($messages.get().map(message => message.id)).toEqual(['history-A'])+ // An ordinary foreground send must still route to A after B's recovery.+ await act(async () => {+ expect(await handle.actions.submitText('A next prompt', { attachments: [], composerScope: 'stored-A' })).toBe(+ true+ )+ })+ expect(requestGatewayForAgent).toHaveBeenLastCalledWith(+ 'connection-A',+ 'default',+ 'prompt.submit',+ expect.objectContaining({ session_id: 'rt-A', text: 'A next prompt' }),+ expect.any(Number),+ undefined+ )+ }+)++const rebuiltRuntimeCases = steeringActions.flatMap(action =>+ [false, true].flatMap(recover => ['stored-B', 'stored-B-tip'].map(selection => ({ ...action, recover, selection })))+)++it.each(rebuiltRuntimeCases)(+ '$action ($status, recovery: $recover, selection: $selection) preserves a rebuilt runtime’s tip binding and durable route',+ async ({ action, method, status, recover, selection }) => {+ seed()+ const rotation = $activeSessionStoredIdRotation.get()++ act(() => {+ setSessions([+ {+ id: 'stored-B-tip',+ _lineage_root_id: 'stored-B',+ profile: 'default',+ connection_id: 'connection-B',+ source: 'desktop',+ message_count: 2+ }+ ] as SessionInfo[])+ handleSessionInfoEvent({+ deps: {+ ...handle.cache,+ activeGatewayProfile: 'default',+ compactedTurnRef: { current: new Set() },+ lastCwdInfoSessionRef: { current: null },+ nativeSubagentSessionsRef: { current: new Set() },+ appendAssistantDelta: vi.fn(),+ appendReasoningDelta: vi.fn(),+ completeAssistantMessage: vi.fn(),+ failAssistantMessage: vi.fn(),+ flushQueuedDeltas: vi.fn(),+ finalizeInterimAssistantMessage: vi.fn(),+ hydrateFromStoredSession: vi.fn(async () => undefined),+ queryClient: new QueryClient(),+ refreshHermesConfig: vi.fn(async () => undefined),+ scheduleSessionsRefresh: vi.fn(),+ sessionInterrupted: () => false,+ upsertToolCall: vi.fn()+ },+ event: { profile: 'default', session_id: 'rt-B-rebuilt', type: 'session.info' },+ explicitSid: 'rt-B-rebuilt',+ fromActiveSource: () => true,+ isActiveEvent: false,+ occurredAt: Date.now() / 1000,+ payload: { stored_session_id: 'stored-B-tip', model: 'fixture-model', running: true },+ scheduleConfigRefresh: vi.fn(),+ sessionId: 'rt-B-rebuilt'+ })+ })+ // The real reducer adopts this runtime without rotating the durable selection.+ expect($activeSessionId.get()).toBe('rt-B-rebuilt')+ expect($selectedStoredSessionId.get()).toBe('stored-B')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B-rebuilt')?.storedSessionId).toBe('stored-B-tip')++ // A selection may also follow the tip while the durable route stays on root.+ act(() => {+ setSelectedStoredSessionId(selection)+ })++ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connection, _profile, rpc, params) => {+ if (rpc === 'session.resume') {+ return { session_id: 'rt-B2' }+ }++ if (recover && params?.session_id === 'rt-B-rebuilt') {+ throw new Error('session not found')+ }++ return { status }+ })+ await act(async () => {+ expect(await handle.actions[action]('same chat correction')).toBe(true)+ })++ const runtimeId = recover ? 'rt-B2' : 'rt-B-rebuilt'+ expect(requestGatewayForAgent).toHaveBeenLastCalledWith('connection-B', 'default', method, {+ session_id: runtimeId,+ text: 'same chat correction'+ })++ if (recover) {+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'connection-B',+ 'default',+ 'session.resume',+ expect.objectContaining({ session_id: 'stored-B-tip' })+ )+ }++ expect($activeSessionId.get()).toBe(runtimeId)+ expect(handle.cache.activeSessionIdRef.current).toBe(runtimeId)+ expect($selectedStoredSessionId.get()).toBe(selection)+ expect(routedStoredId).toBe('stored-B')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B-rebuilt')?.storedSessionId).toBe('stored-B-tip')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId).toBe('stored-B-tip')+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B-tip')).toBe(runtimeId)+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B')+ expect($activeSessionStoredIdRotation.get()).toBe(rotation)+ expect(requestGatewayForProfile).not.toHaveBeenCalled()+ }+)diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-session.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-session.tsnew file mode 100644index 00000000000..4c40e817fb9--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-session.ts@@ -0,0 +1,85 @@+import type { MutableRefObject } from 'react'++import { findStoredIdForRuntimeId } from '@/app/contrib/wiring-routing'+import type { ClientSessionState } from '@/app/types'+import { $sessions, idsShareLineage, setActiveSessionId } from '@/store/session'+import { requestForSessionProfile } from '@/store/session-request-router'+import { knownOwnerForSession } from '@/store/session-states'++import type { GatewayRequest } from './utils'++interface SteeringSessionDeps {+ activeSessionIdRef: MutableRefObject<string | null>+ selectedStoredSessionIdRef: MutableRefObject<string | null>+ runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>+ getRoutedStoredSessionId: () => string | null+ requestGateway: GatewayRequest+ updateSessionState: (+ sessionId: string,+ updater: (state: ClientSessionState) => ClientSessionState,+ storedSessionId?: string | null+ ) => ClientSessionState+}++/** Pin a correction to its source, not the selection at retry time. */+export function captureSteeringSession(deps: SteeringSessionDeps) {+ const { activeSessionIdRef, selectedStoredSessionIdRef, runtimeIdByStoredSessionIdRef, getRoutedStoredSessionId } =+ deps++ const sessionId = activeSessionIdRef.current+ const selectedStoredSessionId = selectedStoredSessionIdRef.current+ const routedStoredSessionId = getRoutedStoredSessionId()+ const bindings = runtimeIdByStoredSessionIdRef.current+ const boundStoredSessionId = sessionId ? findStoredIdForRuntimeId(bindings, sessionId) : undefined+ const sessions = $sessions.get()++ const matchesSelection = (id: string) =>+ Boolean(selectedStoredSessionId && idsShareLineage(id, selectedStoredSessionId, sessions))++ // Navigation publishes these identities independently. Unlike ordinary Send,+ // a mid-turn correction must not resolve another target and interrupt it.+ if (+ !sessionId ||+ (routedStoredSessionId && !matchesSelection(routedStoredSessionId)) ||+ (selectedStoredSessionId &&+ selectedStoredSessionId !== sessionId &&+ (!boundStoredSessionId || !matchesSelection(boundStoredSessionId))) ||+ [...bindings].some(([stored, runtime]) => runtime === sessionId && !matchesSelection(stored))+ ) {+ return null+ }++ // A rebuilt runtime can bind the tip while selection/route keep the root.+ // Use its proven stored id for writes; reapplying the root would rotate it back.+ const storedSessionId = boundStoredSessionId ?? selectedStoredSessionId+ const owner = knownOwnerForSession(sessionId) ?? knownOwnerForSession(storedSessionId)+ let adoptedSessionId = sessionId++ const requestGateway: GatewayRequest = (method, params, timeoutMs) =>+ requestForSessionProfile(owner, deps.requestGateway, method, params, timeoutMs)++ return {+ sessionId,+ storedSessionId,+ requestGateway,+ resolveProfile: owner ? async () => (typeof owner === 'string' ? owner : owner.profile) : undefined,+ onRecovered: (recoveredId: string) => {+ // Both visible redirect and hidden steer need the binding BEFORE retry:+ // hidden steer has no optimistic row to establish it incidentally.+ deps.updateSessionState(recoveredId, state => state, storedSessionId)++ // The correction still belongs to its source when navigation backgrounds+ // it. Keep its recovery, but only the unchanged view may adopt its id.+ // A cached recovery can itself expire: the resolver then calls us again.+ if (+ activeSessionIdRef.current === adoptedSessionId &&+ selectedStoredSessionIdRef.current === selectedStoredSessionId &&+ getRoutedStoredSessionId() === routedStoredSessionId+ ) {+ adoptedSessionId = recoveredId+ activeSessionIdRef.current = recoveredId+ setActiveSessionId(recoveredId)+ }+ }+ }+}