The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop re-entrant pin-sync reconcile from overflowing nanostores
dcdexhome0599b66de77e
diff --git a/apps/desktop/src/store/session-pin-sync.test.ts b/apps/desktop/src/store/session-pin-sync.test.tsindex 634b2b09be6..d77d9d68d5b 100644--- a/apps/desktop/src/store/session-pin-sync.test.ts+++ b/apps/desktop/src/store/session-pin-sync.test.ts@@ -14,6 +14,7 @@ vi.mock('@/hermes', () => ({}))import { $pinnedSessionIds } from '@/store/layout'+import { $activeGatewayProfile } from '@/store/profile'import { $sessions } from '@/store/session'import { resetSessionPinMirror, watchSessionPins } from './session-pin-sync'@@ -290,4 +291,33 @@ describe('watchSessionPins remote pull', () => {expect($pinnedSessionIds.get()).toContain('failed')expect(patch).toHaveBeenCalledWith('failed', true, undefined)})++ it('does not oscillate when two profiles share a session id with conflicting pins', async () => {+ // The cross-profile list can hold the same durable id twice with opposite+ // `pinned` flags (copied/imported profile DBs). A profile-blind pull would+ // pin then unpin the id in one pass and re-fire reconcile forever,+ // overflowing nanostores' listenerQueue (RangeError: Invalid array length).+ $sessions.set([+ row('shared', { profile: 'default', pinned: true }),+ row('shared', { profile: 'hcoder', pinned: false })+ ])+ await flush()++ // Deterministic: exactly one row wins, so the local set settles and no+ // runaway re-entrant reconcile occurs.+ expect($pinnedSessionIds.get()).toEqual(['shared'])+ })++ it('prefers the active gateway profile when duplicate ids disagree', async () => {+ $activeGatewayProfile.set('hcoder')+ $sessions.set([+ row('shared', { profile: 'default', pinned: true }),+ row('shared', { profile: 'hcoder', pinned: false })+ ])+ await flush()++ // The active profile's row is authoritative, so the pin is dropped.+ expect($pinnedSessionIds.get()).toEqual([])+ $activeGatewayProfile.set('default')+ })})diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.tsindex e22bf9433dc..e299b72cb2d 100644--- a/apps/desktop/src/store/session-pin-sync.ts+++ b/apps/desktop/src/store/session-pin-sync.ts@@ -24,7 +24,9 @@import { setSessionPinnedRemote } from '@/hermes'import { onConnectionScopeChange } from '@/lib/connection-scoped'import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'+import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'import { $sessions, sessionMatchesStoredId, sessionPinId } from '@/store/session'+import type { SessionInfo } from '@/types/hermes'// pin ids we've successfully PATCHed pinned=true this session.const mirrored = new Set<string>()@@ -46,6 +48,39 @@ function profileFor(pinId: string): null | string | undefined {return $sessions.get().find(row => sessionMatchesStoredId(row, pinId))?.profile}+/**+ * One authoritative row per durable pin id. Session ids are only unique inside+ * a profile, so the cross-profile list can legitimately hold two rows with the+ * same `sessionPinId` but different `pinned` flags (copied/imported profile+ * databases). Iterating both would pin then unpin the same id in one pass and+ * re-fire `reconcile` forever — the runaway that overflows nanostores'+ * listenerQueue. Collapse to a single row per id, preferring the active+ * gateway's profile (the same tie-break `resolveLoadedRow` uses), so the pull+ * is deterministic and never oscillates.+ */+function rowsByPinId(rows: readonly SessionInfo[]): Map<string, SessionInfo> {+ const byId = new Map<string, SessionInfo>()+ const gateway = normalizeProfileKey($activeGatewayProfile.get())++ for (const row of rows) {+ const pinId = sessionPinId(row)+ const existing = byId.get(pinId)++ if (!existing) {+ byId.set(pinId, row)++ continue+ }++ // Prefer the active gateway's profile; otherwise keep the first seen.+ if (normalizeProfileKey(row.profile) === gateway && normalizeProfileKey(existing.profile) !== gateway) {+ byId.set(pinId, row)+ }+ }++ return byId+}+/** PATCH the flag, guarding reads against pages that predate the write. */function writePin(id: string, pinned: boolean, profile?: null | string): Promise<void> {unconfirmed.set(id, { at: Date.now(), value: pinned })@@ -78,7 +113,7 @@ function writePin(id: string, pinned: boolean, profile?: null | string): Promisefunction pullRemotePins(): void {const local = new Set($pinnedSessionIds.get())- for (const row of $sessions.get()) {+ for (const row of rowsByPinId($sessions.get()).values()) {// A backend without the flag has no opinion; never act on `undefined`.if (typeof row.pinned !== 'boolean') {continue@@ -128,7 +163,31 @@ function pullRemotePins(): void {}}+// Re-entrancy guard: reconcile() is subscribed to BOTH $sessions and+// $pinnedSessionIds, and pullRemotePins() mutates $pinnedSessionIds (via+// pinSession/unpinSession), which fires reconcile() again synchronously.+// Without this guard, a session whose pin state oscillates — two rows with the+// same durable id but conflicting `pinned` flags, possible when profile+// databases share session ids — drives an unbounded re-entrant loop that+// overflows nanostores' shared listenerQueue and crashes the renderer with+// `RangeError: Invalid array length`.+let reconciling = false+function reconcile(): void {+ if (reconciling) {+ return+ }++ reconciling = true++ try {+ reconcileInner()+ } finally {+ reconciling = false+ }+}++function reconcileInner(): void {// Config/session REST is only reachable through the Electron bridge.if (!window.hermesDesktop) {returndiff --git a/apps/desktop/src/store/session-unread.ts b/apps/desktop/src/store/session-unread.tsindex b6afadace0f..64f3cdf115e 100644--- a/apps/desktop/src/store/session-unread.ts+++ b/apps/desktop/src/store/session-unread.ts@@ -64,6 +64,9 @@ type SeenCounts = Record<string, Record<string, number>>/** profile key → durable ids flagged by the live busy→idle edge. */type Markers = Record<string, string[]>+const isPlainRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === 'object' && !Array.isArray(value)+export const $sessionSeenCounts = persistentAtom<SeenCounts>('hermes.desktop.sessionSeenCounts',{},@@ -76,9 +79,6 @@ export const $unreadFinishedMarkers = persistentAtom<Markers>(Codecs.json(sanitizeMarkers))-const isPlainRecord = (value: unknown): value is Record<string, unknown> =>- Boolean(value) && typeof value === 'object' && !Array.isArray(value)-// Also the migration: a pre-profile-scoping flat record (durable id → number)// has non-object values, so it drops wholesale rather than mis-attributing// every id to a profile named after it. Dropped watermarks reseed on next