The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): one conversation never opens as two tabs after compaction
Alonso202997b51ddf
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.tsindex 03179c05b83..3d1bcf26309 100644--- a/apps/desktop/src/store/session-states.test.ts+++ b/apps/desktop/src/store/session-states.test.ts@@ -331,6 +331,24 @@ describe('SessionTile workspace scope', () => {expect(focusOpenSession('bot-chat', scope)).toBe('tile')})+ it('fronts the existing tab when compaction rotated the tip id — never a duplicate', () => {+ // The tile was opened when seg-2 was the tip; the conversation has since+ // rotated to seg-3 (projected row carries the full chain). Opening the+ // new tip must front that tile, not open the same chat twice.+ setSessions([+ { _lineage_ids: ['seg-1', 'seg-2', 'seg-3'], _lineage_root_id: 'seg-1', id: 'seg-3' } as never+ ])+ openSessionTile('seg-2')++ expect(focusOpenSession('seg-3')).toBe('tile')+ expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['seg-2'])++ // The open path dedupes through the same lineage test.+ openSessionTile('seg-3')+ expect($sessionTiles.get().map(t => t.storedSessionId)).toEqual(['seg-2'])+ setSessions([])+ })+it('keeps Bot tabs while a profile publication swaps the Sessions bucket', () => {const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::writer' }diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 699c4ce35c3..ec04175a617 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1406,7 +1406,9 @@ export function openSessionTile(markSessionRead(storedSessionId)ackStoredSessionId(storedSessionId)- if (workspaceScope.workspaceMode === 'sessions' && storedSessionId === $selectedStoredSessionId.get()) {+ const aliases = lineageAliases(storedSessionId, $sessions.get())++ if (workspaceScope.workspaceMode === 'sessions' && aliases.includes($selectedStoredSessionId.get() ?? '')) {return}@@ -1414,7 +1416,7 @@ export function openSessionTile(const workspaceOwnerKey = workspaceScope.workspaceMode === 'bots' ? workspaceScope.workspaceOwnerKey : undefined- if (!tiles.some(t => t.storedSessionId === storedSessionId)) {+ if (!tiles.some(t => aliases.includes(t.storedSessionId))) {saveTiles([...tiles,{@@ -1510,8 +1512,16 @@ export function focusOpenSession(storedSessionId: string,workspaceScope: SessionTileWorkspaceScope = { workspaceMode: 'sessions' }): 'main' | 'tile' | null {- if ($sessionTiles.get().some(t => t.storedSessionId === storedSessionId)) {- const paneId = `${TILE_PANE_PREFIX}${storedSessionId}`+ // Compression rotates a conversation's tip id while tiles stay keyed by+ // whichever segment id they were opened with. An exact-id test right after+ // a rotation said "not open" for a conversation that IS on screen, and+ // callers opened the same chat in a second tab. Match any id of the+ // lineage instead, and front the tile under ITS key.+ const aliases = lineageAliases(storedSessionId, $sessions.get())+ const tile = $sessionTiles.get().find(t => aliases.includes(t.storedSessionId))++ if (tile) {+ const paneId = `${TILE_PANE_PREFIX}${tile.storedSessionId}`revealTreePane(paneId) // un-dismiss + adopt + front in its groupconst tree = $layoutTree.get()const group = tree ? findGroupOfPane(tree, paneId) : null@@ -1525,7 +1535,7 @@ export function focusOpenSession(// Already the main session: front the workspace tab and drop tile focus so// the readouts + sidebar highlight come home (a no-op when main is focused).- if (workspaceScope.workspaceMode === 'sessions' && storedSessionId === $selectedStoredSessionId.get()) {+ if (workspaceScope.workspaceMode === 'sessions' && aliases.includes($selectedStoredSessionId.get() ?? '')) {revealTreePane('workspace')noteActiveTreeGroup(null)diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex c1c1285c442..479c7bfc522 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -45,10 +45,12 @@ import {keepFailedProfileMeta,knownSessionOwner,knownSessionProfile,+ lineageAliases,mergeSessionPage,rememberedSessionProfile,resolveComposerSessionKey,sessionBelongsToProfile,+ sessionMatchesStoredId,sessionOwnerRouteFromRow,sessionPinId,setComposerSelectionOwner,@@ -366,6 +368,27 @@ describe('sessionPinId', () => {})})+describe('lineageAliases across a deep compression chain', () => {+ it('aliases every segment, intermediates included', () => {+ // The projected row carries the full chain: a tile or route can hold a+ // MIDDLE segment's id from when IT was the tip.+ const rows = [+ session({ _lineage_ids: ['root', 'mid', 'tip'], _lineage_root_id: 'root', id: 'tip' })+ ]++ expect(lineageAliases('mid', rows).sort()).toEqual(['mid', 'root', 'tip'])+ expect(lineageAliases('tip', rows).sort()).toEqual(['mid', 'root', 'tip'])+ expect(sessionMatchesStoredId(rows[0], 'mid')).toBe(true)+ })++ it('keeps the root/tip pairing for gateways without the field', () => {+ const rows = [session({ _lineage_root_id: 'root', id: 'tip' })]++ expect(lineageAliases('tip', rows).sort()).toEqual(['root', 'tip'])+ expect(lineageAliases('unknown', rows)).toEqual(['unknown'])+ })+})+describe('resolveComposerSessionKey', () => {it('keeps the lineage root across compression tip rotation', () => {const tipBefore = '20260720_062637_ad96b3'diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex a90555bc24a..39e91c32cc1 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -359,16 +359,19 @@ export const sessionPinId = (session: Pick<SessionInfo, '_lineage_root_id' | 'id* the live id or the stable lineage root (see sessionPinId). The one place the* "same conversation across compression" test lives. */export const sessionMatchesStoredId = (- session: Pick<SessionInfo, '_lineage_root_id' | 'id'>,+ session: Pick<SessionInfo, '_lineage_ids' | '_lineage_root_id' | 'id'>,storedSessionId: string-): boolean => session.id === storedSessionId || session._lineage_root_id === storedSessionId+): boolean =>+ session.id === storedSessionId ||+ session._lineage_root_id === storedSessionId ||+ Boolean(session._lineage_ids?.includes(storedSessionId))// Alias lookup, memoized per sessions-list reference. `lineageAliases` runs// per cached session state per status projection per message delta — an// O(sessions) scan there multiplies out to states × sessions × ~30Hz per busy// session, which is what made a populated recents list drag every stream. The// list is replaced wholesale (never mutated), so its reference is the cache key.-type LineageRow = Pick<SessionInfo, '_lineage_root_id' | 'id'>+type LineageRow = Pick<SessionInfo, '_lineage_ids' | '_lineage_root_id' | 'id'>const lineageIndexBySessions = new WeakMap<readonly LineageRow[], Map<string, string[]>>()function lineageIndex(sessions: readonly LineageRow[]): Map<string, string[]> {@@ -398,6 +401,21 @@ function lineageIndex(sessions: readonly LineageRow[]): Map<string, string[]> {add(session._lineage_root_id, session.id)add(session._lineage_root_id, session._lineage_root_id)}++ // Chains three+ segments deep: the projected row carries every id the+ // conversation has answered to, so a surface keyed to a MIDDLE segment+ // (it was the tip when the surface opened) still aliases to the rest.+ // Without this, only tip↔root connect and such a surface reads as a+ // different conversation — one chat open twice after a compaction.+ const ids = session._lineage_ids++ if (ids && ids.length > 1) {+ for (const a of ids) {+ for (const b of ids) {+ add(a, b)+ }+ }+ }}lineageIndexBySessions.set(sessions, index)diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 41fa24118a1..5402baa7462 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -508,6 +508,10 @@ export interface SessionInfo {* continuation tip. Stable across compressions — used as the durable id for* pins so a pinned conversation survives auto-compression. */_lineage_root_id?: null | string+ /** Every id on the compression chain (root, intermediates, tip) when this+ * entry is a projected continuation tip. Intermediates matter: a persisted+ * tile or route can hold a middle segment's id from when IT was the tip. */+ _lineage_ids?: null | string[]input_tokens: number/** Spend for the session, straight off the `sessions` row. `actual` is set* when the provider reported a price; `estimated` is our own pricing-tablediff --git a/hermes_state.py b/hermes_state.pyindex f6a928f4319..fa79f615462 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -11556,8 +11556,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)return f"{base} #{max_num + 1}"- def get_compression_tip(self, session_id: str) -> Optional[str]:- """Walk the compression-continuation chain forward and return the tip.+ def get_compression_chain(self, session_id: str) -> List[str]:+ """Walk the compression-continuation chain forward and return every id.++ Root-first order, ending at the tip; ``[session_id]`` when no+ continuation exists. ``get_compression_tip`` is this walk's last+ element — kept as the single implementation so the two can never+ disagree about what the chain is.A compression continuation is a child of a session whose``end_reason = 'compression'``. Older builds tried to distinguish@@ -11578,6 +11583,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)continuation exists."""current = session_id+ chain = [current] if current else []seen = {current} if current else set()# Bound the walk defensively — compression chains this deep are# pathological and shouldn't happen in practice. 100 = plenty.@@ -11608,13 +11614,21 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin))row = cursor.fetchone()if row is None:- return current+ return chainchild_id = row["id"]if not child_id or child_id in seen:- return current+ return chainseen.add(child_id)current = child_id- return current+ chain.append(child_id)+ return chain++ def get_compression_tip(self, session_id: str) -> Optional[str]:+ """The live tip of a compression-continuation chain (see+ ``get_compression_chain`` for the walk's semantics). Returns the input+ id when no continuation exists."""+ chain = self.get_compression_chain(session_id)+ return chain[-1] if chain else session_id# Columns excluded from compact_rows projections: only the payload-heavy# blob no list consumer renders. Everything else — including gateway@@ -11992,12 +12006,15 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)# call per compression root. Batch that half instead: resolve# every tip id first, then fetch all tip rows in a single query.tip_ids_by_root: Dict[str, str] = {}+ chain_by_root: Dict[str, List[str]] = {}for s in sessions:if s.get("end_reason") != "compression":continue- tip_id = self.get_compression_tip(s["id"])+ chain = self.get_compression_chain(s["id"])+ tip_id = chain[-1] if chain else s["id"]if tip_id != s["id"]:tip_ids_by_root[s["id"]] = tip_id+ chain_by_root[s["id"]] = chaintip_rows = (self._get_session_rich_rows_batch(@@ -12025,6 +12042,13 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)if key in tip_row:merged[key] = tip_row[key]merged["_lineage_root_id"] = s["id"]+ # Every id on the chain, intermediates included. Root and tip+ # alone are not enough client-side: a persisted tile or route+ # can hold a MIDDLE segment's id (it was the tip when opened,+ # then rotated again), and with only the root/tip pair such a+ # surface can no longer prove it names this conversation —+ # which is how one chat ends up open twice after compaction.+ merged["_lineage_ids"] = chain_by_root.get(s["id"]) or Noneprojected.append(merged)sessions = projecteddiff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.pyindex e3b09c97de0..b0abbd37a5b 100644--- a/tests/test_hermes_state.py+++ b/tests/test_hermes_state.py@@ -2752,6 +2752,36 @@ class TestCompressionChainProjection:assert db.get_compression_tip("mid1") == "tip1"assert db.get_compression_tip("tip1") == "tip1"+ def test_get_compression_chain_lists_every_segment(self, db):+ """Root-first order, intermediates included; a chainless id is its+ own one-element chain."""+ import time as _time+ self._build_compression_chain(db, _time.time() - 3600)+ assert db.get_compression_chain("root1") == ["root1", "mid1", "tip1"]+ assert db.get_compression_chain("mid1") == ["mid1", "tip1"]+ assert db.get_compression_chain("tip1") == ["tip1"]+ db.create_session("solo_chain", "cli")+ db._conn.commit()+ assert db.get_compression_chain("solo_chain") == ["solo_chain"]++ def test_list_serves_full_lineage_ids_for_projected_rows(self, db):+ """The projected tip row must carry every chain id. Root and tip+ alone are not enough client-side: a persisted tile or route can hold+ a MIDDLE segment's id (it was the tip when opened), and without the+ intermediates that surface cannot prove it names this conversation —+ which is how one chat ends up open twice after a compaction."""+ import time as _time+ self._build_compression_chain(db, _time.time() - 3600)+ db.create_session("solo", "cli")+ db.append_message("solo", "user", "standalone")+ db._conn.commit()++ sessions = db.list_sessions_rich(source="cli", limit=20)+ tip_row = next(s for s in sessions if s["id"] == "tip1")+ assert tip_row["_lineage_ids"] == ["root1", "mid1", "tip1"]+ solo_row = next(s for s in sessions if s["id"] == "solo")+ assert solo_row.get("_lineage_ids") is None+def test_list_surfaces_tip_for_compressed_root(self, db):diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 85680b65c62..16d144f35a5 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -15771,6 +15771,7 @@ def _project_tree_row(r: dict) -> dict:return {"id": r.get("id"),"_lineage_root_id": r.get("_lineage_root_id"),+ "_lineage_ids": r.get("_lineage_ids"),# The sidebar nests branch/fork sessions under their parent# (flattenSessionsWithBranches keys on this); without it, lane rows can't# draw the └─ connector the flat Recents list shows.