Skip to content

The agent that grows with you

fix(desktop): scope the composer queue panel to the session it renders

unsupportedpastels0609dfb9fe99
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
index e665b154529..f25788dfb0a 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.test.tsx
@@ -496,3 +496,41 @@ describe('useComposerQueue park integration', () => {
expect($notifications.get().some(n => n.message.includes('Re-select the lines'))).toBe(true)
})
})
+
+describe('useComposerQueue scope', () => {
+ afterEach(() => {
+ cleanup()
+ window.localStorage.clear()
+ $queuedPromptsBySession.set({})
+ })
+
+ it('leaving a session for a new chat does not move its queue there (#139190)', () => {
+ enqueueQueuedPrompt('session-a', { attachments: [], text: 'for A' })
+
+ type Scope = { activeQueueSessionKey: string; queueSessionKey: null | string; sessionId: null | string }
+
+ const hook = renderHook(
+ (scope: Scope) =>
+ useComposerQueue({
+ ...scope,
+ attachments: [],
+ busy: true,
+ clearDraft: () => undefined,
+ draftRef: { current: '' },
+ focusInput: () => undefined,
+ loadIntoComposer: () => undefined,
+ onCancel: vi.fn(),
+ onSteer: undefined,
+ onSubmit: vi.fn(async () => true),
+ queueEditRef: { current: null }
+ }),
+ { initialProps: { activeQueueSessionKey: 'session-a', queueSessionKey: 'session-a', sessionId: 'session-a' } as Scope }
+ )
+
+ expect(hook.result.current.queuedPrompts.map(entry => entry.text)).toEqual(['for A'])
+ hook.rerender({ activeQueueSessionKey: '__new__:fresh', queueSessionKey: null, sessionId: null })
+
+ expect(hook.result.current.queuedPrompts).toEqual([])
+ expect(getQueuedPrompts('session-a').map(entry => entry.text)).toEqual(['for A'])
+ })
+})
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
index 3b3d19d985b..9e0b71a7d32 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts
@@ -598,17 +598,23 @@ export function useComposerQueue({
// never churns, so a change there is a real session switch and must NOT
// migrate; only the runtime-derived key (queueSessionKey falsy → key is
// sessionId) churns on a backend bounce/resume of the same conversation.
+ // Both sides must be runtime keys: leaving a stored chat for a fresh draft
+ // is a switch too, and must not carry that chat's queue along (#139190).
+ const runtimeKeyed = !queueSessionKey && activeQueueSessionKey === sessionId
+ const prevRuntimeKeyedRef = useRef(runtimeKeyed)
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
useEffect(() => {
const prev = prevQueueKeyRef.current
+ const prevRuntimeKeyed = prevRuntimeKeyedRef.current
prevQueueKeyRef.current = activeQueueSessionKey
+ prevRuntimeKeyedRef.current = runtimeKeyed
- if (queueSessionKey || !prev || !activeQueueSessionKey || prev === activeQueueSessionKey) {
+ if (!prevRuntimeKeyed || !runtimeKeyed || !prev || !activeQueueSessionKey || prev === activeQueueSessionKey) {
return
}
migrateQueuedPrompts(prev, activeQueueSessionKey)
- }, [activeQueueSessionKey, queueSessionKey])
+ }, [activeQueueSessionKey, runtimeKeyed])
// Queued turns flow whenever the session is idle — on the busy→false settle
// edge, on mount/reconnect, and after a re-key — so a swallowed edge can't
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx
index 6ac5f1a8722..e822b162cb0 100644
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@ -90,7 +90,7 @@ import { shouldConvertPasteToAttachment } from './large-paste'
import { ActionBadges } from './micro-actions'
import { chipTypedPathOnSpace, pathifyRefs } from './path-refs'
import { PreparedImageRecovery } from './prepared-image-recovery'
-import { renderComposerQueueSlot } from './queue-slot'
+import { composerQueueScopeKey, renderComposerQueueSlot } from './queue-slot'
import { RestoredDraftNotice } from './restored-draft-notice'
import {
beginComposerComposition,
@@ -179,7 +179,7 @@ export function ChatBar({
// prompt owns its own dismissal (Skip, Reject, dialog close).
const awaitingInput = useStore(scope.$awaitingInput)
const blockingPrompt = useStore(useMemo(() => sessionBlockingPrompt(sessionId ?? null), [sessionId]))
- const activeQueueSessionKey = queueSessionKey || sessionId || freshDraftKey || null
+ const activeQueueSessionKey = composerQueueScopeKey(queueSessionKey, sessionId, freshDraftKey)
const { collapsed: statusDrawerCollapsed, toggle: toggleStatusDrawer } = useStatusDrawer(activeQueueSessionKey)
const statusDrawerId = useId()
const codingDrawerId = useId()
diff --git a/apps/desktop/src/app/chat/composer/queue-scope.test.tsx b/apps/desktop/src/app/chat/composer/queue-scope.test.tsx
new file mode 100644
index 00000000000..5c2ce2b5fa2
--- /dev/null
+++ b/apps/desktop/src/app/chat/composer/queue-scope.test.tsx
@@ -0,0 +1,70 @@
+import { AssistantRuntimeProvider, type ThreadMessageLike, useExternalStoreRuntime } from '@assistant-ui/react'
+import { cleanup, render, screen } from '@testing-library/react'
+import { MemoryRouter } from 'react-router'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import type { ClientSessionState } from '@/app/types'
+import { I18nProvider } from '@/i18n/context'
+import { en } from '@/i18n/en'
+import { mainComposerScope } from '@/store/composer'
+import { $queuedPromptsBySession, enqueueQueuedPrompt } from '@/store/composer-queue'
+import { $sessionStates } from '@/store/session-states'
+
+import type { ChatBarState } from './types'
+
+import { ChatBar } from './index'
+
+afterEach(() => {
+ cleanup()
+ $queuedPromptsBySession.set({})
+ $sessionStates.set({})
+ mainComposerScope.clear()
+ localStorage.clear()
+})
+
+const chatBarState: ChatBarState = {
+ model: { canSwitch: false, model: '', provider: '' },
+ tools: { enabled: false, label: '' },
+ voice: { enabled: false, active: false }
+}
+
+function Harness({ queueSessionKey }: { queueSessionKey: null | string }) {
+ const runtime = useExternalStoreRuntime({
+ convertMessage: (message: ThreadMessageLike) => message,
+ isRunning: true,
+ messages: [] as ThreadMessageLike[],
+ onNew: async () => {}
+ })
+
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <MemoryRouter>
+ <I18nProvider configClient={null} initialLocale="en">
+ <ChatBar
+ busy
+ disabled={false}
+ freshDraftKey="__new__:fresh"
+ gateway={null}
+ onCancel={vi.fn()}
+ onSubmit={vi.fn(async () => true)}
+ queueSessionKey={queueSessionKey}
+ // The runtime of the chat just left is still active for a frame after the switch.
+ sessionId="session-a"
+ state={chatBarState}
+ />
+ </I18nProvider>
+ </MemoryRouter>
+ </AssistantRuntimeProvider>
+ )
+}
+
+it('a new chat does not show the queue of the session just left (#139190)', async () => {
+ $sessionStates.set({ 'session-a': { storedSessionId: 'session-a' } as ClientSessionState })
+ enqueueQueuedPrompt('session-a', { attachments: [], text: 'for A' })
+
+ const view = render(<Harness queueSessionKey="session-a" />)
+ expect(await screen.findByText(en.composer.queued(1))).toBeTruthy()
+
+ view.rerender(<Harness queueSessionKey={null} />)
+ expect(screen.queryByText(en.composer.queued(1))).toBeNull()
+})
diff --git a/apps/desktop/src/app/chat/composer/queue-slot.tsx b/apps/desktop/src/app/chat/composer/queue-slot.tsx
index 38a639014a0..0d143a3b750 100644
--- a/apps/desktop/src/app/chat/composer/queue-slot.tsx
+++ b/apps/desktop/src/app/chat/composer/queue-slot.tsx
@@ -4,6 +4,7 @@ import type { HermesGateway } from '@/hermes'
import type { Translations } from '@/i18n'
import { type QueuedPromptEntry, removeQueuedPrompt, unparkQueuedPrompts } from '@/store/composer-queue'
import { notifyError } from '@/store/notifications'
+import { storedSessionIdForRuntimeId } from '@/store/session-states'
import type { QueueEditState } from './composer-utils'
import { cancelQueuedPrompt, discardLostPrompt } from './discard-lost-prompt'
@@ -25,6 +26,28 @@ export interface ComposerQueueSlotInputs {
t: Translations
}
+/**
+ * The composer's draft/queue scope. A routed chat uses its durable key. Without
+ * one (a new-chat route) the runtime id stands in only while no stored session
+ * claims it: a claimed runtime there is the chat just left, still active for a
+ * frame after the switch, and its queue is not this chat's (#139190).
+ */
+export function composerQueueScopeKey(
+ queueSessionKey: null | string | undefined,
+ sessionId: null | string | undefined,
+ freshDraftKey: null | string | undefined
+): null | string {
+ if (queueSessionKey) {
+ return queueSessionKey
+ }
+
+ if (sessionId && !storedSessionIdForRuntimeId(sessionId)) {
+ return sessionId
+ }
+
+ return freshDraftKey || null
+}
+
/**
* The queue node handed to the status stack: a QueuePanel wired to the
* composer's queue engine, or null when there is nothing queued (the stack
diff --git a/apps/desktop/src/store/composer-queue.test.ts b/apps/desktop/src/store/composer-queue.test.ts
index febcfce0776..09da587b26c 100644
--- a/apps/desktop/src/store/composer-queue.test.ts
+++ b/apps/desktop/src/store/composer-queue.test.ts
@@ -231,6 +231,16 @@ describe('migrateQueuedPrompts', () => {
expect(migrateQueuedPrompts('rt-old', 'rt-new')).toBe(false)
expect(migrateQueuedPrompts('rt-x', 'rt-x')).toBe(false)
})
+
+ it('migrating the same submission twice keeps one entry (#138934)', () => {
+ enqueueQueuedPrompt('rt-old', { attachments: [], id: 'sub-1', text: 'once' })
+ migrateQueuedPrompts('rt-old', 'rt-new')
+ enqueueQueuedPrompt('rt-old', { attachments: [], id: 'sub-1', text: 'once' })
+ migrateQueuedPrompts('rt-old', 'rt-new')
+
+ expect(getQueuedPrompts('rt-new').map(e => e.id)).toEqual(['sub-1'])
+ expect(getQueuedPrompts('rt-old')).toEqual([])
+ })
})
describe('shouldAutoDrain', () => {
diff --git a/apps/desktop/src/store/composer-queue.ts b/apps/desktop/src/store/composer-queue.ts
index 3d9123d102a..ade99a83e8b 100644
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@ -607,8 +607,12 @@ export const migrateQueuedPrompts = (fromKey: string | null | undefined, toKey:
}
const next: QueueState = { ...live }
+ const target = live[to] ?? []
+ // An entry re-mirrored under the old key after an earlier migration keeps
+ // its one row on the target: same id, same submission (#138934).
+ const onTarget = new Set(target.map(entry => entry.id))
delete next[from]
- next[to] = [...(live[to] ?? []), ...pending]
+ next[to] = [...target, ...pending.filter(entry => !onTarget.has(entry.id))]
$queuedPromptsBySession.set(next)
save(next)
diff --git a/apps/desktop/src/store/pending-submissions.test.ts b/apps/desktop/src/store/pending-submissions.test.ts
index 63f2aa70df6..c85f9d2254f 100644
--- a/apps/desktop/src/store/pending-submissions.test.ts
+++ b/apps/desktop/src/store/pending-submissions.test.ts
@@ -5,9 +5,11 @@ import { handleSessionInfoEvent } from '@/app/session/hooks/use-message-stream/g
import type { GatewayEventContext } from '@/app/session/hooks/use-message-stream/gateway-event/types'
import { applyRuntimeInfo } from '@/app/session/hooks/use-session-actions/utils'
import { isSteerableEntry } from '@/store/composer-queue'
+import type { SessionInfo } from '@/types/hermes'
-import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts } from './composer-queue'
+import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts, migrateQueuedPrompts } from './composer-queue'
import { readPendingSubmissions, reconcilePendingSubmissions, trackPendingSubmission } from './pending-submissions'
+import { $sessions } from './session'
beforeEach(() => {
window.localStorage.clear()
@@ -145,3 +147,30 @@ it('a stale started snapshot keeps an existing unknown card and its Discard cont
reconcilePendingSubmissions('lost', [])
expect(getQueuedPrompts('lost')).toEqual([])
})
+
+// After compression the panel reads the lineage root while the runtime reports the tip. A tip-keyed
+// projection only reached the panel through rotation migrations, which stacked copies there that no
+// later snapshot could retire: duplicate, undeletable, back after a delete (#138934).
+it('projects a compressed tip snapshot onto the lineage key the panel reads', () => {
+ $sessions.set([{ id: 'tip', _lineage_root_id: 'root' } as SessionInfo])
+
+ try {
+ const listed = [{ admission_id: 'x', status: 'queued', user: 'later' }]
+ reconcilePendingSubmissions('tip', listed, { epoch: 'e', sequence: 1 })
+ migrateQueuedPrompts('tip', 'root')
+ reconcilePendingSubmissions('tip', listed, { epoch: 'e', sequence: 2 })
+ migrateQueuedPrompts('tip', 'root')
+ expect(getQueuedPrompts('root').map(entry => [entry.id, entry.serverStatus])).toEqual([['x', 'queued']])
+
+ // Withdrawn at the gateway: the next snapshot no longer lists it.
+ reconcilePendingSubmissions('tip', [], { epoch: 'e', sequence: 3 })
+ expect(getQueuedPrompts('root')).toEqual([])
+
+ // The same earlier status mirrored again does not bring it back.
+ reconcilePendingSubmissions('tip', listed, { epoch: 'e', sequence: 2 })
+ migrateQueuedPrompts('tip', 'root')
+ expect(getQueuedPrompts('root')).toEqual([])
+ } finally {
+ $sessions.set([])
+ }
+})
diff --git a/apps/desktop/src/store/pending-submissions.ts b/apps/desktop/src/store/pending-submissions.ts
index c04d1ff319c..c5b52841216 100644
--- a/apps/desktop/src/store/pending-submissions.ts
+++ b/apps/desktop/src/store/pending-submissions.ts
@@ -1,4 +1,5 @@
import { getQueuedPrompts, type QueuedPromptEntry, writeSessionQueue } from './composer-queue'
+import { $sessions, resolveComposerSessionKey } from './session'
// One localStorage key per (session, admission). Every Desktop window of the origin shares this
// storage with last-writer-wins per KEY, so a single journal blob let one window's
@@ -203,11 +204,15 @@ function updateKnownReceipts(known: Record<string, PendingSubmission>, value: Ra
/** Project one pending snapshot onto the session's queue. `fence` orders canonical snapshots so a
* delayed older one cannot retire an admission a newer one still listed. */
-export function reconcilePendingSubmissions(key: string, value: unknown, fence?: PendingSnapshotFence): void {
+export function reconcilePendingSubmissions(storedId: string, value: unknown, fence?: PendingSnapshotFence): void {
if (!Array.isArray(value)) {
return
}
+ // Project onto the key the queue panel reads. After compression that is the lineage root, not
+ // the tip the runtime reports, and only snapshots projected there can retire a card shown there.
+ const key = resolveComposerSessionKey(storedId, $sessions.get()) ?? storedId
+
const before = readPendingSubmissions(key)
const known = { ...before }
const { receipts, admissionByInput } = collectReceipts(value, known)