The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): interrupt a deleted session's runtime so no prompt outlives it (#124859)
Austin Pickettbfda74c71acd
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.tsindex 1a991c02ec4..8cf53335235 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts@@ -51,6 +51,13 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {const { deps, event, payload, sessionId, occurredAt } = ctxif (isConnectionRequestEvent(event)) {+ // An interrupted/deleted session's runtime has no turn left to consent to a+ // connection; the backend withdraws its request on the same boundary. Drop+ // the frame rather than parking a stale consent card (#75587).+ if (sessionId && deps.sessionInterrupted(sessionId)) {+ return true+ }+// Park per-session and upsert a stable tool row so the card renders even if tool.start was missed.const request = normalizeConnectionRequest(event.payload, sessionId ?? null)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.tsindex 6618ff7d40a..cdd849d1c17 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { createClientSessionState } from '@/lib/chat-runtime'+import { hasOpenServerRequest, resetServerRequestsForTests } from '@/store/server-requests'import { setActiveSessionId, setSessions } from '@/store/session'import { $sessionTiles } from '@/store/session-states'import { $toursEnabled } from '@/store/tours'@@ -159,3 +160,45 @@ describe('tour request routing', () => {expect(JSON.parse(respond.mock.calls[0][0].value)).toMatchObject({ success: false })})})++// #75587: a blocking-input request still in flight when the session's runtime is+// interrupted (Stop) or deleted must not park its card — parking one would+// resurrect an overlay (and native notification) for a turn that is gone. It is+// answered with an error (the backend's "unanswered"), not dropped, so the+// blocked tool returns instead of waiting out its deadline.+describe('blocking-input guard for interrupted sessions', () => {+ const depsWith = (interrupted: boolean) =>+ ({ ...deps, sessionInterrupted: () => interrupted }) as ServerRequestContext['deps']++ const approvalRequest = (id: string) => ({+ fail: vi.fn(),+ id,+ method: 'approval',+ params: { command: 'rm -rf /', description: 'dangerous', request_id: 'r1', session_id: 'session-a' },+ profile: 'default',+ respond: vi.fn()+ })++ afterEach(() => {+ resetServerRequestsForTests()+ })++ it('fails an approval request for an interrupted session instead of parking it', () => {+ const request = approvalRequest('srq-dead')++ expect(handleServerRequest(request, depsWith(true), 'session-a')).toBe(true)++ expect(hasOpenServerRequest('srq-dead')).toBe(false)+ expect(request.fail).toHaveBeenCalledWith(expect.any(Number), 'session interrupted')+ expect(request.respond).not.toHaveBeenCalled()+ })++ it('still parks an approval request for a live session', () => {+ const request = approvalRequest('srq-live')++ handleServerRequest(request, depsWith(false), 'session-a')++ expect(hasOpenServerRequest('srq-live')).toBe(true)+ expect(request.fail).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.tsindex e09945af96b..d7a77d2b5e2 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts@@ -1,3 +1,5 @@+import { JSON_RPC_INTERNAL_ERROR } from '@hermes/shared'+import { readActivePreview } from '@/app/chat/right-rail/preview-reader'import {abortPreviewTyping,@@ -107,6 +109,26 @@ const markNeedsInput = (ctx: ServerRequestContext) => {}}+/**+ * A blocking-input card must not park for a session whose runtime is already+ * interrupted — the user hit Stop, or `removeSession` marked the doomed runtime+ * interrupted before it deletes the row. A frame still in flight would otherwise+ * re-create an overlay (and native notification) for a turn that is gone+ * (#75587). Answer it rather than drop it: the backend blocks on this frame, and+ * an error reply is the same "unanswered" its own `request.cancel` produces, so+ * the tool returns now instead of waiting out its deadline. Sessionless requests+ * (app-level Bot Screen install) are never gated.+ */+const declineIfSessionStopped = (ctx: ServerRequestContext): boolean => {+ if (!ctx.sessionId || !ctx.deps.sessionInterrupted(ctx.sessionId)) {+ return false+ }++ ctx.request.fail(JSON_RPC_INTERNAL_ERROR, 'session interrupted')++ return true+}+const notifyInput = (ctx: ServerRequestContext, body: string) => {if (!ctx.request.replayed) {dispatchNativeNotification({@@ -223,6 +245,10 @@ const approval: Handler = ctx => {const command = str(p.command)const description = str(p.description) || 'dangerous command'+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(request)void receiveApprovalRequest(null, {// false only when a tirith warning forbids it; backend omits the field otherwise.@@ -261,6 +287,10 @@ const approval: Handler = ctx => {}const sudo: Handler = ctx => {+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(ctx.request)setSudoRequest({command: str(ctx.request.params.command),@@ -289,6 +319,10 @@ const secret: Handler = ctx => {const envVar = str(p.env_var)const promptText = str(p.prompt)+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(ctx.request)setSecretRequest({ envVar, prompt: promptText, requestId: ctx.request.id, sessionId: ctx.sessionId || null })markNeedsInput(ctx)@@ -299,6 +333,10 @@ const vaultCode: Handler = ctx => {const p = ctx.request.paramsconst site = str(p.site)+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(ctx.request)setVaultCodeRequest({ hint: str(p.hint), requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })markNeedsInput(ctx)@@ -310,6 +348,10 @@ const vaultSaveLogin: Handler = ctx => {const origin = str(p.origin)const site = str(p.site) || origin+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(ctx.request)setVaultSaveLoginRequest({ origin, requestId: ctx.request.id, sessionId: ctx.sessionId || null, site })markNeedsInput(ctx)@@ -321,6 +363,10 @@ const vaultUnlockPrompt: Handler = ctx => {const backend = str(p.backend)const displayName = str(p.display_name) || backend+ if (declineIfSessionStopped(ctx)) {+ return+ }+rememberServerRequest(ctx.request)setVaultUnlockRequest({ backend, displayName, requestId: ctx.request.id, sessionId: ctx.sessionId || null })markNeedsInput(ctx)diff --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 df82a8cf02e..69d735e47a1 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@@ -174,16 +174,24 @@ function Harness({navigate = vi.fn(),onReady,requestGateway,+ runtimeIdByStoredSessionIdRef: runtimeIdByStoredSessionIdRefOverride,selectedStoredSessionId = null,- selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride+ selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride,+ updateSessionState: updateSessionStateOverride}: {activeSessionId?: null | stringactiveSessionIdRef?: MutableRefObject<null | string>navigate?: ReturnType<typeof vi.fn>onReady: (handle: HarnessHandle) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>+ runtimeIdByStoredSessionIdRef?: MutableRefObject<Map<string, string>>selectedStoredSessionId?: null | stringselectedStoredSessionIdRef?: MutableRefObject<null | string>+ updateSessionState?: (+ sessionId: string,+ updater: (state: ClientSessionState) => ClientSessionState,+ storedSessionId?: null | string+ ) => ClientSessionState}) {const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })@@ -198,12 +206,12 @@ function Harness({navigate: navigate as never,requestGateway,resetViewSync: vi.fn(),- runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),+ runtimeIdByStoredSessionIdRef: runtimeIdByStoredSessionIdRefOverride ?? ref(new Map<string, string>()),selectedStoredSessionId,selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride ?? ref(selectedStoredSessionId),sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),syncSessionStateToView: vi.fn(),- updateSessionState: () => ({}) as ClientSessionState+ updateSessionState: updateSessionStateOverride ?? (() => ({}) as ClientSessionState)})useEffect(() => {@@ -423,6 +431,100 @@ describe('connection-qualified session deletion', () => {expect(selectedStoredSessionIdRef.current).toBeNull()expect(activeSessionIdRef.current).toBeNull()})++ // #75587: deleting a NON-selected (sidebar/background) session used to skip+ // session.close entirely (`closingRuntimeId` was gated on selection), so its+ // in-flight turn kept running and could surface an approval prompt for a+ // conversation that no longer existed. The runtime must be resolved from the+ // stored→runtime map, marked interrupted, interrupted, and closed.+ it('interrupts and closes a non-selected session resolved from the runtime map', async () => {+ const requestGateway = vi.fn().mockResolvedValue({})++ const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {+ current: new Map([['background-session', 'runtime-bg']])+ }++ const updateSessionState = vi.fn((_sessionId: string, updater: (state: ClientSessionState) => ClientSessionState) =>+ updater({ interrupted: false, needsInput: true } as ClientSessionState)+ )++ let actions: HarnessHandle | null = null++ setSessions([storedSession({ id: 'background-session' })])+ vi.mocked(deleteSession).mockResolvedValue({ ok: true })++ render(+ <Harness+ activeSessionId="runtime-foreground"+ onReady={value => {+ actions = value+ }}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionId="foreground-session"+ updateSessionState={updateSessionState}+ />+ )+ await waitFor(() => expect(actions).not.toBeNull())++ await act(async () => {+ await actions?.removeSession('background-session')+ })++ expect(requestGateway).toHaveBeenCalledWith('session.interrupt', { session_id: 'runtime-bg' })+ expect(requestGateway).toHaveBeenCalledWith('session.close', { session_id: 'runtime-bg' })+ // The selected session's runtime must not be touched by another row's delete.+ expect(requestGateway).not.toHaveBeenCalledWith('session.interrupt', { session_id: 'runtime-foreground' })+ expect(requestGateway).not.toHaveBeenCalledWith('session.close', { session_id: 'runtime-foreground' })+ // Marked interrupted BEFORE the RPCs so a queued blocking-input frame is+ // declined instead of parked.+ expect(updateSessionState).toHaveBeenCalledWith('runtime-bg', expect.any(Function))+ expect(updateSessionState.mock.results[0].value).toMatchObject({ interrupted: true, needsInput: false })+ expect(updateSessionState.mock.invocationCallOrder[0]).toBeLessThan(requestGateway.mock.invocationCallOrder[0])+ })++ it('rolls the delete back when the interrupt fails for a reason other than a gone runtime', async () => {+ const requestGateway = vi.fn().mockImplementation(async (method: string) => {+ if (method === 'session.interrupt') {+ throw new Error('gateway unreachable')+ }++ return {}+ })++ const updateSessionState = vi.fn((_sessionId: string, updater: (state: ClientSessionState) => ClientSessionState) =>+ updater({ interrupted: false, needsInput: true } as ClientSessionState)+ )++ let actions: HarnessHandle | null = null++ setSessions([storedSession({ id: 'background-session' })])+ vi.mocked(deleteSession).mockResolvedValue({ ok: true })++ render(+ <Harness+ activeSessionId="runtime-foreground"+ onReady={value => {+ actions = value+ }}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={{ current: new Map([['background-session', 'runtime-bg']]) }}+ selectedStoredSessionId="foreground-session"+ updateSessionState={updateSessionState}+ />+ )+ await waitFor(() => expect(actions).not.toBeNull())++ await act(async () => {+ await actions?.removeSession('background-session')+ })++ expect(requestGateway).not.toHaveBeenCalledWith('session.close', expect.anything())+ expect(deleteSession).not.toHaveBeenCalled()+ // The live state the interrupt clobbered is restored, and the row survives.+ expect(updateSessionState.mock.results.at(-1)?.value).toMatchObject({ interrupted: false, needsInput: true })+ expect($sessions.get().some(session => session.id === 'background-session')).toBe(true)+ })})function StoredIdRotationHarness({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 fbf69bbccbf..3c8294a8465 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@@ -32,7 +32,7 @@ import { isMissingRpcMethod } from '@/lib/gateway-rpc'import { recoverInFlightTurnJournal } from '@/lib/inflight-turn-journal'import { latestSessionTodoSnapshot } from '@/lib/todos'import { setSessionYolo } from '@/lib/yolo-session'-import { $clarifyRequests } from '@/store/clarify'+import { $clarifyRequests, clearClarifyRequest } from '@/store/clarify'import { announceGoneSessionDraft, announceNewSessionDraftKey, migrateSessionDraft } from '@/store/composer'import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'import { $connectionRequests } from '@/store/connection-request'@@ -62,7 +62,7 @@ import {} from '@/store/profile'import { $projectScope } from '@/store/project-scope'import { resolveNewSessionCwd } from '@/store/projects'-import { receiveApprovalRequest, replayPendingApproval } from '@/store/prompts'+import { clearAllPrompts, receiveApprovalRequest, replayPendingApproval } from '@/store/prompts'import { clearStoredTranscriptReadOnly, markStoredTranscriptReadOnly } from '@/store/read-only-transcript'import {$activeSessionStoredIdRotation,@@ -2870,7 +2870,17 @@ export function useSessionActions({// delete lands in the same tick, which used to leave the doomed route in// place and let the generic 4001 recovery rebind it.const wasSelected = selectedStoredSessionIdRef.current === storedSessionId- const closingRuntimeId = wasSelected ? activeSessionIdRef.current : null++ // Resolve the doomed session's live runtime from the SELECTION or the+ // stored→runtime map. Deleting a NON-selected (sidebar/background) session+ // used to skip this entirely, so its in-flight turn kept running and could+ // surface an approval/clarify prompt for a conversation that no longer+ // exists (#75587).+ const closingRuntimeId =+ (wasSelected ? activeSessionIdRef.current : null) ??+ runtimeIdByStoredSessionIdRef.current.get(storedSessionId) ??+ null+const previousMessages = $messages.get()const previousPinned = $pinnedSessionIds.get()@@ -2905,6 +2915,43 @@ export function useSessionActions({try {if (closingRuntimeId) {+ // Deleting a session must END its turn, not just drop the row.+ // `session.close` tears down the runtime but does not walk the+ // interrupt path that releases approval / clarify / sudo / secret+ // waits, so a blocked run could outlive its sidebar row and surface a+ // blocking prompt (and native notification) for a conversation that is+ // gone (#75587). Mark the runtime interrupted first so a+ // blocking-input request already queued on the transport is dropped+ // instead of parking its overlay, then interrupt, then close.+ let previousInterruptState: Pick<ClientSessionState, 'interrupted' | 'needsInput'> | null = null++ updateSessionState(closingRuntimeId, state => {+ previousInterruptState = { interrupted: state.interrupted, needsInput: state.needsInput }++ return { ...state, interrupted: true, needsInput: false }+ })++ try {+ await requestForSessionProfile(removedOwner, requestGateway, 'session.interrupt', {+ session_id: closingRuntimeId+ })+ } catch (error) {+ // A missing runtime has no turn left to stop. Any other failure means+ // deletion cannot safely continue: restore the live state and let the+ // outer rollback put the conversation back in the sidebar.+ if (!isSessionGoneError(error)) {+ updateSessionState(closingRuntimeId, state =>+ previousInterruptState ? { ...state, ...previousInterruptState } : state+ )+ throw error+ }+ }++ // Catch a blocking-input request already queued before the interrupted+ // flag became visible to this renderer.+ clearAllPrompts(closingRuntimeId)+ clearClarifyRequest(undefined, closingRuntimeId)+await requestForSessionProfile(removedOwner, requestGateway, 'session.close', {session_id: closingRuntimeId}).catch(() => undefined)@@ -2980,7 +3027,8 @@ export function useSessionActions({runtimeIdByStoredSessionIdRef,selectedStoredSessionIdRef,sessionStateByRuntimeIdRef,- startFreshSessionDraft+ startFreshSessionDraft,+ updateSessionState])