Skip to content

The agent that grows with you

fix(desktop): refresh active transcript on session changes

Guilherme Aguiar1a2b0ca8cbb7
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
index 22a46927af0..b4d5b6e6c25 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
@@ -1,5 +1,9 @@
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { $changeEventsAvailable, notifySessionsChanged, resetLiveSync } from '@/store/live-sync'
+import { $activeSessionId, $selectedStoredSessionId, setBusy, setMessagingSessions, setSessions } from '@/store/session'
import {
$attentionSessionIds,
$stalledSessionIds,
@@ -8,19 +12,300 @@ import {
SESSION_WATCHDOG_TIMEOUT_MS
} from '@/store/session-states'
-import { rehydrateLiveSessionStatuses } from './use-background-sync'
+import {
+ type ActiveTranscriptRefreshDeps,
+ reconcileActiveTranscript,
+ rehydrateLiveSessionStatuses,
+ resolveActiveTranscriptSession,
+ useBackgroundSync
+} from './use-background-sync'
-describe('rehydrateLiveSessionStatuses', () => {
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal()),
+ getLatestSessionMessages: vi.fn()
+}))
+
+const { getLatestSessionMessages } = await import('@/hermes')
+
+const ACTIVE_RUNTIME_ID = 'runtime-active'
+const ACTIVE_STORED_ID = 'stored-active'
+
+function transcript(answer: string) {
+ return {
+ messages: [
+ { content: 'question', role: 'user', timestamp: 1 },
+ { content: answer, role: 'assistant', timestamp: 2 }
+ ],
+ session_id: ACTIVE_STORED_ID
+ }
+}
+
+function makeRefresh(resolveSession: ActiveTranscriptRefreshDeps['resolveSession'] = () => ({ profile: 'default' })) {
+ const activeSessionIdRef = { current: ACTIVE_RUNTIME_ID as string | null }
+ const selectedStoredSessionIdRef = { current: ACTIVE_STORED_ID as string | null }
+ const busyRef = { current: false }
+ const requestSequenceRef = { current: 0 }
+ const signatureRef = { current: new Map<string, string>() }
+ const state = createClientSessionState(ACTIVE_STORED_ID)
+ const states = new Map([[ACTIVE_RUNTIME_ID, state]])
+
+ const updateSessionState = vi.fn((sessionId: string, updater: (value: typeof state) => typeof state) => {
+ const next = updater(states.get(sessionId) ?? createClientSessionState(ACTIVE_STORED_ID))
+ states.set(sessionId, next)
+
+ return next
+ })
+
+ const refresh = () =>
+ reconcileActiveTranscript({
+ activeSessionIdRef,
+ busyRef,
+ requestSequenceRef,
+ resolveSession,
+ selectedStoredSessionIdRef,
+ signatureRef,
+ updateSessionState
+ })
+
+ return { activeSessionIdRef, busyRef, refresh, selectedStoredSessionIdRef, state, states, updateSessionState }
+}
+
+function useSyncHarness({
+ activeIsMessaging = false,
+ activeSessionId,
+ activeStoredSessionId,
+ refreshActiveTranscript
+}: {
+ activeIsMessaging?: boolean
+ activeSessionId: string | null
+ activeStoredSessionId: string | null
+ refreshActiveTranscript: () => Promise<void>
+}) {
+ useBackgroundSync({
+ activeGatewayProfile: 'default',
+ activeIsMessaging,
+ activeSessionId,
+ activeStoredSessionId,
+ freshDraftReady: false,
+ gatewayState: 'open',
+ refreshActiveTranscript,
+ refreshCronJobs: vi.fn(),
+ refreshCurrentModel: vi.fn(),
+ refreshHermesConfig: vi.fn(),
+ refreshMessagingSessions: vi.fn(),
+ refreshSessions: vi.fn(),
+ requestGateway: vi.fn(async () => ({ sessions: [] })) as never
+ })
+}
+
+function renderSync(
+ refreshActiveTranscript: () => Promise<void>,
+ options: { activeIsMessaging?: boolean; activeSessionId?: null | string; activeStoredSessionId?: null | string } = {}
+) {
+ return renderHook(() =>
+ useSyncHarness({
+ activeSessionId: ACTIVE_RUNTIME_ID,
+ activeStoredSessionId: ACTIVE_STORED_ID,
+ refreshActiveTranscript,
+ ...options
+ })
+ )
+}
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+ resetLiveSync()
+ $activeSessionId.set(null)
+ $selectedStoredSessionId.set(null)
+ setSessions([])
+ setMessagingSessions([])
+ setBusy(false)
+ vi.clearAllMocks()
+ clearAllSessionStates()
+})
+
+describe('active transcript refresh', () => {
beforeEach(() => {
+ vi.mocked(getLatestSessionMessages).mockResolvedValue(transcript('answer') as never)
+ })
+
+ it('refreshes a local/Desktop session when sessions.changed ticks', async () => {
+ $changeEventsAvailable.set(true)
+ $activeSessionId.set(ACTIVE_RUNTIME_ID)
+ $selectedStoredSessionId.set(ACTIVE_STORED_ID)
+ setSessions([{ id: ACTIVE_STORED_ID, profile: 'desktop-profile', source: 'desktop' } as never])
+ const fixture = makeRefresh(resolveActiveTranscriptSession)
+ vi.mocked(getLatestSessionMessages).mockResolvedValue(transcript('external answer') as never)
+
+ renderSync(fixture.refresh)
+
+ act(() => notifySessionsChanged())
+
+ await waitFor(() =>
+ expect(fixture.states.get(ACTIVE_RUNTIME_ID)?.messages.at(-1)?.parts[0]).toMatchObject({
+ text: 'external answer'
+ })
+ )
+ })
+
+ it('does not add a periodic transcript poll to local/Desktop sessions', async () => {
vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refresh = vi.fn(async () => undefined)
+
+ renderSync(refresh)
+ expect(refresh).not.toHaveBeenCalled()
+
+ await act(async () => {
+ vi.advanceTimersByTime(60_000)
+ await Promise.resolve()
+ })
+
+ expect(refresh).not.toHaveBeenCalled()
})
- afterEach(() => {
- vi.clearAllTimers()
- vi.useRealTimers()
- clearAllSessionStates()
+ it('retains the existing periodic backstop for messaging sessions', async () => {
+ vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refresh = vi.fn(async () => undefined)
+
+ renderSync(refresh, { activeIsMessaging: true })
+ expect(refresh).toHaveBeenCalledTimes(1)
+ await act(async () => Promise.resolve())
+ refresh.mockClear()
+
+ await act(async () => {
+ vi.advanceTimersByTime(30_000)
+ await Promise.resolve()
+ })
+
+ expect(refresh).toHaveBeenCalledTimes(1)
})
+ it('only defers an external tick while busy, then refreshes once after idle', async () => {
+ $changeEventsAvailable.set(true)
+ setBusy(true)
+ const refresh = vi.fn(async () => undefined)
+
+ renderSync(refresh)
+
+ act(() => setBusy(false))
+ expect(refresh).not.toHaveBeenCalled()
+ act(() => setBusy(true))
+
+ act(() => {
+ notifySessionsChanged()
+ notifySessionsChanged()
+ })
+ expect(refresh).not.toHaveBeenCalled()
+
+ act(() => setBusy(false))
+ await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1))
+ })
+
+ it('coalesces a burst of global ticks, including writes for another session', async () => {
+ vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refresh = vi.fn(async () => undefined)
+
+ renderSync(refresh)
+
+ act(() => {
+ for (let index = 0; index < 20; index += 1) {
+ notifySessionsChanged()
+ }
+ })
+ expect(refresh).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ vi.advanceTimersByTime(10_000)
+ await Promise.resolve()
+ })
+
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('reconcileActiveTranscript', () => {
+ it('resolves and hydrates a messaging session from the messaging sessions store', async () => {
+ setMessagingSessions([{ id: ACTIVE_STORED_ID, profile: 'messaging-profile', source: 'telegram' } as never])
+ const fixture = makeRefresh(resolveActiveTranscriptSession)
+ vi.mocked(getLatestSessionMessages).mockResolvedValue(transcript('telegram answer') as never)
+
+ await fixture.refresh()
+
+ expect(getLatestSessionMessages).toHaveBeenCalledWith(ACTIVE_STORED_ID, 'messaging-profile')
+ expect(fixture.states.get(ACTIVE_RUNTIME_ID)?.messages.at(-1)?.parts[0]).toMatchObject({
+ text: 'telegram answer'
+ })
+ })
+
+ it('publishes changed authoritative messages once without duplicates', async () => {
+ const fixture = makeRefresh()
+ vi.mocked(getLatestSessionMessages).mockResolvedValue(transcript('new answer') as never)
+
+ await fixture.refresh()
+
+ expect(fixture.updateSessionState).toHaveBeenCalledTimes(1)
+ const messages = fixture.states.get(ACTIVE_RUNTIME_ID)?.messages ?? []
+ expect(messages.map(message => message.role)).toEqual(['user', 'assistant'])
+ expect(new Set(messages.map(message => message.id)).size).toBe(messages.length)
+
+ await fixture.refresh()
+
+ expect(fixture.updateSessionState).toHaveBeenCalledTimes(1)
+ })
+
+ it('preserves a local assistant error while hydrating authoritative messages', async () => {
+ const fixture = makeRefresh()
+ fixture.state.messages = [
+ { id: '1-0-user', parts: [{ text: 'question', type: 'text' }], role: 'user' },
+ { error: 'local failure', id: 'assistant-error', parts: [], role: 'assistant' }
+ ]
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [{ content: 'question', role: 'user', timestamp: 1 }],
+ session_id: ACTIVE_STORED_ID
+ } as never)
+
+ await fixture.refresh()
+
+ const messages = fixture.states.get(ACTIVE_RUNTIME_ID)?.messages ?? []
+ expect(messages.map(message => message.id)).toEqual(['1-0-user', 'assistant-error'])
+ expect(messages.at(-1)?.error).toBe('local failure')
+ })
+
+ it('does not clobber a busy stream', async () => {
+ const fixture = makeRefresh()
+ fixture.busyRef.current = true
+
+ await fixture.refresh()
+
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ expect(fixture.updateSessionState).not.toHaveBeenCalled()
+ })
+
+ it('discards a response when the active session changes in flight', async () => {
+ const fixture = makeRefresh()
+ let resolve: ((value: unknown) => void) | undefined
+ vi.mocked(getLatestSessionMessages).mockReturnValueOnce(
+ new Promise(currentResolve => {
+ resolve = currentResolve
+ }) as never
+ )
+
+ const request = fixture.refresh()
+ fixture.selectedStoredSessionIdRef.current = 'stored-other'
+ fixture.activeSessionIdRef.current = 'runtime-other'
+ resolve?.(transcript('stale answer'))
+ await request
+
+ expect(fixture.updateSessionState).not.toHaveBeenCalled()
+ })
+})
+
+describe('rehydrateLiveSessionStatuses', () => {
it('restores running sessions after reconnect without opening them', () => {
const now = 1_800_000_000_000
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 32abacdacd2..793d5da2b8f 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -1,11 +1,23 @@
import { useStore } from '@nanostores/react'
-import { useEffect } from 'react'
+import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
+import { getLatestSessionMessages } from '@/hermes'
+import { preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
+import { sessionMessagesSignature } from '@/lib/session-signatures'
import { $changeEventsAvailable, $cronChangeTick, $sessionsChangeTick } from '@/store/live-sync'
import { $onBattery, batteryPollInterval } from '@/store/power'
import { refreshActiveProfile } from '@/store/profile'
-import { $activeSessionId, $currentCwd, setCurrentCwd } from '@/store/session'
+import {
+ $activeSessionId,
+ $busy,
+ $currentCwd,
+ $messagingSessions,
+ $selectedStoredSessionId,
+ $sessions,
+ sessionMatchesStoredId,
+ setCurrentCwd
+} from '@/store/session'
import {
$sessionStates,
publishSessionState,
@@ -13,8 +25,93 @@ import {
setSessionStalled
} from '@/store/session-states'
+import type { ClientSessionState } from '../../types'
import type { GatewayRequester } from '../types'
+interface ActiveTranscriptSession {
+ profile?: string | null
+}
+
+/** Resolve an active transcript from either local recents or messaging slices. */
+export function resolveActiveTranscriptSession(storedSessionId: string): ActiveTranscriptSession | undefined {
+ return (
+ $sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId)) ??
+ $messagingSessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+ )
+}
+
+export interface ActiveTranscriptRefreshDeps {
+ activeSessionIdRef: MutableRefObject<string | null>
+ busyRef: MutableRefObject<boolean>
+ requestSequenceRef: MutableRefObject<number>
+ selectedStoredSessionIdRef: MutableRefObject<string | null>
+ resolveSession: (storedSessionId: string) => ActiveTranscriptSession | null | undefined
+ signatureRef: MutableRefObject<Map<string, string>>
+ updateSessionState: (
+ sessionId: string,
+ updater: (state: ClientSessionState) => ClientSessionState,
+ storedSessionId?: string | null
+ ) => ClientSessionState
+}
+
+/** Reconcile one persisted transcript snapshot into the currently viewed session. */
+export async function reconcileActiveTranscript({
+ activeSessionIdRef,
+ busyRef,
+ requestSequenceRef,
+ resolveSession,
+ selectedStoredSessionIdRef,
+ signatureRef,
+ updateSessionState
+}: ActiveTranscriptRefreshDeps): Promise<void> {
+ const storedSessionId = selectedStoredSessionIdRef.current
+ const runtimeSessionId = activeSessionIdRef.current
+
+ if (!storedSessionId || !runtimeSessionId || busyRef.current) {
+ return
+ }
+
+ const stored = resolveSession(storedSessionId)
+
+ if (!stored) {
+ return
+ }
+
+ const requestId = requestSequenceRef.current + 1
+ requestSequenceRef.current = requestId
+
+ try {
+ const latest = await getLatestSessionMessages(storedSessionId, stored.profile)
+
+ if (
+ requestId !== requestSequenceRef.current ||
+ busyRef.current ||
+ selectedStoredSessionIdRef.current !== storedSessionId ||
+ activeSessionIdRef.current !== runtimeSessionId
+ ) {
+ return
+ }
+
+ const signatureKey = `${stored.profile ?? 'default'}:${storedSessionId}`
+ const signature = sessionMessagesSignature(latest.messages)
+
+ if (signatureRef.current.get(signatureKey) === signature) {
+ return
+ }
+
+ signatureRef.current.set(signatureKey, signature)
+ const messages = toChatMessages(latest.messages)
+
+ updateSessionState(
+ runtimeSessionId,
+ state => ({ ...state, messages: preserveLocalAssistantErrors(messages, state.messages) }),
+ storedSessionId
+ )
+ } catch {
+ // Non-fatal: the next change event or manual resume can hydrate the view.
+ }
+}
+
// Cron sessions are written by a background scheduler tick, messaging turns by
// the background gateway (Telegram, WeChat, Discord, …) — neither signals the
// desktop websocket directly. Backends with the change watcher broadcast
@@ -177,9 +274,10 @@ interface BackgroundSyncParams {
activeGatewayProfile: string
activeIsMessaging: boolean
activeSessionId: null | string
+ activeStoredSessionId: null | string
freshDraftReady: boolean
gatewayState: string
- refreshActiveMessagingTranscript: () => Promise<unknown> | unknown
+ refreshActiveTranscript: () => Promise<unknown> | unknown
refreshCronJobs: () => Promise<unknown> | unknown
refreshCurrentModel: (force?: boolean) => Promise<unknown> | unknown
refreshHermesConfig: () => Promise<unknown> | unknown
@@ -226,9 +324,10 @@ export function useBackgroundSync({
activeGatewayProfile,
activeIsMessaging,
activeSessionId,
+ activeStoredSessionId,
freshDraftReady,
gatewayState,
- refreshActiveMessagingTranscript,
+ refreshActiveTranscript,
refreshCronJobs,
refreshCurrentModel,
refreshHermesConfig,
@@ -239,6 +338,48 @@ export function useBackgroundSync({
const changeEventsAvailable = useStore($changeEventsAvailable)
const cronChangeTick = useStore($cronChangeTick)
const sessionsChangeTick = useStore($sessionsChangeTick)
+ const activeTranscriptBusy = useStore($busy)
+ const activeTranscriptRefreshPendingRef = useRef<string | null>(null)
+
+ const requestActiveTranscriptRefresh = useCallback(
+ (preservePending: boolean) => {
+ if (!activeStoredSessionId || !activeSessionId) {
+ return
+ }
+
+ const storedSessionId = activeStoredSessionId
+ const runtimeSessionId = activeSessionId
+ const sessionKey = `${storedSessionId}:${runtimeSessionId}`
+
+ if (preservePending) {
+ activeTranscriptRefreshPendingRef.current = sessionKey
+ }
+
+ if ($busy.get()) {
+ return
+ }
+
+ if (preservePending && activeTranscriptRefreshPendingRef.current === sessionKey) {
+ activeTranscriptRefreshPendingRef.current = null
+ }
+
+ void Promise.resolve(refreshActiveTranscript()).finally(() => {
+ // If streaming began while the read was in flight, reconciliation was
+ // discarded and the external event still needs one idle retry.
+ if (
+ preservePending &&
+ $busy.get() &&
+ $activeSessionId.get() === runtimeSessionId &&
+ $selectedStoredSessionId.get() === storedSessionId
+ ) {
+ activeTranscriptRefreshPendingRef.current = sessionKey
+
+ return
+ }
+ })
+ },
+ [activeSessionId, activeStoredSessionId, refreshActiveTranscript]
+ )
useEffect(() => {
if (gatewayState !== 'open') {
@@ -332,6 +473,7 @@ export function useBackgroundSync({
lastRunAt = Date.now()
void refreshSessions()
void refreshMessagingSessions()
+ requestActiveTranscriptRefresh(true)
}
const unsubscribe = $sessionsChangeTick.listen(() => {
@@ -354,7 +496,7 @@ export function useBackgroundSync({
window.clearTimeout(timer)
}
}
- }, [changeEventsAvailable, gatewayState, refreshMessagingSessions, refreshSessions])
+ }, [changeEventsAvailable, gatewayState, refreshMessagingSessions, refreshSessions, requestActiveTranscriptRefresh])
// Keep the cron-jobs section live without a user action (scheduler ticks in
// the background). cron.changed (jobs.json moved: CRUD or a scheduler tick's
@@ -374,24 +516,47 @@ export function useBackgroundSync({
)
}, [changeEventsAvailable, cronChangeTick, gatewayState, refreshCronJobs])
- // Only the open messaging transcript needs its own cadence — local chats are
- // live over the websocket already. sessions.changed re-pulls it via the tick
- // dep; the visible poll is the backstop.
+ // A busy transition only consumes a pending sessions.changed refresh. It
+ // never creates one, so an ordinary local turn going busy -> idle does not
+ // add a REST read. The event itself is coalesced by the list throttle above.
useEffect(() => {
- if (gatewayState !== 'open' || !activeIsMessaging) {
+ if (
+ gatewayState !== 'open' ||
+ activeTranscriptBusy ||
+ !activeSessionId ||
+ !activeStoredSessionId ||
+ activeTranscriptRefreshPendingRef.current !== `${activeStoredSessionId}:${activeSessionId}`
+ ) {
return
}
- const dispose = visiblePoll(
- changeEventsAvailable ? ACTIVE_MESSAGING_SESSION_BACKSTOP_INTERVAL_MS : ACTIVE_MESSAGING_SESSION_POLL_INTERVAL_MS,
- () => void refreshActiveMessagingTranscript()
- )
+ requestActiveTranscriptRefresh(true)
+ }, [activeSessionId, activeStoredSessionId, activeTranscriptBusy, gatewayState, requestActiveTranscriptRefresh])
- void refreshActiveMessagingTranscript()
+ // Preserve the pre-existing messaging behavior: refresh once when a
+ // messaging transcript opens, then keep its visibility backstop. Desktop
+ // sessions never enter this effect and therefore gain no periodic timer.
+ useEffect(() => {
+ if (gatewayState !== 'open' || !activeIsMessaging || !activeSessionId || !activeStoredSessionId) {
+ return
+ }
+
+ const runScheduledRefresh = () => requestActiveTranscriptRefresh(false)
+
+ runScheduledRefresh()
- return dispose
- // sessionsChangeTick: an inbound turn re-pulls the open transcript.
- }, [activeIsMessaging, changeEventsAvailable, gatewayState, refreshActiveMessagingTranscript, sessionsChangeTick])
+ return visiblePoll(
+ changeEventsAvailable ? ACTIVE_MESSAGING_SESSION_BACKSTOP_INTERVAL_MS : ACTIVE_MESSAGING_SESSION_POLL_INTERVAL_MS,
+ runScheduledRefresh
+ )
+ }, [
+ activeIsMessaging,
+ activeSessionId,
+ activeStoredSessionId,
+ changeEventsAvailable,
+ gatewayState,
+ requestActiveTranscriptRefresh
+ ])
// Messaging session lists against an older backend: no sessions.changed, so
// keep the legacy visible poll. (Event-capable backends fold this into the
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 12160a7823f..7eeaeaa4797 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -26,7 +26,6 @@ import { RemoteDisplayBanner } from '@/components/remote-display-banner'
import { emitGatewayEvent } from '@/contrib/events'
import { getLatestSessionMessages, triggerCronJob } from '@/hermes'
import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
-import { sessionMessagesSignature } from '@/lib/session-signatures'
import { isMessagingSource } from '@/lib/session-source'
import { latestSessionTodos } from '@/lib/todos'
import { activateWakeIndicator } from '@/lib/wake-indicator'
@@ -122,7 +121,11 @@ import { TitlebarControls } from '../shell/titlebar-controls'
import { UpdatesOverlay } from '../updates-overlay'
import { ContribWiringContext } from './context'
-import { useBackgroundSync } from './hooks/use-background-sync'
+import {
+ reconcileActiveTranscript,
+ resolveActiveTranscriptSession,
+ useBackgroundSync
+} from './hooks/use-background-sync'
import { useDesktopIntegrations } from './hooks/use-desktop-integrations'
import { usePetBridge } from './hooks/use-pet-bridge'
import { useQuickEntryBridge } from './hooks/use-quick-entry-bridge'
@@ -159,7 +162,8 @@ export function ContribWiring({ children }: { children: ReactNode }) {
// intent counter here; the ref skips the initial mount value.
const billingSettingsSeenRef = useRef(0)
const cronReviewSeenRef = useRef(0)
- const messagingTranscriptSignatureRef = useRef(new Map<string, string>())
+ const activeTranscriptSignatureRef = useRef(new Map<string, string>())
+ const activeTranscriptRequestSequenceRef = useRef(0)
// Stable identity for the whole callback surface (see WiringActions). Mutated
// in place each render so memoized surfaces never re-render on churn.
const actionsRef = useRef<WiringActions | null>(null)
@@ -374,44 +378,21 @@ export function ContribWiring({ children }: { children: ReactNode }) {
[activeSessionIdRef, selectedStoredSessionIdRef, updateSessionState]
)
- // Refresh the open messaging transcript (inbound platform turns arrive via
- // the background gateway, not the desktop websocket). Signature-gated so a
- // no-change poll doesn't churn the thread.
- const refreshActiveMessagingTranscript = useCallback(async () => {
- const storedSessionId = selectedStoredSessionIdRef.current
- const runtimeSessionId = activeSessionIdRef.current
-
- if (!storedSessionId || !runtimeSessionId || busyRef.current) {
- return
- }
-
- const stored = $messagingSessions.get().find(s => sessionMatchesStoredId(s, storedSessionId))
-
- if (!stored || !isMessagingSource(stored.source)) {
- return
- }
-
- try {
- const latest = await getLatestSessionMessages(storedSessionId, stored.profile)
- const signatureKey = `${stored.profile ?? 'default'}:${storedSessionId}`
- const sig = sessionMessagesSignature(latest.messages)
-
- if (messagingTranscriptSignatureRef.current.get(signatureKey) === sig) {
- return
- }
-
- messagingTranscriptSignatureRef.current.set(signatureKey, sig)
- const messages = toChatMessages(latest.messages)
-
- updateSessionState(
- runtimeSessionId,
- state => ({ ...state, messages: preserveLocalAssistantErrors(messages, state.messages) }),
- storedSessionId
- )
- } catch {
- // Non-fatal: next poll or manual refresh can hydrate.
- }
- }, [activeSessionIdRef, busyRef, selectedStoredSessionIdRef, updateSessionState])
+ // Refresh any active transcript changed by another process. Signature-gated
+ // so a no-change event does not churn the thread.
+ const refreshActiveTranscript = useCallback(
+ () =>
+ reconcileActiveTranscript({
+ activeSessionIdRef,
+ busyRef,
+ requestSequenceRef: activeTranscriptRequestSequenceRef,
+ resolveSession: resolveActiveTranscriptSession,
+ selectedStoredSessionIdRef,
+ signatureRef: activeTranscriptSignatureRef,
+ updateSessionState
+ }),
+ [activeSessionIdRef, busyRef, selectedStoredSessionIdRef, updateSessionState]
+ )
const { handleGatewayEvent } = useMessageStream({
activeGatewayProfile,
@@ -769,21 +750,22 @@ export function ContribWiring({ children }: { children: ReactNode }) {
}
}, [gatewayState, requestGateway])
- // Only the open messaging transcript needs its own poll — local chats are
- // live over the websocket already.
const activeIsMessaging =
!!selectedStoredSessionId &&
isMessagingSource(messagingSessions.find(s => sessionMatchesStoredId(s, selectedStoredSessionId))?.source)
+ // sessions.changed refreshes every open transcript; only messaging retains
+ // the periodic safety-net it already had before this fix.
// Keep app data live while the gateway is open (on-connect reseed + the
// cron / messaging / transcript visibility polls + fresh-draft reseed).
useBackgroundSync({
activeGatewayProfile,
activeIsMessaging,
activeSessionId,
+ activeStoredSessionId: selectedStoredSessionId,
freshDraftReady,
gatewayState,
- refreshActiveMessagingTranscript,
+ refreshActiveTranscript,
refreshCronJobs,
refreshCurrentModel,
refreshHermesConfig,