Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(chats): show archived chats, unarchive them, and let a message bring one back

raullopez-sandbox6bf6329a09e3
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.ts
index 71c1ac74a..1e9757f9e 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
@@ -47,6 +47,7 @@ import {
fetchThreadMessages,
listChatCommands,
listChatMembers,
+ listArchivedChats,
listChats,
listWorkspaceMembers,
listAgentCandidates,
@@ -56,6 +57,7 @@ import {
renameChat,
sendChatControl,
sendChatMessage,
+ unarchiveChat,
uploadChatAttachment,
warmChatAgent,
} from './gateway';
@@ -157,6 +159,7 @@ export const chatsController = createRPCController({
return { userId: me.id, tenantId: workspace.tenantId };
},
list: (serverId: string): Promise<ChatSummary[]> => onServer(serverId, listChats),
+ listArchived: (serverId: string): Promise<ChatSummary[]> => onServer(serverId, listArchivedChats),
/** `greeting`: what the chat's one agent, the caller's own, says as it joins, in place of its usual line. */
create: async (params: {
serverId: string;
@@ -262,6 +265,8 @@ export const chatsController = createRPCController({
},
archive: (serverId: string, roomId: string): Promise<void> =>
onServer(serverId, (server) => archiveChat(server, roomId)),
+ unarchive: (serverId: string, roomId: string): Promise<void> =>
+ onServer(serverId, (server) => unarchiveChat(server, roomId)),
delete: (serverId: string, roomId: string): Promise<void> =>
onServer(serverId, async (server) => {
await deleteRoom(server, roomId);
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.ts
index 6abd29687..97922a01c 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
@@ -113,6 +113,10 @@ export async function listChats(server: SwitchServer): Promise<ChatSummary[]> {
return parseChatRows((await json(server, '/chats', chatListSchema)).chats);
}
+export async function listArchivedChats(server: SwitchServer): Promise<ChatSummary[]> {
+ return parseChatRows((await json(server, '/chats/archived', chatListSchema)).chats);
+}
+
/**
* One agent goes as `agentId`, which every server with chats accepts; only a
* chat with several needs `agentIds`. Zero agents allowed; memberUserIds optional.
@@ -370,6 +374,10 @@ export async function archiveChat(server: SwitchServer, roomId: string): Promise
await call(server, `${room(roomId)}/archive`, { method: 'POST' });
}
+export async function unarchiveChat(server: SwitchServer, roomId: string): Promise<void> {
+ await call(server, `${room(roomId)}/unarchive`, { method: 'POST' });
+}
+
/** Rename uses the room route: a chat's name is its room's name. */
export async function renameChat(
server: SwitchServer,
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/archived-fold.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/archived-fold.tsx
new file mode 100644
index 000000000..7f02e605f
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/archived-fold.tsx
@@ -0,0 +1,32 @@
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import { type ReactNode, useState } from 'react';
+
+/** A fold under a list holding its archived entries, closed until asked for; nothing when there are none. */
+export function ArchivedFold({
+ count,
+ error,
+ children,
+}: {
+ count: number;
+ error: string | null;
+ children: ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ if (count === 0 && !error) return null;
+ const Chevron = open ? ChevronDown : ChevronRight;
+ return (
+ <div className="flex flex-col gap-[2px] pt-1">
+ <button
+ type="button"
+ aria-expanded={open}
+ onClick={() => setOpen(!open)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-foreground-muted hover:text-foreground"
+ >
+ <Chevron className="size-3.5" />
+ Archived{count > 0 ? ` (${count})` : ''}
+ </button>
+ {open && error && <p className="px-2 py-1 text-xs text-foreground-muted">{error}</p>}
+ {open && children}
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx
index de751ffd8..91f8da2f2 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-actions.tsx
@@ -1,4 +1,4 @@
-import { Archive, LogOut, Pencil, Trash2 } from 'lucide-react';
+import { Archive, ArchiveRestore, LogOut, Pencil, Trash2 } from 'lucide-react';
import { Fragment, type ReactNode } from 'react';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { toast } from '@renderer/lib/hooks/use-toast';
@@ -86,16 +86,27 @@ export function chatActions(serverId: string, chat: ChatSummary): ChatAction[] {
icon: <Pencil className="size-4" />,
run: () => showModal('renameChatModal', { serverId, roomId, currentName: chat.name }),
},
- {
- key: 'archive',
- label: 'Archive',
- icon: <Archive className="size-4" />,
- run: () =>
- void attempt(async () => {
- await chatsStore.archive(serverId, roomId);
- leaveIfOpen(roomId);
- }, 'Could not archive the chat.'),
- },
+ chatsStore.archived.has(roomId)
+ ? {
+ key: 'unarchive',
+ label: 'Unarchive',
+ icon: <ArchiveRestore className="size-4" />,
+ run: () =>
+ void attempt(
+ () => chatsStore.unarchive(serverId, roomId),
+ 'Could not unarchive the chat.'
+ ),
+ }
+ : {
+ key: 'archive',
+ label: 'Archive',
+ icon: <Archive className="size-4" />,
+ run: () =>
+ void attempt(async () => {
+ await chatsStore.archive(serverId, roomId);
+ leaveIfOpen(roomId);
+ }, 'Could not archive the chat.'),
+ },
{
key: 'delete',
label: 'Delete chat…',
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.ts
index a952c0ef1..7a5dd682e 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
@@ -31,9 +31,11 @@ export type ChatsApi = {
connect: (serverId: string) => Promise<{ state: ChatStreamState; detail: string | null }>;
disconnect: (serverId: string) => Promise<void>;
list: (serverId: string) => Promise<ChatSummary[]>;
+ listArchived: (serverId: string) => Promise<ChatSummary[]>;
identity: (serverId: string) => Promise<{ userId: string; tenantId: string | null }>;
timeline: (serverId: string) => TimelineApi;
archive: (serverId: string, roomId: string) => Promise<void>;
+ unarchive: (serverId: string, roomId: string) => Promise<void>;
delete: (serverId: string, roomId: string) => Promise<void>;
markRead: (serverId: string, roomId: string, seq: number) => Promise<void>;
removeMember: (serverId: string, roomId: string, userId: string) => Promise<void>;
@@ -63,6 +65,9 @@ export class ChatsStore {
removed = new Set<string>();
/** Rooms off the list while the person is still a member. */
unlisted = new Set<string>();
+ /** The person's archived chats: off the list, still readable, and written back into it. */
+ archived = new Map<string, ChatSummary>();
+ archivedError: string | null = null;
streamState: ChatStreamState = 'offline';
streamDetail: string | null = null;
listError: string | null = null;
@@ -92,7 +97,10 @@ export class ChatsStore {
});
events.onMessage(({ serverId, message }) => this.message(serverId, message));
events.onRemoved(({ serverId, roomId, reason }) => {
- if (serverId === this.serverId) this.remove(roomId, reason);
+ if (serverId !== this.serverId) return;
+ this.remove(roomId, reason);
+ // Archiving is one way a chat leaves the list while its people stay in it.
+ if (reason === 'unlisted') void this.loadArchived(serverId);
});
events.onState(({ serverId, state, detail }) => {
if (serverId !== this.serverId) return;
@@ -141,6 +149,8 @@ export class ChatsStore {
this.chats = new Map();
this.removed = new Set();
this.unlisted = new Set();
+ this.archived = new Map();
+ this.archivedError = null;
this.userId = null;
this.tenantId = null;
this.listError = null;
@@ -173,15 +183,36 @@ export class ChatsStore {
this.listError = failureText(error, 'Your chats could not be listed.');
});
}
+ await this.loadArchived(serverId);
+ }
+
+ async loadArchived(serverId: string): Promise<void> {
+ try {
+ const chats = await this.api.listArchived(serverId);
+ if (serverId !== this.serverId) return;
+ runInAction(() => {
+ this.archived = new Map(
+ chats.filter((chat) => !this.chats.has(chat.roomId)).map((chat) => [chat.roomId, chat])
+ );
+ this.archivedError = null;
+ });
+ } catch (error) {
+ if (serverId !== this.serverId) return;
+ runInAction(() => {
+ this.archivedError = failureText(error, 'Your archived chats could not be listed.');
+ });
+ }
}
upsert(chat: ChatSummary): void {
this.chats.set(chat.roomId, chat);
this.removed.delete(chat.roomId);
+ const wasArchived = this.archived.delete(chat.roomId);
const timeline = this.serverId ? this.timelines.peek(this.serverId, chat.roomId) : undefined;
timeline?.restore();
// The feed did not follow the room while it was off the list.
- if (this.unlisted.delete(chat.roomId) && timeline?.loaded) void timeline.load();
+ if ((this.unlisted.delete(chat.roomId) || wasArchived) && timeline?.loaded)
+ void timeline.load();
}
/** A chat the person made or was let into from here, ahead of the feed. */
@@ -192,7 +223,17 @@ export class ChatsStore {
/** Archived for everyone in it; throws, leaving the chat listed, if the server refuses. */
async archive(serverId: string, roomId: string): Promise<void> {
await this.api.archive(serverId, roomId);
- this.remove(roomId, 'access');
+ const chat = this.chats.get(roomId);
+ this.remove(roomId, 'unlisted');
+ if (chat) this.archived.set(roomId, chat);
+ await switchRoomsStore.refreshRoomState();
+ }
+
+ /** Back on the list for everyone in it; throws, leaving it archived, if the server refuses. */
+ async unarchive(serverId: string, roomId: string): Promise<void> {
+ await this.api.unarchive(serverId, roomId);
+ const chat = this.archived.get(roomId);
+ if (chat) this.upsert(chat);
await switchRoomsStore.refreshRoomState();
}
@@ -216,7 +257,12 @@ export class ChatsStore {
this.timelines.peek(serverId, message.roomId)?.apply(message);
const chat = this.chats.get(message.roomId);
// The feed follows hidden chats too; a message in one is what brings it back.
- if (!chat && !this.removed.has(message.roomId) && !this.unlisted.has(message.roomId))
+ if (
+ !chat &&
+ !this.removed.has(message.roomId) &&
+ !this.unlisted.has(message.roomId) &&
+ !this.archived.has(message.roomId)
+ )
void this.relist(serverId);
if (chat && (chat.lastMessage === null || chat.lastMessage.seq < message.seq))
this.chats.set(message.roomId, {
@@ -285,6 +331,7 @@ export class ChatsStore {
return;
}
this.unlisted.delete(roomId);
+ this.archived.delete(roomId);
this.removed.add(roomId);
if (this.serverId) {
const timeline = this.timelines.peek(this.serverId, roomId);
@@ -298,6 +345,8 @@ export class ChatsStore {
this.chats = new Map();
this.removed = new Set();
this.unlisted = new Set();
+ this.archived = new Map();
+ this.archivedError = null;
this.userId = null;
this.tenantId = null;
void this.connect(serverId);
@@ -360,8 +409,16 @@ export class ChatsStore {
.sort((a, b) => (b.lastMessage?.sentAt ?? '').localeCompare(a.lastMessage?.sentAt ?? ''));
}
+ /** The archived chats an agent is in, newest activity first. */
+ archivedOfAgent(agentId: string): ChatSummary[] {
+ return [...this.archived.values()]
+ .filter((chat) => chat.agents.some((agent) => agent.id === agentId))
+ .sort((a, b) => (b.lastMessage?.sentAt ?? '').localeCompare(a.lastMessage?.sentAt ?? ''));
+ }
+
+ /** A listed chat, or an archived one. */
chat(roomId: string): ChatSummary | undefined {
- return this.chats.get(roomId);
+ return this.chats.get(roomId) ?? this.archived.get(roomId);
}
}
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.ts
index ac6c79f9b..8b6b9e266 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
@@ -19,6 +19,7 @@ export const chatsStore = new ChatsStore(
},
disconnect: (serverId) => rpc.chats.disconnect(serverId),
list: (serverId) => rpc.chats.list(serverId),
+ listArchived: (serverId) => rpc.chats.listArchived(serverId),
identity: (serverId) => rpc.chats.identity(serverId),
timeline: (serverId) => ({
messages: (roomId, beforeSeq, limit) =>
@@ -30,6 +31,7 @@ export const chatsStore = new ChatsStore(
newId: () => crypto.randomUUID(),
}),
archive: (serverId, roomId) => rpc.chats.archive(serverId, roomId),
+ unarchive: (serverId, roomId) => rpc.chats.unarchive(serverId, roomId),
delete: (serverId, roomId) => rpc.chats.delete(serverId, roomId),
removeMember: (serverId, roomId, userId) =>
rpc.chats.removeMember({ serverId, roomId, userId }),
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.tsx
index fbd30ff3d..509435e4f 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
@@ -2,6 +2,7 @@ import { ChevronDown, ChevronRight, Plus } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { type ReactNode, useEffect, useRef, useState } from 'react';
import { agentConversations } from '@renderer/features/chats/agent-conversations';
+import { ArchivedFold } from '@renderer/features/chats/components/archived-fold';
import { ChatPanel } from '@renderer/features/chats/components/chat-panel';
import { ChatRow } from '@renderer/features/chats/components/chat-row';
import { useOpenGroupAsRoom } from '@renderer/features/chats/console-chat-redirect';
@@ -10,6 +11,7 @@ import { chatsStore } from '@renderer/features/chats/stores/chats';
import { RoomListRow } from '@renderer/features/sidebar/main-section';
import { SidebarItemMiniButton } from '@renderer/features/sidebar/sidebar-primitives';
import { EmbeddedRoom } from '@renderer/features/switch-rooms/view';
+import { isConsoleDirectChatSummary } from '@renderer/features/switch-servers/room-filters';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
import { useFeatureFlags } from '@renderer/lib/hooks/useFeatureFlags';
import { useParams } from '@renderer/lib/layout/navigation-provider';
@@ -118,18 +120,26 @@ const Note = ({ children }: { children: ReactNode }) => (
function conversationsOf({ serverId, workspaceId, agentId }: ManagedAgentView) {
// The chats store follows the window's server; another server's chats are not in it.
- const agentChats = chatsStore.serverId === serverId ? chatsStore.chatsOfAgent(agentId) : [];
+ const ownServer = chatsStore.serverId === serverId;
+ const agentChats = ownServer ? chatsStore.chatsOfAgent(agentId) : [];
+ const archived = ownServer
+ ? chatsStore.archivedOfAgent(agentId).filter(isConsoleDirectChatSummary)
+ : [];
const agentRooms = switchRoomsStore.roomsFor(workspaceId, agentId);
- return { agentRooms, ...agentConversations(agentChats, agentRooms ?? [], chatsStore.removed) };
+ return {
+ agentRooms,
+ archived,
+ ...agentConversations(agentChats, agentRooms ?? [], chatsStore.removed),
+ };
}
-/** The direct chat open on an agent's page: the one in the params, else its newest. */
+/** The direct chat open on an agent's page: the one in the params, archived or not, else its newest. */
export function openAgentChat(
agent: ManagedAgentView,
roomId: string | undefined
): ChatSummary | null {
- const { direct } = conversationsOf(agent);
- return direct.find((chat) => chat.roomId === roomId) ?? direct[0] ?? null;
+ const { direct, archived } = conversationsOf(agent);
+ return [...direct, ...archived].find((chat) => chat.roomId === roomId) ?? direct[0] ?? null;
}
/** The room shown on an agent's page in place of a chat, if one is. */
@@ -155,7 +165,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
return switchRoomsStore.watchMembership(workspaceId, agentId);
}, [workspaceId, agentId]);
- const { agentRooms, direct, rooms } = conversationsOf(agent);
+ const { agentRooms, direct, archived, rooms } = conversationsOf(agent);
const roomsError = switchRoomsStore.errorFor(workspaceId, agentId);
const { sections, section } = useAgentSection(serverId, agent, params.section);
const thisComputer = useRunsOnThisComputer(agent);
@@ -221,6 +231,17 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: Manag
/>
))}
{direct.length === 0 && !chatsStore.listError && <Note>No direct chats yet.</Note>}
+ <ArchivedFold count={archived.length} error={ownServer ? chatsStore.archivedError : null}>
+ {archived.map((chat) => (
+ <ChatRow
+ key={chat.roomId}
+ serverId={serverId}
+ chat={chat}
+ isActive={!section && chat.roomId === roomId}
+ onOpen={() => open(chat.roomId)}
+ />
+ ))}
+ </ArchivedFold>
</Section>
<Section
title="Rooms"
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.tsx
index ef8e94031..dc15e68ce 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,7 +2,9 @@ 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 { ArchivedFold } from '@renderer/features/chats/components/archived-fold';
import { UnreadBadge } from '@renderer/features/chats/components/unread-badge';
+import { chatsStore } from '@renderer/features/chats/stores/chats';
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';
@@ -10,6 +12,8 @@ import { roomTitle } from '@renderer/features/switch-rooms/room-labels';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { toast } from '@renderer/lib/hooks/use-toast';
import { useParams } from '@renderer/lib/layout/navigation-provider';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
@@ -19,7 +23,7 @@ import { ToggleGroup, ToggleGroupItem } from '@renderer/lib/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';
import { cn } from '@renderer/utils/utils';
import type { RemoteRoomSummary } from '@shared/core/switch-servers/switch-servers';
-import { allReadableRooms } from './room-filters';
+import { allReadableRooms, isConsoleGroupChatSummary } from './room-filters';
import { groupByMessagingApp, type RoomGroup } from './rooms-by-messaging-app';
import { ServerPage, ServerTableEmpty } from './server-page';
import { ServerSectionTitlebar } from './server-section-titlebar';
@@ -58,6 +62,13 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
const query = filter.trim().toLowerCase();
const matching = query === '' ? rooms : rooms.filter((r) => r.name.toLowerCase().includes(query));
const groups = groupByMessagingApp(matching);
+ const archived =
+ chatsStore.serverId === serverId
+ ? [...chatsStore.archived.values()]
+ .filter(isConsoleGroupChatSummary)
+ .filter((chat) => query === '' || chat.name.toLowerCase().includes(query))
+ .sort((a, b) => a.name.localeCompare(b.name))
+ : [];
return (
<ServerPage
@@ -140,6 +151,40 @@ const ServerRoomsPanel = observer(function ServerRoomsPanel() {
/>
))
)}
+ <ArchivedFold
+ count={archived.length}
+ error={chatsStore.serverId === serverId ? chatsStore.archivedError : null}
+ >
+ <div className="divide-y divide-border overflow-hidden rounded-[10px] border border-border">
+ {archived.map((chat) => (
+ <div key={chat.roomId} className="flex items-center gap-3 bg-background px-4 py-3">
+ <button
+ type="button"
+ onClick={() => void openRoom(chat.roomId)}
+ className="min-w-0 flex-1 cursor-pointer truncate text-left text-sm font-medium text-foreground hover:underline"
+ >
+ {chat.name}
+ </button>
+ {chat.canManage && (
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ void chatsStore.unarchive(serverId, chat.roomId).catch((error: unknown) =>
+ toast({
+ title: failureText(error, 'Could not unarchive the room.'),
+ variant: 'destructive',
+ })
+ )
+ }
+ >
+ Unarchive
+ </Button>
+ )}
+ </div>
+ ))}
+ </div>
+ </ArchivedFold>
</div>
)}
</ServerPage>
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.ts
index 6a234b482..d49ebed37 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
@@ -68,7 +68,8 @@ function message(roomId: string, seq: number): ChatMessage {
function setup(
list: () => Promise<ChatSummary[]>,
timeline: Partial<TimelineApi> = {},
- identity: ChatsApi['identity'] = async () => ({ userId: 'u', tenantId: 't' })
+ identity: ChatsApi['identity'] = async () => ({ userId: 'u', tenantId: 't' }),
+ listArchived: () => Promise<ChatSummary[]> = async () => []
) {
let onMessage: Parameters<ChatsEvents['onMessage']>[0] = () => {};
let onState: Parameters<ChatsEvents['onState']>[0] = () => {};
@@ -89,9 +90,11 @@ function setup(
connect: vi.fn(async () => ({ state: 'live' as const, detail: null })),
disconnect: vi.fn(async () => {}),
list: vi.fn(list),
+ listArchived: vi.fn(listArchived),
identity,
timeline: () => timeline as TimelineApi,
archive: vi.fn(async () => {}),
+ unarchive: vi.fn(async () => {}),
delete: vi.fn(async () => {}),
markRead: vi.fn(async () => {}),
removeMember: vi.fn(async () => {}),
@@ -169,17 +172,68 @@ describe('ChatsStore', () => {
expect(api.list).toHaveBeenCalledTimes(2);
});
- it.each(['archive', 'delete'] as const)(
- 'drops a chat once the server agrees to %s it',
- async (op) => {
- const { store, api } = setup(async () => [summary('r1', 1), summary('r2', 1)]);
- await store.connect('s1');
- await store[op]('s1', 'r2');
- expect(api[op]).toHaveBeenCalledWith('s1', 'r2');
- expect(store.chat('r2')).toBeUndefined();
- expect(store.chat('r1')).toBeDefined();
- }
- );
+ it('drops a chat once the server agrees to delete it', async () => {
+ const { store, api } = setup(async () => [summary('r1', 1), summary('r2', 1)]);
+ await store.connect('s1');
+ await store.delete('s1', 'r2');
+ expect(api.delete).toHaveBeenCalledWith('s1', 'r2');
+ expect(store.chat('r2')).toBeUndefined();
+ expect(store.chat('r1')).toBeDefined();
+ });
+
+ it('moves an archived chat off the list into the archive, still openable', async () => {
+ const { store, api } = setup(async () => [summary('r1', 1), summary('r2', 1)]);
+ await store.connect('s1');
+ await store.archive('s1', 'r2');
+ expect(api.archive).toHaveBeenCalledWith('s1', 'r2');
+ expect(store.chats.has('r2')).toBe(false);
+ expect(store.archivedOfAgent('a1').map((chat) => chat.roomId)).toEqual(['r2']);
+ expect(store.chat('r2')).toBeDefined();
+ expect(store.removed.has('r2')).toBe(false);
+ });
+
+ it('lists the archived chats the server holds, and brings one back when it is listed again', async () => {
+ const { store } = setup(
+ async () => [summary('r1', 1)],
+ {},
+ undefined,
+ async () => [summary('r2', 1)]
+ );
+ await store.connect('s1');
+ expect([...store.archived.keys()]).toEqual(['r2']);
+
+ store.upsert(summary('r2', 2));
+ expect(store.archived.size).toBe(0);
+ expect(store.chats.has('r2')).toBe(true);
+ });
+
+ it('unarchives a chat back onto the list', async () => {
+ const { store, api } = setup(
+ async () => [],
+ {},
+ undefined,
+ async () => [summary('r2', 1)]
+ );
+ await store.connect('s1');
+ await store.unarchive('s1', 'r2');
+ expect(api.unarchive).toHaveBeenCalledWith('s1', 'r2');
+ expect(store.chats.has('r2')).toBe(true);
+ expect(store.archived.size).toBe(0);
+ });
+
+ it('says so when the archive cannot be listed, keeping the chats', async () => {
+ const { store } = setup(
+ async () => [summary('r1', 1)],
+ {},
+ undefined,
+ async () => {
+ throw new Error('boom');
+ }
+ );
+ await store.connect('s1');
+ expect(store.chats.has('r1')).toBe(true);
+ expect(store.archivedError).not.toBeNull();
+ });
it.each(['archive', 'delete'] as const)('keeps a chat the server refuses to %s', async (op) => {
const { store, api } = setup(async () => [summary('r1', 1)]);
@@ -408,9 +462,11 @@ async function viewer() {
connect: async () => ({ state: 'live', detail: null }),
disconnect: async () => {},
list: async () => [group],
+ listArchived: async () => [],
identity: async () => ({ userId: 'u', tenantId: 't' }),
timeline: () => ({}) as TimelineApi,
archive: async () => {},
+ unarchive: async () => {},
delete: async () => {},
markRead,
removeMember,
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 42fd788a7..c52cbeae2 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -711,22 +711,41 @@ class ChatService:
async def readable_and_listed(
self, session: AsyncSession, user_id: str
) -> list[tuple[Room, bool]]:
- """`readable_rooms`, each with whether it is one of `stream_rooms`, in
- one query."""
+ """The caller's member rooms, archived ones included, each with whether
+ it is one of `stream_rooms`, in one query."""
+ return [
+ (room, is_chat and room.archived_at is None)
+ for room, is_chat in await self._member_rooms(session, user_id)
+ ]
+
+ async def archived_chats(self, session: AsyncSession, user_id: str) -> list[Room]:
+ """The caller's member rooms that would be in `stream_rooms` but for
+ being archived."""
+ return [
+ room
+ for room, is_chat in await self._member_rooms(session, user_id)
+ if is_chat and room.archived_at is not None
+ ]
+
+ async def _member_rooms(
+ self, session: AsyncSession, user_id: str
+ ) -> list[tuple[Room, bool]]:
+ """Every room the caller's member client is in, each with whether it
+ is a chat: holding an agent or started in Switch Console."""
client = await self.member_client(session, user_id)
if client is None:
return []
- listed = or_(
+ is_chat = or_(
exists().where(room_agents.c.room_id == Room.id),
Room.metadata_.has_key("chat_operation_id"),
)
result = await session.execute(
- select(Room, listed)
+ select(Room, is_chat)
.join(ClientRoom, ClientRoom.room_id == Room.id)
- .where(ClientRoom.client_id == client.id, Room.archived_at.is_(None))
+ .where(ClientRoom.client_id == client.id)
.order_by(Room.created_at)
)
- return [(room, bool(is_listed)) for room, is_listed in result.all()]
+ return [(room, bool(chat)) for room, chat in result.all()]
async def moved_rooms(
self, session: AsyncSession, cursors: dict[str, int]
@@ -1129,6 +1148,14 @@ class ChatService:
await self._room_service.set_room_archived(room.id, True)
self._memberships_changed(tenant_id, member_ids, [room.id])
+ async def unarchive(self, tenant_id: str, user: User, room_id: str) -> None:
+ async with tenant_session(self.session_factory, tenant_id) as session:
+ room, _ = await self.require_member(session, tenant_id, user, room_id)
+ await self._require_manager(session, tenant_id, user, room)
+ member_ids = [member.id for member, _ in await self.members(session, room)]
+ await self._room_service.set_room_archived(room.id, False)
+ self._memberships_changed(tenant_id, member_ids, [room.id])
+
async def _start_reading(
self, session: AsyncSession, room_id: str, user_ids: list[str]
) -> None:
@@ -1647,6 +1674,14 @@ class ChatService:
self._require_same(operation, "send", payload_hash)
return room, await self._posted(session, room, operation)
+ unarchive = room.archived_at is not None
+ if unarchive and not await self.can_manage(session, tenant_id, user, room):
+ raise ChatError(
+ 403,
+ "NOT_A_MANAGER",
+ "This chat is archived. Only its owner or a workspace admin "
+ "can bring it back by writing in it.",
+ )
if not body.strip() and not upload_ids:
raise ChatError(422, "EMPTY_MESSAGE", "There is nothing to send.")
uploads = [
@@ -1746,7 +1781,11 @@ class ChatService:
)
.values(result={"messageIds": [m.transport_event_id for m in posted]})
)
+ if unarchive:
+ await self._room_store.set_archived(session, room.id, False)
await session.commit()
+ if unarchive:
+ self._room_service.room_changed(tenant_id, room.id)
for each in routed:
each.committed()
for content in contents:
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index 3d8b37057..8928eba9e 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -298,6 +298,20 @@ async def list_chats(user: CurrentUser, service: Service) -> ChatList:
)
[email protected]("/archived", response_model=ChatList)
+async def list_archived_chats(user: CurrentUser, service: Service) -> ChatList:
+ """The caller's archived chats: those `GET /chats` would list were they
+ not archived, hidden ones included."""
+ tenant_id = require_tenant_id()
+ async with tenant_session(service.session_factory, tenant_id) as session:
+ if not await service.has_tenant_role(session, tenant_id, user.id):
+ return ChatList(chats=[])
+ rooms = await service.archived_chats(session, user.id)
+ return ChatList(
+ chats=await _summaries(service, session, tenant_id, user, rooms)
+ )
+
+
@router.post("", response_model=ChatEnvelope)
async def create_chat(
req: CreateChatRequest, user: CurrentUser, service: Service
@@ -640,6 +654,12 @@ async def archive_chat(room_id: str, user: CurrentUser, service: Service) -> Res
return Response(status_code=204)
[email protected]("/{room_id}/unarchive", status_code=204)
+async def unarchive_chat(room_id: str, user: CurrentUser, service: Service) -> Response:
+ await service.unarchive(require_tenant_id(), user, room_id)
+ return Response(status_code=204)
+
+
# ── Live updates ─────────────────────────────────────────────────────────────
@@ -665,8 +685,8 @@ def _frame(event: str, data: object) -> bytes:
def _removed(room_id: str, reason: RemovalReason) -> bytes:
"""`chat.removed`: "access" when the caller lost the room (membership,
- tenant role, archive), "unlisted" when they are still a member but it no
- longer qualifies for the list."""
+ tenant role), "unlisted" when they are still a member but it no longer
+ qualifies for the list (no agents left, archived)."""
return _frame("chat.removed", {"roomId": room_id, "reason": reason})
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 0fefe26a1..7c70a4dc5 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -211,7 +211,7 @@ class RoomService:
not block."""
self._room_listeners = (*self._room_listeners, listener)
- def _room_changed(self, tenant_id: str, room_id: str) -> None:
+ def room_changed(self, tenant_id: str, room_id: str) -> None:
for listener in self._room_listeners:
try:
listener(tenant_id, room_id, [])
@@ -826,7 +826,7 @@ class RoomService:
failed_attachments,
)
- self._room_changed(room.tenant_id, room.id)
+ self.room_changed(room.tenant_id, room.id)
return RoomCreateResult(room=room, failed_attachments=failed_attachments)
async def _seed_aliases(
@@ -1064,7 +1064,7 @@ class RoomService:
logger.info("Added %d agents to room %s", len(agent_ids), room_id)
await self.room_agents_changed(room.tenant_id, room.id)
- self._room_changed(room.tenant_id, room.id)
+ self.room_changed(room.tenant_id, room.id)
emit_safely(
self._telemetry,
@@ -1107,7 +1107,7 @@ class RoomService:
logger.info("Removed %d agents from room %s", len(agent_ids), room_id)
await self.room_agents_changed(room.tenant_id, room.id)
- self._room_changed(room.tenant_id, room.id)
+ self.room_changed(room.tenant_id, room.id)
emit_safely(
self._telemetry,
@@ -1181,7 +1181,7 @@ class RoomService:
write_visibility=write_visibility,
)
await session.commit()
- self._room_changed(tenant_id, room_id)
+ self.room_changed(tenant_id, room_id)
async def take_platform_name(
self, room_id: str, name: str, channel_name: str
@@ -1194,7 +1194,7 @@ class RoomService:
session, room_id, name, channel_name
)
await session.commit()
- self._room_changed(tenant_id, room_id)
+ self.room_changed(tenant_id, room_id)
async def follow_channel_name(
self, room_id: str, name: str, channel_name: str, legacy_name: str
@@ -1208,7 +1208,7 @@ class RoomService:
)
await session.commit()
if followed:
- self._room_changed(tenant_id, room_id)
+ self.room_changed(tenant_id, room_id)
return followed
async def record_channel_name(self, room_id: str, channel_name: str) -> None:
@@ -1218,7 +1218,7 @@ class RoomService:
async with tenant_session(self._session_factory, tenant_id) as session:
await self._room_store.record_channel_name(session, room_id, channel_name)
await session.commit()
- self._room_changed(tenant_id, room_id)
+ self.room_changed(tenant_id, room_id)
async def set_join_event_listeners(
self, room_id: str, settings: dict[str, bool]
@@ -1262,7 +1262,7 @@ class RoomService:
async with tenant_session(self._session_factory, room.tenant_id) as session:
await self._room_store.set_archived(session, room_id, archived)
await session.commit()
- self._room_changed(room.tenant_id, room_id)
+ self.room_changed(room.tenant_id, room_id)
if not archived or self._telemetry is None:
return
diff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.py
index 3c092edcc..28da005c3 100644
--- a/core/tests/switch_core/gateway/test_chats_routes.py
+++ b/core/tests/switch_core/gateway/test_chats_routes.py
@@ -733,6 +733,99 @@ async def test_only_a_manager_archives_a_chat(chats: _Harness) -> None:
assert listed.json()["chats"] == []
+async def _archived(chats: _Harness, user: User) -> dict[str, dict[str, Any]]:
+ response = await chats.client.get("/chats/archived", headers=chats.as_user(user))
+ assert response.status_code == 200, response.text
+ return {chat["roomId"]: chat for chat in response.json()["chats"]}
+
+
+async def _archive(chats: _Harness, user: User, room_id: str) -> None:
+ response = await chats.client.post(
+ f"/chats/{room_id}/archive", headers=chats.as_user(user)
+ )
+ assert response.status_code == 204, response.text
+
+
+async def test_archived_chats_are_listed_only_to_their_members(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ shared = await chats.new_chat(chats.alice, agent, "c1")
+ assert (await chats.invite(chats.alice, shared, chats.bob)).status_code == 200
+ assert (await chats.send(chats.alice, shared, "s1", "kept")).status_code == 200
+ bobs_agent = await chats.agent("bobs", owner=chats.bob)
+ private = await chats.new_chat(chats.bob, bobs_agent, "c2")
+ others = await _room(chats, [agent], owner=chats.alice, archived=True)
+ await _archive(chats, chats.alice, shared)
+ await _archive(chats, chats.bob, private)
+
+ assert shared not in await _listed(chats, chats.alice)
+ assert set(await _archived(chats, chats.alice)) == {shared}
+ assert set(await _archived(chats, chats.bob)) == {shared, private}
+ assert others not in await _archived(chats, chats.admin)
+ assert await _archived(chats, chats.carol) == {}
+
+ page = await chats.client.get(
+ f"/chats/{shared}/messages", headers=chats.as_user(chats.bob)
+ )
+ assert page.status_code == 200
+ assert [m["body"] for m in page.json()["messages"]][-1] == "kept"
+ assert await _reads(chats, chats.alice, private) == 403
+
+
+async def test_only_a_manager_unarchives_a_chat(chats: _Harness) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ await _archive(chats, chats.alice, room_id)
+
+ refused = await chats.client.post(
+ f"/chats/{room_id}/unarchive", headers=chats.as_user(chats.bob)
+ )
+ assert refused.status_code == 403
+ assert _code(refused) == "NOT_A_MANAGER"
+
+ restored = await chats.client.post(
+ f"/chats/{room_id}/unarchive", headers=chats.as_user(chats.alice)
+ )
+ assert restored.status_code == 204
+ assert room_id in await _listed(chats, chats.bob)
+ assert await _archived(chats, chats.bob) == {}
+
+
+async def test_a_managers_message_unarchives_the_chat_once(chats: _Harness) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ await _archive(chats, chats.alice, room_id)
+
+ sent = await chats.send(chats.alice, room_id, "s1", "back again")
+ assert sent.status_code == 200, sent.text
+ retried = await chats.send(chats.alice, room_id, "s1", "back again")
+ assert retried.status_code == 200
+ assert retried.json() == sent.json()
+
+ assert room_id in await _listed(chats, chats.alice)
+ assert await _archived(chats, chats.alice) == {}
+ assert [m.content["body"] for m in await chats.message_rows(room_id)] == [
+ "back again"
+ ]
+
+
+async def test_a_member_who_cannot_unarchive_cannot_send_to_an_archived_chat(
+ chats: _Harness,
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+ assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
+ await _archive(chats, chats.alice, room_id)
+
+ refused = await chats.send(chats.bob, room_id, "s1", "hello?")
+ assert refused.status_code == 403
+ assert _code(refused) == "NOT_A_MANAGER"
+ assert await chats.message_rows(room_id) == []
+ assert room_id in await _archived(chats, chats.bob)
+
+
# ── Live updates ─────────────────────────────────────────────────────────────
@@ -1017,7 +1110,9 @@ async def test_an_owner_only_member_loses_access_with_the_last_agent(
await events.stream.aclose() # type: ignore[attr-defined]
-async def test_archiving_a_chat_removes_it_for_access(chats: _Harness) -> None:
+async def test_archiving_a_chat_unlists_it_until_a_message_restores_it(
+ chats: _Harness,
+) -> None:
agent = await chats.agent("helper", owner=chats.alice)
room_id = await chats.new_chat(chats.alice, agent, "c1")
assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
@@ -1032,8 +1127,12 @@ async def test_archiving_a_chat_removes_it_for_access(chats: _Harness) -> None:
assert archived.status_code == 204
assert await events.next() == (
"chat.removed",
- {"roomId": room_id, "reason": "access"},
+ {"roomId": room_id, "reason": "unlisted"},
)
+
+ assert (await chats.send(chats.alice, room_id, "s1", "back")).status_code == 200
+ seen = {(await events.next())[0], (await events.next())[0]}
+ assert seen == {"chat", "message"}
await events.stream.aclose() # type: ignore[attr-defined]