The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): preserve owner scope and concurrent turns during gap recovery
unsupportedpastels75d66bf2d550
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 c58a5b3a4fe..ac851b42bed 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@@ -264,6 +264,69 @@ describe('useSessionTileDelegate resumeTile', () => {$sessionTiles.set([])})+ it('preserves a newer completed tile turn when an older authoritative snapshot arrives late', async () => {+ const ownerRoute = { connectionId: 'remote-tile', profile: 'tile-profile', targetProfile: 'backend-tile' }++ const baseline = {+ busy: false,+ messages: [+ { id: 'old-user', parts: [{ type: 'text', text: 'old prompt' }], role: 'user' },+ { id: 'old-answer', parts: [{ type: 'text', text: 'old answer' }], role: 'assistant' }+ ],+ storedSessionId: 'stored-tile'+ }++ const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-tile', 'runtime-tile']]) }+ const states = { current: new Map([['runtime-tile', baseline]]) }++ const update = vi.fn((id, updater) => {+ const next = updater(states.current.get(id))+ states.current.set(id, next)++ return next+ })++ let resolveSnapshot!: (value: unknown) => void+ const snapshot = new Promise(resolve => (resolveSnapshot = resolve))++ vi.mocked(requestGatewayForAgent).mockReset()+ vi.mocked(requestGatewayForAgent).mockReturnValueOnce(snapshot as never)+ $sessionTiles.set([{ ownerRoute, runtimeId: 'runtime-tile', storedSessionId: 'stored-tile' }] as never)+ renderTile(vi.fn(), {+ runtimeIdByStoredSessionIdRef,+ sessionStateByRuntimeIdRef: states,+ updateSessionState: update+ })++ const refreshing = sessionTileDelegate()!.resumeTile('stored-tile', { authoritativeSnapshot: true })+ await vi.waitFor(() => expect(requestGatewayForAgent).toHaveBeenCalledTimes(1))++ const completed = {+ ...baseline,+ messages: [+ ...baseline.messages,+ { id: 'new-user', parts: [{ type: 'text', text: 'new prompt' }], role: 'user' },+ { id: 'new-answer', parts: [{ type: 'text', text: 'new completed answer' }], role: 'assistant' }+ ]+ }++ states.current.set('runtime-tile', completed as never)+ resolveSnapshot({+ messages: [+ { content: 'old prompt', role: 'user', timestamp: 1 },+ { content: 'old answer', role: 'assistant', timestamp: 2 }+ ],+ resumed: 'stored-tile',+ running: false,+ session_id: 'runtime-tile'+ })+ await refreshing++ expect(states.current.get('runtime-tile')?.messages).toContainEqual(completed.messages[2])+ expect(states.current.get('runtime-tile')?.messages).toContainEqual(completed.messages[3])+ $sessionTiles.set([])+ })+it('serializes an authoritative gap snapshot after an omitted-message resume already in flight', async () => {const ownerRoute = { connectionId: 'remote-tile', profile: 'tile-profile', targetProfile: 'backend-tile' }const oldMessage = { id: 'old-user', parts: [{ type: 'text', text: 'old prompt' }], role: 'user' }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 94eccc0ea28..80f927e2d90 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@@ -30,6 +30,7 @@ import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actionimport { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils'import {chatMessageArraysEquivalent,+ overlayConcurrentMessageChanges,preserveLocalPendingTurnMessages,reconcileResumeMessages,resolveResumedBusy,@@ -275,6 +276,7 @@ export function useSessionTileDelegate({$sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.runtimeIdconst cached = existing ? sessionStateByRuntimeIdRef.current.get(existing) : undefined+ const resumeRequestBaselineMessages = cached?.messages ?? []const refreshTranscript = options?.refreshTranscript === trueconst authoritativeSnapshot = options?.authoritativeSnapshot === true@@ -357,7 +359,7 @@ export function useSessionTileDelegate({omit_messages: !authoritativeSnapshot,...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})}),- { requiresMessages: authoritativeSnapshot }+ { requiresMessages: authoritativeSnapshot, scope: owner })},async () => {@@ -407,16 +409,34 @@ 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++ // Another resume/rebind won while this request was in flight. Do not+ // publish the older response into the runtime the tile now owns.+ if (currentBinding && currentBinding !== existing && currentBinding !== runtimeId) {+ return currentBinding+ }+const info = resumed?.infoupdateSessionState(runtimeId,state => {- const previousMessages = state.messages.length > 0 ? state.messages : (cached?.messages ?? [])+ const previousMessages = state.messages.length > 0 ? state.messages : resumeRequestBaselineMessagesconst messages = authoritativeSnapshot? resumed.messages.length > 0- ? mergeTileTranscript(previousMessages, resumed.messages, state.streamId ?? cached?.streamId)+ ? overlayConcurrentMessageChanges(+ mergeTileTranscript(+ resumeRequestBaselineMessages,+ resumed.messages,+ cached?.streamId+ ),+ resumeRequestBaselineMessages,+ previousMessages+ ): previousMessages: previousMessages.length > 0? previousMessagesdiff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.tsindex 6be79923510..9202c1a91fd 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts@@ -11,7 +11,8 @@ import {setChangeEventsAvailable} from '@/store/live-sync'import { markRuntimeGone } from '@/store/runtime-gone'-import { getSessionOwnerHint, requestSessionResume } from '@/store/session'+import { getSessionOwnerHint, knownSessionOwner, ownerLookupSessionRows, requestSessionResume } from '@/store/session'+import type { SessionOwnerScope } from '@/store/session-request-router'import {$sessionTiles,dropSessionState,@@ -129,29 +130,49 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {? deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId: null- const eventMatchesOwner = (owner: { connectionId: string; profile: string } | undefined) =>- Boolean(- owner &&- event.connectionId === owner.connectionId &&- (event.profile?.trim() || 'default') === (owner.profile.trim() || 'default')- )+ const eventProfile = event.profile?.trim() || 'default'+ const eventConnectionId = event.connectionId?.trim() || ''++ const eventMatchesOwner = (owner: SessionOwnerScope) => {+ if (!owner) {+ return false+ }++ if (typeof owner === 'string') {+ // A profile-only owner is the legacy/local pool route. It is safe only+ // for an untagged primary event; an explicitly tagged source must have+ // an exact route so same-named remote profiles remain isolated.+ return !eventConnectionId && eventProfile === (owner.trim() || 'default')+ }++ return eventConnectionId === owner.connectionId.trim() && eventProfile === (owner.profile.trim() || 'default')+ }++ const ownerForStoredSession = (id: string): SessionOwnerScope =>+ getSessionOwnerHint(id, {+ connectionId: eventConnectionId,+ profile: eventProfile+ }) ?? knownSessionOwner(ownerLookupSessionRows(), id)if (storedSessionId && runtimeId === deps.activeSessionIdRef.current) {- const ownerRoute = getSessionOwnerHint(storedSessionId, {- connectionId: event.connectionId || '',- profile: event.profile || 'default'- })+ const ownerRoute = ownerForStoredSession(storedSessionId)if (eventMatchesOwner(ownerRoute)) {- requestSessionResume(storedSessionId, ownerRoute, { authoritativeSnapshot: true })+ requestSessionResume(storedSessionId, ownerRoute && typeof ownerRoute === 'object' ? ownerRoute : undefined, {+ authoritativeSnapshot: true+ })return true}}- const tile = $sessionTiles- .get()- .find(candidate => candidate.runtimeId === runtimeId && eventMatchesOwner(candidate.ownerRoute))+ const tile = $sessionTiles.get().find(candidate => {+ if (candidate.runtimeId !== runtimeId) {+ return false+ }++ return eventMatchesOwner(candidate.ownerRoute ?? ownerForStoredSession(candidate.storedSessionId))+ })if (tile) {void sessionTileDelegate()?.resumeTile(tile.storedSessionId, { authoritativeSnapshot: true }).catch(() => undefined)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsxindex 69294b0f734..5b5f7f3cc5d 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsx@@ -6,7 +6,8 @@ import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/import {$sessionResumeRequest,_resetSessionOwnerHintsForTests,- setSessionOwnerHint+ setSessionOwnerHint,+ setSessions} from '@/store/session'import {$sessionTiles,@@ -19,7 +20,7 @@ import { renderMessageStream } from './test-harness'const replayGap = (sessionId: string,- owner: { connectionId: string; profile: string }+ owner: { connectionId?: string; profile?: string }): RpcEvent => ({...owner,payload: { latest_seq: 41, replay_epoch: 'epoch-next' },@@ -42,6 +43,7 @@ describe('session.replay_gap recovery', () => {beforeEach(() => {$sessionResumeRequest.set(null)$sessionTiles.set([])+ setSessions([])_resetSessionOwnerHintsForTests()setSessionTileDelegate(inertDelegate() as never)})@@ -52,6 +54,7 @@ describe('session.replay_gap recovery', () => {clearSessionDraft('stored-tile')$sessionResumeRequest.set(null)$sessionTiles.set([])+ setSessions([])_resetSessionOwnerHintsForTests()})@@ -82,6 +85,23 @@ describe('session.replay_gap recovery', () => {expect(takeSessionDraft('stored-active').text).toBe('keep typing')})+ it('accepts an untagged primary replay gap for its profile-only local session owner', () => {+ setSessions([{ id: 'stored-active', profile: 'default' }] as never)+ const state = createClientSessionState('stored-active')++ const stream = renderMessageStream('runtime-active', {+ states: new Map([['runtime-active', state]])+ })++ act(() => stream.handleEvent(replayGap('runtime-active', { profile: 'default' })))++ expect($sessionResumeRequest.get()).toMatchObject({+ authoritativeSnapshot: true,+ sessionId: 'stored-active'+ })+ expect($sessionResumeRequest.get()?.ownerRoute).toBeUndefined()+ })+it('re-resumes the affected mounted tile for a gateway snapshot while retaining its owner and draft', async () => {const ownerRoute = {connectionId: 'remote-b',diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.tsindex 8e3986add1f..fa4b04df878 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.test.ts@@ -54,6 +54,42 @@ describe('singleFlightSessionResume', () => {expect(requestGateway).toHaveBeenCalledTimes(2)})+ it('does not coalesce the same stored id across backend owners', async () => {+ let release!: () => void+ const pending = new Promise<void>(resolve => (release = resolve))++ const runA = vi.fn(async () => {+ await pending++ return { session_id: 'runtime-a' }+ })++ const runB = vi.fn(async () => {+ await pending++ return { session_id: 'runtime-b' }+ })++ const a = singleFlightSessionResume('stored-shared', runA, {+ scope: { connectionId: 'backend-a', profile: 'default' }+ })++ const b = singleFlightSessionResume('stored-shared', runB, {+ scope: { connectionId: 'backend-b', profile: 'default' }+ })++ await vi.waitFor(() => {+ expect(runA).toHaveBeenCalledTimes(1)+ expect(runB).toHaveBeenCalledTimes(1)+ })+ release()++ await expect(Promise.all([a, b])).resolves.toEqual([+ { session_id: 'runtime-a' },+ { session_id: 'runtime-b' }+ ])+ })+it('a rejected flight is not cached: the next caller retries', async () => {const run = vi.fn<() => Promise<{ session_id: string }>>()diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.tsindex 9f9a9f41431..9848d830fa1 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts@@ -1,5 +1,7 @@+import { type ProfileScope, profileScopeKey } from '@/api/client'+/**- * Single-flight guard for `session.resume`, keyed by STORED session id.+ * Single-flight guard for `session.resume`, keyed by owner scope + STORED id.** After sleep/wake or a reconnect, many independent surfaces discover the same* dead runtime at once — submit recovery, slash/rewind recovery, tile resumes,@@ -23,9 +25,10 @@ const _inFlightResumeByStoredSessionId = new Map<string, SessionResumeFlight>()export function singleFlightSessionResume<T>(storedSessionId: string,run: () => Promise<T>,- options?: { requiresMessages?: boolean }+ options?: { requiresMessages?: boolean; scope?: ProfileScope }): Promise<T> {- const existing = _inFlightResumeByStoredSessionId.get(storedSessionId)+ const flightKey = JSON.stringify([profileScopeKey(options?.scope), storedSessionId])+ const existing = _inFlightResumeByStoredSessionId.get(flightKey)if (existing && (!options?.requiresMessages || existing.includesMessages)) {return existing.promise as Promise<T>@@ -42,8 +45,8 @@ export function singleFlightSessionResume<T>(const promise = ready.then(run).finally(() => {- if (_inFlightResumeByStoredSessionId.get(storedSessionId) === flight) {- _inFlightResumeByStoredSessionId.delete(storedSessionId)+ if (_inFlightResumeByStoredSessionId.get(flightKey) === flight) {+ _inFlightResumeByStoredSessionId.delete(flightKey)}})@@ -52,7 +55,7 @@ export function singleFlightSessionResume<T>(promise}- _inFlightResumeByStoredSessionId.set(storedSessionId, flight)+ _inFlightResumeByStoredSessionId.set(flightKey, flight)return promise}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.tsindex 6d86b920ccd..617283f2ab6 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@@ -1598,7 +1598,7 @@ export function useSessionActions({: { omit_messages: true }),...(sessionProfile ? { profile: sessionProfile } : {})}),- { requiresMessages: options?.authoritativeSnapshot }+ { requiresMessages: options?.authoritativeSnapshot, scope: sessionOwner }).then(resumed => {resumeRuntimeBaselineMessages =sessionStateByRuntimeIdRef.current.get(resumed.session_id)?.messages ?? resumeRuntimeBaselineMessages