Skip to content

The agent that grows with you

feat(desktop): mark a session as unread/read with a persisted watermark

Nicolas Formentonc75d835555b0
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 1cb5cbc5901..4e9b257e154 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -123,6 +123,8 @@ import {
} from '@/store/session'
import { $sessionDotStateById, sessionStatusBucket } from '@/store/session-dot-state'
import { $focusedStoredSessionId, $workingSessionIds, type SplitDir } from '@/store/session-states'
+import { markSessionUnread } from '@/store/session-unread-remote'
+import { notifyError } from '@/store/notifications'
import { $archivedSessions, loadArchivedSessions } from '@/store/sidebar-archive'
import { $sidebarSessionRankIds } from '@/store/sidebar-sort'
@@ -371,6 +373,18 @@ export function ChatSidebar({
const profiles = useStore($profiles)
const profileColors = useStore($profileColors)
const profileScope = useStore($profileScope)
+ // Toggle the persisted read-state watermark from a row menu. The row's own
+ // `unread` prop mirrors what the dot paints; flip it and let the backend
+ // become the truth (optimistic update + rollback in markSessionUnread).
+ const toggleUnread = (storedId: string) => {
+ const row = $sessions.get().find(r => r.id === storedId)
+
+ if (!row) {
+ return
+ }
+
+ markSessionUnread(storedId, row.unread !== true).catch(err => notifyError(err, s.row.unreadFailed))
+ }
// Only surface the profile switcher when more than one profile exists, so
// single-profile users see the unchanged sidebar.
const multiProfile = profiles.length > 1
@@ -1553,6 +1567,7 @@ export function ChatSidebar({
onResumeSession={onResumeSession}
onToggle={() => undefined}
onTogglePin={pinSession}
+ onToggleUnread={toggleUnread}
open
pinned={false}
rootClassName="min-h-32 flex-1 overflow-hidden p-0"
@@ -1575,6 +1590,7 @@ export function ChatSidebar({
onResumeSession={onResumeSession}
onToggle={() => setSidebarPinsOpen(!pinsOpen)}
onTogglePin={unpinSession}
+ onToggleUnread={toggleUnread}
open={pinsOpen}
pinned
rootClassName="shrink-0 p-0 pb-1"
@@ -1745,6 +1761,7 @@ export function ChatSidebar({
onResumeSession={onResumeSession}
onToggle={() => setSidebarRecentsOpen(!agentsOpen)}
onTogglePin={pinSession}
+ onToggleUnread={toggleUnread}
open={agentsOpen}
pinned={false}
projectBackRow={
@@ -1802,6 +1819,7 @@ export function ChatSidebar({
onResumeSession={onResumeSession}
onToggle={() => toggleSidebarMessagingOpen(group.sourceId)}
onTogglePin={pinSession}
+ onToggleUnread={toggleUnread}
open={messagingOpenIds.includes(group.sourceId)}
pinned={false}
rootClassName="shrink-0 p-0"
diff --git a/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx b/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx
index 30905f8d88c..1619113df24 100644
--- a/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx
+++ b/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx
@@ -105,8 +105,12 @@ interface SessionActions {
sessionId: string
title: string
pinned?: boolean
+ /** Backend-derived read state — drives the Mark as unread/read label. */
+ unread?: boolean
profile?: string
onPin?: () => void
+ /** Toggle the persisted read-state watermark for this row. */
+ onToggleUnread?: () => void
onBranch?: () => void
onArchive?: () => void
onDelete?: () => void
@@ -187,8 +191,10 @@ function useSessionActions({
sessionId,
title,
pinned = false,
+ unread = false,
profile,
onPin,
+ onToggleUnread,
onBranch,
onArchive,
onDelete,
@@ -303,21 +309,32 @@ function useSessionActions({
onPin?.()
}
}),
- // Only meaningful for a row still carrying the finished-unread dot; once
- // read (or never unread) the item vanishes.
- ...(isUnread
- ? [
- spec({
- disabled: !sessionId,
- icon: 'check-all',
- label: r.markRead,
- onSelect: () => {
- triggerHaptic('selection')
- markSessionRead(sessionId)
- }
- })
- ]
- : [])
+ // One read-state item, driven by BOTH unread sources: the transient
+ // finished-unread dot (isUnread) and the backend watermark (unread).
+ // "Mark as read" clears whichever is lit; "Mark as unread" arms the
+ // persisted watermark so the dot survives restarts.
+ spec({
+ disabled: !sessionId || (!onToggleUnread && !isUnread),
+ // Closed envelope = unread, open envelope = read (codicon has mail and
+ // mail-read, but no mail-unread glyph — verified against the font css).
+ icon: unread || isUnread ? 'mail-read' : 'mail',
+ label: unread || isUnread ? r.markRead : r.markUnread,
+ onSelect: () => {
+ triggerHaptic('selection')
+
+ if (unread || isUnread) {
+ // Clear the transient family dot immediately…
+ markSessionRead(sessionId)
+
+ // …and retire the persisted watermark when the row carries one.
+ if (unread) {
+ onToggleUnread?.()
+ }
+ } else {
+ onToggleUnread?.()
+ }
+ }
+ })
]
// WORK — derive/extract from the session.
diff --git a/apps/desktop/src/app/chat/sidebar/session-row.test.tsx b/apps/desktop/src/app/chat/sidebar/session-row.test.tsx
index 9e354264165..4b36f22fbc3 100644
--- a/apps/desktop/src/app/chat/sidebar/session-row.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/session-row.test.tsx
@@ -159,7 +159,9 @@ const renderRow = (session: SessionInfo) =>
onDelete={noop}
onPin={noop}
onResume={noop}
+ onToggleUnread={noop}
session={session}
+ unread={false}
/>
)
@@ -203,7 +205,9 @@ describe('SidebarSessionRow running arc', () => {
onDelete={noop}
onPin={noop}
onResume={noop}
+ onToggleUnread={noop}
session={session}
+ unread={false}
/>
))}
</>
@@ -229,7 +233,9 @@ describe('SidebarSessionRow', () => {
onDelete={noop}
onPin={noop}
onResume={noop}
+ onToggleUnread={noop}
session={makeSession({ title: 'Hermes doctor health check results' })}
+ unread={false}
/>
)
@@ -341,7 +347,9 @@ describe('SidebarSessionRow', () => {
onDelete={noop}
onPin={noop}
onResume={noop}
+ onToggleUnread={noop}
session={makeSession({ title: 'Local session' })}
+ unread={false}
/>
)
@@ -357,11 +365,13 @@ describe('SidebarSessionRow', () => {
onDelete={noop}
onPin={noop}
onResume={noop}
+ onToggleUnread={noop}
session={makeSession({
handoff_platform: 'telegram',
handoff_state: 'active',
title: 'Continued from Telegram'
})}
+ unread={false}
/>
)
diff --git a/apps/desktop/src/app/chat/sidebar/session-row.tsx b/apps/desktop/src/app/chat/sidebar/session-row.tsx
index bb66fefdba5..4b75bd39dea 100644
--- a/apps/desktop/src/app/chat/sidebar/session-row.tsx
+++ b/apps/desktop/src/app/chat/sidebar/session-row.tsx
@@ -55,10 +55,14 @@ interface SidebarSessionRowProps extends React.ComponentProps<'div'> {
branchStem?: string
isPinned: boolean
isSelected: boolean
+ /** Backend-derived read state — same value the dot paints. */
+ unread: boolean
onArchive: () => void
onBranch?: () => void
onDelete: () => void
onPin: () => void
+ /** Toggle the persisted read-state watermark. */
+ onToggleUnread: () => void
onResume: () => void
reorderable?: boolean
dragging?: boolean
@@ -119,10 +123,12 @@ function SidebarSessionRowImpl({
branchStem,
isPinned,
isSelected,
+ unread,
onArchive,
onBranch,
onDelete,
onPin,
+ onToggleUnread,
onResume,
reorderable = false,
dragging = false,
@@ -300,10 +306,12 @@ function SidebarSessionRowImpl({
onBranch={onBranch}
onDelete={onDelete}
onPin={onPin}
+ onToggleUnread={onToggleUnread}
pinned={isPinned}
profile={session.profile}
sessionId={session.id}
title={title}
+ unread={unread}
>
<Button
aria-label={r.sessionActions}
@@ -327,7 +335,9 @@ function SidebarSessionRowImpl({
onBranch={onBranch}
onDelete={onDelete}
onPin={onPin}
+ onToggleUnread={onToggleUnread}
pinned={isPinned}
+ unread={unread}
profile={session.profile}
sessionId={session.id}
title={title}
@@ -564,6 +574,7 @@ function rowPropsEqual(a: SidebarSessionRowProps, b: SidebarSessionRowProps): bo
a.session === b.session &&
a.isPinned === b.isPinned &&
a.isSelected === b.isSelected &&
+ a.unread === b.unread &&
a.branchStem === b.branchStem &&
a.reorderable === b.reorderable &&
a.dragging === b.dragging &&
diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
index 19b20a1addd..ee0a3cf90e8 100644
--- a/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.test.tsx
@@ -75,6 +75,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
onResumeSession={noop}
onToggle={noop}
onTogglePin={noop}
+ onToggleUnread={noop}
open={true}
pinned={false}
sessions={sessions}
@@ -96,6 +97,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
onResumeSession={noop}
onToggle={noop}
onTogglePin={noop}
+ onToggleUnread={noop}
open={true}
pinned={false}
sessions={sessions}
@@ -125,6 +127,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
onResumeSession={noop}
onToggle={noop}
onTogglePin={noop}
+ onToggleUnread={noop}
open={true}
pinned={false}
sessions={initialSessions}
@@ -145,6 +148,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
onResumeSession={noop}
onToggle={noop}
onTogglePin={noop}
+ onToggleUnread={noop}
open={true}
pinned={false}
sessions={initialSessions}
@@ -167,6 +171,7 @@ describe('SidebarSessionsSection memoization & virtualizer stability', () => {
onResumeSession={noop}
onToggle={noop}
onTogglePin={noop}
+ onToggleUnread={noop}
open={true}
pinned={false}
sessions={updatedSessions}
diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
index f95d40a8df6..0cb28700eed 100644
--- a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx
@@ -104,6 +104,7 @@ interface SidebarSessionsSectionProps {
onArchiveSession: (sessionId: string) => void
onBranchSession?: (sessionId: string, profile?: string) => void
onTogglePin: (sessionId: string) => void
+ onToggleUnread: (sessionId: string) => void
onNewSessionInWorkspace?: (path: null | string) => void
pinned: boolean
rootClassName?: string
@@ -181,6 +182,7 @@ export function SidebarSessionsSection({
onArchiveSession,
onBranchSession,
onTogglePin,
+ onToggleUnread,
onNewSessionInWorkspace,
pinned,
rootClassName,
@@ -256,10 +258,12 @@ export function SidebarSessionsSection({
onBranch: onBranchSession ? () => onBranchSession(session.id, session.profile) : undefined,
onDelete: () => onDeleteSession(session.id),
onPin: () => onTogglePin(sessionPinId(session)),
+ onToggleUnread: () => onToggleUnread(session.id),
onResume: () => onResumeSession(session.id),
reorderable: draggable && !branchStem,
session,
- showProfile: showProfileTags
+ showProfile: showProfileTags,
+ unread: session.unread === true
}
return draggable && !branchStem ? (
@@ -276,6 +280,7 @@ export function SidebarSessionsSection({
onDeleteSession,
onResumeSession,
onTogglePin,
+ onToggleUnread,
pinned,
showProfileTags
]
@@ -460,6 +465,7 @@ export function SidebarSessionsSection({
onDeleteSession={onDeleteSession}
onResumeSession={onResumeSession}
onTogglePin={onTogglePin}
+ onToggleUnread={onToggleUnread}
pinned={pinned}
rows={flatRows}
showProfileTags={showProfileTags}
@@ -516,9 +522,11 @@ interface SortableSessionRowProps {
session: SessionInfo
isPinned: boolean
isSelected: boolean
+ unread: boolean
onArchive: () => void
onDelete: () => void
onPin: () => void
+ onToggleUnread: () => void
onResume: () => void
}
diff --git a/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx b/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
index c27e854a228..e0ad175cb78 100644
--- a/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
+++ b/apps/desktop/src/app/chat/sidebar/virtual-session-list.tsx
@@ -22,10 +22,12 @@ interface SessionRowCommonProps {
card?: boolean
isPinned: boolean
isSelected: boolean
+ unread: boolean
onArchive: () => void
onBranch?: () => void
onDelete: () => void
onPin: () => void
+ onToggleUnread: () => void
onResume: () => void
reorderable?: boolean
showProfile?: boolean
@@ -44,6 +46,7 @@ export interface VirtualSessionListProps {
onDeleteSession: (sessionId: string) => void
onResumeSession: (sessionId: string) => void
onTogglePin: (sessionId: string) => void
+ onToggleUnread: (sessionId: string) => void
pinned: boolean
showProfileTags?: boolean
sortable: boolean
@@ -67,6 +70,7 @@ export const VirtualSessionList: FC<VirtualSessionListProps> = ({
onDeleteSession,
onResumeSession,
onTogglePin,
+ onToggleUnread,
pinned,
showProfileTags = false,
sortable
@@ -144,9 +148,11 @@ export const VirtualSessionList: FC<VirtualSessionListProps> = ({
onBranch: onBranchSession ? () => onBranchSession(session.id, session.profile) : undefined,
onDelete: () => onDeleteSession(session.id),
onPin: () => onTogglePin(sessionPinId(session)),
+ onToggleUnread: () => onToggleUnread(session.id),
onResume: () => onResumeSession(session.id),
reorderable,
- showProfile: showProfileTags
+ showProfile: showProfileTags,
+ unread: session.unread === true
}
return reorderable ? (
diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsx
index 80e16fa2720..a3be11e558d 100644
--- a/apps/desktop/src/app/contrib/controller.tsx
+++ b/apps/desktop/src/app/contrib/controller.tsx
@@ -58,6 +58,7 @@ import { runExportProfileFlow, runImportProfileFlow } from '@/store/profile-shar
import { $reviewOpen, closeReview, openReview, REVIEW_PANE_ID } from '@/store/review'
import { $currentCwd, $selectedStoredSessionId, $sessions, $yoloActive, sessionMatchesStoredId } from '@/store/session'
import { watchSessionPins } from '@/store/session-pin-sync'
+import { watchUnreadWriteGuard } from '@/store/session-unread-remote'
import { $statusbarVisible } from '@/store/statusbar-prefs'
import { isHudWindow } from '@/store/windows'
@@ -427,6 +428,9 @@ $layoutTree.subscribe(tree => {
// never hides a pinned chat (and pre-existing pins migrate transparently).
watchSessionPins()
+// Release unread-write guards once a list page confirms the value we wrote.
+watchUnreadWriteGuard()
+
// The main tab reads as its SESSION (the loaded title, "New session" on a
// fresh draft) — a stack of main + tiles is then just a row of session names.
// register() replaces same-id in place; the render fn is the shared constant
diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.ts
index 7621ffe1ff4..f40a7676cc5 100644
--- a/apps/desktop/src/hermes.ts
+++ b/apps/desktop/src/hermes.ts
@@ -658,6 +658,19 @@ export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: st
})
}
+// Mirror a sidebar unread toggle to the backend read-state watermark
+// (sessions.last_read_at via SessionDB.set_session_read). Same profile
+// routing as the other session mutations: a remote session's row lives only
+// on its remote host, so the owning profile must travel with the request.
+export function setSessionUnreadRemote(id: string, unread: boolean, profile?: string | null): Promise<{ ok: boolean }> {
+ return window.hermesDesktop.api<{ ok: boolean }>({
+ ...(profile ? { profile } : {}),
+ path: `/api/sessions/${encodeURIComponent(id)}`,
+ method: 'PATCH',
+ body: { unread }
+ })
+}
+
export function searchSessions(query: string): Promise<SessionSearchResponse> {
return window.hermesDesktop.api<SessionSearchResponse>({
path: `/api/sessions/search?q=${encodeURIComponent(query)}`
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index c53d0249987..1ba11274e03 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -1645,6 +1645,9 @@ export const ar = defineLocale({
row: {
pin: 'تثبيت',
unpin: 'إلغاء التثبيت',
+ markUnread: 'وضع علامة كغير مقروء',
+ markRead: 'وضع علامة كمقروء',
+ unreadFailed: 'تعذر تحديث حالة القراءة',
copyId: 'نسخ المعرف',
export: 'تصدير',
branchFrom: 'فرع',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 5130b6635f9..d72bd101417 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -2029,6 +2029,9 @@ export const en: Translations = {
row: {
pin: 'Pin',
unpin: 'Unpin',
+ markUnread: 'Mark as unread',
+ markRead: 'Mark as read',
+ unreadFailed: 'Could not update unread state',
copyId: 'Copy ID',
export: 'Export',
branchFrom: 'Branch',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index cafe0dc7762..671f60cb9b5 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -1799,6 +1799,9 @@ export const ja = defineLocale({
row: {
pin: 'ピン留め',
unpin: 'ピン留めを解除',
+ markUnread: '未読にする',
+ markRead: '既読にする',
+ unreadFailed: '未読状態を更新できませんでした',
copyId: 'ID をコピー',
export: 'エクスポート',
branchFrom: '分岐',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index f92821a94af..d2f4d207bcd 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1711,6 +1711,9 @@ export interface Translations {
row: {
pin: string
unpin: string
+ markUnread: string
+ markRead: string
+ unreadFailed: string
copyId: string
export: string
branchFrom: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index fffb154946a..2374a973938 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -1741,6 +1741,9 @@ export const zhHant = defineLocale({
row: {
pin: '釘選',
unpin: '取消釘選',
+ markUnread: '標記為未讀',
+ markRead: '標記為已讀',
+ unreadFailed: '無法更新未讀狀態',
copyId: '複製 ID',
export: '匯出',
branchFrom: '分支',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 0ef2e560574..c790def088a 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2215,6 +2215,9 @@ export const zh: Translations = {
row: {
pin: '置顶',
unpin: '取消置顶',
+ markUnread: '标记为未读',
+ markRead: '标记为已读',
+ unreadFailed: '无法更新未读状态',
copyId: '复制 ID',
export: '导出',
branchFrom: '分支',
diff --git a/apps/desktop/src/store/session-dot-state.test.ts b/apps/desktop/src/store/session-dot-state.test.ts
index 5f9120a3915..1661c3ba093 100644
--- a/apps/desktop/src/store/session-dot-state.test.ts
+++ b/apps/desktop/src/store/session-dot-state.test.ts
@@ -1,10 +1,12 @@
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createClientSessionState } from '@/lib/chat-runtime'
+import type { SessionInfo } from '@/types/hermes'
-import { $sessions } from './session'
-import { $delegatingSessionIds, hasLiveTurn, showsRunningArc } from './session-dot-state'
+import { $sessions, $unreadFinishedSessionIds, setSessions } from './session'
+import { $delegatingSessionIds, $sessionDotStateById, hasLiveTurn, showsRunningArc } from './session-dot-state'
import { clearAllSessionStates, publishSessionState } from './session-states'
+import { $unreadWriteGuard } from './session-unread-remote'
import { $subagentsBySession, type SubagentProgress } from './subagents'
describe('showsRunningArc', () => {
@@ -83,3 +85,66 @@ describe('$delegatingSessionIds', () => {
expect($delegatingSessionIds.get()).toContain('runtime-fresh')
})
})
+
+const storedRow = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
+ ({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
+
+describe('persisted unread (backend watermark)', () => {
+ beforeEach(() => {
+ clearAllSessionStates()
+ $sessions.set([])
+ $unreadFinishedSessionIds.set([])
+ $unreadWriteGuard.set(new Map())
+ })
+
+ afterEach(() => {
+ clearAllSessionStates()
+ $sessions.set([])
+ $unreadFinishedSessionIds.set([])
+ $unreadWriteGuard.set(new Map())
+ })
+
+ it('claims unread for a session whose row carries unread: true', () => {
+ setSessions([storedRow('s1', { unread: true })])
+
+ expect($sessionDotStateById.get()['s1']).toBe('unread')
+ })
+
+ it('keeps draft weaker than persisted unread', () => {
+ // A blank tile (no busy, no messages, message_count 0) is a draft; the
+ // persisted unread claim must speak over it.
+ setSessions([storedRow('s1', { message_count: 0, unread: true })])
+ publishSessionState('rt1', createClientSessionState('s1'))
+
+ expect($sessionDotStateById.get()['s1']).toBe('unread')
+ })
+
+ it('lets working outrank persisted unread', () => {
+ setSessions([storedRow('s1', { unread: true })])
+ publishSessionState('rt1', { ...createClientSessionState('s1'), busy: true })
+
+ expect($sessionDotStateById.get()['s1']).toBe('working')
+ })
+
+ it('fences a stale page with the write guard', () => {
+ const guard = new Map<string, { at: number; value: boolean }>()
+ guard.set('s1', { at: Date.now(), value: true })
+ $unreadWriteGuard.set(guard)
+
+ // A page issued before our PATCH still says read — keep OUR value.
+ setSessions([storedRow('s1', { unread: false })])
+ expect($sessionDotStateById.get()['s1']).toBe('unread')
+
+ // The guard expires: the page wins and the dot drops.
+ const expired = new Map<string, { at: number; value: boolean }>()
+ expired.set('s1', { at: Date.now() - 60_000, value: true })
+ $unreadWriteGuard.set(expired)
+ expect($sessionDotStateById.get()['s1']).not.toBe('unread')
+ })
+
+ it('leaves a row alone when the backend omits the flag (older runtime)', () => {
+ setSessions([storedRow('s1')])
+
+ expect($sessionDotStateById.get()['s1'] ?? 'idle').not.toBe('unread')
+ })
+})
diff --git a/apps/desktop/src/store/session-dot-state.ts b/apps/desktop/src/store/session-dot-state.ts
index 7a83e7faa33..39e4971c7d5 100644
--- a/apps/desktop/src/store/session-dot-state.ts
+++ b/apps/desktop/src/store/session-dot-state.ts
@@ -15,6 +15,12 @@
*
* The inputs are all reference-stable across stream deltas, so this recomputes
* on status edges rather than per token.
+ *
+ * Unread has TWO sources, both claiming the same state: the runtime marker
+ * (a turn finished in the background while this window wasn't looking at it,
+ * $unreadFinishedSessionIds — transient) and the backend's derived read-state
+ * watermark (row.unread — persists across restarts and is visible to every
+ * surface). The write side of the persisted flag lives in session-unread.ts.
*/
import { computed } from 'nanostores'
@@ -30,6 +36,7 @@ import {
$stalledSessionIds,
$workingSessionIds
} from './session-states'
+import { $unreadWriteGuard, UNREAD_WRITE_GUARD_MS } from './session-unread-remote'
import { $subagentsBySession, activeSubagentCount } from './subagents'
// Sessions parked in async delegation: the parent turn has ended (busy=false —
@@ -101,9 +108,10 @@ export const $sessionDotStateById = computed(
$delegatingSessionIds,
$unreadFinishedSessionIds,
$draftSessionIds,
- $sessions
+ $sessions,
+ $unreadWriteGuard
],
- (attention, working, stalled, background, delegating, unread, draft, sessions) => {
+ (attention, working, stalled, background, delegating, unread, draft, sessions, unreadWriteGuard) => {
const next: Record<string, SessionDotState> = {}
const claim = (ids: readonly string[], state: SessionDotState) => {
@@ -122,6 +130,28 @@ export const $sessionDotStateById = computed(
// the first thing that does happen speaks over it.
claim(draft, 'draft')
claim(unread, 'unread')
+
+ // Persisted read state (backend watermark): a row marked unread keeps the
+ // same emerald dot a background finish would paint, and survives
+ // restarts. Same tier as the runtime marker — both mean "there is
+ // something here you haven't opened". A list page that predates one of
+ // our own writes is fenced out by the write guard: keep OUR value until a
+ // page confirms it or the guard expires.
+ const persistedUnread: string[] = []
+ for (const s of sessions) {
+ const entry = unreadWriteGuard.get(s.id)
+ if (entry && Date.now() - entry.at < UNREAD_WRITE_GUARD_MS) {
+ if (entry.value) {
+ persistedUnread.push(s.id)
+ }
+ continue
+ }
+ if (s.unread === true) {
+ persistedUnread.push(s.id)
+ }
+ }
+ claim(persistedUnread, 'unread')
+
claim(background, 'background')
// Async delegation: the parent turn has ended but its subagents are still
// running, so the session's work continues in child sessions. Same visual
diff --git a/apps/desktop/src/store/session-unread-remote.test.ts b/apps/desktop/src/store/session-unread-remote.test.ts
new file mode 100644
index 00000000000..645e57d6406
--- /dev/null
+++ b/apps/desktop/src/store/session-unread-remote.test.ts
@@ -0,0 +1,113 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type { SessionInfo } from '@/types/hermes'
+
+const patch = vi.fn<(id: string, unread: boolean, profile?: null | string) => Promise<{ ok: boolean }>>(() =>
+ Promise.resolve({ ok: true })
+)
+
+vi.mock('@/hermes', () => ({
+ // The store only needs the REST mutation; keep the mock minimal.
+ setApiRequestProfile: () => {},
+ setSessionUnreadRemote: (id: string, unread: boolean, profile?: null | string) => patch(id, unread, profile)
+}))
+
+import { $sessions, setSessions } from '@/store/session'
+
+import { $unreadWriteGuard, clearUnreadOnOpen, markSessionUnread, watchUnreadWriteGuard } from './session-unread-remote'
+
+const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
+ ({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
+
+beforeEach(() => {
+ $sessions.set([])
+ $unreadWriteGuard.set(new Map())
+ patch.mockClear()
+})
+
+afterEach(() => {
+ $sessions.set([])
+ $unreadWriteGuard.set(new Map())
+})
+
+describe('markSessionUnread', () => {
+ it('optimistically paints the row, then PATCHes with the owning profile', async () => {
+ $sessions.set([row('a', { profile: 'work', unread: false })])
+
+ await markSessionUnread('a', true)
+
+ expect(patch).toHaveBeenCalledWith('a', true, 'work')
+ expect($sessions.get().find(s => s.id === 'a')?.unread).toBe(true)
+ })
+
+ it('no-ops for a runtime-only session with no persisted row', async () => {
+ await markSessionUnread('ghost', true)
+
+ expect(patch).not.toHaveBeenCalled()
+ })
+
+ it('rolls back the row and rethrows when the PATCH fails', async () => {
+ $sessions.set([row('a', { unread: false })])
+ patch.mockImplementationOnce(() => Promise.reject(new Error('offline')))
+
+ await expect(markSessionUnread('a', true)).rejects.toThrow('offline')
+
+ // The backend kept the old value, so the optimistic flip is undone and
+ // the guard is released (nothing to fence a page about).
+ expect($sessions.get().find(s => s.id === 'a')?.unread).toBe(false)
+ expect($unreadWriteGuard.get().has('a')).toBe(false)
+ })
+})
+
+describe('clearUnreadOnOpen', () => {
+ it('no-ops for a session that is already read', async () => {
+ $sessions.set([row('a', { unread: false })])
+
+ await clearUnreadOnOpen('a')
+
+ expect(patch).not.toHaveBeenCalled()
+ })
+
+ it('PATCHes read for an unread session, using its owning profile', async () => {
+ $sessions.set([row('a', { profile: 'p2', unread: true })])
+
+ await clearUnreadOnOpen('a')
+
+ expect(patch).toHaveBeenCalledWith('a', false, 'p2')
+ expect($sessions.get().find(s => s.id === 'a')?.unread).toBe(false)
+ })
+
+ it('swallows a failed PATCH (the next honest refresh heals the dot)', async () => {
+ $sessions.set([row('a', { unread: true })])
+ patch.mockImplementationOnce(() => Promise.reject(new Error('offline')))
+
+ await expect(clearUnreadOnOpen('a')).resolves.toBeUndefined()
+ })
+})
+
+describe('watchUnreadWriteGuard', () => {
+ it('drops a guard entry once a list page confirms the value we wrote', () => {
+ watchUnreadWriteGuard()
+ const guard = new Map<string, { at: number; value: boolean }>()
+ guard.set('a', { at: Date.now(), value: true })
+ $unreadWriteGuard.set(guard)
+
+ // The server caught up and echoes our value back.
+ $sessions.set([row('a', { unread: true })])
+
+ expect($unreadWriteGuard.get().has('a')).toBe(false)
+ })
+
+ it('keeps the guard while a page contradicts a write still in flight', () => {
+ watchUnreadWriteGuard()
+ const guard = new Map<string, { at: number; value: boolean }>()
+ guard.set('a', { at: Date.now(), value: true })
+ $unreadWriteGuard.set(guard)
+
+ // A list request issued before the PATCH still says read. Honouring it
+ // would silently undo the mark the user just made.
+ $sessions.set([row('a', { unread: false })])
+
+ expect($unreadWriteGuard.get().has('a')).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/store/session-unread-remote.ts b/apps/desktop/src/store/session-unread-remote.ts
new file mode 100644
index 00000000000..e90d3a2c9ee
--- /dev/null
+++ b/apps/desktop/src/store/session-unread-remote.ts
@@ -0,0 +1,97 @@
+/**
+ * Persisted unread flag sync (backend read-state watermark via
+ * PATCH /api/sessions/{id} → SessionDB.set_session_read).
+ *
+ * The sidebar's dot is fed by TWO sources (see session-dot-state.ts): the
+ * runtime "turn finished in background" marker ($unreadFinishedSessionIds,
+ * transient) and the backend's derived `unread` key (last_read_at watermark
+ * vs last_active — survives restarts and is visible to every surface). This
+ * module owns the WRITE side of the persisted flag: the row-level
+ * "Mark as unread"/"Mark as read" toggle and the automatic clear when a
+ * session is opened. The read side lives in session-dot-state.ts.
+ *
+ * Optimistic, then honest (AGENTS.md): paint the row immediately, PATCH the
+ * backend, roll back visibly on failure. A list page already in flight when
+ * we PATCH can land after the ack carrying the OLD value — the write guard
+ * lets our value outrank that stale page briefly (#74570 pattern, same as
+ * session-pin-sync.ts).
+ *
+ * NOTE: import cycle with ./session is inert — both modules only touch each
+ * other's exports inside function bodies, never at module evaluation time.
+ */
+import { atom } from 'nanostores'
+
+import { setSessionUnreadRemote } from '@/hermes'
+
+import { $sessions, setSessions } from './session'
+
+export const UNREAD_WRITE_GUARD_MS = 10_000
+
+/** id -> the value we wrote and when. Guarded rows outrank list pages. */
+export const $unreadWriteGuard = atom<Map<string, { at: number; value: boolean }>>(new Map())
+
+function rowFor(storedId: string) {
+ return $sessions.get().find(row => row.id === storedId)
+}
+
+/** Toggle the persisted unread flag: optimistic row update, then PATCH, then
+ * roll back visibly if the write fails. No-op for runtime-only sessions (a
+ * brand-new chat with no persisted row yet — there is nothing to flag). */
+export async function markSessionUnread(storedId: string, unread: boolean): Promise<void> {
+ const row = rowFor(storedId)
+ if (!row) {
+ return
+ }
+
+ const guard = new Map($unreadWriteGuard.get())
+ guard.set(storedId, { at: Date.now(), value: unread })
+ $unreadWriteGuard.set(guard)
+
+ setSessions(rows => rows.map(r => (r.id === storedId ? { ...r, unread } : r)))
+
+ try {
+ await setSessionUnreadRemote(storedId, unread, row.profile)
+ } catch (err) {
+ // Roll back visibly: the backend kept the old value.
+ const guard2 = new Map($unreadWriteGuard.get())
+ guard2.delete(storedId)
+ $unreadWriteGuard.set(guard2)
+ setSessions(rows => rows.map(r => (r.id === storedId ? { ...r, unread: !unread } : r)))
+ throw err
+ }
+}
+
+/** Opening a session clears its persisted unread flag (auto-mark-read).
+ * Best-effort: a failed PATCH is healed by the next honest refresh. */
+export async function clearUnreadOnOpen(storedId: string): Promise<void> {
+ const row = rowFor(storedId)
+ if (!row || row.unread !== true) {
+ return
+ }
+ try {
+ await markSessionUnread(storedId, false)
+ } catch {
+ // Ignore: the dot simply returns until a refresh reconciles.
+ }
+}
+
+/** Release guard entries once a list page confirms the value we wrote. Call
+ * once at boot, next to watchSessionPins(). */
+export function watchUnreadWriteGuard(): void {
+ $sessions.listen(rows => {
+ const guard = $unreadWriteGuard.get()
+ let changed = false
+
+ for (const [id, entry] of guard) {
+ const row = rows.find(r => r.id === id)
+ if (row && row.unread === entry.value) {
+ guard.delete(id)
+ changed = true
+ }
+ }
+
+ if (changed) {
+ $unreadWriteGuard.set(new Map(guard))
+ }
+ })
+}
diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.ts
index 6b2c72377f7..ab7961dc038 100644
--- a/apps/desktop/src/store/session.test.ts
+++ b/apps/desktop/src/store/session.test.ts
@@ -4,6 +4,17 @@ import type { ClientSessionState } from '@/app/types'
import { createClientSessionState } from '@/lib/chat-runtime'
import type { SessionInfo } from '@/types/hermes'
+const setUnreadRemote = vi.fn<(id: string, unread: boolean, profile?: null | string) => Promise<{ ok: boolean }>>(() =>
+ Promise.resolve({ ok: true })
+)
+
+vi.mock('@/hermes', () => ({
+ // Opening a session now PATCHes its persisted unread flag (clearUnreadOnOpen
+ // -> markSessionUnread); keep the REST mutation minimal for the suite.
+ setApiRequestProfile: () => {},
+ setSessionUnreadRemote: (id: string, unread: boolean, profile?: null | string) => setUnreadRemote(id, unread, profile)
+}))
+
import {
$activeSessionId,
$connection,
@@ -551,12 +562,15 @@ describe('unread finished sessions', () => {
clearAllSessionStates()
$unreadFinishedSessionIds.set([])
$selectedStoredSessionId.set(null)
+ $sessions.set([])
+ setUnreadRemote.mockClear()
})
afterEach(() => {
clearAllSessionStates()
$unreadFinishedSessionIds.set([])
$selectedStoredSessionId.set(null)
+ $sessions.set([])
})
it('marks a session unread when its turn finishes in the background', () => {
@@ -693,6 +707,27 @@ describe('unread finished sessions', () => {
vi.useRealTimers()
})
+
+ it('clears a persisted unread row when the session is opened', async () => {
+ $sessions.set([session({ id: 's1', unread: true })])
+
+ setSelectedStoredSessionId('s1')
+
+ // The optimistic flip is synchronous; the PATCH is fire-and-forget.
+ expect($sessions.get().find(s => s.id === 's1')?.unread).toBe(false)
+
+ await Promise.resolve()
+ expect(setUnreadRemote).toHaveBeenCalledWith('s1', false, undefined)
+ })
+
+ it('does not PATCH a read row when it is opened', async () => {
+ $sessions.set([session({ id: 's1', unread: false })])
+
+ setSelectedStoredSessionId('s1')
+
+ await Promise.resolve()
+ expect(setUnreadRemote).not.toHaveBeenCalled()
+ })
})
describe('remembered session id (per profile)', () => {
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 1501e0321db..b9a43a376e9 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -9,6 +9,8 @@ import { persistBoolean, persistString, storedBoolean, storedString } from '@/li
import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope'
import type { SessionInfo, UsageStats } from '@/types/hermes'
+import { clearUnreadOnOpen } from './session-unread-remote'
+
type Updater<T> = T | ((current: T) => T)
export type ComposerModelSource = '' | 'default' | 'manual'
@@ -682,7 +684,9 @@ export const setActiveSessionStoredIdRotation = (next: Updater<ActiveSessionStor
// 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
+// finished while the app was CLOSED still comes up unread. The explicit
+// Mark-as-unread toggle rides the BACKEND watermark instead
+// (SessionDB.set_session_read, session-unread-remote.ts). Written by
// session-states.ts (live busy→idle edge), cleared here on session open.
export const $unreadFinishedSessionIds = atom<string[]>([])
@@ -710,6 +714,11 @@ export const setSelectedStoredSessionId = (next: Updater<string | null>) => {
if (id) {
markSessionRead(id)
}
+
+ // ...and the persisted watermark flag, when the row carried one.
+ if (id) {
+ void clearUnreadOnOpen(id)
+ }
}
/** Record that the user has seen a session (and its conversation family) at
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index fe954367c91..d3da658c995 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -502,6 +502,11 @@ export interface SessionInfo {
* elsewhere. Undefined against a backend predating the flag; treat that as
* "no opinion" and leave the local pin set alone. */
pinned?: boolean
+ /** Derived read state (backend watermark: `last_read_at` vs `last_active`,
+ * see `SessionDB.session_unread`). True when the conversation was
+ * explicitly marked unread or a response arrived after it was last read.
+ * Undefined against a backend predating the flag; treat as read. */
+ unread?: boolean
preview: null | string
source: null | string
started_at: number
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 4fc3b1a91bd..ce9391cdf79 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3534,16 +3534,19 @@ class APIServerAdapter(BasePlatformAdapter):
# sidebar owns (the "keep" flag exempts a chat from the auto-archive
# sweep). Rejecting them here was silently 400ing every pin the desktop
# made, so pins only ever lived in that one app's localStorage.
- allowed = {"title", "end_reason", "pinned", "archived", "hidden"}
+ # `unread` is the read-state watermark toggle (same desktop owner).
+ allowed = {"title", "end_reason", "pinned", "archived", "hidden", "unread"}
unknown = sorted(set(body) - allowed)
if unknown:
return web.json_response(_openai_error(f"Unsupported session fields: {', '.join(unknown)}", code="unsupported_session_field"), status=400)
- for flag in ("pinned", "archived", "hidden"):
+ for flag in ("pinned", "archived", "hidden", "unread"):
if flag in body and not isinstance(body[flag], bool):
return web.json_response(_openai_error(f"'{flag}' must be a boolean", code="invalid_session_field"), status=400)
db = await self._ensure_session_db_async()
+ if db is None:
+ return web.json_response(_openai_error("Session database unavailable", code="session_db_unavailable"), status=503)
if "title" in body:
try:
await asyncio.to_thread(db.set_session_title, session_id, "" if body["title"] is None else str(body["title"]))
@@ -3555,6 +3558,8 @@ class APIServerAdapter(BasePlatformAdapter):
await asyncio.to_thread(db.set_session_archived, session_id, body["archived"])
if "hidden" in body:
await asyncio.to_thread(db.set_session_hidden, session_id, body["hidden"])
+ if "unread" in body:
+ await asyncio.to_thread(db.set_session_read, session_id, read=not body["unread"])
if body.get("end_reason"):
await asyncio.to_thread(db.end_session, session_id, str(body["end_reason"]))
session = await asyncio.to_thread(db.get_session, session_id) or session
diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.py
index 3577ee312f2..2a44cfef083 100644
--- a/hermes_cli/web_models.py
+++ b/hermes_cli/web_models.py
@@ -333,6 +333,10 @@ class SessionRename(BaseModel):
# Durable "keep" flag mirrored from the Desktop sidebar's pins; pinned
# sessions are exempt from the sessions.auto_archive stale sweep.
pinned: Optional[bool] = None
+ # Read-state watermark toggle (sessions.last_read_at): True marks the
+ # session explicitly unread, False marks it read up to now. Mirrored from
+ # the Desktop sidebar's "Mark as unread"/"Mark as read". None = leave alone.
+ unread: Optional[bool] = None
# Mutate a session belonging to another profile (opens its state.db). Omit
# for the current/default profile.
profile: Optional[str] = None
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 6d54377448b..8b37f9fa908 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -684,11 +684,13 @@ async def delete_session_endpoint(session_id: str, profile: Optional[str] = None
@manage_router.patch("/api/sessions/{session_id}")
async def rename_session_endpoint(session_id: str, body: SessionRename):
- """Update a session: rename, archive, and/or pin it.
+ """Update a session: rename, archive, pin, and/or mark read/unread.
``title`` renames (empty/null clears the title); ``archived`` soft-hides or
restores the session; ``pinned`` sets the durable keep flag (exempts the
- session from the auto-archive sweep). Any field may be omitted. ``profile``
+ session from the auto-archive sweep); ``unread`` toggles the read-state
+ watermark (True = explicitly unread, False = read up to now — see
+ ``SessionDB.set_session_read``). Any field may be omitted. ``profile``
targets another profile's session.
"""
db = _open_session_db_for_profile(body.profile, read_only=False)
@@ -696,10 +698,15 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):
sid = db.resolve_session_id(session_id)
if not sid:
raise HTTPException(status_code=404, detail="Session not found")
- if body.title is None and body.archived is None and body.pinned is None:
+ if (
+ body.title is None
+ and body.archived is None
+ and body.pinned is None
+ and body.unread is None
+ ):
raise HTTPException(
status_code=400,
- detail="Nothing to update; provide 'title', 'archived', and/or 'pinned'.",
+ detail="Nothing to update; provide 'title', 'archived', 'pinned', and/or 'unread'.",
)
if body.title is not None:
try:
@@ -711,11 +718,15 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):
db.set_session_archived(sid, body.archived)
if body.pinned is not None:
db.set_session_pinned(sid, body.pinned)
+ if body.unread is not None:
+ db.set_session_read(sid, read=not body.unread)
result = {"ok": True, "title": db.get_session_title(sid) or ""}
if body.archived is not None:
result["archived"] = bool(body.archived)
if body.pinned is not None:
result["pinned"] = bool(body.pinned)
+ if body.unread is not None:
+ result["unread"] = bool(body.unread)
return result
finally:
db.close()
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 356dadf5518..04c375e32e1 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -4697,3 +4697,65 @@ class TestDashboardComponentHealth:
assert self.ws.DASHBOARD_HEALTH.selftest_status == "failing"
assert self.ws.DASHBOARD_HEALTH.selftest_http_status == 500
assert self.ws.DASHBOARD_HEALTH.snapshot()["status"] == "degraded"
+
+
+class TestSessionPatchUnread:
+ """PATCH /api/sessions/{id} with {"unread": bool} marks the session
+ read/unread, and GET /api/sessions surfaces the derived flag."""
+
+ @pytest.fixture(autouse=True)
+ def _setup_test_client(self, monkeypatch, _isolate_hermes_home):
+ try:
+ from starlette.testclient import TestClient
+ except ImportError:
+ pytest.skip("fastapi/starlette not installed")
+
+ import hermes_state
+ from hermes_constants import get_hermes_home
+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
+
+ monkeypatch.setattr(
+ hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db"
+ )
+
+ self.client = TestClient(app)
+ self.auth_client = TestClient(app)
+ self.auth_client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session(session_id="s1", source="cli")
+ db.append_message(session_id="s1", role="user", content="hi")
+ db.set_session_read("s1") # start read, like a conversation you opened
+ finally:
+ db.close()
+
+ def test_patch_unread_true_marks_row_unread(self):
+ resp = self.auth_client.patch("/api/sessions/s1", json={"unread": True})
+ assert resp.status_code == 200
+ assert resp.json()["unread"] is True
+
+ rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]
+ assert next(s for s in rows if s["id"] == "s1")["unread"] is True
+
+ def test_patch_unread_false_marks_row_read(self):
+ self.auth_client.patch("/api/sessions/s1", json={"unread": True})
+ resp = self.auth_client.patch("/api/sessions/s1", json={"unread": False})
+ assert resp.status_code == 200
+ assert resp.json()["unread"] is False
+
+ rows = self.auth_client.get("/api/sessions?limit=100").json()["sessions"]
+ assert next(s for s in rows if s["id"] == "s1")["unread"] is False
+
+ def test_patch_unread_alone_is_accepted(self):
+ # The route's "Nothing to update" guard must not reject a bare unread.
+ resp = self.auth_client.patch("/api/sessions/s1", json={"unread": True})
+ assert resp.status_code == 200
+
+ def test_patch_unread_rejects_non_bool(self):
+ # NB: pydantic v2 coerces "yes"/"no"/"1"/"0"/"on"/"off" to bool, so use
+ # a string outside the accepted set to prove validation rejects it.
+ resp = self.auth_client.patch("/api/sessions/s1", json={"unread": "maybe"})
+ assert resp.status_code == 422 # pydantic validation