Skip to content

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

fix(chats): the agent-registration bootstrap account is not a person

raullopez-sandbox271072136db6
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.ts
index 47fe5865f..e56d7c221 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
@@ -1,6 +1,6 @@
-import { describe, expect, it, vi } from 'vitest';
-import { gatewayFetch } from '@main/core/switch-servers/gateway-client';
-import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { describe, expect, it, vi } from "vitest";
+import { gatewayFetch } from "@main/core/switch-servers/gateway-client";
+import type { SwitchServer } from "@shared/core/switch-servers/switch-servers";
import {
addChatAgent,
addChatMember,
@@ -11,11 +11,11 @@ import {
removeChatAgent,
sendChatMessage,
warmChatAgent,
-} from './gateway';
+} from "./gateway";
const warn = vi.hoisted(() => vi.fn());
-vi.mock('@main/lib/logger', () => ({ log: { warn } }));
-vi.mock('@main/core/switch-servers/gateway-client', () => ({
+vi.mock("@main/lib/logger", () => ({ log: { warn } }));
+vi.mock("@main/core/switch-servers/gateway-client", () => ({
GatewayError: class extends Error {},
gatewayFetch: vi.fn(),
}));
@@ -36,178 +36,229 @@ function row(roomId: string, channelType: string) {
};
}
-describe('parseChatRows', () => {
- it('accepts every channel type the server sends', () => {
- const types = ['lobby', 'channel_public', 'channel_private', 'group', 'direct'];
- expect(parseChatRows(types.map((type) => row(type, type))).map((c) => c.roomId)).toEqual(types);
+describe("parseChatRows", () => {
+ it("accepts every channel type the server sends", () => {
+ const types = [
+ "lobby",
+ "channel_public",
+ "channel_private",
+ "group",
+ "direct",
+ ];
+ expect(
+ parseChatRows(types.map((type) => row(type, type))).map((c) => c.roomId),
+ ).toEqual(types);
});
- it('skips a row that fails the contract with a warning and keeps the rest', () => {
- const chats = parseChatRows([row('room-a', 'direct'), row('room-bad', 'unknown')]);
- expect(chats.map((chat) => chat.roomId)).toEqual(['room-a']);
+ it("skips a row that fails the contract with a warning and keeps the rest", () => {
+ const chats = parseChatRows([
+ row("room-a", "direct"),
+ row("room-bad", "unknown"),
+ ]);
+ expect(chats.map((chat) => chat.roomId)).toEqual(["room-a"]);
expect(warn).toHaveBeenCalledWith(
expect.any(String),
- expect.objectContaining({ roomId: 'room-bad' })
+ expect.objectContaining({ roomId: "room-bad" }),
);
});
});
-describe('warmChatAgent', () => {
- it('posts the agent to the room’s warm route', async () => {
- const server = { id: 'server-1' } as SwitchServer;
- vi.mocked(gatewayFetch).mockResolvedValueOnce(new Response(null, { status: 202 }));
- await warmChatAgent(server, 'room/a', 'agent-1');
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room%2Fa/warm', {
+describe("warmChatAgent", () => {
+ it("posts the agent to the room’s warm route", async () => {
+ const server = { id: "server-1" } as SwitchServer;
+ vi.mocked(gatewayFetch).mockResolvedValueOnce(
+ new Response(null, { status: 202 }),
+ );
+ await warmChatAgent(server, "room/a", "agent-1");
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/chats/room%2Fa/warm", {
authenticated: true,
- method: 'POST',
- body: { agentId: 'agent-1' },
+ method: "POST",
+ body: { agentId: "agent-1" },
});
});
});
-describe('createChat', () => {
- it('creates chat with zero agents and memberUserIds', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+describe("createChat", () => {
+ it("creates chat with zero agents and memberUserIds", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ chat: row('room-new', 'group') }), { status: 200 })
+ new Response(JSON.stringify({ chat: row("room-new", "group") }), {
+ status: 200,
+ }),
);
await createChat(server, {
agentIds: [],
- memberUserIds: ['user-1', 'user-2'],
- name: 'Test Group',
- requestId: 'req-1',
+ memberUserIds: ["user-1", "user-2"],
+ name: "Test Group",
+ requestId: "req-1",
greeting: null,
});
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats', {
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/chats", {
authenticated: true,
- method: 'POST',
+ method: "POST",
body: {
- requestId: 'req-1',
+ requestId: "req-1",
agentIds: [],
- memberUserIds: ['user-1', 'user-2'],
- name: 'Test Group',
+ memberUserIds: ["user-1", "user-2"],
+ name: "Test Group",
},
});
});
- it('creates chat with one agent using agentId field', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+ it("creates chat with one agent using agentId field", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ chat: row('room-new', 'direct') }), { status: 200 })
+ new Response(JSON.stringify({ chat: row("room-new", "direct") }), {
+ status: 200,
+ }),
);
await createChat(server, {
- agentIds: ['agent-1'],
+ agentIds: ["agent-1"],
name: null,
- requestId: 'req-1',
+ requestId: "req-1",
greeting: null,
});
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats', {
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/chats", {
authenticated: true,
- method: 'POST',
- body: { requestId: 'req-1', agentId: 'agent-1' },
+ method: "POST",
+ body: { requestId: "req-1", agentId: "agent-1" },
});
});
});
-describe('addChatAgent', () => {
- it('posts agent to the chat agents route', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+describe("addChatAgent", () => {
+ it("posts agent to the chat agents route", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ chat: row('room-1', 'group') }), { status: 200 })
+ new Response(JSON.stringify({ chat: row("room-1", "group") }), {
+ status: 200,
+ }),
);
- await addChatAgent(server, 'room-1', 'agent-2');
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/agents', {
+ await addChatAgent(server, "room-1", "agent-2");
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/chats/room-1/agents", {
authenticated: true,
- method: 'POST',
- body: { agentId: 'agent-2' },
+ method: "POST",
+ body: { agentId: "agent-2" },
});
});
});
-describe('removeChatAgent', () => {
- it('deletes agent from the chat', async () => {
- const server = { id: 'server-1' } as SwitchServer;
- vi.mocked(gatewayFetch).mockResolvedValueOnce(new Response(null, { status: 204 }));
- await removeChatAgent(server, 'room-1', 'agent-2');
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/agents/agent-2', {
- authenticated: true,
- method: 'DELETE',
- });
+describe("removeChatAgent", () => {
+ it("deletes agent from the chat", async () => {
+ const server = { id: "server-1" } as SwitchServer;
+ vi.mocked(gatewayFetch).mockResolvedValueOnce(
+ new Response(null, { status: 204 }),
+ );
+ await removeChatAgent(server, "room-1", "agent-2");
+ expect(gatewayFetch).toHaveBeenCalledWith(
+ server,
+ "/chats/room-1/agents/agent-2",
+ {
+ authenticated: true,
+ method: "DELETE",
+ },
+ );
});
});
-describe('chat members', () => {
- it('adds a person and answers with the members', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+describe("chat members", () => {
+ it("adds a person and answers with the members", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ members: [{ userId: 'u2', name: 'Bob', isOwner: false }] }), {
- status: 200,
- })
+ new Response(
+ JSON.stringify({
+ members: [{ userId: "u2", name: "Bob", isOwner: false }],
+ }),
+ {
+ status: 200,
+ },
+ ),
);
- expect(await addChatMember(server, 'room-1', 'u2')).toEqual([
- { userId: 'u2', name: 'Bob', isOwner: false },
+ expect(await addChatMember(server, "room-1", "u2")).toEqual([
+ { userId: "u2", name: "Bob", isOwner: false },
]);
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/members', {
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/chats/room-1/members", {
authenticated: true,
- method: 'POST',
- body: { userId: 'u2' },
+ method: "POST",
+ body: { userId: "u2" },
});
});
- it('reads the workspace roster in its snake_case shape', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+ it("reads the workspace roster in its snake_case shape", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify([{ user_id: 'u2', name: 'Bob', email: null, role: 'member' }]), {
- status: 200,
- })
+ new Response(
+ JSON.stringify([
+ { user_id: "u2", name: "Bob", email: null, role: "member" },
+ {
+ user_id: "u3",
+ name: "Bot",
+ email: null,
+ role: "member",
+ service_account: true,
+ },
+ ]),
+ { status: 200 },
+ ),
);
- expect(await listWorkspaceMembers(server, 't-1')).toEqual([
- { userId: 'u2', name: 'Bob', email: null },
+ expect(await listWorkspaceMembers(server, "t-1")).toEqual([
+ { userId: "u2", name: "Bob", email: null, serviceAccount: false },
+ { userId: "u3", name: "Bot", email: null, serviceAccount: true },
]);
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/tenants/t-1/members', {
+ expect(gatewayFetch).toHaveBeenCalledWith(server, "/tenants/t-1/members", {
authenticated: true,
});
});
});
-describe('sendChatMessage', () => {
- it('sends message with mentionAgentIds', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+describe("sendChatMessage", () => {
+ it("sends message with mentionAgentIds", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ messages: [] }), { status: 200 })
+ new Response(JSON.stringify({ messages: [] }), { status: 200 }),
);
- await sendChatMessage(server, 'room-1', {
- requestId: 'req-1',
- body: 'Test message',
+ await sendChatMessage(server, "room-1", {
+ requestId: "req-1",
+ body: "Test message",
threadRootId: null,
uploadIds: [],
- mentionAgentIds: ['agent-1', 'agent-2'],
+ mentionAgentIds: ["agent-1", "agent-2"],
});
- expect(gatewayFetch).toHaveBeenCalledWith(server, '/chats/room-1/messages', {
- authenticated: true,
- method: 'POST',
- body: {
- requestId: 'req-1',
- body: 'Test message',
- threadRootId: null,
- uploadIds: [],
- mentionAgentIds: ['agent-1', 'agent-2'],
+ expect(gatewayFetch).toHaveBeenCalledWith(
+ server,
+ "/chats/room-1/messages",
+ {
+ authenticated: true,
+ method: "POST",
+ body: {
+ requestId: "req-1",
+ body: "Test message",
+ threadRootId: null,
+ uploadIds: [],
+ mentionAgentIds: ["agent-1", "agent-2"],
+ },
},
- });
+ );
});
});
-describe('fetchThreadMessages', () => {
- it('fetches thread messages with pagination', async () => {
- const server = { id: 'server-1' } as SwitchServer;
+describe("fetchThreadMessages", () => {
+ it("fetches thread messages with pagination", async () => {
+ const server = { id: "server-1" } as SwitchServer;
vi.mocked(gatewayFetch).mockResolvedValueOnce(
- new Response(JSON.stringify({ messages: [], headSeq: 100, hasMore: false }), { status: 200 })
+ new Response(
+ JSON.stringify({ messages: [], headSeq: 100, hasMore: false }),
+ { status: 200 },
+ ),
);
- await fetchThreadMessages(server, 'room-1', 'msg-root', { beforeSeq: 50, limit: 20 });
+ await fetchThreadMessages(server, "room-1", "msg-root", {
+ beforeSeq: 50,
+ limit: 20,
+ });
expect(gatewayFetch).toHaveBeenCalledWith(
server,
- '/chats/room-1/threads/msg-root/messages?limit=20&beforeSeq=50',
- { authenticated: true }
+ "/chats/room-1/threads/msg-root/messages?limit=20&beforeSeq=50",
+ { authenticated: true },
);
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
index 09319c22c..363097362 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-configuration-panel.tsx
@@ -1,57 +1,72 @@
-import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { ExternalLink, FileText, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react';
-import { observer } from 'mobx-react-lite';
-import { useState } from 'react';
-import { opensAsConsoleChat } from '@renderer/features/chats/console-chat-redirect';
-import { chatFailure } from '@renderer/features/chats/stores/chat-errors';
-import { chatsStore } from '@renderer/features/chats/stores/chats';
-import { agentsStore } from '@renderer/features/locations/stores/agents-store';
-import { isConsoleGroupChatSummary } from '@renderer/features/switch-servers/room-filters';
-import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
-import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
-import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
-import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
-import { describeFailure, failureText } from '@renderer/lib/errors/describe-failure';
-import { rpc } from '@renderer/lib/ipc';
-import { useNavigate } from '@renderer/lib/layout/navigation-provider';
-import { useShowModal } from '@renderer/lib/modal/modal-provider';
-import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';
-import { Button } from '@renderer/lib/ui/button';
-import { Input } from '@renderer/lib/ui/input';
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ ExternalLink,
+ FileText,
+ Loader2,
+ Plus,
+ RefreshCw,
+ Search,
+ X,
+} from "lucide-react";
+import { observer } from "mobx-react-lite";
+import { useState } from "react";
+import { opensAsConsoleChat } from "@renderer/features/chats/console-chat-redirect";
+import { chatFailure } from "@renderer/features/chats/stores/chat-errors";
+import { chatsStore } from "@renderer/features/chats/stores/chats";
+import { agentsStore } from "@renderer/features/locations/stores/agents-store";
+import { isConsoleGroupChatSummary } from "@renderer/features/switch-servers/room-filters";
+import { switchRoomsStore } from "@renderer/features/switch-servers/switch-rooms-store";
+import { switchServersStore } from "@renderer/features/switch-servers/switch-servers-store";
+import { workspacesStore } from "@renderer/features/workspaces/workspaces-store";
+import { AgentAvatar } from "@renderer/lib/components/agent-avatar";
+import { bridgePlatformLabel } from "@renderer/lib/components/bridge-platform";
+import {
+ describeFailure,
+ failureText,
+} from "@renderer/lib/errors/describe-failure";
+import { rpc } from "@renderer/lib/ipc";
+import { useNavigate } from "@renderer/lib/layout/navigation-provider";
+import { useShowModal } from "@renderer/lib/modal/modal-provider";
+import { useWorkspaceAgents } from "@renderer/lib/stores/use-workspace-agents";
+import { Button } from "@renderer/lib/ui/button";
+import { Input } from "@renderer/lib/ui/input";
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
-} from '@renderer/lib/ui/input-group';
-import { Textarea } from '@renderer/lib/ui/textarea';
-import { cn } from '@renderer/utils/utils';
-import { agentInitials } from '@shared/core/agents/agent-avatar';
-import { type ChatSummary, chatAgentLabel } from '@shared/core/chats/chats';
-import { providerDisplayName } from '@shared/core/providers/agent-provider-registry';
-import { runsOnThisComputer } from '@shared/core/switch-servers/switch-servers';
+} from "@renderer/lib/ui/input-group";
+import { Textarea } from "@renderer/lib/ui/textarea";
+import { cn } from "@renderer/utils/utils";
+import { agentInitials } from "@shared/core/agents/agent-avatar";
+import { type ChatSummary, chatAgentLabel } from "@shared/core/chats/chats";
+import { providerDisplayName } from "@shared/core/providers/agent-provider-registry";
+import { runsOnThisComputer } from "@shared/core/switch-servers/switch-servers";
import type {
RemoteAgentSummary,
RemoteRoomDetail,
-} from '@shared/core/switch-servers/switch-servers';
-import { administersWorkspace } from '@shared/core/workspaces/workspaces';
-import { channelOnDeleteSummary } from './room-delete-wording';
-import { membershipSummary, roomTitle } from './room-labels';
-import { openRoomChannel } from './room-links';
+} from "@shared/core/switch-servers/switch-servers";
+import { administersWorkspace } from "@shared/core/workspaces/workspaces";
+import { channelOnDeleteSummary } from "./room-delete-wording";
+import { addablePeople, membershipSummary, roomTitle } from "./room-labels";
+import { openRoomChannel } from "./room-links";
/** Query key for one room's own settings — shared so a save can write the
* server's answer straight back into what the page is reading. */
function roomDetailKey(workspaceId: string, roomId: string) {
- return ['remote-room-detail', workspaceId, roomId] as const;
+ return ["remote-room-detail", workspaceId, roomId] as const;
}
/** One room read from its server; `workspaceId` is null until the room list has loaded. */
function useRoomDetail(roomId: string) {
const workspaceId = switchRoomsStore.roomWorkspaceId(roomId);
const query = useQuery({
- queryKey: roomDetailKey(workspaceId ?? '', roomId),
- queryFn: () => rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId }),
+ queryKey: roomDetailKey(workspaceId ?? "", roomId),
+ queryFn: () =>
+ rpc.workspaces.getRoomDetail({
+ workspaceId: workspaceId as string,
+ roomId,
+ }),
enabled: workspaceId !== null && !opensAsConsoleChat(roomId),
});
return { workspaceId, query };
@@ -69,29 +84,48 @@ const ChatConfiguration = observer(function ChatConfiguration({
serverId: string;
chat: ChatSummary;
}) {
- const workspaceId = switchRoomsStore.roomWorkspaceId(chat.roomId) ?? workspacesStore.activeId;
+ const workspaceId =
+ switchRoomsStore.roomWorkspaceId(chat.roomId) ?? workspacesStore.activeId;
const detail = useQuery({
- queryKey: roomDetailKey(workspaceId ?? '', chat.roomId),
+ queryKey: roomDetailKey(workspaceId ?? "", chat.roomId),
queryFn: () =>
- rpc.workspaces.getRoomDetail({ workspaceId: workspaceId as string, roomId: chat.roomId }),
+ rpc.workspaces.getRoomDetail({
+ workspaceId: workspaceId as string,
+ roomId: chat.roomId,
+ }),
enabled: workspaceId !== null && chat.canManage,
});
return (
<div className="h-full overflow-y-auto">
<div className="mx-auto flex w-full max-w-[880px] flex-col gap-8 px-10 py-8">
<div className="flex min-w-0 flex-col gap-1">
- <h1 className="truncate text-2xl font-semibold text-foreground">{chat.name}</h1>
- <p className="text-sm text-foreground-muted">Group chat in Switch Console</p>
+ <h1 className="truncate text-2xl font-semibold text-foreground">
+ {chat.name}
+ </h1>
+ <p className="text-sm text-foreground-muted">
+ Group chat in Switch Console
+ </p>
</div>
{workspaceId !== null && detail.data && (
- <GeneralSection key={chat.roomId} workspaceId={workspaceId} room={detail.data} />
+ <GeneralSection
+ key={chat.roomId}
+ workspaceId={workspaceId}
+ room={detail.data}
+ />
)}
{detail.isError && (
<p className="text-xs text-foreground-muted">
- {failureText(detail.error, 'Could not read this chat’s description and instructions.')}
+ {failureText(
+ detail.error,
+ "Could not read this chat’s description and instructions.",
+ )}
</p>
)}
- <ChatParticipantsSection serverId={serverId} workspaceId={workspaceId} chat={chat} />
+ <ChatParticipantsSection
+ serverId={serverId}
+ workspaceId={workspaceId}
+ chat={chat}
+ />
</div>
</div>
);
@@ -102,7 +136,12 @@ const ChatConfiguration = observer(function ChatConfiguration({
* so an add, a removal or a swap by anyone reads the list again.
*/
export function chatMembersQueryKey(serverId: string, chat: ChatSummary) {
- return ['chat-members', serverId, chat.roomId, chat.memberUserIds.join(',')] as const;
+ return [
+ "chat-members",
+ serverId,
+ chat.roomId,
+ chat.memberUserIds.join(","),
+ ] as const;
}
/** Who is in a group chat; a manager adds and removes agents and people through the chat. */
@@ -122,7 +161,7 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
queryKey: membersKey,
queryFn: () => rpc.chats.members(serverId, roomId),
});
- const [adding, setAdding] = useState<'agent' | 'person' | null>(null);
+ const [adding, setAdding] = useState<"agent" | "person" | null>(null);
const [removing, setRemoving] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const people = members.data ?? [];
@@ -163,7 +202,9 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-baseline gap-2">
- <h2 className="text-sm font-semibold text-foreground">Participants</h2>
+ <h2 className="text-sm font-semibold text-foreground">
+ Participants
+ </h2>
<span className="text-xs text-foreground-muted">
{membershipSummary(agentIds.length, people.length)}
</span>
@@ -173,8 +214,8 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
<Button
variant="outline"
size="sm"
- aria-expanded={adding === 'agent'}
- onClick={() => setAdding((v) => (v === 'agent' ? null : 'agent'))}
+ aria-expanded={adding === "agent"}
+ onClick={() => setAdding((v) => (v === "agent" ? null : "agent"))}
>
<Plus className="size-3.5" />
Add agent
@@ -182,8 +223,10 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
<Button
variant="outline"
size="sm"
- aria-expanded={adding === 'person'}
- onClick={() => setAdding((v) => (v === 'person' ? null : 'person'))}
+ aria-expanded={adding === "person"}
+ onClick={() =>
+ setAdding((v) => (v === "person" ? null : "person"))
+ }
>
<Plus className="size-3.5" />
Add person
@@ -193,26 +236,34 @@ const ChatParticipantsSection = observer(function ChatParticipantsSection({
</div>
{members.isError && (
- <p className="text-xs text-destructive">{chatFailure(members.error).message}</p>
+ <p className="text-xs text-destructive">
+ {chatFailure(members.error).message}
+ </p>
)}
{error !== null && <p className="text-xs text-destructive">{error}</p>}
<ParticipantList
workspaceId={workspaceId}
agentIds={agentIds}
- agentNames={new Map(chat.agents.map((agent) => [agent.id, chatAgentLabel(agent)]))}
+ agentNames={
+ new Map(chat.agents.map((agent) => [agent.id, chatAgentLabel(agent)]))
+ }
people={people.map((person) => ({
id: person.userId,
name: person.name,
- detail: person.isOwner ? 'owner' : 'member',
+ detail: person.isOwner ? "owner" : "member",
}))}
manage={manage}
/>
- {adding === 'agent' && workspaceId !== null && (
- <ChatAddAgentPanel serverId={serverId} workspaceId={workspaceId} chat={chat} />
+ {adding === "agent" && workspaceId !== null && (
+ <ChatAddAgentPanel
+ serverId={serverId}
+ workspaceId={workspaceId}
+ chat={chat}
+ />
)}
- {adding === 'person' && (
+ {adding === "person" && (
<ChatAddPersonPanel
serverId={serverId}
workspaceId={workspaceId}
@@ -245,22 +296,35 @@ const ChatAddAgentPanel = observer(function ChatAddAgentPanel({
searchPlaceholder="Search agents in this workspace…"
allInText="Every agent in this workspace is already in this chat."
loading={agents.isPending}
- loadError={agents.isError ? failureText(agents.error, 'Could not list the agents.') : null}
+ loadError={
+ agents.isError
+ ? failureText(agents.error, "Could not list the agents.")
+ : null
+ }
candidates={(agents.data ?? [])
.filter((agent) => !inChat.has(agent.id))
.map((agent) => ({
id: agent.id,
name: agent.displayName ?? agent.name,
mark: (
- <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} serverId={serverId} size={22} />
+ <AgentAvatar
+ name={agent.name}
+ iconUrl={agent.iconUrl}
+ serverId={serverId}
+ size={22}
+ />
),
- detail: providerDisplayName(agent.knownAgentType) ?? 'Agent',
+ detail: providerDisplayName(agent.knownAgentType) ?? "Agent",
}))}
onAdd={async (agentId) => {
try {
chatsStore.add(
serverId,
- await rpc.chats.addAgent({ serverId, roomId: chat.roomId, agentId })
+ await rpc.chats.addAgent({
+ serverId,
+ roomId: chat.roomId,
+ agentId,
+ }),
);
} catch (cause) {
throw new Error(chatFailure(cause).message);
@@ -288,8 +352,9 @@ function ChatAddPersonPanel({
onAdded: (members: Awaited<ReturnType<typeof rpc.chats.addMember>>) => void;
}) {
const roster = useQuery({
- queryKey: ['workspace-members', serverId, tenantId],
- queryFn: () => rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
+ queryKey: ["workspace-members", serverId, tenantId],
+ queryFn: () =>
+ rpc.chats.workspaceMembers({ serverId, tenantId: tenantId as string }),
enabled: tenantId !== null,
});
return (
@@ -300,20 +365,23 @@ function ChatAddPersonPanel({
loading={tenantId !== null && roster.isPending}
loadError={
tenantId === null
- ? 'This workspace has no tenant to list people from.'
+ ? "This workspace has no tenant to list people from."
: roster.isError
- ? failureText(roster.error, 'Could not list the people.')
+ ? failureText(roster.error, "Could not list the people.")
: null
}
- candidates={(roster.data ?? [])
- .filter((person) => !memberIds.has(person.userId))
- .map((person) => ({
- id: person.userId,
- name: person.name,
- mark: <PersonMark name={person.name} size="sm" />,
- detail: person.email ?? '',
- }))}
- footer={<InviteHint workspaceId={workspaceId} canInvite={canInvite(serverId, workspaceId)} />}
+ candidates={addablePeople(roster.data ?? [], memberIds).map((person) => ({
+ id: person.userId,
+ name: person.name,
+ mark: <PersonMark name={person.name} size="sm" />,
+ detail: person.email ?? "",
+ }))}
+ footer={
+ <InviteHint
+ workspaceId={workspaceId}
+ canInvite={canInvite(serverId, workspaceId)}
+ />
+ }
onAdd={async (userId) => {
try {
onAdded(await rpc.chats.addMember({ serverId, roomId, userId }));
@@ -327,8 +395,10 @@ function ChatAddPersonPanel({
/** Whether the viewer may invite people to the workspace, as the workspace menu decides it. */
function canInvite(serverId: string, workspaceId: string | null): boolean {
- const workspace = workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;
- const server = switchServersStore.servers.find((each) => each.id === serverId) ?? null;
+ const workspace =
+ workspacesStore.workspaces.find((each) => each.id === workspaceId) ?? null;
+ const server =
+ switchServersStore.servers.find((each) => each.id === serverId) ?? null;
return (
workspace !== null &&
server !== null &&
@@ -345,10 +415,10 @@ export function InviteHint({
workspaceId: string | null;
canInvite: boolean;
}) {
- const showInvitePeopleModal = useShowModal('invitePeopleModal');
+ const showInvitePeopleModal = useShowModal("invitePeopleModal");
return (
<p className="px-1 text-xs text-foreground-muted">
- Don&apos;t see someone?{' '}
+ Don&apos;t see someone?{" "}
{canInvite && workspaceId !== null ? (
<button
type="button"
@@ -358,7 +428,7 @@ export function InviteHint({
Invite them to the workspace
</button>
) : (
- 'Ask a workspace admin to invite them.'
+ "Ask a workspace admin to invite them."
)}
</p>
);
@@ -403,14 +473,18 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
if (query.isError) {
const settingsReadFailure = describeFailure(
query.error,
- 'Could not read this room’s settings.'
+ "Could not read this room’s settings.",
);
return (
<PanelNotice
title={settingsReadFailure.headline}
detail={settingsReadFailure.detail ?? undefined}
action={
- <Button variant="outline" size="sm" onClick={() => void query.refetch()}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void query.refetch()}
+ >
<RefreshCw className="size-3" />
Retry
</Button>
@@ -423,7 +497,10 @@ export const RoomConfigurationPanel = observer(function RoomConfigurationPanel({
return (
<div className="h-full overflow-y-auto">
<div className="mx-auto flex w-full max-w-[880px] flex-col gap-8 px-10 py-8">
- <RoomHeading serverId={switchRoomsStore.roomServerId(roomId)} room={room} />
+ <RoomHeading
+ serverId={switchRoomsStore.roomServerId(roomId)}
+ room={room}
+ />
{/* Keyed on the room so the drafts below belong to the room on screen:
switching rooms starts a fresh form rather than carrying half-typed
text across. */}
@@ -449,7 +526,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
workspaceId: string;
room: RemoteRoomDetail;
}) {
- const showDeleteRoomModal = useShowModal('deleteRoomModal');
+ const showDeleteRoomModal = useShowModal("deleteRoomModal");
const { navigate } = useNavigate();
if (!switchRoomsStore.canDeleteRoom(workspaceId, room)) return null;
@@ -462,8 +539,8 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
<p className="text-xs text-foreground-muted">
Removes the room and its conversation for everyone in it.
{room.bridgeType
- ? ` ${channelOnDeleteSummary(bridgePlatformLabel(room.bridgeType), room.channelOnDelete) ?? ''}`
- : ''}
+ ? ` ${channelOnDeleteSummary(bridgePlatformLabel(room.bridgeType), room.channelOnDelete) ?? ""}`
+ : ""}
</p>
</div>
<Button
@@ -477,7 +554,7 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
roomName: roomTitle(room),
// The page this is on is the deleted room's own, so staying would
// leave a settings form for something that no longer exists.
- onSuccess: () => navigate('home'),
+ onSuccess: () => navigate("home"),
})
}
>
@@ -488,17 +565,25 @@ const DeleteRoomSection = observer(function DeleteRoomSection({
);
});
-function RoomHeading({ serverId, room }: { serverId: string | null; room: RemoteRoomDetail }) {
+function RoomHeading({
+ serverId,
+ room,
+}: {
+ serverId: string | null;
+ room: RemoteRoomDetail;
+}) {
const platform = bridgePlatformLabel(room.bridgeType);
const { navigate } = useNavigate();
return (
<div className="flex items-start justify-between gap-4">
<div className="flex min-w-0 flex-col gap-1">
- <h1 className="truncate text-2xl font-semibold text-foreground">{roomTitle(room)}</h1>
+ <h1 className="truncate text-2xl font-semibold text-foreground">
+ {roomTitle(room)}
+ </h1>
<p className="text-sm text-foreground-muted">
{room.bridgeDisplayName
? `Room bridged to ${room.bridgeDisplayName}`
- : 'Room with no messaging app'}
+ : "Room with no messaging app"}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
@@ -506,7 +591,9 @@ function RoomHeading({ serverId, room }: { serverId: string | null; room: Remote
<Button
variant="outline"
size="sm"
- onClick={() => navigate('templateCapture', { serverId, roomId: room.id })}
+ onClick={() =>
+ navigate("templateCapture", { serverId, roomId: room.id })
+ }
>
<FileText className="size-3.5" />
Capture as template
@@ -519,7 +606,11 @@ function RoomHeading({ serverId, room }: { serverId: string | null; room: Remote
{room.bridgeDisplayName}
</span>
)}
- <Button variant="outline" size="sm" onClick={() => openRoomChannel(room.id)}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => openRoomChannel(room.id)}
+ >
<ExternalLink className="size-3.5" />
Open in {platform}
</Button>
@@ -531,7 +622,8 @@ function RoomHeading({ serverId, room }: { serverId: string | null; room: Remote
}
/** What the section is doing, once the user has stopped typing in it. */
-type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; message: string };
+type SaveState =
+ { phase: "idle" | "saving" | "saved" } | { phase: "failed"; message: string };
/**
* Description and instructions, written when Save is pressed.
@@ -544,18 +636,25 @@ type SaveState = { phase: 'idle' | 'saving' | 'saved' } | { phase: 'failed'; mes
*
* One request carries both fields, so the pair is stored together or not at all.
*/
-function GeneralSection({ workspaceId, room }: { workspaceId: string; room: RemoteRoomDetail }) {
+function GeneralSection({
+ workspaceId,
+ room,
+}: {
+ workspaceId: string;
+ room: RemoteRoomDetail;
+}) {
const queryClient = useQueryClient();
const savedDescription = room.description;
- const savedInstructions = room.instructions ?? '';
+ const savedInstructions = room.instructions ?? "";
const [description, setDescription] = useState(savedDescription);
const [instructions, setInstructions] = useState(savedInstructions);
- const [state, setState] = useState<SaveState>({ phase: 'idle' });
+ const [state, setState] = useState<SaveState>({ phase: "idle" });
- const dirty = description !== savedDescription || instructions !== savedInstructions;
+ const dirty =
+ description !== savedDescription || instructions !== savedInstructions;
async function save() {
- setState({ phase: 'saving' });
+ setState({ phase: "saving" });
try {
const updated = await rpc.workspaces.updateRoom({
workspaceId,
@@ -564,9 +663,12 @@ function GeneralSection({ workspaceId, room }: { workspaceId: string; room: Remo
instructions,
});
queryClient.setQueryData(roomDetailKey(workspaceId, room.id), updated);
- setState({ phase: 'saved' });
+ setState({ phase: "saved" });
} catch (cause) {
- setState({ phase: 'failed', message: failureText(cause, 'Could not save the change.') });
+ setState({
+ phase: "failed",
+ message: failureText(cause, "Could not save the change."),
+ });
}
}
@@ -584,19 +686,22 @@ function GeneralSection({ workspaceId, room }: { workspaceId: string; room: Remo
value={description}
onChange={(e) => {
setDescription(e.target.value);
- setState({ phase: 'idle' });
+ setState({ phase: "idle" });
}}
/>
</Field>
- <Field label="Instructions" hint="Sent to every agent as it joins the room.">
+ <Field
+ label="Instructions"
+ hint="Sent to every agent as it joins the room."
+ >
<Textarea
rows={4}
placeholder="Optional guidance shown to agents when they enter the room"
value={instructions}
onChange={(e) => {
setInstructions(e.target.value);
- setState({ phase: 'idle' });
+ setState({ phase: "idle" });
}}
/>
</Field>
@@ -608,10 +713,10 @@ function GeneralSection({ workspaceId, room }: { workspaceId: string; room: Remo
<Button
type="button"
size="sm"
- disabled={!dirty || state.phase === 'saving'}
+ disabled={!dirty || state.phase === "saving"}
onClick={() => void save()}
>
- {state.phase === 'saving' ? 'Saving…' : 'Save'}
+ {state.phase === "saving" ? "Saving…" : "Save"}
</Button>
</div>
</section>
@@ -620,14 +725,20 @@ function GeneralSection({ workspaceId, room }: { workspaceId: string; room: Remo
/** Says where the edits stand, so an unsaved change is never silent. */
function SaveStatus({ state, dirty }: { state: SaveState; dirty: boolean }) {
- if (state.phase === 'failed') {
- return <span className="text-xs text-destructive">Not saved — {state.message}</span>;
+ if (state.phase === "failed") {
+ return (
+ <span className="text-xs text-destructive">
+ Not saved — {state.message}
+ </span>
+ );
}
- if (state.phase === 'saved' && !dirty) {
+ if (state.phase === "saved" && !dirty) {
return <span className="text-xs text-foreground-muted">Saved.</span>;
}
if (dirty) {
- return <span className="text-xs text-foreground-muted">Unsaved changes.</span>;
+ return (
+ <span className="text-xs text-foreground-muted">Unsaved changes.</span>
+ );
}
return null;
}
@@ -666,10 +777,12 @@ const ParticipantsSection = observer(function ParticipantsSection({
}) {
const queryClient = useQueryClient();
const [adding, setAdding] = useState(false);
- const showAddAgentsToRoomModal = useShowModal('addAgentsToRoomModal');
+ const showAddAgentsToRoomModal = useShowModal("addAgentsToRoomModal");
async function refresh() {
- await queryClient.invalidateQueries({ queryKey: roomDetailKey(workspaceId, room.id) });
+ await queryClient.invalidateQueries({
+ queryKey: roomDetailKey(workspaceId, room.id),
+ });
await switchRoomsStore.refreshRoomState();
}
@@ -677,9 +790,14 @@ const ParticipantsSection = observer(function ParticipantsSection({
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<div className="flex items-baseline gap-2">
- <h2 className="text-sm font-semibold text-foreground">Participants</h2>
+ <h2 className="text-sm font-semibold text-foreground">
+ Participants
+ </h2>
<span className="text-xs text-foreground-muted">
- {membershipSummary(room.agentIds.length, room.connectedUserNames.length)}
+ {membershipSummary(
+ room.agentIds.length,
+ room.connectedUserNames.length,
+ )}
</span>
</div>
<div className="flex items-center gap-2">
@@ -710,12 +828,18 @@ const ParticipantsSection = observer(function ParticipantsSection({
people={room.connectedUserNames.map((name) => ({
id: `user:${name}`,
name,
- detail: 'person',
+ detail: "person",
}))}
manage={null}
/>
- {adding && <AddAgentPanel workspaceId={workspaceId} room={room} onAdded={refresh} />}
+ {adding && (
+ <AddAgentPanel
+ workspaceId={workspaceId}
+ room={room}
+ onAdded={refresh}
+ />
+ )}
</section>
);
});
@@ -755,8 +879,17 @@ const ParticipantList = observer(function ParticipantList({
{agentIds.map((agentId) => (
<ParticipantCard
key={agentId}
- mark={<AgentMark agentId={agentId} workspaceId={workspaceId} remoteById={remoteById} />}
- name={agentNames.get(agentId) ?? agentNameFor(agentId, workspaceId, remoteById)}
+ mark={
+ <AgentMark
+ agentId={agentId}
+ workspaceId={workspaceId}
+ remoteById={remoteById}
+ />
+ }
+ name={
+ agentNames.get(agentId) ??
+ agentNameFor(agentId, workspaceId, remoteById)
+ }
detail={agentKindFor(agentId, workspaceId, remoteById)}
removing={manage?.removing === agentId}
onRemove={manage && (() => manage.removeAgent(agentId))}
@@ -777,12 +910,12 @@ const ParticipantList = observer(function ParticipantList({
});
/** A person's initials disc: people have no picture in Switch. */
-function PersonMark({ name, size }: { name: string; size: 'sm' | 'md' }) {
+function PersonMark({ name, size }: { name: string; size: "sm" | "md" }) {
return (
<span
className={cn(
- 'flex shrink-0 items-center justify-center rounded-full bg-[var(--fill-2)] font-medium text-foreground',
- size === 'md' ? 'size-7 text-xs' : 'size-[22px] text-[10px]'
+ "flex shrink-0 items-center justify-center rounded-full bg-[var(--fill-2)] font-medium text-foreground",
+ size === "md" ? "size-7 text-xs" : "size-[22px] text-[10px]",
)}
>
{agentInitials(name)}
@@ -807,7 +940,9 @@ function ParticipantCard({
<div className="flex items-center gap-3 rounded-[10px] border border-border bg-[var(--surface-2)] px-3.5 py-3">
{mark}
<div className="flex min-w-0 flex-1 flex-col">
- <span className="truncate text-sm font-medium text-foreground">{name}</span>
+ <span className="truncate text-sm font-medium text-foreground">
+ {name}
+ </span>
<span className="truncate text-xs text-foreground-muted">{detail}</span>
</div>
{onRemove && (
@@ -826,7 +961,12 @@ function ParticipantCard({
);
}
-type Candidate = { id: string; name: string; mark: React.ReactNode; detail: string };
+type Candidate = {
+ id: string;
+ name: string;
+ mark: React.ReactNode;
+ detail: string;
+};
/**
* A searchable list of who could join, each row adding one. A refusal is shown
@@ -852,13 +992,14 @@ function AddParticipantPanel({
footer: React.ReactNode;
onAdd: (id: string) => Promise<void>;
}) {
- const [filter, setFilter] = useState('');
+ const [filter, setFilter] = useState("");
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const query = filter.trim().toLowerCase();
const shown = candidates.filter(
(candidate) =>
- query === '' || `${candidate.name}\n${candidate.detail}`.toLowerCase().includes(query)
+ query === "" ||
+ `${candidate.name}\n${candidate.detail}`.toLowerCase().includes(query),
);
async function add(id: string) {
@@ -886,12 +1027,12 @@ function AddParticipantPanel({
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
- {filter !== '' && (
+ {filter !== "" && (
<InputGroupAddon align="inline-end">
<InputGroupButton
size="icon-xs"
aria-label="Clear the search"
- onClick={() => setFilter('')}
+ onClick={() => setFilter("")}
>
<X className="size-3.5" />
</InputGroupButton>
@@ -899,15 +1040,21 @@ function AddParticipantPanel({
)}
</InputGroup>
- {error !== null && <p className="text-xs text-destructive">Not added — {error}</p>}
- {loadError !== null && <p className="text-xs text-destructive">{loadError}</p>}
+ {error !== null && (
+ <p className="text-xs text-destructive">Not added — {error}</p>
+ )}
+ {loadError !== null && (
+ <p className="text-xs text-destructive">{loadError}</p>
+ )}
{loading ? (
<p className="px-1 py-2 text-sm text-foreground-muted">Loading…</p>
) : shown.length === 0 ? (
loadError === null && (
<p className="px-1 py-2 text-sm text-foreground-muted">
- {query === '' ? allInText : `No ${noun} here matches “${filter.trim()}”.`}
+ {query === ""
+ ? allInText
+ : `No ${noun} here matches “${filter.trim()}”.`}
</p>
)
) : (
@@ -919,17 +1066,19 @@ function AddParticipantPanel({
disabled={busyId !== null}
onClick={() => void add(candidate.id)}
className={cn(
- 'flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]',
- busyId !== null && 'cursor-wait'
+ "flex w-full cursor-pointer items-center gap-3 bg-background px-3.5 py-2.5 text-left transition-colors hover:bg-[var(--fill)]",
+ busyId !== null && "cursor-wait",
)}
>
{candidate.mark}
<span className="min-w-0 flex-1 truncate text-sm text-foreground">
{candidate.name}
</span>
- <span className="shrink-0 text-xs text-foreground-muted">{candidate.detail}</span>
+ <span className="shrink-0 text-xs text-foreground-muted">
+ {candidate.detail}
+ </span>
<span className="shrink-0 text-xs font-medium text-foreground">
- {busyId === candidate.id ? 'Adding…' : 'Add'}
+ {busyId === candidate.id ? "Adding…" : "Add"}
</span>
</button>
))}
@@ -958,7 +1107,9 @@ const AddAgentPanel = observer(function AddAgentPanel({
}) {
const members = new Set(room.agentIds);
const { data: remoteAgents } = useWorkspaceAgents(workspaceId);
- const remoteById = new Map((remoteAgents ?? []).map((agent) => [agent.id, agent]));
+ const remoteById = new Map(
+ (remoteAgents ?? []).map((agent) => [agent.id, agent]),
+ );
return (
<AddParticipantPanel
noun="agent"
@@ -969,7 +1120,10 @@ const AddAgentPanel = observer(function AddAgentPanel({
loadError={null}
candidates={agentsStore
.agentsInWorkspace(workspaceId)
- .filter((agent) => agent.switchAgentId !== null && !members.has(agent.switchAgentId))
+ .filter(
+ (agent) =>
+ agent.switchAgentId !== null && !members.has(agent.switchAgentId),
+ )
.map((agent) => {
const switchAgentId = agent.switchAgentId as string;
return {
@@ -983,7 +1137,7 @@ const AddAgentPanel = observer(function AddAgentPanel({
size={22}
/>
),
- detail: providerDisplayName(agent.providerId) ?? 'Agent',
+ detail: providerDisplayName(agent.providerId) ?? "Agent",
};
})}
onAdd={async (switchAgentId) => {
@@ -991,7 +1145,7 @@ const AddAgentPanel = observer(function AddAgentPanel({
workspaceId,
roomId: room.id,
agentIds: [switchAgentId],
- direction: 'agents_to_room',
+ direction: "agents_to_room",
});
await onAdded();
}}
@@ -1014,7 +1168,9 @@ function PanelNotice({
<div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">
{icon && <div className="text-foreground-passive">{icon}</div>}
<p className="text-sm font-medium text-foreground">{title}</p>
- {detail && <p className="max-w-md text-xs text-foreground-muted">{detail}</p>}
+ {detail && (
+ <p className="max-w-md text-xs text-foreground-muted">{detail}</p>
+ )}
{action}
</div>
);
@@ -1048,20 +1204,21 @@ function AgentMark({
function localAgentFor(switchAgentId: string, workspaceId: string | null) {
if (workspaceId === null) return null;
return (
- agentsStore.agentsInWorkspace(workspaceId).find((a) => a.switchAgentId === switchAgentId) ??
- null
+ agentsStore
+ .agentsInWorkspace(workspaceId)
+ .find((a) => a.switchAgentId === switchAgentId) ?? null
);
}
function agentNameFor(
switchAgentId: string,
workspaceId: string | null,
- remoteById: Map<string, RemoteAgentSummary>
+ remoteById: Map<string, RemoteAgentSummary>,
): string {
return (
localAgentFor(switchAgentId, workspaceId)?.name ??
remoteById.get(switchAgentId)?.name ??
- 'Agent'
+ "Agent"
);
}
@@ -1070,9 +1227,12 @@ function agentNameFor(
function agentKindFor(
switchAgentId: string,
workspaceId: string | null,
- remoteById: Map<string, RemoteAgentSummary>
+ remoteById: Map<string, RemoteAgentSummary>,
): string {
- const providerId = localAgentFor(switchAgentId, workspaceId)?.providerId ?? null;
+ const providerId =
+ localAgentFor(switchAgentId, workspaceId)?.providerId ?? null;
const knownType = remoteById.get(switchAgentId)?.knownAgentType ?? null;
- return providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? 'agent';
+ return (
+ providerDisplayName(providerId) ?? providerDisplayName(knownType) ?? "agent"
+ );
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
index 728cb1d17..9bfade3d7 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.test.ts
@@ -1,31 +1,50 @@
-import { describe, expect, it } from 'vitest';
-import { membershipSummary, roomTitle } from './room-labels';
+import { describe, expect, it } from "vitest";
+import { addablePeople, membershipSummary, roomTitle } from "./room-labels";
-describe('roomTitle', () => {
- it('marks a bridged room as the channel it is', () => {
- expect(roomTitle({ name: 'louis-dev', bridgeType: 'mattermost' })).toBe('#louis-dev');
+describe("roomTitle", () => {
+ it("marks a bridged room as the channel it is", () => {
+ expect(roomTitle({ name: "louis-dev", bridgeType: "mattermost" })).toBe(
+ "#louis-dev",
+ );
});
- it('leaves a room in no messaging app alone — there is no channel to name', () => {
- expect(roomTitle({ name: 'louis-dev', bridgeType: null })).toBe('louis-dev');
+ it("leaves a room in no messaging app alone — there is no channel to name", () => {
+ expect(roomTitle({ name: "louis-dev", bridgeType: null })).toBe(
+ "louis-dev",
+ );
});
- it('does not double the sigil on a name that already carries one', () => {
- expect(roomTitle({ name: '#general', bridgeType: 'slack' })).toBe('#general');
+ it("does not double the sigil on a name that already carries one", () => {
+ expect(roomTitle({ name: "#general", bridgeType: "slack" })).toBe(
+ "#general",
+ );
});
});
-describe('membershipSummary', () => {
- it('counts agents and people separately', () => {
- expect(membershipSummary(1, 1)).toBe('1 agent · 1 person');
- expect(membershipSummary(3, 2)).toBe('3 agents · 2 people');
+describe("membershipSummary", () => {
+ it("counts agents and people separately", () => {
+ expect(membershipSummary(1, 1)).toBe("1 agent · 1 person");
+ expect(membershipSummary(3, 2)).toBe("3 agents · 2 people");
});
- it('omits people rather than reporting none', () => {
- expect(membershipSummary(2, 0)).toBe('2 agents');
+ it("omits people rather than reporting none", () => {
+ expect(membershipSummary(2, 0)).toBe("2 agents");
});
- it('says an empty room has no agents rather than saying nothing', () => {
- expect(membershipSummary(0, 0)).toBe('0 agents');
+ it("says an empty room has no agents rather than saying nothing", () => {
+ expect(membershipSummary(0, 0)).toBe("0 agents");
+ });
+});
+
+describe("addablePeople", () => {
+ it("skips a service account by its flag and anyone already in, not by name", () => {
+ const roster = [
+ { userId: "u1", name: "Agent Bootstrap", serviceAccount: true },
+ { userId: "u2", name: "Agent Bootstrap", serviceAccount: false },
+ { userId: "u3", name: "alice", serviceAccount: false },
+ ];
+ expect(
+ addablePeople(roster, new Set(["u3"])).map((person) => person.userId),
+ ).toEqual(["u2"]);
});
});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
index ca1bd7611..12d3780cc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-labels.ts
@@ -6,8 +6,11 @@
* the name does not already carry one, and never to a room in no app at all,
* where there is no channel for it to name.
*/
-export function roomTitle(room: { name: string; bridgeType: string | null }): string {
- if (!room.bridgeType || room.name.startsWith('#')) return room.name;
+export function roomTitle(room: {
+ name: string;
+ bridgeType: string | null;
+}): string {
+ if (!room.bridgeType || room.name.startsWith("#")) return room.name;
return `#${room.name}`;
}
@@ -18,8 +21,24 @@ export function roomTitle(room: { name: string; bridgeType: string | null }): st
* People are left out rather than shown as zero: an unbridged room has no way
* for anyone to be in it, and "0 people" reads as a room nobody came to.
*/
-export function membershipSummary(agentCount: number, personCount: number): string {
- const agents = `${agentCount} ${agentCount === 1 ? 'agent' : 'agents'}`;
+export function membershipSummary(
+ agentCount: number,
+ personCount: number,
+): string {
+ const agents = `${agentCount} ${agentCount === 1 ? "agent" : "agents"}`;
if (personCount === 0) return agents;
- return `${agents} · ${personCount} ${personCount === 1 ? 'person' : 'people'}`;
+ return `${agents} · ${personCount} ${personCount === 1 ? "person" : "people"}`;
+}
+
+/**
+ * The roster's people who can still be added to a chat: not in it already, and
+ * not a service account (the agent-registration bootstrap owner), which the
+ * server marks rather than anything its name says.
+ */
+export function addablePeople<
+ T extends { userId: string; serviceAccount: boolean },
+>(roster: T[], memberIds: Set<string>): T[] {
+ return roster.filter(
+ (person) => !person.serviceAccount && !memberIds.has(person.userId),
+ );
}
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.ts
index f5f75af74..7e8b9476f 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
@@ -1,4 +1,4 @@
-import { z } from 'zod';
+import { z } from "zod";
/**
* A chat is a Switch room the signed-in person is a member of and that has at
@@ -22,7 +22,13 @@ export type ChatAgent = z.infer<typeof chatAgentSchema>;
export const chatSummarySchema = z.object({
roomId: z.string(),
name: z.string(),
- channelType: z.enum(['lobby', 'channel_public', 'channel_private', 'group', 'direct']),
+ channelType: z.enum([
+ "lobby",
+ "channel_public",
+ "channel_private",
+ "group",
+ "direct",
+ ]),
bridgeType: z.string().nullable(),
channelName: z.string().nullable(),
agents: z.array(chatAgentSchema),
@@ -46,7 +52,7 @@ export type ChatSummary = z.infer<typeof chatSummarySchema>;
export const chatSenderSchema = z.object({
clientId: z.string(),
name: z.string(),
- kind: z.enum(['human', 'agent', 'system']),
+ kind: z.enum(["human", "agent", "system"]),
agentId: z.string().nullable(),
userId: z.string().nullable(),
});
@@ -92,8 +98,12 @@ export const chatThreadMessagesPageSchema = z.object({
headSeq: z.number().int(),
hasMore: z.boolean(),
});
-export type ChatThreadMessagesPage = z.infer<typeof chatThreadMessagesPageSchema>;
-export const chatSentSchema = z.object({ messages: z.array(chatMessageSchema) });
+export type ChatThreadMessagesPage = z.infer<
+ typeof chatThreadMessagesPageSchema
+>;
+export const chatSentSchema = z.object({
+ messages: z.array(chatMessageSchema),
+});
export const chatAgentAddedSchema = z.object({ chat: chatSummarySchema });
export const chatMemberSchema = z.object({
userId: z.string(),
@@ -101,11 +111,24 @@ export const chatMemberSchema = z.object({
isOwner: z.boolean(),
});
export type ChatMember = z.infer<typeof chatMemberSchema>;
-export const chatMemberListSchema = z.object({ members: z.array(chatMemberSchema) });
+export const chatMemberListSchema = z.object({
+ members: z.array(chatMemberSchema),
+});
/** A person in the workspace, from its roster, who could be added to a chat. */
export const workspaceMemberSchema = z
- .object({ user_id: z.string(), name: z.string(), email: z.string().nullish() })
- .transform(({ user_id, name, email }) => ({ userId: user_id, name, email: email || null }));
+ .object({
+ user_id: z.string(),
+ name: z.string(),
+ email: z.string().nullish(),
+ // Older servers do not report it; they have no way to mark one.
+ service_account: z.boolean().optional(),
+ })
+ .transform(({ user_id, name, email, service_account }) => ({
+ userId: user_id,
+ name,
+ email: email || null,
+ serviceAccount: service_account ?? false,
+ }));
export type WorkspaceMember = z.infer<typeof workspaceMemberSchema>;
export const chatUploadSchema = z.object({
uploadId: z.string(),
@@ -119,7 +142,7 @@ export type ChatUpload = z.infer<typeof chatUploadSchema>;
* `access`: the person lost the room (membership, workspace role, archive).
* `unlisted`: still a member, but the room no longer qualifies for the list.
*/
-export const chatRemovalReasonSchema = z.enum(['access', 'unlisted']);
+export const chatRemovalReasonSchema = z.enum(["access", "unlisted"]);
export type ChatRemovalReason = z.infer<typeof chatRemovalReasonSchema>;
export const chatRemovedSchema = z.object({
roomId: z.string(),
@@ -135,7 +158,7 @@ export const chatErrorBodySchema = z.object({
* The live feed's state. `live` is only reached after the server's `ready`,
* which it sends once every member room has been caught up from its cursor.
*/
-export type ChatStreamState = 'connecting' | 'catching-up' | 'live' | 'offline';
+export type ChatStreamState = "connecting" | "catching-up" | "live" | "offline";
export type ChatSendInput = {
serverId: string;
@@ -158,22 +181,28 @@ export type ChatUploadInput = {
};
/** The display name the room and the platforms show for an agent. */
-export function chatAgentLabel(agent: Pick<ChatAgent, 'name' | 'displayName'>): string {
+export function chatAgentLabel(
+ agent: Pick<ChatAgent, "name" | "displayName">,
+): string {
return agent.displayName ?? agent.name;
}
/** The `clientTxn` a Console send's parts carry: `{requestId}:{index}`. */
export function requestIdOfClientTxn(clientTxn: string | null): string | null {
if (clientTxn === null) return null;
- const at = clientTxn.lastIndexOf(':');
+ const at = clientTxn.lastIndexOf(":");
return at > 0 ? clientTxn.slice(0, at) : null;
}
/** The notice an agent posts to a room while a session starts to answer it. */
-export const SESSION_STARTING_MESSAGE = 'Starting a session to handle this — one moment.';
+export const SESSION_STARTING_MESSAGE =
+ "Starting a session to handle this — one moment.";
export function isSessionStartingNotice(message: ChatMessage): boolean {
- return message.sender.kind === 'agent' && message.body.trim() === SESSION_STARTING_MESSAGE;
+ return (
+ message.sender.kind === "agent" &&
+ message.body.trim() === SESSION_STARTING_MESSAGE
+ );
}
/**
@@ -183,52 +212,63 @@ export function isSessionStartingNotice(message: ChatMessage): boolean {
*/
export function liveSessionStartingNotices(
messages: readonly ChatMessage[],
- turnAgents: ReadonlyMap<string, ReadonlySet<string>>
+ turnAgents: ReadonlyMap<string, ReadonlySet<string>>,
): Set<string> {
const live = new Set<string>();
const seen = new Set<string>();
for (let at = messages.length - 1; at >= 0; at--) {
const message = messages[at];
- if (message.sender.kind !== 'agent' || seen.has(message.sender.clientId)) continue;
+ if (message.sender.kind !== "agent" || seen.has(message.sender.clientId))
+ continue;
seen.add(message.sender.clientId);
if (!isSessionStartingNotice(message)) continue;
let from = at;
- while (from > 0 && messages[from].sender.kind !== 'human') from--;
+ while (from > 0 && messages[from].sender.kind !== "human") from--;
const agentId = message.sender.agentId;
const working = messages
.slice(from)
- .some((each) => agentId !== null && turnAgents.get(each.messageId)?.has(agentId));
+ .some(
+ (each) =>
+ agentId !== null && turnAgents.get(each.messageId)?.has(agentId),
+ );
if (!working) live.add(message.messageId);
}
return live;
}
/** What the host posts for a turn that ended without the agent posting, then why it ended. */
-export const UNPOSTED_REPLY_MESSAGE = 'I finished without replying.';
-export const TURN_FAILED_PHRASE = 'The turn failed';
-export const TURN_INTERRUPTED_PHRASE = 'The turn was interrupted';
+export const UNPOSTED_REPLY_MESSAGE = "I finished without replying.";
+export const TURN_FAILED_PHRASE = "The turn failed";
+export const TURN_INTERRUPTED_PHRASE = "The turn was interrupted";
export type TurnEndNotice = {
- outcome: 'completed' | 'failed' | 'interrupted';
+ outcome: "completed" | "failed" | "interrupted";
reason: string | null;
};
/** The host's notice of a turn that ended without a reply, or null for any other message. */
export function turnEndNotice(message: ChatMessage): TurnEndNotice | null {
const body = message.body.trim();
- if (message.sender.kind !== 'agent' || !body.startsWith(UNPOSTED_REPLY_MESSAGE)) return null;
+ if (
+ message.sender.kind !== "agent" ||
+ !body.startsWith(UNPOSTED_REPLY_MESSAGE)
+ )
+ return null;
const rest = body.slice(UNPOSTED_REPLY_MESSAGE.length).trim();
- if (!rest) return { outcome: 'completed', reason: null };
+ if (!rest) return { outcome: "completed", reason: null };
for (const [phrase, outcome] of [
- [TURN_FAILED_PHRASE, 'failed'],
- [TURN_INTERRUPTED_PHRASE, 'interrupted'],
+ [TURN_FAILED_PHRASE, "failed"],
+ [TURN_INTERRUPTED_PHRASE, "interrupted"],
] as const) {
if (rest === `${phrase}.`) return { outcome, reason: null };
// An interrupt is the person's Stop; the provider's raw reason for it says nothing more.
if (rest.startsWith(`${phrase}: `))
return {
outcome,
- reason: outcome === 'interrupted' ? null : rest.slice(phrase.length + 2).trim(),
+ reason:
+ outcome === "interrupted"
+ ? null
+ : rest.slice(phrase.length + 2).trim(),
};
}
return null;
diff --git a/core/switch_core/bridges/agent/registration_bootstrap.py b/core/switch_core/bridges/agent/registration_bootstrap.py
index 03969a9cd..f327692f1 100644
--- a/core/switch_core/bridges/agent/registration_bootstrap.py
+++ b/core/switch_core/bridges/agent/registration_bootstrap.py
@@ -98,7 +98,9 @@ BOOTSTRAP_LAST_SEEDED_HASH_META_KEY = "agent_bootstrap_key_last_hash"
BOOTSTRAP_REVOKED_HASHES_META_KEY = "agent_bootstrap_revoked_hashes"
-def _is_genuine(owner: User) -> bool:
+def is_bootstrap_owner(owner: User) -> bool:
+ """Whether `owner` is the account bootstrap-registered agents are owned
+ by: a service account, not a person."""
meta = owner.metadata_ or {}
if meta.get(BOOTSTRAP_OWNER_MARKER_META_KEY):
return True
@@ -106,7 +108,7 @@ def _is_genuine(owner: User) -> bool:
def _raise_unless_genuine(owner: User) -> None:
- if not _is_genuine(owner):
+ if not is_bootstrap_owner(owner):
raise RuntimeError(
f"An account already exists at {BOOTSTRAP_OWNER_EMAIL} but "
"cannot be proven to have been created by agent-registration "
@@ -134,7 +136,7 @@ async def ensure_bootstrap_owner(session: AsyncSession, user_store: UserStore) -
"""Idempotently create the account bootstrap-registered agents are owned by.
Raises if an account already exists at that address that cannot be
- proven genuine (see ``_is_genuine``), or that has since been given the
+ proven genuine (see ``is_bootstrap_owner``), or that has since been given the
admin role. A genuine row created before the marker existed is backfilled
with one here rather than refused.
"""
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index 8c3141d21..cd1765fc1 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -47,6 +47,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.addressing import allows_on_behalf_of, parse_policy
from switch_core.authz import administers_tenant
from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
+from switch_core.bridges.agent.registration_bootstrap import is_bootstrap_owner
from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.chats.views import (
COMMAND_EVENT_TYPE,
@@ -786,6 +787,8 @@ class ChatService:
"NOT_A_TENANT_MEMBER",
"That person is not a member of this workspace.",
)
+ if is_bootstrap_owner(user):
+ raise ChatError(422, "NOT_A_PERSON", "That account can't join chats.")
return user
async def _make_group(self, session: AsyncSession, room: Room) -> None:
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index f7ab47064..4975d134c 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1086,6 +1086,9 @@ class MemberDetail(BaseModel):
email: str
role: str
created_at: str
+ # The agent-registration bootstrap owner: kept in the roster, never a
+ # person to add to a chat.
+ service_account: bool
class UsageTotalResponse(BaseModel):
diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.py
index 970c8f3a9..1b13f1513 100644
--- a/core/switch_core/gateway/tenants.py
+++ b/core/switch_core/gateway/tenants.py
@@ -14,6 +14,7 @@ from sqlalchemy.exc import DBAPIError, IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.agent.protocol.agent_core import AgentCore
+from switch_core.bridges.agent.registration_bootstrap import is_bootstrap_owner
from switch_core.clients.client_lifecycle_service import (
ClientLifecycleService,
TenantIsolationNotInForce,
@@ -193,6 +194,7 @@ def _member_detail(user: User, membership: TenantMember) -> MemberDetail:
email=user.email,
role=membership.role,
created_at=str(membership.created_at),
+ service_account=is_bootstrap_owner(user),
)
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 957f8da6f..0b4d0126a 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -12,7 +12,10 @@ import pytest
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import Agent, Message, Room, room_agents
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_OWNER_MARKER_META_KEY,
+)
+from switch_core.db.models import Agent, Message, Room, User, room_agents
from tests.switch_core.gateway.conftest import _Harness
from tests.switch_core.gateway.test_chats_routes import (
_code,
@@ -407,6 +410,43 @@ async def test_a_create_refuses_someone_outside_the_workspace(
assert _code(refused) == "NOT_A_TENANT_MEMBER"
+async def _make_bootstrap_owner(chats: _Harness, user: User) -> None:
+ async with chats.factory() as session:
+ row = await session.get(User, user.id)
+ assert row is not None
+ row.metadata_ = {BOOTSTRAP_OWNER_MARKER_META_KEY: True}
+ await session.commit()
+
+
+async def test_the_bootstrap_owner_is_not_a_person_to_chat_with(
+ chats: _Harness,
+) -> None:
+ await _make_bootstrap_owner(chats, chats.bob)
+ agent = await chats.agent("helper", owner=chats.alice)
+ owned = await chats.agent("bootstrapped", owner=chats.bob)
+ room_id = await chats.new_chat(chats.alice, agent, "c1")
+
+ refused = await chats.invite(chats.alice, room_id, chats.bob)
+ assert refused.status_code == 422
+ assert _code(refused) == "NOT_A_PERSON"
+ created = await chats.client.post(
+ "/chats",
+ json={"agentIds": [], "memberUserIds": [chats.bob.id], "requestId": "c2"},
+ headers=chats.as_user(chats.alice),
+ )
+ assert created.status_code == 422
+ assert _code(created) == "NOT_A_PERSON"
+
+ # Its agents are still welcome, and the flag is the marker, not a name.
+ assert (await _add_agent(chats, chats.alice.id, room_id, owned)).status_code == 200
+ async with chats.factory() as session:
+ admin = await session.get(User, chats.admin.id)
+ assert admin is not None
+ admin.name = "Agent Bootstrap"
+ await session.commit()
+ assert (await chats.invite(chats.alice, room_id, chats.admin)).status_code == 200
+
+
# ── Adding and removing agents ───────────────────────────────────────────────
diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.py
index 328b44c9d..b346955b5 100644
--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py
+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py
@@ -30,6 +30,9 @@ from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.bridges.agent.registration_bootstrap import (
+ BOOTSTRAP_OWNER_MARKER_META_KEY,
+)
from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.connections.adapters.github import GitHubAdapter
from switch_core.connections.broker import ServiceBroker
@@ -1413,6 +1416,30 @@ class TestMemberRoutes:
roles = {row["name"]: row["role"] for row in response.json()}
assert roles == {"list-owner": "owner", "list-member": "member"}
+ async def test_listing_flags_the_bootstrap_owner_as_a_service_account(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _make_tenant(session_factory, TENANT_A)
+ owner_id = await _make_member(
+ session_factory, name="Agent Bootstrap", tenant_id=TENANT_A, role="owner"
+ )
+ bootstrap_id = await _make_member(
+ session_factory, name="robot", tenant_id=TENANT_A, role="member"
+ )
+ async with session_factory() as session:
+ bootstrap = await session.get(User, bootstrap_id)
+ assert bootstrap is not None
+ bootstrap.metadata_ = {BOOTSTRAP_OWNER_MARKER_META_KEY: True}
+ await session.commit()
+ token = _token(owner_id, "Agent [email protected]", TENANT_A)
+
+ async with _client(_app(session_factory), token) as client:
+ response = await client.get(f"/tenants/{TENANT_A}/members")
+
+ assert response.status_code == 200, response.text
+ flags = {row["name"]: row["service_account"] for row in response.json()}
+ assert flags == {"Agent Bootstrap": False, "robot": True}
+
async def test_the_last_owner_cannot_be_demoted(
self, session_factory: async_sessionmaker[AsyncSession]
) -> None: