Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
32 changes: 32 additions & 0 deletions src/server/chat/ChatService.threads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
15 changes: 12 additions & 3 deletions src/server/chat/ChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<number> {
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);

Expand Down
2 changes: 2 additions & 0 deletions src/shared/chatTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 5 additions & 3 deletions src/web/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string | undefined>(undefined);
const [channels, setChannels] = useState<ChannelSummary[]>([]);
Expand Down Expand Up @@ -1668,6 +1669,7 @@ function App(): ReactElement {
botId={selectedBotId}
activeId={chatId ?? selectedBotId}
refreshKey={threadRefreshKey}
unreadIds={unreadIds}
onSelect={handleSelectChat}
/>
)}
Expand Down
20 changes: 16 additions & 4 deletions src/web/components/ThreadBar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} onSelect={onSelect} />);
render(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} unreadIds={new Set()} onSelect={onSelect} />);

const sideChip = await screen.findByRole('tab', { name: 'Trip plan' });

Expand All @@ -53,7 +53,7 @@ describe('ThreadBar', () => {

vi.mocked(createThread)
.mockResolvedValue({ id: 'thread-2', name: 'New chat', isDefault: false, isRunning: false });
render(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} onSelect={onSelect} />);
render(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} unreadIds={new Set()} onSelect={onSelect} />);
await screen.findByRole('tab', { name: 'Trip plan' });
fireEvent.click(screen.getByRole('button', { name: 'New chat' }));

Expand All @@ -68,7 +68,7 @@ describe('ThreadBar', () => {

vi.mocked(deleteThread)
.mockResolvedValue(undefined);
render(<ThreadBar botId="bot-1" activeId="thread-1" refreshKey={0} onSelect={onSelect} />);
render(<ThreadBar botId="bot-1" activeId="thread-1" refreshKey={0} unreadIds={new Set()} onSelect={onSelect} />);
await screen.findByRole('tab', { name: 'Trip plan' });
fireEvent.click(screen.getByRole('button', { name: 'Delete this chat' }));
fireEvent.click(await screen.findByRole('button', { name: 'Delete' }));
Expand All @@ -81,8 +81,20 @@ describe('ThreadBar', () => {
});
});

it('marks only the chats with an unread reply', async () => {
render(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} unreadIds={new Set(['thread-1'])} onSelect={vi.fn()} />);

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(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} onSelect={vi.fn()} />);
render(<ThreadBar botId="bot-1" activeId="bot-1" refreshKey={0} unreadIds={new Set()} onSelect={vi.fn()} />);
await screen.findByRole('tab', { name: 'Trip plan' });

expect(screen.queryByRole('button', { name: 'Delete this chat' }))
Expand Down
5 changes: 4 additions & 1 deletion src/web/components/ThreadBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ 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<string>;
onSelect: (chatId: string) => void;
}

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<string | undefined>(undefined);
const [isDeleting, setIsDeleting] = useState(false);
Expand Down Expand Up @@ -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);
}}
Expand Down
11 changes: 11 additions & 0 deletions src/web/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
52 changes: 47 additions & 5 deletions src/web/unreadMarks.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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([]);
});
});
Loading
Loading