feat(web): add bulk mark-all-read session action (#1773)

* feat(web): add bulk mark-all-read session action

* fix(web): mark duplicate sessions as read

* fix(web): count hidden duplicate unread sessions

* fix(web): exclude empty session stubs from bulk read
This commit is contained in:
Ananovo
2026-09-09 09:28:08 +08:00
committed by GitHub
parent 8357da0a9d
commit 4dac00ccd9
7 changed files with 430 additions and 8 deletions
@@ -0,0 +1,224 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ReactNode } from 'react'
import type { SessionSummary } from '@/types/api'
import { I18nProvider } from '@/lib/i18n-context'
import { ToastProvider } from '@/lib/toast-context'
import { SessionList } from './SessionList'
afterEach(() => cleanup())
function makeSession(overrides: Partial<SessionSummary> & { id: string }): SessionSummary {
return {
active: false,
thinking: false,
activeAt: 0,
updatedAt: 0,
metadata: null,
metadataVersion: 0,
agentStateVersion: 0,
todosUpdatedAt: 0,
todoProgress: null,
pendingRequestsCount: 0,
pendingRequestKinds: [],
pendingRequests: [],
backgroundTaskCount: 0,
futureScheduledMessageCount: 0,
nextScheduledAt: null,
model: null,
effort: null,
...overrides
}
}
function renderWithProviders(children: ReactNode) {
return render(
<QueryClientProvider client={new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
}
})}>
<ToastProvider>
<I18nProvider>{children}</I18nProvider>
</ToastProvider>
</QueryClientProvider>
)
}
function renderSessionList(sessions: SessionSummary[]) {
return renderWithProviders(
<SessionList
sessions={sessions}
selectedSessionId={null}
onSelect={vi.fn()}
onNewSession={vi.fn()}
onRefresh={vi.fn()}
isLoading={false}
renderHeader={false}
api={null}
/>
)
}
describe('SessionList mark all as read', () => {
beforeEach(() => {
localStorage.clear()
})
it('only shows the independent action when unread sessions exist', () => {
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({ read: 1000 }))
renderSessionList([
makeSession({ id: 'read', updatedAt: 1000, metadata: { path: '/work/read', name: 'Read' } })
])
expect(screen.queryByRole('button', { name: 'Mark all as read (1)' })).toBeNull()
cleanup()
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({ unread: 1000 }))
renderSessionList([
makeSession({ id: 'unread', updatedAt: 2000, metadata: { path: '/work/unread', name: 'Unread' } })
])
const action = screen.getByRole('button', { name: 'Mark all as read (1)' })
expect(action).toBeTruthy()
expect(action).toHaveClass('text-[var(--app-hint)]', 'hover:text-[var(--app-fg)]')
expect(action.textContent).toBe('')
expect(action.querySelector('svg')).toBeTruthy()
})
it('requires confirmation before marking every unread session read', async () => {
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({
unreadA: 1000,
unreadB: 2000,
read: 3000
}))
renderSessionList([
makeSession({ id: 'unreadA', updatedAt: 1100, metadata: { path: '/work/a', name: 'Unread A' } }),
makeSession({ id: 'unreadB', updatedAt: 2200, metadata: { path: '/work/b', name: 'Unread B' } }),
makeSession({ id: 'read', updatedAt: 3000, metadata: { path: '/work/read', name: 'Read' } })
])
fireEvent.click(screen.getByRole('button', { name: 'Mark all as read (2)' }))
const dialog = screen.getByRole('dialog')
const title = within(dialog).getByRole('heading', { name: 'Mark all as read?' })
expect(title.parentElement).toHaveClass('pr-0')
expect(title).toHaveClass('min-h-6', 'px-10', 'text-center', 'leading-6')
expect(screen.getByText('This will mark 2 unread sessions as read on this device.')).toBeTruthy()
expect(within(dialog).getByRole('button', { name: 'Confirm' })).toHaveClass('bg-red-600', 'text-white')
expect(JSON.parse(localStorage.getItem('hapi.sessionLastSeen.v1')!)).toMatchObject({ unreadA: 1000, unreadB: 2000 })
fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Mark all as read (2)' })).toBeNull()
})
expect(JSON.parse(localStorage.getItem('hapi.sessionLastSeen.v1')!)).toMatchObject({
unreadA: 1100,
unreadB: 2200,
read: 3000
})
expect(screen.queryByRole('dialog')).toBeNull()
})
it('leaves unread state unchanged when the confirmation is cancelled', () => {
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({ unread: 1000 }))
renderSessionList([
makeSession({ id: 'unread', updatedAt: 2000, metadata: { path: '/work/unread', name: 'Unread' } })
])
fireEvent.click(screen.getByRole('button', { name: 'Mark all as read (1)' }))
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(screen.getByRole('button', { name: 'Mark all as read (1)' })).toBeTruthy()
expect(JSON.parse(localStorage.getItem('hapi.sessionLastSeen.v1')!)).toEqual({ unread: 1000 })
})
it('marks hidden duplicate session IDs so a dedup winner change stays read', async () => {
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({
visibleWinner: 2000,
hiddenDuplicate: 0,
}))
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
}
})
const renderTree = (sessions: SessionSummary[]) => (
<QueryClientProvider client={queryClient}>
<ToastProvider>
<I18nProvider>
<SessionList
sessions={sessions}
selectedSessionId={null}
onSelect={vi.fn()}
onNewSession={vi.fn()}
onRefresh={vi.fn()}
isLoading={false}
renderHeader={false}
api={null}
/>
</I18nProvider>
</ToastProvider>
</QueryClientProvider>
)
const initialSessions = [
makeSession({
id: 'visibleWinner',
updatedAt: 2000,
metadata: { path: '/work/shared', name: 'Visible winner', agentSessionId: 'native-1', flavor: 'codex' }
}),
makeSession({
id: 'hiddenDuplicate',
updatedAt: 1000,
metadata: { path: '/work/shared', name: 'Hidden duplicate', agentSessionId: 'native-1', flavor: 'codex' }
}),
]
const view = render(renderTree(initialSessions))
fireEvent.click(screen.getByRole('button', { name: 'Mark all as read (1)' }))
fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Mark all as read (1)' })).toBeNull()
})
view.rerender(renderTree(initialSessions.map(session => (
session.id === 'hiddenDuplicate' ? { ...session, active: true } : session
))))
expect(screen.queryByRole('button', { name: 'Mark all as read (1)' })).toBeNull()
expect(JSON.parse(localStorage.getItem('hapi.sessionLastSeen.v1')!)).toMatchObject({
visibleWinner: 2000,
hiddenDuplicate: 1000,
})
})
it('does not count unread inactive empty session stubs', () => {
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({
visible: 2000,
emptyStub: 0,
}))
renderSessionList([
makeSession({
id: 'visible',
updatedAt: 2000,
metadata: { path: '/work/visible', name: 'Visible' }
}),
makeSession({ id: 'emptyStub', updatedAt: 3000 })
])
expect(screen.queryByRole('button', { name: 'Mark all as read (1)' })).toBeNull()
})
it('uses the requested Chinese label', () => {
localStorage.setItem('hapi-lang', 'zh-CN')
localStorage.setItem('hapi.sessionLastSeen.v1', JSON.stringify({ unread: 1000 }))
renderSessionList([
makeSession({ id: 'unread', updatedAt: 2000, metadata: { path: '/work/unread', name: 'Unread' } })
])
expect(screen.getByRole('button', { name: '全部标为已读(1)' })).toBeTruthy()
})
})
+45 -8
View File
@@ -10,7 +10,7 @@ import { SessionActionMenu } from '@/components/SessionActionMenu'
import { SessionExportDialog } from '@/components/SessionExportDialog'
import { RenameSessionDialog } from '@/components/RenameSessionDialog'
import { ConfirmDialog } from '@/components/ui/ConfirmDialog'
import { CopyIcon, CheckIcon } from '@/components/icons'
import { CopyIcon, CheckIcon, MarkAllReadIcon } from '@/components/icons'
function PinnedSectionIcon(props: { className?: string }) {
return (
@@ -32,6 +32,8 @@ import {
getSessionLastSeenAt,
getSessionLastSeenSnapshot,
getSessionManualUnreadAt,
getUnreadSessionCount,
markAllSessionsSeen,
markSessionUnread,
useSessionLastSeenVersion
} from '@/lib/sessionLastSeen'
@@ -1209,6 +1211,7 @@ export function SessionList(props: {
const [searchExpanded, setSearchExpanded] = useState(false)
const [customStart, setCustomStart] = useState('')
const [customEnd, setCustomEnd] = useState('')
const [markAllReadOpen, setMarkAllReadOpen] = useState(false)
const [, setCodexImportedSessionsVersion] = useState(0)
const normalizedQuery = normalizeSearch(searchQuery)
const timeRange = getSessionTimeRange(customStart, customEnd)
@@ -1231,14 +1234,23 @@ export function SessionList(props: {
return t('machine.unknown')
}
const sidebarSessions = useMemo(
() => prepareSidebarSessions(props.sessions, selectedSessionId),
[props.sessions, selectedSessionId]
)
const readableSessions = useMemo(
() => props.sessions.filter(session => shouldShowSessionInSidebar(session, selectedSessionId)),
[props.sessions, selectedSessionId]
)
const allSessions = useMemo(
() => {
const prepared = prepareSidebarSessions(props.sessions, selectedSessionId)
return showActiveSessionsOnly
? filterActiveSessionsOnly(prepared, selectedSessionId)
: prepared
},
[props.sessions, selectedSessionId, showActiveSessionsOnly]
() => showActiveSessionsOnly
? filterActiveSessionsOnly(sidebarSessions, selectedSessionId)
: sidebarSessions,
[sidebarSessions, selectedSessionId, showActiveSessionsOnly]
)
const unreadSessionCount = useMemo(
() => getUnreadSessionCount(readableSessions),
[lastSeenVersion, readableSessions]
)
const sessionActivityDates = useMemo(
() => new Set(allSessions.map(session => formatDateValue(new Date(session.updatedAt)))),
@@ -1894,6 +1906,17 @@ export function SessionList(props: {
onChange={setMachineFilter}
/>
) : null}
{unreadSessionCount > 0 ? (
<button
type="button"
onClick={() => setMarkAllReadOpen(true)}
title={t('sessions.markAllRead.button', { count: unreadSessionCount })}
aria-label={t('sessions.markAllRead.button', { count: unreadSessionCount })}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-[var(--app-hint)] transition-colors hover:bg-[var(--app-subtle-bg)] hover:text-[var(--app-fg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--app-link)]"
>
<MarkAllReadIcon className="h-5 w-5" />
</button>
) : null}
<button
type="button"
onClick={() => setShowUnreadOnly(!showUnreadOnly)}
@@ -2056,6 +2079,20 @@ export function SessionList(props: {
</SessionListScrollAnchor>
</div>
</div>
<ConfirmDialog
isOpen={markAllReadOpen}
onClose={() => setMarkAllReadOpen(false)}
title={t('sessions.markAllRead.title')}
description={t('sessions.markAllRead.description', { count: unreadSessionCount })}
confirmLabel={t('sessions.markAllRead.confirm')}
confirmingLabel={t('sessions.markAllRead.confirming')}
onConfirm={async () => {
markAllSessionsSeen(readableSessions)
}}
isPending={false}
centerTitle
destructive
/>
</div>
)
}
+15
View File
@@ -61,6 +61,21 @@ export function CheckIcon(props: IconProps) {
)
}
export function MarkAllReadIcon(props: IconProps) {
return createIcon(
<>
<path d="m3 5 2 2 4-4" />
<path d="M13 5h8" />
<path d="m3 12 2 2 4-4" />
<path d="M13 12h8" />
<path d="m3 19 2 2 4-4" />
<path d="M13 19h8" />
</>,
props,
2
)
}
export function InfoIcon(props: IconProps) {
return createIcon(
<>
+5
View File
@@ -84,6 +84,11 @@ export default {
'sessions.search.clear': 'Clear search',
'sessions.search.noResults': 'No sessions match your filters.',
'sessions.unreadFilter.toggle': 'Unread only',
'sessions.markAllRead.button': 'Mark all as read ({count})',
'sessions.markAllRead.title': 'Mark all as read?',
'sessions.markAllRead.description': 'This will mark {count} unread sessions as read on this device.',
'sessions.markAllRead.confirm': 'Confirm',
'sessions.markAllRead.confirming': 'Marking as read…',
'sessions.timeFilter.label': 'Filter sessions by last activity',
'sessions.timeFilter.pickStart': 'Select start date',
'sessions.timeFilter.pickEnd': 'Select end date',
+5
View File
@@ -84,6 +84,11 @@ export default {
'sessions.search.clear': '清除搜索',
'sessions.search.noResults': '没有符合筛选条件的会话。',
'sessions.unreadFilter.toggle': '仅显示未读',
'sessions.markAllRead.button': '全部标为已读({count})',
'sessions.markAllRead.title': '全部标为已读?',
'sessions.markAllRead.description': '这会将当前设备上的 {count} 个未读会话标记为已读。',
'sessions.markAllRead.confirm': '确定',
'sessions.markAllRead.confirming': '标记中…',
'sessions.timeFilter.label': '按最后活动时间筛选会话',
'sessions.timeFilter.pickStart': '选择开始日期',
'sessions.timeFilter.pickEnd': '选择结束日期',
+45
View File
@@ -5,7 +5,9 @@ import {
getSessionLastSeenAt,
getSessionLastSeenSnapshot,
getSessionManualUnreadAt,
getUnreadSessionCount,
initializeSessionLastSeen,
markAllSessionsSeen,
markSessionUnread,
markSessionSeen,
useSessionLastSeenVersion,
@@ -36,6 +38,49 @@ describe('sessionLastSeen', () => {
})
})
it('counts and marks all unread sessions in one local batch', () => {
markSessionSeen('read', 1000)
markSessionSeen('newer', 1000)
markSessionUnread('manual', 3000)
const sessions = [
{ id: 'read', updatedAt: 1000 },
{ id: 'newer', updatedAt: 2000 },
{ id: 'manual', updatedAt: 3000 },
{ id: 'newer', updatedAt: 1500 },
]
expect(getUnreadSessionCount(sessions)).toBe(2)
expect(markAllSessionsSeen(sessions)).toBe(2)
expect(getUnreadSessionCount(sessions)).toBe(0)
expect(getSessionLastSeenAt('newer')).toBe(2000)
expect(getSessionLastSeenAt('manual')).toBe(3000)
expect(getSessionManualUnreadAt('manual')).toBeNull()
})
it('notifies consumers once for a batch mark-as-read operation', () => {
markSessionUnread('session-a', 1000)
markSessionUnread('session-b', 2000)
const view = render(createElement(SessionLastSeenVersionProbe))
const initialVersion = Number(view.getByTestId('last-seen-version').textContent)
act(() => {
markAllSessionsSeen([
{ id: 'session-a', updatedAt: 1000 },
{ id: 'session-b', updatedAt: 2000 },
])
})
expect(view.getByTestId('last-seen-version')).toHaveTextContent(String(initialVersion + 1))
})
it('does not write or report a change when all sessions are already read', () => {
markSessionSeen('session-a', 1000)
expect(markAllSessionsSeen([{ id: 'session-a', updatedAt: 1000 }])).toBe(0)
expect(getSessionLastSeenSnapshot()).toEqual({ 'session-a': 1000 })
})
it('does not move the watermark backwards', () => {
markSessionSeen('session-a', 5000)
markSessionSeen('session-a', 2000)
+91
View File
@@ -147,6 +147,97 @@ export function getSessionLastSeenSnapshot(): Readonly<Record<string, number>> {
return readStore()
}
type SessionReadStateInput = {
id: string
updatedAt: number
}
function latestSessionUpdates(sessions: Iterable<SessionReadStateInput>): Map<string, number> {
const latest = new Map<string, number>()
for (const session of sessions) {
if (!session.id || !Number.isFinite(session.updatedAt)) {
continue
}
const current = latest.get(session.id)
if (current === undefined || session.updatedAt > current) {
latest.set(session.id, session.updatedAt)
}
}
return latest
}
function hasUnreadActivity(
sessionId: string,
updatedAt: number,
store: LastSeenStore,
manualUnreadStore: ManualUnreadStore
): boolean {
const lastSeenAt = store[sessionId]
const manualUnreadAt = manualUnreadStore[sessionId]
return updatedAt > (typeof lastSeenAt === 'number' && Number.isFinite(lastSeenAt) ? lastSeenAt : 0)
|| manualUnreadAt === updatedAt
}
/** Count unread sessions in the supplied list using one localStorage snapshot. */
export function getUnreadSessionCount(sessions: Iterable<SessionReadStateInput>): number {
const latest = latestSessionUpdates(sessions)
const store = readStore()
const manualUnreadStore = readManualUnreadStore()
let count = 0
for (const [sessionId, updatedAt] of latest) {
if (hasUnreadActivity(sessionId, updatedAt, store, manualUnreadStore)) {
count += 1
}
}
return count
}
/** Mark all supplied unread sessions as seen on this device. Returns changed count. */
export function markAllSessionsSeen(sessions: Iterable<SessionReadStateInput>): number {
const latest = latestSessionUpdates(sessions)
if (latest.size === 0) {
return 0
}
const store = readStore()
const manualUnreadStore = readManualUnreadStore()
let count = 0
let seenChanged = false
let manualUnreadChanged = false
for (const [sessionId, updatedAt] of latest) {
if (!hasUnreadActivity(sessionId, updatedAt, store, manualUnreadStore)) {
continue
}
count += 1
const currentSeenAt = store[sessionId]
const nextSeenAt = Math.max(
typeof currentSeenAt === 'number' && Number.isFinite(currentSeenAt) ? currentSeenAt : 0,
updatedAt
)
if (store[sessionId] !== nextSeenAt) {
store[sessionId] = nextSeenAt
seenChanged = true
}
if (Object.prototype.hasOwnProperty.call(manualUnreadStore, sessionId)) {
delete manualUnreadStore[sessionId]
manualUnreadChanged = true
}
}
if (count === 0) {
return 0
}
const seenWritten = !seenChanged || writeStore(store)
const manualUnreadWritten = !manualUnreadChanged || writeManualUnreadStore(manualUnreadStore)
if (seenWritten || manualUnreadWritten) {
notifyStoreChanged()
}
return count
}
export function initializeSessionLastSeen(scope: string, sessions: Iterable<{ id: string; updatedAt: number }>): void {
const storage = getLocalStorage()
if (!storage) {