Skip to content

The agent that grows with you

fix(desktop): refetch Bot Chat on roster reopen instead of idle snapshot

686f6c616ac193e02b33
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index 661fe8d966c..a81224bbb3b 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -191,6 +191,41 @@ describe('useSessionTileDelegate resumeTile', () => {
expect(runtimeId).toBe('runtime-a')
expect(requestGateway).not.toHaveBeenCalled()
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ })
+
+ it('merges persisted messages into a warm tile on explicit reopen (#96183)', async () => {
+ const stateA = {
+ busy: false,
+ messages: [{ id: 'm1', parts: [{ type: 'text', text: 'old' }], role: 'user' }],
+ storedSessionId: 'stored-a'
+ }
+ const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-a', 'runtime-a']]) }
+ const sessionStateByRuntimeIdRef = { current: new Map([['runtime-a', stateA]]) }
+ const updateSessionState = vi.fn((_id, updater) => updater(stateA))
+ const requestGateway = vi.fn(async () => ({}) as never)
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValueOnce({
+ messages: [
+ { id: 'm1', content: 'old', role: 'user' },
+ { id: 'm2', content: 'cron delivery', role: 'user' }
+ ],
+ session_id: 'stored-a'
+ } as never)
+
+ renderTile(requestGateway, { runtimeIdByStoredSessionIdRef, sessionStateByRuntimeIdRef, updateSessionState })
+ const runtimeId = await sessionTileDelegate()!.resumeTile('stored-a', { refreshTranscript: true })
+
+ expect(runtimeId).toBe('runtime-a')
+ expect(requestGateway).not.toHaveBeenCalled()
+ expect(getLatestSessionMessages).toHaveBeenCalled()
+ expect(updateSessionState).toHaveBeenCalled()
+
+ const updater = updateSessionState.mock.calls[0][1] as (state: typeof stateA) => { messages: Array<{ parts?: Array<{ text?: string }> }> }
+ const next = updater(stateA)
+ const texts = next.messages.flatMap(message => (message.parts ?? []).map(part => part.text ?? ''))
+
+ expect(texts.some(text => text.includes('cron delivery'))).toBe(true)
})
it('falls through to a real resume when the warm binding has no transcript (post-wake empty tile)', async () => {
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 86c4c683406..0b17b09f09b 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
@@ -1,12 +1,13 @@
import { useEffect } from 'react'
+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'
import {
fetchStoredTranscriptAcrossBackends,
getLatestSessionMessages,
PROMPT_SUBMIT_REQUEST_TIMEOUT_MS
} from '@/hermes'
import { translateNow } from '@/i18n/runtime'
-import { toChatMessages } from '@/lib/chat-messages'
+import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
import { notify } from '@/store/notifications'
import {
isReadOnlyRuntimeId,
@@ -22,12 +23,31 @@ 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 { resolveSessionOwner } from '../../session/hooks/use-session-actions/utils'
+import {
+ chatMessageArraysEquivalent,
+ reconcileResumeMessages,
+ resolveSessionOwner
+} from '../../session/hooks/use-session-actions/utils'
import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache'
import type { GatewayRequester } from '../types'
type SessionStateCache = ReturnType<typeof useSessionStateCache>
+function mergeTileTranscript(
+ previous: ChatMessage[],
+ prefetchMessages: SessionResumeResponse['messages'] | undefined
+): ChatMessage[] {
+ const prefetched = toChatMessages(prefetchMessages ?? [])
+
+ if (!prefetched.length) {
+ return previous
+ }
+
+ const persisted = graftRefreshedTailOntoBackfill(prefetched, previous)
+
+ return reconcileResumeMessages(persisted, previous)
+}
+
interface SessionTileDelegateParams {
archiveSession: (storedSessionId: string) => Promise<unknown>
branchStoredSession: (storedSessionId: string) => Promise<unknown>
@@ -182,9 +202,10 @@ export function useSessionTileDelegate({
}
)
},
- resumeTile: async storedSessionId => {
+ resumeTile: async (storedSessionId, options) => {
const existing = runtimeIdByStoredSessionIdRef.current.get(storedSessionId)
const cached = existing ? sessionStateByRuntimeIdRef.current.get(existing) : undefined
+ const refreshTranscript = options?.refreshTranscript === true
// Warm path: reuse a live binding — but only when it still carries a
// transcript (or is mid-turn, where messages legitimately stream in).
@@ -192,7 +213,17 @@ export function useSessionTileDelegate({
// transcript or a stale pre-reconnect survivor; reusing it painted the
// post-sleep/wake tile permanently empty. Fall through to a real
// resume instead — it's idempotent for a genuinely live session.
- if (existing && cached?.storedSessionId === storedSessionId && (cached.busy || cached.messages.length > 0)) {
+ //
+ // Explicit reopen (`refreshTranscript`) must still REST-merge: the
+ // 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
+ ) {
publishSessionState(existing, cached)
return existing
@@ -212,6 +243,19 @@ export function useSessionTileDelegate({
const prefetchPromise = getLatestSessionMessages(storedSessionId, restScope).catch(() => null)
+ if (existing && cached?.storedSessionId === storedSessionId && (cached.busy || cached.messages.length > 0)) {
+ const prefetch = await prefetchPromise
+ const merged = mergeTileTranscript(cached.messages, prefetch?.messages)
+
+ if (!chatMessageArraysEquivalent(cached.messages, merged)) {
+ updateSessionState(existing, state => ({ ...state, messages: merged }), storedSessionId)
+ } else {
+ publishSessionState(existing, cached)
+ }
+
+ return existing
+ }
+
// #94724 no-owner recovery: dispatching the resume through the same
// fail-closed gate as the window's RPC dispatcher keeps an unknown
// owner off the ambient socket, and the wrapper opens the stored
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index c39b6fd32f7..5dff1edc367 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -90,7 +90,8 @@ import {
$focusedSessionState,
$focusedStoredSessionId,
$sessionStates,
- $sessionTiles
+ $sessionTiles,
+ sessionTileDelegate
} from '@/store/session-states'
import { runGatewayRestart } from '@/store/system-actions'
import type { PaginatedSessions, UsageStats } from '@/types/hermes'
@@ -977,8 +978,25 @@ export const host = {
// session-states cache kept across a bot switch (#93604). Callers
// that represent an explicit user navigation pass forceResume to
// skip the heuristic entirely; the resume is idempotent either way.
+ //
+ // Bot Chat opens as a tab/tile. requestSessionResume is consumed
+ // only when the MAIN route is that session, so a roster reopen of
+ // an already-mounted tile would paint the idle snapshot and never
+ // pull messages that arrived while the panel WS was down (#96183).
+ // Refresh the tile transcript in place instead.
if (options.awaitHydration && (options.forceResume || !surfaceHealthy)) {
- requestSessionResume(storedSessionId, ownerRoute || undefined)
+ const existingTile = $sessionTiles.get().some(tile => tile.storedSessionId === storedSessionId)
+ const tileDelegate = existingTile ? sessionTileDelegate() : null
+
+ if (tileDelegate) {
+ try {
+ await tileDelegate.resumeTile(storedSessionId, { refreshTranscript: true })
+ } catch {
+ requestSessionResume(storedSessionId, ownerRoute || undefined)
+ }
+ } else {
+ requestSessionResume(storedSessionId, ownerRoute || undefined)
+ }
}
if (options.awaitHydration) {
diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.ts
index 72f906cc016..fd9227abf4c 100644
--- a/apps/desktop/src/sdk/profile-routing.test.ts
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@ -44,7 +44,8 @@ vi.mock('@/store/session-states', async () => {
$focusedSessionState: atom(null),
$focusedStoredSessionId: atom(null),
$sessionTiles: atom([]),
- $sessionStates: atom({})
+ $sessionStates: atom({}),
+ sessionTileDelegate: vi.fn(() => null)
}
})
vi.mock('@/store/profile', async () => {
@@ -128,8 +129,14 @@ const {
setShowAllProfiles
} = await import('@/store/profile')
-const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId, $sessionStates, $sessionTiles } =
- await import('@/store/session-states')
+const {
+ $focusedRuntimeId,
+ $focusedSessionState,
+ $focusedStoredSessionId,
+ $sessionStates,
+ $sessionTiles,
+ sessionTileDelegate
+} = await import('@/store/session-states')
const { setWorkspaceScope } = await import('@/components/pane-shell/workspace-scope')
@@ -156,6 +163,7 @@ const profile = (name: string): ProfileInfo => ({
afterEach(() => {
vi.clearAllMocks()
+ vi.mocked(sessionTileDelegate).mockReturnValue(null)
vi.mocked(activeGatewayConnectionId).mockReturnValue('local')
$activeGatewayProfile.set('remote-worker')
$gatewaySwapTarget.set(null)
@@ -718,6 +726,32 @@ describe('profile-aware plugin session opens', () => {
expect($gatewaySwapTarget.get()).toBeNull()
})
+ it('refreshes an already-open Bot Chat tile instead of trusting the idle snapshot (#96183)', async () => {
+ const resumeTile = vi.fn(async () => 'runtime-bot-chat')
+
+ vi.mocked(sessionTileDelegate).mockReturnValue({ resumeTile } as never)
+ $activeGatewayProfile.set('hyoseob')
+ setMockAtom($sessionTiles, [{ storedSessionId: 'bot-chat' }] as never)
+ setMockAtom($focusedStoredSessionId, 'bot-chat')
+ setMockAtom($focusedRuntimeId, 'runtime-bot-chat')
+ setMockAtom($focusedSessionState, { messages: [{ id: 'stale-history', parts: [], role: 'assistant' }] } as never)
+
+ const opening = host.openSession('bot-chat', {
+ profile: 'hyoseob',
+ awaitHydration: true,
+ expectHistory: true,
+ forceResume: true,
+ hydrationTimeoutMs: 1_000,
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'hyoseob'
+ })
+
+ await opening
+
+ expect(resumeTile).toHaveBeenCalledWith('bot-chat', { refreshTranscript: true })
+ expect(requestSessionResume).not.toHaveBeenCalled()
+ })
+
it('forces a resume on an explicit bot switch even when a cached transcript looks healthy (#93604)', async () => {
// Bot-switch shape from the field: the previous visit left a non-empty
// snapshot in the session-states cache, so the surface passes every
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 98143ffa8a1..c99fb4baf63 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -1216,8 +1216,11 @@ export interface SessionTileDelegate {
* right pane" bug). Bindings re-record from live post-reconnect events. */
invalidateRuntimeBindings?(preserveStoredSessionIds?: ReadonlySet<string>): void
/** Bind a live runtime id for a stored session (resume without touching
- * the main view). Returns the runtime id, or throws. */
- resumeTile(storedSessionId: string): Promise<string>
+ * the main view). Returns the runtime id, or throws.
+ * `refreshTranscript` forces a REST merge even when a warm cached
+ * transcript already exists — reopen-after-idle must not paint the
+ * snapshot that was current when the panel last had a socket. */
+ resumeTile(storedSessionId: string, options?: { refreshTranscript?: boolean }): Promise<string>
/** Retire one runtime's busy/awaiting claim through the wiring cache
* (updateSessionState), so cache, focused view, busyRef, and tile mirrors
* settle together. Returns false when the cache holds no busy state for