The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): refresh peer windows and refuse a stale multi-window submit (#65047)
brooklyn!f86db25ef53c
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.tsindex a525b8c20f9..95d802ee27c 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@@ -4,7 +4,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { reasoningEffortPending } from '@/app/chat/session-view'import type { ClientSessionState } from '@/app/types'import type * as HermesModule from '@/hermes'+import { textPart } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'+import { $notifications } from '@/store/notifications'import { setSessionOwnerHint, setSessions } from '@/store/session'import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'@@ -554,3 +556,105 @@ describe('useSessionTileDelegate interruptSession', () => {expect(isSessionRecentlyInterrupted('runtime-tile-1')).toBe(true)})})++describe('useSessionTileDelegate stale multi-window guard (#65047)', () => {+ const storedId = 'stored-tile-peer'+ const runtimeId = 'rt-tile-peer'++ beforeEach(() => {+ setSessions([])+ $notifications.set([])+ vi.mocked(getLatestSessionMessages).mockReset()+ vi.mocked(getLatestSessionMessages).mockImplementation(async () => ({ messages: [], session_id: storedId }))+ })++ afterEach(() => {+ setSessions([])+ $notifications.set([])+ })++ it('refuses submitToSession when a peer window advanced the transcript', async () => {+ setSessions([row({ id: storedId, profile: 'work-vps' })])+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: storedId,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 },+ { content: 'c', role: 'user', timestamp: 3 },+ { content: 'd', role: 'assistant', timestamp: 4 }+ ]+ })++ const stale = createClientSessionState(storedId, [+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ])++ const sessionStateByRuntimeIdRef = { current: new Map([[runtimeId, stale]]) }+ const runtimeIdByStoredSessionIdRef = { current: new Map([[storedId, runtimeId]]) }+ const seeds: unknown[] = []+ const requestGateway = vi.fn(async () => ({}) as never)++ renderTile(requestGateway, {+ runtimeIdByStoredSessionIdRef,+ sessionStateByRuntimeIdRef,+ updateSessionState: vi.fn((id, updater, stored) => {+ const prev = sessionStateByRuntimeIdRef.current.get(id) ?? createClientSessionState(stored)+ const next = updater(prev)+ sessionStateByRuntimeIdRef.current.set(id, next)+ seeds.push(next)++ return next+ })+ })++ await sessionTileDelegate()!.submitToSession(runtimeId, 'stale tile send')++ expect(getLatestSessionMessages).toHaveBeenCalledWith(storedId, 'work-vps')+ expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())+ expect(requestGatewayForProfile).not.toHaveBeenCalledWith(+ 'work-vps',+ 'prompt.submit',+ expect.anything(),+ expect.anything(),+ expect.anything()+ )+ expect(seeds.at(-1)).toEqual(expect.objectContaining({ busy: false, messages: expect.any(Array) }))+ expect((seeds.at(-1) as { messages: unknown[] }).messages).toHaveLength(4)+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(true)+ })++ it('allows submitToSession when the authoritative transcript is not ahead', async () => {+ setSessions([row({ id: storedId, profile: 'work-vps' })])+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: storedId,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 }+ ]+ })++ const fresh = createClientSessionState(storedId, [+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ])++ const requestGateway = vi.fn(async () => ({}) as never)++ renderTile(requestGateway, {+ runtimeIdByStoredSessionIdRef: { current: new Map([[storedId, runtimeId]]) },+ sessionStateByRuntimeIdRef: { current: new Map([[runtimeId, fresh]]) }+ })++ await sessionTileDelegate()!.submitToSession(runtimeId, 'fresh tile send')++ expect(requestGatewayForProfile).toHaveBeenCalledWith(+ 'work-vps',+ 'prompt.submit',+ { session_id: runtimeId, text: 'fresh tile send' },+ 1_800_000,+ undefined+ )+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)+ })+})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.tsindex 6177c2f4644..a869238bc6e 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@@ -9,6 +9,7 @@ import {import { translateNow } from '@/i18n/runtime'import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'import { markReasoningEffortPending } from '@/lib/chat-runtime'+import { profileScopeForSessionOwner, refreshIfTranscriptStale } from '@/lib/stale-transcript-guard'import { notify } from '@/store/notifications'import {isReadOnlyRuntimeId,@@ -436,6 +437,36 @@ export function useSessionTileDelegate({const storedSessionId = storedSessionIdForRuntime(runtimeId)+ if (storedSessionId) {+ const cached = sessionStateByRuntimeIdRef.current.get(runtimeId)+ const owner = await ownerForStoredSession(storedSessionId)++ const refreshed = await refreshIfTranscriptStale(storedSessionId, cached?.messages ?? [], {+ profile: profileScopeForSessionOwner(owner)+ })++ if (refreshed) {+ updateSessionState(+ runtimeId,+ state => ({+ ...state,+ awaitingResponse: false,+ busy: false,+ messages: refreshed,+ pendingBranchGroup: null+ }),+ storedSessionId+ )+ notify({+ kind: 'warning',+ message: translateNow('desktop.staleSessionBody'),+ title: translateNow('desktop.staleSessionTitle')+ })++ return+ }+ }+const routedRequest = storedSessionId? <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) =>requestForStoredSession<T>(storedSessionId, method, params ?? {}, timeoutMs)diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 95549630e57..f94024170bf 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -135,6 +135,7 @@ import { useRouteResume } from '../session/hooks/use-route-resume'import { useSessionActions } from '../session/hooks/use-session-actions'import { useSessionListActions } from '../session/hooks/use-session-list-actions'import { useSessionStateCache } from '../session/hooks/use-session-state-cache'+import { useTranscriptPeerSync } from '../session/hooks/use-transcript-peer-sync'import { startWorkspaceSession } from '../session/workspace-session-target'import { PluginInstallModal } from '../settings/plugin-install-modal'import { useOverlayRouting } from '../shell/hooks/use-overlay-routing'@@ -941,6 +942,13 @@ export function ContribWiring({ children }: { children: ReactNode }) {!!selectedStoredSessionId &&isMessagingSource(messagingSessions.find(s => sessionMatchesStoredId(s, selectedStoredSessionId))?.source)+ useTranscriptPeerSync({+ activeSessionIdRef,+ busyRef,+ selectedStoredSessionIdRef,+ updateSessionState+ })+// 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 + thediff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.tsindex e48d8fceb08..7944ecdee59 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts@@ -32,6 +32,7 @@ import { isDiskFullErrorMessage, notifyError } from '@/store/notifications'import { broadcastSessionsChanged } from '@/store/session-sync'import { upsertSubagent } from '@/store/subagents'import { $todosBySession, setSessionTodos } from '@/store/todos'+import { broadcastTranscriptChanged } from '@/store/transcript-sync'import type { ClientSessionState } from '../../../types'@@ -931,6 +932,13 @@ export function useMessageStream({scheduleSessionsRefresh()+ if (completedState.storedSessionId) {+ broadcastTranscriptChanged({+ messageCount: completedState.messages.length,+ sessionId: completedState.storedSessionId+ })+ }+if (compactedTurnRef.current.delete(sessionId)) {shouldHydrate = false}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/peer-transcript-notify.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/peer-transcript-notify.test.tsxnew file mode 100644index 00000000000..292923358b5--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/peer-transcript-notify.test.tsx@@ -0,0 +1,43 @@+import { act, cleanup } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { createClientSessionState } from '@/lib/chat-runtime'++import { renderMessageStream } from './test-harness'++const broadcastTranscriptChanged = vi.hoisted(() => vi.fn())++vi.mock('@/store/transcript-sync', () => ({+ broadcastTranscriptChanged+}))++const SID = 'rt-peer'+const STORED = 'stored-peer'++describe('completed turn notifies peer windows (#65047)', () => {+ afterEach(() => {+ cleanup()+ broadcastTranscriptChanged.mockClear()+ })++ it('broadcasts the stored session when a turn completes', () => {+ const states = new Map([[SID, createClientSessionState(STORED)]])+ const stream = renderMessageStream(SID, { states })++ act(() => {+ stream.handleEvent({ payload: { text: 'done' }, session_id: SID, type: 'message.complete' })+ })++ expect(broadcastTranscriptChanged).toHaveBeenCalledWith(expect.objectContaining({ sessionId: STORED }))+ })++ it('does not broadcast a completed runtime that has no stored session', () => {+ const stream = renderMessageStream(SID)++ act(() => {+ stream.handleEvent({ payload: { text: 'done' }, session_id: SID, type: 'message.complete' })+ })++ expect(broadcastTranscriptChanged).not.toHaveBeenCalled()+ })+})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.tsxindex d831003fd31..04f98adcfb5 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@@ -4,8 +4,8 @@ import type { MutableRefObject } from 'react'import { useEffect, useRef } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { getSession } from '@/hermes'-import { textPart } from '@/lib/chat-messages'+import { getLatestSessionMessages, getSession } from '@/hermes'+import { textPart, toChatMessages } from '@/lib/chat-messages'import { createClientSessionState } from '@/lib/chat-runtime'import { $composerAttachments, $composerDraft, type ComposerAttachment, setComposerDraft } from '@/store/composer'import { $queuedPromptsBySession, getQueuedPrompts } from '@/store/composer-queue'@@ -41,9 +41,12 @@ import { uploadComposerAttachment, usePromptActions } from '.'// never-settling in-flight promise from one test into the next.beforeEach(() => {clearSingleFlightSessionResumeState()+ vi.mocked(getLatestSessionMessages).mockReset()+ vi.mocked(getLatestSessionMessages).mockImplementation(async () => ({ messages: [], session_id: 'session' }))})vi.mock('@/hermes', () => ({+ getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: 'session' })),getProfiles: vi.fn(async () => ({ profiles: [] })),getSession: vi.fn(),PROMPT_SUBMIT_REQUEST_TIMEOUT_MS: 1_800_000,@@ -5852,3 +5855,156 @@ describe('usePromptActions live-owner refusal (#106217)', () => {expect(requestGateway.mock.calls.map(c => c[0])).toEqual(['prompt.submit'])})})++describe('usePromptActions stale multi-window guard (#65047)', () => {+ afterEach(() => {+ cleanup()+ $notifications.set([])+ setSessions(() => [])+ })++ it('refuses prompt.submit when the local transcript is behind and refreshes it', async () => {+ const storedId = 'stored-stale-submit'+ setSessions(() => [sessionInfo({ id: storedId, profile: 'work-vps', title: 'Remote chat' })])+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: storedId,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 },+ { content: 'c', role: 'user', timestamp: 3 },+ { content: 'd', role: 'assistant', timestamp: 4 }+ ]+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ const seeds: Record<string, unknown>[] = []+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ onSeedState={state => seeds.push(state)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ]}+ storedSessionId={storedId}+ />+ )++ expect(await handle!.submitText('stale send from secondary window')).toBe(false)+ expect(getLatestSessionMessages).toHaveBeenCalledWith(storedId, 'work-vps')+ expect(requestGateway).not.toHaveBeenCalledWith('prompt.submit', expect.anything(), expect.anything())++ const last = seeds.at(-1) as { awaitingResponse?: boolean; busy?: boolean; messages?: unknown[] } | undefined+ expect(last?.busy).toBe(false)+ expect(last?.awaitingResponse).toBe(false)+ expect(last?.messages).toHaveLength(4)+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(true)+ })++ it('allows prompt.submit when the authoritative transcript is not ahead', async () => {+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: RUNTIME_SESSION_ID,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 }+ ]+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ]}+ />+ )++ expect(await handle!.submitText('fresh enough')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',+ { session_id: RUNTIME_SESSION_ID, text: 'fresh enough' },+ 1_800_000+ )+ expect($notifications.get().some(note => note.kind === 'warning')).toBe(false)+ })++ it('does not refuse when raw session rows are longer only because tools fold into chat messages', async () => {+ const remoteSessionMessages = [+ { content: 'check the repo', role: 'user' as const, timestamp: 1 },+ {+ content: 'Looking.',+ role: 'assistant' as const,+ timestamp: 2,+ tool_calls: [{ id: 'tc-1', function: { name: 'terminal', arguments: '{"command":"ls"}' } }]+ },+ {+ content: '{"output":"ok"}',+ role: 'tool' as const,+ tool_call_id: 'tc-1',+ tool_name: 'terminal',+ timestamp: 3+ },+ { content: 'Done.', role: 'assistant' as const, timestamp: 4 }+ ]++ const localChat = toChatMessages(remoteSessionMessages)++ expect(remoteSessionMessages.length).toBeGreaterThan(localChat.length)+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: RUNTIME_SESSION_ID,+ messages: remoteSessionMessages+ })++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={localChat}+ />+ )++ expect(await handle!.submitText('follow-up after tools')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',+ { session_id: RUNTIME_SESSION_ID, text: 'follow-up after tools' },+ 1_800_000+ )+ })++ it('does not refuse when the authoritative transcript read fails', async () => {+ vi.mocked(getLatestSessionMessages).mockRejectedValue(new Error('wrong backend'))++ const requestGateway = vi.fn(async () => ({}) as never)+ let handle: HarnessHandle | null = null++ await actRender(+ <Harness+ onReady={h => (handle = h)}+ refreshSessions={async () => undefined}+ requestGateway={requestGateway}+ seedMessages={[{ id: 'u1', role: 'user', parts: [textPart('a')] }]}+ />+ )++ expect(await handle!.submitText('send anyway')).toBe(true)+ expect(requestGateway).toHaveBeenCalledWith(+ 'prompt.submit',+ { session_id: RUNTIME_SESSION_ID, text: 'send anyway' },+ 1_800_000+ )+ })+})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.tsindex a5d5b499290..33909016e7d 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@@ -7,6 +7,7 @@ import { type ChatMessage, textPart } from '@/lib/chat-messages'import { optimisticAttachmentRef } from '@/lib/chat-runtime'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'import { setMutableRef } from '@/lib/mutable-ref'+import { refreshIfTranscriptStale } from '@/lib/stale-transcript-guard'import {isVoicePlaybackActive,markVoicePlaybackInterrupted,@@ -36,6 +37,7 @@ import {import { $sessionStates } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'+import { profileScopeForTranscriptSession, resolveActiveTranscriptSession } from '../../../contrib/hooks/use-background-sync'import type { ClientSessionState } from '../../../types'import { sessionContextDrift } from '../session-context-drift'import { resolveSessionProfile } from '../use-session-actions/utils'@@ -812,6 +814,53 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {rewriteOptimistic(liveSessionId)const text = buildContextText(syncedAttachments)+ // Another Desktop window may own a newer transcript while this one+ // still shows an open-time snapshot. Refuse the send and refresh+ // rather than forking the session (#65047).+ const guardStoredId = targetStoredSessionId ?? selectedStoredSessionIdRef.current++ if (guardStoredId && liveSessionId) {+ const localSnapshot = updateSessionState(liveSessionId, state => state, targetStoredSessionId)++ const refreshed = await refreshIfTranscriptStale(guardStoredId, localSnapshot.messages, {+ excludeMessageId: optimisticId,+ profile: profileScopeForTranscriptSession(+ resolveActiveTranscriptSession(guardStoredId, liveSessionId)+ )+ })++ if (sessionDriftReason()) {+ return abortForSessionSwitch(liveSessionId)+ }++ if (refreshed) {+ updateSessionState(+ liveSessionId,+ state => ({+ ...state,+ awaitingResponse: false,+ busy: false,+ messages: refreshed,+ pendingBranchGroup: null+ }),+ targetStoredSessionId+ )++ if (targetIsCurrentView()) {+ scope.setMessages(() => refreshed)+ notify({+ kind: 'warning',+ message: copy.staleSessionBody,+ title: copy.staleSessionTitle+ })+ }++ releaseBusy()++ return false+ }+ }+const submitParams = (targetId: string) => ({session_id: targetId,text,diff --git a/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.test.tsx b/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.test.tsxnew file mode 100644index 00000000000..f05ef1ce052--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.test.tsx@@ -0,0 +1,173 @@+import { act, cleanup, render } from '@testing-library/react'+import { useRef } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type * as HermesModule from '@/hermes'+import { textPart } from '@/lib/chat-messages'+import { createClientSessionState } from '@/lib/chat-runtime'+import { $sessionTiles, publishSessionState } from '@/store/session-states'++vi.mock('@/hermes', async importOriginal => {+ const actual = await importOriginal<typeof HermesModule>()++ return {+ ...actual,+ getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: 'stored-1' }))+ }+})++type ChannelListener = (event: MessageEvent) => void++class FakeBroadcastChannel {+ static instances = new Map<string, Set<FakeBroadcastChannel>>()++ name: string+ private listeners = new Set<ChannelListener>()++ constructor(name: string) {+ this.name = name+ const group = FakeBroadcastChannel.instances.get(name) ?? new Set()+ group.add(this)+ FakeBroadcastChannel.instances.set(name, group)+ }++ postMessage(data: unknown) {+ const group = FakeBroadcastChannel.instances.get(this.name)++ if (!group) {+ return+ }++ for (const channel of group) {+ if (channel === this) {+ continue+ }++ for (const listener of channel.listeners) {+ listener({ data } as MessageEvent)+ }+ }+ }++ addEventListener(_type: string, listener: ChannelListener) {+ this.listeners.add(listener)+ }++ removeEventListener(_type: string, listener: ChannelListener) {+ this.listeners.delete(listener)+ }+}++const STORED = 'stored-peer-sync'+const RUNTIME = 'rt-peer-sync'++describe('useTranscriptPeerSync (#65047)', () => {+ beforeEach(() => {+ FakeBroadcastChannel.instances.clear()+ vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel)+ vi.resetModules()+ $sessionTiles.set([])+ })++ afterEach(() => {+ cleanup()+ vi.unstubAllGlobals()+ vi.resetModules()+ $sessionTiles.set([])+ })++ it('re-pulls the transcript when a peer finishes a turn on the viewed session', async () => {+ const local = createClientSessionState(STORED, [+ { id: 'u1', role: 'user', parts: [textPart('a')] },+ { id: 'a1', role: 'assistant', parts: [textPart('b')] }+ ])++ publishSessionState(RUNTIME, local)++ const { getLatestSessionMessages } = await import('@/hermes')+ vi.mocked(getLatestSessionMessages).mockResolvedValue({+ session_id: STORED,+ messages: [+ { content: 'a', role: 'user', timestamp: 1 },+ { content: 'b', role: 'assistant', timestamp: 2 },+ { content: 'c', role: 'user', timestamp: 3 },+ { content: 'd', role: 'assistant', timestamp: 4 }+ ]+ })++ const { useTranscriptPeerSync } = await import('./use-transcript-peer-sync')+ const seeds: unknown[] = []++ function Harness() {+ const activeSessionIdRef = useRef<string | null>(RUNTIME)+ const busyRef = useRef(false)+ const selectedStoredSessionIdRef = useRef<string | null>(STORED)++ useTranscriptPeerSync({+ activeSessionIdRef,+ busyRef,+ selectedStoredSessionIdRef,+ updateSessionState: (sessionId, updater, storedSessionId) => {+ const next = updater(local)+ seeds.push({ sessionId, storedSessionId, messages: next.messages })++ return next+ }+ })++ return null+ }++ await act(async () => {+ render(<Harness />)+ })++ const peer = new FakeBroadcastChannel('hermes:transcript')++ await act(async () => {+ peer.postMessage({ messageCount: 4, sessionId: STORED })+ })++ expect(getLatestSessionMessages).toHaveBeenCalledWith(STORED, undefined)+ expect(seeds.at(-1)).toEqual(+ expect.objectContaining({+ sessionId: RUNTIME,+ storedSessionId: STORED+ })+ )+ expect((seeds.at(-1) as { messages: unknown[] }).messages).toHaveLength(4)+ })++ it('ignores a peer ping for a session this window is not viewing', async () => {+ const { getLatestSessionMessages } = await import('@/hermes')+ vi.mocked(getLatestSessionMessages).mockClear()+ const { useTranscriptPeerSync } = await import('./use-transcript-peer-sync')++ function Harness() {+ const activeSessionIdRef = useRef<string | null>(RUNTIME)+ const busyRef = useRef(false)+ const selectedStoredSessionIdRef = useRef<string | null>(STORED)++ useTranscriptPeerSync({+ activeSessionIdRef,+ busyRef,+ selectedStoredSessionIdRef,+ updateSessionState: (sessionId, updater) => updater(createClientSessionState(STORED))+ })++ return null+ }++ await act(async () => {+ render(<Harness />)+ })++ const peer = new FakeBroadcastChannel('hermes:transcript')++ await act(async () => {+ peer.postMessage({ sessionId: 'some-other-chat', messageCount: 9 })+ })++ expect(getLatestSessionMessages).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.ts b/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.tsnew file mode 100644index 00000000000..ece07410b7a--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-transcript-peer-sync.ts@@ -0,0 +1,97 @@+import { type MutableRefObject, useEffect } from 'react'++import {+ hydrateStoredSessionTranscript,+ profileScopeForTranscriptSession,+ resolveActiveTranscriptSession+} from '@/app/contrib/hooks/use-background-sync'+import type { ClientSessionState } from '@/app/types'+import { $sessionTiles } from '@/store/session-states'+import { onTranscriptChanged } from '@/store/transcript-sync'++interface TranscriptPeerSyncOptions {+ activeSessionIdRef: MutableRefObject<string | null>+ busyRef: MutableRefObject<boolean>+ selectedStoredSessionIdRef: MutableRefObject<string | null>+ updateSessionState: (+ sessionId: string,+ updater: (state: ClientSessionState) => ClientSessionState,+ storedSessionId?: string | null+ ) => ClientSessionState+}++/**+ * When another window finishes a turn on a stored session this window is+ * showing, re-pull that transcript. The completing window does not receive+ * its own broadcast. Submit still refuses if this pull has not landed yet.+ */+export function useTranscriptPeerSync({+ activeSessionIdRef,+ busyRef,+ selectedStoredSessionIdRef,+ updateSessionState+}: TranscriptPeerSyncOptions): void {+ useEffect(() => {+ let cancelled = false++ const unsubscribe = onTranscriptChanged(payload => {+ const storedSessionId = payload.sessionId++ if (!storedSessionId) {+ return+ }+ void (async () => {+ const selected = selectedStoredSessionIdRef.current+ const runtimeId = activeSessionIdRef.current++ if (+ !cancelled &&+ selected === storedSessionId &&+ runtimeId &&+ !busyRef.current+ ) {+ await hydrateStoredSessionTranscript({+ attempts: 1,+ runtimeSessionId: runtimeId,+ storedProfile: profileScopeForTranscriptSession(resolveActiveTranscriptSession(storedSessionId, runtimeId)),+ storedSessionId,+ updateSessionState+ })+ }++ if (cancelled) {+ return+ }++ for (const tile of $sessionTiles.get()) {+ if (tile.storedSessionId !== storedSessionId || !tile.runtimeId || tile.runtimeId === runtimeId) {+ continue+ }++ const owner = tile.ownerRoute+ ? { ownerRoute: tile.ownerRoute, profile: tile.ownerProfile ?? tile.ownerRoute.profile }+ : tile.ownerProfile+ ? { profile: tile.ownerProfile }+ : resolveActiveTranscriptSession(storedSessionId, tile.runtimeId)++ await hydrateStoredSessionTranscript({+ attempts: 1,+ runtimeSessionId: tile.runtimeId,+ storedProfile: profileScopeForTranscriptSession(owner),+ storedSessionId,+ updateSessionState+ })++ if (cancelled) {+ return+ }+ }+ })()+ })++ return () => {+ cancelled = true+ unsubscribe()+ }+ }, [activeSessionIdRef, busyRef, selectedStoredSessionIdRef, updateSessionState])+}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex d19dffc5f69..69ec70f0ff0 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -3438,6 +3438,9 @@ export const ar = defineLocale({sessionUnavailable: 'الجلسة غير متاحة',createSessionFailed: 'فشل إنشاء الجلسة',promptFailed: 'فشل إرسال الرسالة',+ staleSessionTitle: 'المحادثة غير محدّثة',+ staleSessionBody:+ 'كانت هذه النافذة متأخرة عن عرض آخر لنفس المحادثة. تم تحميل أحدث الرسائل. أعد الإرسال إذا كنت لا تزال تريد ذلك.',providerCredentialRequired: 'مطلوب اعتماد المزود',emptySlashCommand: 'أمر slash فارغ',desktopCommands: 'أوامر سطح المكتب',diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 889244e357a..76a4d810ed3 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -5882,6 +5882,9 @@ export const deOverrides = {sessionUnavailable: 'Session nicht verfügbar',createSessionFailed: 'Neue Session konnte nicht erstellt werden',promptFailed: 'Prompt fehlgeschlagen',+ staleSessionTitle: 'Chat veraltet',+ staleSessionBody:+ 'Dieses Fenster war hinter einer anderen Ansicht desselben Chats. Die neuesten Nachrichten wurden geladen. Senden Sie erneut, wenn Sie noch möchten.',providerCredentialRequired:'Fügen Sie Anmeldedaten für einen Anbieter hinzu, bevor Sie Ihre erste Nachricht senden.',emptySlashCommand: 'leerer Slash-Befehl',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 5de6ef49877..03fc35cb6ae 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -5333,6 +5333,9 @@ export const en: Translations = {sessionUnavailable: 'Session unavailable',createSessionFailed: 'Could not create a new session',promptFailed: 'Prompt failed',+ staleSessionTitle: 'Chat out of date',+ staleSessionBody:+ 'This window was behind another view of the same chat. Latest messages were loaded. Send again if you still want to.',providerCredentialRequired: 'Add a provider credential before sending your first message.',emptySlashCommand: 'empty slash command',desktopCommands: 'Desktop commands',diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 4541f2e8349..a67ba6933ba 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -5874,6 +5874,9 @@ export const esOverrides = {sessionUnavailable: 'Sesión no disponible',createSessionFailed: 'No se pudo crear una sesión nueva',promptFailed: 'Falló el prompt',+ staleSessionTitle: 'Chat desactualizado',+ staleSessionBody:+ 'Esta ventana estaba detrás de otra vista del mismo chat. Se cargaron los mensajes más recientes. Envía de nuevo si aún quieres.',providerCredentialRequired: 'Añade una credencial de proveedor antes de enviar tu primer mensaje.',emptySlashCommand: 'comando slash vacío',desktopCommands: 'Comandos de escritorio',diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex d617f185fd3..92622644afd 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -5894,6 +5894,9 @@ export const frOverrides = {sessionUnavailable: 'Session indisponible',createSessionFailed: 'Impossible de créer une nouvelle session',promptFailed: "Échec de l'invite",+ staleSessionTitle: 'Conversation obsolète',+ staleSessionBody:+ 'Cette fenêtre était en retard sur une autre vue du même chat. Les derniers messages ont été chargés. Renvoyez si vous le souhaitez encore.',providerCredentialRequired: "Ajoutez un identifiant de fournisseur avant d'envoyer votre premier message.",emptySlashCommand: 'commande slash vide',desktopCommands: 'Commandes Desktop',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 1edee7313b4..2e41d12f7b2 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3949,6 +3949,9 @@ export const ja = defineLocale({sessionUnavailable: 'セッションが利用できません',createSessionFailed: '新しいセッションを作成できませんでした',promptFailed: 'プロンプトに失敗しました',+ staleSessionTitle: 'チャットが最新ではありません',+ staleSessionBody:+ 'このウィンドウは同じチャットの別ビューより遅れています。最新のメッセージを読み込みました。送信する場合はもう一度送ってください。',providerCredentialRequired: '最初のメッセージを送信する前にプロバイダー認証情報を追加してください。',emptySlashCommand: '空のスラッシュコマンド',desktopCommands: 'デスクトップコマンド',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex d6f39fcac02..1b3a44cb2f5 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -4076,6 +4076,9 @@ export const ru = defineLocale({sessionUnavailable: 'Сеанс недоступен',createSessionFailed: 'Не удалось создать новый сеанс',promptFailed: 'Промпт не удался',+ staleSessionTitle: 'Чат устарел',+ staleSessionBody:+ 'Это окно отставало от другого вида того же чата. Загружены последние сообщения. Отправьте снова, если всё ещё хотите.',providerCredentialRequired: 'Добавьте учётные данные провайдера перед отправкой первого сообщения.',emptySlashCommand: 'пустая слэш-команда',desktopCommands: 'Команды desktop',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex ae928d3de2a..7e417033ae3 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -4425,6 +4425,8 @@ export interface Translations {sessionUnavailable: stringcreateSessionFailed: stringpromptFailed: string+ staleSessionTitle: string+ staleSessionBody: stringproviderCredentialRequired: stringemptySlashCommand: stringdesktopCommands: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex ffa0b92c063..6e82484286e 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -4099,6 +4099,8 @@ export const zhHant = defineLocale({sessionUnavailable: '工作階段不可用',createSessionFailed: '無法建立新工作階段',promptFailed: '提示詞傳送失敗',+ staleSessionTitle: '對話已過期',+ staleSessionBody: '此視窗落後於同一對話的其他視窗。已載入最新訊息。若仍要傳送請再試一次。',providerCredentialRequired: '傳送第一則訊息前請先新增提供方憑證。',emptySlashCommand: '空的斜線指令',desktopCommands: '桌面端指令',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex bbed6a8f9a8..8bf7eb1578d 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4922,6 +4922,8 @@ export const zh = defineLocale({sessionUnavailable: '会话不可用',createSessionFailed: '无法创建新会话',promptFailed: '提示词发送失败',+ staleSessionTitle: '对话已过期',+ staleSessionBody: '此窗口落后于同一对话的其他窗口。已加载最新消息。若仍要发送请再试一次。',providerCredentialRequired: '发送第一条消息前请先添加提供方凭据。',emptySlashCommand: '空 slash 命令',desktopCommands: '桌面端命令',diff --git a/apps/desktop/src/lib/stale-transcript-guard.ts b/apps/desktop/src/lib/stale-transcript-guard.tsnew file mode 100644index 00000000000..b6ac5c9f7ed--- /dev/null+++ b/apps/desktop/src/lib/stale-transcript-guard.ts@@ -0,0 +1,85 @@+import { graftRefreshedTailOntoBackfill } from '@/app/chat/transcript-backfill'+import { getLatestSessionMessages, type ProfileScope } from '@/hermes'+import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'+import { knownSessionOwner, ownerLookupSessionRows } from '@/store/session'+import type { SessionOwnerScope } from '@/store/session-request-router'++/** REST scope for a session owner. Undefined when the owner is unknown. */+export function profileScopeForSessionOwner(owner: SessionOwnerScope): ProfileScope {+ if (!owner) {+ return undefined+ }++ if (typeof owner === 'string') {+ return owner+ }++ return {+ connectionId: owner.connectionId,+ profile: owner.targetProfile ?? owner.profile+ }+}++/**+ * Chat messages to install when the authoritative latest page is ahead of the+ * local view. Null when the local view is current.+ *+ * Length is compared after `toChatMessages`, so tool rows folded into an+ * assistant bubble are not "ahead". A backfilled prefix is kept when the+ * refreshed tail anchors inside it. Live stream ids that do not anchor still+ * use length, so the window that just finished the turn is not blocked when+ * the counts match.+ */+export function messagesIfTranscriptBehind(+ localMessages: ChatMessage[],+ remoteChat: ChatMessage[]+): ChatMessage[] | null {+ if (remoteChat.length === 0) {+ return null+ }++ if (localMessages.length === 0) {+ return remoteChat+ }++ const grafted = graftRefreshedTailOntoBackfill(remoteChat, localMessages)++ if (grafted === remoteChat) {+ return remoteChat.length > localMessages.length ? remoteChat : null+ }++ return grafted.length > localMessages.length ? grafted : null+}++/**+ * Read the authoritative latest page and return a refreshed transcript when+ * this view is behind. Null when current or the read fails — a missing+ * profile or a down backend must not soft-lock send.+ */+export async function refreshIfTranscriptStale(+ storedSessionId: string,+ localMessages: ChatMessage[],+ options?: { excludeMessageId?: string; profile?: ProfileScope }+): Promise<ChatMessage[] | null> {+ const baseline = options?.excludeMessageId+ ? localMessages.filter(message => message.id !== options.excludeMessageId)+ : localMessages++ const profile =+ options && 'profile' in options+ ? options.profile+ : profileScopeForSessionOwner(knownSessionOwner(ownerLookupSessionRows(), storedSessionId))++ try {+ const remote = await getLatestSessionMessages(storedSessionId, profile)+ const refreshed = messagesIfTranscriptBehind(baseline, toChatMessages(remote.messages))++ if (!refreshed) {+ return null+ }++ return preserveLocalAssistantErrors(refreshed, baseline)+ } catch {+ return null+ }+}diff --git a/apps/desktop/src/store/transcript-sync.ts b/apps/desktop/src/store/transcript-sync.tsnew file mode 100644index 00000000000..8da76770a1a--- /dev/null+++ b/apps/desktop/src/store/transcript-sync.ts@@ -0,0 +1,48 @@+// Cross-window transcript freshness. Each desktop window owns its own gateway+// transport for a session, so a turn that completes in window A never streams+// into window B. This bus pings peers with the stored session id so a window+// viewing that chat can re-pull history before the user sends into an+// out-of-date context. Distinct from hermes:sessions (sidebar list).++export type TranscriptChangedPayload = {+ /** Stored session id shared across Desktop windows. */+ sessionId: string+ /** Chat-message length after the completed turn, when the sender has one. */+ messageCount?: number+}++const CHANNEL = 'hermes:transcript'++const channel = typeof BroadcastChannel === 'undefined' ? null : new BroadcastChannel(CHANNEL)++export function broadcastTranscriptChanged(payload: TranscriptChangedPayload): void {+ if (!payload.sessionId) {+ return+ }++ channel?.postMessage(payload)+}++export function onTranscriptChanged(handler: (payload: TranscriptChangedPayload) => void): () => void {+ if (!channel) {+ return () => {}+ }++ const listener = (event: MessageEvent<TranscriptChangedPayload>) => {+ const data = event.data++ if (!data || typeof data.sessionId !== 'string' || !data.sessionId) {+ return+ }++ if (data.messageCount !== undefined && typeof data.messageCount !== 'number') {+ return+ }++ handler(data)+ }++ channel.addEventListener('message', listener)++ return () => channel.removeEventListener('message', listener)+}