Skip to content

The agent that grows with you

fix(desktop): single-flight session.resume per stored id + adopt-or-reuse on drift-abort

Teknium77dd06994658
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index 4eaf3d14d90..ed49e99061d 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -8,6 +8,7 @@ import { publishSessionState, sessionTileOwnerRoute, setSessionTileDelegate } fr
import type { SessionResumeResponse } from '@/types/hermes'
import type { usePromptActions } from '../../session/hooks/use-prompt-actions'
+import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume'
import { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils'
import { resolveSessionProfile } from '../../session/hooks/use-session-actions/utils'
import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache'
@@ -176,12 +177,14 @@ export function useSessionTileDelegate({
const [prefetch, resumed] = await Promise.all([
getLatestSessionMessages(storedSessionId, restScope).catch(() => null),
- requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {
- session_id: storedSessionId,
- cols: 96,
- omit_messages: true,
- ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})
- })
+ singleFlightSessionResume(storedSessionId, () =>
+ requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {
+ session_id: storedSessionId,
+ cols: 96,
+ omit_messages: true,
+ ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})
+ })
+ )
])
const runtimeId = resumed?.session_id
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 1c4657467f3..3445a386152 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
@@ -29,10 +29,18 @@ import { dropSessionState, publishSessionState } from '@/store/session-states'
import { $wakeWord, resetWakeWordState } from '@/store/wake-word'
import type { SessionInfo } from '@/types/hermes'
+import { clearSingleFlightSessionResumeState } from './single-flight-resume'
import type { SubmitTextOptions } from './utils'
import { uploadComposerAttachment, usePromptActions } from '.'
+// Suites in this file reuse the same stored-id constants. The module-level
+// single-flight resume map (and drift-recovery cache) would otherwise leak a
+// never-settling in-flight promise from one test into the next.
+beforeEach(() => {
+ clearSingleFlightSessionResumeState()
+})
+
vi.mock('@/hermes', () => ({
getProfiles: vi.fn(async () => ({ profiles: [] })),
getSession: vi.fn(),
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/resolve-target-session.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/resolve-target-session.ts
index 93dc4f4484f..ce4ff405c21 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/resolve-target-session.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/resolve-target-session.ts
@@ -1,5 +1,6 @@
import { resolveSessionProfile } from '../use-session-actions/utils'
+import { singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
import type { GatewayRequest } from './utils'
/**
@@ -89,12 +90,22 @@ export async function resolveTargetSessionId(deps: ResolveTargetSessionDeps): Pr
if (storedTarget) {
try {
- const profile = await resolveSessionProfile(storedTarget)
+ // Reuse a runtime an aborted recovery already minted for this stored
+ // session; otherwise resume once, shared across concurrent callers.
+ const cachedRuntimeId = takeRecoveredRuntime(storedTarget)
- const resumed = await requestGateway<{ session_id?: string }>('session.resume', {
- session_id: storedTarget,
- source: 'desktop',
- ...(profile ? { profile } : {})
+ if (cachedRuntimeId) {
+ return cachedRuntimeId
+ }
+
+ const resumed = await singleFlightSessionResume(storedTarget, async () => {
+ const profile = await resolveSessionProfile(storedTarget)
+
+ return requestGateway<{ session_id?: string }>('session.resume', {
+ session_id: storedTarget,
+ source: 'desktop',
+ ...(profile ? { profile } : {})
+ })
})
return resumed?.session_id || null
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts
new file mode 100644
index 00000000000..8e3986add1f
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ clearSingleFlightSessionResumeState,
+ registerRecoveredRuntime,
+ singleFlightSessionResume,
+ takeRecoveredRuntime
+} from './single-flight-resume'
+import { resumeStoredRuntimeSession, SessionRecoveryAborted, withSessionNotFoundResume } from './utils'
+
+afterEach(() => {
+ clearSingleFlightSessionResumeState()
+ vi.restoreAllMocks()
+})
+
+describe('singleFlightSessionResume', () => {
+ it('two concurrent resume callers for the same stored id produce ONE session.resume RPC', async () => {
+ const requestGateway = vi.fn(async (method: string) => {
+ expect(method).toBe('session.resume')
+ // Yield so both callers are in flight before either resolves.
+ await new Promise(resolve => setTimeout(resolve, 10))
+
+ return { session_id: 'rt-fresh' }
+ })
+
+ const deps = { requestGateway: requestGateway as never, resolveProfile: async () => undefined }
+
+ const [a, b] = await Promise.all([
+ resumeStoredRuntimeSession('stored-a', deps),
+ resumeStoredRuntimeSession('stored-a', deps)
+ ])
+
+ expect(a).toBe('rt-fresh')
+ expect(b).toBe('rt-fresh')
+ expect(requestGateway).toHaveBeenCalledTimes(1)
+ })
+
+ it('different stored ids still resume independently', async () => {
+ const requestGateway = vi.fn(async (_method: string, params?: Record<string, unknown>) => {
+ await new Promise(resolve => setTimeout(resolve, 5))
+
+ return { session_id: `rt-${String(params?.session_id)}` }
+ })
+
+ const deps = { requestGateway: requestGateway as never, resolveProfile: async () => undefined }
+
+ const [a, b] = await Promise.all([
+ resumeStoredRuntimeSession('stored-a', deps),
+ resumeStoredRuntimeSession('stored-b', deps)
+ ])
+
+ expect(a).toBe('rt-stored-a')
+ expect(b).toBe('rt-stored-b')
+ expect(requestGateway).toHaveBeenCalledTimes(2)
+ })
+
+ it('a rejected flight is not cached: the next caller retries', async () => {
+ const run = vi
+ .fn<() => Promise<{ session_id: string }>>()
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValueOnce({ session_id: 'rt-second' })
+
+ await expect(singleFlightSessionResume('stored-a', run)).rejects.toThrow('boom')
+ await expect(singleFlightSessionResume('stored-a', run)).resolves.toEqual({ session_id: 'rt-second' })
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+})
+
+describe('drift-abort recovered-runtime cache', () => {
+ it('drift-abort does not strand the recovered runtime — it is registered in the cache', async () => {
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.resume') {
+ return { session_id: 'rt-recovered' }
+ }
+
+ throw new Error('unexpected call')
+ })
+
+ const call = vi.fn(async (liveId: string) => {
+ if (liveId === 'rt-dead') {
+ throw new Error('session not found: rt-dead')
+ }
+
+ return 'ok'
+ })
+
+ await expect(
+ withSessionNotFoundResume('rt-dead', 'stored-a', call, {
+ requestGateway: requestGateway as never,
+ resolveProfile: async () => undefined,
+ driftReason: () => 'user switched away'
+ })
+ ).rejects.toThrow(SessionRecoveryAborted)
+
+ // The freshly-minted runtime is NOT abandoned: the next action reuses it.
+ expect(takeRecoveredRuntime('stored-a')).toBe('rt-recovered')
+ // Take-semantics: consumed exactly once.
+ expect(takeRecoveredRuntime('stored-a')).toBeUndefined()
+ })
+
+ it('a later non-drifted recovery adopts the cached runtime instead of resuming again', async () => {
+ registerRecoveredRuntime('stored-a', 'rt-cached')
+
+ const requestGateway = vi.fn(async () => {
+ throw new Error('session.resume must not be called when a cached runtime exists')
+ })
+
+ const onRecovered = vi.fn()
+
+ const call = vi.fn(async (liveId: string) => {
+ if (liveId === 'rt-dead') {
+ throw new Error('session not found: rt-dead')
+ }
+
+ return `ran-on-${liveId}`
+ })
+
+ const outcome = await withSessionNotFoundResume('rt-dead', 'stored-a', call, {
+ requestGateway: requestGateway as never,
+ resolveProfile: async () => undefined,
+ onRecovered
+ })
+
+ expect(outcome).toEqual({ recovered: true, result: 'ran-on-rt-cached', sessionId: 'rt-cached' })
+ expect(onRecovered).toHaveBeenCalledWith('rt-cached')
+ expect(requestGateway).not.toHaveBeenCalled()
+ })
+
+ it('takeRecoveredRuntime skips a cached id the caller already knows is dead', () => {
+ registerRecoveredRuntime('stored-a', 'rt-dead')
+
+ expect(takeRecoveredRuntime('stored-a', 'rt-dead')).toBeUndefined()
+ expect(takeRecoveredRuntime('stored-a')).toBeUndefined()
+ })
+})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts
new file mode 100644
index 00000000000..a2ce9f3a36a
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts
@@ -0,0 +1,77 @@
+/**
+ * Single-flight guard for `session.resume`, keyed by STORED session id.
+ *
+ * After sleep/wake or a reconnect, many independent surfaces discover the same
+ * dead runtime at once — submit recovery, slash/rewind recovery, tile resumes,
+ * the route resolver — and each used to fire its own `session.resume` for the
+ * same durable conversation. The gateway happily mints a runtime per call and
+ * the losers become orphans for the reaper (#91276 storm).
+ *
+ * Module-level so EVERY call site in the window shares one in-flight promise
+ * per stored id, no matter which hook instance it lives in. All participating
+ * callers resolve to a `session.resume`-shaped response (an object carrying
+ * `session_id`); joiners receive whatever the winning call returns.
+ */
+
+const _inFlightResumeByStoredSessionId = new Map<string, Promise<unknown>>()
+
+export function singleFlightSessionResume<T>(storedSessionId: string, run: () => Promise<T>): Promise<T> {
+ const existing = _inFlightResumeByStoredSessionId.get(storedSessionId)
+
+ if (existing) {
+ return existing as Promise<T>
+ }
+
+ const flight = run().finally(() => {
+ if (_inFlightResumeByStoredSessionId.get(storedSessionId) === flight) {
+ _inFlightResumeByStoredSessionId.delete(storedSessionId)
+ }
+ })
+
+ _inFlightResumeByStoredSessionId.set(storedSessionId, flight)
+
+ return flight
+}
+
+/**
+ * Adopt-or-reuse cache for recovered runtimes a drift-abort walked away from.
+ *
+ * A recovery resume can succeed while the caller's drift check says the user
+ * moved on (SessionRecoveryAborted). The freshly-minted runtime is REAL and
+ * registered on the gateway; abandoning the id client-side strands it for the
+ * orphan reaper AND makes the next action for the same stored session mint yet
+ * another runtime. When adoption (rebinding the caller's runtime ref via
+ * onRecovered/onRuntimeRecovered) is wrong — the user is elsewhere — record it
+ * here so the next resume-shaped action reuses it instead of re-minting.
+ */
+const _recoveredRuntimeByStoredSessionId = new Map<string, string>()
+
+export function registerRecoveredRuntime(storedSessionId: string, runtimeId: string): void {
+ if (storedSessionId && runtimeId) {
+ _recoveredRuntimeByStoredSessionId.set(storedSessionId, runtimeId)
+ }
+}
+
+/**
+ * Consume a previously-abandoned recovered runtime for this stored session.
+ * Take-semantics: the entry is removed so a dead cached id can only cost one
+ * bounded retry, never a loop. `deadRuntimeId` skips (and drops) the entry
+ * when the caller already knows that exact runtime is dead.
+ */
+export function takeRecoveredRuntime(storedSessionId: string, deadRuntimeId?: null | string): string | undefined {
+ const cached = _recoveredRuntimeByStoredSessionId.get(storedSessionId)
+
+ if (cached === undefined) {
+ return undefined
+ }
+
+ _recoveredRuntimeByStoredSessionId.delete(storedSessionId)
+
+ return deadRuntimeId && cached === deadRuntimeId ? undefined : cached
+}
+
+/** Test seam: reset all module-level single-flight/recovery state. */
+export function clearSingleFlightSessionResumeState(): void {
+ _inFlightResumeByStoredSessionId.clear()
+ _recoveredRuntimeByStoredSessionId.clear()
+}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index 033c7918b2a..2325d9d98c3 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@ -37,6 +37,7 @@ import { sessionContextDrift } from '../session-context-drift'
import { resolveSessionProfile } from '../use-session-actions/utils'
import { finalizeInterruptedMessages } from './rewind'
+import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
import {
acquireSubmitInFlight,
type GatewayRequest,
@@ -543,6 +544,15 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
if (routedResumeDrift) {
console.warn('[submit-drift-abort]', routedResumeDrift, { phase: 'post-routed-resume' })
+ // The high-level resume may have already published a fresh runtime
+ // for this durable session. Don't strand it: record it so the next
+ // action targeting this stored session reuses it (#91276).
+ const publishedRuntimeId = getRuntimeIdForStoredSession(routedStoredSessionId)
+
+ if (publishedRuntimeId) {
+ registerRecoveredRuntime(routedStoredSessionId, publishedRuntimeId)
+ }
+
return abortForSessionSwitch(null)
}
@@ -573,20 +583,34 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {
try {
// Re-register on the session's OWNING profile — resuming on whichever
// profile is live would fork the conversation into the wrong DB (#67603).
- const resumeProfile = await resolveSessionProfile(targetStoredSessionId)
-
- const resumed = await requestGateway<{ session_id: string }>('session.resume', {
- session_id: targetStoredSessionId,
- source: 'desktop',
- omit_messages: true,
- ...(resumeProfile ? { profile: resumeProfile } : {})
- })
+ // A runtime a previous drift-aborted recovery already minted for this
+ // exact stored session is reused instead of resuming again.
+ const cachedRuntimeId = takeRecoveredRuntime(targetStoredSessionId)
+
+ const resumed = cachedRuntimeId
+ ? { session_id: cachedRuntimeId }
+ : await singleFlightSessionResume(targetStoredSessionId, async () => {
+ const resumeProfile = await resolveSessionProfile(targetStoredSessionId)
+
+ return requestGateway<{ session_id: string }>('session.resume', {
+ session_id: targetStoredSessionId,
+ source: 'desktop',
+ omit_messages: true,
+ ...(resumeProfile ? { profile: resumeProfile } : {})
+ })
+ })
const resumeDrift = sessionDriftReason()
if (resumeDrift) {
console.warn('[submit-drift-abort]', resumeDrift, { phase: 'post-resume' })
+ // Keep the freshly-bound runtime findable for the next action on
+ // this stored session instead of stranding it for the reaper.
+ if (resumed?.session_id) {
+ registerRecoveredRuntime(targetStoredSessionId, resumed.session_id)
+ }
+
return abortForSessionSwitch(sessionId)
}
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
index 35b783a11d0..c5bfb83da70 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
@@ -6,6 +6,8 @@ import { type CommandsCatalogLike, filterDesktopCommandsCatalog } from '@/lib/de
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import type { ComposerAttachment } from '@/store/composer'
+import { registerRecoveredRuntime, singleFlightSessionResume, takeRecoveredRuntime } from './single-flight-resume'
+
export type GatewayRequest = <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) => Promise<T>
export function delay(ms: number): Promise<void> {
@@ -113,14 +115,20 @@ export async function resumeStoredRuntimeSession(
storedSessionId: string,
deps: SessionRecoveryDeps
): Promise<null | string> {
- const resolveProfile = deps.resolveProfile ?? defaultResolveProfile
- const profile = await resolveProfile(storedSessionId)
-
- const resumed = await deps.requestGateway<{ session_id: string }>('session.resume', {
- session_id: storedSessionId,
- source: 'desktop',
- omit_messages: true,
- ...(profile ? { profile } : {})
+ // Single-flight per stored id: after a reconnect many surfaces discover the
+ // same dead runtime at once, and each independent session.resume mints a new
+ // runtime — every loser is an orphan for the reaper. Sharing one in-flight
+ // promise makes concurrent recoveries converge on ONE runtime.
+ const resumed = await singleFlightSessionResume(storedSessionId, async () => {
+ const resolveProfile = deps.resolveProfile ?? defaultResolveProfile
+ const profile = await resolveProfile(storedSessionId)
+
+ return deps.requestGateway<{ session_id: string }>('session.resume', {
+ session_id: storedSessionId,
+ source: 'desktop',
+ omit_messages: true,
+ ...(profile ? { profile } : {})
+ })
})
return resumed?.session_id ?? null
@@ -163,6 +171,33 @@ export async function withSessionNotFoundResume<T>(
throw err
}
+ // A previous recovery for this stored session already minted a runtime
+ // that its caller drift-aborted away from. Reuse it before resuming
+ // again — re-minting would strand yet another runtime for the reaper.
+ const cachedRecoveredId = takeRecoveredRuntime(storedSessionId, sessionId)
+
+ if (cachedRecoveredId) {
+ const cachedDrift = deps.driftReason?.()
+
+ if (cachedDrift) {
+ // Still drifted: keep the runtime findable for whoever acts next.
+ registerRecoveredRuntime(storedSessionId, cachedRecoveredId)
+ throw new SessionRecoveryAborted(cachedDrift, cachedRecoveredId)
+ }
+
+ try {
+ deps.onRecovered?.(cachedRecoveredId)
+
+ return { recovered: true, result: await call(cachedRecoveredId), sessionId: cachedRecoveredId }
+ } catch (cachedErr) {
+ // The cached runtime died in the meantime; fall through to a fresh
+ // resume only for the same stale-session class, otherwise surface it.
+ if (!isSessionNotFoundError(cachedErr)) {
+ throw cachedErr
+ }
+ }
+ }
+
let recoveredId: null | string
try {
@@ -178,6 +213,11 @@ export async function withSessionNotFoundResume<T>(
const drift = deps.driftReason?.()
if (drift) {
+ // Do NOT abandon the freshly-minted runtime: adoption is wrong here
+ // (the user moved on), so record it in the stored->runtime recovery
+ // cache. The next action targeting this stored session reuses it
+ // instead of minting another orphan (#91276).
+ registerRecoveredRuntime(storedSessionId, recoveredId)
throw new SessionRecoveryAborted(drift, recoveredId)
}
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.ts
index 810f6beebff..540058dc537 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
@@ -99,6 +99,7 @@ import type { SessionCreateResponse, SessionMessage, SessionResumeResponse, Usag
import { navigateToWorkspacePage, NEW_CHAT_ROUTE, sessionRoute, SETTINGS_ROUTE } from '../../../routes'
import type { ClientSessionState, SidebarNavItem } from '../../../types'
import { sessionContextDrift } from '../session-context-drift'
+import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
import {
appendLiveSessionProjection,
@@ -1196,21 +1197,23 @@ export function useSessionActions({
let resumeRuntimeBaselineMessages: ChatMessage[] = []
- const resumePromise = requestForSession<SessionResumeResponse>('session.resume', {
- session_id: storedSessionId,
- cols: 96,
- source: 'desktop',
- defer_history: !watchWindow,
- // REST is the transcript authority for Desktop. Avoid duplicating a
- // potentially huge compression lineage in the WebSocket response.
- // Watch windows attach lazily (live mirror). Every other cold resume
- // gets the gateway's default deferred build: the RPC returns the
- // transcript immediately instead of blocking the switch on _make_agent
- // (MCP discovery / prompt build), and the agent pre-warms in the
- // background while the prefetch above paints the transcript.
- ...(watchWindow ? { lazy: true } : { omit_messages: true }),
- ...(sessionProfile ? { profile: sessionProfile } : {})
- }).then(resumed => {
+ const resumePromise = singleFlightSessionResume(storedSessionId, () =>
+ requestForSession<SessionResumeResponse>('session.resume', {
+ session_id: storedSessionId,
+ cols: 96,
+ source: 'desktop',
+ defer_history: !watchWindow,
+ // REST is the transcript authority for Desktop. Avoid duplicating a
+ // potentially huge compression lineage in the WebSocket response.
+ // Watch windows attach lazily (live mirror). Every other cold resume
+ // gets the gateway's default deferred build: the RPC returns the
+ // transcript immediately instead of blocking the switch on _make_agent
+ // (MCP discovery / prompt build), and the agent pre-warms in the
+ // background while the prefetch above paints the transcript.
+ ...(watchWindow ? { lazy: true } : { omit_messages: true }),
+ ...(sessionProfile ? { profile: sessionProfile } : {})
+ })
+ ).then(resumed => {
resumeRuntimeBaselineMessages =
sessionStateByRuntimeIdRef.current.get(resumed.session_id)?.messages ?? resumeRuntimeBaselineMessages