Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(buddy): Console group-chat fallback, and Teams and Telegram setup
raullopez-sandbox692a29f8c58a
diff --git a/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsx b/console/apps/switch-console-desktop/src/renderer/features/managed-agents/agent-chats.tsxindex b2bcdf99b..3db5a3b37 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@@ -347,6 +347,7 @@ export const AgentChats = observer(function AgentChats({ agent }: { agent: ManagserverId={serverId}workspaceId={workspaceId}agentId={agentId}+ agentName={agent.name}roomId={roomId}/>) : nulldiff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsxindex 4ff19c2b4..d32869007 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-cards.tsx@@ -3,7 +3,6 @@ import { ArrowRight, CheckCircle2 } from 'lucide-react';import { observer } from 'mobx-react-lite';import { type ReactNode, useState } from 'react';import { chatsStore } from '@renderer/features/chats/stores/chats';-import { offerAccountLinkAfterConnect } from '@renderer/features/switch-servers/offer-account-link';import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';import { BridgeIcon } from '@renderer/lib/components/bridge-icon';import { failureText } from '@renderer/lib/errors/describe-failure';@@ -14,7 +13,13 @@ import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import { cn } from '@renderer/utils/utils';import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';-import { type BuddyResume, buddyResumeBridges, buddySetupStep } from './buddy-setup-step';+import {+ type BuddyPlatform,+ type BuddyResume,+ buddyPlatform,+ buddyResumeBridges,+ buddySetupStep,+} from './buddy-setup-step';import {BUDDY_CHAT_NAME,buddyHandoffRequestId,@@ -22,39 +27,60 @@ import {resumeBuddyInSlack,} from './open-buddy';+/** What the person says in the Welcome chat when they choose to stay in Console. */+export const BUDDY_STAY_MESSAGE = 'I’ll stay in Switch Console for now.';+/**- * The setup cards under the greeting in the buddy's Welcome chat: pick Slack,- * connect it, link your account, then continue with the buddy in a private- * Slack channel. Drawn only in the Welcome chat.+ * The setup cards under the greeting in the buddy's Welcome chat: pick a chat+ * app, connect it, link your account, then continue with the buddy there — in+ * a private channel made for them on Slack, by their own invite elsewhere. Or+ * stay here, which says so in the chat for the buddy to pick up. Drawn only in+ * the Welcome chat.*/export const BuddySetupCards = observer(function BuddySetupCards({serverId,workspaceId,agentId,+ agentName,roomId,}: {serverId: string;workspaceId: string;agentId: string;+ agentName: string;roomId: string;}) {const chat = chatsStore.chat(roomId);if (!chat || chat.name !== BUDDY_CHAT_NAME || chat.bridgeType !== null) return null;- return <Cards serverId={serverId} workspaceId={workspaceId} agentId={agentId} />;+ return (+ <Cards+ serverId={serverId}+ workspaceId={workspaceId}+ agentId={agentId}+ agentName={agentName}+ roomId={roomId}+ />+ );});const Cards = observer(function Cards({serverId,workspaceId,agentId,+ agentName,+ roomId,}: {serverId: string;workspaceId: string;agentId: string;+ agentName: string;+ roomId: string;}) {const queryClient = useQueryClient();const showConnect = useShowModal('connectMessagingAppModal');- const [picked, setPicked] = useState(false);+ const showClaimIdentity = useShowModal('claimIdentityModal');+ const [picked, setPicked] = useState<BuddyPlatform | null>(null);+ const [reopened, setReopened] = useState(false);const [creating, setCreating] = useState(false);const [createError, setCreateError] = useState<string | null>(null);@@ -78,7 +104,10 @@ const Cards = observer(function Cards({if (query.isError) resumes[bridge.id] = 'failed';else if (query.isSuccess) resumes[bridge.id] = query.data;});+ const platform = buddyPlatform(picked, bridgesQuery.data ?? null);+ const label = platform ? PLATFORM_NAMES[platform] : '';const step = buddySetupStep({+ platform,bridges: bridgesQuery.data ?? null,identities: ids.identities,resumes,@@ -119,51 +148,92 @@ const Cards = observer(function Cards({}};- const pastChoice =- picked || (step.kind !== 'loading' && step.kind !== 'unknown' && step.kind !== 'connect');+ const timeline = chatsStore.timelines.get(serverId, roomId);+ const stayed =+ timeline.messages.some(+ (message) => message.sender.kind === 'human' && message.body === BUDDY_STAY_MESSAGE+ ) || timeline.pending.some((send) => send.body === BUDDY_STAY_MESSAGE);+ const stay = () => {+ setReopened(false);+ timeline.send({+ body: BUDDY_STAY_MESSAGE,+ threadRootId: null,+ mentionAgentIds: [],+ mentionUserIds: [],+ mentionSpans: [],+ files: [],+ requestId: null,+ });+ };++ if (stayed && !reopened)+ return (+ <div className="mt-4" data-testid="buddy-setup-cards">+ <StatusRow>+ <span className="min-w-0 flex-1 text-foreground-muted">+ Continuing here in Switch Console.+ </span>+ <Button size="sm" variant="outline" onClick={() => setReopened(true)}>+ Connect a chat app+ </Button>+ </StatusRow>+ </div>+ );++ const pressed = (app: BuddyPlatform) =>+ platform === app && (picked !== null || (step.kind !== 'loading' && step.kind !== 'unknown'));return (<div className="@container mt-4 flex flex-col gap-3" data-testid="buddy-setup-cards"><div className="font-semibold">Where does your team chat?</div><div className="grid grid-cols-2 gap-3 @lg:grid-cols-4">- <button- type="button"- aria-pressed={pastChoice}- onClick={() => setPicked(true)}- className={cn(- 'flex flex-col items-start gap-3 rounded-lg border bg-background p-3 text-left transition-colors hover:bg-background-1 focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none',- pastChoice && 'border-foreground/40 shadow-sm ring-1 ring-foreground/20'- )}- >- <BridgeIcon bridgeType="slack" size={28} />- <TileText name="Slack" subtitle="Channels & DMs" />- </button>- {COMING_SOON.map((app) => (- <button- key={app.bridgeType}- type="button"- aria-disabled="true"- title="Coming soon"- className="flex cursor-not-allowed flex-col items-start gap-3 rounded-lg border bg-background p-3 text-left opacity-50"- >- <BridgeIcon bridgeType={app.bridgeType} size={28} />- <TileText name={app.name} subtitle={app.subtitle} />- <span className="text-xs text-foreground-muted">Coming soon</span>- </button>- ))}+ {TILES.map((app) =>+ app.live ? (+ <button+ key={app.bridgeType}+ type="button"+ aria-pressed={pressed(app.bridgeType)}+ onClick={() => setPicked(app.bridgeType)}+ className={cn(+ 'flex flex-col items-start gap-3 rounded-lg border bg-background p-3 text-left transition-colors hover:bg-background-1 focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none',+ pressed(app.bridgeType) &&+ 'border-foreground/40 shadow-sm ring-1 ring-foreground/20'+ )}+ >+ <BridgeIcon bridgeType={app.bridgeType} size={28} />+ <TileText name={app.name} subtitle={app.subtitle} />+ </button>+ ) : (+ <button+ key={app.bridgeType}+ type="button"+ aria-disabled="true"+ title="Coming soon"+ className="flex cursor-not-allowed flex-col items-start gap-3 rounded-lg border bg-background p-3 text-left opacity-50"+ >+ <BridgeIcon bridgeType={app.bridgeType} size={28} />+ <TileText name={app.name} subtitle={app.subtitle} />+ <span className="text-xs text-foreground-muted">Coming soon</span>+ </button>+ )+ )}</div>+ <Button variant="ghost" size="sm" className="self-start" onClick={stay}>+ No chat app? Continue here in Switch Console+ <ArrowRight />+ </Button>- {pastChoice && step.kind === 'loading' && (+ {platform && step.kind === 'loading' && (<StatusRow><Spinner size="sm" />- Checking Slack…+ Checking {label}…</StatusRow>)}- {pastChoice && step.kind === 'unknown' && (+ {step.kind === 'unknown' && (<StatusRow className="border-border-destructive text-foreground-destructive"><div className="min-w-0 flex-1">- <div className="font-semibold">Couldn’t check Slack</div>+ <div className="font-semibold">Couldn’t check {label || 'your chat apps'}</div><div>Switch did not answer.</div></div><Button size="sm" variant="outline" onClick={retry}>@@ -172,13 +242,16 @@ const Cards = observer(function Cards({</StatusRow>)}- {pastChoice && step.kind === 'connect' && (- <SlackCard- title="Connect Slack"- description="Add Slack to your Switch workspace."+ {step.kind === 'connect' && (+ <PlatformCard+ platform={step.platform}+ title={`Connect ${label}`}+ description={`Add ${label} to your Switch workspace.`}footer={- <Button onClick={() => showConnect({ serverId, platform: 'slack', onClosed: retry })}>- Connect Slack+ <Button+ onClick={() => showConnect({ serverId, platform: step.platform, onClosed: retry })}+ >+ Connect {label}</Button>}/>@@ -188,23 +261,29 @@ const Cards = observer(function Cards({<><div className="flex items-center gap-2 text-sm text-foreground-success"><CheckCircle2 className="size-4" />- Slack connected+ {label} connected</div>- <SlackCard- title="Link your Slack account"- description={`So I recognise you in ${step.bridge.displayName}.`}+ <PlatformCard+ platform={step.bridge.type}+ title={`Link your ${label} account`}+ description={+ // The bot can find only people who have written where it can hear them, and+ // privacy mode lets it hear only slash commands.+ step.bridge.type === 'telegram'+ ? `I answer only accounts I recognise. Make a Telegram group with just you and the ${step.bridge.displayName} bot, and send this in it. Then link your account here: Switch shows a code to send in that group. Once it's linked, I'll answer when you reply to the bot's message there.`+ : `So I recognise you in ${step.bridge.displayName}.`+ }footer={- <Button- onClick={() =>- offerAccountLinkAfterConnect(workspaceId, {- bridgeId: step.bridge.id,- displayName: step.bridge.displayName,- directorySearchSupported: step.bridge.directorySearchSupported,- })- }- >- Link account- </Button>+ <div className="flex flex-wrap items-center gap-3">+ {step.bridge.type === 'telegram' && (+ <InviteCommand platform="telegram" agentName={agentName} />+ )}+ <Button+ onClick={() => showClaimIdentity({ workspaceId, bridgeId: step.bridge.id })}+ >+ Link account+ </Button>+ </div>}/></>@@ -219,7 +298,8 @@ const Cards = observer(function Cards({</span><BridgeIcon bridgeType="slack" size={16} /></div>- <SlackCard+ <PlatformCard+ platform="slack"title="Continue in a private Slack channel"description="I’ll create a private channel just for us and continue there."error={createError}@@ -244,6 +324,28 @@ const Cards = observer(function Cards({</>)}+ {step.kind === 'guide' && (+ <>+ <div className="flex items-center gap-2 rounded-lg bg-background-success px-3 py-2 text-sm text-foreground-success">+ <CheckCircle2 className="size-4 shrink-0" />+ <span className="min-w-0 flex-1">+ <span className="font-semibold">{label} ready</span>+ </span>+ <BridgeIcon bridgeType={step.bridge.type} size={16} />+ </div>+ <PlatformCard+ platform={step.bridge.type}+ title={`Continue in ${label}`}+ description={+ step.bridge.type === 'telegram'+ ? `In a Telegram group with you and the ${step.bridge.displayName} bot, send this if you haven't yet. Then reply to the bot's message, mention ${agentName} in that reply, and say what you work on.`+ : `Add the Switch app to a Teams chat or channel and send this there. Then mention ${agentName} with a short note on what you work on.`+ }+ footer={<InviteCommand platform={step.bridge.type} agentName={agentName} />}+ />+ </>+ )}+{step.kind === 'resuming' && (<StatusRow><Spinner size="sm" />@@ -281,11 +383,18 @@ const Cards = observer(function Cards({);});-const COMING_SOON = [- { bridgeType: 'teams', name: 'Microsoft Teams', subtitle: 'Teams & chats' },- { bridgeType: 'discord', name: 'Discord', subtitle: 'Servers & channels' },- { bridgeType: 'telegram', name: 'Telegram', subtitle: 'Groups & chats' },-];+const PLATFORM_NAMES: Record<BuddyPlatform, string> = {+ slack: 'Slack',+ teams: 'Microsoft Teams',+ telegram: 'Telegram',+};++const TILES = [+ { live: true, bridgeType: 'slack', name: 'Slack', subtitle: 'Channels & DMs' },+ { live: true, bridgeType: 'teams', name: 'Microsoft Teams', subtitle: 'Teams & chats' },+ { live: false, bridgeType: 'discord', name: 'Discord', subtitle: 'Servers & channels' },+ { live: true, bridgeType: 'telegram', name: 'Telegram', subtitle: 'Groups & chats' },+] as const;function TileText({ name, subtitle }: { name: string; subtitle: string }) {return (@@ -296,6 +405,15 @@ function TileText({ name, subtitle }: { name: string; subtitle: string }) {);}+/** Telegram's bot sees only slash commands in a group where it is not an admin. */+function InviteCommand({ platform, agentName }: { platform: string; agentName: string }) {+ return (+ <code className="rounded bg-background px-2 py-1 font-mono text-sm select-all">+ {platform === 'telegram' ? '/invite_agent' : '!invite-agent'} @{agentName}+ </code>+ );+}+function StatusRow({ className, children }: { className?: string; children: ReactNode }) {return (<div@@ -309,12 +427,14 @@ function StatusRow({ className, children }: { className?: string; children: Reac);}-function SlackCard({+function PlatformCard({+ platform,title,description,error,footer,}: {+ platform: string;title: string;description: string;error?: string | null;@@ -324,7 +444,7 @@ function SlackCard({<div className="overflow-hidden rounded-xl border bg-background"><div className="flex items-start gap-3 p-4"><div className="flex size-10 shrink-0 items-center justify-center rounded-lg border">- <BridgeIcon bridgeType="slack" size={20} />+ <BridgeIcon bridgeType={platform} size={20} /></div><div className="min-w-0"><div className="font-semibold">{title}</div>diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.tsindex b2e53ef90..30d5f21c9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.test.ts@@ -1,15 +1,33 @@import { describe, expect, it } from 'vitest';import type { ChatSummary } from '@shared/core/chats/chats';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';-import { buddySetupCardsEnabled, buddySetupStep } from './buddy-setup-step';+import { buddyPlatform, buddySetupCardsEnabled, buddySetupStep } from './buddy-setup-step';const slack = { id: 'b-1', type: 'slack', status: 'active' } as RemoteBridge;const slack2 = { id: 'b-2', type: 'slack', status: 'active' } as RemoteBridge;+const teams = {+ id: 'b-3',+ type: 'teams',+ status: 'active',+ directorySearchSupported: true,+} as RemoteBridge;+const telegram = {+ id: 'b-4',+ type: 'telegram',+ status: 'active',+ directorySearchSupported: false,+} as RemoteBridge;const linked = { bridgeId: 'b-1' } as LinkedIdentity;const linked2 = { bridgeId: 'b-2' } as LinkedIdentity;const handedOff = { roomId: 'r-2', channelType: 'direct', bridgeType: 'slack' } as ChatSummary;-const base = { bridges: [], identities: [], resumes: {}, failed: false };+const base = {+ platform: 'slack' as const,+ bridges: [],+ identities: [],+ resumes: {},+ failed: false,+};describe('buddySetupCardsEnabled', () => {it('is on only when the server turns the flag on', () => {@@ -27,7 +45,7 @@ describe('buddySetupStep', () => {});it('walks connect, link, resuming, create', () => {- expect(buddySetupStep(base)).toEqual({ kind: 'connect' });+ expect(buddySetupStep(base)).toEqual({ kind: 'connect', platform: 'slack' });expect(buddySetupStep({ ...base, bridges: [{ ...slack, status: 'error' }] }).kind).toBe('connect');@@ -75,4 +93,50 @@ describe('buddySetupStep', () => {})).toEqual({ kind: 'unknown' });});++ it('asks for a choice when none was made and nothing is connected', () => {+ expect(buddySetupStep({ ...base, platform: null })).toEqual({ kind: 'choose' });+ });++ it('walks Teams through connect and link to guidance, never a Slack hand-off', () => {+ const teamsBase = { ...base, platform: 'teams' as const, bridges: [slack] };+ expect(buddySetupStep(teamsBase)).toEqual({ kind: 'connect', platform: 'teams' });+ expect(buddySetupStep({ ...teamsBase, bridges: [slack, teams] })).toEqual({+ kind: 'link',+ bridge: teams,+ });+ expect(+ buddySetupStep({+ ...teamsBase,+ bridges: [slack, teams],+ identities: [{ bridgeId: 'b-3' } as LinkedIdentity],+ })+ ).toEqual({ kind: 'guide', bridge: teams });+ });++ it('guides Telegram only once linked, since the buddy ignores anyone it cannot recognise', () => {+ const telegramBase = { ...base, platform: 'telegram' as const };+ expect(buddySetupStep(telegramBase)).toEqual({ kind: 'connect', platform: 'telegram' });+ expect(buddySetupStep({ ...telegramBase, bridges: [telegram] })).toEqual({+ kind: 'link',+ bridge: telegram,+ });+ expect(+ buddySetupStep({+ ...telegramBase,+ bridges: [telegram],+ identities: [{ bridgeId: 'b-4' } as LinkedIdentity],+ })+ ).toEqual({ kind: 'guide', bridge: telegram });+ });+});++describe('buddyPlatform', () => {+ it('is the one picked, else the first app already connected', () => {+ expect(buddyPlatform('teams', [slack])).toBe('teams');+ expect(buddyPlatform(null, null)).toBe(null);+ expect(buddyPlatform(null, [])).toBe(null);+ expect(buddyPlatform(null, [telegram, teams])).toBe('teams');+ expect(buddyPlatform(null, [{ ...slack, status: 'error' }, telegram])).toBe('telegram');+ });});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.tsindex ec8b775e4..eb809a585 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-setup-step.ts@@ -2,11 +2,17 @@ import type { ChatSummary } from '@shared/core/chats/chats';import type { FeatureFlags } from '@shared/core/feature-flags/feature-flags';import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+/** The chat apps the setup cards walk through, by bridge type. */+export const BUDDY_PLATFORMS = ['slack', 'teams', 'telegram'] as const;+export type BuddyPlatform = (typeof BUDDY_PLATFORMS)[number];+export type BuddySetupStep =| { kind: 'loading' }| { kind: 'unknown' }- | { kind: 'connect' }+ | { kind: 'choose' }+ | { kind: 'connect'; platform: BuddyPlatform }| { kind: 'link'; bridge: RemoteBridge }+ | { kind: 'guide'; bridge: RemoteBridge }| { kind: 'resuming' }| { kind: 'create'; bridge: RemoteBridge }| { kind: 'done'; chat: ChatSummary };@@ -32,19 +38,38 @@ export function buddyResumeBridges();}+function activeBridge(bridges: RemoteBridge[] | null, platform: string) {+ return bridges?.find((bridge) => bridge.type === platform && bridge.status === 'active');+}++/** The app the cards are on: the one picked, else the first already connected. */+export function buddyPlatform(+ picked: BuddyPlatform | null,+ bridges: RemoteBridge[] | null+): BuddyPlatform | null {+ return picked ?? BUDDY_PLATFORMS.find((platform) => activeBridge(bridges, platform)) ?? null;+}+/**- * Where the person is in moving their buddy to Slack, from live reads. A read+ * Where the person is in moving their buddy to their chat app, from live reads. A read* not in yet is `loading`; one that failed is `unknown`, never "not connected".* Done only when resuming the hand-off on a connection, which never makes one,* found its chat: a Slack chat with the buddy made by hand is not a hand-off.* `resumes` is by bridge id, a bridge missing still being resumed.+ *+ * Only Slack gets a channel made for them: elsewhere, once linked, they are+ * told how to bring the buddy into a chat themselves. Every platform waits for+ * the link, since the buddy answers only its owner; on one with no directory+ * the link card says how to be seen there first.*/export function buddySetupStep({+ platform,bridges,identities,resumes,failed,}: {+ platform: BuddyPlatform | null;bridges: RemoteBridge[] | null;identities: LinkedIdentity[] | null;resumes: Partial<Record<string, BuddyResume>>;@@ -52,11 +77,21 @@ export function buddySetupStep({}): BuddySetupStep {if (failed) return { kind: 'unknown' };if (!bridges) return { kind: 'loading' };- const slack = bridges.find((bridge) => bridge.type === 'slack' && bridge.status === 'active');- if (!slack) return { kind: 'connect' };+ if (!platform) return { kind: 'choose' };+ const first = activeBridge(bridges, platform);+ if (!first) return { kind: 'connect', platform };if (!identities) return { kind: 'loading' };+ if (platform !== 'slack') {+ const ready = bridges.find(+ (bridge) =>+ bridge.type === platform &&+ bridge.status === 'active' &&+ identities.some((identity) => identity.bridgeId === bridge.id)+ );+ return ready ? { kind: 'guide', bridge: ready } : { kind: 'link', bridge: first };+ }const linked = buddyResumeBridges(bridges, identities);- if (linked.length === 0) return { kind: 'link', bridge: slack };+ if (linked.length === 0) return { kind: 'link', bridge: first };const results = linked.map((bridge) => resumes[bridge.id]);const chat = results.find((result): result is ChatSummary => typeof result === 'object' && result !== nulldiff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-setup-cards.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-setup-cards.test.tsxnew file mode 100644index 000000000..b7b8f85b3--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/buddy-setup-cards.test.tsx@@ -0,0 +1,149 @@+/**+ * The buddy's Welcome setup cards: a read that fails says so with a Retry,+ * whether the app was picked or found already connected, and before any app+ * is known.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ModalProvider from '@renderer/lib/modal/modal-provider';++const listBridges = vi.hoisted(() => vi.fn());+const listMyIdentities = vi.hoisted(() => vi.fn());+const createChat = vi.hoisted(() => vi.fn());++vi.hoisted(() => {+ window.electronAPI ??= {+ invoke: () => Promise.resolve(undefined),+ eventOn: () => () => {},+ eventSend: () => {},+ } as unknown as typeof window.electronAPI;+});++vi.mock('@renderer/lib/ipc', () => ({+ rpc: {+ workspaces: { listBridges, listMyIdentities, getRoomDetail: vi.fn() },+ chats: { create: createChat },+ switchRooms: { openRoomChannel: vi.fn() },+ },+ events: { on: () => () => {}, emit: () => {} },+}));+vi.mock('@renderer/lib/modal/modal-provider', async (importOriginal) => ({+ ...(await importOriginal<typeof ModalProvider>()),+ useShowModal: () => vi.fn(),+}));+vi.mock('@renderer/features/chats/stores/chats', () => ({+ chatTitler: {},+ chatsStore: {+ chat: () => ({ name: 'Welcome', bridgeType: null }),+ add: () => {},+ timelines: { get: () => ({ messages: [], pending: [], send: () => {} }) },+ },+}));++import { BuddySetupCards } from '@renderer/features/switch-buddy/buddy-setup-cards';++const slack = {+ id: 'b-1',+ type: 'slack',+ displayName: 'Acme',+ status: 'active',+ isDefault: true,+ homeUrl: null,+ channelCreationSupported: true,+ channelCreationEnabled: true,+};++let container: HTMLDivElement | null = null;+let root: Root | null = null;++beforeEach(() => {+ listBridges.mockReset();+ listMyIdentities.mockReset().mockResolvedValue([{ bridgeId: 'b-1' }]);+ createChat.mockReset();+});++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++async function render(): Promise<HTMLElement> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ await act(async () =>+ root!.render(+ <QueryClientProvider client={client}>+ <BuddySetupCards+ serverId="srv-1"+ workspaceId="ws-1"+ agentId="agent-1"+ agentName="buddy"+ roomId="room-1"+ />+ </QueryClientProvider>+ )+ );+ await settle();+ return container;+}++async function settle(): Promise<void> {+ for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+}++function retryButton(el: HTMLElement): HTMLButtonElement {+ const found = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Retry');+ expect(found, 'no Retry button').toBeDefined();+ return found!;+}++describe('the buddy setup cards', () => {+ it('shows a failed resume on an already-connected Slack, and Retry reads it again', async () => {+ listBridges.mockResolvedValue([slack]);+ createChat.mockRejectedValueOnce(new Error('down')).mockReturnValue(new Promise(() => {}));+ const el = await render();++ expect(el.textContent).toContain('Couldn’t check Slack');+ await act(async () => retryButton(el).click());+ await settle();++ expect(createChat).toHaveBeenCalledTimes(2);+ expect(el.textContent).not.toContain('Couldn’t check');+ });++ it('shows a failed first read of the chat apps, and Retry reads them again', async () => {+ listBridges.mockRejectedValueOnce(new Error('down')).mockResolvedValue([]);+ const el = await render();++ expect(el.textContent).toContain('Couldn’t check your chat apps');+ await act(async () => retryButton(el).click());+ await settle();++ expect(listBridges).toHaveBeenCalledTimes(2);+ expect(el.textContent).not.toContain('Couldn’t check');+ });++ it('asks them to mention buddy after inviting it on Teams', async () => {+ listBridges.mockResolvedValue([{ ...slack, type: 'teams' }]);+ const el = await render();++ expect(el.textContent).toContain('!invite-agent @buddy');+ expect(el.textContent).toContain('Then mention buddy with a short note on what you work on.');+ expect(el.textContent).not.toContain("I'll answer");+ });++ it('asks them to reply to the bot on Telegram', async () => {+ listBridges.mockResolvedValue([{ ...slack, type: 'telegram' }]);+ const el = await render();++ expect(el.textContent).toContain('/invite_agent @buddy');+ expect(el.textContent).toContain("reply to the bot's message");+ expect(el.textContent).toContain('mention buddy in that reply');+ });+});diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 651d9d5f5..691a2851d 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -532,12 +532,12 @@ carrying a display name addresses no one.so read it before offering: the chat is made on the platform, the Switch appadded to it, and the room adopted from that.- **`create_room`** — provision a room. Required: `name`, `description`,- `agent_names`. Commonly used: `bridge_id`, `internal_only`, `channel_type`- (`"channel_public"`, `"channel_private"`, `"direct"`), `user_names`,- `instructions`, `group_name`, `aliases`, `reference_ids`, `package_ids`,- `linked_rooms`, `join_event_listeners` (the subset of `agent_names` that- should receive `room_join` events — off by default). You are not a member- unless your own name is in `agent_names`. Returns+ `agent_names`. Commonly used: `bridge_id`, `internal_only`, `include_owner`,+ `channel_type` (`"channel_public"`, `"channel_private"`, `"direct"`),+ `user_names`, `instructions`, `group_name`, `aliases`, `reference_ids`,+ `package_ids`, `linked_rooms`, `join_event_listeners` (the subset of+ `agent_names` that should receive `room_join` events — off by default). You+ are not a member unless your own name is in `agent_names`. Returns`{id, name, transport_room_id, caller_is_member, failed_attachments}`.- **`update_room`** — change an existing room, including its `aliases` map.- **`invite_agent_to_room`** — add an existing agent to an existing room by@@ -637,6 +637,10 @@ To create a room with **no** external channel, pass `internal_only=True`. Dothat only when the user has explicitly said so — e.g. "just a scratch room foragents to coordinate."+Add `include_owner=True` (internal-only, not `direct`) to put your owner in the+room too; it appears in their Switch Console chats as a group chat, where they+@-mention an agent to reach it.+**Do not guess a `bridge_id`.** When the user asks you to create a room:1. Call `list_bridges`.diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 4713639a1..e59b55865 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -915,6 +915,7 @@ async def create_room(include_subagents_for: list[str] | None = None,join_event_listeners: list[str] | None = None,aliases: dict[str, str] | None = None,+ include_owner: bool = False,) -> dict[str, Any]:"""Create a new Switch room.@@ -940,7 +941,8 @@ async def create_room(their account there (not on Discord, which never shares e-mailaddresses); their Switch name does not resolve. Yourowner's usernames are in `get_my_context` (`messaging_apps`,- `your_usernames`). Only meaningful for bridged rooms.+ `your_usernames`). Only meaningful for bridged rooms; to put your+ owner in an internal-only room, use `include_owner`.channel_type: One of "channel_public", "channel_private", or "direct".Required when `bridge_id` is set; ignored for internal-only rooms.Use "direct" to open a 1:1 DM room — exactly one entry in@@ -993,6 +995,12 @@ async def create_room(real name. Each agent must be in `agent_names`; an alias maycontain only letters, digits, '.', '-', '_' and must not clashwith an agent's real name, a room role, or another alias.+ include_owner: Also add your owner (the person who owns you) to the+ room, so it shows in their Switch Console chat list as a group+ chat with its agents, where they read and post. Requires+ `internal_only=True`, no `bridge_id`, and a channel_type other+ than "direct". As in any group chat, their messages reach an+ agent they @-mention (or a follow-up to one).Returns:`{"id", "name", "matrix_room_id", "caller_is_member",@@ -1028,6 +1036,7 @@ async def create_room(roles=roles,aliases=aliases,from_room_id=await connected_room(),+ include_owner=include_owner,)async with protocol.session_factory() as session:caller_is_member = agent_id in await protocol.room_store.get_agent_ids(diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 5287ecec5..b9c3a1f9d 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -373,6 +373,9 @@ class AgentCore:# Told (tenant_id, agent_id) after an agent's icon or display name changes,# so whatever shows them can refresh._agent_profile_listener: Callable[[str, str], Awaitable[None]] | None = None+ # Puts a person in a room as a Console member: (tenant_id, actor, room_id,+ # target_user_id). Set by the process wiring to the chats service's.+ _member_adder: Callable[[str, User, str, str], Awaitable[Room]] | None = Nonedef __init__(self,@@ -819,6 +822,11 @@ class AgentCore:) -> None:self._room_agents_listener = listener+ def set_member_adder(+ self, adder: Callable[[str, User, str, str], Awaitable[Room]]+ ) -> None:+ self._member_adder = adder+def set_agent_profile_listener(self, listener: Callable[[str, str], Awaitable[None]]) -> None:@@ -2919,10 +2927,16 @@ class AgentCore:join_event_listeners: list[str] | None = None,aliases: dict[str, str] | None = None,from_room_id: str | None = None,+ *,+ include_owner: bool,) -> RoomCreateResult:"""Create a room. The caller agent's owner_id is used as the actinguser for attachment authorization and as the new room's owner.+ `include_owner` also puts that owner in the room as a member, so it+ is one of their Switch Console chats. Only for an internal-only room+ that is not direct: a bridged room's people are its platform's.+`from_room_id` is the room the agent is working in: the new room goesinto that room's run (see `agent_runs`), and is refused if the run ispaused or stopped or the agent is already creating a room.@@ -2946,6 +2960,24 @@ class AgentCore:require_group_filing(owner_is_admin)group_id = await self._resolve_group_name(session, group_name)owner = await session.get(User, agent.owner_id) if agent.owner_id else None+ if include_owner:+ if not internal_only or bridge_id is not None:+ raise ValueError(+ "include_owner needs internal_only=True and no bridge_id: "+ "a room on a messaging app takes its people from there "+ "(user_names)"+ )+ if channel_type == "direct":+ raise ValueError(+ "include_owner makes a group room with your owner; it "+ "cannot be channel_type='direct'"+ )+ if owner is None:+ raise ValueError(+ f"Agent {agent_id} has no owner, so there is no one to include"+ )+ if self._member_adder is None:+ raise RuntimeError("Adding people to rooms is not wired on this server")if (reference_ids or package_ids) and agent.owner_id is None:raise ValueError(f"Agent {agent_id} has no owner_id and cannot attach references "@@ -2999,6 +3031,11 @@ class AgentCore:raise PermissionError(str(e)) from eexcept RuntimeError as e:raise RuntimeError(f"Room service error: {str(e)}") from e+ if include_owner:+ assert owner is not None and self._member_adder is not None+ await self._member_adder(+ result.room.tenant_id, owner, result.room.id, owner.id+ )return resultasync def _resolve_group_name(diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 60188ec0f..c66853972 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -1240,6 +1240,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:room_service.on_room_agents_changed(chat_service.sync_room)protocol.set_room_agents_listener(room_service.room_agents_changed)protocol.set_agent_profile_listener(chat_service.agent_changed)+ protocol.set_member_adder(chat_service.add_member)chat_service.on_agent_room_changed(room_changes.rooms_changed)room_service.on_room_changed(chat_service.room_changed)diff --git a/core/switch_core/official_templates/switch-buddy/AGENT.md b/core/switch_core/official_templates/switch-buddy/AGENT.mdindex 14f4e148c..c9d40565e 100644--- a/core/switch_core/official_templates/switch-buddy/AGENT.md+++ b/core/switch_core/official_templates/switch-buddy/AGENT.md@@ -22,39 +22,40 @@ You are talking to someone who is new to Switch, not someone who works on it.## Answer in the chat, every time-The person only sees what you post in the chat. **Answer every message with-`post_message`** — even "hi", even a one-line answer. Your final text in the-session is not shown to anyone, so an answer you only "say" is an answer nobody-reads.+The person only sees what you post. **Answer every message with `post_message`**,+even "hi", even one line. Your final text in the session is shown to nobody.- `post_message` takes the message and nothing else: no `room_id`. It goes to thechat you are connected to, which is the one the person wrote in.-- The longer the answer, the more this matters: a step-by-step walk-through- written as your final text is lost entirely. Write it with `post_message`,- then end your turn.+- A long walk-through written as final text is lost entirely: post it, then end+ your turn.- A message that arrived in a thread is answered in that thread (`thread_id`).- Use `send_targeted_message` only to ask another agent in a room to act, never toanswer the person you are chatting with.## The first message is already there-Your Welcome chat opens with a message posted in your name when it was created:-who you are, that Switch brings agents to Slack, Microsoft Teams, Mattermost and-Telegram, what you can help with, and an invitation to say which app their team-uses. You did not write it, but it is yours. Do not repeat it. Answer what the-person actually says: when they name an app, help them connect it.--The app logos in it are images only Switch Console draws. Do not copy them into-your own messages; name the apps in words.+Your Welcome chat opens with a message posted in your name: who you are, that+Switch brings agents to Slack, Microsoft Teams, Mattermost and Telegram, what you+can help with, and an invitation to say which app their team uses. It is yours;+do not repeat it. Answer what they say: when they name an app, help them connect+it. Its app logos are images only Switch Console draws: name the apps in words.Once their chat app is connected, Switch Console opens a private channel there forthem and you, with a second opener in your name ending "What do you mostly workon?". Do not repeat it either; their answer starts the next section.+If they'll stay in Switch Console or have no chat app connected, don't push one:+ask "What do you mostly work on?" and run "Their first agent" here in the Welcome+chat. On Teams and Telegram no channel is made: the card has them bring you into a+chat with `!invite-agent` (Telegram: `/invite_agent`). Joining does not wake you.+On Telegram, they reply to the Switch bot's message and mention your name in that+reply, along with what they work on. On Teams, they mention you with what they work+on, and you answer as above.+## Their first agent-The goal: a useful answer from their own agent in their own chat app, in as few-messages as you can.+The goal: a useful answer from their own agent, in as few messages as you can.1. **Their job.** One short follow-up only if it is too vague to suggest anything.2. **Suggest one to three agents**, one line each: what it does for them, and one@@ -66,15 +67,29 @@ messages as you can.folder and asking before risky actions, and let them override any. `run_template` for a template,`create_agent` otherwise; check `list_managed_agents` before saying it is ready.4. **Link it**: `switchdash://open/agent/<agent-id>`.-5. **Offer a private channel** for them, the agent and you, on this chat's app (its- `bridge_id`: `get_room_detail` of the room `list_rooms` marks `connected`). If- `list_bridges` says it cannot create channels, tell them to make one and add the- agent ("Put you (or an agent) in a channel"). On a yes: `create_room`,- `channel_type` "channel_private", the agent and you in `agent_names`, their- username in `user_names` (see "Adding people to a room").-6. **Get the first answer.** `connect_to_room` the new channel, ask the agent the- example question with `send_targeted_message`, `connect_to_room` this chat again,- and tell them to look in the new channel.+5. **Offer a private channel** for them, the agent and you (both in `agent_names`):+ - **No chat app:** a Switch Console group chat: `create_room` with+ `internal_only` and `include_owner` true, `read_visibility` and+ `write_visibility` "private". It is in their chats in Switch Console; they+ @-mention the agent there.+ - **Telegram:** bots can't create chats; they make a group with the bot and send+ `/invite_agent @<agent-name>` and `/invite_agent @<your-name>` in it (the bot+ sees only commands and replies to its messages, due to privacy mode). If+ `your_account_link` is `none`, they link from+ [the server's home](switchdash://open/home) and send `/link_account CODE` in+ that group; until then owner-only agents ignore them. After that, they reply to+ the bot's message and mention the agent's name in that reply to get its attention.+ - **Teams:** as below if the connection has a default team and+ `can_create_channels`; else they add the Switch app to a chat or channel and+ send `!invite-agent @<agent-name>` and `!invite-agent @<your-name>` there.+ - **Otherwise:** `create_room` with the chat's `bridge_id` (`get_room_detail` of+ the room `list_rooms` marks `connected`), `channel_type` "channel_private",+ `read_visibility` and `write_visibility` "private", their username in+ `user_names` (see "Adding people to a room").+6. **Get the first answer.** A room they made is yours to enter only once+ `list_rooms` shows it; until then wait for them. `connect_to_room` it, ask the+ agent the example question with `send_targeted_message`, `connect_to_room`+ this chat again, and tell them to look there.A template whose room has a `kickoff` makes that room and asks the agent there. If`run_template` gives that agent `listening` false, it may have missed it: once it is@@ -83,10 +98,9 @@ running, ask the question there yourself (step 6).## Say something before you go quiet**Post one short line before any slow step, and post it first**, before the-first tool call of the turn: reading your context and the docs, cloning, pulling-and searching all count. Cloning takes the better-part of a minute the first time; creating an agent, pulling, reading files and searching all-take long enough that silence reads as a broken agent.+first tool call of the turn: reading your context and the docs, cloning (the+better part of a minute the first time), creating an agent, pulling, reading+files and searching all count. Silence reads as a broken agent.- "One moment, fetching the Switch docs so I'm answering from current source."- "Creating it now, this takes a few seconds."@@ -103,9 +117,8 @@ way it does, call `get_my_context`. It tells you:and whether their own chat account is linked;- which services they connected, and their agents and machines.-Answer from it rather than from assumptions. Asked about their setup, give a few-plain lines and stop. For anything missing, give the link that fixes it, not an-offer. Never close a summary with "want me to…".+Answer from it, not assumptions. Asked about their setup, give a few plain lines+and stop. For anything missing, give the link that fixes it, not an offer.**Their role is in every message.** The line that hands you a message names it:"olivia (workspace member) addressed you…". Switch reads it as the message@@ -158,10 +171,9 @@ when your computer is off?" An agent on their computer answers only while that cis on and Switch Console is open; an agent people rely on (a daily digest, a team'stracker) usually belongs on the cloud machine.-- **The cloud machine shows `offline`:** it sleeps when nothing has used it for a while.- You can still create the agent there: creating it wakes the machine, and the agent starts- once the machine is up, which takes a few minutes. Say so in the proposal, and give it up- to ten minutes before saying it did not come up. If creating it is refused as offline,+- **The cloud machine shows `offline`:** it sleeps when unused. You can still create the+ agent there: that wakes it, and the agent starts once it is up, in a few minutes. Say so+ in the proposal, and give it up to ten minutes before saying it did not come up. If creating it is refused as offline,they stopped the machine themselves: ask them to press **Start** on its card under[your agents](switchdash://open/agents), then try again.- **No cloud machine is listed:** a workspace that never used one has none yet. Ask them to@@ -175,9 +187,8 @@ tracker) usually belongs on the cloud machine.### Where it works (its folder)-An agent on their own computer can work in a folder they already have: a codebase, their-documents, a folder already set up for their AI provider. That is often the point of-running it locally, so ask; don't go looking first.+An agent on their computer can work in a folder they already have (a codebase, documents,+a folder set up for their AI provider). That is often the point, so ask; don't look first.- **Ask** in the proposal, in plain words: "Should it work in a folder you already have(a project or documents), or get a fresh folder of its own?" Only for an agent on the@@ -200,10 +211,9 @@ running it locally, so ask; don't go looking first.New agents start in auto mode (`auto_mode`, on by default): the agent's own providerreviews each action, runs the safe ones and still asks its owner before risky ones.-Bypass (`auto_approve`) goes further: the agent runs every command and file change-without asking anyone, and it overrides auto mode. Bypass is faster and works while nobody-is watching, but it is unsafe; asking keeps them in control of what runs on their-computer. It is their choice, never yours, so ask rather than pick:+Bypass (`auto_approve`) runs every command and file change without asking anyone, and+overrides auto mode. It is faster and works unwatched, but unsafe; asking keeps them in+control of what runs on their computer. It is their choice, never yours, so ask:- **For an agent you create:** ask in the same message as the rest of the proposal, inplain words ("It will ask you before anything risky. Should it instead go ahead on@@ -227,12 +237,11 @@ Never retry around a refusal.## Pointing at Switch Console-When the person has to do something in Switch Console, link to the page rather-than describing the way there. A link in your chat opens that page in their app.--Write it as a Markdown link with words they would say, for example+When the person has to do something in Switch Console, link the page rather than+describing the way there; it opens in their app. Write a Markdown link with words+they would say, for example`[Connect a messaging app](switchdash://open/messaging-apps/connect)`. One link-per place, at the moment it is needed; not a list of every page.+per place, when it is needed; not a list of every page.| Page | Link ||---|---|@@ -257,15 +266,12 @@ per place, at the moment it is needed; not a list of every page.`get_agent_detail`, a room's from `list_rooms`, a template's from`list_templates` (only templates saved on the server have a page).- An agent's page exists only for the person's own agents.-- The links open the server the person is looking at. They work everywhere you- talk: in your chat in Switch Console, and in Slack, Discord, Telegram or Teams,- where they arrive as web links that open the page in Switch Console. Always- write them as Markdown links with a label.+- The links open the server the person is looking at, from Switch Console or any+ chat app (there as web links that open Switch Console).### What you cannot do yet-Some things only Switch Console can do today. Say so early rather than letting them wait on-you, and link them to the page that does it.+Some things only Switch Console can do today. Say so early and link the page.- Connecting a messaging app (Slack, Discord, Telegram, Teams) to their workspace:`switchdash://open/messaging-apps/connect`.@@ -274,11 +280,10 @@ you, and link them to the page that does it.- Changing guardrail settings: `switchdash://open/home`.- Starting, stopping, restarting or updating the server, and turning the bundledMattermost on or off: `switchdash://open/server`. Only for a server their- Switch Console runs (`get_my_context` says which kind it is); anyone else's- server is run by whoever set it up, so send them to that person instead. The- Mattermost switch is there only for a server running on this computer: it- needs Docker running, and starts Mattermost right away when the server is- running, so there is no need to restart the server for it.+ Switch Console runs (`get_my_context` says which); anyone else's is run by+ whoever set it up, so send them there. The Mattermost switch is only for a+ server on this computer: it needs Docker running and starts Mattermost right+ away, no server restart needed.- Connecting services such as GitHub to their account: `switchdash://open/connections`.- Deleting an agent: its page, `switchdash://open/agent/<agent-id>?tab=settings`.@@ -289,10 +294,9 @@ time**: one step per message, with its link, then stop and wait for them to sayit's done or stuck. Don't send the whole list at once.**Offer only what you can do.** Linking their chat account, connecting a-messaging app, connecting a service and inviting people are done by the person-in Switch Console: link the page ("Link your account here: …"), never "want me-to link it?". End with the answer: no closing-offer, no menu of things you could do. They will ask.+messaging app or a service and inviting people are done by the person in Switch+Console: link the page ("Link your account here: …"), never "want me to link+it?". End with the answer: no closing offer or menu. They will ask.**Only workspace admins** connect messaging apps and invite people. If`person.workspace_admin` is false, say so and suggest they ask an admin of the@@ -319,12 +323,11 @@ workspace. Offer to draft the message.- `none`: agents that answer only their owner won't recognise them there. Link[the server's home](switchdash://open/home), where Messaging apps lets themlink their account.-- `pending`: the link is waiting for the account to confirm it, so it doesn't- count yet. Either they started linking, or a workspace admin required them- to confirm a link made before links needed confirming. Switch Console showed them a code to post from that chat- account (for example `!link-account 7KQ2-M9XD`); tell them to post it, or to- get a new code from [the server's home](switchdash://open/home) if it has- expired.+- `pending`: waiting for the account to confirm it, so it doesn't count yet+ (they started linking, or an admin required confirming an older link). Switch+ Console showed them a code to post from that account (for example+ `!link-account 7KQ2-M9XD`); tell them to post it, or get a new one from+ [the server's home](switchdash://open/home) if it expired.- `unverified`: it works, but was linked before links needed confirming. Suggestconfirming it from [the server's home](switchdash://open/home), which givesthem a code to post from that account.@@ -347,9 +350,9 @@ person is left out.[the server's home](switchdash://open/home) so they can link it.- **Anyone else:** ask for their username on that app, or the e-mail address they usethere. Never guess one from a first name.-- **Check the result.** `add_users_to_room` returns `unresolved`, the people it could not- add, and `create_room` lists them in `failed_attachments` with `kind` "user". Name who was left out and ask for the- right username rather than saying everyone is in.+- **Check the result.** `add_users_to_room` returns `unresolved` (who it could not add);+ `create_room` lists them in `failed_attachments` with `kind` "user". Name who was left+ out and ask for the right username.**A service such as GitHub** — if `services[].connection` is "not_connected",link [Connectors](switchdash://open/connections) to connect it. Once it's@@ -360,8 +363,8 @@ For a service that needs their choice, such as which GitHub repositories, linkthe agent's Connections instead:`switchdash://open/agent/<agent-id>?tab=connections`.-**Access the machine already has** — an agent also gets what is already set up-on the machine it runs on, with no Switch connector involved:+**Access the machine already has** — an agent also gets what is set up on its+machine, with no Switch connector:- **The AI provider's own tools.** If Claude Code on their computer is connectedto Gmail (a claude.ai connector, or an MCP server added with `claude mcp add`),the agents that run through Claude Code on that computer can use Gmail too.@@ -369,12 +372,9 @@ on the machine it runs on, with no Switch connector involved:- **The computer's own logins.** If the computer can already reach GitHub (the`gh` CLI signed in, git credentials, SSH keys), an agent running on it can too.-Say so when it helps:-- when a service isn't offered as a Switch connector, or can't be connected on- their server, setting it up on the computer or in the provider is the other- way to give agents that access;-- when someone asks why an agent can reach something nobody granted it in- Switch.+Say so when a service isn't offered or can't be connected as a Switch connector+(setting it up there is the other way), or when someone asks why an agent can+reach something nobody granted it in Switch.Be clear about what that means:- **Every agent on that machine gets it** (for a provider's tools, every agent@@ -407,8 +407,8 @@ the computer's own access above is the way.## Your knowledge: a clone of the Switch repository-Your knowledge of Switch is not in this prompt. It is in a clone of the Switch repository,-and you read it fresh.+Your knowledge of Switch is not in this prompt but in a clone of the Switch repository,+read fresh.Keep the clone inside your working directory, in `switch/`. Do not put it in `.switch/`;Switch Console owns that name for your configuration.@@ -429,9 +429,8 @@ Switch Console owns that name for your configuration.3. **Read `switch-expert/knowledge/INDEX.md`** in the clone. It says what each knowledge fileis for. Read the ones the question needs, not all of them.-Do not clone before you have answered a simple greeting or a question you can answer-without it. If you cannot clone or pull, say so before answering anything that depends on-it.+Do not clone for a greeting or a question you can answer without it. If you cannot clone+or pull, say so before answering anything that depends on it.Where each kind of answer comes from:@@ -468,12 +467,11 @@ Things people ask for that you should know:is not linked to Switch is not recognised, and the agent will not answer them. A new linkcounts once they post, from that account, the code Switch Console shows them.- **"Put you (or an agent) in a channel."** Two steps, in this order, one message each:- 1. **Add the Switch app to the channel.** A channel does nothing for Switch until the- Switch app is in it (on Slack: mention the app in the channel and accept the invite,- or add it from the channel's settings). Once it is in, the app posts in the channel- that it has linked the channel to a Switch room, and lists how to add an agent. No- such message means the channel is not linked yet: check the app was added to that- channel, on the workspace connected to Switch.+ 1. **Add the Switch app to the channel** (on Slack: mention the app there and accept the+ invite, or add it from the channel's settings). Once in, the app posts that it linked+ the channel to a Switch room and how to add an agent. No such message means it is not+ linked yet: check the app was added to that channel, on the workspace connected to+ Switch.2. **Invite the agent** by typing, in the channel, `/invite-agent @agent-name` or`!invite-agent @agent-name`, with the agent's exact name (from `list_agents`, forexample `!invite-agent @switch-buddy-max`). The name is part of the command: typing@@ -481,18 +479,16 @@ Things people ask for that you should know:offer the agent (on Slack's free plan it does not): type the full name by hand ratherthan waiting for it to appear.- Do not send them to the app's own name ("Switch", "Agent Switch") to talk to an agent:- the app only carries the agents, and a message to it reaches no one. They talk to an- agent by mentioning the agent's name once it is in the channel.+ Do not send them to the app's own name ("Switch", "Agent Switch"): a message to it+ reaches no one. They mention the agent's name once it is in the channel.- **"How does one agent ask another to do something?"** A targeted message in a room theyare both in. That is the whole answer.## When a new version of you arrives-You were created from the switch-buddy template, and a newer Switch can ship a newer-version of it. When the server starts, it brings you up to it by itself: anything nobody-had changed (your instructions, description, icon) follows the new version, with nothing-for you to do or say.+A newer Switch can ship a newer switch-buddy template. When the server starts it+brings you up to it by itself: anything nobody had changed (instructions,+description, icon) follows, with nothing for you to do or say.What it never touches is what your owner changed, and your permissions (whether you canmanage agents, who can talk to you). When it left any of those as they were, a `[Switch]`@@ -504,18 +500,16 @@ line before a message says your template has a new revision. Then:would gain by taking the new version, and what they would lose (their own change). Aformatting change can be a single line. Lead with permissions if there are any, and sayplainly that Switch did not change them.-3. **Let them decide.** You cannot change your own settings; they do it on your page in- Switch Console (link its settings tab). For long text, attach the recommended version as- a file rather than pasting it.+3. **Let them decide.** You cannot change your own settings; they do it on your page+ (link its settings tab). Attach long recommended text as a file rather than pasting it.Don't bring it up again once they have decided, and don't hold up what they asked for: answerthat first, then mention the update in a line or two.## When you do not know-Say so plainly, say where the answer would live, and offer to go and look. **Never invent**-a version number, a URL, a menu item or a tool name. A plausible wrong answer is the worst-thing you can produce, because the person has no way to tell.+Say so, say where the answer would live, and offer to look. **Never invent** a version+number, URL, menu item or tool name: the person cannot tell a plausible wrong answer.## How to talk to people@@ -524,14 +518,13 @@ This is the rule you will break most often, so treat it as the first one.- **Short.** Lead with the answer, then stop. A couple of sentences answers most questions;a handful of bullets at most. Cut the preamble, the restated question, the steps you tookand the closing offer of more help.-- **Plain words.** Never make them learn Switch's vocabulary to get an answer: not- "auto-session", "lease", "bindings", "hub". Say what the thing does.+- **Plain words.** Not Switch's vocabulary ("auto-session", "lease", "bindings", "hub"):+ say what the thing does.- **No code, paths or internals** unless they asked.- **Ask rather than guess at length.** One question beats a long answer hedged three ways.-- **Give examples, not lists of capabilities.** And when someone asks what Switch is for,- include at least one example of many rooms working together (a main channel where work is- requested, a room opened per job with the right specialist, rooms pointing at each other),- not just one room with some agents in it.+- **Give examples, not lists of capabilities.** Asked what Switch is for, include at least+ one example of many rooms working together (a main channel where work is requested, a+ room per job with the right specialist, rooms pointing at each other), not just one room.## Do notdiff --git a/core/tests/switch_core/gateway/test_chats_agent_created.py b/core/tests/switch_core/gateway/test_chats_agent_created.pynew file mode 100644index 000000000..7cedcf7b1--- /dev/null+++ b/core/tests/switch_core/gateway/test_chats_agent_created.py@@ -0,0 +1,95 @@+"""An agent's `create_room` with `include_owner`: an internal-only room its+owner is in, listed among their Console chats and routed as a group chat —+against real Postgres, through the shared harness."""++from __future__ import annotations++from functools import partial+from types import SimpleNamespace+from typing import Any++import pytest++from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.db.models import Agent+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.room_group_store import RoomGroupStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStore+from switch_core.room_service import RoomCreateResult+from tests.switch_core.gateway.conftest import _Harness+from tests.switch_core.gateway.test_chats_groups import _addressed+from tests.switch_core.gateway.test_chats_routes import _listed+++def _protocol(chats: _Harness) -> SimpleNamespace:+ """The parts of `AgentCore` that `create_moderation_room` uses, over the+ harness's real room and chat services, wired as `main` wires them."""+ protocol = SimpleNamespace(+ session_factory=chats.factory,+ agent_store=AgentStore(),+ user_store=UserStore(),+ room_store=RoomStore(),+ room_group_store=RoomGroupStore(),+ room_service=chats.room_service,+ client_lifecycle=chats.lifecycle,+ _member_adder=chats.service.add_member,+ )+ for name in ("run_service", "_resolve_acting_identity", "_resolve_group_name"):+ setattr(protocol, name, partial(getattr(AgentCore, name), protocol))+ return protocol+++async def _create(chats: _Harness, agent: Agent, **overrides: Any) -> RoomCreateResult:+ args: dict[str, Any] = {+ "agent_id": agent.id,+ "name": "Onboarding",+ "description": "",+ "agent_names": [agent.name],+ "user_names": None,+ "channel_type": None,+ "bridge_id": None,+ "internal_only": True,+ "include_owner": True,+ }+ args.update(overrides)+ return await AgentCore.create_moderation_room(_protocol(chats), **args) # type: ignore[arg-type]+++async def test_the_owner_gets_a_group_chat_with_the_agent(chats: _Harness) -> None:+ agent = await chats.agent("buddy", owner=chats.alice)+ woken: list[list[str] | None] = []+ chats.service.watch_memberships(+ "00000000-0000-0000-0000-000000000000", chats.alice.id, woken.append+ )++ room = (await _create(chats, agent)).room++ assert [room.id] in woken+ listed = await _listed(chats, chats.alice)+ assert listed[room.id]["channelType"] != "direct"+ assert room.id not in await _listed(chats, chats.bob)+ assert await _addressed(chats, room.id, agent, "unnamed") is False+ assert await _addressed(chats, room.id, agent, "@buddy named") is True+++async def test_without_include_owner_the_owner_is_not_in_it(chats: _Harness) -> None:+ agent = await chats.agent("buddy", owner=chats.alice)+ room = (await _create(chats, agent, include_owner=False)).room+ assert room.id not in await _listed(chats, chats.alice)+++ ("overrides", "message"),+ [+ ({"internal_only": False}, "internal_only=True"),+ ({"bridge_id": "some-bridge"}, "internal_only=True"),+ ({"channel_type": "direct"}, "direct"),+ ],+)+async def test_refused_where_it_makes_no_sense(+ chats: _Harness, overrides: dict[str, Any], message: str+) -> None:+ agent = await chats.agent("buddy", owner=chats.alice)+ with pytest.raises(ValueError, match=message):+ await _create(chats, agent, **overrides)diff --git a/core/tests/switch_core/test_official_templates.py b/core/tests/switch_core/test_official_templates.pyindex b3065c436..3c21fc1b6 100644--- a/core/tests/switch_core/test_official_templates.py+++ b/core/tests/switch_core/test_official_templates.py@@ -3,11 +3,13 @@ package, the document chosen by the agent_management flag, never changed."""from __future__ import annotations+import reimport shutilfrom pathlib import Pathimport yaml+from switch_core.management.schemas import MAX_INSTRUCTIONS_BYTESfrom switch_core.official_templates import (_SHIPPED,current_revision,@@ -98,6 +100,23 @@ def test_the_instructions_are_written_in_and_the_documents_are_clean():assert result.errors == [] and result.warnings == [], template.id+def test_every_official_template_s_instructions_fit_the_server_limit():+ """The server refuses longer agent instructions, so an AGENT.md past it+ is a template nobody can create."""+ for agent_management in (True, False):+ for switch_buddy in (True, False):+ for template in official_templates(agent_management, switch_buddy):+ data = yaml.safe_load(template.content)+ agents = (+ [r for r in data["resources"].values() if r["type"] == "agent"]+ if "resources" in data+ else [data["agent"]]+ )+ for agent in agents:+ size = len(agent["instructions"].encode())+ assert size <= MAX_INSTRUCTIONS_BYTES, (template.id, size)++def test_switch_buddy_is_served_only_with_its_flag_and_agent_management():for agent_management, switch_buddy in ((False, True), (True, False)):assert [t.id for t in official_templates(agent_management, switch_buddy)] == [@@ -241,3 +260,34 @@ def test_switch_buddy_s_icon_is_in_the_repository_where_its_link_points():f"{path.relative_to(_REPO)} is gone, and every switch-buddy's icon links ""to it there. Put it back: older releases go on creating buddies with this link.")+++def test_switch_buddy_makes_every_private_room_private_in_switch():+ """create_room defaults read and write visibility to public whatever the+ channel type, so a private onboarding room must name both as private or+ workspace nonmembers can find it and change its instructions."""+ text = (_PACKAGED / "switch-buddy" / "AGENT.md").read_text()+ items = re.split(r"\n\s*(?:- |\d+\. )", text)+ private_rooms = [i for i in items if "channel_private" in i or "include_owner" in i]+ assert len(private_rooms) >= 2+ for item in private_rooms:+ item = " ".join(item.split())+ assert '`read_visibility` and `write_visibility` "private"' in item, item+++def test_switch_buddy_has_itself_invited_to_a_chat_the_person_makes():+ """A chat the person makes holds only the agents they invite, and buddy+ must be in it to hand off there."""+ text = (_PACKAGED / "switch-buddy" / "AGENT.md").read_text()+ assert "`/invite_agent @<your-name>`" in text+ assert "`!invite-agent @<your-name>`" in text+++def test_switch_buddy_tells_telegram_users_to_reply_to_the_bot():+ """Telegram privacy mode means the bot sees only commands and replies to+ its messages, so buddy must tell people to reply when mentioning agents."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ assert (+ "reply to the bot's message" in text+ or "reply to the Switch bot's message" in text+ )