Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): unread counts on rooms and chats
raullopez-sandbox583a04f43ec9
diff --git a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.tsindex f7b715489..e7f416d30 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/chat-stream.test.ts@@ -17,6 +17,7 @@ function summary(roomId: string, seq: number | null): ChatSummary {ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage:seq === null ? null : { seq, sentAt: '2026-01-01T00:00:00Z', preview: '', senderName: '' },};diff --git a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts b/console/apps/switch-console-desktop/src/main/core/chats/controller.tsindex f2108b897..8e9aee19d 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/controller.ts@@ -50,6 +50,7 @@ import {listAgentCandidates,removeChatAgent,removeChatMember,+ markChatRead,renameChat,sendChatControl,sendChatMessage,@@ -194,6 +195,8 @@ export const chatsController = createRPCController({/** The agents the viewer may add to a new chat (`roomId` null) or to that chat. */agentCandidates: (params: { serverId: string; roomId: string | null }): Promise<string[]> =>onServer(params.serverId, (server) => listAgentCandidates(server, params.roomId)),+ markRead: (params: { serverId: string; roomId: string; seq: number }): Promise<void> =>+ onServer(params.serverId, (server) => markChatRead(server, params.roomId, params.seq)),messages: (params: {serverId: string;roomId: string;diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.tsindex f46c78b75..5155150a6 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.test.ts@@ -33,6 +33,7 @@ function row(roomId: string, channelType: string) {ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: null,};}diff --git a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts b/console/apps/switch-console-desktop/src/main/core/chats/gateway.tsindex ba2cd72c4..0b267bb4b 100644--- a/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts+++ b/console/apps/switch-console-desktop/src/main/core/chats/gateway.ts@@ -218,6 +218,11 @@ export async function listAgentCandidates(return (await json(server, `/chats/agent-candidates${query}`, agentCandidatesSchema)).agentIds;}+/** The viewer has been shown the chat through `seq`; the server never moves it back. */+export async function markChatRead(server: SwitchServer, roomId: string, seq: number) {+ await call(server, `${room(roomId)}/read`, { method: 'PUT', body: { seq } });+}+export async function sendChatMessage(server: SwitchServer,roomId: string,diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsxindex ad13a01d8..30f2008db 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-panel.tsx@@ -84,6 +84,8 @@ export const ChatPanel = observer(function ChatPanel({useEffect(() => {if (!timeline.loaded && !lost && !timeline.notMember) void timeline.load();}, [timeline, lost, timeline.notMember]);+ const panel = useRef<HTMLDivElement>(null);+ useReadWhileShown(roomId, timeline, panel, lost || timeline.notMember);// Reasoning lives only on a local or SSH host and is read while a turn runs,// and whenever the joined turns change.@@ -134,7 +136,11 @@ export const ChatPanel = observer(function ChatPanel({);return (- <div data-chat-panel className="flex h-full min-h-0 flex-col bg-background text-foreground">+ <div+ ref={panel}+ data-chat-panel+ className="flex h-full min-h-0 flex-col bg-background text-foreground"+ >{timeline.loadError && (<divrole="alert"@@ -195,6 +201,49 @@ export const ChatPanel = observer(function ChatPanel({);});+/**+ * While the conversation is on screen in a focused window it is the chat being+ * read: its new messages do not count as unread, and it is marked read through+ * the last message shown. A hidden tab or a background window reads nothing.+ */+function useReadWhileShown(+ roomId: string,+ timeline: ChatTimeline,+ panel: React.RefObject<HTMLDivElement | null>,+ hidden: boolean+): void {+ const [shown, setShown] = useState(false);+ const lastSeq = timeline.loaded ? (timeline.messages.at(-1)?.seq ?? null) : null;+ useEffect(() => {+ const update = () =>+ setShown(+ !hidden &&+ document.visibilityState === 'visible' &&+ document.hasFocus() &&+ (panel.current?.checkVisibility() ?? false)+ );+ update();+ document.addEventListener('visibilitychange', update);+ window.addEventListener('focus', update);+ window.addEventListener('blur', update);+ return () => {+ document.removeEventListener('visibilitychange', update);+ window.removeEventListener('focus', update);+ window.removeEventListener('blur', update);+ };+ }, [panel, hidden]);+ useEffect(() => {+ if (!shown) return;+ chatsStore.setViewing(roomId);+ return () => {+ if (chatsStore.viewing === roomId) chatsStore.setViewing(null);+ };+ }, [shown, roomId]);+ useEffect(() => {+ if (shown && lastSeq !== null) chatsStore.read(roomId, lastSeq);+ }, [shown, roomId, lastSeq]);+}+/*** Sending from here jumps to the end and resumes following, wherever the* reader had scrolled to: what they just sent is what they want to see.diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsxindex 89166f6a5..81e39b618 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-row.tsx@@ -12,6 +12,7 @@ import type { ChatSummary } from '@shared/core/chats/chats';import { agentActivities } from '../stores/activities';import { chatsStore } from '../stores/chats';import { ChatActionItems, chatActions } from './chat-actions';+import { UnreadBadge } from './unread-badge';/** Whether something is under way in the chat: a send from here, or an agent working. */function chatBusy(serverId: string, chat: ChatSummary): boolean {@@ -47,6 +48,7 @@ export const ChatRow = observer(function ChatRow({<SidebarMenuAction aria-label={`Open chat ${chat.name}`} className="overflow-hidden"><span className="min-w-0 truncate">{chat.name}</span></SidebarMenuAction>+ <UnreadBadge roomId={chat.roomId} /></div><div className="ml-2 flex min-w-6 shrink-0 items-center justify-end gap-1">{!menuOpen && (diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/unread-badge.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/unread-badge.tsxnew file mode 100644index 000000000..904afaac6--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/unread-badge.tsx@@ -0,0 +1,16 @@+import { observer } from 'mobx-react-lite';+import { chatsStore } from '../stores/chats';++/** How many of a room's messages wait to be read, as a small count; nothing when none do. */+export const UnreadBadge = observer(function UnreadBadge({ roomId }: { roomId: string }) {+ const count = chatsStore.unread(roomId);+ if (count === 0) return null;+ return (+ <span+ aria-label={`${count} unread`}+ className="ml-auto flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-primary-button-background px-1 text-[10px] leading-none font-medium text-primary-button-foreground tabular-nums"+ >+ {count > 99 ? '99+' : count}+ </span>+ );+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.tsindex 621a26290..ef3202d5e 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats-store.ts@@ -35,8 +35,12 @@ export type ChatsApi = {timeline: (serverId: string) => TimelineApi;archive: (serverId: string, roomId: string) => Promise<void>;delete: (serverId: string, roomId: string) => Promise<void>;+ markRead: (serverId: string, roomId: string, seq: number) => Promise<void>;};+/** How long reading settles before the read position is sent. */+export const READ_DEBOUNCE_MS = 400;+export type ChatsEvents = {onMessage: (cb: (data: { serverId: string; message: ChatMessage }) => void) => () => void;onSummary: (cb: (data: { serverId: string; chat: ChatSummary }) => void) => () => void;@@ -61,6 +65,11 @@ export class ChatsStore {streamState: ChatStreamState = 'offline';streamDetail: string | null = null;listError: string | null = null;+ /** The room whose chat is on screen and being read: its messages do not count as unread. */+ viewing: string | null = null;+ /** The furthest message marked read here, by room; a read never moves back. */+ private readonly readThrough = new Map<string, number>();+ private readonly readTimers = new Map<string, ReturnType<typeof setTimeout>>();readonly timelines: ChatTimelines;constructor(@@ -68,7 +77,12 @@ export class ChatsStore {events: ChatsEvents) {this.timelines = new ChatTimelines(api.timeline);- makeAutoObservable<ChatsStore, 'api'>(this, { api: false, timelines: false });+ makeAutoObservable<ChatsStore, 'api' | 'readThrough' | 'readTimers'>(this, {+ api: false,+ timelines: false,+ readThrough: false,+ readTimers: false,+ });events.onSummary(({ serverId, chat }) => {if (serverId === this.serverId) this.upsert(chat);});@@ -178,6 +192,11 @@ export class ChatsStore {if (chat && (chat.lastMessage === null || chat.lastMessage.seq < message.seq))this.chats.set(message.roomId, {...chat,+ // Counted here until the server's next summary says otherwise.+ unreadCount:+ message.sender.userId !== this.userId && this.viewing !== message.roomId+ ? chat.unreadCount + 1+ : chat.unreadCount,lastMessage: {seq: message.seq,sentAt: message.sentAt,@@ -243,6 +262,37 @@ export class ChatsStore {});}+ /** Which room's chat is on screen and being read; null when none is. */+ setViewing(roomId: string | null): void {+ this.viewing = roomId;+ }++ /**+ * The chat was shown through message `seq`: its count goes to 0 here at once,+ * and the position reaches the server once reading settles. Never backwards.+ */+ read(roomId: string, seq: number): void {+ const serverId = this.serverId;+ if (!serverId) return;+ const chat = this.chats.get(roomId);+ if (chat && chat.unreadCount !== 0) this.chats.set(roomId, { ...chat, unreadCount: 0 });+ if ((this.readThrough.get(roomId) ?? 0) >= seq) return;+ this.readThrough.set(roomId, seq);+ clearTimeout(this.readTimers.get(roomId));+ this.readTimers.set(+ roomId,+ setTimeout(() => {+ this.readTimers.delete(roomId);+ void this.api.markRead(serverId, roomId, seq);+ }, READ_DEBOUNCE_MS)+ );+ }++ /** How many messages in a room wait to be read: none for the one being read. */+ unread(roomId: string): number {+ return this.viewing === roomId ? 0 : (this.chats.get(roomId)?.unreadCount ?? 0);+ }+/** The chats an agent is in, newest activity first. */chatsOfAgent(agentId: string): ChatSummary[] {return [...this.chats.values()]diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.tsindex 8e035c183..f66665d68 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/chats.ts@@ -31,6 +31,16 @@ export const chatsStore = new ChatsStore(}),archive: (serverId, roomId) => rpc.chats.archive(serverId, roomId),delete: (serverId, roomId) => rpc.chats.delete(serverId, roomId),+ markRead: (serverId, roomId, seq) =>+ rpc.chats.markRead({ serverId, roomId, seq }).catch((error: unknown) => {+ // The count stays at 0 here; the server's comes back with the next summary.+ log.warn('Could not save how far a chat has been read', {+ serverId,+ roomId,+ seq,+ error: String(error),+ });+ }),},chatsEventsFrom(events));diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.tsindex 3e3be644f..5151403b4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/stores/empty-chat-finder.test.ts@@ -24,6 +24,7 @@ const makeChat = (overrides: Partial<ChatSummary> = {}): ChatSummary => ({ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: null,...overrides,});diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsxindex 1adda8a8b..a52dd266c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx@@ -191,6 +191,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag{rooms.map((room) => (<RoomListRowkey={room.roomId}+ roomId={room.roomId}room={{name: switchRoomsStore.roomNameById(room.roomId) ?? room.roomName,bridgeType: switchRoomsStore.roomBridgeTypeById(room.roomId),diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsxindex c03f44235..7f9e60c16 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/main-section.tsx@@ -1,6 +1,7 @@import { DoorOpen, MessageCircle, X } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useState } from 'react';+import { UnreadBadge } from '@renderer/features/chats/components/unread-badge';import { ManagedAgentList } from '@renderer/features/managed-agents/managed-agent-list';import { useManagedAgents } from '@renderer/features/managed-agents/use-managed-agents';import { BuddyAvatar } from '@renderer/features/switch-buddy/buddy-avatar';@@ -119,6 +120,7 @@ const RoomList = observer(function RoomList({ rooms }: { rooms: RemoteRoomSummar{rooms.map((room) => (<RoomListRowkey={room.id}+ roomId={room.id}room={room}isActive={isRoomViewActive(room.id)}onOpen={() => openRoomView(room.id)}@@ -129,10 +131,12 @@ const RoomList = observer(function RoomList({ rooms }: { rooms: RemoteRoomSummar});export function RoomListRow({+ roomId,room,isActive,onOpen,}: {+ roomId: string;room: Pick<RemoteRoomSummary, 'name' | 'bridgeType' | 'bridgeDisplayName'>;isActive: boolean;onOpen: () => void;@@ -151,6 +155,7 @@ export function RoomListRow({<DoorOpen className="size-[17px] shrink-0 text-[var(--fg-icon)]" />)}<span className="min-w-0 flex-1 truncate">{room.name}</span>+ <UnreadBadge roomId={roomId} /></SidebarMenuRow>);}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsxindex ce17778f8..2113146a0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/room-tree.tsx@@ -1,5 +1,6 @@import { observer } from 'mobx-react-lite';import { Fragment } from 'react';+import { UnreadBadge } from '@renderer/features/chats/components/unread-badge';import type { SessionStore } from '@renderer/features/sessions/stores/session-store';import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';import { useListedRoomsInActiveScope } from '@renderer/features/switch-servers/use-listed-rooms';@@ -156,6 +157,7 @@ export const RoomTree = observer(function RoomTree() {expanded={expanded}depth={0}bridgeType={switchRoomsStore.roomBridgeTypeById(roomKey)}+ badge={<UnreadBadge roomId={roomKey} />}onToggle={() => sidebarStore.toggleGroupExpanded(roomViewKey)}onSelect={() => openRoomView(roomKey)}isActive={isRoomViewActive(roomKey)}diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsxindex 6ecdecd48..55d596586 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-room-grouping.tsx@@ -155,6 +155,7 @@ export function RoomRow({bridgeType = null,nameKnown = true,nameBlockedBySignIn = false,+ badge = null,}: {label: string;/** Whether there is anything under this room to unfold. */@@ -184,6 +185,8 @@ export function RoomRow({depth?: number;/** Bridge platform type (`slack`, `mattermost`, …) when the room is bridged. */bridgeType?: string | null;+ /** Beside the name, such as how many messages wait to be read. */+ badge?: React.ReactNode;}) {// Offered wherever the room has a channel to open, whether or not its// platform has a logo: the link is what makes the action work, not the icon.@@ -229,6 +232,7 @@ export function RoomRow({</TooltipContent></Tooltip>)}+ {badge}{hasRoomActions && (<DropdownMenu><DropdownMenuTriggerdiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.tsindex 60b85f608..dfb30ad2c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/room-filters.test.ts@@ -73,6 +73,7 @@ const chat = (roomId: string, extra: Partial<ChatSummary> = {}): ChatSummary =>ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: null,...extra,});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsxindex e3f5f4518..901374821 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-rooms-view.tsx@@ -2,6 +2,7 @@ import { ChevronDown, DoorOpen, MessagesSquare, Plus } from 'lucide-react';import { observer } from 'mobx-react-lite';import { useEffect, useState } from 'react';import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';+import { UnreadBadge } from '@renderer/features/chats/components/unread-badge';import { agentsStore } from '@renderer/features/locations/stores/agents-store';import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';import { openRoom } from '@renderer/features/switch-rooms/open-room';@@ -230,7 +231,10 @@ const RoomRow = observer(function RoomRow({className="group/room flex w-full cursor-pointer items-center gap-3 bg-background px-4 py-3 text-left transition-colors hover:bg-[var(--fill)]"><div className="flex min-w-0 flex-1 flex-col">- <span className="truncate text-sm font-medium text-foreground">{roomTitle(room)}</span>+ <span className="flex items-center gap-2">+ <span className="truncate text-sm font-medium text-foreground">{roomTitle(room)}</span>+ <UnreadBadge roomId={room.id} />+ </span>{/* An empty room is a state, not a quantity. "0 agents" reads as ameasurement of something that is working; a room nobody is in is aroom that cannot answer, and it should say so in words. */}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.tsindex dc2594791..ed81e4708 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-agent-conversations.test.ts@@ -28,6 +28,7 @@ const summary = (overrides: Partial<ChatSummary>): ChatSummary => ({ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: null,...overrides,});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.tsindex 46f5fa584..279f1fae1 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-configuration.test.ts@@ -50,6 +50,7 @@ function render(canManage: boolean): string {ownsAgent: false,memberUserIds: ['u1', 'u2'],memberCount: 2,+ unreadCount: 0,lastMessage: null,};const client = new QueryClient();@@ -109,6 +110,7 @@ describe('chatMembersQueryKey', () => {...base,memberUserIds,memberCount: memberUserIds.length,+ unreadCount: 0,...extra,});const now = key(['u1', 'u2']);diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.tsindex a1803211d..6adc2602a 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-titler.test.ts@@ -25,6 +25,7 @@ function summary(roomId: string, channelType: ChatSummary['channelType'] = 'direownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: null,};}diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.tsindex c40241fc4..e21d4571a 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chats-store.test.ts@@ -4,6 +4,7 @@ import {ChatsStore,type ChatsApi,type ChatsEvents,+ READ_DEBOUNCE_MS,} from '@renderer/features/chats/stores/chats-store';import type { ChatMessage, ChatSummary } from '@shared/core/chats/chats';@@ -36,6 +37,7 @@ function summary(roomId: string, seq: number): ChatSummary {ownsAgent: false,memberUserIds: [],memberCount: 0,+ unreadCount: 0,lastMessage: { seq, sentAt: '2026-01-01T00:00:00Z', preview: 'hi', senderName: 'Ada' },};}@@ -88,6 +90,7 @@ function setup(timeline: () => timeline as TimelineApi,archive: vi.fn(async () => {}),delete: vi.fn(async () => {}),+ markRead: vi.fn(async () => {}),};const store = new ChatsStore(api, events);return {@@ -271,8 +274,13 @@ describe('ChatsStore', () => {/** A viewer's store whose feed the test drives, already connected to `s1`. */async function viewer() {let onSummary: Parameters<ChatsEvents['onSummary']>[0] = () => {};+ let onMessage: Parameters<ChatsEvents['onMessage']>[0] = () => {};+ const markRead = vi.fn(async () => {});const events: ChatsEvents = {- onMessage: () => () => {},+ onMessage: (cb) => {+ onMessage = cb;+ return () => {};+ },onSummary: (cb) => {onSummary = cb;return () => {};@@ -291,11 +299,18 @@ async function viewer() {timeline: () => ({}) as TimelineApi,archive: async () => {},delete: async () => {},+ markRead,},events);await store.connect('s1');- return { store, push: (chat: ChatSummary) => onSummary({ serverId: 's1', chat }), group };+ return {+ store,+ push: (chat: ChatSummary) => onSummary({ serverId: 's1', chat }),+ emit: (m: ChatMessage) => onMessage({ serverId: 's1', message: m }),+ markRead,+ group,+ };}describe('ChatsStore membership', () => {@@ -310,3 +325,46 @@ describe('ChatsStore membership', () => {expect(store.chat('g')?.name).toBe('renamed');});});++describe('ChatsStore unread counts', () => {+ const from = (roomId: string, seq: number, userId: string) => ({+ ...message(roomId, seq),+ sender: { ...message(roomId, seq).sender, userId },+ });++ it('counts others’ new messages in rooms not being read, and takes the server’s count', async () => {+ const { store, emit, push, group } = await viewer();+ emit(from('g', 2, 'bob'));+ emit(from('g', 3, 'bob'));+ emit(from('g', 3, 'bob'));+ expect(store.unread('g')).toBe(2);+ emit(from('g', 4, 'u'));+ expect(store.unread('g')).toBe(2);+ store.setViewing('g');+ emit(from('g', 5, 'bob'));+ expect(store.unread('g')).toBe(0);+ store.setViewing(null);+ expect(store.unread('g')).toBe(2);+ push({ ...group, unreadCount: 7 });+ expect(store.unread('g')).toBe(7);+ });++ it('marks read at once here and sends the furthest position once, never backwards', async () => {+ vi.useFakeTimers();+ try {+ const { store, push, group, markRead } = await viewer();+ push({ ...group, unreadCount: 3 });+ store.read('g', 5);+ store.read('g', 9);+ expect(store.unread('g')).toBe(0);+ vi.advanceTimersByTime(READ_DEBOUNCE_MS);+ expect(markRead).toHaveBeenCalledTimes(1);+ expect(markRead).toHaveBeenCalledWith('s1', 'g', 9);+ store.read('g', 4);+ vi.advanceTimersByTime(READ_DEBOUNCE_MS);+ expect(markRead).toHaveBeenCalledTimes(1);+ } finally {+ vi.useRealTimers();+ }+ });+});diff --git a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts b/console/apps/switch-console-desktop/src/shared/core/chats/chats.tsindex 1fd7c35a5..85620f016 100644--- a/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts+++ b/console/apps/switch-console-desktop/src/shared/core/chats/chats.ts@@ -32,6 +32,8 @@ export const chatSummarySchema = z.object({/** The people in the chat, by user id, sorted. */memberUserIds: z.array(z.string()),memberCount: z.number().int(),+ /** Messages since the viewer last read the chat; 0 from a server older than read positions. */+ unreadCount: z.number().int().default(0),lastMessage: z.object({seq: z.number().int(),