From d2c2b0b6d4fae0749c99709844b08f5c7bccc3cf Mon Sep 17 00:00:00 2001 From: Zeus-Deus Date: Wed, 29 Jul 2026 20:41:33 +0200 Subject: [PATCH] fix(desktop): persist sidebar unread dots across app restarts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The green "finished — unread" session dot lived only in the transient $unreadFinishedSessionIds atom, written by a live busy->idle edge the renderer had to witness. Closing and reopening the app grayed out every dot, and a session that finished while the app was closed could never be flagged at all. Add a persisted layer (session-unread.ts), ported from the webui's proven design: - Seen watermarks (hermes.desktop.sessionSeenCounts): the message_count last acknowledged per session, keyed by the durable lineage id (same rule as session colors). A row whose live count exceeds its watermark paints unread on every list refresh - this reconstructs dots after a restart AND surfaces sessions that finished while the app was closed. First sight of an unknown session seeds the watermark so a fresh install doesn't light up every row. - Explicit finish markers (hermes.desktop.unreadFinishedSessions): the live edge, persisted, covering the gap before the sidebar list refreshes its counts. Opening a session acks both; the selected session's watermark tracks its live count so on-screen activity never reads as unread. Chat and cron rows get full watermark treatment; messaging rows keep explicit markers only, so inbound messages don't paint false completion dots. Profile switches keep persisted markers (keyed by durable id) and only wipe the transient paint layer, so a round-trip repaints them. Covered by store unit tests and an e2e spec that boots the app three times: dot appears on a background finish, survives a restart, clears on open, and stays cleared after another restart. --- apps/desktop/e2e/unread-dot-restart.spec.ts | 162 ++++++++++ apps/desktop/src/store/gateway-switch.ts | 6 +- apps/desktop/src/store/session-states.ts | 9 +- apps/desktop/src/store/session-unread.test.ts | 161 ++++++++++ apps/desktop/src/store/session-unread.ts | 281 ++++++++++++++++++ apps/desktop/src/store/session.ts | 9 +- 6 files changed, 620 insertions(+), 8 deletions(-) create mode 100644 apps/desktop/e2e/unread-dot-restart.spec.ts create mode 100644 apps/desktop/src/store/session-unread.test.ts create mode 100644 apps/desktop/src/store/session-unread.ts diff --git a/apps/desktop/e2e/unread-dot-restart.spec.ts b/apps/desktop/e2e/unread-dot-restart.spec.ts new file mode 100644 index 0000000000..9ef8c3d9e2 --- /dev/null +++ b/apps/desktop/e2e/unread-dot-restart.spec.ts @@ -0,0 +1,162 @@ +/** + * E2E test for PERSISTED unread state — the green "Finished — unread" dot + * must survive an app restart. + * + * Regression coverage for the reset-on-restart bug: the unread flag used to + * live only in the in-memory `$unreadFinishedSessionIds` atom, so closing and + * reopening the desktop app grayed out every green dot. The persisted layer + * (src/store/session-unread.ts) now rebuilds the dot from localStorage-backed + * finish markers + seen-count watermarks. + * + * The scenario uses TWO sessions on purpose: with a single session the app + * can reopen straight into it after a restart, which acks the session (the + * user is looking at it) and would mask the dot. Session A finishes in the + * background while session B is the selected one; the restart reopens into + * B, so A's dot is observable. + * + * 1. Session A: start a turn, hold its stream open. + * 2. Session B: new session, send a message, let it finish while SELECTED. + * 3. Release A's stream → its background finish paints A's green dot. + * 4. QUIT the app, relaunch on the SAME sandbox → A's dot must still be + * there (previously it was lost). + * 5. Open session A → dot clears. + * 6. Restart once more → the cleared state must persist too (no zombie dot). + * + * Prerequisite: `npm run build` must have been run so dist/ exists. + */ + +import { expect, type Page, test } from '@playwright/test' +import { type ElectronApplication } from '@playwright/test' + +import { + buildAppEnv, + launchDesktop, + type MockBackendFixture, + setupMockBackend, + waitForAppReady, +} from './fixtures' +import { restartMockServer } from './mock-server' + +/** Finished-unread dot aria-label (from i18n en.ts). */ +const UNREAD_DOT_LABEL = 'Finished — unread' + +/** Held prompt — the mock pauses this stream until we release it, so the + * turn is deterministically still running when we switch away. */ +const HELD_PROMPT = 'E2E unread restart: hold this stream until released.' +/** Second session's prompt — completes normally while selected. */ +const SECOND_PROMPT = 'E2E unread restart: second session, read while open.' + +const unreadDots = (page: Page) => page.locator(`[aria-label="${UNREAD_DOT_LABEL}"]`) + +async function sendMessage(page: Page, text: string): Promise { + const composer = page.locator('[contenteditable="true"]').first() + await composer.waitFor({ state: 'visible', timeout: 15_000 }) + await composer.click() + await composer.type(text, { delay: 5 }) + await page.keyboard.press('Enter') +} + +test.describe('unread dot survives app restart', () => { + test.describe.configure({ mode: 'serial' }) + // Three full app boots in one scenario — give it more than the global 90s. + test.setTimeout(300_000) + + let fixture: MockBackendFixture + let app: ElectronApplication + let page: Page + + test.beforeAll(async () => { + restartMockServer() + fixture = await setupMockBackend({ + mockServer: { holdFirstStreamForPrompt: HELD_PROMPT }, + }) + app = fixture.app + page = fixture.page + await waitForAppReady(fixture, 120_000) + }) + + test.afterAll(async () => { + // The fixture's own app handle may already be closed by the restart + // steps — close whatever is current, then drop the sandbox + mock. + try { + await app?.close() + } catch { + // already closed + } + + fixture?.mock.close() + fixture?.sandbox.cleanup() + }) + + /** Relaunch the desktop app against the SAME sandbox (same userData → + * same localStorage, same HERMES_HOME → same session store). */ + async function restartApp(): Promise { + await app.close() + + const relaunched = await launchDesktop(buildAppEnv(fixture.sandbox)) + app = relaunched.app + page = relaunched.page + await waitForAppReady({ ...fixture, app, page }, 120_000) + } + + test('green dot persists across restart and its clear persists too', async () => { + // ── 1. Session A: start a turn whose stream the mock holds open ──── + await sendMessage(page, HELD_PROMPT) + await fixture.mock.waitForHeldStream() + + // ── 2. Session B: complete a turn while SELECTED (stays read) ────── + await page.locator('button:has-text("New session")').first().click() + await sendMessage(page, SECOND_PROMPT) + + // B's reply lands in the open transcript — this session is "read". + await page.waitForFunction( + () => (document.body.textContent ?? '').includes('Hello from the mock inference server'), + undefined, + { timeout: 30_000 }, + ) + + // ── 3. Release A's stream → background finish paints A's dot ────── + fixture.mock.releaseHeldStream() + + await expect + .poll(() => unreadDots(page).count(), { + timeout: 30_000, + message: 'green unread dot should appear after the background finish', + }) + .toBeGreaterThan(0) + + // ── 4. Restart the app — the dot must survive ────────────────────── + // The app reopens into session B (or a fresh draft), NOT session A, so + // A's dot is observable rather than being acked by the route restore. + await restartApp() + + await expect + .poll(() => unreadDots(page).count(), { + timeout: 60_000, + message: 'green unread dot should be rebuilt from persisted state after restart', + }) + .toBeGreaterThan(0) + + // ── 5. Open session A — the dot clears ───────────────────────────── + // The dot sits inside A's sidebar row button; click that row. + await unreadDots(page) + .first() + .locator('xpath=ancestor::button[1]') + .click() + + await expect + .poll(() => unreadDots(page).count(), { + timeout: 15_000, + message: 'opening the session should clear its unread dot', + }) + .toBe(0) + + // ── 6. Restart again — the CLEARED state must persist as well ────── + await restartApp() + + // Give the sidebar a moment to load rows, then assert no dot returns. + await page.waitForSelector('[data-slot="sidebar"]', { timeout: 60_000 }) + await page.waitForTimeout(5_000) + expect(await unreadDots(page).count(), 'acked session must stay read after restart').toBe(0) + }) +}) diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts index 0338f06bc4..3003be4b32 100644 --- a/apps/desktop/src/store/gateway-switch.ts +++ b/apps/desktop/src/store/gateway-switch.ts @@ -58,7 +58,11 @@ export function wipeSessionListsForGatewaySwitch(): void { setMessagingTruncated(false) // Clearing $sessionStates automatically clears $workingSessionIds and // $attentionSessionIds (computed) and $stalledSessionIds (owned beside it). - // $unreadFinishedSessionIds is separate, so wipe it explicitly. + // $unreadFinishedSessionIds is separate, so wipe it explicitly. Only the + // transient paint layer is wiped: the persisted markers/watermarks in + // session-unread.ts are keyed by durable session id and repaint the rows + // that are still unread once the next gateway's lists load — so a profile + // round-trip doesn't swallow green dots. clearAllSessionStates() resetLiveRuntimeTracking() resetLiveSync() diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts index e7f55b12d6..e1eb31fb41 100644 --- a/apps/desktop/src/store/session-states.ts +++ b/apps/desktop/src/store/session-states.ts @@ -43,6 +43,7 @@ import { setActiveSessionStoredIdRotation, setSessions } from './session' +import { markSessionUnreadFinished } from './session-unread' import { isSecondaryWindow } from './windows' // --------------------------------------------------------------------------- @@ -185,11 +186,9 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessi // FOCUSED, not selected: a session finishing in the tile the user is // watching is already seen, and a tile is never the primary selection. if (storedId !== $focusedStoredSessionId.get()) { - const cur = $unreadFinishedSessionIds.get() - - if (!cur.includes(storedId)) { - $unreadFinishedSessionIds.set([...cur, storedId]) - } + // Flags the transient atom AND persists a marker, so the green dot + // survives an app restart (see session-unread.ts). + markSessionUnreadFinished(storedId) } } } diff --git a/apps/desktop/src/store/session-unread.test.ts b/apps/desktop/src/store/session-unread.test.ts new file mode 100644 index 0000000000..22b6e8b456 --- /dev/null +++ b/apps/desktop/src/store/session-unread.test.ts @@ -0,0 +1,161 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import type { SessionInfo } from '@/types/hermes' + +import { + $cronSessions, + $messagingSessions, + $selectedStoredSessionId, + $sessions, + $unreadFinishedSessionIds, + setSelectedStoredSessionId, + setSessions +} from './session' +import { clearAllSessionStates } from './session-states' +import { $sessionSeenCounts, $unreadFinishedMarkers, markSessionUnreadFinished } from './session-unread' + +const session = (over: Partial): SessionInfo => ({ + archived: false, + cwd: null, + ended_at: null, + id: 'live', + input_tokens: 0, + is_active: false, + last_active: 0, + message_count: 0, + model: null, + output_tokens: 0, + preview: null, + source: null, + started_at: 0, + title: null, + tool_call_count: 0, + ...over +}) + +function resetAll() { + clearAllSessionStates() + // Lists first: their listeners recompute the unread atom, so wiping the + // atom afterwards leaves a genuinely clean slate. + $sessions.set([]) + $cronSessions.set([]) + $messagingSessions.set([]) + $selectedStoredSessionId.set(null) + $sessionSeenCounts.set({}) + $unreadFinishedMarkers.set([]) + $unreadFinishedSessionIds.set([]) +} + +describe('persisted unread (session-unread)', () => { + beforeEach(resetAll) + + 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 }) + + setSessions([session({ id: 's1', message_count: 5 })]) + + expect($unreadFinishedSessionIds.get()).toEqual(['s1']) + }) + + it('seeds the watermark on first sight instead of painting every row green', () => { + setSessions([session({ id: 's1', message_count: 5 })]) + + expect($unreadFinishedSessionIds.get()).toEqual([]) + expect($sessionSeenCounts.get()).toEqual({ s1: 5 }) + }) + + it('keeps a live-edge marker across a transient wipe (gateway/profile switch)', () => { + setSessions([session({ id: 's1', message_count: 4 })]) + markSessionUnreadFinished('s1') + expect($unreadFinishedSessionIds.get()).toEqual(['s1']) + + // Gateway switch: transient paint layer wiped, lists drained… + setSessions([]) + $unreadFinishedSessionIds.set([]) + + // …then the profile's lists load again: the persisted marker repaints. + setSessions([session({ id: 's1', message_count: 4 })]) + + expect($unreadFinishedSessionIds.get()).toEqual(['s1']) + }) + + it('acks watermark + marker when the user opens the session', () => { + $sessionSeenCounts.set({ 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 }) + + // A later refresh with the same count stays read. + setSessions([session({ id: 's1', message_count: 5 })]) + expect($unreadFinishedSessionIds.get()).toEqual([]) + }) + + it('tracks the selected session’s count so on-screen activity never reads as unread', () => { + $selectedStoredSessionId.set('s1') + setSessions([session({ id: 's1', message_count: 2 })]) + + // The turn completes while the user is looking at it. + setSessions([session({ id: 's1', message_count: 7 })]) + + expect($unreadFinishedSessionIds.get()).toEqual([]) + expect($sessionSeenCounts.get()).toEqual({ s1: 7 }) + + // Navigating away must not retroactively flag it. + setSelectedStoredSessionId(null) + setSessions([session({ id: 's1', message_count: 7 })]) + expect($unreadFinishedSessionIds.get()).toEqual([]) + }) + + it('follows auto-compression id rotation via the durable lineage id', () => { + $sessionSeenCounts.set({ root: 3 }) + + setSessions([session({ _lineage_root_id: 'root', id: 'tip-2', message_count: 6 })]) + + expect($unreadFinishedSessionIds.get()).toEqual(['tip-2']) + + // Opening the rotated tip acks the lineage watermark. + setSelectedStoredSessionId('tip-2') + expect($sessionSeenCounts.get()).toEqual({ root: 6 }) + }) + + it('reconstructs unread for cron rows too', () => { + $sessionSeenCounts.set({ cron1: 1 }) + + $cronSessions.set([session({ id: 'cron1', message_count: 3 })]) + + expect($unreadFinishedSessionIds.get()).toEqual(['cron1']) + }) + + it('never paints messaging rows from count growth, but honors live-edge markers', () => { + // First sight seeds… + $messagingSessions.set([session({ id: 'tg1', message_count: 10 })]) + // …then inbound messages bump the count: NOT "finished — unread". + $messagingSessions.set([session({ id: 'tg1', message_count: 14 })]) + + expect($unreadFinishedSessionIds.get()).toEqual([]) + + // A real background turn edge still marks it, durably. + markSessionUnreadFinished('tg1') + $unreadFinishedSessionIds.set([]) + $messagingSessions.set([session({ id: 'tg1', message_count: 14 })]) + + expect($unreadFinishedSessionIds.get()).toEqual(['tg1']) + }) + + it('preserves a live-edge id whose row is not in any loaded list yet', () => { + // A brand-new session's first turn isn't flushed to the sidebar list until + // persisted — the flag must survive list refreshes in the meantime. + markSessionUnreadFinished('fresh') + + setSessions([session({ id: 'other', message_count: 2 })]) + + expect($unreadFinishedSessionIds.get()).toContain('fresh') + }) +}) diff --git a/apps/desktop/src/store/session-unread.ts b/apps/desktop/src/store/session-unread.ts new file mode 100644 index 0000000000..d98f010532 --- /dev/null +++ b/apps/desktop/src/store/session-unread.ts @@ -0,0 +1,281 @@ +import { Codecs, persistentAtom } from '@/lib/persisted' +import { stableArray } from '@/lib/stable-array' +import type { SessionInfo } from '@/types/hermes' + +import { + $cronSessions, + $messagingSessions, + $selectedStoredSessionId, + $sessions, + $unreadFinishedSessionIds, + sessionMatchesStoredId, + sessionPinId +} from './session' + +/** + * 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`: + * + * 1. SEEN WATERMARKS — the message_count last acknowledged for a session + * (set when the user opens it, kept current while it stays selected, and + * seeded on FIRST SIGHT of an unknown session so a fresh install doesn't + * paint every row green). A row whose live `message_count` exceeds its + * watermark is unread — this is what reconstructs the green dot for a + * session that finished while the app was CLOSED, which the live + * busy→idle edge in session-states.ts can never replay after a restart. + * + * 2. EXPLICIT MARKERS — the live busy→idle edge, persisted. Covers the gap + * where a turn finishes in the background but the sidebar list hasn't + * 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). + * + * Scope of watermark-based unread: chat + cron rows. Messaging rows get their + * message_count bumped by inbound human messages, so count-over-watermark + * would paint "finished — unread" on every new inbound text; they keep only + * the explicit live-edge markers (now persisted across restarts too). + */ + +export const $sessionSeenCounts = persistentAtom>( + 'hermes.desktop.sessionSeenCounts', + {}, + Codecs.json(sanitizeSeenCounts) +) + +export const $unreadFinishedMarkers = persistentAtom( + 'hermes.desktop.unreadFinishedSessions', + [], + Codecs.stringArray +) + +function sanitizeSeenCounts(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return {} + } + + return Object.fromEntries( + Object.entries(value).filter( + (entry): entry is [string, number] => typeof entry[1] === 'number' && Number.isFinite(entry[1]) + ) + ) +} + +// Watermarks accrete one entry per session ever seen; keep the record bounded. +// Past the cap, entries for sessions no longer in any loaded list (and not +// explicitly marked) are dropped — a pruned session reseeds on next sight, +// which reads as "not unread", the safe default. +const SEEN_COUNTS_CAP = 2000 + +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) + ) + + return row ? sessionPinId(row) : storedSessionId +} + +/** 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. */ +export function markSessionUnreadFinished(storedSessionId: string): void { + const current = $unreadFinishedSessionIds.get() + + if (!current.includes(storedSessionId)) { + $unreadFinishedSessionIds.set([...current, storedSessionId]) + } + + const durableId = durableIdForStoredId(storedSessionId) + const markers = $unreadFinishedMarkers.get() + + if (!markers.includes(durableId)) { + $unreadFinishedMarkers.set([...markers, durableId]) + } +} + +/** 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 durableId = sessionPinId(row) + + if (Number.isFinite(row.message_count)) { + const seen = $sessionSeenCounts.get() + + if (seen[durableId] !== row.message_count) { + $sessionSeenCounts.set({ ...seen, [durableId]: row.message_count }) + } + } + + const markers = $unreadFinishedMarkers.get() + const next = markers.filter(id => id !== durableId && !sessionMatchesStoredId(row, id)) + + if (next.length !== markers.length) { + $unreadFinishedMarkers.set(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. */ +export function ackStoredSessionId(storedSessionId: null | string): void { + if (!storedSessionId) { + return + } + + const row = rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]).find(s => + sessionMatchesStoredId(s, storedSessionId) + ) + + if (row) { + ackSessionRow(row) + + return + } + + const markers = $unreadFinishedMarkers.get() + const next = markers.filter(id => id !== storedSessionId) + + if (next.length !== markers.length) { + $unreadFinishedMarkers.set(next) + } +} + +/** Seed/refresh watermarks from freshly loaded lists: the SELECTED session + * tracks its live count (it's on screen — nothing there is unread), and a + * session never seen before seeds at its current count instead of lighting + * up green on first sight. Known, unselected rows are left alone — the gap + * between their watermark and live count IS the unread signal. */ +function ingestRows(rows: readonly SessionInfo[]): void { + const selected = $selectedStoredSessionId.get() + const seen = $sessionSeenCounts.get() + let next: null | Record = null + + for (const row of rows) { + if (!Number.isFinite(row.message_count)) { + continue + } + + const durableId = sessionPinId(row) + + if (isSelected(row, selected)) { + if (seen[durableId] !== row.message_count) { + ;(next ??= { ...seen })[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)) + + if (kept.length !== markers.length) { + $unreadFinishedMarkers.set(kept) + } + } else if (!(durableId in seen) && !(next && durableId in next)) { + ;(next ??= { ...seen })[durableId] = row.message_count + } + } + + if (next) { + $sessionSeenCounts.set(pruneSeenCounts(next, rows)) + } +} + +function pruneSeenCounts(seen: Record, rows: readonly SessionInfo[]): Record { + const keys = Object.keys(seen) + + if (keys.length <= SEEN_COUNTS_CAP) { + return seen + } + + const keep = new Set($unreadFinishedMarkers.get()) + + for (const row of rows) { + keep.add(sessionPinId(row)) + } + + return Object.fromEntries(keys.filter(key => keep.has(key)).map(key => [key, seen[key]])) +} + +/** Recompute the transient unread atom from persisted state + loaded rows. + * Runs after every list refresh — including the first one after a cold + * start, which is what brings green dots back from a restart. Stored ids + * already flagged by the live edge but not (yet) present in any list — a + * brand-new session's first turn isn't flushed to the list until persisted — + * are preserved, not dropped. */ +function recomputeUnread(): void { + const selected = $selectedStoredSessionId.get() + const markers = $unreadFinishedMarkers.get() + const seen = $sessionSeenCounts.get() + const unread: string[] = [] + + // Watermark + marker unread for chat and cron rows. + for (const row of rowsFor([$sessions.get(), $cronSessions.get()])) { + if (isSelected(row, selected)) { + continue + } + + const durableId = sessionPinId(row) + const watermark = seen[durableId] + + const exceedsWatermark = + typeof watermark === 'number' && Number.isFinite(row.message_count) && row.message_count > watermark + + if (exceedsWatermark || markers.includes(durableId) || markers.includes(row.id)) { + 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))) { + unread.push(row.id) + } + } + + // Preserve live-edge ids whose row isn't loaded yet. + const loadedRows = rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()]) + + for (const id of $unreadFinishedSessionIds.get()) { + if (id !== selected && !unread.includes(id) && !loadedRows.some(row => sessionMatchesStoredId(row, id))) { + unread.push(id) + } + } + + const current = $unreadFinishedSessionIds.get() + const next = stableArray(current, unread) + + if (next !== current) { + $unreadFinishedSessionIds.set([...next]) + } +} + +function onListChange(): void { + ingestRows(rowsFor([$sessions.get(), $cronSessions.get(), $messagingSessions.get()])) + recomputeUnread() +} + +// 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) diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts index 8b882b6f66..499604f28d 100644 --- a/apps/desktop/src/store/session.ts +++ b/apps/desktop/src/store/session.ts @@ -677,8 +677,13 @@ export const setActiveSessionId = (next: Updater) => updateAtom($ export const setActiveSessionStoredIdRotation = (next: Updater) => updateAtom($activeSessionStoredIdRotation, next) -// Transient: a background session finished and the user hasn't opened it since. -// Written by session-states.ts (handleTransition), cleared here on session open. +// A background session finished and the user hasn't opened it since. This atom +// is the transient PAINT layer (what the dots subscribe to); durability lives +// in session-unread.ts, which persists explicit finish markers + per-session +// "seen message_count" watermarks and rebuilds this atom from them on every +// list refresh — so the green dot survives an app restart, and a session that +// finished while the app was CLOSED still comes up unread. Written by +// session-states.ts (live busy→idle edge), cleared here on session open. export const $unreadFinishedSessionIds = atom([]) export const markAllSessionsRead = () => {