The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep the session-list merge/dedup/order pipeline invariant-consistent
Tekniumdac5f86313a5
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsxindex 7cab99808a5..6377cd75b8f 100644--- a/apps/desktop/src/app/chat/sidebar/index.tsx+++ b/apps/desktop/src/app/chat/sidebar/index.tsx@@ -161,7 +161,7 @@ import {} from './projects'import { WorktreeDialog } from './projects/worktree-dialog'import { SidebarBlankState, SidebarPinnedEmptyState, SidebarSessionSkeletons } from './section-states'-import { buildSessionByAnyId } from './session-index'+import { buildSessionByAnyId, resolvePinnedSessions } from './session-index'import { SidebarSessionsSection, VIRTUALIZE_THRESHOLD } from './sessions-section'import { CONTEXT_SPLIT_KIT, SplitSubmenu } from './split-submenu'@@ -510,21 +510,18 @@ export function ChatSidebar({[visibleSessions, cronSessions, messagingSessions])- const pinnedSessions = useMemo(() => {- const seen = new Set<string>()- const out: SessionInfo[] = []-- for (const pinId of pinnedSessionIds) {- const session = sessionByAnyId.get(pinId)-- if (session && !seen.has(session.id)) {- seen.add(session.id)- out.push(session)- }- }-- return out- }, [pinnedSessionIds, sessionByAnyId])+ // Local pin ids first (hand-picked order), then server-flagged pins the+ // local set doesn't know about — a backend `pinned=1` row must never be+ // invisible just because localStorage is cold or was clobbered (#85969).+ const pinnedSessions = useMemo(+ () =>+ resolvePinnedSessions(pinnedSessionIds, sessionByAnyId, [+ ...visibleSessions,+ ...cronSessions,+ ...messagingSessions+ ]),+ [pinnedSessionIds, sessionByAnyId, visibleSessions, cronSessions, messagingSessions]+ )// Every id a pin is reachable under: the raw stored ids, plus BOTH identities// of each session we resolved one to. A pin is stored on the durable lineagediff --git a/apps/desktop/src/app/chat/sidebar/order.ts b/apps/desktop/src/app/chat/sidebar/order.tsindex 625cb083f31..0796b55ddff 100644--- a/apps/desktop/src/app/chat/sidebar/order.ts+++ b/apps/desktop/src/app/chat/sidebar/order.ts@@ -39,10 +39,7 @@ export function reconcileFreshFirst(currentIds: string[], orderIds: string[]): s// self-perpetuate through reconcile, and duplicate live ids (e.g. the same// repo surfacing under several projects) must not be written back into the// saved order — either one paints as duplicate headers (#73314).- return mergeFreshByPosition(- [...new Set(currentIds)],- [...new Set(orderIds.filter(id => current.has(id)))]- )+ return mergeFreshByPosition([...new Set(currentIds)], [...new Set(orderIds.filter(id => current.has(id)))])}export function resolveManualSessionOrderIds(currentIds: string[], orderIds: string[], manual: boolean): string[] {diff --git a/apps/desktop/src/app/chat/sidebar/session-index.test.ts b/apps/desktop/src/app/chat/sidebar/session-index.test.tsindex bee60a64603..a63b484b577 100644--- a/apps/desktop/src/app/chat/sidebar/session-index.test.ts+++ b/apps/desktop/src/app/chat/sidebar/session-index.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'import type { SessionInfo } from '@/types/hermes'-import { buildSessionByAnyId } from './session-index'+import { buildSessionByAnyId, resolvePinnedSessions } from './session-index'const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo@@ -46,3 +46,52 @@ describe('buildSessionByAnyId', () => {expect(index.get('root')?.id).toBe('root')})})++describe('resolvePinnedSessions', () => {+ it('resolves local pin ids in their hand-picked order', () => {+ const sessions = [row('a'), row('b'), row('c')]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions(['c', 'a'], index, sessions).map(s => s.id)).toEqual(['c', 'a'])+ })++ it('falls back to the server pinned flag when localStorage is cold (#85969)', () => {+ // Backend says pinned=1 but the local pin set is empty (cold localStorage+ // after a reload, pin from another client, clobbered persist). Every other+ // list filters the row out as pinned, so if the Pinned section can't+ // resolve it the session vanishes from the sidebar entirely.+ const sessions = [row('a', { pinned: true }), row('b', { pinned: false })]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions([], index, sessions).map(s => s.id)).toEqual(['a'])+ })++ it('does not duplicate a session held both locally and server-side', () => {+ const sessions = [row('a', { pinned: true })]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions(['a'], index, sessions).map(s => s.id)).toEqual(['a'])+ })++ it('does not duplicate a server-pinned row whose pin is stored on the lineage root', () => {+ const sessions = [row('tip', { _lineage_root_id: 'root', pinned: true })]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions(['root'], index, sessions).map(s => s.id)).toEqual(['tip'])+ })++ it('keeps locally pinned rows ahead of server-only fallback pins', () => {+ const sessions = [row('server-pin', { pinned: true }), row('local-pin')]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions(['local-pin'], index, sessions).map(s => s.id)).toEqual(['local-pin', 'server-pin'])+ })++ it('ignores rows from a backend that predates the pinned flag', () => {+ // `pinned` undefined means "no opinion", never "pinned".+ const sessions = [row('a')]+ const index = buildSessionByAnyId(sessions, [], [])++ expect(resolvePinnedSessions([], index, sessions)).toEqual([])+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/session-index.ts b/apps/desktop/src/app/chat/sidebar/session-index.tsindex 486d977366b..be353fe6537 100644--- a/apps/desktop/src/app/chat/sidebar/session-index.ts+++ b/apps/desktop/src/app/chat/sidebar/session-index.ts@@ -31,3 +31,46 @@ export function buildSessionByAnyId(return map}++/**+ * Resolve the Pinned section's rows: the locally stored pin ids first (in the+ * user's hand-picked order), then any row the SERVER flags `pinned` that the+ * local set doesn't know about yet.+ *+ * The local set (`$pinnedSessionIds` in localStorage) is a UI-ordering hint,+ * not the source of truth — `sessions.pinned` in the backend's state.db is.+ * When the two disagree (cold localStorage after a reload, a pin made from+ * another client, a persist that never landed), every other sidebar list+ * filters the session out as "pinned" while the Pinned section — resolving+ * only local ids — renders empty, so the conversation vanishes from the+ * sidebar entirely (#85969). Falling back to the row flag keeps the invariant:+ * a session the backend says is pinned is always reachable from the Pinned+ * section, whatever the local cache holds. session-pin-sync then adopts the+ * pin into the local set on its next reconcile, restoring ordering control.+ */+export function resolvePinnedSessions(+ pinnedSessionIds: readonly string[],+ sessionByAnyId: Map<string, SessionInfo>,+ allSessions: readonly SessionInfo[]+): SessionInfo[] {+ const seen = new Set<string>()+ const out: SessionInfo[] = []++ for (const pinId of pinnedSessionIds) {+ const session = sessionByAnyId.get(pinId)++ if (session && !seen.has(session.id)) {+ seen.add(session.id)+ out.push(session)+ }+ }++ for (const session of allSessions) {+ if (session.pinned === true && !seen.has(session.id)) {+ seen.add(session.id)+ out.push(session)+ }+ }++ return out+}diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex be1ea4adbcc..9a80b923162 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -276,8 +276,9 @@ describe('mergeSessionPage', () => {const previous = [session({ id: 'c', last_active: 100 }),session({ id: 'b', last_active: 200 }),- session({ id: 'a', last_active: 300 }),+ session({ id: 'a', last_active: 300 })]+// Server returns A (fresh page, order=recent), omits B and C (min_messages=1)const incoming = [session({ id: 'a', last_active: 300, message_count: 2 })]@@ -290,19 +291,57 @@ describe('mergeSessionPage', () => {it('places a very recent survivor in correct position among incoming sessions', () => {// A survivor with last_active between two incoming sessions should be// interleaved, not prepended as a block.- const previous = [- session({ id: 'survivor', last_active: 150 }),- session({ id: 'old', last_active: 50 }),- ]- const incoming = [- session({ id: 'newest', last_active: 200 }),- session({ id: 'older', last_active: 100 }),- ]+ const previous = [session({ id: 'survivor', last_active: 150 }), session({ id: 'old', last_active: 50 })]++ const incoming = [session({ id: 'newest', last_active: 200 }), session({ id: 'older', last_active: 100 })]const merged = mergeSessionPage(previous, incoming, ['survivor'])// survivor (150) should be between newest (200) and older (100)expect(merged.map(s => s.id)).toEqual(['newest', 'survivor', 'older'])+ })++ it('keeps a survivor whose optimistic last_active outranks the whole page on top', () => {+ // touchSessionActivity stamps last_active on user-send before the server+ // sees the message; that bump must place the survivor by its FRESH time.+ const previous = [session({ id: 'typing', last_active: 900 }), session({ id: 'settled', last_active: 100 })]++ const incoming = [session({ id: 'settled', last_active: 100, message_count: 3 })]++ const merged = mergeSessionPage(previous, incoming, ['typing'])++ expect(merged.map(s => s.id)).toEqual(['typing', 'settled'])+ })++ it('falls back to started_at for survivors that have no last_active yet', () => {+ // A brand-new session (no persisted message) carries last_active 0; the+ // backend's effective-recency key falls back to started_at, so we must+ // too, or a fresh draft sinks to the very bottom of the sidebar.+ const previous = [+ session({ id: 'draft', last_active: 0, started_at: 500 }),+ session({ id: 'other', last_active: 400 })+ ]++ const incoming = [session({ id: 'other', last_active: 400, message_count: 2 })]++ const merged = mergeSessionPage(previous, incoming, ['draft'])++ expect(merged.map(s => s.id)).toEqual(['draft', 'other'])+ })++ it('interleaves against the title-preserving merged rows, not the raw incoming page', () => {+ // The optimistic last_active carried onto an incoming row must count for+ // its position in the interleave: previous knows 'bumped' was touched at+ // 300 even though the server page still reports 100.+ const previous = [session({ id: 'survivor', last_active: 200 }), session({ id: 'bumped', last_active: 300 })]++ const incoming = [session({ id: 'bumped', last_active: 100, message_count: 2 })]++ const merged = mergeSessionPage(previous, incoming, ['survivor'])++ expect(merged.map(s => s.id)).toEqual(['bumped', 'survivor'])+ expect(merged[0]?.last_active).toBe(300)+ })})describe('touchSessionActivity', () => {diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 36c872cc44e..8b882b6f66e 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -443,22 +443,20 @@ export function mergeSessionPage(// Survivors carry their old relative positions from `previous`, which can be// stale — the server page is the fresh `order=recent` truth. Sort survivors- // by the same effective-recency key the backend sorts by (last_active, then- // started_at, then id) and interleave them into the title-preserving merged+ // by the same effective-recency key the backend sorts by (last_active with a+ // started_at fallback) and interleave them into the title-preserving merged// rows so a retained session lands where recency puts it instead of the// whole set forming a stale block at the top of the sidebar (fixes #47203).- const recency = (session: SessionInfo): number => session.last_active || session.started_at || 0+ // Ties keep the survivor first, matching the old prepend behavior.+ const recency = (session: SessionInfo): number => Math.max(session.last_active || 0, session.started_at || 0)- const bySessionRecency = (a: SessionInfo, b: SessionInfo): number =>- recency(b) - recency(a) || (b.started_at ?? 0) - (a.started_at ?? 0) || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)-- const sortedSurvivors = [...survivors].sort(bySessionRecency)+ const sortedSurvivors = [...survivors].sort((a, b) => recency(b) - recency(a))const interleaved: SessionInfo[] = []let survivorIndex = 0let mergedIndex = 0while (survivorIndex < sortedSurvivors.length && mergedIndex < merged.length) {- if (bySessionRecency(sortedSurvivors[survivorIndex], merged[mergedIndex]) <= 0) {+ if (recency(sortedSurvivors[survivorIndex]) >= recency(merged[mergedIndex])) {interleaved.push(sortedSurvivors[survivorIndex++])} else {interleaved.push(merged[mergedIndex++])