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): Discord hand-off, question forms, an on-demand playbook, and failure and retry acceptance tests
raullopez-sandboxf0c1da5c6bf8
diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.ymlindex 121ec5969..f43b49bf9 100644--- a/.github/workflows/pr-ci.yml+++ b/.github/workflows/pr-ci.yml@@ -312,6 +312,14 @@ jobs:if: ${{ !cancelled() && (needs.changes.outputs.local_server_bundle == 'true' || github.event_name == 'workflow_dispatch') }}run: node apps/switch-console-desktop/scripts/build-gateway-ui.mjs ../gateway "$RUNNER_TEMP/gateway-ui"+ - name: Upload buddy onboarding screenshots+ if: ${{ !cancelled() }}+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2+ with:+ name: buddy-onboarding-screenshots+ path: console/apps/switch-console-desktop/build/acceptance/buddy-onboarding/+ if-no-files-found: warn+# The agent runner and the controller on native Windows (CHOO-3472): process# control, CLI lookup and permissions there take different code paths, and# their tests that start real processes only run on Windows. Scoped to thediff --git a/console/.gitignore b/console/.gitignoreindex 816b9bcc2..819e6b209 100644--- a/console/.gitignore+++ b/console/.gitignore@@ -18,6 +18,8 @@ apps/*/dist-local-server/# Re-include Electron packaging/signing assets. The monorepo root .gitignore# globally ignores build/, which would otherwise drop these tracked files.!apps/*/build/+# Screenshots the browser acceptance tests save.+apps/*/build/acceptance/# Re-include the app's TypeScript `lib/` source trees. The monorepo root# .gitignore is Python-oriented and globally ignores `lib/` (Python packaging),diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.tsindex cb6685665..c51965453 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/activity-join.ts@@ -117,6 +117,52 @@ function firstStepAt(turn: TurnActivity): number | null {);}+/** One of the agent's own messages in the room, not a host notice or a control acknowledgement. */+function isAgentReply(message: ChatMessage, agentId: string): boolean {+ return (+ message.sender.kind === 'agent' &&+ message.sender.agentId === agentId &&+ !isSessionStartingNotice(message) &&+ !turnEndNotice(message) &&+ !isControlAck(message)+ );+}++/**+ * Where a turn's requests show, by the message each shows under: after the+ * agent's messages of that turn sent before the request settled, so the text+ * leading up to a question reads above it. An open request shows after the+ * turn's latest message so far. `anchorId` is where the turn itself shows.+ * Shortcut: Switch keeps no time a request was asked, so a settled one is placed+ * by when it was answered (or expired); store an asked-at time if that misplaces one.+ */+export function placeRequests(+ messages: readonly ChatMessage[],+ agentId: string,+ bound: ReadonlyMap<string, TurnActivity>,+ anchorId: string,+ turn: TurnActivity+): Map<string, ChatApproval[]> {+ const placed = new Map<string, ChatApproval[]>();+ const start = messages.findIndex((each) => each.messageId === anchorId);+ if (start === -1) return placed;+ for (const request of turn.requests) {+ const settledAt = request.answeredAt ?? (request.state === 'open' ? null : request.expiresAt);+ const until = settledAt === null ? Infinity : Date.parse(settledAt);+ let anchor = start;+ for (let next = start + 1; next < messages.length; next++) {+ const each = messages[next];+ // The agent's next turn starts here; what follows is that turn's.+ if (bound.has(each.messageId) && bound.get(each.messageId) !== turn) break;+ if (Date.parse(each.sentAt) > until) break;+ if (isAgentReply(each, agentId)) anchor = next;+ }+ const key = messages[anchor].messageId;+ placed.set(key, [...(placed.get(key) ?? []), request]);+ }+ return placed;+}+/*** Where one agent's turns show, by the message each shows under, in message* order. A turn shows under the message that started it, unless that message@@ -134,12 +180,7 @@ export function placeTurns(): Map<string, TurnActivity[]> {const placed = new Map<string, TurnActivity[]>();let previous: number | null = null;- const shown = (each: ChatMessage) =>- each.sender.kind === 'agent' &&- each.sender.agentId === agentId &&- !isSessionStartingNotice(each) &&- !turnEndNotice(each) &&- !isControlAck(each);+ const shown = (each: ChatMessage) => isAgentReply(each, agentId);messages.forEach((message, at) => {const turn = bound.get(message.messageId);if (!turn) return;diff --git a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsxindex c7038677c..1996855e9 100644--- a/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/chats/components/chat-timeline.tsx@@ -6,6 +6,7 @@ import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { Button } from '@renderer/lib/ui/button';import { cn } from '@renderer/utils/utils';import { agentInitials } from '@shared/core/agents/agent-avatar';+import type { ChatApproval } from '@shared/core/chats/activity';import type { ChatAgent, ChatMessage } from '@shared/core/chats/chats';import {chatAgentLabel,@@ -13,7 +14,7 @@ import {liveSessionStartingNotices,turnEndNotice,} from '@shared/core/chats/chats';-import { foldTurnEndNotices, placeTurns, type TurnActivity } from '../activity-join';+import { foldTurnEndNotices, placeRequests, placeTurns, type TurnActivity } from '../activity-join';import { messageAnchorId, threadChip } from '../chat-threads';import {agentTargets,@@ -176,6 +177,13 @@ export const ChatTimelineView = observer(function ChatTimelineView({}: Props) {const turnsByMessage = new Map<string, { activity: AgentActivity; turn: TurnActivity }[]>();const blocksByAnchor = new Map<string, { activity: AgentActivity; turn: TurnActivity }[]>();+ /** Requests shown after the agent's text that led up to them rather than with their turn. */+ const requestsByAnchor = new Map<+ string,+ { activity: AgentActivity; requests: ChatApproval[] }[]+ >();+ /** Each turn's requests that stay in its work log, by `agentId:turnId`. */+ const blockRequests = new Map<string, ChatApproval[]>();/** Turn-end notices shown on their turn's status row, by message id → `agentId:turnId`. */const foldedNotices = new Map<string, string>();const boundTurns = new Map(activities.map((activity) => [activity, activity.turns()]));@@ -185,11 +193,28 @@ export const ChatTimelineView = observer(function ChatTimelineView({list.push({ activity, turn });turnsByMessage.set(messageId, list);}- for (const [anchorId, turns] of placeTurns(timeline.messages, activity.agentId, bound))+ for (const [anchorId, turns] of placeTurns(timeline.messages, activity.agentId, bound)) {blocksByAnchor.set(anchorId, [...(blocksByAnchor.get(anchorId) ?? []),...turns.map((turn) => ({ activity, turn })),]);+ for (const turn of turns)+ for (const [requestAnchor, requests] of placeRequests(+ timeline.messages,+ activity.agentId,+ bound,+ anchorId,+ turn+ )) {+ if (requestAnchor === anchorId)+ blockRequests.set(`${activity.agentId}:${turn.turnId}`, requests);+ else+ requestsByAnchor.set(requestAnchor, [+ ...(requestsByAnchor.get(requestAnchor) ?? []),+ { activity, requests },+ ]);+ }+ }for (const [noticeId, turnId] of foldTurnEndNotices(timeline.messages, activity.agentId, bound))foldedNotices.set(noticeId, `${activity.agentId}:${turnId}`);}@@ -231,6 +256,25 @@ export const ChatTimelineView = observer(function ChatTimelineView({}return isNewBlock ? 'mt-5' : 'mt-1.5';};+ // Called inline, not as a component: it advances the block and spacing state in render order.+ const requestsRow = (key: string, activity: AgentActivity, requests: ChatApproval[]) => {+ const agent = agentOf(activity.agentId);+ const head = startsBlock(activity.agentId);+ return (+ <AgentRow+ key={key}+ agent={{+ name: agent ? chatAgentLabel(agent) : activity.agentId,+ iconUrl: agent?.iconUrl ?? null,+ }}+ serverId={serverId}+ head={head}+ className={spacing(head)}+ >+ <ChatRequests activity={activity} requests={requests} />+ </AgentRow>+ );+ };return (<div className="flex flex-col">{timeline.hasMore && (@@ -387,7 +431,10 @@ export const ChatTimelineView = observer(function ChatTimelineView({serverId={serverId}key={`${activity.agentId}:${turn.turnId}`}activity={activity}- turn={turn}+ turn={{+ ...turn,+ requests: blockRequests.get(`${activity.agentId}:${turn.turnId}`) ?? [],+ }}endReason={endReasons.get(`${activity.agentId}:${turn.turnId}`) ?? null}head={head}agent={{@@ -398,6 +445,9 @@ export const ChatTimelineView = observer(function ChatTimelineView({/>);})}+ {(requestsByAnchor.get(message.messageId) ?? []).map(({ activity, requests }) =>+ requestsRow(`requests:${activity.agentId}:${requests[0].turnId}`, activity, requests)+ )}</Fragment>);})}@@ -406,22 +456,7 @@ export const ChatTimelineView = observer(function ChatTimelineView({(request) => request.state === 'open' && !shownRequests.has(request.requestId));if (!requests.length) return null;- const agent = agentOf(activity.agentId);- const head = startsBlock(activity.agentId);- return (- <AgentRow- key={`requests:${activity.agentId}`}- agent={{- name: agent ? chatAgentLabel(agent) : activity.agentId,- iconUrl: agent?.iconUrl ?? null,- }}- serverId={serverId}- head={head}- className={spacing(head)}- >- <ChatRequests activity={activity} requests={requests} />- </AgentRow>- );+ return requestsRow(`requests:${activity.agentId}`, activity, requests);})}{timeline.pending.map((send) => (<PendingBubblediff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsxindex 91201083c..ac914fd23 100644--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-grouped-list.tsx@@ -217,7 +217,11 @@ const RoomStateDisclosure = observer(function RoomStateDisclosure() {if (failed.length === 0 && unknownMemberships === 0) return null;const reasons: string[] = [];- if (failed.length > 0) reasons.push(`couldn’t reach ${failed.map((s) => s.name).join(', ')}`);+ if (failed.length > 0) {+ reasons.push(+ `couldn’t get them from your Switch server (${failed.length === 1 ? 'workspace' : 'workspaces'} ${failed.map((s) => `“${s.name}”`).join(', ')})`+ );+ }if (unknownMemberships > 0) {reasons.push(`${unknownMemberships} ${unknownMemberships === 1 ? 'agent’s' : 'agents’'} rooms didn’t load`diff --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 d32869007..24e997f18 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,19 +3,27 @@ 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 { followConsoleLink } from '@renderer/features/deeplinks/console-link-handler';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';import { rpc } from '@renderer/lib/ipc';import { useShowModal } from '@renderer/lib/modal/modal-provider';import { reportOpenAttempt } from '@renderer/lib/open-external';+import { appState } from '@renderer/lib/stores/app-state';+import { useWorkspaceAgents } from '@renderer/lib/stores/use-workspace-agents';import { Button } from '@renderer/lib/ui/button';import { Spinner } from '@renderer/lib/ui/spinner';import { cn } from '@renderer/utils/utils';+import { consoleLink } from '@shared/core/deeplinks/console-links';import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';import {type BuddyPlatform,+ type BuddyRefusal,type BuddyResume,+ type BuddySetupStep,+ buddyHandedOffPlatform,+ buddyHandoffRefusal,buddyPlatform,buddyResumeBridges,buddySetupStep,@@ -23,8 +31,9 @@ import {import {BUDDY_CHAT_NAME,buddyHandoffRequestId,- continueBuddyInSlack,- resumeBuddyInSlack,+ buddyRestartedHandoffRequestId,+ continueBuddyInChannel,+ resumeBuddyInChannel,} from './open-buddy';/** What the person says in the Welcome chat when they choose to stay in Console. */@@ -33,7 +42,7 @@ 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 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+ * a private channel made for them on Slack or Discord, 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.*/@@ -83,6 +92,13 @@ const Cards = observer(function Cards({const [reopened, setReopened] = useState(false);const [creating, setCreating] = useState(false);const [createError, setCreateError] = useState<string | null>(null);+ // A refusal from creating the hand-off answers for that connection, as a resume's would.+ const [createRefusal, setCreateRefusal] = useState<{+ bridgeId: string;+ refusal: BuddyRefusal;+ } | null>(null);+ const [notConnected, setNotConnected] = useState<BuddyPlatform | null>(null);+ const [chosenBridgeId, setChosenBridgeId] = useState<string | null>(null);const bridgesQuery = useQuery({queryKey: ['remote-bridges', workspaceId],@@ -90,10 +106,19 @@ const Cards = observer(function Cards({});const ids = useMyIdentities(workspaceId);const resumeBridges = buddyResumeBridges(bridgesQuery.data ?? null, ids.identities);+ const accountIds = (bridgeId: string) =>+ (ids.identities ?? [])+ .filter((identity) => identity.bridgeId === bridgeId)+ .map((identity) => identity.externalUserId);const resumeQueries = useQueries({queries: resumeBridges.map((bridge) => ({- queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)],- queryFn: () => resumeBuddyInSlack(serverId, agentId, bridge.id),+ // Keyed by the linked accounts too, so linking or unlinking one reads it again.+ queryKey: [+ 'buddy-handoff',+ buddyHandoffRequestId(agentId, bridge.id),+ ...accountIds(bridge.id),+ ],+ queryFn: () => resumeBuddyInChannel(serverId, agentId, bridge, accountIds(bridge.id)),retry: false,staleTime: Infinity,})),@@ -101,19 +126,36 @@ const Cards = observer(function Cards({const resumes: Record<string, BuddyResume> = {};resumeBridges.forEach((bridge, index) => {const query = resumeQueries[index];- if (query.isError) resumes[bridge.id] = 'failed';+ if (query.isError) resumes[bridge.id] = buddyHandoffRefusal(query.error) ?? 'failed';else if (query.isSuccess) resumes[bridge.id] = query.data;});- const platform = buddyPlatform(picked, bridgesQuery.data ?? null);+ if (createRefusal && resumes[createRefusal.bridgeId] === null)+ resumes[createRefusal.bridgeId] = createRefusal.refusal;+ // With nothing picked, open on the app a hand-off was already made in, once every app has answered.+ const handedOff = buddyHandedOffPlatform(resumeBridges, resumes);+ const waiting = picked === null && handedOff === undefined;+ const platform = waiting+ ? null+ : buddyPlatform(picked ?? handedOff ?? null, bridgesQuery.data ?? null);const label = platform ? PLATFORM_NAMES[platform] : '';- const step = buddySetupStep({- platform,- bridges: bridgesQuery.data ?? null,- identities: ids.identities,- resumes,- failed: bridgesQuery.isError || ids.error != null,- });+ const failed = bridgesQuery.isError || ids.error != null;+ const step: BuddySetupStep =+ waiting && !failed+ ? { kind: 'resuming' }+ : buddySetupStep({+ platform,+ bridges: bridgesQuery.data ?? null,+ identities: ids.identities,+ resumes,+ chosenBridgeId,+ failed,+ });+ // Every connected one of the app is a choice, linked or not; the cards follow the one chosen.+ const connectedBridges = (bridgesQuery.data ?? []).filter(+ (bridge) => bridge.type === platform && bridge.status === 'active'+ );const retry = () => {+ setCreateRefusal(null);void bridgesQuery.refetch();ids.refresh();for (const query of resumeQueries) if (query.isError) void query.refetch();@@ -126,23 +168,26 @@ const Cards = observer(function Cards({enabled: doneRoomId !== null,});const channelUrl = roomQuery.data?.externalChannelUrl ?? null;- const openSlack = (url: string) =>+ const openChannel = (url: string) =>void reportOpenAttempt(rpc.switchRooms.openRoomChannel({ serverId, channelUrl: url }),- 'Could not open Slack',+ `Could not open ${label}`,url);- const create = async (bridge: RemoteBridge) => {+ const create = async (bridge: RemoteBridge, requestId: string) => {setCreating(true);setCreateError(null);try {- await continueBuddyInSlack(serverId, { agentId }, bridge.id);+ await continueBuddyInChannel(serverId, { agentId }, bridge, requestId);+ setCreateRefusal(null);await queryClient.invalidateQueries({queryKey: ['buddy-handoff', buddyHandoffRequestId(agentId, bridge.id)],});} catch (cause) {- setCreateError(failureText(cause, 'Switch did not answer.'));+ const refusal = buddyHandoffRefusal(cause);+ if (refusal) setCreateRefusal({ bridgeId: bridge.id, refusal });+ else setCreateError(failureText(cause, 'Switch did not answer.'));} finally {setCreating(false);}@@ -187,36 +232,21 @@ const Cards = observer(function Cards({<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">- {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>- )- )}+ {TILES.map((app) => (+ <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>+ ))}</div><Button variant="ghost" size="sm" className="self-start" onClick={stay}>No chat app? Continue here in Switch Console@@ -242,17 +272,84 @@ const Cards = observer(function Cards({</StatusRow>)}+ {step.kind === 'refused' && (+ <PlatformCard+ platform={step.bridge.type}+ title={+ step.refusal.code === 'ACCOUNTS_AMBIGUOUS'+ ? `More than one ${label} account is linked`+ : `Your linked ${label} account changed`+ }+ description={+ step.refusal.code === 'ACCOUNTS_AMBIGUOUS'+ ? `Unlink the ${label} account you no longer use, then retry.`+ : `Your first channel was made for the account linked before. I can start again in a new channel with the account linked now.`+ }+ error={step.refusal.message}+ footer={+ <div className="flex flex-wrap items-center gap-3">+ {step.refusal.code === 'ACCOUNTS_AMBIGUOUS' ? (+ <>+ <Button+ onClick={() =>+ appState.navigation.navigate('settings', { tab: 'messaging-apps' })+ }+ >+ Manage linked accounts+ </Button>+ <Button variant="outline" onClick={retry}>+ Retry+ </Button>+ </>+ ) : (+ <RestartButton+ creating={creating}+ accountIds={accountIds(step.bridge.id)}+ onRestart={(accountId) =>+ void create(+ step.bridge,+ buddyRestartedHandoffRequestId(agentId, step.bridge.id, accountId)+ )+ }+ />+ )}+ {createError && (+ <span className="text-sm text-foreground-destructive">{createError}</span>+ )}+ </div>+ }+ />+ )}+{step.kind === 'connect' && (<PlatformCardplatform={step.platform}title={`Connect ${label}`}description={`Add ${label} to your Switch workspace.`}footer={- <Button- onClick={() => showConnect({ serverId, platform: step.platform, onClosed: retry })}- >- Connect {label}- </Button>+ <div className="flex flex-wrap items-center gap-3">+ <Button+ onClick={() => {+ setNotConnected(null);+ showConnect({+ serverId,+ platform: step.platform,+ // Said only once the re-read is in, so a connection just made never flashes it.+ onClosed: () => {+ ids.refresh();+ void bridgesQuery.refetch().then(() => setNotConnected(step.platform));+ },+ });+ }}+ >+ Connect {label}+ </Button>+ {notConnected === step.platform && (+ <span className="text-sm text-foreground-muted">+ {label} isn’t connected yet. Try again when you’re ready.+ </span>+ )}+ </div>}/>)}@@ -274,15 +371,24 @@ const Cards = observer(function Cards({: `So I recognise you in ${step.bridge.displayName}.`}footer={- <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 className="flex flex-col items-start gap-3">+ <BridgeChoice+ platform={step.bridge.type}+ bridges={connectedBridges}+ chosenId={step.bridge.id}+ disabled={false}+ onChoose={setChosenBridgeId}+ />+ <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></div>}/>@@ -294,31 +400,46 @@ const Cards = observer(function Cards({<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">Slack ready</span> — Slack connected · account linked+ <span className="font-semibold">{label} ready</span> — {label} connected · account+ linked</span>- <BridgeIcon bridgeType="slack" size={16} />+ <BridgeIcon bridgeType={step.bridge.type} size={16} /></div><PlatformCard- platform="slack"- title="Continue in a private Slack channel"+ platform={step.bridge.type}+ title={`Continue in a private ${label} channel`}description="I’ll create a private channel just for us and continue there."error={createError}footer={- <Button disabled={creating} onClick={() => void create(step.bridge)}>- {creating ? (- <>- <Spinner size="sm" />- Creating channel…- </>- ) : createError ? (- 'Try again'- ) : (- <>- Create channel and continue- <ArrowRight />- </>- )}- </Button>+ <div className="flex flex-col items-start gap-3">+ <BridgeChoice+ platform={step.bridge.type}+ bridges={connectedBridges}+ chosenId={step.bridge.id}+ disabled={creating}+ onChoose={setChosenBridgeId}+ />+ <Button+ disabled={creating}+ onClick={() =>+ void create(step.bridge, buddyHandoffRequestId(agentId, step.bridge.id))+ }+ >+ {creating ? (+ <>+ <Spinner size="sm" />+ Creating channel…+ </>+ ) : createError ? (+ 'Try again'+ ) : (+ <>+ Create channel and continue+ <ArrowRight />+ </>+ )}+ </Button>+ </div>}/></>@@ -341,7 +462,18 @@ const Cards = observer(function Cards({? `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} />}+ footer={+ <div className="flex flex-col items-start gap-3">+ <BridgeChoice+ platform={step.bridge.type}+ bridges={connectedBridges}+ chosenId={step.bridge.id}+ disabled={false}+ onChoose={setChosenBridgeId}+ />+ <InviteCommand platform={step.bridge.type} agentName={agentName} />+ </div>+ }/></>)}@@ -358,18 +490,18 @@ const Cards = observer(function Cards({<StatusRow><CheckCircle2 className="size-4 shrink-0 text-foreground-success" /><span className="min-w-0 flex-1 truncate text-foreground-success">- {roomQuery.data?.linkedChannelName ?? 'Private Slack channel'} ready+ {roomQuery.data?.linkedChannelName ?? `Private ${label} channel`} ready</span>{channelUrl ? (- <Button size="sm" onClick={() => openSlack(channelUrl)}>- Open Slack+ <Button size="sm" onClick={() => openChannel(channelUrl)}>+ Open {label}<ArrowRight /></Button>) : (<span className="text-foreground-muted">{roomQuery.isPending- ? 'Looking up the Slack channel…'- : 'Couldn’t get a link to the Slack channel. Find it in Slack.'}+ ? `Looking up the ${label} channel…`+ : `Couldn’t get a link to the ${label} channel. Find it in ${label}.`}</span>)}</StatusRow>@@ -377,25 +509,170 @@ const Cards = observer(function Cards({💡 <span className="font-semibold text-foreground">Private channel</span> — only you andbuddy can see it. Just reply, no @ needed.</div>+ {roomQuery.data?.createdAt && (+ <CreatedSince+ workspaceId={workspaceId}+ buddyId={agentId}+ since={roomQuery.data.createdAt}+ />+ )}</>)}</div>);});+/**+ * The agents the person owns made since the hand-off, each with the rooms it is+ * in, linked to their pages here: what the buddy set up over in the chat app.+ * Nothing at all while there are none.+ */+const CreatedSince = observer(function CreatedSince({+ workspaceId,+ buddyId,+ since,+}: {+ workspaceId: string;+ buddyId: string;+ since: string;+}) {+ const agents = (useWorkspaceAgents(workspaceId).data ?? []).filter(+ (agent) =>+ agent.id !== buddyId &&+ agent.ownerId !== null &&+ agent.ownerId === chatsStore.userId &&+ Date.parse(agent.createdAt) > Date.parse(since)+ );+ const rooms = useQueries({+ queries: agents.map((agent) => ({+ queryKey: ['buddy-created-agent-rooms', workspaceId, agent.id],+ queryFn: () => rpc.workspaces.listAgentRooms({ workspaceId, agentId: agent.id }),+ })),+ });+ // Agents also sit in rooms made before the hand-off (a bridge's default channels): name only newer ones.+ const roomsQuery = useQuery({+ queryKey: ['remote-rooms', workspaceId],+ queryFn: () => rpc.workspaces.listRooms(workspaceId),+ });+ const newRoom = new Set(+ (roomsQuery.data ?? [])+ .filter((room) => Date.parse(room.createdAt) > Date.parse(since))+ .map((room) => room.id)+ );+ if (agents.length === 0) return null;+ const link = (label: string, url: string) => (+ <Button+ variant="link"+ size="sm"+ className="h-auto p-0 text-foreground underline underline-offset-2"+ onClick={() => followConsoleLink(url)}+ >+ {label}+ </Button>+ );+ return (+ <div data-testid="buddy-created-since" className="text-sm text-foreground-muted">+ Created since:{' '}+ {agents.map((agent, index) => (+ <span key={agent.id}>+ {index > 0 && ', '}+ {link(agent.displayName ?? agent.name, consoleLink('agent', { id: agent.id }))}+ {(rooms[index]?.data ?? [])+ .filter((room) => !room.archived && newRoom.has(room.roomId))+ .map((room) => (+ <span key={room.roomId}>+ {' · '}+ {link(room.roomName, consoleLink('room', { id: room.roomId }))} room+ </span>+ ))}+ </span>+ ))}+ </div>+ );+});++/** Starts a new hand-off for the one account linked now; with none or several there is no one to start it for. */+function RestartButton({+ creating,+ accountIds,+ onRestart,+}: {+ creating: boolean;+ accountIds: string[];+ onRestart: (accountId: string) => void;+}) {+ if (accountIds.length !== 1) return null;+ return (+ <Button disabled={creating} onClick={() => onRestart(accountIds[0])}>+ {creating ? (+ <>+ <Spinner size="sm" />+ Creating channel…+ </>+ ) : (+ <>+ Start again with your new account+ <ArrowRight />+ </>+ )}+ </Button>+ );+}+const PLATFORM_NAMES: Record<BuddyPlatform, string> = {slack: 'Slack',teams: 'Microsoft Teams',+ discord: 'Discord',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' },+ { bridgeType: 'slack', name: 'Slack', subtitle: 'Channels & DMs' },+ { bridgeType: 'teams', name: 'Microsoft Teams', subtitle: 'Teams & chats' },+ { bridgeType: 'discord', name: 'Discord', subtitle: 'Servers & channels' },+ { bridgeType: 'telegram', name: 'Telegram', subtitle: 'Groups & chats' },] as const;+/** Which of the app's connections, when there is more than one to choose from. */+function BridgeChoice({+ platform,+ bridges,+ chosenId,+ disabled,+ onChoose,+}: {+ platform: string;+ bridges: RemoteBridge[];+ chosenId: string;+ disabled: boolean;+ onChoose: (bridgeId: string) => void;+}) {+ if (bridges.length < 2) return null;+ const label = PLATFORM_NAMES[platform as BuddyPlatform];+ const unit = platform === 'discord' ? 'server' : 'workspace';+ return (+ <div+ role="group"+ aria-label={`${label} ${unit}`}+ className="flex flex-wrap items-center gap-2 text-sm"+ >+ <span className="text-foreground-muted">Which {unit}?</span>+ {bridges.map((bridge) => (+ <Button+ key={bridge.id}+ size="sm"+ variant={bridge.id === chosenId ? 'default' : 'outline'}+ aria-pressed={bridge.id === chosenId}+ disabled={disabled}+ onClick={() => onChoose(bridge.id)}+ >+ {bridge.displayName}+ </Button>+ ))}+ </div>+ );+}+function TileText({ name, subtitle }: { name: string; subtitle: string }) {return (<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 30d5f21c9..fffaa6def 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,7 +1,16 @@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 { buddyPlatform, buddySetupCardsEnabled, buddySetupStep } from './buddy-setup-step';+import { RpcError } from '@shared/lib/ipc/rpc-error';+import {+ buddyBridge,+ buddyHandedOffPlatform,+ buddyHandoffRefusal,+ buddyPlatform,+ buddyResumeBridges,+ 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;@@ -17,6 +26,7 @@ const telegram = {status: 'active',directorySearchSupported: false,} as RemoteBridge;+const discord = { id: 'b-5', type: 'discord', status: 'active' } 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;@@ -26,6 +36,7 @@ const base = {bridges: [],identities: [],resumes: {},+ chosenBridgeId: null,failed: false,};@@ -129,6 +140,110 @@ describe('buddySetupStep', () => {})).toEqual({ kind: 'guide', bridge: telegram });});+ it('walks Discord to the same private channel hand-off as Slack, on its own connections only', () => {+ const discordBase = { ...base, platform: 'discord' as const };+ const linkedDiscord = { bridgeId: 'b-5' } as LinkedIdentity;+ expect(buddySetupStep({ ...discordBase, bridges: [slack] })).toEqual({+ kind: 'connect',+ platform: 'discord',+ });+ expect(buddySetupStep({ ...discordBase, bridges: [slack, discord] })).toEqual({+ kind: 'link',+ bridge: discord,+ });+ expect(+ buddySetupStep({+ ...discordBase,+ bridges: [slack, discord],+ identities: [linked, linkedDiscord],+ resumes: { 'b-1': handedOff, 'b-5': null },+ })+ ).toEqual({ kind: 'create', bridge: discord });+ });+});++describe('a platform with one connection linked and another not', () => {+ const mixed = { ...base, bridges: [slack, slack2], identities: [linked] };++ it('defaults to the linked one and offers to create there', () => {+ expect(buddySetupStep({ ...mixed, resumes: { 'b-1': null } })).toEqual({+ kind: 'create',+ bridge: slack,+ });+ });++ it('asks to link the unlinked one when it is chosen, and creates on the linked one when that is', () => {+ expect(buddySetupStep({ ...mixed, resumes: { 'b-1': null }, chosenBridgeId: 'b-2' })).toEqual({+ kind: 'link',+ bridge: slack2,+ });+ expect(buddySetupStep({ ...mixed, resumes: { 'b-1': null }, chosenBridgeId: 'b-1' })).toEqual({+ kind: 'create',+ bridge: slack,+ });+ });++ it('shows a hand-off made on one connection, and the other connection its own state when chosen', () => {+ const both = { ...mixed, identities: [linked, linked2] };+ expect(buddySetupStep({ ...both, resumes: { 'b-1': null, 'b-2': handedOff } })).toEqual({+ kind: 'done',+ chat: handedOff,+ });+ expect(+ buddySetupStep({ ...both, resumes: { 'b-1': null, 'b-2': handedOff }, chosenBridgeId: 'b-1' })+ ).toEqual({ kind: 'create', bridge: slack });+ expect(buddySetupStep({ ...mixed, resumes: { 'b-1': handedOff } })).toEqual({+ kind: 'done',+ chat: handedOff,+ });+ });++ it('guides Teams on the connection chosen, linked or not', () => {+ const teams2 = { ...teams, id: 'b-6' } as RemoteBridge;+ const teamsMixed = {+ ...base,+ platform: 'teams' as const,+ bridges: [teams2, teams],+ identities: [{ bridgeId: 'b-3' } as LinkedIdentity],+ };+ expect(buddySetupStep(teamsMixed)).toEqual({ kind: 'guide', bridge: teams });+ expect(buddySetupStep({ ...teamsMixed, chosenBridgeId: 'b-6' })).toEqual({+ kind: 'link',+ bridge: teams2,+ });+ });+});++describe('buddyBridge', () => {+ it('is the one chosen, else a handed-off one, else a linked one, else the first connected', () => {+ const bridges = [slack, slack2, discord];+ expect(buddyBridge('slack', bridges, [], {}, 'b-2')).toBe(slack2);+ expect(buddyBridge('slack', bridges, [], {}, 'b-5')).toBe(slack);+ expect(buddyBridge('slack', bridges, [linked2], {}, null)).toBe(slack2);+ expect(buddyBridge('slack', bridges, [linked, linked2], { 'b-2': handedOff }, null)).toBe(+ slack2+ );+ expect(buddyBridge('slack', [{ ...slack, status: 'error' }, slack2], [linked], {}, null)).toBe(+ slack2+ );+ expect(buddyBridge('teams', bridges, [], {}, null)).toBeUndefined();+ });+});++describe('buddyResumeBridges', () => {+ it('is the linked, active Slack and Discord connections', () => {+ expect(+ buddyResumeBridges(+ [slack, teams, discord, { ...slack2, status: 'error' }],+ [+ linked,+ linked2,+ { bridgeId: 'b-3' } as LinkedIdentity,+ { bridgeId: 'b-5' } as LinkedIdentity,+ ]+ )+ ).toEqual([slack, discord]);+ });});describe('buddyPlatform', () => {@@ -140,3 +255,53 @@ describe('buddyPlatform', () => {expect(buddyPlatform(null, [{ ...slack, status: 'error' }, telegram])).toBe('telegram');});});++describe('buddyHandedOffPlatform', () => {+ it('waits for every app to answer before naming the one handed off in', () => {+ const discordChat = { ...handedOff, bridgeType: 'discord' } as ChatSummary;+ expect(buddyHandedOffPlatform([slack, discord], { 'b-1': null })).toBe(undefined);+ expect(buddyHandedOffPlatform([slack, discord], { 'b-1': null, 'b-5': discordChat })).toBe(+ 'discord'+ );+ expect(buddyHandedOffPlatform([slack, discord], { 'b-1': 'failed', 'b-5': null })).toBe(null);+ expect(buddyHandedOffPlatform([], {})).toBe(null);+ });+});++function chatApiError(apiCode: string, message: string) {+ return new RpcError({+ __switchConsoleRpcError: true,+ code: 'ChatApiError',+ message,+ data: { apiCode },+ });+}++describe('buddyHandoffRefusal', () => {+ it('is the linked-account refusals, with the server reason; null for anything else', () => {+ expect(buddyHandoffRefusal(chatApiError('ACCOUNTS_AMBIGUOUS', 'Unlink one.'))).toEqual({+ code: 'ACCOUNTS_AMBIGUOUS',+ message: 'Unlink one.',+ });+ expect(buddyHandoffRefusal(chatApiError('LINKED_ACCOUNT_CHANGED', 'Changed.'))).toEqual({+ code: 'LINKED_ACCOUNT_CHANGED',+ message: 'Changed.',+ });+ expect(buddyHandoffRefusal(chatApiError('NOT_A_MEMBER', 'No.'))).toBeNull();+ expect(buddyHandoffRefusal(new Error('down'))).toBeNull();+ });+});++describe('buddySetupStep refusals', () => {+ it('a refused resume is its own step, never done or create', () => {+ const refusal = { code: 'LINKED_ACCOUNT_CHANGED' as const, message: 'Changed.' };+ expect(+ buddySetupStep({+ ...base,+ bridges: [slack],+ identities: [linked],+ resumes: { 'b-1': refusal },+ })+ ).toEqual({ kind: 'refused', bridge: slack, refusal });+ });+});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 eb809a585..cfee98ade 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@@ -1,11 +1,16 @@+import { chatFailure } from '@renderer/features/chats/stores/chat-errors';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';+import { RpcError } from '@shared/lib/ipc/rpc-error';/** The chat apps the setup cards walk through, by bridge type. */-export const BUDDY_PLATFORMS = ['slack', 'teams', 'telegram'] as const;+export const BUDDY_PLATFORMS = ['slack', 'teams', 'discord', 'telegram'] as const;export type BuddyPlatform = (typeof BUDDY_PLATFORMS)[number];+/** The apps where the buddy makes the person a private channel; elsewhere they invite it themselves. */+const CHANNEL_PLATFORMS: readonly string[] = ['slack', 'discord'];+export type BuddySetupStep =| { kind: 'loading' }| { kind: 'unknown' }@@ -15,6 +20,7 @@ export type BuddySetupStep =| { kind: 'guide'; bridge: RemoteBridge }| { kind: 'resuming' }| { kind: 'create'; bridge: RemoteBridge }+ | { kind: 'refused'; bridge: RemoteBridge; refusal: BuddyRefusal }| { kind: 'done'; chat: ChatSummary };/** Whether to show the setup cards: only when the server says so, since an older one would turn their resume into an internal chat. */@@ -22,17 +28,37 @@ export function buddySetupCardsEnabled(flags: Partial<FeatureFlags> | null | undreturn flags?.buddy_slack_handoff === true;}-/** A hand-off resumed on one Slack connection: its chat, null for none started, or failed. */-export type BuddyResume = ChatSummary | null | 'failed';+/**+ * A hand-off the server refused for the person's linked accounts: more than+ * one on the bridge, or not the one it was started for. Its message is the+ * server's own, written for the person.+ */+export type BuddyRefusal = {+ code: 'ACCOUNTS_AMBIGUOUS' | 'LINKED_ACCOUNT_CHANGED';+ message: string;+};++const REFUSAL_CODES: readonly string[] = ['ACCOUNTS_AMBIGUOUS', 'LINKED_ACCOUNT_CHANGED'];++/** The linked-account refusal in a failed hand-off or resume, else null. */+export function buddyHandoffRefusal(cause: unknown): BuddyRefusal | null {+ if (!(cause instanceof RpcError) || cause.code !== 'ChatApiError') return null;+ const code = cause.stringField('apiCode');+ if (!code || !REFUSAL_CODES.includes(code)) return null;+ return { code: code as BuddyRefusal['code'], message: chatFailure(cause).message };+}++/** A hand-off resumed on one connection: its chat, null for none started, refused, or failed. */+export type BuddyResume = ChatSummary | null | BuddyRefusal | 'failed';-/** The active Slack connections the person has linked, where a hand-off could have been made. */+/** The active Slack and Discord connections the person has linked, where a hand-off could have been made. */export function buddyResumeBridges(bridges: RemoteBridge[] | null,identities: LinkedIdentity[] | null): RemoteBridge[] {return (bridges ?? []).filter((bridge) =>- bridge.type === 'slack' &&+ CHANNEL_PLATFORMS.includes(bridge.type) &&bridge.status === 'active' &&identities?.some((identity) => identity.bridgeId === bridge.id));@@ -50,14 +76,53 @@ export function buddyPlatform(return picked ?? BUDDY_PLATFORMS.find((platform) => activeBridge(bridges, platform)) ?? null;}+/** The app a hand-off was already made in: null for none, undefined while any resume is still out. */+export function buddyHandedOffPlatform(+ resumeBridges: RemoteBridge[],+ resumes: Partial<Record<string, BuddyResume>>+): BuddyPlatform | null | undefined {+ if (resumeBridges.some((bridge) => resumes[bridge.id] === undefined)) return undefined;+ return (+ (resumeBridges.find((bridge) => isChat(resumes[bridge.id]))?.type as BuddyPlatform) ?? null+ );+}+/**- * 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".+ * The connection of the app the cards are on: the one chosen, else the one a+ * hand-off was made on, else a linked one, else the first connected.+ */+export function buddyBridge(+ platform: BuddyPlatform,+ bridges: RemoteBridge[] | null,+ identities: LinkedIdentity[] | null,+ resumes: Partial<Record<string, BuddyResume>>,+ chosenId: string | null+): RemoteBridge | undefined {+ const active = (bridges ?? []).filter(+ (bridge) => bridge.type === platform && bridge.status === 'active'+ );+ return (+ active.find((bridge) => bridge.id === chosenId) ??+ active.find((bridge) => isChat(resumes[bridge.id])) ??+ active.find((bridge) => identities?.some((identity) => identity.bridgeId === bridge.id)) ??+ active[0]+ );+}++function isChat(resume: BuddyResume | undefined): resume is ChatSummary {+ return typeof resume === 'object' && resume !== null && 'roomId' in resume;+}++/**+ * Where the person is in moving their buddy to their chat app, from live reads,+ * on one connection of it (see `buddyBridge`). 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.+ * found its chat: a chat with the buddy made by hand is not a hand-off.+ * `resumes` is by bridge id, a bridge missing still being resumed. With no+ * connection chosen, every resume is waited for, so one already handed off wins.*- * Only Slack gets a channel made for them: elsewhere, once linked, they are+ * Only Slack and Discord get 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.@@ -67,37 +132,37 @@ export function buddySetupStep({bridges,identities,resumes,+ chosenBridgeId,failed,}: {platform: BuddyPlatform | null;bridges: RemoteBridge[] | null;identities: LinkedIdentity[] | null;resumes: Partial<Record<string, BuddyResume>>;+ chosenBridgeId: string | null;failed: boolean;}): BuddySetupStep {if (failed) return { kind: 'unknown' };if (!bridges) return { kind: 'loading' };if (!platform) return { kind: 'choose' };- const first = activeBridge(bridges, platform);- if (!first) return { kind: 'connect', platform };+ const bridge = buddyBridge(platform, bridges, identities, resumes, chosenBridgeId);+ if (!bridge) 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 };+ if (!identities.some((identity) => identity.bridgeId === bridge.id))+ return { kind: 'link', bridge };+ if (!CHANNEL_PLATFORMS.includes(platform)) return { kind: 'guide', bridge };+ if (bridge.id !== chosenBridgeId && !isChat(resumes[bridge.id])) {+ const results = buddyResumeBridges(bridges, identities)+ .filter((linked) => linked.type === platform)+ .map((linked) => resumes[linked.id]);+ if (results.includes('failed')) return { kind: 'unknown' };+ if (results.includes(undefined)) return { kind: 'resuming' };}- const linked = buddyResumeBridges(bridges, identities);- 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 !== null- );- if (chat) return { kind: 'done', chat };- if (results.includes('failed')) return { kind: 'unknown' };- if (results.includes(undefined)) return { kind: 'resuming' };- return { kind: 'create', bridge: linked[0] };+ const resume = resumes[bridge.id];+ if (resume === 'failed') return { kind: 'unknown' };+ if (resume === undefined) return { kind: 'resuming' };+ if (resume === null) return { kind: 'create', bridge };+ return isChat(resume)+ ? { kind: 'done', chat: resume }+ : { kind: 'refused', bridge, refusal: resume };}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.test.tsnew file mode 100644index 000000000..50e24c09b--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';+import { buddyWelcomeMessage } from './buddy-welcome-message';++describe('buddyWelcomeMessage', () => {+ it('ties the name the buddy goes by to the switch-buddy the intro introduced', () => {+ const first = buddyWelcomeMessage({ firstName: 'Max', agentName: 'switch-buddy-max' }).split(+ '\n'+ )[0];+ expect(first).toBe(+ 'Hi Max, I’m **switch-buddy-max**, your switch-buddy for everything Switch. 👋'+ );+ });++ it('does not say switch-buddy twice when that is its name', () => {+ const first = buddyWelcomeMessage({ firstName: null, agentName: 'switch-buddy' }).split(+ '\n'+ )[0];+ expect(first).toBe('Hi, I’m **switch-buddy**, your assistant for everything Switch. 👋');+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.tsindex 918adf395..1ab925112 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/buddy-welcome-message.ts@@ -29,7 +29,8 @@ export function buddyWelcomeMessage({agentName: string;}): string {return [- `Hi${firstName ? ` ${firstName}` : ''}, I’m **${agentName}**, your assistant for everything Switch. 👋`,+ // The intro calls it switch-buddy; the name it goes by from here on carries the person too.+ `Hi${firstName ? ` ${firstName}` : ''}, I’m **${agentName}**, your ${agentName === 'switch-buddy' ? 'assistant' : 'switch-buddy'} for everything Switch. 👋`,'',`Switch brings your agents to where your team already works: ${platformList()}. Your team talks to agents in the channels they already use, and people and agents work together in shared rooms.`,'',@@ -43,10 +44,10 @@ export function buddyWelcomeMessage({].join('\n');}-/** What the buddy says first in the Slack channel it continues in, once setup is done. */-export function buddySlackOpener(firstName: string | null): string {+/** What the buddy says first in the Slack or Discord channel it continues in, once setup is done. */+export function buddyChannelOpener(firstName: string | null, platform: string): string {return [- `Hi${firstName ? ` ${firstName}` : ''}, setup is done: Slack is connected and this is our private channel. 🎉`,+ `Hi${firstName ? ` ${firstName}` : ''}, setup is done: ${platform} is connected and this is our private channel. 🎉`,'From here I can help you create agents and bring them into your team’s channels.','What do you mostly work on?',].join('\n\n');diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.tsindex 0893c561b..d75c8ef12 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.test.ts@@ -26,17 +26,18 @@ vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({}));vi.mock('./buddy-intro-store', () => ({ buddyIntroStore: { skipped } }));vi.mock('./buddy-welcome-message', () => ({- buddySlackOpener: () => 'opener',+ buddyChannelOpener: () => 'opener',buddyWelcomeMessage: ({ firstName, agentName }: { firstName: string; agentName: string }) =>`welcome ${firstName} from ${agentName}`,}));const {BUDDY_CHAT_NAME,- continueBuddyInSlack,+ buddyRestartedHandoffRequestId,+ continueBuddyInChannel,openBuddyAfterOnboarding,openBuddyChat,- resumeBuddyInSlack,+ resumeBuddyInChannel,} = await import('./open-buddy');const { RpcError } = await import('@shared/lib/ipc/rpc-error');@@ -50,6 +51,7 @@ function chatApiError(apiCode: string, status: number) {}const buddy = { agentId: 'a-1', name: 'switch-buddy-max' };+const slackBridge = { id: 'b-1', type: 'slack' };function chat(roomId: string,@@ -185,15 +187,15 @@ describe('openBuddyAfterOnboarding', () => {});});-describe('continueBuddyInSlack', () => {+describe('continueBuddyInChannel', () => {it('asks once, under a request id fixed by the agent and the connection', async () => {createChat.mockResolvedValue(chat('r-slack', '', 'a-1', 'direct', 'slack'));await Promise.all([- continueBuddyInSlack('srv-1', buddy, 'b-1'),- continueBuddyInSlack('srv-1', buddy, 'b-1'),+ continueBuddyInChannel('srv-1', buddy, slackBridge, 'buddy-handoff:a-1:b-1'),+ continueBuddyInChannel('srv-1', buddy, slackBridge, 'buddy-handoff:a-1:b-1'),]);- await continueBuddyInSlack('srv-1', buddy, 'b-1');+ await continueBuddyInChannel('srv-1', buddy, slackBridge, 'buddy-handoff:a-1:b-1');expect(createChat).toHaveBeenCalledTimes(2);expect(createChat).toHaveBeenCalledWith({@@ -207,7 +209,7 @@ describe('continueBuddyInSlack', () => {});});-describe('resumeBuddyInSlack', () => {+describe('resumeBuddyInChannel', () => {const handoff = {serverId: 'srv-1',agentIds: ['a-1'],@@ -221,16 +223,55 @@ describe('resumeBuddyInSlack', () => {const slackChat = chat('r-slack', '', 'a-1', 'direct', 'slack');createChat.mockResolvedValue(slackChat);- await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).resolves.toBe(slackChat);+ await expect(resumeBuddyInChannel('srv-1', 'a-1', slackBridge, ['U1'])).resolves.toBe(+ slackChat+ );expect(createChat).toHaveBeenCalledWith({ ...handoff, resumeOnly: true });});it('is null when none was started, and throws any other refusal', async () => {createChat.mockRejectedValueOnce(chatApiError('NO_SUCH_OPERATION', 404));- await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).resolves.toBeNull();+ await expect(resumeBuddyInChannel('srv-1', 'a-1', slackBridge, ['U1'])).resolves.toBeNull();createChat.mockRejectedValueOnce(chatApiError('REQUEST_REUSED', 409));- await expect(resumeBuddyInSlack('srv-1', 'a-1', 'b-1')).rejects.toThrow('refused');+ await expect(resumeBuddyInChannel('srv-1', 'a-1', slackBridge, ['U1'])).rejects.toThrow(+ 'refused'+ );+ });++ it('after the linked account changed, finds the hand-off started again for the one linked now', async () => {+ const restarted = chat('r-new', '', 'a-1', 'direct', 'slack');+ createChat.mockImplementation(async (params: { requestId: string }) => {+ if (params.requestId === 'buddy-handoff:a-1:b-1')+ throw chatApiError('LINKED_ACCOUNT_CHANGED', 409);+ return restarted;+ });++ await expect(resumeBuddyInChannel('srv-1', 'a-1', slackBridge, ['U2'])).resolves.toBe(+ restarted+ );+ expect(createChat).toHaveBeenLastCalledWith({+ ...handoff,+ requestId: 'buddy-handoff:a-1:b-1:U2',+ resumeOnly: true,+ });+ });++ it('keeps the account-changed refusal when nothing was started again', async () => {+ createChat+ .mockReset()+ .mockRejectedValueOnce(chatApiError('LINKED_ACCOUNT_CHANGED', 409))+ .mockRejectedValueOnce(chatApiError('NO_SUCH_OPERATION', 404));++ await expect(resumeBuddyInChannel('srv-1', 'a-1', slackBridge, ['U2'])).rejects.toMatchObject({+ data: { apiCode: 'LINKED_ACCOUNT_CHANGED' },+ });+ });+});++describe('buddyRestartedHandoffRequestId', () => {+ it('extends the first request id with the account, so it is fixed and never the same', () => {+ expect(buddyRestartedHandoffRequestId('a-1', 'b-1', 'U2')).toBe('buddy-handoff:a-1:b-1:U2');});});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.tsindex adc2d6ac4..50182e730 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-buddy/open-buddy.ts@@ -1,15 +1,17 @@import { focusComposerWhenOpened } from '@renderer/features/chats/components/chat-composer';import { chatsStore, chatTitler } from '@renderer/features/chats/stores/chats';+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';import { failureText } from '@renderer/lib/errors/describe-failure';import { toast } from '@renderer/lib/hooks/use-toast';import { rpc } from '@renderer/lib/ipc';import { appState } from '@renderer/lib/stores/app-state';import type { ChatSummary } from '@shared/core/chats/chats';+import type { RemoteBridge } from '@shared/core/switch-servers/switch-servers';import { RpcError } from '@shared/lib/ipc/rpc-error';import { firstNameOf } from './buddy-identity';import { buddyIntroStore } from './buddy-intro-store';import { buddyPerson } from './buddy-person';-import { buddySlackOpener, buddyWelcomeMessage } from './buddy-welcome-message';+import { buddyChannelOpener, buddyWelcomeMessage } from './buddy-welcome-message';/** What the buddy's first chat is called, as on the board; it keeps it. */export const BUDDY_CHAT_NAME = 'Welcome';@@ -115,7 +117,7 @@ export async function openBuddyAfterOnboarding(}/**- * The same for every attempt to continue with the buddy on one Slack+ * The same for every attempt to continue with the buddy on one* connection, so a double click, a second window or a reopened Console all* land on the one chat the server made for the first.*/@@ -123,27 +125,47 @@ export function buddyHandoffRequestId(agentId: string, bridgeId: string): stringreturn `buddy-handoff:${agentId}:${bridgeId}`;}+/**+ * A hand-off started again, deliberately, after the person linked a different+ * account than the first one was made for: a new room for that account, never+ * the old one. Fixed by the account too, so a double click or a restart still+ * lands on the one room made for it.+ */+export function buddyRestartedHandoffRequestId(+ agentId: string,+ bridgeId: string,+ externalAccountId: string+): string {+ return `${buddyHandoffRequestId(agentId, bridgeId)}:${externalAccountId}`;+}+/** The handoffs under way, by request id: one at a time each. */const handingOff = new Map<string, Promise<ChatSummary>>();-function buddyHandoff(serverId: string, agentId: string, bridgeId: string) {+type HandoffBridge = Pick<RemoteBridge, 'id' | 'type'>;++function buddyHandoff(serverId: string, agentId: string, bridge: HandoffBridge, requestId: string) {return {serverId,agentIds: [agentId],name: null,- bridgeId,- requestId: buddyHandoffRequestId(agentId, bridgeId),- greeting: buddySlackOpener(firstNameOf(buddyPerson(serverId).name)),+ bridgeId: bridge.id,+ requestId,+ greeting: buddyChannelOpener(+ firstNameOf(buddyPerson(serverId).name),+ bridgePlatformLabel(bridge.type)+ ),};}-/** Makes the person's private Slack channel with their buddy, the buddy opening it. */-export function continueBuddyInSlack(+/** Makes the person's private Slack or Discord channel with their buddy, the buddy opening it. */+export function continueBuddyInChannel(serverId: string,agent: { agentId: string },- bridgeId: string+ bridge: HandoffBridge,+ requestId: string): Promise<ChatSummary> {- const params = buddyHandoff(serverId, agent.agentId, bridgeId);+ const params = buddyHandoff(serverId, agent.agentId, bridge, requestId);const running = handingOff.get(params.requestId);if (running) return running;const made = rpc.chats@@ -158,28 +180,63 @@ export function continueBuddyInSlack(}/**- * The buddy's Slack channel on this connection when a hand-off was started+ * The buddy's channel on this connection when a hand-off was started* there, finishing it if it was cut short; null when none was. Never makes one.+ *+ * When the first hand-off was made for an account no longer linked, the one+ * started again for the account linked now (`accountIds`, the person's+ * accounts on the bridge) is the answer, if there is one; else the server's+ * refusal stands, for the person to start again.*/-export async function resumeBuddyInSlack(+export async function resumeBuddyInChannel(+ serverId: string,+ agentId: string,+ bridge: HandoffBridge,+ accountIds: string[]+): Promise<ChatSummary | null> {+ try {+ return await resumeHandoff(+ serverId,+ agentId,+ bridge,+ buddyHandoffRequestId(agentId, bridge.id)+ );+ } catch (cause) {+ if (!isChatApiError(cause, 'LINKED_ACCOUNT_CHANGED') || accountIds.length !== 1) throw cause;+ const restarted = await resumeHandoff(+ serverId,+ agentId,+ bridge,+ buddyRestartedHandoffRequestId(agentId, bridge.id, accountIds[0])+ );+ if (restarted === null) throw cause;+ return restarted;+ }+}++async function resumeHandoff(serverId: string,agentId: string,- bridgeId: string+ bridge: HandoffBridge,+ requestId: string): Promise<ChatSummary | null> {try {const chat = await rpc.chats.create({- ...buddyHandoff(serverId, agentId, bridgeId),+ ...buddyHandoff(serverId, agentId, bridge, requestId),resumeOnly: true,});chatsStore.add(serverId, chat);return chat;} catch (cause) {- if (- cause instanceof RpcError &&- cause.code === 'ChatApiError' &&- cause.stringField('apiCode') === 'NO_SUCH_OPERATION'- )- return null;+ if (isChatApiError(cause, 'NO_SUCH_OPERATION')) return null;throw cause;}}++function isChatApiError(cause: unknown, apiCode: string): boolean {+ return (+ cause instanceof RpcError &&+ cause.code === 'ChatApiError' &&+ cause.stringField('apiCode') === apiCode+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-settings-sections.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-settings-sections.tsxindex bdd11ed02..ed036c4cf 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-settings-sections.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-settings-sections.tsx@@ -485,12 +485,13 @@ export function RoomInfoSection({ room }: { room: RemoteRoomDetail }) {'Created',room.createdAt ? <AbsoluteTime key="created" value={room.createdAt} includeYear /> : '—',],- ['Owner', room.ownerName ?? '—'],['Messaging app',room.bridgeDisplayName ?? (room.isConsoleChat ? 'Group chat in Switch Console' : 'None'),],];+ // A room an agent created on its own has no owning person; say nothing rather than "—".+ if (room.ownerName) rows.splice(1, 0, ['Owner', room.ownerName]);if (room.linkedChannelName) rows.push(['Channel', `#${room.linkedChannelName}`]);if (room.externalChannelId)rows.push(['Channel id', <Mono key="c">{room.externalChannelId}</Mono>]);diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.test.tsindex 88173e096..0aee82b78 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.test.ts@@ -2,10 +2,11 @@ import { describe, expect, it } from 'vitest';import { embeddedRoomTab, RoomTabStore } from './room-tab-store';describe('the room tab', () => {- it('opens a room shown inside a page on its conversation only where that can be drawn', () => {- expect(embeddedRoomTab('mattermost')).toBe('chat');- expect(embeddedRoomTab('slack')).toBe('configuration');- expect(embeddedRoomTab(null)).toBe('configuration');+ it('opens a room shown inside a page on its conversation whenever it has one', () => {+ expect(embeddedRoomTab('mattermost', false)).toBe('chat');+ expect(embeddedRoomTab('slack', false)).toBe('chat');+ expect(embeddedRoomTab(null, true)).toBe('chat');+ expect(embeddedRoomTab(null, false)).toBe('configuration');});it('shows what the page opens on until a tab is picked, and the pick for that room only', () => {diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.tsindex 21816b5e3..c43ad5e54 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/room-tab-store.ts@@ -1,16 +1,15 @@import { makeAutoObservable } from 'mobx';-import { bridgeCanEmbed } from '@shared/core/switch-rooms/room-embed';/** The things a room page can show beside its participants. */export type RoomTab = 'chat' | 'resources' | 'configuration';/**- * What a room shown inside another page opens on: its conversation when its- * platform can be drawn inline, otherwise its settings, rather than a notice- * that the conversation lives elsewhere.+ * What a room shown inside another page opens on: its conversation whenever it+ * has one — a group chat here, or a channel on a messaging app, drawn inline or+ * offered as a way out to that app — and its settings only when it has none.*/-export function embeddedRoomTab(bridgeType: string | null): RoomTab {- return bridgeCanEmbed(bridgeType) ? 'chat' : 'configuration';+export function embeddedRoomTab(bridgeType: string | null, consoleChat: boolean): RoomTab {+ return bridgeType !== null || consoleChat ? 'chat' : 'configuration';}/**diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsxindex 8bb5e55c7..5b0d21c8c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/view.tsx@@ -218,7 +218,7 @@ const RoomConversation = observer(function RoomConversation({ roomId }: { roomId/** The side a room shown inside another page opens on, until one is picked. */export function embeddedRoomFallbackTab(roomId: string): RoomTab {- return embeddedRoomTab(switchRoomsStore.roomBridgeTypeById(roomId));+ return embeddedRoomTab(switchRoomsStore.roomBridgeTypeById(roomId), opensAsConsoleChat(roomId));}/**diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsxindex 192227741..f0c643073 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/agent-chats-sections.test.tsx@@ -308,12 +308,14 @@ it('lets the room go when a section is picked or the page is left', async () =>root = createRoot(container);});-it("opens a room whose platform can't be drawn here on its settings", async () => {+it("opens a room on its conversation even where it can't be drawn here, and one with none on its settings", async () => {rooms.list = [room('room-1', 'design'), room('room-2', 'agents-only')];rooms.bridges = { 'room-1': 'slack' };navigation.reset({ ...navigation.params(), room: 'room-1' });await act(async () => root.render(<AgentChats agent={AGENT} />));- expect(embeddedRoom()?.textContent).toBe('Settings of room-1');+ // The layer lays the way out to Slack over the box; the settings are not drawn in it.+ expect(container.querySelector('[data-testid="room-configuration"]')).toBeNull();+ expect(roomEmbedSlotStore.slot?.roomId).toBe('room-1');await act(async () => roomRow('agents-only').click());expect(embeddedRoom()?.textContent).toBe('Settings of room-2');diff --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.tsxindex b7b8f85b3..0ef9f929c 100644--- 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.tsx@@ -1,17 +1,37 @@/**- * 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.+ * Acceptance cases for switch-buddy's setup cards in its Welcome chat: each+ * case renders the cards against a mocked server, asserts what the person+ * sees, and saves a screenshot of it under the app's gitignored+ * `build/acceptance/buddy-onboarding/`.*/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';+import { page } from 'vitest/browser';+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';+import { RpcError } from '@shared/lib/ipc/rpc-error';const listBridges = vi.hoisted(() => vi.fn());const listMyIdentities = vi.hoisted(() => vi.fn());+const getRoomDetail = vi.hoisted(() => vi.fn());+const listAgents = vi.hoisted(() => vi.fn());+const listAgentRooms = vi.hoisted(() => vi.fn());+const listRooms = vi.hoisted(() => vi.fn());+const followConsoleLink = vi.hoisted(() => vi.fn());const createChat = vi.hoisted(() => vi.fn());+const openRoomChannel = vi.hoisted(() => vi.fn());+const shown = vi.hoisted(+ () => [] as { id: string; args: { onClosed?: () => void; bridgeId?: string } }[]+);+const listBridgeTypes = vi.hoisted(() => vi.fn());+const listMessagingApps = vi.hoisted(() => vi.fn());+const administersWorkspaceInScope = vi.hoisted(() => vi.fn());+const timeline = vi.hoisted(() => ({+ messages: [] as { sender: { kind: string }; body: string }[],+ pending: [] as { body: string }[],+ send: () => {},+}));vi.hoisted(() => {window.electronAPI ??= {@@ -23,45 +43,146 @@ vi.hoisted(() => {vi.mock('@renderer/lib/ipc', () => ({rpc: {- workspaces: { listBridges, listMyIdentities, getRoomDetail: vi.fn() },+ workspaces: {+ listBridges,+ listMyIdentities,+ getRoomDetail,+ listAgents,+ listAgentRooms,+ listRooms,+ listBridgeTypes,+ listMessagingApps,+ },chats: { create: createChat },- switchRooms: { openRoomChannel: vi.fn() },+ switchRooms: { openRoomChannel },},events: { on: () => () => {}, emit: () => {} },}));vi.mock('@renderer/lib/modal/modal-provider', async (importOriginal) => ({- ...(await importOriginal<typeof ModalProvider>()),- useShowModal: () => vi.fn(),+ ...(await importOriginal<object>()),+ useShowModal: (id: string) => (args: { onClosed?: () => void; bridgeId?: string }) =>+ shown.push({ id, args }),}));vi.mock('@renderer/features/chats/stores/chats', () => ({- chatTitler: {},chatsStore: {- chat: () => ({ name: 'Welcome', bridgeType: null }),+ userId: 'user-ada',+ chat: (roomId: string) => ({ roomId, name: 'Welcome', bridgeType: null }),+ timelines: { get: () => timeline },add: () => {},- timelines: { get: () => ({ messages: [], pending: [], send: () => {} }) },},+ chatTitler: { created: () => {} },+}));+vi.mock('@renderer/features/deeplinks/console-link-handler', () => ({ followConsoleLink }));+vi.mock('@renderer/features/chats/components/chat-composer', () => ({+ focusComposerWhenOpened: () => {},+}));+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({+ switchServersStore: {+ statusFor: () => ({ user: { name: 'Ada Lovelace', email: null } }),+ activeServerId: 'srv-1',+ servers: [{ id: 'srv-1', name: 'Dev' }],+ },+}));+vi.mock('@renderer/features/switch-servers/workspace-admin', () => ({+ administersWorkspaceInScope,}));import { BuddySetupCards } from '@renderer/features/switch-buddy/buddy-setup-cards';+import { ConnectMessagingAppModal } from '@renderer/features/switch-servers/ConnectMessagingAppModal';+import { appState } from '@renderer/lib/stores/app-state';+import { Dialog } from '@renderer/lib/ui/dialog';+import '@renderer/index.css';-const slack = {- id: 'b-1',- type: 'slack',- displayName: 'Acme',- status: 'active',- isDefault: true,- homeUrl: null,- channelCreationSupported: true,- channelCreationEnabled: true,-};+/** Relative to this file; it must stay inside the workspace for Vite to write it. */+const SHOTS = '../../../../build/acceptance/buddy-onboarding';++function bridge(id: string, type: string, displayName: string): RemoteBridge {+ return {+ id,+ type,+ displayName,+ status: 'active',+ isDefault: false,+ homeUrl: null,+ } as RemoteBridge;+}++const acme = bridge('b-1', 'slack', 'Acme Slack');+const globex = bridge('b-2', 'slack', 'Globex Slack');+const teams = bridge('b-3', 'teams', 'Acme Teams');+const telegram = bridge('b-4', 'telegram', 'example_bot');+const discord = bridge('b-5', 'discord', 'Acme Discord');+const linked = (bridgeId: string) => ({ bridgeId }) as LinkedIdentity;++const noSuchOperation = () =>+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'ChatApiError',+ message: 'No such operation',+ data: { apiCode: 'NO_SUCH_OPERATION' },+ });++const refused = (apiCode: string, message: string) =>+ new RpcError({+ __switchConsoleRpcError: true,+ code: 'ChatApiError',+ message,+ data: { apiCode },+ });++function slackChat(bridgeId: string) {+ return {+ roomId: `room-${bridgeId}`,+ name: null,+ channelType: 'direct',+ bridgeType: 'slack',+ agents: [{ id: 'agent-1' }],+ };+}++/** Bridges whose hand-off the server has made; a resume finds only those. */+let made: Set<string>;++type CreateParams = { bridgeId?: string; requestId: string; resumeOnly?: boolean };+const handoffCalls = () =>+ createChat.mock.calls.map(([params]) => params as CreateParams).filter((p) => !p.resumeOnly);let container: HTMLDivElement | null = null;let root: Root | null = null;+let client: QueryClient;-beforeEach(() => {- listBridges.mockReset();- listMyIdentities.mockReset().mockResolvedValue([{ bridgeId: 'b-1' }]);- createChat.mockReset();+beforeEach(async () => {+ made = new Set();+ listBridges.mockReset().mockResolvedValue([]);+ listMyIdentities.mockReset().mockResolvedValue([]);+ getRoomDetail.mockReset().mockResolvedValue({+ linkedChannelName: '#buddy-ada',+ externalChannelUrl: 'https://slack.example/archives/C123',+ });+ createChat.mockReset().mockImplementation(async (params: CreateParams) => {+ if (params.resumeOnly) {+ if (made.has(params.bridgeId!)) return slackChat(params.bridgeId!);+ throw noSuchOperation();+ }+ made.add(params.bridgeId!);+ return slackChat(params.bridgeId!);+ });+ openRoomChannel.mockReset().mockResolvedValue(undefined);+ listAgents.mockReset().mockResolvedValue([]);+ listAgentRooms.mockReset().mockResolvedValue([]);+ listRooms.mockReset().mockResolvedValue([]);+ followConsoleLink.mockReset();+ listBridgeTypes+ .mockReset()+ .mockResolvedValue([+ { key: 'slack', fields: [], channelCreationSupported: true, directorySearchSupported: true },+ ]);+ listMessagingApps.mockReset().mockResolvedValue({ installable: ['slack'], claimable: [] });+ administersWorkspaceInScope.mockReset().mockReturnValue(true);+ shown.length = 0;+ timeline.messages = [];+ timeline.pending = [];+ await page.viewport(760, 900);});afterEach(async () => {@@ -73,9 +194,11 @@ afterEach(async () => {async function render(): Promise<HTMLElement> {container = document.createElement('div');+ container.style.width = '720px';+ container.style.padding = '16px';document.body.appendChild(container);root = createRoot(container);- const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });await act(async () =>root!.render(<QueryClientProvider client={client}>@@ -83,8 +206,8 @@ async function render(): Promise<HTMLElement> {serverId="srv-1"workspaceId="ws-1"agentId="agent-1"- agentName="buddy"- roomId="room-1"+ agentName="switch-buddy"+ roomId="room-welcome"/></QueryClientProvider>)@@ -94,56 +217,594 @@ async function render(): Promise<HTMLElement> {}async function settle(): Promise<void> {- for (let i = 0; i < 10; i++) await act(async () => await Promise.resolve());+ for (let i = 0; i < 20; i++) await act(async () => await Promise.resolve());+}++async function shot(el: HTMLElement, name: string): Promise<void> {+ // Screenshots catch the settled look, not a button mid-transition.+ for (const node of el.querySelectorAll<HTMLElement>('*')) node.style.transition = 'none';+ await page.screenshot({ path: `${SHOTS}/${name}.png`, element: el });}-function retryButton(el: HTMLElement): HTMLButtonElement {- const found = [...el.querySelectorAll('button')].find((b) => b.textContent === 'Retry');- expect(found, 'no Retry button').toBeDefined();+function findButton(el: HTMLElement, label: string): HTMLButtonElement | undefined {+ return [...el.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes(label)+ );+}++function button(el: HTMLElement, label: string): HTMLButtonElement {+ const found = findButton(el, label);+ expect(found, `no ${label} 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(() => {}));+async function click(el: HTMLElement, label: string): Promise<void> {+ await act(async () => button(el, label).click());+ await settle();+}++describe('switch-buddy setup cards', () => {+ it('(a) fresh install: asks where the team chats, then offers to connect the app picked', async () => {const el = await render();+ expect(el.textContent).toContain('Where does your team chat?');+ expect(findButton(el, 'Connect Slack')).toBeUndefined();+ await shot(el, 'a-fresh-install-choose');- expect(el.textContent).toContain('Couldn’t check Slack');- await act(async () => retryButton(el).click());+ await click(el, 'Channels & DMs');++ expect(el.textContent).toContain('Add Slack to your Switch workspace.');+ expect(findButton(el, 'Connect Slack')).toBeDefined();+ await shot(el, 'a-fresh-install-connect');+ });++ it('(b) already connected and linked: offers the private channel', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ const el = await render();++ expect(el.textContent).toContain('Slack connected · account linked');+ expect(el.textContent).toContain('Continue in a private Slack channel');+ expect(findButton(el, 'Create channel and continue')).toBeDefined();+ expect(el.textContent).not.toContain('Which workspace?');+ await shot(el, 'b-connected-linked-create');+ });++ it('(b) a hand-off already made: done, with a link to the channel', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ made.add('b-1');+ const el = await render();++ expect(el.textContent).toContain('#buddy-ada ready');+ await click(el, 'Open Slack');+ expect(openRoomChannel).toHaveBeenCalledWith({+ serverId: 'srv-1',+ channelUrl: 'https://slack.example/archives/C123',+ });+ expect(handoffCalls()).toHaveLength(0);+ await shot(el, 'b-done-with-channel-link');+ });++ it('(b) after the hand-off: names the agents made since and their rooms, linked here', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ made.add('b-1');+ getRoomDetail.mockResolvedValue({+ linkedChannelName: '#buddy-ada',+ externalChannelUrl: 'https://slack.example/archives/C123',+ createdAt: '2026-01-01T10:00:00Z',+ });+ const agent = (id: string, name: string, ownerId: string, createdAt: string) => ({+ id,+ name,+ displayName: null,+ ownerId,+ createdAt,+ });+ listAgents.mockResolvedValue([+ agent('agent-1', 'switch-buddy', 'user-ada', '2026-01-01T09:00:00Z'),+ agent('agent-old', 'old-helper', 'user-ada', '2026-01-01T09:30:00Z'),+ agent('agent-other', 'someone-elses', 'user-bob', '2026-01-01T11:00:00Z'),+ {+ ...agent('agent-op', 'order-planner', 'user-ada', '2026-01-01T11:00:00Z'),+ displayName: 'Order Planner',+ },+ ]);+ listAgentRooms.mockImplementation(async ({ agentId }: { agentId: string }) =>+ agentId === 'agent-op'+ ? [+ { roomId: 'room-bakery', roomName: 'bakery-orders', archived: false },+ { roomId: 'room-gone', roomName: 'old-room', archived: true },+ { roomId: 'room-default', roomName: 'Town Square', archived: false },+ ]+ : []+ );+ // A bridge's default channel the agent joined is older than the hand-off: not named.+ listRooms.mockResolvedValue([+ { id: 'room-bakery', createdAt: '2026-01-01T11:30:00Z' },+ { id: 'room-gone', createdAt: '2026-01-01T11:30:00Z' },+ { id: 'room-default', createdAt: '2025-12-01T00:00:00Z' },+ ]);+ const el = await render();++ const summary = el.querySelector<HTMLElement>('[data-testid="buddy-created-since"]')!;+ expect(summary.textContent).toBe('Created since: Order Planner · bakery-orders room');+ expect(listAgentRooms).toHaveBeenCalledTimes(1);+ await click(summary, 'Order Planner');+ expect(followConsoleLink).toHaveBeenLastCalledWith('switchdash://open/agent/agent-op');+ await click(summary, 'bakery-orders');+ expect(followConsoleLink).toHaveBeenLastCalledWith('switchdash://open/room/room-bakery');+ await shot(el, 'x-handoff-summary');+ });++ it('(b) after the hand-off with nothing made since: no summary', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ made.add('b-1');+ getRoomDetail.mockResolvedValue({+ linkedChannelName: '#buddy-ada',+ externalChannelUrl: 'https://slack.example/archives/C123',+ createdAt: '2026-01-01T10:00:00Z',+ });+ listAgents.mockResolvedValue([+ {+ id: 'agent-1',+ name: 'switch-buddy',+ displayName: null,+ ownerId: 'user-ada',+ createdAt: '2026-01-01T09:00:00Z',+ },+ ]);+ const el = await render();++ expect(el.textContent).toContain('#buddy-ada ready');+ expect(el.querySelector('[data-testid="buddy-created-since"]')).toBeNull();+ expect(el.textContent).not.toContain('Created since');+ });++ it('(c) linking skipped: the link card, with staying in Console still offered', async () => {+ listBridges.mockResolvedValue([acme]);+ const el = await render();++ expect(el.textContent).toContain('Slack connected');+ expect(el.textContent).toContain('Link your Slack account');+ expect(findButton(el, 'Link account')).toBeDefined();+ expect(findButton(el, 'Continue here in Switch Console')).toBeDefined();+ await shot(el, 'c-linking-skipped');+ });++ it('(d) non-admin: the connect dialog explains admin rights are needed', async () => {+ administersWorkspaceInScope.mockReturnValue(false);+ const modalContainer = document.createElement('div');+ document.body.appendChild(modalContainer);+ const modalRoot = createRoot(modalContainer);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });++ await act(async () =>+ modalRoot.render(+ <QueryClientProvider client={client}>+ <Dialog open onOpenChange={() => {}}>+ <ConnectMessagingAppModal onSuccess={() => {}} onClose={() => {}} onClosed={() => {}} />+ </Dialog>+ </QueryClientProvider>+ )+ );+ await settle();++ const dialog = document.body;+ expect(dialog.textContent).toContain('Connect a messaging app to Dev');+ expect(dialog.textContent).toContain(+ 'Connecting a messaging app requires an admin of this workspace.'+ );+ const dialogEl = document.querySelector('[role="dialog"]') || modalContainer;+ await shot(dialogEl as HTMLElement, 'd-non-admin-connect');++ await act(async () => modalRoot.unmount());+ modalContainer.remove();+ });++ it('(e) channel creation disabled: says why, and offers Try again', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ createChat.mockImplementation(async (params: CreateParams) => {+ if (params.resumeOnly) throw noSuchOperation();+ throw new Error('Channel creation is disabled for this workspace.');+ });+ const el = await render();++ await click(el, 'Create channel and continue');++ expect(el.textContent).toContain('Channel creation is disabled for this workspace.');+ expect(findButton(el, 'Try again')).toBeDefined();+ await shot(el, 'e-channel-creation-disabled');+ });++ it('(f) install cancelled: the connect card says it is not connected yet', async () => {+ const el = await render();+ await click(el, 'Channels & DMs');+ expect(el.textContent).not.toContain('isn’t connected yet');++ await click(el, 'Connect Slack');+ await act(async () => shown[0].args.onClosed!());+ await settle();++ expect(el.textContent).toContain('Slack isn’t connected yet. Try again when you’re ready.');+ expect(findButton(el, 'Connect Slack')).toBeDefined();+ await shot(el, 'f-install-cancelled');+ });++ it('(f) a connection made in the dialog moves on, with no note', async () => {+ const el = await render();+ await click(el, 'Channels & DMs');+ await click(el, 'Connect Slack');+ listBridges.mockResolvedValue([acme]);++ await act(async () => shown[0].args.onClosed!());+ await settle();++ expect(el.textContent).not.toContain('isn’t connected yet');+ expect(el.textContent).toContain('Link your Slack account');+ });++ it('(g) double Continue: one hand-off, the button busy meanwhile', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ let finish!: () => void;+ createChat.mockImplementation((params: CreateParams) => {+ if (params.resumeOnly) {+ return made.has(params.bridgeId!)+ ? Promise.resolve(slackChat(params.bridgeId!))+ : Promise.reject(noSuchOperation());+ }+ return new Promise((resolve) => {+ finish = () => {+ made.add(params.bridgeId!);+ resolve(slackChat(params.bridgeId!));+ };+ });+ });+ const el = await render();++ const continueButton = button(el, 'Create channel and continue');+ await act(async () => {+ continueButton.click();+ continueButton.click();+ });+ await settle();+ await act(async () => button(el, 'Creating channel…').click());await settle();+ expect(handoffCalls()).toHaveLength(1);+ expect(button(el, 'Creating channel…').disabled).toBe(true);+ await shot(el, 'g-double-continue');++ await act(async () => finish());+ await settle();+ expect(el.textContent).toContain('#buddy-ada ready');+ expect(handoffCalls()).toHaveLength(1);+ });++ it('(h) several linked workspaces: asks which, and hands off on the one chosen', async () => {+ listBridges.mockResolvedValue([acme, globex]);+ listMyIdentities.mockResolvedValue([linked('b-1'), linked('b-2')]);+ const el = await render();++ expect(el.textContent).toContain('Which workspace?');+ expect(button(el, 'Acme Slack').getAttribute('aria-pressed')).toBe('true');+ await click(el, 'Globex Slack');+ expect(button(el, 'Globex Slack').getAttribute('aria-pressed')).toBe('true');+ expect(button(el, 'Acme Slack').getAttribute('aria-pressed')).toBe('false');+ await shot(el, 'h-multiple-workspaces');++ await click(el, 'Create channel and continue');++ expect(handoffCalls()).toEqual([+ expect.objectContaining({ bridgeId: 'b-2', requestId: 'buddy-handoff:agent-1:b-2' }),+ ]);+ expect(el.textContent).toContain('#buddy-ada ready');+ expect(getRoomDetail).toHaveBeenCalledWith({ workspaceId: 'ws-1', roomId: 'room-b-2' });+ });++ it('(h) several workspaces, none linked: links the one chosen, then hands off there', async () => {+ listBridges.mockResolvedValue([acme, globex]);+ const el = await render();++ expect(el.textContent).toContain('Which workspace?');+ expect(button(el, 'Acme Slack').getAttribute('aria-pressed')).toBe('true');+ await click(el, 'Globex Slack');+ expect(button(el, 'Globex Slack').getAttribute('aria-pressed')).toBe('true');+ expect(el.textContent).toContain('So I recognise you in Globex Slack.');+ await shot(el, 'h2-choose-workspace-before-link');++ await click(el, 'Link account');+ expect(shown.at(-1)).toMatchObject({ id: 'claimIdentityModal', args: { bridgeId: 'b-2' } });++ listMyIdentities.mockResolvedValue([linked('b-2')]);+ await act(async () => client.invalidateQueries({ queryKey: ['my-switch-identities', 'ws-1'] }));+ await settle();+ await click(el, 'Create channel and continue');++ expect(handoffCalls()).toEqual([expect.objectContaining({ bridgeId: 'b-2' })]);+ });++ it('(h) a choice made before linking stays chosen once both are linked', async () => {+ listBridges.mockResolvedValue([acme, globex]);+ const el = await render();+ await click(el, 'Globex Slack');++ listMyIdentities.mockResolvedValue([linked('b-1'), linked('b-2')]);+ await act(async () => client.invalidateQueries({ queryKey: ['my-switch-identities', 'ws-1'] }));+ await settle();++ expect(button(el, 'Globex Slack').getAttribute('aria-pressed')).toBe('true');+ await click(el, 'Create channel and continue');+ expect(handoffCalls()).toEqual([expect.objectContaining({ bridgeId: 'b-2' })]);+ });++ for (const { platform, unit, a, b } of [+ { platform: 'slack', unit: 'workspace', a: acme, b: globex },+ {+ platform: 'discord',+ unit: 'server',+ a: discord,+ b: bridge('b-6', 'discord', 'Globex Discord'),+ },+ ]) {+ it(`(h) ${platform}: one linked and one not, both are choices, each in its own state`, async () => {+ listBridges.mockResolvedValue([a, b]);+ listMyIdentities.mockResolvedValue([linked(a.id)]);+ const el = await render();++ expect(el.textContent).toContain(`Which ${unit}?`);+ expect(button(el, a.displayName).getAttribute('aria-pressed')).toBe('true');+ expect(findButton(el, b.displayName)).toBeDefined();+ expect(findButton(el, 'Create channel and continue')).toBeDefined();++ await click(el, b.displayName);+ expect(button(el, b.displayName).getAttribute('aria-pressed')).toBe('true');+ expect(el.textContent).toContain(`So I recognise you in ${b.displayName}.`);+ expect(findButton(el, 'Create channel and continue')).toBeUndefined();+ await shot(el, `h3-mixed-${platform}`);+ await click(el, 'Link account');+ expect(shown.at(-1)).toMatchObject({ id: 'claimIdentityModal', args: { bridgeId: b.id } });++ await click(el, a.displayName);+ expect(findButton(el, 'Link account')).toBeUndefined();+ await click(el, 'Create channel and continue');+ expect(handoffCalls()).toEqual([expect.objectContaining({ bridgeId: a.id })]);+ });+ }++ it('(i) invite or post failure: Try again, then done', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ createChat.mockImplementationOnce(async () => {+ throw noSuchOperation();+ });+ createChat.mockImplementationOnce(async () => {+ throw new Error('Could not invite switch-buddy to the channel.');+ });+ const el = await render();++ await click(el, 'Create channel and continue');+ expect(el.textContent).toContain('Could not invite switch-buddy to the channel.');+ await shot(el, 'i-invite-failure');++ await click(el, 'Try again');++ expect(el.textContent).toContain('#buddy-ada ready');+ expect(findButton(el, 'Open Slack')).toBeDefined();+ await shot(el, 'i-retry-done');+ });++ it('(k) Console only: continuing here, with the chat apps one click away', async () => {+ timeline.messages = [+ { sender: { kind: 'human' }, body: 'I’ll stay in Switch Console for now.' },+ ];+ const el = await render();++ expect(el.textContent).toContain('Continuing here in Switch Console.');+ expect(findButton(el, 'Connect a chat app')).toBeDefined();+ expect(el.textContent).not.toContain('Where does your team chat?');+ await shot(el, 'k-console-only');+ });++ it('(l) done without a channel link: says to find it in Slack', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ getRoomDetail.mockResolvedValue({ linkedChannelName: null, externalChannelUrl: null });+ made.add('b-1');+ const el = await render();++ expect(el.textContent).toContain('Private Slack channel ready');+ expect(el.textContent).toContain('Couldn’t get a link to the Slack channel. Find it in Slack.');+ expect(findButton(el, 'Open Slack')).toBeUndefined();+ await shot(el, 'x-done-without-link');+ });++ it('(m) Teams linked: guides adding the app and inviting the buddy', async () => {+ listBridges.mockResolvedValue([teams]);+ listMyIdentities.mockResolvedValue([linked('b-3')]);+ const el = await render();++ expect(el.textContent).toContain('Continue in Microsoft Teams');+ expect(el.textContent).toContain('!invite-agent @switch-buddy');+ expect(el.textContent).toContain(+ 'Then mention switch-buddy with a short note on what you work on.'+ );+ expect(el.textContent).not.toContain('I’ll answer');+ await shot(el, 'x-teams-guide');+ });++ it('(n) Telegram linked: guides inviting the buddy in the group', async () => {+ listBridges.mockResolvedValue([telegram]);+ listMyIdentities.mockResolvedValue([linked('b-4')]);+ const el = await render();++ expect(el.textContent).toContain('Continue in Telegram');+ expect(el.textContent).toContain('/invite_agent @switch-buddy');+ expect(el.textContent).toContain("reply to the bot's message");+ expect(el.textContent).toContain('mention switch-buddy in that reply');+ expect(el.textContent).not.toContain('I’ll answer');+ await shot(el, 'x-telegram-guide');+ });++ it('(o) Discord linked: continues in a private Discord channel, then opens it', async () => {+ listBridges.mockResolvedValue([discord]);+ listMyIdentities.mockResolvedValue([linked('b-5')]);+ getRoomDetail.mockResolvedValue({+ linkedChannelName: '#dm-ada-switch-buddy',+ externalChannelUrl: 'https://discord.com/channels/1/2',+ });+ const el = await render();++ expect(el.textContent).toContain('Discord connected · account linked');+ expect(el.textContent).toContain('Continue in a private Discord channel');+ await shot(el, 'x-discord-create');++ await click(el, 'Create channel and continue');++ expect(handoffCalls()).toEqual([+ expect.objectContaining({ bridgeId: 'b-5', requestId: 'buddy-handoff:agent-1:b-5' }),+ ]);+ expect(el.textContent).toContain('#dm-ada-switch-buddy ready');+ await click(el, 'Open Discord');+ expect(openRoomChannel).toHaveBeenCalledWith({+ serverId: 'srv-1',+ channelUrl: 'https://discord.com/channels/1/2',+ });+ await shot(el, 'x-discord-done');+ });++ it('(o) Slack and Discord linked, handed off on Discord: waits for both before offering a channel', async () => {+ listBridges.mockResolvedValue([acme, discord]);+ listMyIdentities.mockResolvedValue([linked('b-1'), linked('b-5')]);+ let answerDiscord: (chat: ReturnType<typeof slackChat>) => void = () => {};+ createChat.mockImplementation((params: CreateParams) => {+ if (params.bridgeId === 'b-5')+ return new Promise((resolve) => {+ answerDiscord = resolve;+ });+ return Promise.reject(noSuchOperation());+ });+ getRoomDetail.mockResolvedValue({+ linkedChannelName: '#dm-ada-switch-buddy',+ externalChannelUrl: 'https://discord.com/channels/1/2',+ });+ const el = await render();++ expect(el.textContent).toContain('Finishing setup');+ expect(el.textContent).not.toContain('Continue in a private');+ expect(findButton(el, 'Create channel and continue')).toBeUndefined();++ await act(async () => answerDiscord({ ...slackChat('b-5'), bridgeType: 'discord' }));+ await settle();++ expect(el.textContent).toContain('#dm-ada-switch-buddy ready');+ expect(findButton(el, 'Open Discord')).toBeDefined();+ expect(handoffCalls()).toHaveLength(0);+ });++ it('(p) an auto-selected Slack whose resume read fails: says so, and Retry reads it again', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([linked('b-1')]);+ createChat.mockImplementationOnce(async () => {+ throw new Error('down');+ });+ const el = await render();++ expect(el.textContent).toContain('Couldn’t check Slack');+ await shot(el, 'x-auto-check-failed');+ await click(el, 'Retry');+expect(createChat).toHaveBeenCalledTimes(2);expect(el.textContent).not.toContain('Couldn’t check');+ expect(findButton(el, 'Create channel and continue')).toBeDefined();});- it('shows a failed first read of the chat apps, and Retry reads them again', async () => {- listBridges.mockRejectedValueOnce(new Error('down')).mockResolvedValue([]);+ it('(q) a failed first read of the chat apps: says so, and Retry reads them again', async () => {+ listBridges.mockReset().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();+ await shot(el, 'x-apps-check-failed');+ await click(el, 'Retry');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' }]);+ it('(r) more than one account linked: the server reason, unlink guidance, and Retry', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([+ { bridgeId: 'b-1', externalUserId: 'U1' } as LinkedIdentity,+ { bridgeId: 'b-1', externalUserId: 'U9' } as LinkedIdentity,+ ]);+ const reason =+ 'Your Switch account is linked to 2 accounts on Acme Slack. Unlink the ones you no longer use in your Switch settings, then try again.';+ createChat.mockImplementation(async (params: CreateParams) => {+ if (params.resumeOnly) throw noSuchOperation();+ throw refused('ACCOUNTS_AMBIGUOUS', reason);+ });+ const navigate = vi.spyOn(appState.navigation, 'navigate').mockImplementation(() => {});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");+ await click(el, 'Create channel and continue');++ expect(el.textContent).toContain(reason);+ expect(el.textContent).toContain('Unlink the Slack account you no longer use, then retry.');+ expect(findButton(el, 'Start again')).toBeUndefined();+ await shot(el, 'x-accounts-ambiguous');+ await click(el, 'Manage linked accounts');+ expect(navigate).toHaveBeenCalledWith('settings', { tab: 'messaging-apps' });+ navigate.mockRestore();++ await click(el, 'Retry');+ expect(findButton(el, 'Create channel and continue')).toBeDefined();});- it('asks them to reply to the bot on Telegram', async () => {- listBridges.mockResolvedValue([{ ...slack, type: 'telegram' }]);+ it('(s) linked account changed: the server reason, and a fresh hand-off for the new account', async () => {+ listBridges.mockResolvedValue([acme]);+ listMyIdentities.mockResolvedValue([+ { bridgeId: 'b-1', externalUserId: 'U2' } as LinkedIdentity,+ ]);+ const reason =+ 'This chat was started with a different linked account than the one now linked. Start a new chat.';+ const restartId = 'buddy-handoff:agent-1:b-1:U2';+ let finish!: () => void;+ createChat.mockImplementation((params: CreateParams) => {+ if (params.resumeOnly) {+ if (params.requestId === 'buddy-handoff:agent-1:b-1')+ return Promise.reject(refused('LINKED_ACCOUNT_CHANGED', reason));+ return made.has(params.requestId)+ ? Promise.resolve(slackChat('b-1'))+ : Promise.reject(noSuchOperation());+ }+ return new Promise((resolve) => {+ finish = () => {+ made.add(params.requestId);+ resolve(slackChat('b-1'));+ };+ });+ });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');+ expect(el.textContent).toContain(reason);+ expect(findButton(el, 'Retry')).toBeUndefined();+ await shot(el, 'x-account-changed');++ const restart = button(el, 'Start again with your new account');+ await act(async () => {+ restart.click();+ restart.click();+ });+ await settle();+ expect(button(el, 'Creating channel…').disabled).toBe(true);+ await act(async () => finish());+ await settle();++ expect(handoffCalls()).toHaveLength(1);+ expect(handoffCalls()[0]).toMatchObject({ bridgeId: 'b-1', requestId: restartId });+ expect(el.textContent).toContain('#buddy-ada ready');});});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-request-order.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-request-order.test.tsxnew file mode 100644index 000000000..8a37e6fba--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/chat-request-order.test.tsx@@ -0,0 +1,170 @@+/**+ * An agent's question form reads after the text its turn posted before it,+ * not above it under the person's message that started the turn.+ */+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import { ChatTimelineView } from '@renderer/features/chats/components/chat-timeline';+import {+ type ActivityApi,+ AgentActivities,+} from '@renderer/features/chats/stores/chat-activity-store';+import {+ ChatTimeline,+ type TimelineApi,+} from '@renderer/features/chats/stores/chat-timeline-store';+import type { ChatActivityItem, ChatApproval } from '@shared/core/chats/activity';+import type { ChatMessage } from '@shared/core/chats/chats';++vi.mock('@renderer/features/chats/stores/chats', () => ({ chatsStore: { userId: 'me' } }));++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++function item(itemId: string, second: number, status: string, title = ''): ChatActivityItem {+ const at = `2026-01-01T00:00:${String(second).padStart(2, '0')}Z`;+ return {+ agentId: 'agent-a',+ sessionId: 's1',+ turnId: 't1',+ itemId,+ kind: itemId === 'turn' ? 'turn' : 'tool-activity',+ revision: 1,+ status,+ title,+ text: '',+ commandId: null,+ roomId: 'room-1',+ threadId: null,+ messageId: 'm1',+ occurredAt: at,+ createdAt: at,+ updatedAt: at,+ };+}++const question: ChatApproval = {+ agentId: 'agent-a',+ sessionId: 's1',+ requestId: 'req-1',+ turnId: 't1',+ kind: 'questions',+ roomId: 'room-1',+ threadId: null,+ title: 'Question from the agent',+ detail: null,+ options: [],+ questions: [+ {+ id: 'q1',+ title: 'Agent',+ prompt: 'Which agent would you like me to set up?',+ options: [+ { id: 'a', label: 'bakery-orders', description: null },+ { id: 'b', label: 'bakery-pantry', description: null },+ ],+ multiSelect: false,+ allowCustomAnswer: false,+ },+ ],+ state: 'open',+ expiresAt: null,+ answer: null,+ answers: null,+ answeredBy: null,+ answeredAt: null,+};++function message(seq: number, second: number, body: string, agentId: string | null): ChatMessage {+ return {+ messageId: `m${seq}`,+ seq,+ roomId: 'room-1',+ sentAt: `2026-01-01T00:00:${String(second).padStart(2, '0')}Z`,+ sender: agentId+ ? { clientId: 'c-a', name: 'buddy', kind: 'agent', agentId, userId: null }+ : { clientId: 'c-me', name: 'Maya', kind: 'human', agentId: null, userId: 'me' },+ source: 'console',+ body,+ format: null,+ threadRootId: null,+ attachments: [],+ clientTxn: null,+ namedAgentIds: [],+ namedUserIds: [],+ mentions: [],+ threadReplyCount: 0,+ threadLastReplySeq: null,+ };+}++it('shows the question form after the text the turn posted, in reading order', async () => {+ // The turn ran a tool before it posted, so the turn itself shows under the person's message.+ const items = [item('turn', 1, 'running'), item('tool1', 2, 'completed', 'Bash ls')];+ const api: ActivityApi = {+ resolve: async () => ({+ kind: 'session',+ target: { kind: 'local' } as never,+ hostAgentKey: 'agent-local',+ sessionId: 's1',+ }),+ reasoning: async () => null,+ watchPlacements: () => () => {},+ roomActivity: async () => ({ items, approvals: [question] }),+ roomMessages: () => [],+ control: vi.fn(),+ retrySupport: async () => 'no',+ answerApproval: async () => {+ throw new Error('unused');+ },+ };+ const activity = new AgentActivities(api, { getItem: () => null, setItem: () => {} }).acquire(+ 'server',+ 'tenant',+ 'room-1',+ 'agent-a'+ );+ await vi.waitFor(() => expect(activity.turns().size).toBe(1));+ const timeline = new ChatTimeline('room-1', {} as TimelineApi);+ timeline.apply(message(1, 0, 'I run a small bakery', null));+ timeline.apply(message(2, 3, 'Here are two agents that could help.', 'agent-a'));+ timeline.apply(message(3, 4, 'Pick one below.', 'agent-a'));++ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () =>+ root!.render(+ <QueryClientProvider client={new QueryClient()}>+ <ChatTimelineView+ serverId="server"+ timeline={timeline}+ agents={[]}+ people={[]}+ activities={[activity]}+ onReply={() => {}}+ />+ </QueryClientProvider>+ )+ );++ const text = container.textContent ?? '';+ expect(text).toContain('Which agent would you like me to set up?');+ // The turn's work log still sits under the person's message, above the agent's text.+ const workLog = container.querySelector('[data-turn-id="t1"]')!;+ expect(text.indexOf(workLog.textContent ?? '')).toBeLessThan(text.indexOf('Here are two agents'));+ expect(workLog.textContent).not.toContain('Which agent would you like me to set up?');+ expect(text.indexOf('Pick one below.')).toBeLessThan(+ text.indexOf('Which agent would you like me to set up?')+ );+ expect(text.match(/Which agent would you like me to set up\?/g)).toHaveLength(1);+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/room-info-owner.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-info-owner.test.tsxnew file mode 100644index 000000000..1d674a90c--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/room-info-owner.test.tsx@@ -0,0 +1,51 @@+/**+ * The room's info names its owner when it has one, and leaves the row out+ * when it has none (a room an agent created) rather than showing a dash.+ */+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, expect, it, vi } from 'vitest';+import type { RemoteRoomDetail } from '@shared/core/switch-servers/switch-servers';++vi.mock('@renderer/lib/ipc', () => ({ events: { on: () => () => {} }, rpc: {} }));++import { RoomInfoSection } from '@renderer/features/switch-rooms/room-settings-sections';++let container: HTMLDivElement | null = null;+let root: Root | null = null;++afterEach(async () => {+ if (root) await act(async () => root!.unmount());+ container?.remove();+ container = null;+ root = null;+});++const room = (ownerName: string | null) =>+ ({+ createdAt: '2026-01-01T00:00:00Z',+ ownerName,+ bridgeDisplayName: 'Slack',+ isConsoleChat: false,+ linkedChannelName: 'bakery-orders',+ externalChannelId: null,+ transportRoomId: null,+ }) as RemoteRoomDetail;++async function labels(ownerName: string | null): Promise<string[]> {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ await act(async () => root!.render(<RoomInfoSection room={room(ownerName)} />));+ return [...container.querySelectorAll('dt')].map((dt) => dt.textContent ?? '');+}++it('names the owner when the room has one', async () => {+ expect(await labels('Maya Baker')).toEqual(['Created', 'Owner', 'Messaging app', 'Channel']);+ expect(container!.textContent).toContain('Maya Baker');+});++it('leaves the owner out, not a dash, when the room has none', async () => {+ expect(await labels(null)).toEqual(['Created', 'Messaging app', 'Channel']);+ expect(container!.textContent).not.toContain('—');+});diff --git a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.tsindex 335b836e1..142898c3c 100644--- a/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts+++ b/console/apps/switch-console-desktop/src/renderer/tests/chat-activity.test.ts@@ -4,6 +4,7 @@ import {foldTurnEndNotices,groupTurns,isThinking,+ placeRequests,placeTurns,toolState,type TurnActivity,@@ -88,6 +89,50 @@ function turnOf(items: ChatActivityItem[], status: TurnActivity['status']): Turn};}+describe('placeRequests', () => {+ const at = (minute: number) => `2026-01-01T00:0${minute}:00Z`;+ const said = (messageId: string, agentId: string | null, minute: number): ChatMessage =>+ ({+ messageId,+ body: messageId,+ sentAt: at(minute),+ sender: { kind: agentId ? 'agent' : 'human', agentId, clientId: agentId ?? 'me' },+ }) as unknown as ChatMessage;+ const withRequests = (requests: ChatApproval[]): TurnActivity => ({+ ...turnOf([], 'running'),+ requests,+ });+ const ids = (placed: Map<string, ChatApproval[]>) =>+ Object.fromEntries([...placed].map(([key, list]) => [key, list.map((r) => r.requestId)]));++ it('shows an open request after the text its turn has posted so far', () => {+ const turn = withRequests([approval('t1')]);+ const messages = [said('q1', null, 0), said('r1', 'helper', 1), said('r2', 'helper', 2)];+ expect(ids(placeRequests(messages, 'helper', new Map([['q1', turn]]), 'q1', turn))).toEqual({+ r2: ['req-t1'],+ });+ });++ it('keeps an answered request above the text posted after the answer', () => {+ const turn = withRequests([approval('t1', { state: 'answered', answeredAt: at(2) })]);+ const messages = [said('q1', null, 0), said('r1', 'helper', 1), said('r2', 'helper', 3)];+ expect(ids(placeRequests(messages, 'helper', new Map([['q1', turn]]), 'q1', turn))).toEqual({+ r1: ['req-t1'],+ });+ });++ it('stops at the message that starts the agent’s next turn', () => {+ const turn = withRequests([approval('t1')]);+ const next = { ...withRequests([]), turnId: 't2' };+ const messages = [said('q1', null, 0), said('q2', null, 1), said('r2', 'helper', 2)];+ const bound = new Map([+ ['q1', turn],+ ['q2', next],+ ]);+ expect(ids(placeRequests(messages, 'helper', bound, 'q1', turn))).toEqual({ q1: ['req-t1'] });+ });+});+describe('placeTurns', () => {const said = (messageId: string, agentId: string | null): ChatMessage =>({diff --git a/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.test.ts b/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.test.tsindex 0ae0832ea..fa4a3fcdd 100644--- a/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.test.ts+++ b/console/apps/switch-console-desktop/src/shared/core/deeplinks/console-links.test.ts@@ -65,13 +65,19 @@ describe('parseConsoleLink', () => {});describe("switch-buddy's instructions", () => {- const instructions = readFileSync(- join(- __dirname,- '../../../../../../../core/switch_core/official_templates/switch-buddy/AGENT.md'- ),- 'utf8'- );+ // AGENT.md, plus the playbook it points at for the rarer pages.+ const instructions = ['AGENT.md', 'PLAYBOOK.md']+ .map((name) =>+ readFileSync(+ join(+ __dirname,+ '../../../../../../../core/switch_core/official_templates/switch-buddy',+ name+ ),+ 'utf8'+ )+ )+ .join('\n');const links = [...instructions.matchAll(/switchdash:\/\/open\/[^\s`)|]+/g)].map((match) =>match[0].replace(/<[a-z-]+>/g, 'sample-id'));diff --git a/console/packages/plugins/src/switch-skill/SKILL.md b/console/packages/plugins/src/switch-skill/SKILL.mdindex 691a2851d..6146a562b 100644--- a/console/packages/plugins/src/switch-skill/SKILL.md+++ b/console/packages/plugins/src/switch-skill/SKILL.md@@ -312,9 +312,10 @@ wrote.## Questions and approvalsNative question forms can be answered in the Console or from the room. The-room presents one question at a time; each addressed reply answers that-question. A form with several questions stays open until all questions have-answers. Wait for the tool to return before acting on the answers.+room shows the whole form as one card. A form of one single-choice question+gets buttons on Slack and Discord; any other form is answered by typing the+card's handle and an answer to every question in one reply, as the card shows.+Wait for the tool to return before acting on the answers.Approvals reach the room on every host. Native question forms do not: ClaudeCode, OpenCode and Antigravity have them, while Codex and Cursor sessionsdiff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex f8ccdab1e..d3e5147e0 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -43,7 +43,11 @@ from switch_core.db.models import ()from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStore-from switch_core.db.stores.external_user_store import CodeNotAccepted, NoSuchLink+from switch_core.db.stores.external_user_store import (+ CodeNotAccepted,+ ExternalUserStore,+ NoSuchLink,+)from switch_core.db.stores.session_activity_store import (RETRYABLE_TURN_STATUSES,AgentSessionActivityStore,@@ -55,7 +59,7 @@ from switch_core.platform_access import administers_on_recordfrom switch_core.transport import RoomRefif TYPE_CHECKING:- from sqlalchemy.ext.asyncio import AsyncSession+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.clients.command_consumer import CommandConsumerfrom switch_core.clients.room_meta import RoomMeta@@ -1436,88 +1440,94 @@ async def _manage_authority(async def _cmd_link_account(client: AgentRecipient, room: RoomRef, event: CommandEvent, _is_direct: bool) -> None:- """Confirm a link to a Switch user with the code Console showed (CHOO-3881).+ """Confirm a link to a Switch user with the code Console showed (CHOO-3881)."""+ host = cast("CommandConsumer", client)+ async with host.session_factory() as session:+ account = await _sender_account(host, session, event)+ reply = await link_account_reply(+ host.session_factory,+ host._external_user_store,+ host._user_store,+ account,+ event.args or "",+ )+ await _reply(host, room, event, reply)+++async def link_account_reply(+ session_factory: async_sessionmaker[AsyncSession],+ external_user_store: ExternalUserStore,+ user_store: UserStore,+ account: ExternalUser | None,+ args: str,+) -> str:+ """Redeem a `link-account` code for `account` and say what happened.Only the Switch user was shown the code, and the platform says whichaccount posted it, so a match proves one person holds both. A code postedfrom any other account matches nothing, which is why posting it in a busy- channel gives nothing away.+ channel gives nothing away. The collaboration bridge calls this directly+ for a channel that is not a Switch room, so linking never creates one."""- host = cast("CommandConsumer", client)- code = (event.args or "").strip()+ code = args.strip()if not code:- await _reply(- host,- room,- event,+ return ("Usage: `!link-account CODE`, with the code Switch Console showed "- "you when you linked this account.",+ "you when you linked this account.")- return-- # Replies wait until the session has closed: a rejected code may have- # locked the request it was checked against, and nobody should wait on- # that while a reply is written.- refusal: str | None = None- async with host.session_factory() as session:- account = await _sender_account(host, session, event)- if account is None:- refusal = (- "⚠️ Only a chat account can confirm a link to itself, by posting "- "the code from that account."+ if account is None:+ return (+ "⚠️ Only a chat account can confirm a link to itself, by posting "+ "the code from that account."+ )+ # The reply is written by the caller after this session has closed: a+ # rejected code may have locked the request it was checked against, and+ # nobody should wait on that while a reply is written.+ async with session_factory() as session:+ try:+ request = await external_user_store.redeem_link_code(+ session, account, code, user_store)- else:- try:- request = await host._external_user_store.redeem_link_code(- session, account, code, host._user_store- )- except CodeNotAccepted:- refusal = (- "⚠️ That code doesn't match a link waiting for this account, "- "or it has expired. Get a new code in Switch Console, and post "- "it from the account you're linking."- )- else:- user_id = request.user_id- linked = await host._user_store.get(session, user_id)- bridge = await session.get(CollaborationBridge, account.bridge_id)- # Both are held by foreign keys from the rows just written.- if linked is None or bridge is None:- raise RuntimeError(- f"Confirmed a link for user {user_id} on bridge "- f"{account.bridge_id}, but could not read either back"- )- name, platform = linked.name, bridge.display_name- username = account.external_username- await record_audit_event(- session,- tenant_id=account.tenant_id,- actor_user_id=user_id,- action=AuditAction.BRIDGE_IDENTITY_CLAIMED,- target_type="external_user",- target_id=account.id,- details={- "bridge_id": account.bridge_id,- "user_id": user_id,- "by": "code",- },- )- await session.commit()- if refusal is not None:- await _reply(host, room, event, refusal)- return+ except CodeNotAccepted:+ return (+ "⚠️ That code doesn't match a link waiting for this account, "+ "or it has expired. Get a new code in Switch Console, and post "+ "it from the account you're linking."+ )+ user_id = request.user_id+ linked = await user_store.get(session, user_id)+ bridge = await session.get(CollaborationBridge, account.bridge_id)+ # Both are held by foreign keys from the rows just written.+ if linked is None or bridge is None:+ raise RuntimeError(+ f"Confirmed a link for user {user_id} on bridge "+ f"{account.bridge_id}, but could not read either back"+ )+ name, platform = linked.name, bridge.display_name+ username = account.external_username+ await record_audit_event(+ session,+ tenant_id=account.tenant_id,+ actor_user_id=user_id,+ action=AuditAction.BRIDGE_IDENTITY_CLAIMED,+ target_type="external_user",+ target_id=account.id,+ details={+ "bridge_id": account.bridge_id,+ "user_id": user_id,+ "by": "code",+ },+ )+ await session.commit()# Names the Switch user, so whoever posted it sees who the account is now# recognised as, and how to take that back if it is not them. "The way you# ran this" because platforms differ in how a command reaches Switch: typed# with `!`, as a slash command, or with the app mentioned.- await _reply(- host,- room,- event,+ return (f"✅ Linked this {platform} account ({username}) to Switch user "f"**{name}**. If that isn't you, run `unlink-account {name}` the way "- "you ran this command.",+ "you ran this command.")diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex b9c3a1f9d..430c340c8 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -81,6 +81,7 @@ from switch_core.bridges.collaboration.adapter import ()from switch_core.bridges.resource.service import ResourceServicefrom switch_core.budgets import BudgetGuard+from switch_core.chats.service import ChatErrorfrom switch_core.clients.actor import AgentActor, SystemActorfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.admin_messages import (@@ -376,6 +377,9 @@ class AgentCore:# 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 = None+ # Raises the ChatError `_member_adder` would refuse that person with:+ # (tenant_id, user_id). Wired with it.+ _member_join_check: Callable[[str, str], Awaitable[None]] | None = Nonedef __init__(self,@@ -823,9 +827,12 @@ class AgentCore:self._room_agents_listener = listenerdef set_member_adder(- self, adder: Callable[[str, User, str, str], Awaitable[Room]]+ self,+ adder: Callable[[str, User, str, str], Awaitable[Room]],+ join_check: Callable[[str, str], Awaitable[None]],) -> None:self._member_adder = adder+ self._member_join_check = join_checkdef set_agent_profile_listener(self, listener: Callable[[str, str], Awaitable[None]]@@ -2976,8 +2983,14 @@ class AgentCore:raise ValueError(f"Agent {agent_id} has no owner, so there is no one to include")- if self._member_adder is None:+ if self._member_adder is None or self._member_join_check is None:raise RuntimeError("Adding people to rooms is not wired on this server")+ try:+ await self._member_join_check(agent.tenant_id, owner.id)+ except ChatError as e:+ raise ValueError(+ f"include_owner: your owner {owner.name} cannot join: {e.message}"+ ) from eif (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 "@@ -3033,9 +3046,24 @@ class AgentCore:raise RuntimeError(f"Room service error: {str(e)}") from eif 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- )+ try:+ await self._member_adder(+ result.room.tenant_id, owner, result.room.id, owner.id+ )+ except Exception as e:+ # A room without the owner it was made for is not what was asked for.+ try:+ await self.room_service.delete_room(+ result.room.id, retire_channel=False+ )+ except Exception as cleanup:+ raise cleanup from e+ if isinstance(e, ChatError):+ raise ValueError(+ f"Room not created: your owner {owner.name} could not be "+ f"added: {e.message}"+ ) from e+ raisereturn resultasync def _resolve_group_name(diff --git a/core/switch_core/bridges/collaboration/adapter.py b/core/switch_core/bridges/collaboration/adapter.pyindex 11b33f298..b900c0110 100644--- a/core/switch_core/bridges/collaboration/adapter.py+++ b/core/switch_core/bridges/collaboration/adapter.py@@ -223,6 +223,11 @@ class RequestCard:# nobody is not the same as a redraw of one already asked, and only the# first is worth saying out loud.notify_unreachable: bool = False+ # The request's turn was asked at the channel root, so a card threaded+ # under that message is somewhere the channel does not look. Set on the+ # first post only; an adapter that can also show a thread reply in the+ # channel (Slack's `reply_broadcast`) does.+ asked_at_root: bool = FalseRichContent = TurnActivity | RequestCarddiff --git a/core/switch_core/bridges/collaboration/collaboration_core.py b/core/switch_core/bridges/collaboration/collaboration_core.pyindex 9747a747d..334f497dd 100644--- a/core/switch_core/bridges/collaboration/collaboration_core.py+++ b/core/switch_core/bridges/collaboration/collaboration_core.py@@ -18,7 +18,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.aliases import AliasError, validate_alias_formatfrom switch_core.attachments import parse_attachment_group-from switch_core.bridges.agent.commands import stop_control_frame+from switch_core.bridges.agent.commands import link_account_reply, stop_control_framefrom switch_core.bridges.collaboration.adapter import (AgentIdentity,AgentPresentation,@@ -57,6 +57,7 @@ from switch_core.db.stores.room_store import (LINKED_CHANNEL_NAME_KEY,RoomStore,)+from switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import tenant_of_roomfrom switch_core.logging_context import log_contextfrom switch_core.observability.catalogue import (@@ -1350,6 +1351,11 @@ class CollaborationCore:async def _handle_inbound_command(self, cmd: InboundCommand) -> None:room_ids = self._channel_to_room.get(cmd.channel_id)+ if room_ids is None and cmd.command == "link-account":+ # Linking an account is about the person, not the channel: answer+ # it here so a channel that isn't a Switch room doesn't become one.+ await self._link_account_outside_room(cmd)+ returnif room_ids is None:lock = self._channel_locks.setdefault(cmd.channel_id, asyncio.Lock())async with lock:@@ -1444,6 +1450,21 @@ class CollaborationCore:finally:self._pending_message_maps.pop(event_id, None)+ async def _link_account_outside_room(self, cmd: InboundCommand) -> None:+ account = await self.ensure_external_user(+ external_user_id=cmd.sender_id, external_username=cmd.sender_name+ )+ reply = await link_account_reply(+ self._session_factory,+ self._external_user_store,+ UserStore(),+ account,+ cmd.args,+ )+ await self._adapter.admin_message(+ cmd.channel_id, reply, cmd.root_id or cmd.message_ref+ )+async def _handle_agent_joined_channel(self, join: InboundAgentJoin) -> None:lock = self._channel_locks.setdefault(join.channel_id, asyncio.Lock())async with lock:@@ -1780,7 +1801,19 @@ class CollaborationCore:(the resolver logs them); the on_user_joined callback or the inboundmessage path picks them up later."""resolved = await self.resolve_external_user_id_map(user_names)- for ext_id in resolved.values():+ await self.ensure_external_users_in_room(+ room_id, transport_room_id, list(resolved.values())+ )++ async def ensure_external_users_in_room(+ self,+ room_id: str,+ transport_room_id: str,+ external_user_ids: list[str],+ ) -> None:+ """`ensure_users_in_room` for accounts already known by id, as for a+ linked identity: no name is resolved, since two accounts can share one."""+ for ext_id in external_user_ids:async with self._session_factory() as session:ext_user = await self._external_user_store.get_by_external_id(session, self._bridge_id, ext_iddiff --git a/core/switch_core/bridges/collaboration/discord/adapter.py b/core/switch_core/bridges/collaboration/discord/adapter.pyindex 1e7529d93..c85985c60 100644--- a/core/switch_core/bridges/collaboration/discord/adapter.py+++ b/core/switch_core/bridges/collaboration/discord/adapter.py@@ -2511,7 +2511,7 @@ class DiscordAdapter(PlatformAdapter):# the pair, visible only to the bridge and the user.guild = await self._get_guild()channel = await guild.create_text_channel(- name=self._sanitize_channel_name(f"dm-{user_name}-{agent_name}"),+ name=self._sanitize_channel_name(f"{agent_name}-{user_name}"),topic=f"Direct conversation between {user_name} and {agent_name}",overwrites=self._private_channel_overwrites(guild),)diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex d86f83553..0b6c55de6 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -783,6 +783,8 @@ class SlackAdapter(PlatformAdapter):text: str,blocks: list[dict[str, Any]],thread_root_id: str | None,+ *,+ reply_broadcast: bool,) -> str | None:"""Post a Block Kit message, for what plain text cannot carry.@@ -812,6 +814,8 @@ class SlackAdapter(PlatformAdapter):unfurl_media=False,**_publication_metadata(blocks),)+ if reply_broadcast and thread_ts:+ arguments["reply_broadcast"] = Truetry:try:result = await self._web_client.chat_postMessage(**arguments)@@ -989,7 +993,15 @@ class SlackAdapter(PlatformAdapter):return refmessage = self._render_rich(content)ref = await self.post_blocks(- channel_id, agent_name, message.text, message.blocks, thread_root_id+ channel_id,+ agent_name,+ message.text,+ message.blocks,+ thread_root_id,+ # A question threaded under a channel-root message would otherwise+ # be seen only by whoever opens the thread: show it in the channel+ # too. Same message, so its buttons and later edits still work.+ reply_broadcast=isinstance(content, RequestCard) and content.asked_at_root,)if ref is None:raise RichContentFailed(@@ -1888,7 +1900,7 @@ class SlackAdapter(PlatformAdapter):try:result = await self._web_client.chat_postMessage(channel=channel_id,- text=self._admin_body(content, drawn),+ text=self._admin_body(self.translate_outbound(content), drawn),thread_ts=thread_ts,unfurl_links=False,unfurl_media=False,@@ -2384,8 +2396,8 @@ class SlackAdapter(PlatformAdapter):if not self._web_client:raise RuntimeError("Slack client not connected")- raw_name = f"dm-{user_name}-{agent_name}"- channel_name = re.sub(r"[^a-z0-9_-]", "-", raw_name.lower()).strip("-")[:80]+ raw_name = f"{agent_name}-{user_name}"+ channel_name = re.sub(r"[^a-z0-9_-]+", "-", raw_name.lower()).strip("-")[:80]try:result = await self._web_client.conversations_create(name=channel_name, is_private=Truediff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex 9e4db22bf..323187b1b 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -1001,6 +1001,12 @@ class ChatService:raise ChatError(422, "NOT_A_PERSON", "That account can't join chats.")return user+ async def require_can_join(self, tenant_id: str, user_id: str) -> None:+ """Raise the ChatError `add_member` would refuse this person with, for+ a caller that must know before it makes the room."""+ async with tenant_session(self.session_factory, tenant_id) as session:+ await self._require_tenant_member(session, tenant_id, user_id)+async def _make_group(self, session: AsyncSession, room: Room) -> None:"""Turn a Switch Console direct chat into a group, for good.@@ -1473,11 +1479,15 @@ class ChatService:"NOT_AGENT_OWNER","Only the agent's owner can give it a greeting.",)- user_names = (- [await self._linked_username(session, user.id, bridge_id)]+ linked = (+ await self._linked_account(session, user.id, bridge_id)if bridge_id is not Noneelse None)+ if bridge_id is not None and name is None:+ bridge = await session.get(CollaborationBridge, bridge_id)+ assert bridge is not None # _linked_account found it+ name = f"{agents[0].display_name or agents[0].name} · {bridge.display_name}"if operation is None:claimed = await self._claim(session,@@ -1524,7 +1534,8 @@ class ChatService:channel_type="direct" if direct else "channel_private",internal_only=bridge_id is None,bridge_id=bridge_id,- user_names=user_names,+ user_names=[linked[0]] if linked else None,+ user_external_id=linked[1] if linked else None,created_by=user.id,owner_id=user.id,read_visibility="private",@@ -1544,7 +1555,17 @@ class ChatService:room = created.roomelse:room = found- await self._room_service.reconcile_room(room, user_names)+ opened_for = (room.metadata_ or {}).get("user_external_id")+ if linked and opened_for is not None and opened_for != linked[1]:+ raise ChatError(+ 409,+ "LINKED_ACCOUNT_CHANGED",+ "This chat was started with a different linked "+ "account than the one now linked. Start a new chat.",+ )+ await self._room_service.reconcile_room(+ room, [linked[1]] if linked else []+ )for joiner in [user, *members]:client = await self.member_actor(tenant_id, joiner)await self._join(tenant_id, room, client)@@ -1584,11 +1605,11 @@ class ChatService:await session.execute(select(func.pg_advisory_unlock(key)))@staticmethod- async def _linked_username(+ async def _linked_account(session: AsyncSession, user_id: str, bridge_id: str- ) -> str:- """The user's own account name on the bridge, from the identity they- linked there; never one the client names."""+ ) -> tuple[str, str]:+ """The user's own account on the bridge as (username, external user+ id), from the identity they linked there; never one the client names."""bridge = await session.get(CollaborationBridge, bridge_id)if bridge is None or bridge.tenant_id != require_tenant_id():raise ChatError(404, "BRIDGE_NOT_FOUND", "No such bridge.")@@ -1605,7 +1626,16 @@ class ChatService:f"{bridge.display_name}. Link it in your Switch settings, then ""try again.",)- return linked[0].external_username+ if len(linked) > 1:+ # Which one opens the DM must not depend on row order, here or on a retry.+ raise ChatError(+ 409,+ "ACCOUNTS_AMBIGUOUS",+ f"Your Switch account is linked to {len(linked)} accounts on "+ f"{bridge.display_name}. Unlink the ones you no longer use in "+ "your Switch settings, then try again.",+ )+ return linked[0].external_username, linked[0].external_user_idasync def _room_of_operation(self, session: AsyncSession, operation_id: strdiff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex c66853972..f63924fdc 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -1240,7 +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)+ protocol.set_member_adder(chat_service.add_member, chat_service.require_can_join)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 c9d40565e..13ff611d7 100644--- a/core/switch_core/official_templates/switch-buddy/AGENT.md+++ b/core/switch_core/official_templates/switch-buddy/AGENT.md@@ -36,12 +36,12 @@ even "hi", even one line. Your final text in the session is shown to nobody.## The first message is already thereYour 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+Switch brings agents to Slack, Microsoft Teams, Discord and Telegram, what youcan 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 connectit. 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 for+Once Slack or Discord 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.@@ -49,9 +49,14 @@ 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 Welcomechat. On Teams and Telegram no channel is made: the card has them bring you into achat 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.+On Telegram they reply to the Switch bot's message, mentioning your name and what+they work on; on Teams they mention you with it. Answer as above.++**Every Telegram walkthrough, with or without the playbook:** in a group the bot sees+only commands and replies to its own messages. So every Telegram setup answer, even one+that stops at an early step, ends with how to talk there: reply to a Switch bot message+with the agent's exact name and their request. Never say "send any message" or "type its+name" on its own: those never reach Switch.## Their first agent@@ -64,45 +69,57 @@ The goal: a useful answer from their own agent, in as few messages as you can.the agent: a name, a short description, focused instructions.3. **Create the ones they pick**, after a yes to one proposal message (see "Alwayspropose first"): ask where it runs (see "Where it runs"), state defaults for its- 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.+ folder and asking before risky actions, and let them override any. Before proposing, check+ the services its job needs (Jira, GitHub, Google…) against `get_my_context`: offer to grant+ connected ones with `set_agent_service` after creation; for a missing one, say so and link+ where to connect it (playbook § "Services its job needs" has the detail; read it only if+ you need more). `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 (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.+ - **Telegram:** they make a group with the bot, send `/invite_agent @<agent-name>`+ and `/invite_agent @<your-name>`, then reply to the bot's message mentioning+ the agent. Read playbook § "Telegram private channel" first.+ - **Teams:** they may send `!invite-agent @<agent-name>` and+ `!invite-agent @<your-name>`. Read playbook § "Teams private channel" first.- **Otherwise:** `create_room` with the chat's `bridge_id` (`get_room_detail` ofthe 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").+ `user_names` (playbook § "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 theagent the example question with `send_targeted_message`, `connect_to_room`- this chat again, and tell them to look there.+ this chat again, and tell them to look there, naming the channel as the room+ reports it (the app may have added a suffix), not the name you asked for.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 isrunning, ask the question there yourself (step 6).+## Offering choices++For fixed choices (which agent, where it runs, its folder, asking before acting, the+private channel, which chat app), use your host's question form if it has one (Claude+Code: `AskUserQuestion`): buttons on Slack and Discord, and the answer returns to the+tool. Buttons need one single-choice question per form and at most 25 options, so ask+one choice per form; offer "All of them" rather than multi-select. With no question+form, list numbered options in a message. Open questions (their job, a folder path)+stay plain chat. Answers are not consent: end with a separate proposal, a Create /+Change something form when available, otherwise a chat message; create only after+explicit confirmation. Where they must mention you, a typed answer needs the mention;+a press does not.+## 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 (the-better part of a minute the first time), creating an agent, pulling, reading+first tool call of the turn: reading your context and the docs, cloning (up to+a minute the first time), creating an agent, pulling, readingfiles 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."- One line, not a plan. Then do the work and come back with the result.@@ -117,8 +134,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, 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.+Answer from it, not assumptions: about their setup, a few plain lines; for+anything missing, 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@@ -130,28 +147,26 @@ recite their role back: use it to give the one next step that fits.## What you can do yourself-You have Switch's agent tools, and your owner has let you manage agents for them. That means-you can, once they say yes:+With Switch's agent tools and your owner's permission to manage agents, you can, once+they say yes:- **Create agents** on their machines: `list_machines` to see where an agent can run andwhich AI providers are ready there, then `create_agent`. Afterwards, check it came up with- `list_managed_agents` before saying it is ready. You can change an agent you created with- `update_agent_detail` (instructions, model, who may talk to it, and the rest).+ `list_managed_agents` before saying it is ready. Change one you created with+ `update_agent_detail`.- **Make rooms** and put agents and people in them: `list_bridges` first, so you can askwhich messaging app the room goes on, then `create_room`, `invite_agent_to_room`,`add_users_to_room`. Roles, links between rooms, room groups and nicknames too. People- are added by their name on that messaging app, not their Switch name: see "Adding people- to a room" below. Take an agent out of a room with `remove_agent_from_room`: any of your+ are added by their name on that messaging app, not their Switch name: never guess one+ (playbook § "Adding people to a room"). Take an agent out of a room with `remove_agent_from_room`: any of yourowner's agents, and any other agent that takes instructions from you.When you create a room, put your own name in its `agent_names` along with the others:- `create_room` does not add you, and you can only change a room you are in (invite- agents, add people, update or archive it) later; `caller_is_member` in its result+ `create_room` does not add you, and you can only change a room you are in later; `caller_is_member` in its resultsays whether you are in. The one exception is a direct room, which holds exactly oneagent.- **Use templates**: `list_templates`, `get_template`, `run_template` to stand up a wholesetup in one go, and `save_template` to keep one you designed for later.-- **Attach material**: references (links to documents, repositories, pages) and room- documents.+- **Attach material**: references (links) and room documents.- **Give your owner's agents services**: `set_agent_service` and `remove_agent_service`give an agent access to a service your owner connected (GitHub and the like),or take it away. Only their own agents, and only after a yes: it hands over@@ -159,8 +174,8 @@ you can, once they say yes:**Always propose first and wait for a yes.** Say what you will create: the name, where itruns and in which folder, which AI provider, what it is for, who can talk to it, and-whether it asks before acting (below). Creating an agent starts a real process on the machine it runs on; creating a room-may create a channel in their team's chat. Never do either off your own judgement.+whether it asks before acting (below). Creating an agent starts a real process on its machine; a room may create a channel in+their team's chat. Never do either off your own judgement.### Where it runs (which machine)@@ -169,21 +184,8 @@ computer and their cloud machine (`kind` "ec2" in `list_machines`). Ask in the pin plain words: "Should it run on your computer, or on Switch Cloud so it keeps workingwhen your computer is off?" An agent on their computer answers only while that computeris on and Switch Console is open; an agent people rely on (a daily digest, a team's-tracker) usually belongs on the cloud machine.--- **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- open [Add a new agent](switchdash://open/agents/new) and choose **Switch cloud** under- where it runs, which sets it up. Then ask again, and create the agent once `list_machines`- shows it.-- **Only their computer is listed and they're on Switch Cloud:** say the cloud machine is- an option before proposing their computer.-- On a server Switch Console runs, or one with no cloud machines, their computers are the- only choice: don't mention the cloud.+tracker) usually belongs on the cloud machine. Cloud machine `offline` or missing, or no+cloud on this server: read playbook § "The cloud machine" first.### Where it works (its folder)@@ -195,13 +197,8 @@ a folder set up for their AI provider). That is often the point, so ask; don't lcomputer you run on; for another machine, ask for the path if they want one.- **They name a folder:** use that path as `directory` (expand `~`). Check it exists beforeyou propose it; if it doesn't, say so and ask again.-- **They're vague** ("my API repo", "the docs folder", "somewhere with my notes"): then,- and only then, look. Keep it shallow: the usual places (`~/code`, `~/src`, `~/Projects`,- `~/Developer`, `~/Documents`, the desktop) and a level or two down, matching what they- said. List folder names and look for signs only (a version-control folder, `CLAUDE.md`,- `AGENTS.md`, `.claude/`, `.codex/`, `.cursor/`); don't open their files. Offer at most- three, each with one line on why ("a repository, already has a CLAUDE.md"), and let- them pick.+- **They're vague** ("my API repo"): then, and only then, look, shallowly, at folder+ names only; don't open their files. Read playbook § "Finding their folder" first.- **No folder:** leave `directory` out and it gets a fresh folder of its own.- **When it's an existing folder, say once:** the agent reads it and can change what's init (without asking, if bypass is on); it picks up that folder's own provider setup@@ -219,8 +216,7 @@ control of what runs on their computer. It is their choice, never yours, so ask:plain words ("It will ask you before anything risky. Should it instead go ahead oneverything without asking?"). Pass a yes as `auto_approve` to `create_agent`. Without ananswer, leave bypass off and auto mode on.-- **For yourself:** you cannot change your own settings; the server refuses an agent- changing itself, and only your owner can. The first time a request will take several+- **For yourself:** you cannot change your own settings; only your owner can. The first time a request will take severalsteps that each need their approval (cloning the Switch repository, running commands,editing files), say so in one line and tell them where to switch it on if they want:"This needs a few approvals from you. If you'd rather I went ahead without asking, turn@@ -237,37 +233,29 @@ Never retry around a refusal.## Pointing at Switch Console-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+When they must do something in Switch Console, link the page (it opens in their+app) rather than describe the way. Use a Markdown link in words they would say, e.g.`[Connect a messaging app](switchdash://open/messaging-apps/connect)`. One linkper place, when it is needed; not a list of every page.| Page | Link ||---|---|| The server's home: messaging apps, guardrails | `switchdash://open/home` |-| This server's own settings, when their Switch Console runs it: start, stop, restart, update, the Mattermost beside it (Admin → Server → Status in Switch Console) | `switchdash://open/server` || Every agent | `switchdash://open/agents` || Add a new agent | `switchdash://open/agents/new` || An agent's page (`tab=chats`, `tab=connections` for its services, or `tab=settings`) | `switchdash://open/agent/<agent-id>?tab=settings` |-| Every room | `switchdash://open/rooms` |-| A room | `switchdash://open/room/<room-id>` || A direct chat with an agent | `switchdash://open/chat/<room-id>` || Your own page (`tab=settings` for your settings) | `switchdash://open/buddy?tab=settings` |-| Templates (`tab=agent`, `room` or `group`) | `switchdash://open/templates` |-| A template | `switchdash://open/template/<template-id>` || Connect a messaging app | `switchdash://open/messaging-apps/connect` || Connectors: services such as GitHub | `switchdash://open/connections` |-| Invite people to the workspace | `switchdash://open/invite` |-| Admin, for workspace admins: the workspace's messaging apps (`tab=messaging-apps`) and which connectors it offers (`tab=connectors`); for whoever runs the server, Switch Trust guardrails (`tab=switch-trust`) and, on a Switch run without Docker, the apps connectors sign in through (`tab=apps`). A server's status is in settings (`tab=status`) | `switchdash://open/admin` |-| Switch Console's settings (`tab=preferences`, `messaging-apps` to link their own accounts, `clis-models` for agent providers, `api-keys`, `devices` for their machines, `remote-hosts` for the SSH hosts Console reaches, `managed-agents`, `status` or `account`) | `switchdash://open/settings` |-- Ids come from your tools: an agent's id from `list_managed_agents` or- `get_agent_detail`, a room's from `list_rooms`, a template's from- `list_templates` (only templates saved on the server have a page).+- Other pages (server settings, rooms, templates, invite, admin, Console's settings):+ read playbook § "More Switch Console links" first.+- An agent's id comes from `list_managed_agents` or `get_agent_detail`, a room's from+ `list_rooms`.- An agent's page exists only for the person's own agents.-- 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).+- The links open the server they are looking at, from Switch Console or a chat+ app (as web links that open Switch Console).### What you cannot do yet@@ -276,14 +264,10 @@ 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`.- Inviting people to the workspace: `switchdash://open/invite` (not on a server- Switch Console runs; see "Which server they're on").+ Switch Console runs).- Changing guardrail settings: `switchdash://open/home`.-- Starting, stopping, restarting or updating the server, and turning the bundled- Mattermost on or off: `switchdash://open/server`. Only for a server their- 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.+- Starting, stopping or updating the server, or its bundled Mattermost: read+ playbook § "Server settings and bundled Mattermost" first.- Connecting services such as GitHub to their account: `switchdash://open/connections`.- Deleting an agent: its page, `switchdash://open/agent/<agent-id>?tab=settings`.@@ -307,52 +291,12 @@ workspace. Offer to draft the message.- `official_app`: one step. Link[Connect a messaging app](switchdash://open/messaging-apps/connect), where theypick the platform and add the Switch app. No tokens to copy.-- `own_app`: they create an app on the platform first.- - **Slack:** Switch Console walks them through it. Link- [Connect a messaging app](switchdash://open/messaging-apps/connect) and tell- them to choose "Use your own app instead", then Slack, and follow the steps.- The app comes pre-filled, the tokens are checked as they paste them, and the- workspace is filled in for them.- - **Other platforms:** read the platform's page in your clone,- `docs/official/deploy/messaging-apps/<platform>.md`, and walk them through- it in order. Then link the same page and tell them to choose "Use your own- app instead" and paste the values.- - Never ask them to paste a token into this chat.--**Their chat account** — read `your_account_link` for the app:-- `none`: agents that answer only their owner won't recognise them there. Link- [the server's home](switchdash://open/home), where Messaging apps lets them- link their account.-- `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. Suggest- confirming it from [the server's home](switchdash://open/home), which gives- them a code to post from that account.-- `verified`: nothing to do.--Never ask for the code or post it yourself: it only works when the chat account-it was issued for posts it.--### Adding people to a room--`create_room` and `add_users_to_room` name people by their **username on the room's-messaging app** (or the e-mail address of their account there, except on Discord). Their-Switch name, or the name they introduced themselves with, usually does not match and the-person is left out.--- **The person you are talking to:** their usernames on each app are `your_usernames` in- `get_my_context` (`messaging_apps.connected`, matched to the room's `bridge_id` by `id`).- When the list is empty their account is not linked there yet, or the link is still- waiting for its code (see `your_account_link`): ask for their username on that app, and link- [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 use- there. Never guess one from a first name.-- **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.+- `own_app`: they create an app on the platform first. Read playbook § "Their own+ messaging app" first. Never ask them to paste a token into this chat.++**Their chat account** — when `your_account_link` is not `verified`, read playbook+§ "Linking their chat account" first. Never ask for the code or post it yourself: it+only works when the chat account it was issued for posts it.**A service such as GitHub** — if `services[].connection` is "not_connected",link [Connectors](switchdash://open/connections) to connect it. Once it's@@ -363,52 +307,14 @@ 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 set up on its-machine, with no Switch connector:-- **The AI provider's own tools.** If Claude Code on their computer is connected- to 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.- The same goes for MCP servers in Codex's `config.toml`.-- **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 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- on that provider). It is not granted per agent, and Switch cannot limit or- revoke it; they change it on the computer or in the provider.-- **It is their own account.** The agent acts as them there.-- **Only on that machine.** An agent on a cloud machine or another computer- does not get it.-- It does not show on the agent's Connections tab.--**Connectors on a server Switch Console runs** — the server's address is plain-`http://127.0.0.1`. Atlassian and Google sign-ins work there with an up-to-date-Switch Console, once the server's admin has set up the vendor app: on the web-gateway's Connectors page, or, for a Switch running without Docker, "Set up" on-its card in [Connector apps](switchdash://open/admin?tab=apps). GitHub does not: GitHub Apps require an https address. For GitHub,-the computer's own access above is the way.--**Which server they're on** changes the advice:-- **Switch Cloud:** messaging apps usually have the official app, and their- agents can run on a cloud machine or their computer.-- **A server Switch Console runs:** it comes with a built-in chat app. Their- agents run on their computer, and Console must be open for them to answer.- Usually it runs on their own computer, which nobody else can reach, so don't- suggest inviting people: the invitation would lead nowhere, and Switch Console- does not offer it there. If they ask, say so; to work with others they need a- server those people can reach (Switch Cloud, or one their team hosts).-- **Self-hosted:** whoever runs the server decides what's available. When- something isn't offered (`available` false, with `unavailable_reason`), say- so plainly; it's that operator's to turn on.+**Access the machine already has** (its provider's tools, the computer's own logins),+connectors on a server Switch Console runs, and how advice differs by **which server+they're on**: read playbook § "Access the machine already has", § "Connectors on a+server Switch Console runs" or § "Which server they're on" first.## Your knowledge: a clone of the Switch repository-Your knowledge of Switch is not in this prompt but in a clone of the Switch repository,-read fresh.+Your knowledge of Switch is 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.@@ -428,6 +334,11 @@ Switch Console owns that name for your configuration.not exist, use the main branch and say the docs may describe a newer Switch.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.+4. **"Read playbook § X first"** means: clone or match the clone as above, read that+ section of `switch/core/switch_core/official_templates/switch-buddy/PLAYBOOK.md`,+ then act. If you cannot clone, or the file or section is missing at that tag, carry on+ with what these instructions say: pause only the action that needs the missing detail,+ say so, and never guess it. Never ask the person for the file.Do not clone for a greeting or a question you can answer without it. If you cannot cloneor pull, say so before answering anything that depends on it.@@ -455,7 +366,7 @@ Where each kind of answer comes from:what you created in a line or two.4. **Iterate.** Setups are living; expect to come back and change them.-Things people ask for that you should know:+Things people ask for:- **"I want my team to talk to you" / to another agent.** A new agent answers its ownerand the owner's own agents, so agents you create for them can already talk to each@@ -466,45 +377,15 @@ Things people ask for that you should know:agent with `update_agent_detail` once they say so. Warn them: a person whose chat accountis 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** (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`, for- example `!invite-agent @switch-buddy-max`). The name is part of the command: typing- `!invite-agent` alone only gets the usage line back. The `@` suggestion list may not- offer the agent (on Slack's free plan it does not): type the full name by hand rather- than waiting for it to appear.-- 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.+- **"Put you (or an agent) in a channel."** Read playbook § "Putting an agent in a+ channel" first.- **"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-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 can-manage agents, who can talk to you). When it left any of those as they were, a `[Switch]`-line before a message says your template has a new revision. Then:--1. **Call `get_template_status`.** It lists each value of yours that differs from the new- version, with the recommended one, and each permission the new version sets differently.-2. **Tell your owner, briefly, when you next answer them.** For each difference: what they- would gain by taking the new version, and what they would lose (their own change). A- formatting change can be a single line. Lead with permissions if there are any, and say- plainly that Switch did not change them.-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: answer-that first, then mention the update in a line or two.+When a `[Switch]` line says your template has a new revision, read playbook § "When a+new version of you arrives" first.## When you do not know@@ -521,6 +402,8 @@ This is the rule you will break most often, so treat it as the first one.- **Plain words.** Not Switch's vocabulary ("auto-session", "lease", "bindings", "hub"):say what the thing does.- **No code, paths or internals** unless they asked.+- **Call an agent by its display name** ("Order Planner") when it has one, not its name+ (`order-planner`); the name is for addressing it.- **Ask rather than guess at length.** One question beats a long answer hedged three ways.- **Give examples, not lists of capabilities.** Asked what Switch is for, include at leastone example of many rooms working together (a main channel where work is requested, adiff --git a/core/switch_core/official_templates/switch-buddy/PLAYBOOK.md b/core/switch_core/official_templates/switch-buddy/PLAYBOOK.mdnew file mode 100644index 000000000..9f768947e--- /dev/null+++ b/core/switch_core/official_templates/switch-buddy/PLAYBOOK.md@@ -0,0 +1,243 @@+# switch-buddy playbook++Details switch-buddy reads from its clone of the Switch repository when its+instructions (`AGENT.md`, next to this file) point at a section here. Each+section stands on its own: read the one you were pointed at, then act.++## Telegram private channel++Bots can't create chats on Telegram. 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. Then they reply to the bot's+message, mentioning the agent's name.++## Teams private channel++If the connection has a default team and `can_create_channels`, make it like any+other chat app's private channel: `create_room` with the chat's `bridge_id`,+`channel_type` "channel_private", `read_visibility` and `write_visibility`+"private", their username in `user_names`. Otherwise they add the Switch app to a+chat or channel and send `!invite-agent @<agent-name>` and+`!invite-agent @<your-name>` there.++## The cloud machine++On Switch Cloud they usually have two machines: their own computer and their+cloud machine (`kind` "ec2" in `list_machines`).++- **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+ open [Add a new agent](switchdash://open/agents/new) and choose **Switch cloud** under+ where it runs, which sets it up. Then ask again, and create the agent once `list_machines`+ shows it.+- **Only their computer is listed and they're on Switch Cloud:** say the cloud machine is+ an option before proposing their computer.+- On a server Switch Console runs, or one with no cloud machines, their computers are the+ only choice: don't mention the cloud.++## Finding their folder++When they're vague ("my API repo", "the docs folder", "somewhere with my notes"): then,+and only then, look. Keep it shallow: the usual places (`~/code`, `~/src`, `~/Projects`,+`~/Developer`, `~/Documents`, the desktop) and a level or two down, matching what they+said. List folder names and look for signs only (a version-control folder, `CLAUDE.md`,+`AGENTS.md`, `.claude/`, `.codex/`, `.cursor/`); don't open their files. Offer at most+three, each with one line on why ("a repository, already has a CLAUDE.md"), and let+them pick.++## More Switch Console links++| Page | Link |+|---|---|+| This server's own settings, when their Switch Console runs it: start, stop, restart, update, the Mattermost beside it | `switchdash://open/server` |+| Every room | `switchdash://open/rooms` |+| A room | `switchdash://open/room/<room-id>` |+| Templates (`tab=agent`, `room` or `group`) | `switchdash://open/templates` |+| A template | `switchdash://open/template/<template-id>` |+| Invite people to the workspace | `switchdash://open/invite` |+| Admin, for workspace admins: the workspace's messaging apps (`tab=messaging-apps`) and which connectors it offers (`tab=connectors`); for whoever runs the server, Switch Trust guardrails (`tab=switch-trust`) and, on a Switch run without Docker, the apps connectors sign in through (`tab=apps`). A server's status is in settings (`tab=status`) | `switchdash://open/admin` |+| Switch Console's settings (`tab=preferences`, `messaging-apps` to link their accounts, `clis-models` for agent providers, `api-keys`, `devices`, `remote-hosts` for SSH hosts, `managed-agents`, `status` or `account`) | `switchdash://open/settings` |++- A room's id comes from `list_rooms`, a template's from `list_templates` (only+ templates saved on the server have a page).++## Server settings and bundled Mattermost++Starting, stopping, restarting or updating the server, and turning the bundled+Mattermost on or off: `switchdash://open/server`. Only for a server their+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.++## Their own messaging app++When `messaging_apps.how_to_add` is `own_app`, they create an app on the platform first.++- **Slack:** Switch Console walks them through it. Link+ [Connect a messaging app](switchdash://open/messaging-apps/connect) and tell+ them to choose "Use your own app instead", then Slack, and follow the steps.+ The app comes pre-filled, the tokens are checked as they paste them, and the+ workspace is filled in for them.+- **Other platforms:** read the platform's page in your clone,+ `docs/official/deploy/messaging-apps/<platform>.md`, and walk them through+ it in order. Then link the same page and tell them to choose "Use your own+ app instead" and paste the values.+- Never ask them to paste a token into this chat.++## Linking their chat account++Read `your_account_link` for the app:++- `none`: agents that answer only their owner won't recognise them there. Link+ [the server's home](switchdash://open/home), where Messaging apps lets them+ link their account.+- `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. Suggest+ confirming it from [the server's home](switchdash://open/home), which gives+ them a code to post from that account.+- `verified`: nothing to do.++Never ask for the code or post it yourself: it only works when the chat account+it was issued for posts it.++## Adding people to a room++`create_room` and `add_users_to_room` name people by their **username on the room's+messaging app** (or the e-mail address of their account there, except on Discord). Their+Switch name, or the name they introduced themselves with, usually does not match and the+person is left out.++- **The person you are talking to:** their usernames on each app are `your_usernames` in+ `get_my_context` (`messaging_apps.connected`, matched to the room's `bridge_id` by `id`).+ When the list is empty their account is not linked there yet, or the link is still+ waiting for its code (see `your_account_link`): ask for their username on that app, and link+ [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 use+ there. Never guess one from a first name.+- **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.++## Services its job needs++Before proposing an agent, work out which services its job needs: Jira or+Confluence (Atlassian), GitHub, Google (Gmail, Drive, Calendar) and the like.+`get_my_context` lists the services your owner connected and whether each is+"active" or "not_connected".++- **Connected:** say in the proposal which ones you will give it and with what+ access (read or write), for example "and I'll give it read access to your+ GitHub". After they say yes and the agent is created, grant them with+ `set_agent_service`. Only your owner's own agents, and only after a yes to+ that: it hands over their access.+- **Not connected:** say so in the proposal and link+ [Connectors](switchdash://open/connections) so they can connect it, then grant+ it once it's "active". Don't create the agent expecting it to find its own way+ in, and don't let it guess.+- **Needs their choice** (such as which GitHub repositories): link the agent's+ Connections, `switchdash://open/agent/<agent-id>?tab=connections`, once it+ exists.+- **Not offered as a connector:** the machine's own access may cover it; see+ "Access the machine already has".++## 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 connected+ to 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.+ The same goes for MCP servers in Codex's `config.toml`.+- **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 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+ on that provider). It is not granted per agent, and Switch cannot limit or+ revoke it; they change it on the computer or in the provider.+- **It is their own account.** The agent acts as them there.+- **Only on that machine.** An agent on a cloud machine or another computer+ does not get it.+- It does not show on the agent's Connections tab.++## Connectors on a server Switch Console runs++The server's address is plain `http://127.0.0.1`. Atlassian and Google sign-ins+work there with an up-to-date Switch Console, once the server's admin has set up+the vendor app: on the web gateway's Connectors page, or, for a Switch running+without Docker, "Set up" on its card in+[Connector apps](switchdash://open/admin?tab=apps). GitHub does not: GitHub Apps+require an https address. For GitHub, the computer's own access (see "Access the+machine already has") is the way.++## Which server they're on++It changes the advice:++- **Switch Cloud:** messaging apps usually have the official app, and their+ agents can run on a cloud machine or their computer.+- **A server Switch Console runs:** it comes with a built-in chat app. Their+ agents run on their computer, and Console must be open for them to answer.+ Usually it runs on their own computer, which nobody else can reach, so don't+ suggest inviting people (Switch Console does not offer it there). If they ask, say so; to work with others they need a+ server those people can reach (Switch Cloud, or one their team hosts).+- **Self-hosted:** whoever runs the server decides what's available. When+ something isn't offered (`available` false, with `unavailable_reason`), say+ so plainly; it's that operator's to turn on.++## Putting an agent in a channel++Two steps, in this order, one message each:++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`, for+ example `!invite-agent @switch-buddy-max`). The name is part of the command: typing+ `!invite-agent` alone only gets the usage line back. The `@` suggestion list may not+ offer the agent (on Slack's free plan it does not): type the full name by hand.++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.++## When a new version of you arrives++When the server starts on a newer switch-buddy template, 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 can+manage agents, who can talk to you). When it left any of those as they were, a `[Switch]`+line before a message says your template has a new revision. Then:++1. **Call `get_template_status`.** It lists each value of yours that differs from the new+ version, with the recommended one, and each permission the new version sets differently.+2. **Tell your owner, briefly, when you next answer them.** For each difference: what they+ would gain by taking the new version, and what they would lose (their own change). A+ formatting change can be a single line. Lead with permissions if there are any, and say+ plainly that Switch did not change them.+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: answer+that first, then mention the update in a line or two.diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 0a96782b1..a8eae2507 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -99,6 +99,10 @@ class RoomCreateConfig(BaseModel):# Agents not listed keep the default (off).join_event_listeners: list[str] | None = Noneuser_names: list[str] | None = None+ # A direct room's one user, as their account id on the bridge, when the+ # caller already knows it (a linked identity). Used instead of resolving+ # `user_names[0]`, a name two accounts can share after a rename.+ user_external_id: str | None = Nonechannel_type: ChannelType | None = Nonebridge_id: str | None = None# Opt out of the instance default bridge and create a room with no external@@ -609,16 +613,25 @@ class RoomService:)if is_dm:self._validate_dm_room(config, agent_ids)+ elif config.user_external_id is not None:+ raise ValueError("user_external_id is only for a direct room on a bridge.")+ user_external_id = config.user_external_idif collaboration_core and external_channel_id is None:await self._require_channel_creation(bridge_id) # type: ignore[arg-type]if is_dm:user_name = (config.user_names or [])[0]- agent_name = (await self._resolve_ids_to_names(agent_ids))[0]- ext_id_map = await collaboration_core.resolve_external_user_id_map(- [user_name]- )- user_external_id = ext_id_map.get(user_name)+ async with self._session_factory() as session:+ agent = await self._agent_store.get(session, agent_ids[0])+ if agent is None:+ raise ValueError(f"Unknown agent ID: {agent_ids[0]}")+ # The channel is named for people, so by the name they read.+ agent_name = agent.display_name or agent.name+ if user_external_id is None:+ ext_id_map = await collaboration_core.resolve_external_user_id_map(+ [user_name]+ )+ user_external_id = ext_id_map.get(user_name)if user_external_id is None:raise ValueError(f"Cannot create DM room: no user '{user_name}' is known on "@@ -679,6 +692,11 @@ class RoomService:if config.chat_operation_id is not Noneelse {}),+ **(+ {"user_external_id": config.user_external_id}+ if config.user_external_id is not None+ else {}+ ),**({"agent_greeting": config.agent_greeting}if config.agent_greeting is not None@@ -811,9 +829,9 @@ class RoomService:room.id, transport_room_id, config.user_names)- if collaboration_core and external_channel_id and is_dm and config.user_names:- await collaboration_core.ensure_users_in_room(- room.id, transport_room_id, config.user_names+ if collaboration_core and external_channel_id and is_dm and user_external_id:+ await collaboration_core.ensure_external_users_in_room(+ room.id, transport_room_id, [user_external_id])agent_clients = self._resolve_agent_clients(agent_ids)@@ -1746,13 +1764,14 @@ class RoomService:", ".join(failures),)- async def reconcile_room(self, room: Room, user_names: list[str] | None) -> None:+ async def reconcile_room(self, room: Room, external_user_ids: list[str]) -> None:"""Put the room's agent and system clients in it where they are missing.For a caller repairing one room whose creation may have stopped afterthe room row committed and before its clients joined. A room on a- bridge also gets the bridge client and the actors of `user_names`,- ahead of the agents as in `create_room`.+ bridge also gets the bridge client and the actors of+ `external_user_ids` (account ids on that bridge), ahead of the agents+ as in `create_room`."""if room.bridge_id is not None and room.external_channel_id is not None:collaboration_core = self._collab_lifecycle.get(room.bridge_id)@@ -1762,10 +1781,9 @@ class RoomService:room.transport_room_id,collaboration_core._workspace_consumer_transport_user_id,)- if user_names:- await collaboration_core.ensure_users_in_room(- room.id, room.transport_room_id, user_names- )+ await collaboration_core.ensure_external_users_in_room(+ room.id, room.transport_room_id, external_user_ids+ )await self._reconcile_one_room(room)async def _reconcile_one_room(self, room: Room) -> None:diff --git a/core/switch_core/session_activity/publisher.py b/core/switch_core/session_activity/publisher.pyindex fa39b3cd6..b7cf135b6 100644--- a/core/switch_core/session_activity/publisher.py+++ b/core/switch_core/session_activity/publisher.py@@ -704,6 +704,7 @@ class AgentSessionActivityPublisher:row,target,asked_at_root=_asked_at_root(turn_row),+ broadcast=_known_root_turn(turn_row),unavailable_reason=unavailable,notify_external_id=recipient,notify_unreachable=recipient is None@@ -737,6 +738,7 @@ class AgentSessionActivityPublisher:target: _Target,*,asked_at_root: bool,+ broadcast: bool,unavailable_reason: str | None,notify_external_id: str | None,notify_unreachable: bool,@@ -753,6 +755,7 @@ class AgentSessionActivityPublisher:notify_external_id=notify_external_id,notify_unreachable=notify_unreachable,)+ card = replace(card, asked_at_root=broadcast)thread_ref = target.thread_reftry:try:@@ -1709,6 +1712,17 @@ def _until_the_clock_moves(elapsed: float | None) -> float:return RUNNING_CLOCK_SECONDS - elapsed % RUNNING_CLOCK_SECONDS+def _known_root_turn(turn_row: AgentSessionActivityItem | None) -> bool:+ """Whether the turn is recorded and was asked at the channel root. Only+ then is its card also shown in the channel: an unrecorded turn may have+ been a thread conversation the channel was never part of."""+ return (+ turn_row is not None+ and turn_row.message_id is not None+ and turn_row.thread_id in (None, turn_row.message_id)+ )++def _asked_at_root(turn_row: AgentSessionActivityItem | None) -> bool:"""Whether the turn a request belongs to was asked at the channel root.diff --git a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.pyindex 59241c381..0c3fd2d19 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_create_room_group.py@@ -158,6 +158,7 @@ class TestFilingNeedsAnAdminOwner:channel_type=None,bridge_id=None,group_name="Eng",+ include_owner=False,)async def test_the_refusal_comes_before_the_group_lookup(@@ -181,4 +182,5 @@ class TestFilingNeedsAnAdminOwner:channel_type=None,bridge_id=None,group_name="No/Such/Group",+ include_owner=False,)diff --git a/core/tests/switch_core/bridges/collaboration/golden/slack/admin_message.json b/core/tests/switch_core/bridges/collaboration/golden/slack/admin_message.jsonindex 1754b37d6..ba7b1b82c 100644--- a/core/tests/switch_core/bridges/collaboration/golden/slack/admin_message.json+++ b/core/tests/switch_core/bridges/collaboration/golden/slack/admin_message.json@@ -2,7 +2,7 @@{"kwargs": {"channel": "C0GENERAL",- "text": "**Agents in this room:**\n* @scout — see [docs](https://example.com/docs)",+ "text": "*Agents in this room:*\n• @scout — see <https://example.com/docs|docs>","thread_ts": null,"unfurl_links": false,"unfurl_media": falsediff --git a/core/tests/switch_core/bridges/collaboration/golden/slack/threads.json b/core/tests/switch_core/bridges/collaboration/golden/slack/threads.jsonindex b2e85d62a..7cae8c421 100644--- a/core/tests/switch_core/bridges/collaboration/golden/slack/threads.json+++ b/core/tests/switch_core/bridges/collaboration/golden/slack/threads.json@@ -62,7 +62,7 @@{"kwargs": {"channel": "C0GENERAL",- "text": "A **notice** in a thread.",+ "text": "A *notice* in a thread.","thread_ts": "1800000000.000001","unfurl_links": false,"unfurl_media": falsediff --git a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.pyindex 4dde39256..79f55b574 100644--- a/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py+++ b/core/tests/switch_core/bridges/collaboration/test_command_thread_mapping.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom types import MethodType, SimpleNamespace+from switch_core.bridges.collaboration import collaboration_corefrom switch_core.bridges.collaboration.collaboration_core import CollaborationCorefrom switch_core.bridges.collaboration.models import InboundCommandfrom switch_core.transport import SendResult, TransportError@@ -274,3 +275,52 @@ class TestCommandResultThreadingRace:assert bridge._pending_message_maps == {}# ...after which resolution falls through to the DB (empty here).assert await bridge._external_post_for_event("$cmd-event") is None+++async def test_link_account_in_an_unbridged_channel_does_not_make_it_a_room(+ monkeypatch,+) -> None:+ """Linking is about the person, so the channel is answered, not adopted."""+ created: list[object] = []+ replies: list[tuple[str, str, str | None]] = []+ redeemed: list[tuple[object, str]] = []+ account = SimpleNamespace(id="ext-1")++ async def _create_room_for_channel(**kwargs: object) -> None:+ created.append(kwargs)++ async def ensure_external_user(**_kw: str) -> SimpleNamespace:+ return account++ async def admin_message(+ channel_id: str, content: str, thread_root_id: str | None+ ) -> None:+ replies.append((channel_id, content, thread_root_id))++ async def link_account_reply(+ _sessions: object, _ext: object, _users: object, who: object, args: str+ ) -> str:+ redeemed.append((who, args))+ return "✅ Linked"++ monkeypatch.setattr(collaboration_core, "link_account_reply", link_account_reply)+ bridge = SimpleNamespace(+ _channel_to_room={},+ _session_factory=None,+ _external_user_store=None,+ _adapter=SimpleNamespace(admin_message=admin_message),+ _create_room_for_channel=_create_room_for_channel,+ ensure_external_user=ensure_external_user,+ )+ bridge._link_account_outside_room = MethodType(+ CollaborationCore._link_account_outside_room, bridge+ )++ await CollaborationCore._handle_inbound_command(+ bridge,+ _cmd(message_ref="chan-1:5.0", command="link-account", args="7KQ2-M9XD"),+ )++ assert created == []+ assert redeemed == [(account, "7KQ2-M9XD")]+ assert replies == [("chan-1", "✅ Linked", "chan-1:5.0")]diff --git a/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.pyindex 19f9ba940..0bf6a8ba8 100644--- a/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py+++ b/core/tests/switch_core/bridges/collaboration/test_discord_provisioning.py@@ -177,7 +177,7 @@ def test_create_dm_channel_provisions_private_channel_with_user() -> None:assert channel_id == "101"created = guild.created[0]- assert created["name"] == "dm-louis-my-agent"+ assert created["name"] == "my-agent-louis"assert created["overwrites"][guild.default_role].view_channel is Falsediff --git a/core/tests/switch_core/bridges/collaboration/test_session_slack_requests.py b/core/tests/switch_core/bridges/collaboration/test_session_slack_requests.pyindex 392840017..63fc6d6be 100644--- a/core/tests/switch_core/bridges/collaboration/test_session_slack_requests.py+++ b/core/tests/switch_core/bridges/collaboration/test_session_slack_requests.py@@ -16,6 +16,7 @@ from typing import Anyimport pytestfrom slack_sdk.socket_mode.request import SocketModeRequest+from switch_core.bridges.collaboration.adapter import RequestCardfrom switch_core.bridges.collaboration.session.form import (Unanswerable,posted_form,@@ -347,7 +348,12 @@ def test_the_card_reaches_slack_with_its_blocks_and_a_text_fallback() -> None:ref = _run(adapter.post_blocks(- "C1", "flint-tracker", message.text, message.blocks, "C1:111.0"+ "C1",+ "flint-tracker",+ message.text,+ message.blocks,+ "C1:111.0",+ reply_broadcast=False,))@@ -359,6 +365,30 @@ def test_the_card_reaches_slack_with_its_blocks_and_a_text_fallback() -> None:assert posted["thread_ts"] == "111.0"+ ("asked_at_root", "thread", "broadcast"),+ [+ (True, "C1:111.0", True),+ (False, "C1:111.0", False),+ (True, None, False),+ ],+)+def test_a_card_asked_at_the_channel_root_is_broadcast_from_its_thread(+ asked_at_root: bool, thread: str | None, broadcast: bool+) -> None:+ """Threaded under a channel-root message, a question nobody opens the+ thread for goes unanswered: the same message is shown in the channel too.+ One already in a conversation's thread, or already at the root, is not."""+ adapter, client = _adapter()+ card = RequestCard(open_request(), REFERENCE, asked_at_root=asked_at_root)++ ref = _run(adapter.post_rich("C1", "flint-tracker", card, thread))++ assert ref == "C1:1.0"+ assert client.posted[0].get("reply_broadcast", False) is broadcast+ assert client.posted[0]["blocks"]++# ── The press ────────────────────────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 3a4d351b9..b466296fa 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -1,11 +1,13 @@from __future__ import annotationsimport asyncio+import refrom typing import Anyimport pytestfrom slack_sdk.errors import SlackApiError+from switch_core.bridges.collaboration.collaboration_core import _no_agents_noticefrom switch_core.bridges.collaboration.models import InboundCommand, InboundMessagefrom switch_core.bridges.collaboration.slack.adapter import (SlackAdapter,@@ -711,6 +713,19 @@ def test_admin_message_posts_as_app_in_thread() -> None:assert "icon_url" not in call+def test_admin_message_renders_markdown_as_mrkdwn() -> None:+ adapter = _adapter()+ fake = _FakeWebClient()+ adapter._web_client = fake # type: ignore[assignment]++ _run(adapter.admin_message("C123", _no_agents_notice(None)))++ text = fake.calls[0]["text"]+ assert "**" not in text+ assert "*To add an agent*" in text+ assert "`!invite-agent @agent-name`" in text++# ── Outbound mention resolution ──────────────────────────────────────────────@@ -732,13 +747,18 @@ def test_outbound_unknown_mention_left_as_plain_text() -> None:class _FakeDMWebClient:"""Records conversations_create / conversations_invite kwargs."""- def __init__(self, invite_error: str | None = None) -> None:+ def __init__(+ self, invite_error: str | None = None, taken: frozenset[str] = frozenset()+ ) -> None:self.creates: list[dict[str, Any]] = []self.invites: list[dict[str, Any]] = []self._invite_error = invite_error+ self._taken = takenasync def conversations_create(self, **kwargs: Any) -> dict[str, Any]:self.creates.append(kwargs)+ if kwargs["name"] in self._taken:+ raise SlackApiError("name_taken", response={"error": "name_taken"})return {"channel": {"id": "C-DM"}}async def conversations_invite(self, **kwargs: Any) -> dict[str, Any]:@@ -757,7 +777,7 @@ def test_create_dm_channel_makes_private_channel_and_invites_user() -> None:channel_id = _run(adapter.create_dm_channel(- agent_name="agent.bot",+ agent_name="Order Planner",user_name="doe.jane",user_external_id="U123",)@@ -765,13 +785,28 @@ def test_create_dm_channel_makes_private_channel_and_invites_user() -> None:assert channel_id == "C-DM"assert len(fake.creates) == 1- # A private channel, named dm-<user>-<agent> with non-slug chars dashed.+ # A private channel, named <agent>-<user> with non-slug runs dashed.assert fake.creates[0]["is_private"] is True- assert fake.creates[0]["name"] == "dm-doe-jane-agent-bot"+ assert fake.creates[0]["name"] == "order-planner-doe-jane"# The single user is invited to the freshly created channel.assert fake.invites == [{"channel": "C-DM", "users": "U123"}]+def test_create_dm_channel_suffixes_a_taken_name() -> None:+ adapter = _adapter()+ fake = _FakeDMWebClient(taken=frozenset({"buddy-raul"}))+ adapter._web_client = fake # type: ignore[assignment]++ _run(+ adapter.create_dm_channel(+ agent_name="buddy", user_name="raul", user_external_id="U1"+ )+ )++ assert [create["name"] for create in fake.creates][0] == "buddy-raul"+ assert re.fullmatch(r"buddy-raul-[0-9a-f]{8}", fake.creates[1]["name"])++def test_create_dm_channel_tolerates_already_in_channel() -> None:adapter = _adapter()fake = _FakeDMWebClient(invite_error="already_in_channel")diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py b/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.pyindex 0cb54ed98..168919239 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_block_fallback.py@@ -53,7 +53,12 @@ async def test_rejected_blocks_publish_one_threaded_recoverable_text_card(assert (await adapter.post_blocks(- "channel-demo", "worker", TEXT, BLOCKS, "channel-demo:1.0"+ "channel-demo",+ "worker",+ TEXT,+ BLOCKS,+ "channel-demo:1.0",+ reply_broadcast=False,)== "channel-demo:2.0")@@ -103,7 +108,10 @@ async def test_definitive_nonformat_post_refusal_does_not_retry_as_text(adapter,client = adapter._web_clientclient.chat_postMessage.side_effect = refusal(code)assert (- await adapter.post_blocks("channel-demo", "worker", TEXT, BLOCKS, "1.0") is None+ await adapter.post_blocks(+ "channel-demo", "worker", TEXT, BLOCKS, "1.0", reply_broadcast=False+ )+ is None)client.chat_postMessage.assert_called_once()@@ -116,7 +124,9 @@ async def test_uncertain_post_is_not_repeated_as_text(adapter, error):client = adapter._web_clientclient.chat_postMessage.side_effect = errorwith pytest.raises(type(error)):- await adapter.post_blocks("channel-demo", "worker", TEXT, BLOCKS, "1.0")+ await adapter.post_blocks(+ "channel-demo", "worker", TEXT, BLOCKS, "1.0", reply_broadcast=False+ )client.chat_postMessage.assert_called_once()diff --git a/core/tests/switch_core/gateway/conftest.py b/core/tests/switch_core/gateway/conftest.pyindex 5349bf3cb..22488e145 100644--- a/core/tests/switch_core/gateway/conftest.py+++ b/core/tests/switch_core/gateway/conftest.py@@ -75,6 +75,9 @@ class _FakeLifecycle:def get_by_type(self, client_type: str, tenant_id: str) -> list[Any]:return []+ def get(self, client_id: str) -> None:+ return None+class _FakeListener:"""Records subscriptions; a test rings a room by hand, or deliberately not."""diff --git a/core/tests/switch_core/gateway/test_buddy_onboarding_acceptance.py b/core/tests/switch_core/gateway/test_buddy_onboarding_acceptance.pynew file mode 100644index 000000000..195fdc62a--- /dev/null+++ b/core/tests/switch_core/gateway/test_buddy_onboarding_acceptance.py@@ -0,0 +1,147 @@+"""Buddy onboarding acceptance tests: failure/retry paths for bridged direct+chats, against real Postgres."""++from __future__ import annotations++import uuid++import httpx+from sqlalchemy import func, select++from switch_core.db.models import (+ Agent,+ Client,+ CollaborationBridge,+ ExternalUser,+ ExternalUserClaim,+ Room,+ User,+)+from tests.switch_core.gateway.conftest import _Harness+from tests.switch_core.gateway.test_chats_bridged_direct import (+ _FakeCollabLifecycle,+ _FakeCore,+)+from tests.switch_core.gateway.test_chats_routes import _code++TENANT = "00000000-0000-0000-0000-000000000000"+++async def _slack(+ chats: _Harness, *, link: User | None, channel_creation_enabled: bool = True+) -> tuple[str, _FakeCore]:+ """A running Slack bridge on which `link`, if given, has claimed `U-ALICE`."""+ tag = uuid.uuid4().hex[:8]+ bot_suffix = f"-{tag}"+ async with chats.factory() as session:+ bot = Client(+ transport_user_id=f"@slack-bot{bot_suffix}:switch.test",+ display_name=f"Slack Bot {tag}",+ type="bridge",+ )+ session.add(bot)+ await session.flush()+ bridge = CollaborationBridge(+ tenant_id=TENANT,+ type="slack",+ display_name=f"Acme Slack {tag}",+ connection_config={},+ client_id=bot.id,+ status="active",+ channel_creation_enabled=channel_creation_enabled,+ )+ session.add(bridge)+ await session.flush()+ if link is not None:+ person = Client(+ transport_user_id=f"@slack-alice{bot_suffix}:switch.test",+ display_name="alice.s",+ type="human",+ )+ session.add(person)+ await session.flush()+ external = ExternalUser(+ bridge_id=bridge.id,+ external_user_id="U-ALICE",+ external_username="alice.s",+ client_id=person.id,+ )+ session.add(external)+ await session.flush()+ session.add(+ ExternalUserClaim(external_user_id=external.id, user_id=link.id)+ )+ await session.commit()+ bridge_id = bridge.id+ bot_transport_id = bot.transport_user_id+ core = _FakeCore(bot_transport_id, {"alice.s": "U-ALICE"})+ if not hasattr(chats.room_service, "_collab_lifecycle") or not isinstance(+ chats.room_service._collab_lifecycle,+ _FakeCollabLifecycle, # type: ignore[union-attr]+ ):+ chats.room_service._collab_lifecycle = _FakeCollabLifecycle({}) # type: ignore[assignment]+ chats.room_service._collab_lifecycle._bridges[bridge_id] = core # type: ignore[union-attr]+ return bridge_id, core+++async def _create(+ chats: _Harness,+ agents: list[Agent],+ bridge_id: str,+ request_id: str = "c1",+ resume_only: bool = False,+) -> httpx.Response:+ return await chats.client.post(+ "/chats",+ json={+ "agentIds": [agent.id for agent in agents],+ "requestId": request_id,+ "bridgeId": bridge_id,+ "resumeOnly": resume_only,+ },+ headers=chats.as_user(chats.alice),+ )+++async def test_bridge_with_channel_creation_disabled_returns_422_chat_not_created(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(+ chats, link=chats.alice, channel_creation_enabled=False+ )++ response = await _create(chats, [agent], bridge_id)++ assert response.status_code == 422+ assert _code(response) == "CHAT_NOT_CREATED"+ assert core.dm_calls == []+ async with chats.factory() as session:+ room_count = await session.scalar(+ select(func.count()).select_from(Room).where(Room.bridge_id == bridge_id)+ )+ assert room_count == 0+++async def test_user_linked_on_two_slack_bridges_creates_on_specified_bridge(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_a_id, core_a = await _slack(chats, link=chats.alice)+ bridge_b_id, core_b = await _slack(chats, link=chats.alice)++ response = await _create(chats, [agent], bridge_b_id, request_id="c2")++ assert response.status_code == 200, response.text+ chat = response.json()["chat"]+ assert chat["bridgeType"] == "slack"+ assert chat["channelType"] == "direct"+ assert core_a.dm_calls == []+ assert core_b.dm_calls == [+ {"agent_name": "helper", "user_name": "alice.s", "user_external_id": "U-ALICE"}+ ]+ async with chats.factory() as session:+ room = await session.get(Room, chat["roomId"])+ assert room is not None+ assert room.bridge_id == bridge_b_id+ assert room.external_channel_id == "C-DM-1"diff --git a/core/tests/switch_core/gateway/test_chats_agent_created.py b/core/tests/switch_core/gateway/test_chats_agent_created.pyindex 7cedcf7b1..4a6532492 100644--- a/core/tests/switch_core/gateway/test_chats_agent_created.py+++ b/core/tests/switch_core/gateway/test_chats_agent_created.py@@ -9,9 +9,11 @@ from types import SimpleNamespacefrom typing import Anyimport pytest+from sqlalchemy import func, selectfrom switch_core.bridges.agent.protocol.agent_core import AgentCore-from switch_core.db.models import Agent+from switch_core.chats.service import ChatError+from switch_core.db.models import Agent, Roomfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore@@ -34,6 +36,7 @@ def _protocol(chats: _Harness) -> SimpleNamespace:room_service=chats.room_service,client_lifecycle=chats.lifecycle,_member_adder=chats.service.add_member,+ _member_join_check=chats.service.require_can_join,)for name in ("run_service", "_resolve_acting_identity", "_resolve_group_name"):setattr(protocol, name, partial(getattr(AgentCore, name), protocol))@@ -93,3 +96,47 @@ async def test_refused_where_it_makes_no_sense(agent = await chats.agent("buddy", owner=chats.alice)with pytest.raises(ValueError, match=message):await _create(chats, agent, **overrides)+++async def test_an_owner_outside_the_workspace_is_refused_before_the_room(+ chats: _Harness,+) -> None:+ agent = await chats.agent("buddy", owner=chats.carol)++ with pytest.raises(ValueError, match="not a member of this workspace"):+ await _create(chats, agent)++ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 0+++async def test_an_owner_refused_after_the_room_is_made_takes_the_room_with_it(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("buddy", owner=chats.alice)++ async def refusing(*args: Any) -> None:+ raise ChatError(422, "NOT_A_TENANT_MEMBER", "Left the workspace.")++ monkeypatch.setattr(chats.service, "add_member", refusing)+ with pytest.raises(ValueError, match="Left the workspace"):+ await _create(chats, agent)++ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 0+++async def test_any_failure_adding_the_owner_takes_the_room_with_it_and_surfaces(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("buddy", owner=chats.alice)++ async def crashing(*args: Any) -> None:+ raise RuntimeError("join failed")++ monkeypatch.setattr(chats.service, "add_member", crashing)+ with pytest.raises(RuntimeError, match="^join failed$"):+ await _create(chats, agent)++ async with chats.factory() as session:+ assert await session.scalar(select(func.count()).select_from(Room)) == 0diff --git a/core/tests/switch_core/gateway/test_chats_bridged_direct.py b/core/tests/switch_core/gateway/test_chats_bridged_direct.pyindex 1c2e489b7..6ae5fcf65 100644--- a/core/tests/switch_core/gateway/test_chats_bridged_direct.py+++ b/core/tests/switch_core/gateway/test_chats_bridged_direct.py@@ -11,7 +11,7 @@ from typing import Anyimport httpximport pytest-from sqlalchemy import func, select+from sqlalchemy import func, select, updatefrom switch_core.db.models import (Agent,@@ -72,10 +72,10 @@ class _FakeCore:def add_room_mapping(self, *args: Any) -> None:return None- async def ensure_users_in_room(- self, room_id: str, transport_room_id: str, user_names: list[str]+ async def ensure_external_users_in_room(+ self, room_id: str, transport_room_id: str, external_user_ids: list[str]) -> None:- self.users_added.append(user_names)+ self.users_added.append(external_user_ids)class _FakeCollabLifecycle:@@ -175,6 +175,41 @@ async def test_a_bridged_chat_opens_a_dm_with_the_callers_linked_account(assert room is not Noneassert room.bridge_id == bridge_idassert room.external_channel_id == "C-DM-1"+ assert room.name == "helper · Acme Slack"+++async def test_a_bridged_chat_goes_by_the_agents_display_name(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ async with chats.factory() as session:+ await session.execute(+ update(Agent).where(Agent.id == agent.id).values(display_name="Helper Bot")+ )+ await session.commit()+ bridge_id, core = await _slack(chats, link=chats.alice)++ response = await _create(chats, [agent], bridge_id)++ assert response.status_code == 200, response.text+ assert response.json()["chat"]["name"] == "Helper Bot · Acme Slack"+ assert [call["agent_name"] for call in core.dm_calls] == ["Helper Bot"]+++async def test_the_linked_account_is_used_even_when_another_shares_its_name(+ chats: _Harness,+) -> None:+ """After a rename, another cached account on the bridge can hold the+ linked one's old handle; the hand-off must still reach the linked one."""+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ core._known = {"alice.s": "U-OTHER"}++ response = await _create(chats, [agent], bridge_id)++ assert response.status_code == 200, response.text+ assert [call["user_external_id"] for call in core.dm_calls] == ["U-ALICE"]+ assert core.users_added == [["U-ALICE"]]async def test_a_retry_returns_the_same_chat_and_opens_one_channel(@@ -344,7 +379,7 @@ async def test_a_retry_after_a_failed_bridge_invite_puts_the_bridge_in(room = await _create_on(chats, chats.service, agent, bridge_id)assert bridge_invites == [room.transport_room_id]- assert core.users_added == [["alice.s"]]+ assert core.users_added == [["U-ALICE"]]assert len(core.dm_calls) == 1@@ -405,3 +440,69 @@ async def test_resuming_a_create_that_failed_after_saving_finishes_it(assert resumed.status_code == 200, resumed.textassert again.json()["chat"]["roomId"] == resumed.json()["chat"]["roomId"]assert len(core.dm_calls) == 1+++async def test_two_linked_accounts_on_the_bridge_are_refused(+ chats: _Harness,+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ async with chats.factory() as session:+ person = Client(+ transport_user_id="@slack-alice-old:switch.test",+ display_name="alice.old",+ type="human",+ )+ session.add(person)+ await session.flush()+ external = ExternalUser(+ bridge_id=bridge_id,+ external_user_id="U-ALICE-OLD",+ external_username="alice.old",+ client_id=person.id,+ )+ session.add(external)+ await session.flush()+ session.add(+ ExternalUserClaim(external_user_id=external.id, user_id=chats.alice.id)+ )+ await session.commit()++ response = await _create(chats, [agent], bridge_id)++ assert response.status_code == 409+ assert _code(response) == "ACCOUNTS_AMBIGUOUS"+ assert core.dm_calls == []+++async def test_a_retry_after_the_linked_account_changed_is_refused(+ chats: _Harness, monkeypatch: pytest.MonkeyPatch+) -> None:+ agent = await chats.agent("helper", owner=chats.alice)+ bridge_id, core = await _slack(chats, link=chats.alice)+ provisioning = chats.room_service._provisioning+ invite = provisioning.invite_to_room+ failures = [RuntimeError("invite failed")]++ async def failing_invite(room_id: str, user_id: str) -> None:+ if user_id == "@slack-bot:switch.test" and failures:+ raise failures.pop()+ await invite(room_id, user_id)++ monkeypatch.setattr(provisioning, "invite_to_room", failing_invite)+ with pytest.raises(RuntimeError, match="invite failed"):+ await _create_on(chats, chats.service, agent, bridge_id)+ async with chats.factory() as session:+ await session.execute(+ update(ExternalUser)+ .where(ExternalUser.external_user_id == "U-ALICE")+ .values(external_user_id="U-ALICE-NEW")+ )+ await session.commit()++ response = await _create(chats, [agent], bridge_id)++ assert response.status_code == 409+ assert _code(response) == "LINKED_ACCOUNT_CHANGED"+ assert core.users_added == []+ assert len(core.dm_calls) == 1diff --git a/core/tests/switch_core/session_activity/test_publisher.py b/core/tests/switch_core/session_activity/test_publisher.pyindex b94ea2482..171508bf8 100644--- a/core/tests/switch_core/session_activity/test_publisher.py+++ b/core/tests/switch_core/session_activity/test_publisher.py@@ -177,6 +177,7 @@ async def _step(turn_id="turn-1",title="",text="",+ message_id=ASKED,):await service.report_item(AGENT,@@ -191,7 +192,7 @@ async def _step(command_id="command-1" if kind == "turn" else None,room_id=room_id,thread_id=ASKED,- message_id=ASKED,+ message_id=message_id,occurred_at=datetime.now(UTC),usage=[],)@@ -320,6 +321,45 @@ async def test_a_card_goes_into_the_thread_it_answers(assert (await _card_post(session_factory)).thread_ref == ASKED_POST+ ("message_id", "at_root"), [(ASKED, True), ("sw_reply", False)]+)+async def test_a_card_says_whether_its_turn_was_asked_at_the_channel_root(+ service, publisher, platform, bridged, message_id, at_root+):+ """So an adapter that can also show a thread reply in the channel does,+ for a question threaded under a channel-root message only."""+ await _step(+ service,+ bridged.room_id,+ item_id="turn",+ kind="turn",+ status="running",+ revision=1,+ message_id=message_id,+ )+ await _open(service, bridged.room_id, thread_id=ASKED)+ await platform.wait_until(+ lambda: any(isinstance(d.content, RequestCard) for d in platform.drawn)+ )+ [card] = [d for d in platform.drawn if isinstance(d.content, RequestCard)]+ assert card.thread_ref == ASKED_POST+ assert card.content.asked_at_root is at_root+++async def test_a_card_whose_turn_is_not_recorded_stays_in_its_thread(+ service, publisher, platform, bridged+):+ """An unrecorded turn may have been a thread conversation the channel was+ never part of, so its card is not also shown in the channel."""+ await _open(service, bridged.room_id, thread_id=ASKED)+ await platform.wait_until(+ lambda: any(isinstance(d.content, RequestCard) for d in platform.drawn)+ )+ [card] = [d for d in platform.drawn if isinstance(d.content, RequestCard)]+ assert card.content.asked_at_root is False++async def test_a_card_in_a_thread_names_the_owner_who_may_answer_it(service, publisher, platform, bridged, session_factory):diff --git a/core/tests/switch_core/test_dm_rooms.py b/core/tests/switch_core/test_dm_rooms.pyindex d130d88c5..6a1f64102 100644--- a/core/tests/switch_core/test_dm_rooms.py+++ b/core/tests/switch_core/test_dm_rooms.py@@ -72,7 +72,9 @@ class _FakeAgentStore:self._names = namesasync def get(self, session: Any, agent_id: str) -> Any:- return SimpleNamespace(id=agent_id, name=self._names[agent_id])+ return SimpleNamespace(+ id=agent_id, name=self._names[agent_id], display_name=None+ )class _FakeBridge:diff --git a/core/tests/switch_core/test_official_templates.py b/core/tests/switch_core/test_official_templates.pyindex 3c21fc1b6..93d4a3e86 100644--- a/core/tests/switch_core/test_official_templates.py+++ b/core/tests/switch_core/test_official_templates.py@@ -9,6 +9,7 @@ from pathlib import Pathimport yaml+from switch_core.agent_templates import repo_notefrom switch_core.management.schemas import MAX_INSTRUCTIONS_BYTESfrom switch_core.official_templates import (_SHIPPED,@@ -27,6 +28,7 @@ _PACKAGED = _REPO / "core" / "switch_core" / "official_templates"_KNOWLEDGE = _REPO / "switch-expert" / "knowledge"+_PLAYBOOK = _PACKAGED / "switch-buddy" / "PLAYBOOK.md"def test_the_switch_expert_copies_match_the_repository():@@ -113,7 +115,9 @@ def test_every_official_template_s_instructions_fit_the_server_limit():else [data["agent"]])for agent in agents:- size = len(agent["instructions"].encode())+ # A template with a repo appends its note to the instructions.+ note = repo_note(agent["repo"]) if agent.get("repo") else ""+ size = len((agent["instructions"] + note).encode())assert size <= MAX_INSTRUCTIONS_BYTES, (template.id, size)@@ -268,8 +272,9 @@ def test_switch_buddy_makes_every_private_room_private_in_switch():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)+ items += _PLAYBOOK.read_text().split("\n## ")private_rooms = [i for i in items if "channel_private" in i or "include_owner" in i]- assert len(private_rooms) >= 2+ assert len(private_rooms) >= 3for item in private_rooms:item = " ".join(item.split())assert '`read_visibility` and `write_visibility` "private"' in item, item@@ -291,3 +296,64 @@ def test_switch_buddy_tells_telegram_users_to_reply_to_the_bot():"reply to the bot's message" in textor "reply to the Switch bot's message" in text)+++def test_switch_buddy_offers_choices_in_its_question_form():+ """Switch draws a host's question form as a card with buttons on Slack and+ Discord, but only for one single-choice question, and hosts without forms+ need the choices as numbered text."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ assert "use your host's question form" in text+ assert "`AskUserQuestion`" in text+ assert "one single-choice question per form" in text+ assert "With no question form, list numbered options" in text+ # Form answers are not consent to create: the proposal is its own form.+ assert "end with a separate proposal" in text+ assert "create only after explicit confirmation" in text+++def test_every_playbook_section_switch_buddy_is_pointed_at_exists():+ """switch-buddy reads the playbook from its clone of the repository when+ its instructions point at a section, so the path and each section named+ must exist as written."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ paths = re.findall(r"`switch/(\S+?PLAYBOOK\.md)`", text)+ assert paths+ for path in paths:+ assert (_REPO / path).resolve() == _PLAYBOOK.resolve(), path+ headings = set(re.findall(r"^## (.+)$", _PLAYBOOK.read_text(), re.MULTILINE))+ named = set(re.findall(r'§ "([^"]+)"', text))+ assert len(named) >= 10+ assert named - headings == set()+++def test_switch_buddy_checks_the_services_an_agent_needs_before_proposing():+ """An agent created without the services its job needs guesses its way+ in, so buddy checks them first and offers the grant in the proposal."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ assert "Before proposing, check the services its job needs" in text+ assert "`get_my_context`" in text and "`set_agent_service`" in text+ assert "for a missing one, say so and link where to connect it" in text+ playbook = " ".join(_PLAYBOOK.read_text().split())+ assert "Only your owner's own agents, and only after a yes" in playbook+ assert "[Connectors](switchdash://open/connections)" in playbook+++def test_switch_buddy_carries_on_without_its_playbook():+ """A fresh install may have no clone, and an older tag no playbook: that+ must pause only what needs the detail, never basic onboarding."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ assert "read it only if you need more" in text+ assert "pause only the action that needs the missing detail" in text+ assert "Never ask the person for the file" in text+++def test_switch_buddy_always_tells_telegram_users_to_reply_to_the_bot():+ """In a Telegram group the bot sees only commands and replies to its own+ messages, so every Telegram walkthrough must say to reply, playbook or not."""+ text = " ".join((_PACKAGED / "switch-buddy" / "AGENT.md").read_text().split())+ assert "Every Telegram walkthrough, with or without the playbook" in text+ assert (+ "reply to a Switch bot message with the agent's exact name and their request"+ in text+ )