Skip to content

The agent that grows with you

refactor(desktop): extract session-actions resume/owner helpers for code health

Tekniumee8498a4416e
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index cd0fd53f0f4..07d2d527562 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -81,6 +81,19 @@ export function profileScopeForTranscriptSession(stored: ActiveTranscriptSession
return stored.profile
}
+/** Dedupe key for one active transcript's last published page signature. */
+function transcriptSignatureKey(stored: ActiveTranscriptSession, storedSessionId: string): string {
+ return stored.ownerRoute
+ ? JSON.stringify([
+ stored.ownerRoute.connectionId,
+ stored.ownerRoute.profile,
+ stored.ownerRoute.targetProfile ?? '',
+ stored.ownerRoute.mode ?? '',
+ storedSessionId
+ ])
+ : `${stored.profile ?? 'default'}:${storedSessionId}`
+}
+
/** Only a runtime-matched explicit tile owner overrides visible rows; unique hints are the last fallback. */
export function resolveActiveTranscriptSession(
storedSessionId: string,
@@ -604,15 +617,7 @@ export async function reconcileActiveTranscript({
return
}
- const signatureKey = stored.ownerRoute
- ? JSON.stringify([
- stored.ownerRoute.connectionId,
- stored.ownerRoute.profile,
- stored.ownerRoute.targetProfile ?? '',
- stored.ownerRoute.mode ?? '',
- storedSessionId
- ])
- : `${stored.profile ?? 'default'}:${storedSessionId}`
+ const signatureKey = transcriptSignatureKey(stored, storedSessionId)
// Same rule as the warm-activation guard (use-session-actions/index.ts):
// publishing the page would blank the thread and trip the routed loading
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 06029fdcbb1..be476e72427 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
@@ -51,10 +51,37 @@ import {
resolveSessionOwner
} from '../../session/hooks/use-session-actions/utils'
import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache'
+import type { ClientSessionState } from '../../types'
import type { GatewayRequester } from '../types'
type SessionStateCache = ReturnType<typeof useSessionStateCache>
+/** Runtime a stored session is bound to: the primary reverse lookup, else a retained tile. */
+function boundTileRuntimeId(
+ runtimeIdByStoredSessionIdRef: SessionStateCache['runtimeIdByStoredSessionIdRef'],
+ storedSessionId: string
+): string | undefined {
+ return (
+ runtimeIdByStoredSessionIdRef.current.get(storedSessionId) ??
+ $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.runtimeId
+ )
+}
+
+/** REST read scope for a tile's resolved owner (connection-scoped owners read their target profile). */
+function tileRestScope(owner: SessionOwnerScope) {
+ return owner && typeof owner === 'object'
+ ? { connectionId: owner.connectionId, profile: owner.targetProfile || owner.profile }
+ : owner
+}
+
+/** A cached binding still carrying this session's transcript (or mid-turn). */
+function isWarmTileState(
+ cached: ClientSessionState | undefined,
+ storedSessionId: string
+): cached is ClientSessionState {
+ return cached?.storedSessionId === storedSessionId && (cached.busy || cached.messages.length > 0)
+}
+
function mergeTileTranscript(
previous: ChatMessage[],
prefetched: ChatMessage[],
@@ -324,9 +351,7 @@ export function useSessionTileDelegate({
resumeTile: async (storedSessionId, options) => {
// A retained tile can still own its runtime after the primary view drops
// its reverse lookup. Reconnect invalidates both bindings.
- const existing =
- runtimeIdByStoredSessionIdRef.current.get(storedSessionId) ??
- $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.runtimeId
+ const existing = boundTileRuntimeId(runtimeIdByStoredSessionIdRef, storedSessionId)
const cached = existing ? sessionStateByRuntimeIdRef.current.get(existing) : undefined
const resumeRequestBaselineMessages = cached?.messages ?? []
@@ -344,13 +369,7 @@ export function useSessionTileDelegate({
// warm snapshot is whatever the tile last painted, and cron bot-chat
// deliveries that landed while the panel's WS was down never arrive
// as realtime events (#96183).
- if (
- existing &&
- cached?.storedSessionId === storedSessionId &&
- (cached.busy || cached.messages.length > 0) &&
- !refreshTranscript &&
- !authoritativeSnapshot
- ) {
+ if (existing && isWarmTileState(cached, storedSessionId) && !refreshTranscript && !authoritativeSnapshot) {
publishSessionState(existing, cached)
return existing
@@ -363,21 +382,13 @@ export function useSessionTileDelegate({
// the same cross-profile bleed the recovery resumes had (#67603).
const owner = await ownerForStoredSession(storedSessionId)
- const restScope =
- owner && typeof owner === 'object'
- ? { connectionId: owner.connectionId, profile: owner.targetProfile || owner.profile }
- : owner
+ const restScope = tileRestScope(owner)
const prefetchPromise = authoritativeSnapshot
? Promise.resolve(null)
: getLatestSessionMessages(storedSessionId, restScope).catch(() => null)
- if (
- !authoritativeSnapshot &&
- existing &&
- cached?.storedSessionId === storedSessionId &&
- (cached.busy || cached.messages.length > 0)
- ) {
+ if (!authoritativeSnapshot && existing && isWarmTileState(cached, storedSessionId)) {
const prefetch = await prefetchPromise
// A long turn can push every rendered row off the newest page; read
@@ -476,9 +487,7 @@ export function useSessionTileDelegate({
throw new Error('resume returned no session id')
}
- const currentBinding =
- runtimeIdByStoredSessionIdRef.current.get(storedSessionId) ??
- $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.runtimeId
+ const currentBinding = boundTileRuntimeId(runtimeIdByStoredSessionIdRef, storedSessionId)
// Another resume/rebind won while this request was in flight. Do not
// publish the older response into the runtime the tile now owns.
@@ -511,8 +520,7 @@ export function useSessionTileDelegate({
const busyChangedWhileResuming = cached
? Boolean(
- state.busy &&
- (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))
+ state.busy && (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))
)
: state.busy
diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.ts
index c2258fb92c9..6b9ed5e32f8 100644
--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts
+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts
@@ -51,6 +51,25 @@ function resumeRetryDelayMs(attempt: number): number {
return Math.min(RESUME_RETRY_MAX_MS, RESUME_RETRY_BASE_MS * 2 ** attempt)
}
+// Resume the routed session with the owner route / snapshot mode carried by an
+// explicit resume request for that same session.
+function dispatchRouteResume(
+ resumeSession: RouteResumeOptions['resumeSession'],
+ routedSessionId: string,
+ sessionResumeRequest: SessionResumeRequest | null,
+ explicitlyRequested: boolean
+): void {
+ const ownerRoute = sessionResumeRequest?.sessionId === routedSessionId ? sessionResumeRequest.ownerRoute : undefined
+
+ if (explicitlyRequested && sessionResumeRequest?.authoritativeSnapshot) {
+ void resumeSession(routedSessionId, true, ownerRoute, { authoritativeSnapshot: true })
+ } else if (ownerRoute) {
+ void resumeSession(routedSessionId, true, ownerRoute)
+ } else {
+ void resumeSession(routedSessionId, true)
+ }
+}
+
// HashRouter boot edge case: pathname briefly reads `/` before the hash is
// parsed. If the hash references a real session, defer; resume picks it up
// next tick. Without this, ctrl+R on `#/:sessionId` flashes 5 loading states.
@@ -202,16 +221,7 @@ export function useRouteResume({
bootResumeRef.current = false
- const ownerRoute =
- sessionResumeRequest?.sessionId === routedSessionId ? sessionResumeRequest.ownerRoute : undefined
-
- if (explicitlyRequested && sessionResumeRequest.authoritativeSnapshot) {
- void resumeSession(routedSessionId, true, ownerRoute, { authoritativeSnapshot: true })
- } else if (ownerRoute) {
- void resumeSession(routedSessionId, true, ownerRoute)
- } else {
- void resumeSession(routedSessionId, true)
- }
+ dispatchRouteResume(resumeSession, routedSessionId, sessionResumeRequest, explicitlyRequested)
}
return
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 db7af2f507e..637ac997786 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
@@ -37,14 +37,7 @@ import { announceGoneSessionDraft, announceNewSessionDraftKey, migrateSessionDra
import { clearQueuedPrompts, migrateQueuedPrompts } from '@/store/composer-queue'
import { resetSessionBackground } from '@/store/composer-status'
import { $connectionRequests } from '@/store/connection-request'
-import {
- isActivePrimary,
- openGatewayForAgent,
- openGatewayForProfile,
- pendingSessionReplay,
- requestGatewayForAgent,
- retainGatewayForAgent
-} from '@/store/gateway'
+import { pendingSessionReplay, requestGatewayForAgent, retainGatewayForAgent } from '@/store/gateway'
import { $gatewaySwitching } from '@/store/gateway-switch'
import { clearSessionGoal } from '@/store/goals'
import { $pinnedSessionIds } from '@/store/layout'
@@ -55,7 +48,6 @@ import {
$gatewaySwapTarget,
$newChatProfile,
$profiles,
- $showAllProfiles,
type AgentProfileRoute,
ensureGatewayAgent,
ensureGatewayProfile,
@@ -175,6 +167,13 @@ import { rememberedOwnerForResume } from './remembered-owner'
import { restorePendingApproval } from './restore-pending-approval'
import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'
import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'
+import {
+ ambientResumeConnectionId,
+ openResumeGateway,
+ primaryResumeParams,
+ rememberResolvedResumeOwner,
+ resolveResumeOwner
+} from './resume-owner'
import { createGatewaySession } from './session-create-request'
import {
createPersistedDisplayTranscriptProvenance,
@@ -776,7 +775,7 @@ export function useSessionActions({
): Promise<string | null> => {
const startingStoredSessionId = selectedStoredSessionIdRef.current
const startingRouteToken = getRouteToken()
- const createIntent = createIntentRef.current ??= crypto.randomUUID()
+ const createIntent = (createIntentRef.current ??= crypto.randomUUID())
creatingSessionRef.current = true
@@ -897,7 +896,9 @@ export function useSessionActions({
resetViewSync()
- if (createIntentRef.current === createIntent) { createIntentRef.current = null }
+ if (createIntentRef.current === createIntent) {
+ createIntentRef.current = null
+ }
activeSessionIdRef.current = created.session_id
selectedStoredSessionIdRef.current = stored
ensureSessionState(created.session_id, stored)
@@ -1440,21 +1441,8 @@ export function useSessionActions({
// fills in when the caller had no route to give.
const ownerRoute = capturedOwner || rememberedOwner
- // A connection switch clears/reloads the session rows before this path
- // runs, so an untagged row belongs to the connection that supplied the
- // current list. Capture that source before the async metadata lookup. If
- // we reduce it to the profile string `default`, requestForSessionProfile
- // resolves the local default socket and sends an SSH session id to the
- // wrong machine ("resume failed: session not found").
- const ambientConnection = $connection.get()
-
- // Keep the legacy primary-local profile door: main may resolve a named
- // profile to its own remote override (#94166). A registry secondary is
- // already an explicit source, even when it is This device under Home.
- const ambientConnectionId =
- ambientConnection?.mode === 'remote' || (ambientConnection?.registryScoped && !isActivePrimary())
- ? ambientConnection.connectionId?.trim() || ''
- : ''
+ // Capture the list's source connection before the async metadata lookup.
+ const ambientConnectionId = ambientResumeConnectionId()
const provisional = provisionalTranscriptPaint(
storedSessionId,
@@ -1491,55 +1479,18 @@ export function useSessionActions({
return
}
- const resolvedConnectionId = ownerRoute?.connectionId || storedForProfile?.connection_id || ambientConnectionId
-
- // A row spliced from a CONNECTED registry gateway (#88880) carries its
- // owning connection. A row fetched directly after activating a registry
- // gateway can be untagged, so retain the captured ambient connection too.
- // Either way, route by the composite (connection, profile), never by a
- // same-named profile alone.
- const sessionOwner: SessionOwnerScope =
- ownerRoute ||
- (resolvedConnectionId
- ? {
- connectionId: resolvedConnectionId,
- profile: sessionProfile || 'default'
- }
- : sessionProfile)
+ const { resolvedConnectionId, sessionOwner } = resolveResumeOwner(
+ ownerRoute,
+ storedForProfile,
+ ambientConnectionId
+ )
- // Preserve this resolved source for later prompt/approval RPCs too;
- // otherwise an untagged row falls back to its bare profile after resume.
- // Only for a row the ambient source actually returned: an id that did not
- // resolve (deep link, routed restore) proves nothing about its owner, and
- // a persisted hint would pin it to whichever source was in front.
- if (
- !ownerRoute &&
- storedForProfile &&
- !storedForProfile.connection_id &&
- sessionOwner &&
- typeof sessionOwner === 'object'
- ) {
- setSessionOwnerHint(storedSessionId, sessionOwner)
- }
+ rememberResolvedResumeOwner(storedSessionId, ownerRoute, storedForProfile, sessionOwner)
const sessionRestScope = transcriptRestScope(ownerRoute, storedForProfile, ambientConnectionId)
provisional.paint(sessionRestScope)
- // All-profiles / plugin navigation must not steal chrome API-home:
- // dial the owning backend without moving $activeGatewayProfile.
- if ($showAllProfiles.get()) {
- if (resolvedConnectionId) {
- await openGatewayForAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default', {
- spawnPriority: 'foreground'
- })
- } else if (sessionProfile) {
- await openGatewayForProfile(normalizeProfileKey(sessionProfile), { spawnPriority: 'foreground' })
- }
- } else if (resolvedConnectionId) {
- await ensureGatewayAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default')
- } else {
- await ensureGatewayProfile(sessionProfile)
- }
+ await openResumeGateway(resolvedConnectionId, ownerRoute, sessionProfile)
// Request-time routing guard for every session-scoped RPC below. The
// await above REQUESTS the swap, but by dispatch time the active gateway
@@ -2190,25 +2141,10 @@ export function useSessionActions({
const resumePromise = singleFlightSessionResume(
storedSessionId,
() =>
- requestForSession<SessionResumeResult>('session.resume', {
- session_id: storedSessionId,
- cols: 96,
- source: 'desktop',
- defer_history: options?.authoritativeSnapshot ? false : !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.
- ...(options?.authoritativeSnapshot
- ? { omit_messages: false }
- : watchWindow
- ? { lazy: true }
- : { omit_messages: true }),
- ...(sessionProfile ? { profile: sessionProfile } : {})
- }),
+ requestForSession<SessionResumeResult>(
+ 'session.resume',
+ primaryResumeParams(storedSessionId, watchWindow, options?.authoritativeSnapshot, sessionProfile)
+ ),
{ requiresMessages: options?.authoritativeSnapshot, scope: sessionOwner }
).then(resumed => {
resumeRuntimeBaselineMessages =
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/resume-owner.ts b/apps/desktop/src/app/session/hooks/use-session-actions/resume-owner.ts
new file mode 100644
index 00000000000..4aef7334990
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/resume-owner.ts
@@ -0,0 +1,132 @@
+import type { SessionInfo } from '@/hermes'
+import { isActivePrimary, openGatewayForAgent, openGatewayForProfile } from '@/store/gateway'
+import { $showAllProfiles, ensureGatewayAgent, ensureGatewayProfile, normalizeProfileKey } from '@/store/profile'
+import { $connection, setSessionOwnerHint } from '@/store/session'
+import type { SessionOwnerScope, SessionProfileRoute } from '@/store/session-request-router'
+
+/**
+ * Connection that supplied the current session list, captured before resume's
+ * async metadata lookup.
+ *
+ * A connection switch clears/reloads the session rows before this path runs,
+ * so an untagged row belongs to the connection that supplied the current list.
+ * If we reduce it to the profile string `default`, requestForSessionProfile
+ * resolves the local default socket and sends an SSH session id to the wrong
+ * machine ("resume failed: session not found").
+ */
+export function ambientResumeConnectionId(): string {
+ const ambientConnection = $connection.get()
+
+ // Keep the legacy primary-local profile door: main may resolve a named
+ // profile to its own remote override (#94166). A registry secondary is
+ // already an explicit source, even when it is This device under Home.
+ return ambientConnection?.mode === 'remote' || (ambientConnection?.registryScoped && !isActivePrimary())
+ ? ambientConnection.connectionId?.trim() || ''
+ : ''
+}
+
+/**
+ * Route a resumed session by the composite (connection, profile).
+ *
+ * A row spliced from a CONNECTED registry gateway (#88880) carries its owning
+ * connection. A row fetched directly after activating a registry gateway can
+ * be untagged, so retain the captured ambient connection too. Either way,
+ * route by the composite (connection, profile), never by a same-named profile
+ * alone.
+ */
+export function resolveResumeOwner(
+ ownerRoute: SessionProfileRoute | undefined,
+ storedForProfile: SessionInfo | undefined,
+ ambientConnectionId: string
+): { resolvedConnectionId: string; sessionOwner: SessionOwnerScope } {
+ const sessionProfile = storedForProfile?.profile
+ const resolvedConnectionId = ownerRoute?.connectionId || storedForProfile?.connection_id || ambientConnectionId
+
+ const sessionOwner: SessionOwnerScope =
+ ownerRoute ||
+ (resolvedConnectionId
+ ? {
+ connectionId: resolvedConnectionId,
+ profile: sessionProfile || 'default'
+ }
+ : sessionProfile)
+
+ return { resolvedConnectionId, sessionOwner }
+}
+
+/**
+ * Preserve this resolved source for later prompt/approval RPCs too; otherwise
+ * an untagged row falls back to its bare profile after resume. Only for a row
+ * the ambient source actually returned: an id that did not resolve (deep link,
+ * routed restore) proves nothing about its owner, and a persisted hint would
+ * pin it to whichever source was in front.
+ */
+export function rememberResolvedResumeOwner(
+ storedSessionId: string,
+ ownerRoute: SessionProfileRoute | undefined,
+ storedForProfile: SessionInfo | undefined,
+ sessionOwner: SessionOwnerScope
+): void {
+ if (
+ !ownerRoute &&
+ storedForProfile &&
+ !storedForProfile.connection_id &&
+ sessionOwner &&
+ typeof sessionOwner === 'object'
+ ) {
+ setSessionOwnerHint(storedSessionId, sessionOwner)
+ }
+}
+
+/**
+ * Dial the backend that owns a resumed session.
+ *
+ * All-profiles / plugin navigation must not steal chrome API-home: dial the
+ * owning backend without moving $activeGatewayProfile.
+ */
+export async function openResumeGateway(
+ resolvedConnectionId: string,
+ ownerRoute: SessionProfileRoute | undefined,
+ sessionProfile: string | undefined
+): Promise<void> {
+ if ($showAllProfiles.get()) {
+ if (resolvedConnectionId) {
+ await openGatewayForAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default', {
+ spawnPriority: 'foreground'
+ })
+ } else if (sessionProfile) {
+ await openGatewayForProfile(normalizeProfileKey(sessionProfile), { spawnPriority: 'foreground' })
+ }
+ } else if (resolvedConnectionId) {
+ await ensureGatewayAgent(resolvedConnectionId, ownerRoute?.profile || sessionProfile || 'default')
+ } else {
+ await ensureGatewayProfile(sessionProfile)
+ }
+}
+
+/**
+ * `session.resume` params for a primary-view resume.
+ *
+ * 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 paints
+ * the transcript.
+ */
+export function primaryResumeParams(
+ storedSessionId: string,
+ watchWindow: boolean,
+ authoritativeSnapshot: boolean | undefined,
+ sessionProfile: string | undefined
+): Record<string, unknown> {
+ return {
+ session_id: storedSessionId,
+ cols: 96,
+ source: 'desktop',
+ defer_history: authoritativeSnapshot ? false : !watchWindow,
+ ...(authoritativeSnapshot ? { omit_messages: false } : watchWindow ? { lazy: true } : { omit_messages: true }),
+ ...(sessionProfile ? { profile: sessionProfile } : {})
+ }
+}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/resume-verdicts.ts b/apps/desktop/src/app/session/hooks/use-session-actions/resume-verdicts.ts
new file mode 100644
index 00000000000..31d0c54356f
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/resume-verdicts.ts
@@ -0,0 +1,56 @@
+// A "session genuinely doesn't exist" failure (deleted, or an id from a wiped /
+// rotated backend) — the REST transcript 404s with `Session not found`. Distinct
+// from a transient/wedged backend (ECONNREFUSED, timeout), which must still
+// retry rather than discard the id.
+export function isSessionGoneError(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err ?? '')
+
+ return message.includes('404') || /session not found/i.test(message)
+}
+
+/**
+ * What to do when a resume's RPC and REST fallback BOTH came back
+ * gone-looking (#88540).
+ *
+ * A 404 is only proof of deletion when it came from the backend that owns
+ * the session. During (or moments after) a profile/connection switch the
+ * request can land on a backend that has never heard of the id — the
+ * cross-profile Bots-pane open is the reproducer: the route is written
+ * correctly, the resume races the gateway swap, both lookups 404 on the
+ * wrong backend, and the "genuinely gone" branch yanks the window to the
+ * blank new-chat route while the target session is perfectly alive.
+ *
+ * `'retry'` keeps the route and arms the bounded auto-retry (which re-runs
+ * the resume once the swap settles); `'draft'` is reserved for a session
+ * that is verifiably gone in calm conditions.
+ */
+export function goneSessionVerdict(options: {
+ /** The session was created by this window in this run — never discard. */
+ createdThisRun: boolean
+ /** A post-failure re-resolve still finds the row on SOME profile. */
+ stillListed: boolean
+ /** A profile swap or connection switch is in flight (or just targeted). */
+ switchInFlight: boolean
+}): 'draft' | 'retry' {
+ return options.createdThisRun || options.stillListed || options.switchInFlight ? 'retry' : 'draft'
+}
+
+/**
+ * The busy value a resume/activate response should land with (#70449).
+ *
+ * `running` in a `session.activate` / `session.resume` payload is a snapshot
+ * taken when the RPC was issued. A turn that started — or streamed — after
+ * that snapshot has already marked the runtime busy in the live cache, so a
+ * stale `running: false` must never rewind it: that is exactly how opening an
+ * in-progress chat cleared its working indicator while the agent was still
+ * going. Preserving the newer live busy is safe, because the turn's own
+ * terminal signal (running:false via session.info / the settle path) remains
+ * the only authority that ends it, and the background-sync reaper clears
+ * truly lost turns.
+ *
+ * A snapshot that says `running: true` always wins — adopting a live turn is
+ * never stale.
+ */
+export function resolveResumedBusy(snapshotRunning: boolean | null | undefined, liveBusy: boolean): boolean {
+ return Boolean(snapshotRunning) || liveBusy
+}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index b89cc9d96e5..d77a63bdb1a 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -76,6 +76,8 @@ import {
transcriptRowIds
} from './pending-turn-identity'
+export { goneSessionVerdict, isSessionGoneError, resolveResumedBusy } from './resume-verdicts'
+
function withAppendedText(message: ChatMessage, suffix: string): ChatMessage {
let appended = false
@@ -1700,12 +1702,27 @@ export function overlayConcurrentMessageChanges(
rows.length > 0 &&
rows.every(id =>
overlaid.some(
- message => message.id !== current.id && message.role === current.role && transcriptRowIds(message).includes(id)
+ message =>
+ message.id !== current.id && message.role === current.role && transcriptRowIds(message).includes(id)
)
)
)
}
+ const representedOnPage = (current: ChatMessage): boolean =>
+ // The page can still carry the row's older streaming copy by id when it
+ // was composed from the baseline; the committed row replaces both.
+ (current.role === 'assistant' &&
+ current.pending !== true &&
+ !current.error &&
+ isLiveTailReplyId(current.id) &&
+ committedOnPage(current)) ||
+ // A completion receipt bound this optimistic prompt to its stored row
+ // while REST was in flight, so it differs from the pre-bind baseline only
+ // by that row id. The page already carries the stored row under its own
+ // id: the prompt is represented, not a new concurrent row.
+ (current.role === 'user' && representedByStoredRow(current))
+
for (const current of currentMessages) {
const baseline = baselineById.get(current.id)
const changedSinceBaseline = !baseline || !chatMessagesEquivalent(baseline, current)
@@ -1716,27 +1733,7 @@ export function overlayConcurrentMessageChanges(
const nextIndex = nextIndexById.get(current.id)
- // The page can still carry the row's older streaming copy by id when it
- // was composed from the baseline; the committed row replaces both.
- if (
- current.role === 'assistant' &&
- current.pending !== true &&
- !current.error &&
- isLiveTailReplyId(current.id) &&
- committedOnPage(current)
- ) {
- if (nextIndex !== undefined) {
- dropped.add(current.id)
- }
-
- continue
- }
-
- // A completion receipt bound this optimistic prompt to its stored row
- // while REST was in flight, so it differs from the pre-bind baseline only
- // by that row id. The page already carries the stored row under its own
- // id: the prompt is represented, not a new concurrent row.
- if (current.role === 'user' && representedByStoredRow(current)) {
+ if (representedOnPage(current)) {
if (nextIndex !== undefined) {
dropped.add(current.id)
}
@@ -2428,14 +2425,8 @@ function publishRuntimeToComposer(state: SessionRuntimeStatePatch): void {
}
}
-export function applyRuntimeInfo(
- info: SessionRuntimeInfo | undefined,
- { foreground = true }: ApplyRuntimeInfoOptions = {}
-): SessionRuntimeStatePatch | null {
- if (!info) {
- return null
- }
-
+/** Session-independent side effects of one runtime info snapshot. */
+function reportRuntimeInfoAppState(info: SessionRuntimeInfo): void {
if (info.stored_session_id) {
reconcilePendingSubmissions(info.stored_session_id, info.pending_submissions)
}
@@ -2451,6 +2442,17 @@ export function applyRuntimeInfo(
requestDesktopOnboardingForCredentialWarning(info.credential_warning)
reportInstallMethodWarning(info.install_warning)
+}
+
+export function applyRuntimeInfo(
+ info: SessionRuntimeInfo | undefined,
+ { foreground = true }: ApplyRuntimeInfoOptions = {}
+): SessionRuntimeStatePatch | null {
+ if (!info) {
+ return null
+ }
+
+ reportRuntimeInfoAppState(info)
const sessionState: SessionRuntimeStatePatch = {}
@@ -2580,60 +2582,3 @@ export function applyStoredSessionPreviewRuntimeInfo(
// carrying the previous conversation's label across a switch is never right.
setCurrentBranch('')
}
-
-// A "session genuinely doesn't exist" failure (deleted, or an id from a wiped /
-// rotated backend) — the REST transcript 404s with `Session not found`. Distinct
-// from a transient/wedged backend (ECONNREFUSED, timeout), which must still
-// retry rather than discard the id.
-export function isSessionGoneError(err: unknown): boolean {
- const message = err instanceof Error ? err.message : String(err ?? '')
-
- return message.includes('404') || /session not found/i.test(message)
-}
-
-/**
- * What to do when a resume's RPC and REST fallback BOTH came back
- * gone-looking (#88540).
- *
- * A 404 is only proof of deletion when it came from the backend that owns
- * the session. During (or moments after) a profile/connection switch the
- * request can land on a backend that has never heard of the id — the
- * cross-profile Bots-pane open is the reproducer: the route is written
- * correctly, the resume races the gateway swap, both lookups 404 on the
- * wrong backend, and the "genuinely gone" branch yanks the window to the
- * blank new-chat route while the target session is perfectly alive.
- *
- * `'retry'` keeps the route and arms the bounded auto-retry (which re-runs
- * the resume once the swap settles); `'draft'` is reserved for a session
- * that is verifiably gone in calm conditions.
- */
-export function goneSessionVerdict(options: {
- /** The session was created by this window in this run — never discard. */
- createdThisRun: boolean
- /** A post-failure re-resolve still finds the row on SOME profile. */
- stillListed: boolean
- /** A profile swap or connection switch is in flight (or just targeted). */
- switchInFlight: boolean
-}): 'draft' | 'retry' {
- return options.createdThisRun || options.stillListed || options.switchInFlight ? 'retry' : 'draft'
-}
-
-/**
- * The busy value a resume/activate response should land with (#70449).
- *
- * `running` in a `session.activate` / `session.resume` payload is a snapshot
- * taken when the RPC was issued. A turn that started — or streamed — after
- * that snapshot has already marked the runtime busy in the live cache, so a
- * stale `running: false` must never rewind it: that is exactly how opening an
- * in-progress chat cleared its working indicator while the agent was still
- * going. Preserving the newer live busy is safe, because the turn's own
- * terminal signal (running:false via session.info / the settle path) remains
- * the only authority that ends it, and the background-sync reaper clears
- * truly lost turns.
- *
- * A snapshot that says `running: true` always wins — adopting a live turn is
- * never stale.
- */
-export function resolveResumedBusy(snapshotRunning: boolean | null | undefined, liveBusy: boolean): boolean {
- return Boolean(snapshotRunning) || liveBusy
-}