The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): profile-scope persisted unread and stop cold-boot storage clobber
Zeus-Deus26b4315e09b5
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 20bdf2352bb..66b0a54e708 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@@ -69,6 +69,7 @@ import {type TileDock} from '@/store/session-states'import { broadcastSessionsChanged } from '@/store/session-sync'+import { forgetSessionUnread } from '@/store/session-unread'import { isWatchWindow } from '@/store/windows'import type { SessionCreateResponse, SessionMessage, SessionResumeResponse, UsageStats } from '@/types/hermes'@@ -1592,6 +1593,9 @@ export function useSessionActions({}await deleteSession(storedSessionId, removed?.profile)+ // Only after the RPC lands — the optimistic eviction above can roll+ // back, and a rolled-back row must keep its watermark/marker.+ forgetSessionUnread(removedIds, removed?.profile)clearQueuedPrompts(storedSessionId)if (closingRuntimeId) {@@ -1682,6 +1686,9 @@ export function useSessionActions({try {await setSessionArchived(storedSessionId, true, archived?.profile)+ // Archived rows never reach the sidebar, so their persisted unread can+ // only rot. Dropped after the RPC so a failed archive keeps it.+ forgetSessionUnread(archivedIds, archived?.profile)// An archived session is hidden from the sidebar; its tile must go too.const tiledRuntimeId = runtimeIdByStoredSessionIdRef.current.get(storedSessionId)closeSessionTile(storedSessionId)diff --git a/apps/desktop/src/app/settings/sessions-settings.tsx b/apps/desktop/src/app/settings/sessions-settings.tsxindex 82e4a9d0e0a..6218bce7ead 100644--- a/apps/desktop/src/app/settings/sessions-settings.tsx+++ b/apps/desktop/src/app/settings/sessions-settings.tsx@@ -18,6 +18,7 @@ import { Archive, ArchiveOff, FolderOpen, Loader2, Trash2 } from '@/lib/icons'import { notify, notifyError } from '@/store/notifications'import { untombstoneSessions } from '@/store/projects'import { applyConfiguredDefaultProjectDir, ensureDefaultWorkspaceCwd, setSessions } from '@/store/session'+import { forgetSessionUnread } from '@/store/session-unread'import type { HermesConfigRecord, SessionInfo } from '@/types/hermes'import { EmptyState, ListRow, SectionHeading, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'@@ -83,6 +84,9 @@ export function SessionsSettings() {try {await deleteSession(session.id, session.profile)+ // Permanent delete bypasses removeSession, so retire the persisted+ // unread state here too rather than leaving it to rot.+ forgetSessionUnread([session.id, session._lineage_root_id], session.profile)setLocalSessions(prev => prev.filter(s => s.id !== session.id))triggerHaptic('warning')} catch (err) {diff --git a/apps/desktop/src/lib/persisted.test.ts b/apps/desktop/src/lib/persisted.test.tsnew file mode 100644index 00000000000..95eaa3ff36d--- /dev/null+++ b/apps/desktop/src/lib/persisted.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it } from 'vitest'++import { Codecs, persistentAtom } from './persisted'++// Unique key per test run — persistentAtom instances are singletons per call,+// so tests mint fresh keys instead of sharing one.+let counter = 0+const freshKey = () => `test.persisted.${++counter}`++describe('persistentAtom', () => {+ beforeEach(() => {+ window.localStorage.clear()+ })++ it('seeds from a stored value', () => {+ const key = freshKey()+ window.localStorage.setItem(key, JSON.stringify({ a: 1 }))++ const $value = persistentAtom<Record<string, number>>(key, {})++ expect($value.get()).toEqual({ a: 1 })+ })++ it('does NOT write at creation — an empty read must never clobber storage', () => {+ // A cold boot can evaluate the bundle against a storage snapshot that has+ // not caught up yet (early hidden/boot load). If creation echoed the+ // fallback back out, that load would overwrite the real record other+ // loads are about to read. Creation must be read-only.+ const key = freshKey()+ persistentAtom<Record<string, number>>(key, {})++ expect(window.localStorage.getItem(key)).toBeNull()+ })++ it('leaves an existing stored value untouched at creation even when it fails to decode', () => {+ const key = freshKey()+ window.localStorage.setItem(key, 'not json')++ const $value = persistentAtom<Record<string, number>>(key, { fallback: 1 })++ expect($value.get()).toEqual({ fallback: 1 })+ // The corrupt value survives until a real write replaces it — creation+ // never writes.+ expect(window.localStorage.getItem(key)).toBe('not json')+ })++ it('persists real changes', () => {+ const key = freshKey()+ const $value = persistentAtom<Record<string, number>>(key, {})++ $value.set({ b: 2 })++ expect(window.localStorage.getItem(key)).toBe(JSON.stringify({ b: 2 }))+ })++ it('removes the key when the codec encodes null', () => {+ const key = freshKey()+ window.localStorage.setItem(key, JSON.stringify(['x']))++ const $value = persistentAtom<string[]>(key, [], Codecs.stringArray)++ $value.set([])++ expect(window.localStorage.getItem(key)).toBeNull()+ })+})diff --git a/apps/desktop/src/lib/persisted.ts b/apps/desktop/src/lib/persisted.tsindex 95cd0335ae6..f9d3c7c4004 100644--- a/apps/desktop/src/lib/persisted.ts+++ b/apps/desktop/src/lib/persisted.ts@@ -72,7 +72,26 @@ export function persistentAtom<T>(key: string, fallback: T, codec: Codec<T> = Coconst $value = atom<T>(initial)- $value.subscribe(value => writeKey(key, codec.encode(value)))+ // Persist CHANGES only — never the creation-time value. nanostores'+ // subscribe fires immediately, and writing what was just read back is a+ // no-op at best; at worst it is a data-loss clobber: on a cold boot the+ // renderer bundle can run against a storage snapshot that has not caught+ // up yet (an early hidden/boot load of the same bundle sees an empty+ // area), and echoing the fallback back out overwrites the real record+ // other loads are about to read. Observed with the unread-dot records:+ // the early load wrote `{}` over a populated store between the disk read+ // and the main window's module init.+ let creationEmission = true++ $value.subscribe(value => {+ if (creationEmission) {+ creationEmission = false++ return+ }++ writeKey(key, codec.encode(value))+ })return $value}diff --git a/apps/desktop/src/store/session-unread.test.ts b/apps/desktop/src/store/session-unread.test.tsindex 22b6e8b456e..f1d0224c9b0 100644--- a/apps/desktop/src/store/session-unread.test.ts+++ b/apps/desktop/src/store/session-unread.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'import type { SessionInfo } from '@/types/hermes'+import { $activeGatewayProfile } from './profile'import {$cronSessions,$messagingSessions,@@ -12,7 +13,12 @@ import {setSessions} from './session'import { clearAllSessionStates } from './session-states'-import { $sessionSeenCounts, $unreadFinishedMarkers, markSessionUnreadFinished } from './session-unread'+import {+ $sessionSeenCounts,+ $unreadFinishedMarkers,+ forgetSessionUnread,+ markSessionUnreadFinished+} from './session-unread'const session = (over: Partial<SessionInfo>): SessionInfo => ({archived: false,@@ -41,8 +47,9 @@ function resetAll() {$cronSessions.set([])$messagingSessions.set([])$selectedStoredSessionId.set(null)+ $activeGatewayProfile.set('default')$sessionSeenCounts.set({})- $unreadFinishedMarkers.set([])+ $unreadFinishedMarkers.set({})$unreadFinishedSessionIds.set([])}@@ -52,7 +59,7 @@ describe('persisted unread (session-unread)', () => {it('reconstructs the green dot from a seen watermark after a cold start', () => {// "Restart": persisted watermark says 3 messages were seen; the freshly// loaded list says the session now has 5 — it finished while we were away.- $sessionSeenCounts.set({ s1: 3 })+ $sessionSeenCounts.set({ default: { s1: 3 } })setSessions([session({ id: 's1', message_count: 5 })])@@ -63,7 +70,7 @@ describe('persisted unread (session-unread)', () => {setSessions([session({ id: 's1', message_count: 5 })])expect($unreadFinishedSessionIds.get()).toEqual([])- expect($sessionSeenCounts.get()).toEqual({ s1: 5 })+ expect($sessionSeenCounts.get()).toEqual({ default: { s1: 5 } })})it('keeps a live-edge marker across a transient wipe (gateway/profile switch)', () => {@@ -82,15 +89,15 @@ describe('persisted unread (session-unread)', () => {})it('acks watermark + marker when the user opens the session', () => {- $sessionSeenCounts.set({ s1: 3 })+ $sessionSeenCounts.set({ default: { s1: 3 } })setSessions([session({ id: 's1', message_count: 5 })])markSessionUnreadFinished('s1')setSelectedStoredSessionId('s1')expect($unreadFinishedSessionIds.get()).toEqual([])- expect($unreadFinishedMarkers.get()).toEqual([])- expect($sessionSeenCounts.get()).toEqual({ s1: 5 })+ expect($unreadFinishedMarkers.get()).toEqual({})+ expect($sessionSeenCounts.get()).toEqual({ default: { s1: 5 } })// A later refresh with the same count stays read.setSessions([session({ id: 's1', message_count: 5 })])@@ -105,7 +112,7 @@ describe('persisted unread (session-unread)', () => {setSessions([session({ id: 's1', message_count: 7 })])expect($unreadFinishedSessionIds.get()).toEqual([])- expect($sessionSeenCounts.get()).toEqual({ s1: 7 })+ expect($sessionSeenCounts.get()).toEqual({ default: { s1: 7 } })// Navigating away must not retroactively flag it.setSelectedStoredSessionId(null)@@ -114,7 +121,7 @@ describe('persisted unread (session-unread)', () => {})it('follows auto-compression id rotation via the durable lineage id', () => {- $sessionSeenCounts.set({ root: 3 })+ $sessionSeenCounts.set({ default: { root: 3 } })setSessions([session({ _lineage_root_id: 'root', id: 'tip-2', message_count: 6 })])@@ -122,11 +129,11 @@ describe('persisted unread (session-unread)', () => {// Opening the rotated tip acks the lineage watermark.setSelectedStoredSessionId('tip-2')- expect($sessionSeenCounts.get()).toEqual({ root: 6 })+ expect($sessionSeenCounts.get()).toEqual({ default: { root: 6 } })})it('reconstructs unread for cron rows too', () => {- $sessionSeenCounts.set({ cron1: 1 })+ $sessionSeenCounts.set({ default: { cron1: 1 } })$cronSessions.set([session({ id: 'cron1', message_count: 3 })])@@ -158,4 +165,81 @@ describe('persisted unread (session-unread)', () => {expect($unreadFinishedSessionIds.get()).toContain('fresh')})++ it('keeps same-id sessions in different profiles independent', () => {+ // Session ids are caller-supplied and every profile backend is its own+ // namespace, so "s1" in alpha and "s1" in beta are different sessions —+ // and cron/messaging lists always mix profiles into one array.+ $sessionSeenCounts.set({ alpha: { s1: 3 }, beta: { s1: 5 } })+ $unreadFinishedMarkers.set({ alpha: ['s1'] })++ setSessions([+ session({ id: 's1', message_count: 5, profile: 'beta' }),+ session({ id: 's1', message_count: 5, profile: 'alpha' })+ ])++ // Only alpha's row is past its watermark; beta's sits exactly on it.+ expect($unreadFinishedSessionIds.get()).toEqual(['s1'])+ expect($sessionSeenCounts.get()).toEqual({ alpha: { s1: 3 }, beta: { s1: 5 } })++ // Opening beta's row (the gateway is on beta) acks beta only.+ $activeGatewayProfile.set('beta')+ setSelectedStoredSessionId('s1')++ expect($sessionSeenCounts.get()).toEqual({ alpha: { s1: 3 }, beta: { s1: 5 } })+ // alpha's marker survives an ack of beta's identically-named session.+ expect($unreadFinishedMarkers.get()).toEqual({ alpha: ['s1'] })++ // A later refresh must not launder alpha's gap through beta's selection.+ setSessions([+ session({ id: 's1', message_count: 6, profile: 'beta' }),+ session({ id: 's1', message_count: 5, profile: 'alpha' })+ ])++ expect($sessionSeenCounts.get()).toEqual({ alpha: { s1: 3 }, beta: { s1: 6 } })+ expect($unreadFinishedMarkers.get()).toEqual({ alpha: ['s1'] })+ })++ it('files a live-edge marker with no loaded row under the active gateway profile', () => {+ $activeGatewayProfile.set('work')++ markSessionUnreadFinished('fresh')++ expect($unreadFinishedMarkers.get()).toEqual({ work: ['fresh'] })+ expect($unreadFinishedSessionIds.get()).toEqual(['fresh'])+ })++ it('forgets a deleted session’s persisted unread, per profile', () => {+ $sessionSeenCounts.set({ alpha: { root: 3, other: 1 }, beta: { root: 9 } })+ $unreadFinishedMarkers.set({ alpha: ['root', 'keep'], beta: ['root'] })+ $unreadFinishedSessionIds.set(['tip-2'])++ forgetSessionUnread(['tip-2', 'root', null, undefined], 'alpha')++ expect($sessionSeenCounts.get()).toEqual({ alpha: { other: 1 }, beta: { root: 9 } })+ expect($unreadFinishedMarkers.get()).toEqual({ alpha: ['keep'], beta: ['root'] })+ expect($unreadFinishedSessionIds.get()).toEqual([])+ })++ it('drops an emptied profile bucket instead of persisting an empty shell', () => {+ $sessionSeenCounts.set({ alpha: { s1: 3 } })+ $unreadFinishedMarkers.set({ alpha: ['s1'] })++ forgetSessionUnread(['s1'], 'alpha')++ expect($sessionSeenCounts.get()).toEqual({})+ expect($unreadFinishedMarkers.get()).toEqual({})+ })++ it('caps markers per profile, evicting the oldest', () => {+ for (let i = 0; i < 201; i += 1) {+ markSessionUnreadFinished(`s${i}`)+ }++ const markers = $unreadFinishedMarkers.get().default++ expect(markers).toHaveLength(200)+ expect(markers[0]).toBe('s1')+ expect(markers.at(-1)).toBe('s200')+ })})diff --git a/apps/desktop/src/store/session-unread.ts b/apps/desktop/src/store/session-unread.tsindex d98f010532f..226e2b3c640 100644--- a/apps/desktop/src/store/session-unread.ts+++ b/apps/desktop/src/store/session-unread.ts@@ -1,5 +1,7 @@import { Codecs, persistentAtom } from '@/lib/persisted'import { stableArray } from '@/lib/stable-array'+import { readKey } from '@/lib/storage'+import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'import type { SessionInfo } from '@/types/hermes'import {@@ -11,15 +13,16 @@ import {sessionMatchesStoredId,sessionPinId} from './session'+import { isSecondaryWindow } from './windows'/*** PERSISTED UNREAD ("finished — unread" green dot) — the durable layer under* the transient `$unreadFinishedSessionIds` atom, ported from the webui's* proven design (sessions.js: viewed-count watermarks + completion markers).*- * Two persisted records, both keyed by the DURABLE lineage id (sessionPinId)- * so state survives auto-compression's session-id rotation — same rule as- * `$sessionColorOverrides`:+ * Two persisted records, both bucketed BY PROFILE and then keyed by the+ * DURABLE lineage id (sessionPinId) so state survives auto-compression's+ * session-id rotation — same durable-id rule as `$sessionColorOverrides`:** 1. SEEN WATERMARKS — the message_count last acknowledged for a session* (set when the user opens it, kept current while it stays selected, and@@ -34,12 +37,20 @@ import {* refreshed its message_count yet (and any completion that adds no* stored messages), so a restart right after a finish keeps the dot.*- * Keys are durable ids WITHOUT profile scoping on purpose: session ids are- * unique across profiles, and unread only ever PAINTS for rows present in the- * loaded lists (which are profile-scoped), so another profile's markers stay- * dormant instead of leaking — and survive a profile round-trip (the webui- * needed explicit per-profile scoping, commit 1a64fc68, because its markers- * painted by id lookup alone).+ * PROFILE SCOPING is not optional: session ids are caller-supplied and each+ * remote-profile backend is its own namespace, so two profiles can hold the+ * same id — and the lists routinely mix profiles (cron/messaging are ALWAYS+ * cross-profile, `$sessions` is too in all-profiles mode). Unscoped keys let+ * one profile's watermark/marker paint (or silence) another's row. The bucket+ * is always the ROW's own `profile` (normalizeProfileKey, absent → "default"),+ * never the live gateway's — except for the live busy→idle edge with no loaded+ * row, which only ever fires for the ACTIVE gateway's runtimes and therefore+ * falls back to `$activeGatewayProfile`.+ *+ * Both records are BOUNDED: markers cap per profile (oldest evicted),+ * watermarks cap in total (unlisted, unmarked entries dropped first), and+ * deleting/archiving a session drops its entries outright via+ * {@link forgetSessionUnread}.** Scope of watermark-based unread: chat + cron rows. Messaging rows get their* message_count bumped by inbound human messages, so count-over-watermark@@ -47,28 +58,79 @@ import {* the explicit live-edge markers (now persisted across restarts too).*/-export const $sessionSeenCounts = persistentAtom<Record<string, number>>(+/** profile key → durable id → last acknowledged message_count. */+type SeenCounts = Record<string, Record<string, number>>++/** profile key → durable ids flagged by the live busy→idle edge. */+type Markers = Record<string, string[]>++export const $sessionSeenCounts = persistentAtom<SeenCounts>('hermes.desktop.sessionSeenCounts',{},Codecs.json(sanitizeSeenCounts))-export const $unreadFinishedMarkers = persistentAtom<string[]>(+export const $unreadFinishedMarkers = persistentAtom<Markers>('hermes.desktop.unreadFinishedSessions',- [],- Codecs.stringArray+ {},+ Codecs.json(sanitizeMarkers))-function sanitizeSeenCounts(value: unknown): Record<string, number> {- if (!value || typeof value !== 'object' || Array.isArray(value)) {+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+// sight, which reads as "not unread" — the safe default.+function sanitizeSeenCounts(value: unknown): SeenCounts {+ if (!isPlainRecord(value)) {return {}}- return Object.fromEntries(- Object.entries(value).filter(- (entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1])+ const next: SeenCounts = {}++ for (const [profile, bucket] of Object.entries(value)) {+ if (!isPlainRecord(bucket)) {+ continue+ }++ const counts = Object.fromEntries(+ Object.entries(bucket).filter(+ (entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1])+ ))- )++ if (Object.keys(counts).length) {+ next[profile] = counts+ }+ }++ return next+}++// Same story for markers: the legacy flat shape was a bare string[], which is+// not an object of arrays, so it decodes to {}.+function sanitizeMarkers(value: unknown): Markers {+ if (!isPlainRecord(value)) {+ return {}+ }++ const next: Markers = {}++ for (const [profile, bucket] of Object.entries(value)) {+ if (!Array.isArray(bucket)) {+ continue+ }++ const ids = bucket.filter((id): id is string => typeof id === 'string' && id.length > 0)++ if (ids.length) {+ next[profile] = ids+ }+ }++ return next}// Watermarks accrete one entry per session ever seen; keep the record bounded.@@ -77,24 +139,67 @@ function sanitizeSeenCounts(value: unknown): Record<string, number> {// which reads as "not unread", the safe default.const SEEN_COUNTS_CAP = 2000+// Markers only matter while their session still exists, and a marker whose+// session is gone is invisible (nothing paints it) but immortal — deletes we+// never observed (another client, a wiped backend) would accrete forever. Cap+// per profile and evict oldest-first: the freshest finishes are the ones the+// user still cares about.+const MARKERS_CAP = 200+const rowsFor = (lists: readonly SessionInfo[][]): SessionInfo[] => lists.flat()const isSelected = (row: SessionInfo, selected: null | string): boolean =>Boolean(selected && sessionMatchesStoredId(row, selected))-/** Durable id for a stored id, when the row is loaded; the stored id itself- * otherwise (sessionPinId falls back to the live id anyway). */-function durableIdForStoredId(storedSessionId: string): string {- const row = rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]).find(s =>- sessionMatchesStoredId(s, storedSessionId)+/** The persistence bucket a row belongs to — its OWN profile, never the live+ * gateway's (the lists are routinely cross-profile). */+const profileKeyForRow = (row: SessionInfo): string => normalizeProfileKey(row.profile)++/** The row a bare stored id refers to. Ids are caller-supplied and each+ * profile's backend is its own namespace, so two profiles can hold the same+ * id; a tie breaks toward the live gateway, since both opening a session and+ * running one swap the gateway onto that session's profile. */+function resolveLoadedRow(storedSessionId: string): SessionInfo | undefined {+ const matches = rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]).filter(row =>+ sessionMatchesStoredId(row, storedSessionId))- return row ? sessionPinId(row) : storedSessionId+ if (matches.length < 2) {+ return matches[0]+ }++ const gateway = normalizeProfileKey($activeGatewayProfile.get())++ return matches.find(row => profileKeyForRow(row) === gateway) ?? matches[0]+}++/** Bucket for a bare stored id: its row's profile, else the live gateway's. */+const resolveProfile = (storedSessionId: string): string => {+ const row = resolveLoadedRow(storedSessionId)++ return row ? profileKeyForRow(row) : normalizeProfileKey($activeGatewayProfile.get())+}++/** Write a profile's marker bucket, dropping the key when it empties so we+ * don't persist a graveyard of `[]`. */+function setMarkerBucket(profile: string, ids: readonly string[]): void {+ const markers = $unreadFinishedMarkers.get()+ const next = { ...markers }++ if (ids.length) {+ next[profile] = [...ids]+ } else {+ delete next[profile]+ }++ $unreadFinishedMarkers.set(next)}/** LIVE-EDGE WRITER — called by session-states.ts on a background busy→idle* transition. Flags the transient atom (immediate paint) AND persists the- * marker so the dot survives a restart. */+ * marker so the dot survives a restart. The marker lands in the row's own+ * profile; with no loaded row we use the active gateway's profile, which is+ * the only place a live edge can come from. */export function markSessionUnreadFinished(storedSessionId: string): void {const current = $unreadFinishedSessionIds.get()@@ -102,45 +207,60 @@ export function markSessionUnreadFinished(storedSessionId: string): void {$unreadFinishedSessionIds.set([...current, storedSessionId])}- const durableId = durableIdForStoredId(storedSessionId)- const markers = $unreadFinishedMarkers.get()+ const row = resolveLoadedRow(storedSessionId)+ const profile = row ? profileKeyForRow(row) : normalizeProfileKey($activeGatewayProfile.get())+ const durableId = row ? sessionPinId(row) : storedSessionId+ const bucket = $unreadFinishedMarkers.get()[profile] ?? []- if (!markers.includes(durableId)) {- $unreadFinishedMarkers.set([...markers, durableId])+ if (bucket.includes(durableId)) {+ return}++ const next = [...bucket, durableId]++ setMarkerBucket(profile, next.length > MARKERS_CAP ? next.slice(next.length - MARKERS_CAP) : next)}/** ACK — the user opened (or is looking at) this session: watermark := its* current message_count, and any explicit marker is retired. */function ackSessionRow(row: SessionInfo): void {++ const profile = profileKeyForRow(row)const durableId = sessionPinId(row)if (Number.isFinite(row.message_count)) {const seen = $sessionSeenCounts.get()+ const bucket = seen[profile]- if (seen[durableId] !== row.message_count) {- $sessionSeenCounts.set({ ...seen, [durableId]: row.message_count })+ if (bucket?.[durableId] !== row.message_count) {+ $sessionSeenCounts.set({ ...seen, [profile]: { ...bucket, [durableId]: row.message_count } })}}- const markers = $unreadFinishedMarkers.get()+ const markers = $unreadFinishedMarkers.get()[profile]++ if (!markers) {+ return+ }+const next = markers.filter(id => id !== durableId && !sessionMatchesStoredId(row, id))if (next.length !== markers.length) {- $unreadFinishedMarkers.set(next)+ setMarkerBucket(profile, next)}}/** Clear persisted unread for a stored id even when its row isn't loaded —- * the marker alone can be retired; the watermark needs the row's count. */+ * the marker alone can be retired; the watermark needs the row's count. With+ * no row there is no profile to read, so we retire it from the active+ * gateway's bucket (the profile whose sessions you can actually be opening);+ * other profiles' identically-named ids stay untouched. */export function ackStoredSessionId(storedSessionId: null | string): void {if (!storedSessionId) {return}- const row = rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]).find(s =>- sessionMatchesStoredId(s, storedSessionId)- )+ const row = resolveLoadedRow(storedSessionId)if (row) {ackSessionRow(row)@@ -148,11 +268,69 @@ export function ackStoredSessionId(storedSessionId: null | string): void {return}- const markers = $unreadFinishedMarkers.get()+ const profile = normalizeProfileKey($activeGatewayProfile.get())+ const markers = $unreadFinishedMarkers.get()[profile]++ if (!markers) {+ return+ }+const next = markers.filter(id => id !== storedSessionId)if (next.length !== markers.length) {- $unreadFinishedMarkers.set(next)+ setMarkerBucket(profile, next)+ }+}++/** DELETE/ARCHIVE CLEANUP — the session is gone from the user's world, so its+ * watermark and marker are dead weight. Drops every candidate id (stored id,+ * live id, lineage root) from both persisted records in `profile`'s bucket+ * and from the transient atom. Same-id sessions in other profiles survive. */+export function forgetSessionUnread(+ candidateIds: readonly (null | string | undefined)[],+ profile?: null | string+): void {+ const ids = new Set(candidateIds.filter((id): id is string => Boolean(id)))++ if (!ids.size) {+ return+ }++ const key = normalizeProfileKey(profile)+ const seen = $sessionSeenCounts.get()+ const counts = seen[key]++ if (counts) {+ const kept = Object.fromEntries(Object.entries(counts).filter(([id]) => !ids.has(id)))++ if (Object.keys(kept).length !== Object.keys(counts).length) {+ const next = { ...seen }++ if (Object.keys(kept).length) {+ next[key] = kept+ } else {+ delete next[key]+ }++ $sessionSeenCounts.set(next)+ }+ }++ const markers = $unreadFinishedMarkers.get()[key]++ if (markers) {+ const kept = markers.filter(id => !ids.has(id))++ if (kept.length !== markers.length) {+ setMarkerBucket(key, kept)+ }+ }++ const current = $unreadFinishedSessionIds.get()+ const nextIds = current.filter(id => !ids.has(id))++ if (nextIds.length !== current.length) {+ $unreadFinishedSessionIds.set(nextIds)}}@@ -163,30 +341,43 @@ export function ackStoredSessionId(storedSessionId: null | string): void {* between their watermark and live count IS the unread signal. */function ingestRows(rows: readonly SessionInfo[]): void {const selected = $selectedStoredSessionId.get()+ // Only the OWNING profile's row counts as on-screen: a same-id row in+ // another profile is a different session and keeps its unread gap.+ const selectedProfile = selected ? resolveProfile(selected) : nullconst seen = $sessionSeenCounts.get()- let next: null | Record<string, number> = null+ let next: null | SeenCounts = null++ const write = (profile: string, durableId: string, count: number): void => {+ next ??= { ...seen }+ next[profile] = { ...next[profile], [durableId]: count }+ }for (const row of rows) {if (!Number.isFinite(row.message_count)) {continue}+ const profile = profileKeyForRow(row)const durableId = sessionPinId(row)+ const bucket = next?.[profile] ?? seen[profile]- if (isSelected(row, selected)) {- if (seen[durableId] !== row.message_count) {- ;(next ??= { ...seen })[durableId] = row.message_count+ if (profile === selectedProfile && isSelected(row, selected)) {+ if (bucket?.[durableId] !== row.message_count) {+ write(profile, durableId, row.message_count)}// Any lingering explicit marker for the on-screen session is stale.- const markers = $unreadFinishedMarkers.get()- const kept = markers.filter(id => id !== durableId && !sessionMatchesStoredId(row, id))+ const markers = $unreadFinishedMarkers.get()[profile]- if (kept.length !== markers.length) {- $unreadFinishedMarkers.set(kept)+ if (markers) {+ const kept = markers.filter(id => id !== durableId && !sessionMatchesStoredId(row, id))++ if (kept.length !== markers.length) {+ setMarkerBucket(profile, kept)+ }}- } else if (!(durableId in seen) && !(next && durableId in next)) {- ;(next ??= { ...seen })[durableId] = row.message_count+ } else if (!bucket || !(durableId in bucket)) {+ write(profile, durableId, row.message_count)}}@@ -195,20 +386,43 @@ function ingestRows(rows: readonly SessionInfo[]): void {}}-function pruneSeenCounts(seen: Record<string, number>, rows: readonly SessionInfo[]): Record<string, number> {- const keys = Object.keys(seen)+function pruneSeenCounts(seen: SeenCounts, rows: readonly SessionInfo[]): SeenCounts {+ const total = Object.values(seen).reduce((sum, bucket) => sum + Object.keys(bucket).length, 0)- if (keys.length <= SEEN_COUNTS_CAP) {+ if (total <= SEEN_COUNTS_CAP) {return seen}- const keep = new Set<string>($unreadFinishedMarkers.get())+ const markers = $unreadFinishedMarkers.get()+ const keep = new Map<string, Set<string>>()++ const keepFor = (profile: string): Set<string> => {+ let ids = keep.get(profile)++ if (!ids) {+ ids = new Set(markers[profile] ?? [])+ keep.set(profile, ids)+ }++ return ids+ }for (const row of rows) {- keep.add(sessionPinId(row))+ keepFor(profileKeyForRow(row)).add(sessionPinId(row))+ }++ const next: SeenCounts = {}++ for (const [profile, bucket] of Object.entries(seen)) {+ const allowed = keepFor(profile)+ const kept = Object.fromEntries(Object.entries(bucket).filter(([id]) => allowed.has(id)))++ if (Object.keys(kept).length) {+ next[profile] = kept+ }}- return Object.fromEntries(keys.filter(key => keep.has(key)).map(key => [key, seen[key]]))+ return next}/** Recompute the transient unread atom from persisted state + loaded rows.@@ -223,26 +437,35 @@ function recomputeUnread(): void {const seen = $sessionSeenCounts.get()const unread: string[] = []- // Watermark + marker unread for chat and cron rows.+ const isMarked = (row: SessionInfo, durableId: string): boolean => {+ const bucket = markers[profileKeyForRow(row)]++ return Boolean(bucket?.includes(durableId) || bucket?.includes(row.id))+ }++ // Watermark + marker unread for chat and cron rows. The selected skip stays+ // profile-blind here (unlike the persisted writes): the paint layer is keyed+ // by row id, so dotting a same-id row from another profile would just put a+ // dot on the session you have open.for (const row of rowsFor([$sessions.get(), $cronSessions.get()])) {if (isSelected(row, selected)) {continue}const durableId = sessionPinId(row)- const watermark = seen[durableId]+ const watermark = seen[profileKeyForRow(row)]?.[durableId]const exceedsWatermark =typeof watermark === 'number' && Number.isFinite(row.message_count) && row.message_count > watermark- if (exceedsWatermark || markers.includes(durableId) || markers.includes(row.id)) {+ if (exceedsWatermark || isMarked(row, durableId)) {unread.push(row.id)}}// Messaging rows: explicit (live-edge) markers only — see header comment.for (const row of $messagingSessions.get()) {- if (!isSelected(row, selected) && (markers.includes(sessionPinId(row)) || markers.includes(row.id))) {+ if (!isSelected(row, selected) && isMarked(row, sessionPinId(row))) {unread.push(row.id)}}@@ -264,7 +487,53 @@ function recomputeUnread(): void {}}+// COLD-BOOT REHYDRATE — module evaluation can race Chromium's storage-area+// load: an early read comes back empty, the atoms seed their fallbacks, and+// the first ingest would then re-seed every row and write that emptiness+// back over the real record. By the time the first session list arrives+// (seconds later, over IPC) storage is reliably readable, so re-read both+// keys once right before the first ingest and adopt the disk state, keeping+// any entry this window already wrote in the meantime (a live edge or an+// ack beats the stale disk copy for its own key).+let rehydratedFromDisk = false++function rehydrateFromDiskOnce(): void {+ if (rehydratedFromDisk) {+ return+ }++ rehydratedFromDisk = true++ try {+ const rawSeen = readKey('hermes.desktop.sessionSeenCounts')+ const diskSeen = rawSeen ? sanitizeSeenCounts(JSON.parse(rawSeen) as unknown) : {}+ const memorySeen = $sessionSeenCounts.get()+ const mergedSeen: SeenCounts = { ...diskSeen }++ for (const [profile, bucket] of Object.entries(memorySeen)) {+ mergedSeen[profile] = { ...mergedSeen[profile], ...bucket }+ }++ $sessionSeenCounts.set(mergedSeen)++ const rawMarkers = readKey('hermes.desktop.unreadFinishedSessions')+ const diskMarkers = rawMarkers ? sanitizeMarkers(JSON.parse(rawMarkers) as unknown) : {}+ const memoryMarkers = $unreadFinishedMarkers.get()+ const merged: Markers = { ...diskMarkers }++ for (const [profile, ids] of Object.entries(memoryMarkers)) {+ merged[profile] = [...new Set([...(merged[profile] ?? []), ...ids])]+ }++ $unreadFinishedMarkers.set(merged)+ } catch {+ // Unreadable storage: keep the in-memory state — same fallback the+ // atoms started from.+ }+}+function onListChange(): void {+ rehydrateFromDiskOnce()ingestRows(rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]))recomputeUnread()}@@ -272,10 +541,16 @@ function onListChange(): void {// Wiring: module-scope listeners, same pattern as session-states.ts's// $selectedStoredSessionId listener. Loaded via session-states.ts (the live// edge imports markSessionUnreadFinished), so it's active wherever unread is.-$sessions.listen(onListChange)-$cronSessions.listen(onListChange)-$messagingSessions.listen(onListChange)--// Opening a session acks it durably (the transient atom is already cleared-// synchronously by setSelectedStoredSessionId — this is the persisted half).-$selectedStoredSessionId.listen(ackStoredSessionId)+// ONLY the primary window maintains the persisted records: a secondary window+// (single-chat pop-out, watch window) sees a sliver of the session lists, and+// letting it seed/ack against that partial view would clobber the primary's+// whole-record writes — same isolation rule as the persisted session tiles.+if (!isSecondaryWindow()) {+ $sessions.listen(onListChange)+ $cronSessions.listen(onListChange)+ $messagingSessions.listen(onListChange)++ // Opening a session acks it durably (the transient atom is already cleared+ // synchronously by setSelectedStoredSessionId — this is the persisted half).+ $selectedStoredSessionId.listen(ackStoredSessionId)+}