From e12121b0e50431f02cbf2033c120044c2fc8186d Mon Sep 17 00:00:00 2001 From: mateuscmtropical Date: Sat, 7 Nov 2026 22:28:34 -0300 Subject: [PATCH] feat(chat): unread marks for threads Closes #622 --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 2 +- src/server/chat/ChatService.threads.test.ts | 32 +++++++++++++ src/server/chat/ChatService.ts | 15 ++++-- src/shared/chatTypes.ts | 2 + src/web/App.tsx | 8 ++-- src/web/components/ThreadBar.test.tsx | 20 ++++++-- src/web/components/ThreadBar.tsx | 5 +- src/web/styles.css | 11 +++++ src/web/unreadMarks.test.ts | 52 +++++++++++++++++++-- src/web/unreadMarks.ts | 52 ++++++++++++++------- 11 files changed, 166 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e97ca92..490ab514 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ All notable changes to this project are listed here. The format follows - App triggers: say "when a new issue opens on repo X, do Y" or "when a mail from Ana arrives, do Y" and the bot sets it up itself with `trigger_create`, with no webhook. CloudBot checks the app every 15 minutes by default (10 minutes at least) and wakes the bot only when something new appears, so a check with nothing new costs no model call. Sources are GitHub issues, GitHub pull requests and Gmail. Gmail uses the Gmail app from Connect apps, and a private repository uses the `GITHUB_TOKEN` secret. The first check only records what is there. The new items reach the bot as text from outside, never as instructions. Trigger turns use the routines model, effort and limits. A bot has at most 10 triggers. - A bot can have several chats that run at the same time. The new chat button under the header starts a side chat with its own history and session, and the chips switch between them. Memory, rules, skills, secrets and routines stay with the bot. A bot runs at most 3 chats at once, the others wait and start when one ends, and it keeps at most 8 side chats. Routines, webhooks and Telegram keep going to the bot's own chat. - App triggers now have an owner panel. Profile, App triggers lists each trigger with its source, target, interval and last check, and the owner can pause, resume or delete it. A paused trigger is not checked and does not keep the instance awake. Resuming records a new baseline, so nothing from the pause is sent. Two Google Calendar sources join the list. `calendar_new_event` wakes the bot for an event added in the last check. `calendar_starting` wakes it when an event is about to start, with a target such as `15` or `15 team@example.com`, and it needs a check interval no longer than those minutes. Both use the Google Calendar app from Connect apps, and the event text reaches the bot as data from outside. +- A bot can have several chats that run at the same time. The new chat button under the header starts a side chat with its own history and session, and the chips switch between them. Memory, rules, skills, secrets and routines stay with the bot. A bot runs at most 3 chats at once, the others wait and start when one ends, and it keeps at most 8 side chats. Routines, webhooks and Telegram keep going to the bot's own chat. A chat with a reply you have not seen shows a dot on its chip, and the bot shows a dot in the list until you open that chat. A reply that only adds a tool line does not count. - A file dragged from the computer and dropped anywhere on the chat is attached to the message, like with the attach button. - The bots keep long-term memory in ai-memory, a local MCP server that runs beside each server. Claude and Codex bots get it. Set `CLOUDBOT_AI_MEMORY=off` to turn it off, see docs/MEMORY.md. - Shared groups let people on one server work together. Add person can invite the new person to a new or existing group, and each of your bots can stay with you, be copied to the group or move there. Everyone in a group sees it under Shared with people in their own CloudBot. Inside it, each message shows who wrote it, and Members lists the people. An admin or the owner adds and removes people and bots. Anyone approves bot actions, but money or a bot delete needs an admin or the owner. Nobody can remove the owner of a group. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f793ef54..26402ebb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -553,7 +553,7 @@ never stored. When the block ends, its whole text goes out once as a `message` event, which replaces the draft. The web app shows the draft as an assistant bubble, so the text is never shown twice. -`GET /api/events` is one stream with the `message` and `botDeleted` events of every bot. The bot list uses it to reload the previews and to mark a closed chat as unread. Each bot summary has `lastMessageSequence`, the sequence of the newest message from the bot. The browser keeps the newest sequence it has seen for each bot, and the row is unread when the bot has a newer one and its chat is not open. +`GET /api/events` is one stream with the `message` and `botDeleted` events of every bot. The bot list uses it to reload the previews and to mark a closed chat as unread. Each bot summary has `lastMessageSequence`, the sequence of the newest message from the bot. The browser keeps the newest sequence it has seen for each bot, and the row is unread when the bot has a newer one and its chat is not open. The summary also lists `threads` with the same sequence for each thread. The browser tracks a thread like a bot, by its id. A thread chip is unread when its sequence is newer than the seen one and it is not open, and the bot row is unread when its own chat or any thread is, unless the bot is the open one. ## Attachments diff --git a/src/server/chat/ChatService.threads.test.ts b/src/server/chat/ChatService.threads.test.ts index c009fc37..8a7d7404 100644 --- a/src/server/chat/ChatService.threads.test.ts +++ b/src/server/chat/ChatService.threads.test.ts @@ -78,6 +78,38 @@ describe('ChatService threads', () => { .toBeUndefined(); }); + it('reports the newest readable message of each thread, so a reply can mark the bot as unread', async () => { + const toolOnly = new FakeAgentRunner([ + { event: { type: 'tool_started', toolUseId: 'tool-1', toolName: 'Bash', input: { command: 'ls' } } }, + { event: { type: 'tool_finished', toolUseId: 'tool-1', isError: false, output: 'a.txt' } }, + ]); + const toolService = new ChatService({ botStore, messageStore, runner: toolOnly, dataDir }); + const bot = await botStore.create({ name: 'Ana', title: 'Assistant', description: '' }); + const thread = await createThreadOrFail(toolService, bot.id); + + await toolService.sendMessage(thread.id, 'list files'); + await waitUntilIdle(toolService, thread.id); + + const [afterTools] = await toolService.listBots(); + + expect(afterTools?.threads) + .toEqual([{ id: thread.id, lastMessageSequence: 0 }]); + + const textService = new ChatService({ botStore, messageStore, runner: new FakeAgentRunner([{ event: { type: 'text', text: 'Done.' } }]), dataDir }); + + await textService.resumeQueue(); + await textService.sendMessage(thread.id, 'and now'); + await waitUntilIdle(textService, thread.id); + + const [afterReply] = await textService.listBots(); + const reply = (await textService.listMessages(thread.id))?.find(message => message.role === 'assistant' && message.body.kind === 'text'); + + expect(afterReply?.threads) + .toEqual([{ id: thread.id, lastMessageSequence: reply?.sequence }]); + expect(afterReply?.lastMessageSequence) + .toBe(0); + }); + it('gives a thread its own history and session and names it after its first message', async () => { const runner = new FakeAgentRunner([{ event: { type: 'session', sessionId: 'session-x' } }, { event: { type: 'text', text: 'Done.' } }]); const service = new ChatService({ botStore, messageStore, runner, dataDir }); diff --git a/src/server/chat/ChatService.ts b/src/server/chat/ChatService.ts index 6d92c6e4..e9ca0e9d 100644 --- a/src/server/chat/ChatService.ts +++ b/src/server/chat/ChatService.ts @@ -3943,8 +3943,9 @@ class ChatService { const lastMessagePreview = latestMessage === undefined ? '' : previewOf(latestMessage.content as MessageBody); - const recentMessages = await this.messageStore.listByBot(bot.id, { limit: UNREAD_SCAN_LIMIT }); - const lastReadableMessage = recentMessages.find(message => isReadableForOwner(message.role, message.content as MessageBody)); + const threadSequencePromises = this.threadIdsOf(bot.id) + .map(async id => ({ id, lastMessageSequence: await this.lastReadableSequence(id) })); + const threads = await Promise.all(threadSequencePromises); return { id: bot.id, @@ -3958,10 +3959,18 @@ class ChatService { lastMessagePreview, ...(latestMessage === undefined ? {} : { lastActivityAt: latestMessage.createdAt }), hasUnread: false, - lastMessageSequence: lastReadableMessage?.sequence ?? 0, + lastMessageSequence: await this.lastReadableSequence(bot.id), + threads, }; } + private async lastReadableSequence(chatId: string): Promise { + const recentMessages = await this.messageStore.listByBot(chatId, { limit: UNREAD_SCAN_LIMIT }); + const lastReadableMessage = recentMessages.find(message => isReadableForOwner(message.role, message.content as MessageBody)); + + return lastReadableMessage?.sequence ?? 0; + } + private publish(botId: string, event: ChatEvent): void { const listeners = this.listenersByBot.get(botId); diff --git a/src/shared/chatTypes.ts b/src/shared/chatTypes.ts index bb32a18a..c6ab0a75 100644 --- a/src/shared/chatTypes.ts +++ b/src/shared/chatTypes.ts @@ -144,6 +144,8 @@ interface BotSummary { hasUnread: boolean; // The sequence of the latest message the owner can read, not counting the owner's own and tool lines. Zero when there is none. lastMessageSequence: number; + // The same sequence for each thread of the bot, so a reply in a thread can mark the bot as unread. + threads?: { id: string; lastMessageSequence: number }[]; } // One chat of a bot. The default thread is the bot's own chat and carries the bot's name. The others are side chats. diff --git a/src/web/App.tsx b/src/web/App.tsx index 763c4429..13ea34d1 100644 --- a/src/web/App.tsx +++ b/src/web/App.tsx @@ -24,7 +24,7 @@ import { PullIndicator } from './components/PullIndicator.tsx'; import { UpdateBanner } from './components/UpdateBanner.tsx'; import { changeBotMascot, createBot, createChannel, deleteBot, deleteChannel, getChannel, updateChannel, getScreenHolder, listBots, listChannels, listMessages, postChannelMessage, RequestFailedError, stopChannel, sendMessage, stopTurn, submitChoice, submitCode, submitSecret, subscribeToAllBotEvents, subscribeToEvents, uploadAttachments, listUploads, removeUpload, renameBot } from './apiClient.ts'; import { mergeLoadedUploads } from './attachmentChips.ts'; -import { loadSeen, markUnread, saveSeen, updateSeen } from './unreadMarks.ts'; +import { loadSeen, markUnread, saveSeen, unreadChatIds, updateSeen } from './unreadMarks.ts'; import { applyTabIcon } from './tabIcon.ts'; import { MESSAGE_PAGE_SIZE, mergeMessages, removeMessages, upsertLiveMessage, upsertMessage } from './messageList.ts'; import { withoutToolRows } from './thinkingBubble.ts'; @@ -147,13 +147,14 @@ function App(): ReactElement { const [threadRefreshKey, setThreadRefreshKey] = useState(0); // The newest message of each bot that the owner has seen. A closed chat with a newer one shows as unread. const [seenSequences, setSeenSequences] = useState(loadSeen); - const nextSeenSequences = updateSeen(seenSequences, bots, selectedBotId); + const nextSeenSequences = updateSeen(seenSequences, bots, chatId); if (nextSeenSequences !== seenSequences) { setSeenSequences(nextSeenSequences); } - const botsWithUnread = useMemo(() => markUnread(bots, nextSeenSequences, selectedBotId), [bots, nextSeenSequences, selectedBotId]); + const unreadIds = useMemo(() => unreadChatIds(bots, nextSeenSequences, chatId), [bots, nextSeenSequences, chatId]); + const botsWithUnread = useMemo(() => markUnread(bots, unreadIds, selectedBotId), [bots, unreadIds, selectedBotId]); // A channel replaces the bot's conversation while it is selected. Only one of the two is shown. const [selectedChannelId, setSelectedChannelId] = useState(undefined); const [channels, setChannels] = useState([]); @@ -1668,6 +1669,7 @@ function App(): ReactElement { botId={selectedBotId} activeId={chatId ?? selectedBotId} refreshKey={threadRefreshKey} + unreadIds={unreadIds} onSelect={handleSelectChat} /> )} diff --git a/src/web/components/ThreadBar.test.tsx b/src/web/components/ThreadBar.test.tsx index 13d4e99f..d70c2b03 100644 --- a/src/web/components/ThreadBar.test.tsx +++ b/src/web/components/ThreadBar.test.tsx @@ -32,7 +32,7 @@ describe('ThreadBar', () => { it('shows the own chat as Main and the other chats by name, and opens one on tap', async () => { const onSelect = vi.fn(); - render(); + render(); const sideChip = await screen.findByRole('tab', { name: 'Trip plan' }); @@ -53,7 +53,7 @@ describe('ThreadBar', () => { vi.mocked(createThread) .mockResolvedValue({ id: 'thread-2', name: 'New chat', isDefault: false, isRunning: false }); - render(); + render(); await screen.findByRole('tab', { name: 'Trip plan' }); fireEvent.click(screen.getByRole('button', { name: 'New chat' })); @@ -68,7 +68,7 @@ describe('ThreadBar', () => { vi.mocked(deleteThread) .mockResolvedValue(undefined); - render(); + render(); await screen.findByRole('tab', { name: 'Trip plan' }); fireEvent.click(screen.getByRole('button', { name: 'Delete this chat' })); fireEvent.click(await screen.findByRole('button', { name: 'Delete' })); @@ -81,8 +81,20 @@ describe('ThreadBar', () => { }); }); + it('marks only the chats with an unread reply', async () => { + render(); + + const sideChip = await screen.findByRole('tab', { name: 'Trip plan' }); + + expect(sideChip.getAttribute('data-unread')) + .toBe('true'); + expect(screen.getByRole('tab', { name: 'Main' }) + .getAttribute('data-unread')) + .toBeNull(); + }); + it('offers no delete button on the own chat', async () => { - render(); + render(); await screen.findByRole('tab', { name: 'Trip plan' }); expect(screen.queryByRole('button', { name: 'Delete this chat' })) diff --git a/src/web/components/ThreadBar.tsx b/src/web/components/ThreadBar.tsx index 3ff48784..95b1ae52 100644 --- a/src/web/components/ThreadBar.tsx +++ b/src/web/components/ThreadBar.tsx @@ -13,6 +13,8 @@ interface ThreadBarProps { activeId: string; // Goes up when something may have changed a thread, such as a new message or a turn that ended. refreshKey: number; + // The chats with a reply the owner has not seen. + unreadIds: Set; onSelect: (chatId: string) => void; } @@ -20,7 +22,7 @@ const OWN_CHAT_LABEL = 'Main'; // The chats of a bot as a row of chips, with a button for a new one. Each chat has its own history and works on its own, // while the bot keeps one memory, one set of rules and one set of secrets for all of them. -function ThreadBar({ botId, activeId, refreshKey, onSelect }: ThreadBarProps): ReactElement { +function ThreadBar({ botId, activeId, refreshKey, unreadIds, onSelect }: ThreadBarProps): ReactElement { const [loaded, setLoaded] = useState<{ botId: string; threads: ThreadSummary[] } | undefined>(undefined); const [problem, setProblem] = useState(undefined); const [isDeleting, setIsDeleting] = useState(false); @@ -85,6 +87,7 @@ function ThreadBar({ botId, activeId, refreshKey, onSelect }: ThreadBarProps): R aria-selected={thread.id === activeId} className="thread-chip" data-running={thread.isRunning ? 'true' : undefined} + data-unread={unreadIds.has(thread.id) ? 'true' : undefined} onClick={() => { onSelect(thread.id); }} diff --git a/src/web/styles.css b/src/web/styles.css index 2306b69c..5a183104 100644 --- a/src/web/styles.css +++ b/src/web/styles.css @@ -1716,6 +1716,17 @@ button.list-row { border-radius: 50%; } +/* A chat with a reply the owner has not seen shows the accent dot, like the bot list. */ +.thread-chip[data-unread='true']::before { + content: ''; + display: inline-block; + width: 8px; + height: 8px; + margin-right: var(--space-2); + background: var(--color-accent); + border-radius: 50%; +} + .thread-action { display: inline-flex; flex: none; diff --git a/src/web/unreadMarks.test.ts b/src/web/unreadMarks.test.ts index ed0b1ab5..4d7752b2 100644 --- a/src/web/unreadMarks.test.ts +++ b/src/web/unreadMarks.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest'; import type { BotSummary } from '../shared/chatTypes.ts'; -import { markUnread, updateSeen } from './unreadMarks.ts'; +import { markUnread, unreadChatIds, updateSeen } from './unreadMarks.ts'; -function createBot(id: string, lastMessageSequence: number): BotSummary { - return { id, name: id, title: '', mascotColor: 'blue', mascotShape: 'puff', mascotEyes: 'smile', mascotWeather: 'auto', mascotBolt: 'down', lastMessagePreview: '', hasUnread: false, lastMessageSequence }; +function createBot(id: string, lastMessageSequence: number, threads?: BotSummary['threads']): BotSummary { + return { id, name: id, title: '', mascotColor: 'blue', mascotShape: 'puff', mascotEyes: 'smile', mascotWeather: 'auto', mascotBolt: 'down', lastMessagePreview: '', hasUnread: false, lastMessageSequence, ...(threads === undefined ? {} : { threads }) }; } describe('updateSeen', () => { @@ -26,21 +26,63 @@ describe('updateSeen', () => { expect(updateSeen(seen, [createBot('a', 9)], 'a')) .toBe(seen); }); + + it('moves only the open thread up, not its bot or its sibling threads', () => { + const seen = { a: 3, t1: 3, t2: 3 }; + const bot = createBot('a', 9, [{ id: 't1', lastMessageSequence: 9 }, { id: 't2', lastMessageSequence: 9 }]); + + expect(updateSeen(seen, [bot], 't1')) + .toEqual({ a: 3, t1: 9, t2: 3 }); + }); + + it('counts a thread met for the first time as seen', () => { + const bot = createBot('a', 4, [{ id: 't1', lastMessageSequence: 6 }]); + + expect(updateSeen({ a: 4 }, [bot], 'a')) + .toEqual({ a: 4, t1: 6 }); + }); }); describe('markUnread', () => { it('marks a closed chat with a newer message and clears the open one', () => { const bots = [createBot('a', 9), createBot('b', 9)]; - const marked = markUnread(bots, { a: 3, b: 3 }, 'a'); + const seen = { a: 3, b: 3 }; + const marked = markUnread(bots, unreadChatIds(bots, seen, 'a'), 'a'); expect(marked.map(bot => bot.hasUnread)) .toEqual([false, true]); }); it('does not mark a chat that has nothing new', () => { - const marked = markUnread([createBot('a', 4)], { a: 4 }, undefined); + const bots = [createBot('a', 4)]; + const marked = markUnread(bots, unreadChatIds(bots, { a: 4 }, undefined), undefined); expect(marked[0]?.hasUnread) .toBe(false); }); + + it('marks the bot when only one of its threads has a newer message', () => { + const bots = [createBot('a', 4, [{ id: 't1', lastMessageSequence: 8 }]), createBot('b', 4)]; + const marked = markUnread(bots, unreadChatIds(bots, { a: 4, t1: 5, b: 4 }, 'b'), 'b'); + + expect(marked.map(bot => bot.hasUnread)) + .toEqual([true, false]); + }); + + it('does not mark the open bot for another thread, but lists that thread as unread', () => { + const bots = [createBot('a', 4, [{ id: 't1', lastMessageSequence: 8 }])]; + const unreadIds = unreadChatIds(bots, { a: 4, t1: 5 }, 'a'); + + expect(markUnread(bots, unreadIds, 'a')[0]?.hasUnread) + .toBe(false); + expect([...unreadIds]) + .toEqual(['t1']); + }); + + it('clears the mark once the thread is open', () => { + const bots = [createBot('a', 4, [{ id: 't1', lastMessageSequence: 8 }])]; + + expect([...unreadChatIds(bots, { a: 4, t1: 5 }, 't1')]) + .toEqual([]); + }); }); diff --git a/src/web/unreadMarks.ts b/src/web/unreadMarks.ts index 33b888ab..86903967 100644 --- a/src/web/unreadMarks.ts +++ b/src/web/unreadMarks.ts @@ -1,32 +1,50 @@ import type { BotSummary } from '../shared/chatTypes.ts'; -// The newest message sequence the owner has seen in each bot, by bot id. +// The newest message sequence the owner has seen in each chat, by chat id. A chat is a bot's own chat or one of its threads. type SeenSequences = Record; const STORAGE_KEY = 'cloudbot.seenSequences'; -// The seen marks after this list of bots. The open bot counts as seen up to its newest message. -// A bot met for the first time counts as seen, so a new browser does not mark every chat. Returns the same object when nothing changed. -function updateSeen(seen: SeenSequences, bots: BotSummary[], openBotId: string | undefined): SeenSequences { - const changedEntries = bots.flatMap((bot): [string, number][] => { - const current = seen[bot.id]; - const isOpen = bot.id === openBotId; +// The own chat of a bot and its threads, with the newest message sequence of each. +function chatsOf(bot: BotSummary): { id: string; lastMessageSequence: number }[] { + return [{ id: bot.id, lastMessageSequence: bot.lastMessageSequence }, ...(bot.threads ?? [])]; +} - if (current === undefined || (isOpen && current < bot.lastMessageSequence)) { - return [[bot.id, bot.lastMessageSequence]]; - } +// The seen marks after this list of bots. The open chat counts as seen up to its newest message. +// A chat met for the first time counts as seen, so a new browser does not mark every chat. Returns the same object when nothing changed. +function updateSeen(seen: SeenSequences, bots: BotSummary[], openChatId: string | undefined): SeenSequences { + const changedEntries = bots.flatMap(chatsOf) + .flatMap((chat): [string, number][] => { + const current = seen[chat.id]; + const isOpen = chat.id === openChatId; - return []; - }); + if (current === undefined || (isOpen && current < chat.lastMessageSequence)) { + return [[chat.id, chat.lastMessageSequence]]; + } + + return []; + }); return changedEntries.length === 0 ? seen : { ...seen, ...Object.fromEntries(changedEntries) }; } -// The bots with hasUnread set for a message the owner has not seen in a chat that is not open. -function markUnread(bots: BotSummary[], seen: SeenSequences, openBotId: string | undefined): BotSummary[] { +// The ids of the chats with a message the owner has not seen, apart from the open chat. +function unreadChatIds(bots: BotSummary[], seen: SeenSequences, openChatId: string | undefined): Set { + const unreadChats = bots.flatMap(chatsOf) + .filter(chat => chat.id !== openChatId && chat.lastMessageSequence > (seen[chat.id] ?? chat.lastMessageSequence)); + + const ids = unreadChats.map(chat => chat.id); + + return new Set(ids); +} + +// The bots with hasUnread set when the bot or any of its threads has an unread chat. The open bot is never marked, +// since its chats show their own marks. +function markUnread(bots: BotSummary[], unreadIds: Set, openBotId: string | undefined): BotSummary[] { return bots.map((bot) => { - const seenSequence = seen[bot.id] ?? bot.lastMessageSequence; - const isUnread = bot.id !== openBotId && bot.lastMessageSequence > seenSequence; + const hasUnreadChat = chatsOf(bot) + .some(chat => unreadIds.has(chat.id)); + const isUnread = bot.id !== openBotId && hasUnreadChat; return isUnread === bot.hasUnread ? bot : { ...bot, hasUnread: isUnread }; }); @@ -53,5 +71,5 @@ function saveSeen(seen: SeenSequences): void { } } -export { loadSeen, markUnread, saveSeen, updateSeen }; +export { loadSeen, markUnread, saveSeen, unreadChatIds, updateSeen }; export type { SeenSequences };