Skip to content

The agent that grows with you

fix(desktop): keep background processes alive on plain interrupt; reap them on regenerate

Cary Palmercffe11a42b16
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 58e55030794..df297c8e4ae 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
@@ -11,8 +11,9 @@ import { createClientSessionState } from '@/lib/chat-runtime'
import { $compactingSessions, setSessionCompacting } from '@/store/compaction'
import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'
import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'
+import { $backgroundStatusBySession, reconcileBackgroundProcesses } from '@/store/composer-status'
import { $confirmRequest, settleConfirm } from '@/store/confirm'
-import { requestGatewayForAgent } from '@/store/gateway'
+import { $gateway, requestGatewayForAgent } from '@/store/gateway'
import { $goalsBySession, setSessionGoal } from '@/store/goals'
import { $hudMode } from '@/store/hud'
import { $notifications, clearNotifications } from '@/store/notifications'
@@ -5093,6 +5094,108 @@ describe('usePromptActions cancelRun', () => {
})
})
+// Plain interrupts must not kill background work; rewinds must. cancelRun is
+// Stop and "send now" on a queued message while busy — the timeline survives,
+// and the gateway's session.interrupt leaves terminal(background=true) running.
+// reload / restore / edit truncate history, so processes from the discarded
+// turns get reaped.
+describe('usePromptActions background processes: interrupt vs rewind', () => {
+ const seed = [
+ { id: 'u1', parts: [textPart('first')], role: 'user' as const, timestamp: 0 },
+ { id: 'a1', parts: [textPart('reply')], role: 'assistant' as const, timestamp: 1 }
+ ]
+
+ let gatewayCalls: Array<{ method: string; params?: Record<string, unknown> }>
+ // resetSessionBackground remembers dismissed ids per session at module
+ // level, so each test seeds a fresh process id.
+ let procSeq = 0
+ let procId = ''
+
+ beforeEach(() => {
+ procId = `proc_live_${++procSeq}`
+ $busy.set(false)
+ $backgroundStatusBySession.set({})
+ setMessages(seed as never)
+ gatewayCalls = []
+ $gateway.set({
+ request: async (method: string, params?: Record<string, unknown>) => {
+ gatewayCalls.push({ method, params })
+
+ return {} as never
+ }
+ } as never)
+ reconcileBackgroundProcesses(RUNTIME_SESSION_ID, [
+ { command: 'npm run dev', session_id: procId, status: 'running' }
+ ] as never)
+ })
+
+ afterEach(() => {
+ cleanup()
+ clearNotifications()
+ setMessages([])
+ $busy.set(false)
+ $backgroundStatusBySession.set({})
+ $gateway.set(null)
+ vi.restoreAllMocks()
+ })
+
+ const killed = () => gatewayCalls.some(call => call.method === 'process.kill' && call.params?.process_id === procId)
+
+ async function mount(requestGateway: ReturnType<typeof vi.fn>) {
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness
+ onReady={h => (handle = h)}
+ refreshSessions={async () => undefined}
+ requestGateway={requestGateway as never}
+ seedMessages={seed}
+ />
+ )
+
+ return handle!
+ }
+
+ it('cancelRun interrupts the turn but leaves running background processes alone', async () => {
+ const requestGateway = vi.fn(async () => ({}) as never)
+ const handle = await mount(requestGateway)
+
+ await handle.cancelRun()
+
+ expect(requestGateway).toHaveBeenCalledWith('session.interrupt', { session_id: RUNTIME_SESSION_ID })
+ expect(requestGateway).not.toHaveBeenCalledWith('process.kill', expect.anything())
+ expect(killed()).toBe(false)
+
+ const rows = $backgroundStatusBySession.get()[RUNTIME_SESSION_ID] ?? []
+
+ expect(rows.map(row => [row.id, row.state])).toEqual([[procId, 'running']])
+ })
+
+ it('reloadFromMessage (regenerate) kills processes from the truncated turns', async () => {
+ const requestGateway = vi.fn(async () => ({}) as never)
+ const handle = await mount(requestGateway)
+
+ await handle.reloadFromMessage('u1')
+
+ expect(requestGateway).toHaveBeenCalledWith(
+ 'prompt.submit',
+ expect.objectContaining({ confirm_truncate: true, truncate_before_message_id: 'u1' }),
+ expect.anything()
+ )
+ expect(killed()).toBe(true)
+ expect($backgroundStatusBySession.get()[RUNTIME_SESSION_ID] ?? []).toEqual([])
+ })
+
+ it('restoreToMessage still kills processes from the discarded turns', async () => {
+ const requestGateway = vi.fn(async () => ({}) as never)
+ const handle = await mount(requestGateway)
+
+ await handle.restoreToMessage('u1')
+
+ expect(killed()).toBe(true)
+ expect($backgroundStatusBySession.get()[RUNTIME_SESSION_ID] ?? []).toEqual([])
+ })
+})
+
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 a38707fd496..85b4366f857 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
@@ -801,7 +801,11 @@ export function usePromptActions({
clearSessionTodos(sessionId)
clearSessionSubagents(sessionId)
- resetSessionBackground(sessionId)
+ // No resetSessionBackground() here. A plain interrupt (Stop, or "send now"
+ // on a queued message while busy) keeps the timeline, and the gateway's
+ // session.interrupt deliberately leaves terminal(background=true) processes
+ // running. Killing them belongs only to the rewind paths (reload / restore /
+ // edit), where the spawning turns are discarded.
setSessionDraftingTool(sessionId, '')
// Auto-compaction sets a per-session flag that only clears on message.start
// / message.complete / error. A hung compaction emits none of those, so the
@@ -1106,6 +1110,13 @@ export function usePromptActions({
return
}
+ // Regenerate truncates history (prompt.submit truncate_before_*) just like
+ // restore/edit, so the discarded turns' todos and background processes
+ // belong to an abandoned timeline — drop them before the re-run.
+ clearSessionTodos(sessionId)
+ resetSessionBackground(sessionId)
+ clearPreviewArtifacts(sessionId)
+
clearNotifications()
updateSessionState(sessionId, state => applyReloadOptimistic(state, plan))