The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): ack quick entry submit and create the session atomically (#85590)
LeonardoLGDSa09ea688a700
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 7c5f05db427..735688f7e65 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -470,7 +470,12 @@ import {tagRegistrySessionResponse,tagRemoteSessionRows} from './profile-session-routing'-import { createQuickEntryShortcut, quickEntryWindowBounds, sanitizeQuickEntrySettings } from './quick-entry'+import {+ createQuickEntryShortcut,+ createQuickEntrySubmitRelay,+ quickEntryWindowBounds,+ sanitizeQuickEntrySettings+} from './quick-entry'import { createQuitFinalization } from './quit-finalization'import {type ActiveWork,@@ -18085,29 +18090,54 @@ ipcMain.handle('hermes:quick-entry:settings:set', async (_event, patch) => {// owns the one prompt-submit path, and forwarding keeps it that way. The// payload is `{ target, text }` — target routing (current chat / a picked// session / new) is the renderer's job too.-ipcMain.on('hermes:quick-entry:submit', (_event, payload) => {- hideQuickEntryWindow()+const quickEntrySubmitRelay = createQuickEntrySubmitRelay({+ onSuccess: () => {+ hideQuickEntryWindow()+ if (process.platform === 'darwin') {+ app.dock?.show()+ }+ if (mainWindow && !mainWindow.isDestroyed()) {+ mainWindow.show()+ mainWindow.focus()+ }+ }+})++// Main owns the request lifecycle so the capture window can keep text until+// the primary renderer confirms delivery (#85590).+ipcMain.handle('hermes:quick-entry:submit', (event, payload) => {+ if (!quickEntryWindow || event.sender !== quickEntryWindow.webContents) {+ return { code: 'forbidden', message: 'Quick Entry sender is not authorized.', ok: false, retryable: false }+ }- const text = typeof payload?.text === 'string' ? payload.text.trim() : ''+ const text =+ typeof payload === 'string' ? payload.trim() : typeof payload?.text === 'string' ? payload.text.trim() : ''if (!text) {- return+ return { code: 'empty', message: 'Enter a prompt before submitting.', ok: false, retryable: false }}if (!mainWindow || mainWindow.isDestroyed()) {- rememberLog('[quick-entry] dropped a submit: no primary window to route it to')-- return+ return { code: 'no-primary', message: 'The primary Hermes window is unavailable.', ok: false, retryable: true }}- // Deliberately does NOT raise/focus the main window — the user asked to fire- // a prompt from wherever they were, not to be yanked into the app.- mainWindow.webContents.send('hermes:quick-entry:submit', {- target: typeof payload?.target === 'string' && payload.target ? payload.target : 'current',- text+ const target =+ typeof payload === 'object' && typeof payload?.target === 'string' && payload.target ? payload.target : 'current'++ return quickEntrySubmitRelay.begin(correlationId => {+ mainWindow.webContents.send('hermes:quick-entry:submit', { correlationId, target, text })})})+// Main cannot invoke the primary renderer, so the primary returns by id. Stale+// or duplicate acknowledgements are intentionally ignored (#85590).+ipcMain.on('hermes:quick-entry:ack', (event, payload) => {+ if (!mainWindow || event.sender !== mainWindow.webContents) {+ return+ }+ quickEntrySubmitRelay.acknowledge(payload?.correlationId, payload?.result)+})+// Primary renderer → main → quick window: gateway connection state + the// recent-session list for the target picker. Cached so a quick window spawned// AFTER the last push still boots from truth instead of "disconnected".diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 627a5756c4b..45f59999866 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -228,7 +228,11 @@ contextBridge.exposeInMainWorld('hermesDesktop', {quickEntry: {getSettings: () => ipcRenderer.invoke('hermes:quick-entry:settings:get'),setSettings: patch => ipcRenderer.invoke('hermes:quick-entry:settings:set', patch),- submit: payload => ipcRenderer.send('hermes:quick-entry:submit', payload),+ // Invoke returns the delivery result so the draft is not lost (#85590).+ submit: payload => ipcRenderer.invoke('hermes:quick-entry:submit', payload),+ // Main cannot invoke the primary renderer, so it receives this ack (#85590).+ ackSubmit: (correlationId, result) =>+ ipcRenderer.send('hermes:quick-entry:ack', { correlationId, result }),dismiss: () => ipcRenderer.send('hermes:quick-entry:dismiss'),// Primary renderer → main → quick window: gateway connection state + the// recent-session options the target picker offers. Main caches the latestdiff --git a/apps/desktop/electron/quick-entry.test.ts b/apps/desktop/electron/quick-entry.test.tsindex fa8039791d4..68b80bd3cdf 100644--- a/apps/desktop/electron/quick-entry.test.ts+++ b/apps/desktop/electron/quick-entry.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import {createQuickEntryShortcut,+ createQuickEntrySubmitRelay,DEFAULT_QUICK_ENTRY_SHORTCUT,type GlobalShortcutLike,parseQuickEntryShortcut,@@ -9,6 +10,66 @@ import {sanitizeQuickEntrySettings} from './quick-entry'+describe('quick-entry submit ack relay', () => {+ it('ignores an ack for a stale correlation id', async () => {+ const relay = createQuickEntrySubmitRelay({ onSuccess: vi.fn(), timeoutMs: 1000 })+ let correlationId = ''+ let settled = false+ const pending = relay.begin(id => {+ correlationId = id+ }).then(() => {+ settled = true+ })++ relay.acknowledge('qe-stale', { ok: true })+ await Promise.resolve()++ expect(settled).toBe(false)+ expect(relay.pendingCount()).toBe(1)+ relay.acknowledge(correlationId, { ok: false })+ await pending+ expect(relay.pendingCount()).toBe(0)+ })++ it('resolves an unacknowledged submit as a timeout and cleans it up', async () => {+ vi.useFakeTimers()+ const relay = createQuickEntrySubmitRelay({ onSuccess: vi.fn(), timeoutMs: 15000 })+ const pending = relay.begin(vi.fn())++ await vi.advanceTimersByTimeAsync(15000)++ await expect(pending).resolves.toMatchObject({ code: 'timeout', ok: false })+ expect(relay.pendingCount()).toBe(0)+ vi.useRealTimers()+ })++ it('runs hide and primary focus only after an ok acknowledgement', async () => {+ const events: string[] = []+ const relay = createQuickEntrySubmitRelay({+ onSuccess: () => events.push('hide-primary-show-focus'),+ timeoutMs: 1000+ })+ let correlationId = ''+ const pending = relay.begin(id => {+ correlationId = id+ events.push('forward')+ })++ relay.acknowledge(correlationId, { ok: false })+ await expect(pending).resolves.toMatchObject({ ok: false })+ expect(events).toEqual(['forward'])++ let okCorrelationId = ''+ const okPending = relay.begin(id => {+ okCorrelationId = id+ events.push('forward-ok')+ })+ relay.acknowledge(okCorrelationId, { ok: true })+ await expect(okPending).resolves.toMatchObject({ ok: true })+ expect(events).toEqual(['forward', 'forward-ok', 'hide-primary-show-focus'])+ })+})+function fakeGlobalShortcut(options: { register?: boolean; taken?: string[] } = {}) {const held = new Set(options.taken ?? [])diff --git a/apps/desktop/electron/quick-entry.ts b/apps/desktop/electron/quick-entry.tsindex d8233c217ee..91b987f117f 100644--- a/apps/desktop/electron/quick-entry.ts+++ b/apps/desktop/electron/quick-entry.ts@@ -28,6 +28,64 @@ const QUICK_ENTRY_WINDOW_HEIGHT = 168// comfortable fraction down from the top rather than dead center.const QUICK_ENTRY_TOP_FRACTION = 0.22+export interface QuickEntrySubmitRelayResult {+ ok: boolean+ [key: string]: unknown+}++export interface QuickEntrySubmitRelay {+ begin: (forward: (correlationId: string) => void) => Promise<QuickEntrySubmitRelayResult>+ acknowledge: (correlationId: string, result: QuickEntrySubmitRelayResult) => void+ pendingCount: () => number+}++export function createQuickEntrySubmitRelay(options: {+ onSuccess: () => void+ timeoutMs?: number+}): QuickEntrySubmitRelay {+ const pending = new Map<+ string,+ { resolve: (result: QuickEntrySubmitRelayResult) => void; timer: NodeJS.Timeout }+ >()+ let sequence = 0++ return {+ acknowledge(correlationId, result) {+ const request = pending.get(correlationId)+ if (!request) {+ return+ }++ clearTimeout(request.timer)+ pending.delete(correlationId)+ request.resolve(result)+ if (result.ok === true) {+ options.onSuccess()+ }+ },+ begin(forward) {+ const correlationId = ['qe', Date.now(), ++sequence].join('-')++ return new Promise(resolve => {+ const timer = setTimeout(() => {+ pending.delete(correlationId)+ resolve({+ code: 'timeout',+ message: 'Hermes did not confirm the prompt in time.',+ ok: false,+ retryable: true+ })+ }, options.timeoutMs ?? 15_000)+ pending.set(correlationId, { resolve, timer })+ forward(correlationId)+ })+ },+ pendingCount() {+ return pending.size+ }+ }+}+// Electron accelerator vocabulary (electronjs.org/docs/latest/api/accelerator).// Kept as data so validation and the settings UI agree on one list.const ACCELERATOR_MODIFIERS = new Set([diff --git a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.tsindex 5fbfd102b15..cb0dade94d5 100644--- a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts+++ b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts@@ -5,6 +5,7 @@ import {QUICK_TARGET_CURRENT,QUICK_TARGET_NEW,type QuickEntrySessionOption,+ type QuickEntrySubmitResult,setQuickEntrySubmitHandler} from '@/store/quick-entry'import { $gatewayState, $sessions } from '@/store/session'@@ -12,8 +13,8 @@ import { sessionTileDelegate } from '@/store/session-states'import { isAuxiliaryWindow } from '@/store/windows'interface QuickEntryBridgeParams {- startFreshSessionDraft: () => voidsubmitText: (text: string) => Promise<unknown> | unknown+ submitTextToNewSession: (text: string) => Promise<{ runtimeSessionId: string; sessionId: string }>}// The picker is a capture aid, not a session browser — a handful of recent@@ -50,23 +51,33 @@ function sessionOptions(): QuickEntrySessionOption[] {* secondary session window must not also claim the global capture channel, or* one keystroke would send N prompts.*/-export function useQuickEntryBridge({ startFreshSessionDraft, submitText }: QuickEntryBridgeParams): void {+export function useQuickEntryBridge({+ submitText,+ submitTextToNewSession+}: QuickEntryBridgeParams): void {const submitTextRef = useRef(submitText)submitTextRef.current = submitText- const startFreshRef = useRef(startFreshSessionDraft)- startFreshRef.current = startFreshSessionDraft+ const submitNewRef = useRef(submitTextToNewSession)+ submitNewRef.current = submitTextToNewSessionuseEffect(() => {if (isAuxiliaryWindow()) {return}- setQuickEntrySubmitHandler(({ target, text }) => {+ setQuickEntrySubmitHandler(async ({ correlationId, target, text }) => {+ const ack = (result: QuickEntrySubmitResult) =>+ window.hermesDesktop?.quickEntry.ackSubmit(correlationId, result)+if (target === QUICK_TARGET_NEW) {- // Same as the user clicking New Chat and typing: fresh draft, then the- // normal submit creates the backend session.- startFreshRef.current()- void submitTextRef.current(text)+ // Create and submit as one route-neutral operation so drift cannot+ // orphan the new session (#85590).+ try {+ const created = await submitNewRef.current(text)+ ack({ ok: true, runtimeSessionId: created.runtimeSessionId, sessionId: created.sessionId })+ } catch (error) {+ ack({ code: 'submit-failed', message: error instanceof Error ? error.message : String(error), ok: false, retryable: true })+ }return}@@ -77,17 +88,32 @@ export function useQuickEntryBridge({ startFreshSessionDraft, submitText }: Quicconst delegate = sessionTileDelegate()if (delegate) {- void delegate- .resumeTile(target)- .then(runtimeId => delegate.submitToSession(runtimeId, text))- // A dead/undeliverable target must not swallow the prompt.- .catch(() => void submitTextRef.current(text))+ try {+ const runtimeId = await delegate.resumeTile(target)+ await delegate.submitToSession(runtimeId, text)+ ack({ ok: true })+ } catch (error) {+ ack({ code: 'submit-failed', message: error instanceof Error ? error.message : String(error), ok: false, retryable: true })+ }return}++ ack({+ code: 'submit-unavailable',+ message: 'The selected session submit path is unavailable.',+ ok: false,+ retryable: true+ })+ return}- void submitTextRef.current(text)+ try {+ await submitTextRef.current(text)+ ack({ ok: true })+ } catch (error) {+ ack({ code: 'submit-failed', message: error instanceof Error ? error.message : String(error), ok: false, retryable: true })+ }})const dispose = initQuickEntryBridge()diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex a0517fdb7aa..80faffc7744 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -569,6 +569,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {resumeSession,selectSidebarItem,startFreshSessionDraft,+ submitTextToNewSession,unarchiveSession} = useSessionActions({activeSessionId,@@ -807,7 +808,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {// The global-hotkey Quick Entry window's bridge: its captured text rides the// SAME submit machinery the normal composer uses (current chat / picked// session / new session), and it hears gateway truth from this window.- useQuickEntryBridge({ startFreshSessionDraft, submitText })+ useQuickEntryBridge({ submitText, submitTextToNewSession })// Leaving HUD mode hands this window the session back (see hud/handoff).useHudHandoff({ navigate, resumeSession })diff --git a/apps/desktop/src/app/quick-entry/quick-entry-app.tsx b/apps/desktop/src/app/quick-entry/quick-entry-app.tsxindex 69e8e581f22..d1ec7901d43 100644--- a/apps/desktop/src/app/quick-entry/quick-entry-app.tsx+++ b/apps/desktop/src/app/quick-entry/quick-entry-app.tsx@@ -36,6 +36,7 @@ const QUICK_TARGET_OPTION_STYLE = {*/export function QuickEntryApp() {const inputRef = useRef<HTMLInputElement>(null)+ const submitIdRef = useRef(0)// The reducer returns { send, state }; this wrapper performs the side effect// (hand the payload to the shell, ask to hide) and stores the next state, so@@ -45,7 +46,21 @@ export function QuickEntryApp() {const api = window.hermesDesktop?.quickEntryif (send) {- api?.submit(send)+ const submitId = submitIdRef.current+ void api?.submit(send).then(result => {+ dispatch(+ result.ok+ ? { submitId, type: 'submit-ok' }+ : {+ message: result.message || 'Quick Entry could not deliver the prompt.',+ submitId,+ type: 'submit-error'+ }+ )+ if (!result.ok) {+ requestAnimationFrame(() => inputRef.current?.focus())+ }+ })} else if (!next.visible && current.visible) {api?.dismiss()}@@ -138,7 +153,7 @@ export function QuickEntryApp() {onKeyDown={event => {if (isSubmitEnter(event) && !event.shiftKey) {event.preventDefault()- dispatch({ type: 'submit' })+ dispatch({ submitId: ++submitIdRef.current, type: 'submit' })} else if (event.key === 'Escape') {event.preventDefault()dispatch({ type: 'dismiss' })@@ -208,6 +223,11 @@ export function QuickEntryApp() {))}</select></div>+ {state.error ? (+ <div role="alert" style={{ color: 'var(--destructive, #ef4444)', fontSize: 11 }}>+ {state.error}+ </div>+ ) : null}</div></div>)diff --git a/apps/desktop/src/app/session/hooks/session-context-drift.test.ts b/apps/desktop/src/app/session/hooks/session-context-drift.test.tsindex cebbef7f8de..b76ee155485 100644--- a/apps/desktop/src/app/session/hooks/session-context-drift.test.ts+++ b/apps/desktop/src/app/session/hooks/session-context-drift.test.ts@@ -27,6 +27,33 @@ describe('routeTargetFromToken', () => {})describe('sessionContextDrift', () => {+ it('keeps a pinned atomic-submit session through drift, then restores normal drift behavior', () => {+ const pinned = new Set(['sess-b'])++ expect(+ sessionContextDrift({+ nowRouteToken: routeToken(sessionRoute(SESS_B)),+ nowSelectedStoredId: SESS_B,+ pinnedStoredSessionIds: pinned,+ startRouteToken: routeToken(sessionRoute(SESS_A)),+ startSelectedStoredId: SESS_A,+ submitTargetStoredId: null+ })+ ).toBeNull()++ pinned.delete(SESS_B)+ expect(+ sessionContextDrift({+ nowRouteToken: routeToken(sessionRoute(SESS_B)),+ nowSelectedStoredId: SESS_B,+ pinnedStoredSessionIds: pinned,+ startRouteToken: routeToken(sessionRoute(SESS_A)),+ startSelectedStoredId: SESS_A,+ submitTargetStoredId: null+ })+ ).toBe('route:sess-a->sess-b')+ })+it('does not drift on search/hash-only route churn', () => {const reason = sessionContextDrift({startRouteToken: routeToken(sessionRoute(SESS_A)),diff --git a/apps/desktop/src/app/session/hooks/session-context-drift.ts b/apps/desktop/src/app/session/hooks/session-context-drift.tsindex 7f264a581f9..b35725d1595 100644--- a/apps/desktop/src/app/session/hooks/session-context-drift.ts+++ b/apps/desktop/src/app/session/hooks/session-context-drift.ts@@ -56,8 +56,14 @@ interface SessionContextDriftArgs {* session that has ever compressed.*/submitTargetComposerScope?: string | null+ /** Stored ids being re-homed by an atomic submit (#85590). */+ pinnedStoredSessionIds?: ReadonlySet<string>}+// A short-lived pin marks the session being re-homed by atomic quick submit;+// keeping it here lets every drift caller share the same narrow exception (#85590).+export const activePinnedStoredSessionIds = new Set<string>()+/*** Decide whether the session context genuinely changed under an in-flight* submit — the user (or a real navigation) moved to a DIFFERENT chat — as@@ -77,8 +83,10 @@ export function sessionContextDrift({nowSelectedStoredId,submitTargetStoredId,composerScope,- submitTargetComposerScope+ submitTargetComposerScope,+ pinnedStoredSessionIds: pinnedIds}: SessionContextDriftArgs): string | null {+ const activePins = pinnedIds ?? activePinnedStoredSessionIds// Composer prong: the composer's loaded scope disagrees with the resolved// submit target. Not a start/now comparison like the two prongs below — the// composer only hands us one snapshot per submit — but it belongs in the@@ -97,7 +105,12 @@ export function sessionContextDrift({// (navigated to settings / a non-chat overlay route) or a search/hash-only// change (same target) is not drift, and neither is landing on the submit's// own target.- if (targetNow !== targetStart && targetNow !== null && targetNow !== submitTargetStoredId) {+ if (+ targetNow !== targetStart &&+ targetNow !== null &&+ targetNow !== submitTargetStoredId &&+ !(targetNow !== '__new__' && activePins.has(targetNow))+ ) {return `route:${targetStart}->${targetNow}`}@@ -107,7 +120,8 @@ export function sessionContextDrift({if (nowSelectedStoredId !== null &&nowSelectedStoredId !== startSelectedStoredId &&- nowSelectedStoredId !== submitTargetStoredId+ nowSelectedStoredId !== submitTargetStoredId &&+ !activePins.has(nowSelectedStoredId)) {return `selection:${startSelectedStoredId}->${nowSelectedStoredId}`}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 46d7136b6bd..38de0c4f3d2 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@@ -108,6 +108,7 @@ import { deferred } from '../../../test/deferred'import { NEW_CHAT_ROUTE, sessionRoute } from '../../routes'import type { ClientSessionState } from '../../types'+import { activePinnedStoredSessionIds } from './session-context-drift'import { applySessionInfoStatePatch, sessionInfoStatePatch } from './use-message-stream/utils'import { captureSteeringSession } from './use-prompt-actions/steering-session'import { useSessionActions } from './use-session-actions'@@ -162,7 +163,7 @@ type HarnessHandle = Pick<| 'removeSession'| 'selectSidebarItem'| 'startFreshSessionDraft'->+> & Pick<ReturnType<typeof useSessionActions>, 'submitTextToNewSession'>function storedSession(overrides: Partial<SessionInfo> = {}): SessionInfo {return {@@ -186,6 +187,7 @@ function storedSession(overrides: Partial<SessionInfo> = {}): SessionInfo {function Harness({activeSessionId = null,activeSessionIdRef: activeSessionIdRefOverride,+ getRoutedStoredSessionId = () => null,navigate = vi.fn(),onReady,requestGateway,@@ -196,6 +198,7 @@ function Harness({}: {activeSessionId?: null | stringactiveSessionIdRef?: MutableRefObject<null | string>+ getRoutedStoredSessionId?: () => null | stringnavigate?: ReturnType<typeof vi.fn>onReady: (handle: HarnessHandle) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>@@ -217,7 +220,7 @@ function Harness({creatingSessionRef: ref(false),ensureSessionState: () => ({}) as ClientSessionState,getRouteToken: () => 'token',- getRoutedStoredSessionId: () => null,+ getRoutedStoredSessionId,navigate: navigate as never,requestGateway,resetViewSync: vi.fn(),@@ -1055,6 +1058,54 @@ describe('startFreshSessionDraft', () => {})})+describe('submitTextToNewSession pin release', () => {+ afterEach(() => {+ activePinnedStoredSessionIds.clear()+ cleanup()+ vi.restoreAllMocks()+ })++ it('force-releases the pin when competing navigation prevents route settlement', async () => {+ const stored = 'stored-quick-entry'+ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'session.create') {+ return { session_id: RUNTIME_SESSION_ID, stored_session_id: stored } as never+ }++ return {} as never+ })+ let handle: HarnessHandle | null = null++ render(+ <Harness+ getRoutedStoredSessionId={() => 'stored-other'}+ onReady={value => (handle = value)}+ requestGateway={requestGateway}+ />+ )+ await waitFor(() => expect(handle).not.toBeNull())++ await act(async () => {+ await handle!.submitTextToNewSession('quick entry')+ })++ await new Promise<void>(resolve => {+ let ticks = 30+ const tick = () => {+ ticks -= 1+ if (ticks === 0) {+ resolve()+ } else {+ window.setTimeout(tick, 0)+ }+ }+ window.setTimeout(tick, 0)+ })+ expect(activePinnedStoredSessionIds.has(stored)).toBe(true)+ await waitFor(() => expect(activePinnedStoredSessionIds.has(stored)).toBe(false), { timeout: 3000 })+ })+})+describe('createBackendSessionForSend profile routing', () => {afterEach(() => {cleanup()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 51b851783fe..0e78289b6a8 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@@ -155,7 +155,7 @@ import type {import { navigateToWorkspacePage, NEW_CHAT_ROUTE, sessionRoute, SETTINGS_ROUTE } from '../../../routes'import type { ClientSessionState, SidebarNavItem } from '../../../types'-import { sessionContextDrift } from '../session-context-drift'+import { activePinnedStoredSessionIds, sessionContextDrift } from '../session-context-drift'import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'@@ -970,6 +970,48 @@ export function useSessionActions({])+ const submitTextToNewSession = useCallback(+ async (text: string): Promise<{ runtimeSessionId: string; sessionId: string }> => {+ const params = await desktopSessionCreateParams(resolveNewSessionCwd())+ const created = await requestGateway<SessionCreateResponse>('session.create', params)+ const stored = created.stored_session_id+ if (!stored) {+ throw new Error('The new session did not return a stored id.')+ }+ activePinnedStoredSessionIds.add(stored)+ try {+ markSessionCreatedThisRun(stored)+ runtimeIdByStoredSessionIdRef.current.set(stored, created.session_id)+ ensureSessionState(created.session_id, stored)+ upsertOptimisticSession(created, stored, null, text.trim())+ // Submit the exact runtime id returned by session.create so this+ // atomic path cannot fall back to a route token (#85590).+ await requestGateway('prompt.submit', { session_id: created.session_id, text })+ navigate(sessionRoute(stored), { replace: true })+ // WHY: An unbounded re-arm becomes a hot loop and leaks the pin when+ // competing navigation wins before this session reaches the route.+ // Issue #85590: bound the router settle window to avoid that failure.+ let releaseAttempts = 60+ const releasePin = () => {+ if (getRoutedStoredSessionId() === stored || releaseAttempts === 0) {+ activePinnedStoredSessionIds.delete(stored)+ } else {+ // WHY: 60 ticks is far beyond any real router settle window, so+ // force-release after it rather than spin forever (issue #85590).+ releaseAttempts -= 1+ window.setTimeout(releasePin, 0)+ }+ }+ releasePin()+ return { runtimeSessionId: created.session_id, sessionId: stored }+ } catch (error) {+ activePinnedStoredSessionIds.delete(stored)+ throw error+ }+ },+ [ensureSessionState, getRoutedStoredSessionId, navigate, requestGateway, runtimeIdByStoredSessionIdRef]+ )+const selectSidebarItem = useCallback((item: SidebarNavItem) => {if (item.action === 'new-session') {@@ -3311,6 +3353,7 @@ export function useSessionActions({resumeSession,selectSidebarItem,startFreshSessionDraft,+ submitTextToNewSession,unarchiveSession}}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex ac37020b6a5..ee0bc3ae14a 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -17,7 +17,12 @@ import type {PetOverlayOpenRequest,PetOverlayStatePayload} from './store/pet-overlay'-import type { QuickEntryStatePush, QuickEntryStatus, QuickEntrySubmitPayload } from './store/quick-entry'+import type {+ QuickEntryStatePush,+ QuickEntryStatus,+ QuickEntrySubmitPayload,+ QuickEntrySubmitResult+} from './store/quick-entry'export {}@@ -184,7 +189,8 @@ declare global {// Quick window → main: send this payload (main forwards it to the// primary renderer, which routes it to the target session and submits// through the normal prompt path) and hide.- submit: (payload: QuickEntrySubmitPayload) => void+ submit: (payload: QuickEntrySubmitPayload) => Promise<QuickEntrySubmitResult>+ ackSubmit: (correlationId: string, result: QuickEntrySubmitResult) => void// Quick window → main: hide without sending (Escape / blur).dismiss: () => void// Primary renderer → main → quick window: gateway connection state +@@ -194,7 +200,9 @@ declare global {// Quick window subscribes to those pushes.onState: (callback: (payload: QuickEntryStatePush) => void) => () => void// Primary renderer subscribes to submits captured by the quick window.- onSubmit: (callback: (payload: QuickEntrySubmitPayload | string) => void) => () => void+ onSubmit: (+ callback: (payload: (QuickEntrySubmitPayload & { correlationId: string }) | string) => void+ ) => () => void// Quick window subscribes to "you were just summoned" so it can reset// its draft and re-focus the input on every open.onShown: (callback: () => void) => () => voiddiff --git a/apps/desktop/src/store/quick-entry.test.ts b/apps/desktop/src/store/quick-entry.test.tsindex 5ff1be5bd42..15b36231681 100644--- a/apps/desktop/src/store/quick-entry.test.ts+++ b/apps/desktop/src/store/quick-entry.test.ts@@ -39,13 +39,73 @@ const connect: QuickComposerEvent = {}describe('quickComposerReducer', () => {- it('submit sends the trimmed draft with the target, clears it, and hides', () => {- const { sent, state } = run([connect, { draft: ' ship it ', type: 'edit' }, { type: 'submit' }])+ it('starts visible, empty, DISCONNECTED, and targeting the current chat', () => {+ expect(initialQuickComposerState).toEqual({+ connected: false,+ draft: '',+ error: null,+ pendingSubmitId: null,+ sessions: [],+ submitting: false,+ target: QUICK_TARGET_CURRENT,+ visible: true+ })+ })++ it('submit sends the trimmed draft but waits for acknowledgement to clear and hide', () => {+ const { sent, state } = run([+ connect,+ { draft: ' ship it ', type: 'edit' },+ { submitId: 1, type: 'submit' }+ ])expect(sent).toEqual([{ target: QUICK_TARGET_CURRENT, text: 'ship it' }])- expect(state.draft).toBe('')+ expect(state.draft).toBe(' ship it ')expect(state.submitting).toBe(true)- expect(state.visible).toBe(false)+ expect(state.visible).toBe(true)++ const acknowledged = quickComposerReducer(state, { submitId: 1, type: 'submit-ok' }).state+ expect(acknowledged.draft).toBe('')+ expect(acknowledged.visible).toBe(false)+ })++ it('submit-error keeps the draft visible, records the error, and refocuses on retry', () => {+ const { state } = run([connect, { draft: ' keep me ', type: 'edit' }, { submitId: 7, type: 'submit' }])+ const failed = quickComposerReducer(state, {+ message: 'Delivery failed',+ submitId: 7,+ type: 'submit-error'+ }).state++ expect(failed).toMatchObject({+ draft: ' keep me ',+ error: 'Delivery failed',+ pendingSubmitId: null,+ submitting: false,+ visible: true+ })+ })++ it('ignores submit acknowledgements with stale ids', () => {+ const { state } = run([connect, { draft: 'keep', type: 'edit' }, { submitId: 7, type: 'submit' }])++ expect(quickComposerReducer(state, { submitId: 8, type: 'submit-ok' }).state).toEqual(state)+ expect(+ quickComposerReducer(state, { message: 'stale', submitId: 8, type: 'submit-error' }).state+ ).toEqual(state)+ })++ it('keeps resume and current-target submits on their existing routes', () => {+ const resumed = run([+ connect,+ { target: 's2', type: 'target' },+ { draft: 'resume here', type: 'edit' },+ { submitId: 1, type: 'submit' }+ ])+ const current = run([connect, { draft: 'current here', type: 'edit' }, { submitId: 2, type: 'submit' }])++ expect(resumed.sent).toEqual([{ target: 's2', text: 'resume here' }])+ expect(current.sent).toEqual([{ target: QUICK_TARGET_CURRENT, text: 'current here' }])})it('an empty or whitespace-only submit sends nothing and stays open', () => {diff --git a/apps/desktop/src/store/quick-entry.ts b/apps/desktop/src/store/quick-entry.tsindex 54916083240..65b49850941 100644--- a/apps/desktop/src/store/quick-entry.ts+++ b/apps/desktop/src/store/quick-entry.ts@@ -128,6 +128,15 @@ export interface QuickEntrySubmitPayload {text: string}+export interface QuickEntrySubmitResult {+ ok: boolean+ code?: string+ message?: string+ retryable?: boolean+ sessionId?: string | null+ runtimeSessionId?: string | null+}+/*** The quick window's own composer state. Deliberately a tiny pure reducer: the* behavior that would actually break a user — an empty submit must not send but@@ -142,8 +151,12 @@ export interface QuickComposerState {draft: string/** Recent sessions the picker offers, pushed by the primary renderer. */sessions: QuickEntrySessionOption[]- /** True between a send and the window actually hiding. Blocks a double-send. */+ /** True between a send and its acknowledgement. Blocks a double-send. */submitting: boolean+ /** Inline delivery failure retained with the draft until retry. */+ error: null | string+ /** Local correlation for ignoring an acknowledgement from an older submit. */+ pendingSubmitId: number | null/** Where a submit lands: current / new / a stored session id. */target: string/** Whether the window should be visible. False asks the shell to hide. */@@ -156,7 +169,9 @@ export type QuickComposerEvent =| { type: 'edit'; draft: string }| { type: 'shown' }| { type: 'state'; connected: boolean; sessions: QuickEntrySessionOption[] }- | { type: 'submit' }+ | { type: 'submit'; submitId?: number }+ | { type: 'submit-error'; message: string; submitId: number }+ | { type: 'submit-ok'; submitId: number }| { type: 'target'; target: string }export interface QuickComposerTransition {@@ -170,6 +185,8 @@ export const initialQuickComposerState: QuickComposerState = {// capture window that accepts text it can never deliver is a lie.connected: false,draft: '',+ error: null,+ pendingSubmitId: null,sessions: [],submitting: false,target: QUICK_TARGET_CURRENT,@@ -184,7 +201,15 @@ export function quickComposerReducer(state: QuickComposerState, event: QuickComp// hides — the send already left for the main process.return {send: null,- state: { ...state, draft: '', submitting: false, target: QUICK_TARGET_CURRENT, visible: false }+ state: {+ ...state,+ draft: '',+ error: null,+ pendingSubmitId: null,+ submitting: false,+ target: QUICK_TARGET_CURRENT,+ visible: false+ }}}@@ -197,7 +222,15 @@ export function quickComposerReducer(state: QuickComposerState, event: QuickComp// a leftover target — but the pushed gateway truth carries over.return {send: null,- state: { ...state, draft: '', submitting: false, target: QUICK_TARGET_CURRENT, visible: true }+ state: {+ ...state,+ draft: '',+ error: null,+ pendingSubmitId: null,+ submitting: false,+ target: QUICK_TARGET_CURRENT,+ visible: true+ }}}@@ -232,10 +265,23 @@ export function quickComposerReducer(state: QuickComposerState, event: QuickCompreturn {send: { target: state.target, text },- state: { ...state, draft: '', submitting: true, visible: false }+ // Wait for main's result before clearing or hiding the capture window (#85590).+ state: { ...state, error: null, pendingSubmitId: event.submitId ?? null, submitting: true }}}+ case 'submit-ok': {+ return event.submitId > 0 && state.pendingSubmitId === event.submitId+ ? { send: null, state: { ...state, draft: '', error: null, pendingSubmitId: null, submitting: false, visible: false } }+ : { send: null, state }+ }++ case 'submit-error': {+ return event.submitId > 0 && state.pendingSubmitId === event.submitId+ ? { send: null, state: { ...state, error: event.message, pendingSubmitId: null, submitting: false, visible: true } }+ : { send: null, state }+ }+case 'target': {return { send: null, state: { ...state, target: event.target } }}@@ -248,7 +294,7 @@ export function quickComposerReducer(state: QuickComposerState, event: QuickComp// ── Primary-renderer bridge ────────────────────────────────────────────────-let submitHandler: ((payload: QuickEntrySubmitPayload) => void) | null = null+let submitHandler: ((payload: QuickEntrySubmitPayload & { correlationId: string }) => void) | null = nulllet unsubscribeSubmit: (() => void) | null = null/**@@ -256,7 +302,9 @@ let unsubscribeSubmit: (() => void) | null = null* primary window routes it by target: current chat → `submitText`, a stored* session id → resume + submit, new → fresh draft + submit.*/-export function setQuickEntrySubmitHandler(fn: ((payload: QuickEntrySubmitPayload) => void) | null): void {+export function setQuickEntrySubmitHandler(+ fn: ((payload: QuickEntrySubmitPayload & { correlationId: string }) => void) | null+): void {submitHandler = fn}@@ -298,8 +346,11 @@ export function initQuickEntryBridge(): () => void {unsubscribeSubmit = api.onSubmit(raw => {const payload = normalizeSubmitPayload(raw)- if (payload) {- submitHandler?.(payload)+ if (payload && typeof raw === 'object' && raw !== null) {+ const correlationId = (raw as unknown as Record<string, unknown>).correlationId+ if (typeof correlationId === 'string') {+ submitHandler?.({ ...payload, correlationId })+ }}})