Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { resetBrowseState } from '@/store/composer-input-history'
import {
$queuedPromptsBySession,
enqueueQueuedPrompt,
getQueuedPrompts,
MAX_AUTO_DRAIN_ATTEMPTS,
migrateQueuedPrompts,
promoteQueuedPrompt,
Expand Down Expand Up @@ -189,7 +190,9 @@ export function useComposerQueue({
return false
}

const entry = pickEntry(queuedPrompts)
const drainQueueSessionKey = activeQueueSessionKey
const drainRuntimeSessionId = sessionId ?? null
const entry = pickEntry(getQueuedPrompts(drainQueueSessionKey))

if (!entry) {
return false
Expand All @@ -199,23 +202,28 @@ export function useComposerQueue({

try {
const accepted = await Promise.resolve(
onSubmit(entry.text, { attachments: entry.attachments, fromQueue: true })
onSubmit(entry.text, {
attachments: entry.attachments,
fromQueue: true,
sessionId: drainRuntimeSessionId,
storedSessionId: drainQueueSessionKey
})
)

if (accepted === false) {
return false
}

drainFailuresRef.current.delete(entry.id)
removeQueuedPrompt(activeQueueSessionKey, entry.id)
resetBrowseState(sessionId)
removeQueuedPrompt(drainQueueSessionKey, entry.id)
resetBrowseState(drainRuntimeSessionId)

return true
} finally {
drainingQueueRef.current = false
}
},
[activeQueueSessionKey, onSubmit, queuedPrompts, sessionId]
[activeQueueSessionKey, onSubmit, sessionId]
)

const pickDrainHead = useCallback(
Expand Down
7 changes: 2 additions & 5 deletions apps/desktop/src/app/chat/composer/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ReactNode } from 'react'

import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'
import type { HermesGateway } from '@/hermes'
import type { ComposerAttachment } from '@/store/composer'

import type { DroppedFile } from '../hooks/use-composer-actions'

Expand Down Expand Up @@ -52,10 +52,7 @@ export interface ChatBarProps {
onPickImages?: () => void
onRemoveAttachment?: (id: string) => void
onSteer?: (text: string) => Promise<boolean> | boolean
onSubmit: (
value: string,
options?: { attachments?: ComposerAttachment[]; fromQueue?: boolean }
) => Promise<boolean> | boolean
onSubmit: (value: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onTranscribeAudio?: (audio: Blob) => Promise<string>
}

Expand Down
7 changes: 2 additions & 5 deletions apps/desktop/src/app/chat/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type * as React from 'react'
import { Suspense, useCallback, useMemo } from 'react'
import { useLocation } from 'react-router-dom'

import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'
import { Thread } from '@/components/assistant-ui/thread'
import { Backdrop } from '@/components/Backdrop'
import { COMPOSER_HEART_CONFIG, HeartField } from '@/components/chat/vibe-hearts'
Expand All @@ -19,7 +20,6 @@ import type { ChatMessage } from '@/lib/chat-messages'
import { quickModelOptions, sessionTitle } from '@/lib/chat-runtime'
import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'
import { cn } from '@/lib/utils'
import type { ComposerAttachment } from '@/store/composer'
import { $pinnedSessionIds } from '@/store/layout'
import { $petActive } from '@/store/pet'
import { $petOverlayActive } from '@/store/pet-overlay'
Expand Down Expand Up @@ -74,10 +74,7 @@ interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
onPickImages: () => void
onRemoveAttachment: (id: string) => void
onSteer: (text: string) => Promise<boolean> | boolean
onSubmit: (
text: string,
options?: { attachments?: ComposerAttachment[]; fromQueue?: boolean }
) => Promise<boolean> | boolean
onSubmit: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
onEdit: (message: AppendMessage) => Promise<void>
onReload: (parentId: string | null) => Promise<void>
Expand Down
10 changes: 10 additions & 0 deletions apps/desktop/src/app/contrib/wiring.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ import { PersistentTerminal } from '../right-sidebar/terminal/persistent'
import { CRON_ROUTE, routeSessionId, sessionRoute, SETTINGS_ROUTE, syncWorkspaceIsPage } from '../routes'
import { SessionPickerOverlay } from '../session-picker-overlay'
import { SessionSwitcher } from '../session-switcher'
import { useBackgroundQueueDrain } from '../session/hooks/use-background-queue-drain'
import { useContextSuggestions } from '../session/hooks/use-context-suggestions'
import { useCwdActions } from '../session/hooks/use-cwd-actions'
import { useHermesConfig } from '../session/hooks/use-hermes-config'
Expand Down Expand Up @@ -515,6 +516,15 @@ export function ContribWiring({ children }: { children: ReactNode }) {
updateSessionState
})

// Runs outside the selected ChatBar so queues belonging to background
// sessions continue once those sessions are idle.
useBackgroundQueueDrain({
enabled: gatewayState === 'open',
runtimeIdByStoredSessionIdRef,
selectedStoredSessionId,
submitText
})

// Session-tile delegate (resume/submit/interrupt/slash + the session verbs
// the tile TAB menu needs, without touching the primary view).
useSessionTileDelegate({
Expand Down
139 changes: 139 additions & 0 deletions apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { act, cleanup, render, waitFor } from '@testing-library/react'
import type { MutableRefObject } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts } from '@/store/composer-queue'
import { $workingSessionIds } from '@/store/session'

import { useBackgroundQueueDrain } from './use-background-queue-drain'
import type { SubmitTextOptions } from './use-prompt-actions/utils'

function Harness({
enabled = true,
runtimeMap,
selectedStoredSessionId = 'stored-session-b',
submitText
}: {
enabled?: boolean
runtimeMap: MutableRefObject<Map<string, string>>
selectedStoredSessionId?: string | null
submitText: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
}) {
useBackgroundQueueDrain({
enabled,
runtimeIdByStoredSessionIdRef: runtimeMap,
selectedStoredSessionId,
submitText
})

return null
}

describe('useBackgroundQueueDrain', () => {
beforeEach(() => {
vi.useRealTimers()
})

afterEach(() => {
cleanup()
vi.restoreAllMocks()
vi.useRealTimers()
$queuedPromptsBySession.set({})
$workingSessionIds.set([])
})

it('drains an idle queued prompt for a non-selected background session', async () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)

enqueueQueuedPrompt('stored-session-a', { text: 'continue in the background', attachments: [] })
$workingSessionIds.set([])

render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)

await waitFor(() => {
expect(submitText).toHaveBeenCalledWith('continue in the background', {
attachments: [],
fromQueue: true,
sessionId: 'rt-session-a',
storedSessionId: 'stored-session-a'
})
})

await waitFor(() => expect(getQueuedPrompts('stored-session-a')).toHaveLength(0))
})

it('leaves the selected session queue to the mounted ChatBar drainer', async () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)

enqueueQueuedPrompt('stored-session-a', { text: 'visible queue entry', attachments: [] })
$workingSessionIds.set([])

render(<Harness runtimeMap={runtimeMap} selectedStoredSessionId="stored-session-a" submitText={submitText} />)

await new Promise(resolve => window.setTimeout(resolve, 0))

expect(submitText).not.toHaveBeenCalled()
expect(getQueuedPrompts('stored-session-a')).toHaveLength(1)
})

it('does not drain a background session that is still marked working', async () => {
const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn(async () => true)

enqueueQueuedPrompt('stored-session-a', { text: 'wait for current turn', attachments: [] })
$workingSessionIds.set(['stored-session-a'])

render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)

await new Promise(resolve => window.setTimeout(resolve, 0))

expect(submitText).not.toHaveBeenCalled()
expect(getQueuedPrompts('stored-session-a')).toHaveLength(1)
})

it('passes a null runtime id so submitText can resume stale background sessions by stored id', async () => {
const runtimeMap = { current: new Map<string, string>() }
const submitText = vi.fn(async () => true)

enqueueQueuedPrompt('stored-session-a', { text: 'resume then send', attachments: [] })

render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)

await waitFor(() => {
expect(submitText).toHaveBeenCalledWith('resume then send', {
attachments: [],
fromQueue: true,
sessionId: null,
storedSessionId: 'stored-session-a'
})
})
})

it('retries a rejected background drain without waiting for another queue or busy-state change', async () => {
vi.useFakeTimers()

const runtimeMap = { current: new Map([['stored-session-a', 'rt-session-a']]) }
const submitText = vi.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true)

enqueueQueuedPrompt('stored-session-a', { text: 'retry me', attachments: [] })

render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)

await act(async () => {
await Promise.resolve()
})

expect(submitText).toHaveBeenCalledTimes(1)
expect(getQueuedPrompts('stored-session-a')).toHaveLength(1)

await act(async () => {
await vi.advanceTimersByTimeAsync(750)
await Promise.resolve()
})

expect(submitText).toHaveBeenCalledTimes(2)
expect(getQueuedPrompts('stored-session-a')).toHaveLength(0)
})
})
Loading
Loading