Skip to content

The agent that grows with you

fix(desktop): keep queued prompts bound to their origin session

Andrew Fiebertc9de69c6d5ed
diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx
index 5c0bc521485..0cfe8e0205c 100644
--- a/apps/desktop/src/app/chat/index.tsx
+++ b/apps/desktop/src/app/chat/index.tsx
@@ -39,7 +39,8 @@ import {
$sessions,
resolveComposerSessionKey,
sessionMatchesStoredId,
- sessionPinId
+ sessionPinId,
+ shouldMigrateComposerScope
} from '@/store/session'
import { isSecondaryWindow, isWatchWindow } from '@/store/windows'
import type { ModelOptionsResponse } from '@/types/hermes'
@@ -326,14 +327,19 @@ export function ChatView({
// When the tip row arrives after compression, migrate any tip-keyed stash onto
// the durable lineage key before the composer remounts onto that key.
+ //
+ // ONLY same-conversation rekeys (tip → root). The route-driven queueSessionKey
+ // can flip to Session B a frame before the store selection leaves Session A;
+ // migrating on bare inequality would re-home A's queued prompts onto B and
+ // auto-drain them into the wrong chat.
useEffect(() => {
- if (!selectedSessionId || !queueSessionKey || selectedSessionId === queueSessionKey) {
+ if (!shouldMigrateComposerScope(selectedSessionId, queueSessionKey, sessions)) {
return
}
migrateSessionDraft(selectedSessionId, queueSessionKey)
migrateQueuedPrompts(selectedSessionId, queueSessionKey)
- }, [queueSessionKey, selectedSessionId])
+ }, [queueSessionKey, selectedSessionId, sessions])
// Transcript-side stops (the streaming message's hover Stop, the runtime's
// cancel) are explicit halts, same as the composer's Stop button: park any
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
index dcc16593c18..f9060982294 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.test.tsx
@@ -10,11 +10,33 @@ import {
getQueuedPrompts,
parkQueuedPrompts
} from '@/store/composer-queue'
+import { $sessions, setSessions } from '@/store/session'
import { clearAllSessionStates, publishSessionState } from '@/store/session-states'
+import type { SessionInfo } from '@/types/hermes'
import { useBackgroundQueueDrain } from './use-background-queue-drain'
import type { SubmitTextOptions } from './use-prompt-actions/utils'
+const lineageSession = (over: Partial<SessionInfo>): SessionInfo =>
+ ({
+ archived: false,
+ cwd: null,
+ ended_at: null,
+ id: 'live',
+ input_tokens: 0,
+ is_active: false,
+ last_active: 0,
+ message_count: 0,
+ model: null,
+ output_tokens: 0,
+ preview: null,
+ source: null,
+ started_at: 0,
+ title: null,
+ tool_call_count: 0,
+ ...over
+ }) as SessionInfo
+
function Harness({
enabled = true,
runtimeMap,
@@ -48,6 +70,7 @@ describe('useBackgroundQueueDrain', () => {
vi.useRealTimers()
$queuedPromptsBySession.set({})
$parkedQueueSessions.set({})
+ $sessions.set([])
clearAllSessionStates()
})
@@ -103,6 +126,40 @@ describe('useBackgroundQueueDrain', () => {
expect(getQueuedPrompts('stored-session-a')).toHaveLength(1)
})
+ it('treats a tip working id as busy for a root queue key via lineage', async () => {
+ // Queue keys use the lineage root (resolveComposerSessionKey) while
+ // $workingSessionIds may hold the compression tip — strict equality misses.
+ const runtimeMap = { current: new Map([['root-a', 'rt-tip-a']]) }
+ const submitText = vi.fn(async () => true)
+
+ setSessions([lineageSession({ id: 'tip-a', _lineage_root_id: 'root-a' })])
+ enqueueQueuedPrompt('root-a', { text: 'wait for tip turn', attachments: [] })
+ publishSessionState('rt-tip-a', { ...createClientSessionState('tip-a'), busy: true })
+
+ render(<Harness runtimeMap={runtimeMap} submitText={submitText} />)
+
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+
+ expect(submitText).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('root-a')).toHaveLength(1)
+ })
+
+ it('leaves a root queue to ChatBar when the selected id is the compression tip', async () => {
+ const runtimeMap = { current: new Map([['root-a', 'rt-tip-a']]) }
+ const submitText = vi.fn(async () => true)
+
+ setSessions([lineageSession({ id: 'tip-a', _lineage_root_id: 'root-a' })])
+ enqueueQueuedPrompt('root-a', { text: 'visible after tip select', attachments: [] })
+ clearAllSessionStates()
+
+ render(<Harness runtimeMap={runtimeMap} selectedStoredSessionId="tip-a" submitText={submitText} />)
+
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+
+ expect(submitText).not.toHaveBeenCalled()
+ expect(getQueuedPrompts('root-a')).toHaveLength(1)
+ })
+
it('does not drain a parked background session, even when idle', async () => {
// A Stop in a tile parks that session's queue; when the user then focuses
// another chat, THIS drainer takes over the tile's queue — it must honor
diff --git a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
index 5adf910bdb7..8573ab9c8aa 100644
--- a/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
+++ b/apps/desktop/src/app/session/hooks/use-background-queue-drain.ts
@@ -13,6 +13,7 @@ import {
shouldAutoDrain
} from '@/store/composer-queue'
import { notify } from '@/store/notifications'
+import { $sessions, idsShareLineage } from '@/store/session'
import { $workingSessionIds } from '@/store/session-states'
import type { SubmitTextOptions } from './use-prompt-actions/utils'
@@ -154,14 +155,23 @@ export function useBackgroundQueueDrain({
return
}
- const working = new Set(workingSessionIds)
+ // Queue keys prefer the lineage root (resolveComposerSessionKey) while
+ // $workingSessionIds / selection may hold the compression tip. Strict
+ // equality then mis-classifies a busy or selected chat as idle/offscreen.
+ const sessions = $sessions.get()
+ const working = [...workingSessionIds]
for (const [sessionKey, entries] of Object.entries(queuedPromptsBySession)) {
+ const isSelected =
+ Boolean(selectedStoredSessionId) && idsShareLineage(sessionKey, selectedStoredSessionId!, sessions)
+
+ const isBusy = working.some(workingId => idsShareLineage(sessionKey, workingId, sessions))
+
if (
- sessionKey === selectedStoredSessionId ||
+ isSelected ||
drainingSessionIdsRef.current.has(sessionKey) ||
!shouldAutoDrain({
- isBusy: working.has(sessionKey),
+ isBusy,
parked: Boolean(parkedQueueSessions[sessionKey]),
queueLength: entries.length
})
diff --git a/apps/desktop/src/store/composer-queue.test.ts b/apps/desktop/src/store/composer-queue.test.ts
index 49e9fb3cf97..7e7d0940ee0 100644
--- a/apps/desktop/src/store/composer-queue.test.ts
+++ b/apps/desktop/src/store/composer-queue.test.ts
@@ -151,6 +151,19 @@ describe('migrateQueuedPrompts', () => {
expect(migrateQueuedPrompts('rt-old', 'rt-new')).toBe(false)
expect(migrateQueuedPrompts('rt-x', 'rt-x')).toBe(false)
})
+
+ it('must not be used across sessions without a same-lineage guard (documents the leak)', () => {
+ // ChatView used to call migrateQueuedPrompts(selectedA, routeKeyB) during the
+ // route-ahead/store-lag window of a session switch. That re-homes A's queue
+ // onto B so the idle ChatBar on B auto-drains it into the wrong conversation.
+ // The guard lives in shouldMigrateComposerScope — this test locks the
+ // underlying hazard so a future caller cannot treat migrate as free.
+ enqueueQueuedPrompt('root-a', { attachments: [], text: 'belongs to A' })
+
+ expect(migrateQueuedPrompts('root-a', 'root-b')).toBe(true)
+ expect(getQueuedPrompts('root-a')).toEqual([])
+ expect(getQueuedPrompts('root-b').map(e => e.text)).toEqual(['belongs to A'])
+ })
})
describe('shouldAutoDrain', () => {
diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.ts
index b44c17b2bd8..415c167a195 100644
--- a/apps/desktop/src/store/session.test.ts
+++ b/apps/desktop/src/store/session.test.ts
@@ -23,6 +23,7 @@ import {
setRememberedSessionId,
setSelectedStoredSessionId,
setSessions,
+ shouldMigrateComposerScope,
touchSessionActivity,
workspaceCwdForNewSession
} from './session'
@@ -109,6 +110,35 @@ describe('resolveComposerSessionKey', () => {
})
})
+describe('shouldMigrateComposerScope', () => {
+ it('allows tip → lineage-root rekey within the same conversation', () => {
+ const sessions = [session({ id: 'tip-a', _lineage_root_id: 'root-a' })]
+
+ expect(shouldMigrateComposerScope('tip-a', 'root-a', sessions)).toBe(true)
+ })
+
+ it('blocks cross-session migrate when route flipped but store selection lags', () => {
+ // ChatView mid-switch: selectedStoredSessionId still A, route-driven
+ // queueSessionKey already B. Migrating would re-home A's queue onto B.
+ const sessions = [
+ session({ id: 'tip-a', _lineage_root_id: 'root-a' }),
+ session({ id: 'tip-b', _lineage_root_id: 'root-b' })
+ ]
+
+ expect(shouldMigrateComposerScope('tip-a', 'root-b', sessions)).toBe(false)
+ expect(shouldMigrateComposerScope('root-a', 'root-b', sessions)).toBe(false)
+ expect(shouldMigrateComposerScope('tip-a', 'tip-b', sessions)).toBe(false)
+ })
+
+ it('is a no-op for identical or missing keys', () => {
+ const sessions = [session({ id: 'tip-a', _lineage_root_id: 'root-a' })]
+
+ expect(shouldMigrateComposerScope('root-a', 'root-a', sessions)).toBe(false)
+ expect(shouldMigrateComposerScope(null, 'root-a', sessions)).toBe(false)
+ expect(shouldMigrateComposerScope('root-a', null, sessions)).toBe(false)
+ })
+})
+
describe('mergeSessionPage', () => {
it('returns the server page untouched when there is nothing to keep', () => {
const previous = [session({ id: 'a' }), session({ id: 'b' })]
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index c9d7c1904d1..19e56b2c1b1 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -192,6 +192,42 @@ export const sessionMatchesStoredId = (
storedSessionId: string
): boolean => session.id === storedSessionId || session._lineage_root_id === storedSessionId
+/** True when two ids name the same conversation across compression tip rotation. */
+export function idsShareLineage(
+ a: string,
+ b: string,
+ sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id'>[]
+): boolean {
+ if (a === b) {
+ return true
+ }
+
+ return sessions.some(session => sessionMatchesStoredId(session, a) && sessionMatchesStoredId(session, b))
+}
+
+/**
+ * Whether a composer draft/queue key should move from `fromKey` onto `toKey`.
+ *
+ * Only same-conversation rekeys are allowed (compression tip → lineage root).
+ * A session-switch window where the route already points at B while the store
+ * selection still holds A must NOT migrate — that would re-home Session A's
+ * queued prompts onto B and auto-drain them into the wrong chat.
+ */
+export function shouldMigrateComposerScope(
+ fromKey: string | null | undefined,
+ toKey: string | null | undefined,
+ sessions: readonly Pick<SessionInfo, '_lineage_root_id' | 'id'>[]
+): boolean {
+ const from = fromKey?.trim()
+ const to = toKey?.trim()
+
+ if (!from || !to || from === to) {
+ return false
+ }
+
+ return idsShareLineage(from, to, sessions)
+}
+
/**
* Stable composer + `/queue` scope for a selected stored session.
*