Skip to content

The agent that grows with you

fix(desktop): re-home session tiles on compression tip rotation — one surface per conversation (#98622)

Jean-Dominique Vidjanagni7772e7a332c8
diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
index 20299493ba3..cc2feaad3f9 100644
--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.test.tsx
@@ -357,7 +357,6 @@ describe('useDesktopIntegrations', () => {
expect(window.localStorage.getItem('hermes.desktop.lastSessionId.profile.default')).toBeNull()
expect(window.localStorage.getItem('hermes.desktop.lastRoute.profile.default')).toBeNull()
->>>>>>> a771a14a49 (fix(desktop): stop re-persisting an exhausted session after cleanup (#98467))
})
})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 0547bab333f..67ab9bd2275 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -84,6 +84,7 @@ import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-r
import { requestForSessionProfile, type SessionProfileRoute } from '@/store/session-request-router'
import {
$sessionTiles,
+ clearAllSessionStates,
dropSessionState,
knownOwnerForSession,
publishSessionState,
@@ -496,6 +497,35 @@ describe('active stored-session id rotation routing', () => {
expect($activeSessionStoredIdRotation.get()).toBeNull()
})
+ it('leaves only the rotated main session when handleTransition publishes before route-follow', async () => {
+ const activeSessionIdRef: MutableRefObject<string | null> = { current: 'runtime-ordering' }
+ const selectedStoredSessionIdRef: MutableRefObject<string | null> = { current: 'stored-previous' }
+ const navigate = vi.fn()
+
+ setActiveSessionId('runtime-ordering')
+ setSelectedStoredSessionId('stored-previous')
+ $sessionTiles.set([{ storedSessionId: 'stored-previous' }])
+ render(
+ <StoredIdRotationHarness
+ activeSessionIdRef={activeSessionIdRef}
+ getRoutedStoredSessionId={() => 'stored-previous'}
+ navigate={navigate}
+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}
+ />
+ )
+
+ act(() => {
+ publishSessionState('runtime-ordering', createClientSessionState('stored-previous'))
+ publishSessionState('runtime-ordering', createClientSessionState('stored-next'))
+ })
+
+ await waitFor(() => expect(selectedStoredSessionIdRef.current).toBe('stored-next'))
+ expect($selectedStoredSessionId.get()).toBe('stored-next')
+ expect($sessionTiles.get()).toEqual([])
+
+ clearAllSessionStates()
+ })
+
it('keeps draft on the previous tip when the new tip row is not loaded yet', async () => {
const tipBefore = 'tip-root'
const tipAfter = 'tip-new-unloaded'
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
index 211e5e894e7..d92b29323d3 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
@@ -1,10 +1,11 @@
-import { act, cleanup, render } from '@testing-library/react'
-import { type MutableRefObject, useLayoutEffect } from 'react'
+import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { type MutableRefObject, useLayoutEffect, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { group } from '@/components/pane-shell/tree/model'
import { $layoutTree, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'
import type { ChatMessage } from '@/lib/chat-messages'
+import { $activeGatewayProfile } from '@/store/profile'
import {
$activeSessionStoredIdRotation,
$currentFastMode,
@@ -13,6 +14,7 @@ import {
$currentReasoningEffort,
$currentServiceTier,
$messages,
+ $selectedStoredSessionId,
$sessionStartedAt,
$turnStartedAt,
setActiveSessionId,
@@ -31,12 +33,15 @@ import {
$sessionStates,
$sessionTiles,
clearAllSessionStates,
+ closeSessionTile,
+ openSessionTile,
reconcileBusyStatesOnReconnect,
type SessionTileDelegate,
setSessionTileDelegate,
setZoneParkedTiles
} from '@/store/session-states'
+import { useSessionActions } from './use-session-actions'
import { cachedSessionRow } from './use-session-actions/utils'
import { useSessionStateCache } from './use-session-state-cache'
@@ -51,6 +56,7 @@ interface HarnessProps {
describe('useSessionStateCache — stored-id rotation provenance', () => {
afterEach(() => {
cleanup()
+ clearAllSessionStates()
setActiveSessionId(null)
setActiveSessionStoredIdRotation(null)
setSelectedStoredSessionId(null)
@@ -203,6 +209,128 @@ describe('useSessionStateCache — stored-id rotation provenance', () => {
runtimeSessionId: 'runtime-A'
})
})
+
+ it('re-homes an open tile on a cache-path rotation even when the runtime is background (#98622)', () => {
+ let cache!: Cache
+
+ // Background runtime: the rotation atom stays null, but the tile keyed on
+ // the pre-rotation id must still re-home to the new tip.
+ setActiveSessionId('runtime-B')
+ render(
+ <Harness activeSessionId="runtime-B" onReady={value => (cache = value)} selectedStoredSessionId="stored-B" />
+ )
+
+ act(() => {
+ $sessionTiles.set([{ storedSessionId: 'stored-A' }])
+ cache.updateSessionState('runtime-A', state => state, 'stored-A')
+ cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
+ })
+
+ const tiles = $sessionTiles.get()
+ expect(tiles.find(t => t.storedSessionId === 'stored-A')).toBeUndefined()
+ expect(tiles.find(t => t.storedSessionId === 'stored-A-next')).toBeDefined()
+ })
+
+ it('rekeys the persisted owner profile when its runtime rotates while another profile is visible', () => {
+ let cache!: Cache
+ const profileA = 'rotation-profile-a-98622'
+ const profileB = 'rotation-profile-b-98622'
+ const previousStoredSessionId = 'stored-profile-previous'
+ const nextStoredSessionId = 'stored-profile-next'
+
+ try {
+ act(() => {
+ $activeGatewayProfile.set(profileA)
+ closeSessionTile(previousStoredSessionId)
+ closeSessionTile(nextStoredSessionId)
+ openSessionTile(previousStoredSessionId)
+ $activeGatewayProfile.set(profileB)
+ })
+
+ setActiveSessionId('runtime-visible-b')
+ render(
+ <Harness activeSessionId="runtime-visible-b" onReady={value => (cache = value)} selectedStoredSessionId={null} />
+ )
+
+ act(() => {
+ cache.updateSessionState('runtime-a', state => state, previousStoredSessionId)
+ cache.updateSessionState('runtime-a', state => state, nextStoredSessionId)
+ })
+
+ act(() => {
+ $activeGatewayProfile.set(profileA)
+ })
+ expect($sessionTiles.get().map(tile => tile.storedSessionId)).toEqual([nextStoredSessionId])
+ } finally {
+ act(() => {
+ $activeGatewayProfile.set(profileA)
+ closeSessionTile(previousStoredSessionId)
+ closeSessionTile(nextStoredSessionId)
+ $activeGatewayProfile.set('default')
+ })
+ }
+ })
+
+ it('leaves only the rotated main session when ensureSessionState publishes before route-follow', async () => {
+ let cache!: Cache
+
+ setActiveSessionId('runtime-cache-ordering')
+ setSelectedStoredSessionId('stored-cache-previous')
+ $sessionTiles.set([{ storedSessionId: 'stored-cache-previous' }])
+ render(
+ <RotationHarness
+ activeSessionId="runtime-cache-ordering"
+ onReady={value => (cache = value)}
+ selectedStoredSessionId="stored-cache-previous"
+ />
+ )
+
+ act(() => {
+ cache.updateSessionState('runtime-cache-ordering', state => state, 'stored-cache-previous')
+ cache.updateSessionState('runtime-cache-ordering', state => state, 'stored-cache-next')
+ })
+
+ await waitFor(() => expect($selectedStoredSessionId.get()).toBe('stored-cache-next'))
+ expect($sessionTiles.get()).toEqual([])
+ })
+
+ it('preserves the old tile when a cache update detaches its stored session id', () => {
+ let cache!: Cache
+
+ setActiveSessionId('runtime-detach')
+ $sessionTiles.set([{ storedSessionId: 'stored-detach-old' }])
+ render(
+ <Harness activeSessionId="runtime-detach" onReady={value => (cache = value)} selectedStoredSessionId={null} />
+ )
+
+ act(() => {
+ cache.updateSessionState('runtime-detach', state => state, 'stored-detach-old')
+ cache.updateSessionState('runtime-detach', state => state, null)
+ })
+
+ expect($sessionTiles.get()).toEqual([{ storedSessionId: 'stored-detach-old' }])
+ })
+
+ it('drops the stale tile on a cache-path rotation when the new tip is the main selection (#98622)', () => {
+ let cache!: Cache
+
+ setActiveSessionId('runtime-A')
+ render(
+ <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId="stored-A-next" />
+ )
+
+ act(() => {
+ // The drop decision reads the GLOBAL selection atom, not the harness prop.
+ setSelectedStoredSessionId('stored-A-next')
+ $sessionTiles.set([{ storedSessionId: 'stored-A' }])
+ cache.updateSessionState('runtime-A', state => state, 'stored-A')
+ cache.updateSessionState('runtime-A', state => state, 'stored-A-next')
+ })
+
+ // Main already shows the conversation on the new tip: the tile is dropped
+ // entirely (main OR tile — never both).
+ expect($sessionTiles.get()).toHaveLength(0)
+ })
})
function Harness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessProps) {
@@ -222,6 +350,44 @@ function Harness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessP
return null
}
+function RotationHarness({ activeSessionId, onReady, selectedStoredSessionId }: HarnessProps) {
+ const busyRef = useRef(false)
+ const activeSessionIdRef = useRef<string | null>(activeSessionId)
+ const selectedStoredSessionIdRef = useRef<string | null>(selectedStoredSessionId)
+
+ const cache = useSessionStateCache({
+ activeSessionId,
+ busyRef,
+ selectedStoredSessionId,
+ setAwaitingResponse: () => undefined,
+ setBusy: () => undefined,
+ setMessages: () => undefined
+ })
+
+ useSessionActions({
+ activeSessionId,
+ activeSessionIdRef,
+ busyRef,
+ creatingSessionRef: useRef(false),
+ ensureSessionState: cache.ensureSessionState,
+ getRouteToken: () => 'rotation-test',
+ getRoutedStoredSessionId: () => selectedStoredSessionId,
+ navigate: vi.fn() as never,
+ requestGateway: async () => ({}) as never,
+ resetViewSync: cache.resetViewSync,
+ runtimeIdByStoredSessionIdRef: cache.runtimeIdByStoredSessionIdRef,
+ selectedStoredSessionId,
+ selectedStoredSessionIdRef,
+ sessionStateByRuntimeIdRef: cache.sessionStateByRuntimeIdRef,
+ syncSessionStateToView: cache.syncSessionStateToView,
+ updateSessionState: cache.updateSessionState
+ })
+
+ onReady(cache)
+
+ return null
+}
+
describe('useSessionStateCache — per-session timers', () => {
beforeEach(() => {
// The view-sync flush runs on a real rAF in the browser path; in jsdom we
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
index 348049f0f4e..4ccc6318104 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
@@ -28,6 +28,7 @@ import {
$sessionTiles,
isSessionInForeground,
publishSessionState,
+ rekeySessionTile,
releaseSessionTranscript
} from '@/store/session-states'
@@ -187,6 +188,15 @@ export function useSessionStateCache({
if (existing.storedSessionId && existing.storedSessionId !== storedSessionId) {
runtimeIdByStoredSessionIdRef.current.delete(existing.storedSessionId)
+ // Re-home any open tile keyed on the pre-rotation id (#98622).
+ // Ungated on the active runtime: a background tile's conversation
+ // rotates here too, and its pane would otherwise keep the stale id
+ // (duplicate/differently-titled tabs). Mirrors handleTransition's
+ // rekey, which this path can skip when the state updater is a no-op.
+ if (storedSessionId) {
+ rekeySessionTile(existing.storedSessionId, storedSessionId, sessionId)
+ }
+
// A rotation event needs a real next id — a null/cleared stored id
// is a detach, not a rotation the route-follow effect should chase.
if (
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.ts
index a6bdaf4c20d..051bad96afe 100644
--- a/apps/desktop/src/store/session-states.test.ts
+++ b/apps/desktop/src/store/session-states.test.ts
@@ -43,6 +43,7 @@ import {
orderTilesByTree,
patchSessionTile,
recordSessionEventScope,
+ rekeySessionTile,
releaseSessionTranscript,
requestForOwnedSession,
resetRouteOwnedTileRuntimeBindings,
@@ -1549,3 +1550,149 @@ describe('isSessionRemote (#94640)', () => {
}
})
})
+
+describe('rekeySessionTile (#98622 — pane identity across compression tip rotation)', () => {
+ beforeEach(() => {
+ $activeGatewayProfile.set('default')
+ $layoutTree.set(null)
+ $sessionTiles.set([])
+ $selectedStoredSessionId.set(null)
+ setSessions([])
+ })
+
+ afterEach(() => {
+ $activeGatewayProfile.set('default')
+ $layoutTree.set(null)
+ $sessionTiles.set([])
+ $selectedStoredSessionId.set(null)
+ setSessions([])
+ })
+
+ it('re-keys the open tile to the new tip, preserving placement', () => {
+ $sessionTiles.set([
+ { anchor: 'workspace', before: null, dir: 'right', storedSessionId: 'tip-old' },
+ { storedSessionId: 'unrelated' }
+ ])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ const tiles = $sessionTiles.get()
+ expect(tiles.find(t => t.storedSessionId === 'tip-old')).toBeUndefined()
+ const rekeyed = tiles.find(t => t.storedSessionId === 'tip-new')
+ expect(rekeyed).toMatchObject({ anchor: 'workspace', before: null, dir: 'right' })
+ expect(tiles.find(t => t.storedSessionId === 'unrelated')).toBeDefined()
+ })
+
+ it('keeps a Bot tile when the same stored session is selected in Sessions main', () => {
+ const botTile = {
+ ownerRoute: {
+ connectionId: 'bot-owner',
+ mode: 'remote' as const,
+ profile: 'default'
+ },
+ storedSessionId: 'tip-old',
+ workspaceMode: 'bots' as const,
+ workspaceOwnerKey: 'bot:bot-owner::default'
+ }
+
+ $selectedStoredSessionId.set('tip-new')
+ $sessionTiles.set([botTile])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ expect($sessionTiles.get()).toEqual([{ ...botTile, storedSessionId: 'tip-new' }])
+ })
+
+ it('keeps a tile owned by another backend route beside the Sessions main', () => {
+ const ownerA = { connectionId: 'owner-a', mode: 'remote' as const, profile: 'default' }
+ const ownerB = { connectionId: 'owner-b', mode: 'remote' as const, profile: 'default' }
+
+ setSessions([{ connection_id: 'owner-b', id: 'tip-new', profile: 'default' } as never])
+ $selectedStoredSessionId.set('tip-new')
+ $sessionTiles.set([
+ { ownerRoute: ownerA, storedSessionId: 'tip-old' },
+ { ownerRoute: ownerB, storedSessionId: 'tip-new' }
+ ])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ expect($sessionTiles.get()).toEqual([
+ { ownerRoute: ownerA, storedSessionId: 'tip-new' },
+ { ownerRoute: ownerB, storedSessionId: 'tip-new' }
+ ])
+ })
+
+ it('coalesces a minimal next tile without losing the live previous tile metadata', () => {
+ const ownerRoute = {
+ connectionId: 'connection-a',
+ mode: 'remote' as const,
+ profile: 'writer',
+ targetProfile: 'writer'
+ }
+
+ const previous = {
+ anchor: 'session-tile:anchor',
+ before: 'session-tile:next-sibling',
+ dir: 'left' as const,
+ error: 'resume failed',
+ ownerRoute,
+ runtimeId: 'runtime-live',
+ storedSessionId: 'tip-old',
+ workspaceMode: 'bots' as const,
+ workspaceOwnerKey: 'bot:connection-a::writer',
+ workspaceTabTitle: 'Live bot chat'
+ }
+
+ const next = { storedSessionId: 'tip-new' }
+ const paneId = tilePane('tip-new')
+
+ $layoutTree.set(
+ split('row', [
+ group(['workspace'], { active: 'workspace', id: 'workspace-group' }),
+ group([paneId], { active: paneId, id: 'tile-group' })
+ ])
+ )
+ $sessionTiles.set([previous, next])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ expect($sessionTiles.get()).toEqual([{ ...previous, storedSessionId: 'tip-new' }])
+ expect(findGroupOfPane($layoutTree.get()!, paneId)).toMatchObject({ active: paneId, id: 'tile-group' })
+ })
+
+ it('drops the stale tile when the new tip already has a tile (one pane per conversation)', () => {
+ $sessionTiles.set([{ storedSessionId: 'tip-old' }, { storedSessionId: 'tip-new' }])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ const tiles = $sessionTiles.get()
+ expect(tiles).toHaveLength(1)
+ expect(tiles[0].storedSessionId).toBe('tip-new')
+ })
+
+ it('drops the stale tile when the new tip is already the main selection (main OR tile, never both)', () => {
+ $selectedStoredSessionId.set('tip-new')
+ $sessionTiles.set([{ storedSessionId: 'tip-old' }])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ expect($sessionTiles.get()).toHaveLength(0)
+ })
+
+ it('is a no-op when no tile carries the previous id', () => {
+ $sessionTiles.set([{ storedSessionId: 'other' }])
+
+ rekeySessionTile('tip-old', 'tip-new')
+
+ expect($sessionTiles.get()).toEqual([{ storedSessionId: 'other' }])
+ })
+
+ it('ignores degenerate inputs (empty id, same id)', () => {
+ $sessionTiles.set([{ storedSessionId: 'tip-old' }])
+
+ rekeySessionTile('', 'tip-new')
+ rekeySessionTile('tip-old', 'tip-old')
+
+ expect($sessionTiles.get()).toEqual([{ storedSessionId: 'tip-old' }])
+ })
+})
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 1ea50b81059..951e668873a 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -589,6 +589,12 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessi
})
}
+ // Re-home any open tile keyed on the pre-rotation id to the new tip so the
+ // conversation keeps ONE pane (#98622). Not gated on the active runtime:
+ // a background tile's conversation rotates too, and its pane would
+ // otherwise keep the stale id forever (duplicate/differently-titled tabs).
+ rekeySessionTile(previous.storedSessionId, next.storedSessionId, runtimeId)
+
clearSettled(previous.storedSessionId)
setSessionStalled(previous.storedSessionId, false)
}
@@ -1267,6 +1273,18 @@ function saveTiles(tiles: SessionTile[]) {
$sessionTiles.set(tiles)
}
+function saveTileBucket(bucket: string, tiles: SessionTile[]) {
+ const stored = tiles.map(toStored)
+
+ if (stored.length > 0) {
+ tilesByProfile[bucket] = stored
+ } else {
+ delete tilesByProfile[bucket]
+ }
+
+ persistTiles()
+}
+
// Profile switch: surface the new profile's tiles with runtime ids cleared so
// they re-resume against the now-current gateway. (Fires immediately on
// subscribe; harmless — the init value already matches.) A secondary window
@@ -1281,6 +1299,227 @@ export function patchSessionTile(storedSessionId: string, patch: Partial<Session
saveTiles($sessionTiles.get().map(t => (t.storedSessionId === storedSessionId ? { ...t, ...patch } : t)))
}
+function isSessionOwnerRoute(value: SessionOwnerScope): value is SessionOwnerRoute {
+ return Boolean(value && typeof value === 'object' && 'connectionId' in value)
+}
+
+function sameSessionOwner(left: SessionOwnerScope, right: SessionOwnerScope): boolean {
+ if (isSessionOwnerRoute(left) && isSessionOwnerRoute(right)) {
+ return (
+ left.connectionId.trim() === right.connectionId.trim() &&
+ normalizeProfileKey(left.profile) === normalizeProfileKey(right.profile) &&
+ normalizeProfileKey(left.targetProfile ?? left.profile) === normalizeProfileKey(right.targetProfile ?? right.profile)
+ )
+ }
+
+ if (typeof left === 'string' && typeof right === 'string') {
+ return normalizeProfileKey(left) === normalizeProfileKey(right)
+ }
+
+ return false
+}
+
+function tileWorkspaceMode(tile: SessionTile): WorkspaceMode {
+ return tile.workspaceMode ?? 'sessions'
+}
+
+function tilesShareOwner(left: SessionTile, right: SessionTile): boolean {
+ if (left.workspaceMode && right.workspaceMode && left.workspaceMode !== right.workspaceMode) {
+ return false
+ }
+
+ const workspaceMode = left.workspaceMode ?? right.workspaceMode ?? 'sessions'
+
+ if (workspaceMode === 'bots') {
+ if (left.workspaceOwnerKey && right.workspaceOwnerKey) {
+ return left.workspaceOwnerKey === right.workspaceOwnerKey
+ }
+
+ if (left.ownerRoute && right.ownerRoute) {
+ return sameSessionOwner(left.ownerRoute, right.ownerRoute)
+ }
+
+ return true
+ }
+
+ if (left.ownerRoute && right.ownerRoute) {
+ return sameSessionOwner(left.ownerRoute, right.ownerRoute)
+ }
+
+ return true
+}
+
+function tileBelongsToMain(
+ tile: SessionTile,
+ selectedStoredSessionId: string,
+ tileProfile = profileKey()
+): boolean {
+ if (tileWorkspaceMode(tile) === 'bots') {
+ return false
+ }
+
+ const mainOwner = knownSessionOwner(ownerLookupSessionRows(), selectedStoredSessionId) ?? profileKey()
+
+ if (tile.ownerRoute) {
+ return isSessionOwnerRoute(mainOwner) && sameSessionOwner(tile.ownerRoute, mainOwner)
+ }
+
+ return typeof mainOwner === 'string' && normalizeProfileKey(mainOwner) === normalizeProfileKey(tileProfile)
+}
+
+function mergeSessionTile(previous: SessionTile, next: SessionTile, storedSessionId: string): SessionTile {
+ const merged: SessionTile = { ...previous, storedSessionId }
+
+ if (next.anchor !== undefined) {
+ merged.anchor = next.anchor
+ }
+
+ if (next.before !== undefined) {
+ merged.before = next.before
+ }
+
+ if (next.dir !== undefined) {
+ merged.dir = next.dir
+ }
+
+ if (next.error !== undefined) {
+ merged.error = next.error
+ }
+
+ if (next.ownerRoute !== undefined) {
+ merged.ownerRoute = next.ownerRoute
+ }
+
+ if (next.runtimeId !== undefined) {
+ merged.runtimeId = next.runtimeId
+ }
+
+ if (next.workspaceMode !== undefined) {
+ merged.workspaceMode = next.workspaceMode
+ }
+
+ if (next.workspaceOwnerKey !== undefined) {
+ merged.workspaceOwnerKey = next.workspaceOwnerKey
+ }
+
+ if (next.workspaceTabTitle !== undefined) {
+ merged.workspaceTabTitle = next.workspaceTabTitle
+ }
+
+ return merged
+}
+
+function rekeyTileList(
+ tiles: SessionTile[],
+ tileProfile: string,
+ previousStoredSessionId: string,
+ nextStoredSessionId: string
+): SessionTile[] | null {
+ const stale = tiles.find(t => t.storedSessionId === previousStoredSessionId)
+
+ if (!stale) {
+ return null
+ }
+
+ const selectedStoredSessionId = $selectedStoredSessionId.get()
+
+ const mainOwnsRotation =
+ Boolean(selectedStoredSessionId) &&
+ (selectedStoredSessionId === previousStoredSessionId || selectedStoredSessionId === nextStoredSessionId) &&
+ tileBelongsToMain(stale, selectedStoredSessionId!, tileProfile)
+
+ const nextTile = tiles.find(t => t.storedSessionId === nextStoredSessionId && tilesShareOwner(stale, t))
+
+ if (mainOwnsRotation) {
+ return tiles.filter(t => t !== stale)
+ }
+
+ if (nextTile) {
+ return tiles
+ .map(t => (t === nextTile ? mergeSessionTile(stale, t, nextStoredSessionId) : t))
+ .filter(t => t !== stale)
+ }
+
+ return tiles.map(t => (t === stale ? { ...t, storedSessionId: nextStoredSessionId } : t))
+}
+
+function ownerProfileKey(owner: SessionOwnerScope): string | undefined {
+ if (isSessionOwnerRoute(owner)) {
+ return normalizeProfileKey(owner.profile)
+ }
+
+ return typeof owner === 'string' ? normalizeProfileKey(owner) : undefined
+}
+
+/**
+ * Re-home an open tile after auto-compression rotates the conversation's stored
+ * id (#98622). Without this, the tile stays keyed on the pre-rotation id while
+ * the rest of the app (selection, route, composer) moves to the new tip — the
+ * same conversation then renders as two tabs (identical or differently-titled,
+ * since each tip is titled independently).
+ *
+ * Placement fields (`dir`/`anchor`/`before`) are preserved so the pane mirror
+ * re-docks the re-keyed tile in the same slot; pane-mirror's wanted-set diff
+ * disposes the old pane and adopts the new one from this single change.
+ *
+ * Main-vs-tile reconciliation is scoped to the same Sessions workspace/owner.
+ * Bot tiles and tiles on distinct backend routes remain independent surfaces.
+ * When a rotation arrives for a background runtime, the persisted profile bucket
+ * owning that runtime is updated without replacing the active profile's atom.
+ */
+export function rekeySessionTile(
+ previousStoredSessionId: string,
+ nextStoredSessionId: string,
+ runtimeSessionId?: string
+) {
+ if (!previousStoredSessionId || !nextStoredSessionId || previousStoredSessionId === nextStoredSessionId) {
+ return
+ }
+
+ const visibleTiles = $sessionTiles.get()
+
+ if (visibleTiles.some(t => t.storedSessionId === previousStoredSessionId)) {
+ const nextTiles = rekeyTileList(visibleTiles, profileKey(), previousStoredSessionId, nextStoredSessionId)
+
+ if (nextTiles) {
+ saveTiles(nextTiles)
+ }
+
+ return
+ }
+
+ const candidateBuckets = Object.entries(tilesByProfile).filter(([, tiles]) =>
+ tiles.some(t => t.storedSessionId === previousStoredSessionId)
+ )
+
+ if (candidateBuckets.length === 0) {
+ return
+ }
+
+ const owner =
+ (runtimeSessionId ? knownOwnerForSession(runtimeSessionId) : undefined) ??
+ knownSessionOwner(ownerLookupSessionRows(), previousStoredSessionId)
+
+ const resolvedProfile = ownerProfileKey(owner)
+
+ const candidate = resolvedProfile
+ ? candidateBuckets.find(([bucket]) => bucket === resolvedProfile)
+ : candidateBuckets.length === 1
+ ? candidateBuckets[0]
+ : undefined
+
+ if (!candidate) {
+ return
+ }
+
+ const [bucket, storedTiles] = candidate
+ const nextTiles = rekeyTileList(storedTiles, bucket, previousStoredSessionId, nextStoredSessionId)
+
+ if (nextTiles) {
+ saveTileBucket(bucket, nextTiles)
+ }
+}
+
export function sessionTileOwnerRoute(storedSessionId: string): SessionOwnerRoute | undefined {
return $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.ownerRoute
}