Skip to content

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

fix: Console and core bug sweep (CHOO-2344) (#285)

Louis Amaudruze76b79cdedd4
diff --git a/connectors/claude-code-plugin/skills/configure/SKILL.md b/connectors/claude-code-plugin/skills/configure/SKILL.md
index fca3c132b..7fad677c5 100644
--- a/connectors/claude-code-plugin/skills/configure/SKILL.md
+++ b/connectors/claude-code-plugin/skills/configure/SKILL.md
@@ -323,11 +323,13 @@ with no live session. It is built from what you record here and in Step 5, so it
carries the channels flag when you said channels work:
```
-cd <repo_dir> && claude "connect to switch room <name>" \
+cd <repo_dir> && claude "connect to switch room <name> — if you are asked which agent you are, you are <agent_name>" \
--dangerously-load-development-channels plugin:switch-connector@switch-plugins
```
-(without the flag when `channels_enabled` is false).
+(without the flag when `channels_enabled` is false). The prompt names the agent
+so a session started in a directory holding several of them answers
+`select_agent` without the user having to.
**Note the path is not quoted** in what Switch generates, so a `repo_dir`
containing a space produces a command that breaks when pasted. If the directory
@@ -810,7 +812,7 @@ Report the registered subagents (Switch name + id; not the token) and explain
that each runs as its own session:
```
-cd <repo> && claude "connect to switch room <name>" \
+cd <repo> && claude "connect to switch room <name> — if you are asked which agent you are, you are <agent_name>" \
--agent <subagent_name> \
--settings .claude/switch-subagents/<subagent_name>.settings.json \
--dangerously-load-development-channels plugin:switch-connector@switch-plugins
diff --git a/connectors/codex-plugin/README.md b/connectors/codex-plugin/README.md
index eb4f925fc..f943154fd 100644
--- a/connectors/codex-plugin/README.md
+++ b/connectors/codex-plugin/README.md
@@ -165,10 +165,11 @@ knowing:
- `repo_dir` should be the directory the credentials were written into. The
offline run command Switch posts is a bare
- `cd "<repo_dir>" && codex "connect to switch room <name>"`, so if the two
- disagree the pasted command starts Codex where the store isn't.
+ `cd "<repo_dir>" && codex "connect to switch room <name> — if you are asked which agent you are, you are <agent_name>"`, so if the
+ two disagree the pasted command starts Codex where the store isn't.
- Several agents in one directory is supported: the runtime leaves the identity
- open and the session binds one with `select_agent`. Agents spanning **several
+ open and the session binds one with `select_agent` — which the prompt above
+ answers, since it names the agent the command was generated for. Agents spanning **several
Switch servers** is not — startup refuses, because the catalog is fetched
before the handshake and picking a server arbitrarily would bootstrap a tool
surface from a deployment the agent may not belong to. `SWITCH_API_ENDPOINT`
diff --git a/connectors/codex-plugin/skills/configure/SKILL.md b/connectors/codex-plugin/skills/configure/SKILL.md
index bc1b78117..db7bc2120 100644
--- a/connectors/codex-plugin/skills/configure/SKILL.md
+++ b/connectors/codex-plugin/skills/configure/SKILL.md
@@ -214,9 +214,12 @@ Switch shows room participants a paste-ready command when the agent is
addressed with no live session:
```
-cd "<repo_dir>" && codex "connect to switch room <name>"
+cd "<repo_dir>" && codex "connect to switch room <name> — if you are asked which agent you are, you are <agent_name>"
```
+The prompt names the agent so a session started in a directory holding several
+of them answers `select_agent` without the user having to.
+
`repo_dir` is what makes it useful — **and for Codex it matters twice over**,
because the runtime reads the agent store from the session's working directory.
`repo_dir` should therefore be **the directory this skill writes the credentials
@@ -429,8 +432,8 @@ Be straight with the user; do not imply parity.
**Works:** the full Switch tool surface (including `send_attachment` /
`download_attachment`), room participation, threads, tasks, roles, moderation,
and the offline run command Switch posts — which is a bare
-`cd "<repo_dir>" && codex "connect to switch room <name>"`, so it works as
-written provided `repo_dir` is where the store lives.
+`cd "<repo_dir>" && codex "connect to switch room <name> — if you are asked which agent you are, you are <agent_name>"`, so it works
+as written provided `repo_dir` is where the store lives.
**Does not work, or works differently:**
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
new file mode 100644
index 000000000..d1076cb30
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-icon-backfill-toast.test.ts
@@ -0,0 +1,127 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The agent-icon backfill notice must be said once per server per run, however
+ * many times the sidebar refreshes (CHOO-2344).
+ *
+ * `refreshSidebarRoomState` runs on first paint, window focus, sign-in, the
+ * background reconcile, the retry button and every membership-changing
+ * mutation. Reporting the backfill outcome on each of those turned one
+ * unresolved condition — a signed-out server, a server without the icon
+ * endpoint — into a toast every few seconds that the user could not dismiss
+ * for good.
+ */
+
+const toast = vi.fn();
+const backfillAgentIcons = vi.fn();
+
+const LOCATION = { id: 'loc-1' };
+const AGENT = {
+ id: 'agent-1',
+ name: 'agent one',
+ serverId: 'server-1',
+ switchAgentId: 'switch-agent-1',
+ createdAt: '2026-01-01T00:00:00.000Z',
+};
+
+vi.mock('@renderer/lib/hooks/use-toast', () => ({ toast }));
+vi.mock('@renderer/lib/ipc', () => ({
+ rpc: { switchServers: { backfillAgentIcons } },
+}));
+vi.mock('@renderer/features/locations/stores/agents-store', () => ({
+ agentsStore: {
+ load: vi.fn().mockResolvedValue(undefined),
+ byLocation: new Map([[LOCATION.id, [AGENT]]]),
+ agentsOnServerAtLocation: () => [AGENT],
+ },
+}));
+vi.mock('@renderer/features/switch-servers/switch-rooms-store', () => ({
+ switchRoomsStore: {
+ ensureMembershipsFor: vi.fn().mockResolvedValue(undefined),
+ loadRoomNames: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: { activeServerId: 'server-1' },
+}));
+vi.mock('@renderer/lib/stores/app-state', () => ({
+ sidebarStore: {
+ orderedLocations: [LOCATION],
+ filteredLocations: [LOCATION],
+ visibleSessionsForLocation: () => [],
+ orderAgents: (entries: unknown[]) => entries,
+ },
+}));
+vi.mock('@renderer/utils/logger', () => ({
+ log: { warn: vi.fn(), info: vi.fn(), debug: vi.fn() },
+}));
+
+/** Fresh module state per test — the "said it already" record is per run. */
+async function loadSubject() {
+ vi.resetModules();
+ return await import('./sidebar-tree-data');
+}
+
+describe('agent icon backfill reporting', () => {
+ beforeEach(() => {
+ toast.mockClear();
+ backfillAgentIcons.mockReset();
+ });
+
+ it('reports a server without the icon endpoint once, not on every refresh', async () => {
+ backfillAgentIcons.mockResolvedValue({ kind: 'unsupported' });
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(toast.mock.calls[0][0].title).toContain('does not support agent icons');
+ });
+
+ it('reports a failed backfill once, not on every refresh', async () => {
+ // The reported case: signed out, so fetching the agents throws every time.
+ backfillAgentIcons.mockRejectedValue(new Error('not signed in'));
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+
+ expect(toast).toHaveBeenCalledTimes(1);
+ expect(toast.mock.calls[0][0].title).toBe('Agent icons could not be saved');
+ });
+
+ it('reports agents that kept the old icon once', async () => {
+ backfillAgentIcons.mockResolvedValue({ kind: 'partial', written: 1, failed: 2 });
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+
+ expect(toast).toHaveBeenCalledTimes(1);
+ });
+
+ it('says nothing at all when the backfill succeeds', async () => {
+ backfillAgentIcons.mockResolvedValue({ kind: 'written', written: 3 });
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+
+ expect(toast).not.toHaveBeenCalled();
+ });
+
+ it('still retries the work itself after a failure', async () => {
+ // Reporting once must not turn into trying once: signing in should fix it
+ // without a restart, which needs the next refresh to ask again.
+ backfillAgentIcons.mockRejectedValue(new Error('not signed in'));
+ const { refreshSidebarRoomState } = await loadSubject();
+
+ await refreshSidebarRoomState(false);
+ await refreshSidebarRoomState(false);
+
+ expect(backfillAgentIcons).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
index 0728867b0..f9e406607 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/sidebar-tree-data.ts
@@ -167,10 +167,10 @@ async function giveExistingAgentsAnIcon(): Promise<void> {
const serverIds = new Set(switchIdentities().map((identity) => identity.serverId));
for (const serverId of serverIds) {
try {
- reportBackfill(await rpc.switchServers.backfillAgentIcons(serverId));
+ reportBackfill(serverId, await rpc.switchServers.backfillAgentIcons(serverId));
} catch (cause) {
log.warn('could not give existing agents their icons', { serverId, cause });
- toast({
+ reportOnce(serverId, 'failed', {
title: 'Agent icons could not be saved',
description:
'Your agents show a generated icon here, but the Switch server has not stored it — so they keep their old picture in Slack and the other chat apps.',
@@ -180,9 +180,31 @@ async function giveExistingAgentsAnIcon(): Promise<void> {
}
}
-function reportBackfill(outcome: AgentIconBackfill): void {
+/**
+ * What each server was last told to the user about, so an unresolved condition
+ * is not re-announced on every refresh.
+ *
+ * The caller runs on first paint, window focus, sign-in, the background
+ * reconcile, the retry button and every membership-changing mutation. A server
+ * that is signed out or too old to store icons fails all of them, which turned
+ * one standing problem into a toast every few seconds (CHOO-2344).
+ *
+ * Keyed by outcome, not a bare "said something already": if the situation
+ * changes — a signed-out server starts answering and turns out to be too old —
+ * that is news and gets said. Cleared on success so a later regression is not
+ * swallowed by a record of the last one.
+ */
+const reportedBackfill = new Map<string, string>();
+
+function reportOnce(serverId: string, outcome: string, notice: Parameters<typeof toast>[0]) {
+ if (reportedBackfill.get(serverId) === outcome) return;
+ reportedBackfill.set(serverId, outcome);
+ toast(notice);
+}
+
+function reportBackfill(serverId: string, outcome: AgentIconBackfill): void {
if (outcome.kind === 'unsupported') {
- toast({
+ reportOnce(serverId, 'unsupported', {
title: 'This Switch server does not support agent icons yet',
description:
'Your agents show a generated icon here, but it cannot be saved, so they keep their old picture in Slack and the other chat apps. Updating the server fixes it.',
@@ -191,11 +213,13 @@ function reportBackfill(outcome: AgentIconBackfill): void {
return;
}
if (outcome.kind === 'partial') {
- toast({
+ reportOnce(serverId, `partial:${outcome.failed}`, {
title: `${outcome.failed} agent${outcome.failed === 1 ? '' : 's'} kept the old icon`,
description:
'Their icon could not be saved to the Switch server, so it will not show in Slack or the other chat apps.',
variant: 'destructive',
});
+ return;
}
+ reportedBackfill.delete(serverId);
}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx b/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx
index 00ace4696..2c2a040cb 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx
@@ -1,5 +1,5 @@
import { CheckIcon, XIcon } from 'lucide-react';
-import React, { useCallback, useState } from 'react';
+import React, { useCallback, useRef, useState } from 'react';
import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';
import { Button } from '@renderer/lib/ui/button';
import { Dialog, DialogContent, DialogContentArea, DialogFooter } from '@renderer/lib/ui/dialog';
@@ -58,6 +58,7 @@ export function TelemetryConsentDialog({ onAnswered }: { onAnswered: () => void
const { value, updateAsync } = useAppSettingsKey('telemetry');
const [enabled, setEnabled] = useState(value?.enabled ?? false);
const [saving, setSaving] = useState(false);
+ const popupRef = useRef<HTMLDivElement>(null);
const confirm = useCallback(() => {
setSaving(true);
@@ -81,7 +82,16 @@ export function TelemetryConsentDialog({ onAnswered }: { onAnswered: () => void
// Controlled `open` with no `onOpenChange`: Escape and outside clicks are
// requests the parent ignores, so the prompt cannot be dismissed unanswered.
<Dialog open>
- <DialogContent aria-labelledby="telemetry-consent-heading" onKeyDown={onKeyDown}>
+ {/* Focus the popup, not its first tabbable child. The default would land
+ on the consent switch, which renders its focus ring as a highlighted
+ band around the toggle row — reading as a pre-selected answer to a
+ question the user has not answered yet. */}
+ <DialogContent
+ ref={popupRef}
+ initialFocus={popupRef}
+ aria-labelledby="telemetry-consent-heading"
+ onKeyDown={onKeyDown}
+ >
<div className="flex flex-col gap-2 p-6 pb-4">
<h2 id="telemetry-consent-heading" className="text-base font-normal text-foreground">
Help improve Switch Console
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.test.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.test.ts
new file mode 100644
index 000000000..709d6b299
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.test.ts
@@ -0,0 +1,64 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Identical toasts must take one slot, not one per firing (CHOO-2344).
+ *
+ * Anything toasting from a repeating trigger — a refresh, a poll, a retry —
+ * otherwise stacks copies of a single problem faster than they can be
+ * dismissed. Sonner replaces a toast whose id it already holds, so a stable id
+ * derived from the text is what collapses them.
+ */
+
+const sonnerToast = Object.assign(vi.fn(), { error: vi.fn() });
+
+vi.mock('sonner', () => ({ toast: sonnerToast }));
+
+const { toast } = await import('./use-toast');
+
+describe('toast identity', () => {
+ beforeEach(() => {
+ sonnerToast.mockClear();
+ sonnerToast.error.mockClear();
+ });
+
+ it('gives the same text and severity the same id', () => {
+ toast({ title: 'Nope', description: 'it broke', variant: 'destructive' });
+ toast({ title: 'Nope', description: 'it broke', variant: 'destructive' });
+
+ const [first, second] = sonnerToast.error.mock.calls.map((call) => call[1].id);
+ expect(first).toBe(second);
+ });
+
+ it('separates toasts that differ in text', () => {
+ toast({ title: 'Nope', description: 'it broke', variant: 'destructive' });
+ toast({ title: 'Nope', description: 'it broke differently', variant: 'destructive' });
+
+ const [first, second] = sonnerToast.error.mock.calls.map((call) => call[1].id);
+ expect(first).not.toBe(second);
+ });
+
+ it('separates the same text at different severities', () => {
+ toast({ title: 'Saved', variant: 'destructive' });
+ toast({ title: 'Saved' });
+
+ const errorId = sonnerToast.error.mock.calls[0][1].id;
+ const plainId = sonnerToast.mock.calls[0][1].id;
+ expect(errorId).not.toBe(plainId);
+ });
+
+ it('lets a caller override the identity', () => {
+ toast({ title: 'Same words', id: 'left' });
+ toast({ title: 'Same words', id: 'right' });
+
+ const [first, second] = sonnerToast.mock.calls.map((call) => call[1].id);
+ expect(first).toBe('left');
+ expect(second).toBe('right');
+ });
+
+ it('still passes the action through', () => {
+ const onClick = vi.fn();
+ toast({ title: 'Retry?', action: { label: 'Retry', onClick } });
+
+ expect(sonnerToast.mock.calls[0][1].action).toEqual({ label: 'Retry', onClick });
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.ts b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.ts
index 8e4c8b1d8..dd225e19d 100644
Binary files a/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.ts and b/console/apps/switch-console-desktop/src/renderer/lib/hooks/use-toast.ts differ
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/telemetry-consent-initial-focus.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/telemetry-consent-initial-focus.test.tsx
new file mode 100644
index 000000000..e5d577d0b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/telemetry-consent-initial-focus.test.tsx
@@ -0,0 +1,75 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { TelemetryConsentDialog } from '@renderer/features/telemetry/TelemetryConsentDialog';
+import '@renderer/index.css';
+
+/**
+ * The first-run consent prompt opened with focus on the consent switch — the
+ * dialog's first tabbable element — so its `focus-visible` ring drew a
+ * highlighted band around the toggle row before the user had touched anything,
+ * and vanished on the first click elsewhere (CHOO-2344). Focus belongs on the
+ * popup: inside the dialog, but not on an answer.
+ *
+ * Asserts the rendered ring, not the prop: the ring is the symptom, and only a
+ * real browser with the real stylesheet resolves `focus-visible`.
+ */
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(() => {
+ act(() => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+});
+
+async function openDialog() {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => {
+ root!.render(
+ <QueryClientProvider client={new QueryClient()}>
+ <TelemetryConsentDialog onAnswered={() => {}} />
+ </QueryClientProvider>
+ );
+ });
+ // Base UI moves initial focus after the open transition, not during render.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ });
+}
+
+/** The switch's focusable root — `id` lands on Base UI's hidden input, not here. */
+function consentSwitch(): HTMLElement {
+ const el = document.querySelector<HTMLElement>('[data-slot="switch"]');
+ if (el === null) throw new Error('consent switch not rendered');
+ return el;
+}
+
+describe('telemetry consent dialog initial focus', () => {
+ it('does not open with the consent switch focused', async () => {
+ await openDialog();
+
+ expect(document.activeElement).not.toBe(consentSwitch());
+ expect(consentSwitch().matches(':focus-visible')).toBe(false);
+ });
+
+ it('draws no focus ring around the toggle row', async () => {
+ await openDialog();
+
+ // `ring-3` compiles to a 3px box-shadow; an unfocused switch has none.
+ expect(getComputedStyle(consentSwitch()).boxShadow).not.toMatch(/0px 0px 0px 3px/);
+ });
+
+ it('still moves focus into the dialog', async () => {
+ await openDialog();
+
+ const popup = document.querySelector('[data-slot="dialog-content"]');
+ expect(popup).not.toBeNull();
+ expect(document.activeElement).toBe(popup);
+ });
+});
diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.py
index 232bda3f5..224b19ad6 100644
--- a/core/switch_core/clients/agent_client.py
+++ b/core/switch_core/clients/agent_client.py
@@ -153,6 +153,43 @@ _CONNECTED_NOT_LIVE_MESSAGE = (
)
+def _offline_owner_message(
+ owner_handle: str | None, asker_handle: str, cmd: str | None
+) -> str:
+ """The reply for an auto_session agent addressed with nothing to start it.
+
+ An auto_session agent is brought online by Switch Console watching on its
+ owner's machine, so reaching this means the app is not running or not
+ connected — the fix is for the OWNER to open it, and nobody else in the
+ room can act. So the owner leads and is asked directly; the asker is named
+ as the reason, not as a second person being told to do something.
+
+ Deliberately says "online" rather than anything about sessions: which
+ process is or is not attached to which room is Switch's business, not
+ something to hand a reader in a chat channel.
+ """
+ # The owner addressing their own agent is the common case; naming them as
+ # the reason they should act reads as a stutter ("@me … and @me needs me").
+ needs_me = "" if owner_handle == asker_handle else f", and @{asker_handle} needs me"
+ if owner_handle:
+ opening = (
+ f"@{owner_handle} — I'm not online in this room{needs_me}. "
+ "Open Switch Console to bring me online here."
+ )
+ terminal = "If you'd rather do it from a terminal:"
+ else:
+ # No owner account on this platform to mention. Still name who has to
+ # act, so the message is not read as something the room can fix.
+ opening = (
+ f"I'm not online in this room{needs_me}. **My owner needs to open "
+ "Switch Console** to bring me online here."
+ )
+ terminal = "Or, from a terminal:"
+ if cmd is None:
+ return opening
+ return f"{opening} {terminal}\n\n```\n{cmd}\n```"
+
+
# Posted (once, guarded by AUTO_REPLY_FLAG) when a sender tags this agent but
# the agent's scoped addressing policy does not permit that sender to address
# it here. The message is demoted to unaddressed room chatter; this reply is
@@ -370,8 +407,8 @@ class AgentClient(ClientBase[ClientConfig]):
if not triggered_by_auto_reply and not await self._is_available(
meta.room_id
):
- msg = await self._reply_when_unavailable_here(meta)
handle = self._sender_handle(event)
+ msg = await self._reply_when_unavailable_here(meta, handle)
already_tagged = _mention_regex(handle).search(msg) is not None
body = msg if already_tagged else f"@{handle} {msg}"
await self.send_message(
@@ -379,13 +416,25 @@ class AgentClient(ClientBase[ClientConfig]):
body,
format="markdown",
mentions=[event.sender],
- # Answer where the question was asked: `thread_id`, not the
- # reply root. They differ for a message at the conversation
- # root, where the reply root is the message itself — which
- # opens a thread off it, so a one-line "starting a session"
- # buries itself somewhere nobody is looking, away from the
- # answer that follows it.
- thread_root_id=thread_id,
+ # Where this lands depends on whether an answer follows it.
+ #
+ # "Starting a session" is a preamble: the real answer arrives
+ # after it, in the room the question was asked in. Threading
+ # it off the trigger buries the notice away from the answer
+ # it introduces, so it goes where the question was —
+ # `thread_id`, which is None for a message at the root
+ # (CHOO-2173).
+ #
+ # Everything else here is the whole reply and nothing
+ # follows it, so it threads off the triggering message: an
+ # owner mention and a paste-ready command are a wall of text
+ # to drop into a channel for something only one person can
+ # act on (CHOO-2344).
+ thread_root_id=(
+ thread_id
+ if msg == _STARTING_SESSION_MESSAGE
+ else reply_thread_root
+ ),
extra_content={AUTO_REPLY_FLAG: True},
)
@@ -756,7 +805,9 @@ class AgentClient(ClientBase[ClientConfig]):
self._room_meta[matrix_room_id] = meta
return meta
- async def _reply_when_unavailable_here(self, meta: RoomMeta) -> str:
+ async def _reply_when_unavailable_here(
+ self, meta: RoomMeta, asker_handle: str
+ ) -> str:
"""Message for an agent addressed here but not live in this room.
If the agent has live session(s) connected to OTHER rooms, name them so
@@ -844,15 +895,19 @@ class AgentClient(ClientBase[ClientConfig]):
# No role lease here, just sessions elsewhere: prefer the
# known-agent reply so the operator gets the paste-ready
# connect command alongside the "ask me there" alternative.
- return await self._unavailable_reply(meta, agent, other_room_names=names)
+ return await self._unavailable_reply(
+ meta, agent, asker_handle, other_room_names=names
+ )
# No live session in a distinct room. A session_addressable agent bound
# to THIS room but not live here was most likely launched without live
# channels: say a session is connected-but-not-live rather than imply
# there is none.
if connection_model == "session_addressable" and bound_here:
- return await self._unavailable_reply(meta, agent, connected_not_live=True)
- return await self._unavailable_reply(meta, agent)
+ return await self._unavailable_reply(
+ meta, agent, asker_handle, connected_not_live=True
+ )
+ return await self._unavailable_reply(meta, agent, asker_handle)
async def owner_handle_in(self, agent: Agent, bridge_id: str | None) -> str | None:
"""The agent owner's account on the platform this room is bridged to,
@@ -884,23 +939,48 @@ class AgentClient(ClientBase[ClientConfig]):
self,
meta: RoomMeta,
agent: Agent,
+ asker_handle: str,
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
) -> str:
"""Build the room-facing message for an addressed-but-offline agent.
- Prefers per-known-agent `start_session_instructions` (e.g. the
- paste-ready terminal command for Claude Code). Falls back to the
- static `_UNAVAILABLE_MESSAGES` text keyed by connection_model when
- the agent has no known-agent spec or the spec returns None;
- `connected_not_live` selects the "bound here but not live" fallback.
+ An auto_session agent with nowhere else to point the asker gets the
+ owner-facing "I'm not online" reply: only its owner can act, so the
+ message asks them and nobody else. Every other case prefers the
+ per-known-agent `start_session_instructions` (e.g. the paste-ready
+ terminal command for Claude Code), falling back to the static
+ `_UNAVAILABLE_MESSAGES` text keyed by connection_model when the agent
+ has no known-agent spec or the spec returns None; `connected_not_live`
+ selects the "bound here but not live" fallback.
`agent` is the freshly-read row supplied by the caller (via
`_fresh_agent`), so option edits made through the gateway (e.g.
`PATCH /agents/{id}/options`, `connection_model`) take effect without
restarting this client — `self.agent` alone is a boot-time snapshot.
"""
+ connection_model = (agent.integration_profile or {}).get(
+ "connection_model", "session_passive"
+ )
spec_options = known_agent_for(agent)
+ # `other_room_names` outranks this: a live session in another room is
+ # somewhere the asker can go right now, which beats asking the owner to
+ # start something.
+ if (
+ connection_model == "auto_session"
+ and not other_room_names
+ and not connected_not_live
+ ):
+ cmd = (
+ spec_options[0].connect_command(spec_options[1], agent, meta.name, None)
+ if spec_options is not None
+ else None
+ )
+ return _offline_owner_message(
+ await self.owner_handle_in(agent, meta.bridge_id),
+ asker_handle,
+ cmd,
+ )
if spec_options is not None:
spec, options = spec_options
msg = spec.start_session_instructions(
@@ -915,9 +995,6 @@ class AgentClient(ClientBase[ClientConfig]):
return msg
if connected_not_live:
return _CONNECTED_NOT_LIVE_MESSAGE
- connection_model = (agent.integration_profile or {}).get(
- "connection_model", "session_passive"
- )
return _UNAVAILABLE_MESSAGES.get(
connection_model, _UNAVAILABLE_MESSAGES["session_passive"]
)
diff --git a/core/switch_core/gateway/known_agents.py b/core/switch_core/gateway/known_agents.py
index 5e472be12..f78162ed8 100644
--- a/core/switch_core/gateway/known_agents.py
+++ b/core/switch_core/gateway/known_agents.py
@@ -17,6 +17,27 @@ if TYPE_CHECKING:
from switch_core.db.models import Agent
+def connect_prompt(
+ room_name: str,
+ agent_name: str,
+ assume_role: str | None,
+ also_pull: bool,
+) -> str:
+ """The natural-language prompt a started session is launched with.
+
+ One directory can hold credentials for several provisioned agents, in which
+ case the session has to be told which one it is before it may act. Naming
+ the agent in the prompt itself answers that without the operator having to
+ know it happens.
+ """
+ prompt = f"connect to switch room {room_name}"
+ if assume_role:
+ prompt += f" and assume the role {assume_role}"
+ if also_pull:
+ prompt += " and pull the latest messages"
+ return f"{prompt} — if you are asked which agent you are, you are {agent_name}"
+
+
class KnownAgentOptions(BaseModel):
"""Base class for per-known-agent registration options.
@@ -48,6 +69,27 @@ class KnownAgent(ABC):
def parse_options(cls, raw: dict[str, Any] | None) -> KnownAgentOptions:
return cls.options_schema.model_validate(raw or {})
+ @classmethod
+ def connect_command(
+ cls,
+ options: KnownAgentOptions,
+ agent: Agent,
+ room_name: str,
+ assume_role: str | None,
+ ) -> str | None:
+ """The paste-ready shell command that starts this agent connected to
+ `room_name`, with no surrounding prose.
+
+ Split out from `start_session_instructions` because the command is the
+ one host-specific part: callers that need their own wording around it
+ (the addressed-but-offline reply) take the command and write the rest
+ themselves, rather than each host restating the same sentences.
+
+ None when no command applies — the same condition that makes
+ `start_session_instructions` return None.
+ """
+ return None
+
@classmethod
def start_session_instructions(
cls,
@@ -192,30 +234,13 @@ class ClaudeCodeKnownAgent(KnownAgent):
)
@classmethod
- def start_session_instructions(
+ def connect_command(
cls,
options: KnownAgentOptions,
agent: Agent,
room_name: str,
- owner_handle: str | None,
- assume_role: str | None = None,
- other_room_names: list[str] | None = None,
- connected_not_live: bool = False,
+ assume_role: str | None,
) -> str | None:
- """Build the room-facing onboarding message.
-
- Shape depends on the install's connection model:
-
- - channels disabled (session_passive): the agent reads asynchronously,
- so the message says the operator must trigger a pull, the connect
- command itself includes "and pull the latest messages", and a note
- explains real-time delivery needs an Anthropic API key / subscription.
- - channels enabled (session_addressable): the usual connect command.
- `connected_not_live` switches the opening to "a session is connected
- here but isn't live" (operator likely launched it without the
- dev-channels flag); `other_room_names` points the asker at live
- sessions in genuinely different rooms instead.
- """
assert isinstance(options, ClaudeCodeOptions)
# Channels-enabled installations need the dev-channels flag so the
# plugin can deliver inbound events; without channels the flag is a
@@ -242,16 +267,43 @@ class ClaudeCodeKnownAgent(KnownAgent):
subagent_flags = (
f" --agent {options.subagent_name} --settings {settings_path}"
)
- # Fold an optional role into the connect prompt itself, so the started
- # session lands in the room AND takes the role in one go.
- prompt = f"connect to switch room {room_name}"
- if assume_role:
- prompt += f" and assume the role {assume_role}"
# A session_passive session receives no pushed events, so the connect
# must also pull — fold that into the prompt itself.
- if not options.channels_enabled:
- prompt += " and pull the latest messages"
- cmd = f'cd {dir_token} && claude "{prompt}"{subagent_flags}{flag}'
+ prompt = connect_prompt(
+ room_name,
+ agent.name,
+ assume_role,
+ also_pull=not options.channels_enabled,
+ )
+ return f'cd {dir_token} && claude "{prompt}"{subagent_flags}{flag}'
+
+ @classmethod
+ def start_session_instructions(
+ cls,
+ options: KnownAgentOptions,
+ agent: Agent,
+ room_name: str,
+ owner_handle: str | None,
+ assume_role: str | None = None,
+ other_room_names: list[str] | None = None,
+ connected_not_live: bool = False,
+ ) -> str | None:
+ """Build the room-facing onboarding message.
+
+ Shape depends on the install's connection model:
+
+ - channels disabled (session_passive): the agent reads asynchronously,
+ so the message says the operator must trigger a pull, the connect
+ command itself includes "and pull the latest messages", and a note
+ explains real-time delivery needs an Anthropic API key / subscription.
+ - channels enabled (session_addressable): the usual connect command.
+ `connected_not_live` switches the opening to "a session is connected
+ here but isn't live" (operator likely launched it without the
+ dev-channels flag); `other_room_names` points the asker at live
+ sessions in genuinely different rooms instead.
+ """
+ assert isinstance(options, ClaudeCodeOptions)
+ cmd = cls.connect_command(options, agent, room_name, assume_role)
if not options.channels_enabled:
# session_passive: reads asynchronously, so the operator must
@@ -365,6 +417,19 @@ class CodexKnownAgent(KnownAgent):
),
)
+ @classmethod
+ def connect_command(
+ cls,
+ options: KnownAgentOptions,
+ agent: Agent,
+ room_name: str,
+ assume_role: str | None,
+ ) -> str | None:
+ assert isinstance(options, CodexOptions)
+ dir_token = options.repo_dir if options.repo_dir else "<codex-dir>"
+ prompt = connect_prompt(room_name, agent.name, assume_role, also_pull=False)
+ return f'cd "{dir_token}" && codex "{prompt}"'
+
@classmethod
def start_session_instructions(
cls,
@@ -384,11 +449,7 @@ class CodexKnownAgent(KnownAgent):
connector is watching.
"""
assert isinstance(options, CodexOptions)
- dir_token = options.repo_dir if options.repo_dir else "<codex-dir>"
- prompt = f"connect to switch room {room_name}"
- if assume_role:
- prompt += f" and assume the role {assume_role}"
- cmd = f'cd "{dir_token}" && codex "{prompt}"'
+ cmd = cls.connect_command(options, agent, room_name, assume_role)
prefix = f"@{owner_handle}\n\n" if owner_handle else ""
if connected_not_live:
@@ -487,6 +548,24 @@ class OpenCodeKnownAgent(KnownAgent):
),
)
+ @classmethod
+ def connect_command(
+ cls,
+ options: KnownAgentOptions,
+ agent: Agent,
+ room_name: str,
+ assume_role: str | None,
+ ) -> str | None:
+ """The prompt goes through `--prompt`, never as a positional argument:
+ OpenCode reads its first positional as the project directory, so a bare
+ `opencode "connect to switch room …"` is a request to open a directory
+ of that name rather than a prompt.
+ """
+ assert isinstance(options, OpenCodeOptions)
+ dir_token = options.repo_dir if options.repo_dir else "<opencode-dir>"
+ prompt = connect_prompt(room_name, agent.name, assume_role, also_pull=False)
+ return f'cd "{dir_token}" && opencode --prompt "{prompt}"'
+
@classmethod
def start_session_instructions(
cls,
@@ -498,19 +577,9 @@ class OpenCodeKnownAgent(KnownAgent):
other_room_names: list[str] | None = None,
connected_not_live: bool = False,
) -> str | None:
- """Build the room-facing onboarding message for an OpenCode agent.
-
- The prompt goes through `--prompt`, never as a positional argument:
- OpenCode reads its first positional as the project directory, so a bare
- `opencode "connect to switch room …"` is a request to open a directory of
- that name rather than a prompt.
- """
+ """Build the room-facing onboarding message for an OpenCode agent."""
assert isinstance(options, OpenCodeOptions)
- dir_token = options.repo_dir if options.repo_dir else "<opencode-dir>"
- prompt = f"connect to switch room {room_name}"
- if assume_role:
- prompt += f" and assume the role {assume_role}"
- cmd = f'cd "{dir_token}" && opencode --prompt "{prompt}"'
+ cmd = cls.connect_command(options, agent, room_name, assume_role)
prefix = f"@{owner_handle}\n\n" if owner_handle else ""
if connected_not_live:
diff --git a/core/switch_core/matrix_admin.py b/core/switch_core/matrix_admin.py
index 79fd8c433..8777149b1 100644
--- a/core/switch_core/matrix_admin.py
+++ b/core/switch_core/matrix_admin.py
@@ -296,6 +296,22 @@ class MatrixAdmin:
json={"user_id": user_id},
)
if not resp.is_success:
+ # User is already out — nothing to do, the room teardown this serves
+ # wants them gone and they are. Tuwunel/conduwuit rejects it with
+ # "Cannot kick a user who is not apart of the room" (their typo);
+ # Synapse says "not in the room". The counterpart to the
+ # already-a-member tolerance in `invite_to_room`.
+ if resp.status_code == 403 and (
+ "not apart of the room" in resp.text
+ or "not in the room" in resp.text
+ or "not in room" in resp.text
+ ):
+ logger.debug(
+ "Skipped kicking %s from %s: already not a member",
+ user_id,
+ room_id,
+ )
+ return
raise MatrixAdminError(
f"Failed to kick {user_id} from {room_id}: {resp.status_code} {resp.text}"
)
diff --git a/core/tests/switch_core/clients/test_mention_routing.py b/core/tests/switch_core/clients/test_mention_routing.py
index 091d9de02..a45103b67 100644
--- a/core/tests/switch_core/clients/test_mention_routing.py
+++ b/core/tests/switch_core/clients/test_mention_routing.py
@@ -337,7 +337,11 @@ def _unavailable_client(
return bound_here
async def _unavailable_reply( # type: ignore[no-untyped-def]
- _room_name, _agent, other_room_names=None, connected_not_live=False
+ _room_name,
+ _agent,
+ _asker_handle,
+ other_room_names=None,
+ connected_not_live=False,
):
if other_room_names:
return "ELSEWHERE: " + ", ".join(other_room_names)
@@ -382,7 +386,7 @@ class TestUnavailableHereReply:
async def test_role_holder_session_elsewhere_says_role_elsewhere(self) -> None:
# Holds a role here, but its assuming session is attending room-B.
client = _unavailable_client(live_rooms=["room-B"], role_here=True)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == _role_elsewhere_message("Room room-B")
assert "Room room-B" in msg
@@ -391,20 +395,22 @@ class TestUnavailableHereReply:
# Defers to the known-agent reply (paste-ready connect command) with
# the other rooms threaded in, rather than the role-flavoured wording.
client = _unavailable_client(live_rooms=["room-B", "room-C"], role_here=False)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "ELSEWHERE: Room room-B, Room room-C"
async def test_only_session_is_here_falls_back_to_offline(self) -> None:
# The only live session is the addressed room itself → nothing elsewhere.
client = _unavailable_client(live_rooms=["room-A"], role_here=False)
assert (
- await AgentClient._reply_when_unavailable_here(client, _here()) == "OFFLINE"
+ await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
+ == "OFFLINE"
)
async def test_no_live_sessions_is_offline(self) -> None:
client = _unavailable_client(live_rooms=[], role_here=False)
assert (
- await AgentClient._reply_when_unavailable_here(client, _here()) == "OFFLINE"
+ await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
+ == "OFFLINE"
)
@@ -414,12 +420,12 @@ class TestConnectedNotLive:
async def test_bound_but_not_live_says_connected_not_live(self) -> None:
client = _unavailable_client(live_rooms=[], role_here=False, bound_here=True)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "NOT_LIVE"
async def test_no_binding_is_offline(self) -> None:
client = _unavailable_client(live_rooms=[], role_here=False, bound_here=False)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "OFFLINE"
async def test_passive_never_says_connected_not_live(self) -> None:
@@ -430,7 +436,7 @@ class TestConnectedNotLive:
connection_model="session_passive",
bound_here=True,
)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "OFFLINE"
async def test_same_named_live_room_not_offered_as_elsewhere(self) -> None:
@@ -439,7 +445,7 @@ class TestConnectedNotLive:
# not live → connected-not-live, not a confusing same-name pointer.
# _here() is room-A / "Room A"; room id "A" → name "Room A" (collision).
client = _unavailable_client(live_rooms=["A"], role_here=False, bound_here=True)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "NOT_LIVE"
async def test_distinct_named_live_room_still_points_elsewhere(self) -> None:
@@ -447,5 +453,5 @@ class TestConnectedNotLive:
client = _unavailable_client(
live_rooms=["room-B"], role_here=False, bound_here=True
)
- msg = await AgentClient._reply_when_unavailable_here(client, _here())
+ msg = await AgentClient._reply_when_unavailable_here(client, _here(), "asker")
assert msg == "ELSEWHERE: Room room-B"
diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.py
index 246fd035d..5edf2d770 100644
--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py
+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py
@@ -4,7 +4,11 @@ from types import SimpleNamespace
import pytest
-from switch_core.clients.agent_client import AUTO_REPLY_FLAG, AgentClient
+from switch_core.clients.agent_client import (
+ _STARTING_SESSION_MESSAGE,
+ AUTO_REPLY_FLAG,
+ AgentClient,
+)
class _Recorder:
@@ -52,7 +56,7 @@ def _fake_self(
async def _is_available(_room_id: str) -> bool:
return False # no live session → triggers the auto-reply
- async def _reply_when_unavailable_here(_meta: object) -> str:
+ async def _reply_when_unavailable_here(_meta: object, _asker_handle: str) -> str:
return unavailable_reply
ns = SimpleNamespace(
@@ -161,17 +165,18 @@ async def test_no_session_reply_tags_distinct_asker_and_operator() -> None:
assert "@operator" in body
-class TestUnavailableReplyGoesWhereItWasAsked:
+class TestStartingSessionNoticeGoesWhereItWasAsked:
"""Where "Starting a session to handle this" lands (CHOO-2173).
- It used to reply onto the triggering message, which for a message at the
- conversation root means opening a thread off it. So asking at the root got
- a one-line notice tucked into a new thread, away from where the asker was
- looking and away from the answer that follows.
+ It is a preamble, not an answer: the real reply follows it in the same
+ place. It used to reply onto the triggering message, which for a message at
+ the conversation root means opening a thread off it — so asking at the root
+ got a one-line notice tucked into a new thread, away from where the asker
+ was looking and away from the answer that follows.
This reverses CHOO-586, which made the root case start a thread on purpose.
- The reply is now placed the same way the typing indicator already is: in the
- thread when asked in a thread, at the root when asked at the root.
+ The notice is now placed the same way the typing indicator already is: in
+ the thread when asked in a thread, at the root when asked at the root.
"""
@pytest.mark.asyncio
@@ -180,7 +185,9 @@ class TestUnavailableReplyGoesWhereItWasAsked:
room = SimpleNamespace(room_id="!matrix:server")
await AgentClient.on_message(
- _fake_self(send_message), room, _event(thread_id=None)
+ _fake_self(send_message, unavailable_reply=_STARTING_SESSION_MESSAGE),
+ room,
+ _event(thread_id=None),
)
assert len(send_message.calls) == 1
@@ -194,6 +201,44 @@ class TestUnavailableReplyGoesWhereItWasAsked:
send_message = _Recorder()
room = SimpleNamespace(room_id="!matrix:server")
+ await AgentClient.on_message(
+ _fake_self(send_message, unavailable_reply=_STARTING_SESSION_MESSAGE),
+ room,
+ _event(thread_id="$thread-root"),
+ )
+
+ assert send_message.calls[0]["thread_root_id"] == "$thread-root"
+
+
+class TestTerminalReplyThreadsOffTheTrigger:
+ """Where an "I can't help right now" reply lands (CHOO-2344).
+
+ Unlike the starting-session notice, nothing follows it — it IS the answer.
+ And it is bulky: an owner mention plus a paste-ready connect command, for
+ something only one person can act on. At the conversation root that is a
+ wall of text dropped into the channel, so it threads off the message that
+ triggered it instead.
+ """
+
+ @pytest.mark.asyncio
+ async def test_asked_at_the_root_it_opens_a_thread_on_the_trigger(self) -> None:
+ send_message = _Recorder()
+ room = SimpleNamespace(room_id="!matrix:server")
+
+ await AgentClient.on_message(
+ _fake_self(send_message), room, _event(thread_id=None)
+ )
+
+ assert len(send_message.calls) == 1
+ assert send_message.calls[0]["thread_root_id"] == "$trigger"
+
+ @pytest.mark.asyncio
+ async def test_asked_in_a_thread_it_stays_in_that_thread(self) -> None:
+ # Already in a thread: the trigger's thread root IS that thread, so it
+ # lands there rather than starting a nested one.
+ send_message = _Recorder()
+ room = SimpleNamespace(room_id="!matrix:server")
+
await AgentClient.on_message(
_fake_self(send_message), room, _event(thread_id="$thread-root")
)
diff --git a/core/tests/switch_core/clients/test_offline_owner_reply.py b/core/tests/switch_core/clients/test_offline_owner_reply.py
new file mode 100644
index 000000000..2a6a1bc42
--- /dev/null
+++ b/core/tests/switch_core/clients/test_offline_owner_reply.py
@@ -0,0 +1,147 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from switch_core.clients.agent_client import AgentClient, _offline_owner_message
+
+"""The reply an auto_session agent gives when it is addressed and nothing is
+there to bring it online (CHOO-2344).
+
+It used to say "I don't have a session connected to this room", which names a
+symptom rather than the cause: an auto_session agent is started by Switch
+Console watching on its OWNER's machine, so reaching this reply means the app
+is not running. Nobody else in the room can fix that.
+"""
+
+
+def _meta() -> SimpleNamespace:
+ return SimpleNamespace(
+ room_id="room-uuid",
+ name="Some Room",
+ bridge_id="bridge-1",
+ channel_type="channel_private",
+ )
+
+
+def _agent(connection_model: str, metadata: dict | None) -> SimpleNamespace:
+ return SimpleNamespace(
+ id="agent-1",
+ name="cc-bug-fixing",
+ metadata_=metadata,
+ integration_profile={"connection_model": connection_model},
+ )
+
+
+def _auto_session_claude_agent() -> SimpleNamespace:
+ return _agent(
+ "auto_session",
+ {
+ "known_agent_type": "claude-code",
+ "known_agent_options": {"auto_session": True, "repo_dir": "/srv/work"},
+ },
+ )
+
+
+def _client(owner_handle: str | None) -> SimpleNamespace:
+ async def _owner_handle_in(_agent: object, _bridge_id: object) -> str | None:
+ return owner_handle
+
+ return SimpleNamespace(owner_handle_in=_owner_handle_in)
+
+
+async def _reply(
+ client: SimpleNamespace, agent: SimpleNamespace, **kwargs: object
+) -> str:
+ return await AgentClient._unavailable_reply(
+ client,
+ _meta(),
+ agent,
+ "louisa",
+ **kwargs, # type: ignore[arg-type]
+ )
+
+
+class TestOfflineOwnerMessage:
+ def test_owner_leads_and_is_the_one_asked(self) -> None:
+ msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude …")
+ # The owner is first, because they are the only person who can act.
+ assert msg.startswith("@ownerhandle — ")
+ assert "Open Switch Console" in msg
+ # The asker is named as the reason, not given an instruction.
+ assert "@louisa needs me" in msg
+
+ def test_never_says_session(self) -> None:
+ # Which process is attached to which room is Switch's business, not
+ # something to put in front of a reader in a chat channel.
+ msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude …")
+ assert "session" not in msg.lower()
+ assert "I'm not online in this room" in msg
+
+ def test_unmentionable_owner_still_names_who_must_act(self) -> None:
+ # No claimed account on this platform → nobody to tag. The message must
+ # not read as something the room at large can resolve.
+ msg = _offline_owner_message(None, "louisa", "cd /x && claude …")
+ assert not msg.startswith("@ownerhandle")
+ assert "**My owner needs to open Switch Console**" in msg
+ assert "@louisa needs me" in msg
+ assert "session" not in msg.lower()
+
+ def test_command_is_offered_as_the_alternative(self) -> None:
+ msg = _offline_owner_message("ownerhandle", "louisa", "cd /x && claude go")
+ assert "```\ncd /x && claude go\n```" in msg
+
+ def test_owner_asking_their_own_agent_is_not_named_twice(self) -> None:
+ # The common case. "@louisa — … and @louisa needs me" reads as a stutter.
+ msg = _offline_owner_message("louisa", "louisa", "cd /x && claude …")
+ assert msg.count("@louisa") == 1
+ assert "needs me" not in msg
+ assert msg.startswith("@louisa — I'm not online in this room. ")
+
+ def test_no_command_leaves_no_empty_code_block(self) -> None:
+ msg = _offline_owner_message("ownerhandle", "louisa", None)
+ assert "```" not in msg
+ assert "Open Switch Console" in msg
+
+
+class TestUnavailableReplyRouting:
+ async def test_auto_session_gets_the_owner_message(self) -> None:
+ msg = await _reply(_client("ownerhandle"), _auto_session_claude_agent())
+ assert msg.startswith("@ownerhandle — ")
+ assert "session" not in msg.lower()
+
+ async def test_the_command_names_the_agent(self) -> None:
+ # A directory can hold several provisioned agents, in which case the
+ # started session is asked which one it is.
+ msg = await _reply(_client("ownerhandle"), _auto_session_claude_agent())
+ assert "you are cc-bug-fixing" in msg
+ assert "cd /srv/work && claude " in msg
+
+ async def test_a_live_session_elsewhere_still_wins(self) -> None:
+ # Somewhere the asker can go right now beats asking the owner to start
+ # something, so the "elsewhere" reply is left alone.
+ msg = await _reply(
+ _client("ownerhandle"),
+ _auto_session_claude_agent(),
+ other_room_names=["Hub"],
+ )
+ assert "**Hub**" in msg
+ assert "Open Switch Console" not in msg
+
+ async def test_session_addressable_is_untouched(self) -> None:
+ agent = _agent(
+ "session_addressable",
+ {
+ "known_agent_type": "claude-code",
+ "known_agent_options": {"repo_dir": "/srv/work"},
+ },
+ )
+ msg = await _reply(_client("ownerhandle"), agent)
+ assert "I don't have a session connected to this room." in msg
+ assert "Open Switch Console" not in msg
+
+ async def test_auto_session_without_a_known_agent_still_answers(self) -> None:
+ # Registered via `register-other`: no connect command exists, but the
+ # owner still has to open the app.
+ msg = await _reply(_client("ownerhandle"), _agent("auto_session", {}))
+ assert "Open Switch Console" in msg
+ assert "```" not in msg
diff --git a/core/tests/switch_core/gateway/test_known_agents.py b/core/tests/switch_core/gateway/test_known_agents.py
index 4cf1674e6..b0f4a1812 100644
--- a/core/tests/switch_core/gateway/test_known_agents.py
+++ b/core/tests/switch_core/gateway/test_known_agents.py
@@ -18,6 +18,19 @@ def _agent(metadata: dict | None) -> SimpleNamespace:
return SimpleNamespace(name="claude-code.test", metadata_=metadata)
+def _agent_named(name: str) -> SimpleNamespace:
+ """An agent whose name does not contain "claude" — the Codex and OpenCode
+ suites assert a `claude` binary is never suggested, and the connect prompt
+ now carries the agent's own name."""
+ return SimpleNamespace(name=name, metadata_={})
+
+
+def _identity(agent_name: str) -> str:
+ """The trailing clause the connect prompt carries so a session started in a
+ directory holding several agents knows which one it is."""
+ return f" — if you are asked which agent you are, you are {agent_name}"
+
+
class TestBuildProfileConnectionModel:
def test_channels_enabled_defaults_to_session_addressable(self) -> None:
profile = ClaudeCodeKnownAgent.build_profile(
@@ -72,7 +85,7 @@ class TestStartSessionInstructions:
# The flag must come AFTER the prompt argument so claude treats the
# quoted text as the initial prompt, not as a value for the flag.
assert (
- 'claude "connect to switch room hub" '
+ f'claude "connect to switch room hub{_identity("claude-code.test")}" '
"--dangerously-load-development-channels "
"plugin:switch-connector@switch-plugins"
) in msg
@@ -89,7 +102,7 @@ class TestStartSessionInstructions:
# pushed events), and the message frames reading as asynchronous.
assert (
'cd /srv/agent && claude "connect to switch room ops '
- 'and pull the latest messages"'
+ f'and pull the latest messages{_identity("claude-code.test")}"'
) in msg
assert "asynchronously" in msg
# Real-time delivery requires an API-key / subscription Claude Code.
@@ -118,7 +131,7 @@ class TestStartSessionInstructions:
assert "--dangerously-load-development-channels" not in msg
assert (
'cd /srv/agent && claude "connect to switch room ops '
- 'and pull the latest messages"'
+ f'and pull the latest messages{_identity("claude-code.test")}"'
) in msg
def test_connected_not_live_opening(self) -> None:
@@ -210,7 +223,7 @@ class TestStartSessionInstructions:
# dev-channels flag; the settings path matches what the configure skill
# writes the subagent credentials to.
assert (
- 'claude "connect to switch room hub" '
+ f'claude "connect to switch room hub{_identity("claude-code.test")}" '
"--agent seo-writer "
"--settings .claude/switch-subagents/seo-writer.settings.json "
"--dangerously-load-development-channels "
@@ -299,11 +312,16 @@ class TestCodexKnownAgent:
def test_start_session_instructions_emit_codex_not_claude(self) -> None:
opts = CodexOptions(repo_dir="/Users/x/repo")
- msg = CodexKnownAgent.start_session_instructions(opts, _agent({}), "hub", None)
+ msg = CodexKnownAgent.start_session_instructions(
+ opts, _agent_named("codex.test"), "hub", None
+ )
assert msg is not None
# The path is quoted so a repo_dir with spaces still produces a valid
# paste command.
- assert 'cd "/Users/x/repo" && codex "connect to switch room hub"' in msg
+ assert (
+ 'cd "/Users/x/repo" && codex "connect to switch room hub'
+ f'{_identity("codex.test")}"'
+ ) in msg
# It must NOT suggest a claude command or Claude-specific flags.
assert "claude" not in msg
assert "--dangerously-load-development-channels" not in msg
@@ -321,7 +339,7 @@ class TestCodexKnownAgent:
def test_connected_not_live_opening(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", None, connected_not_live=True
+ opts, _agent_named("codex.test"), "ops", None, connected_not_live=True
)
assert msg is not None
assert "isn't reporting" in msg
@@ -331,7 +349,11 @@ class TestCodexKnownAgent:
def test_other_room_names_branch(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", None, other_room_names=["hub", "triage"]
+ opts,
+ _agent_named("codex.test"),
+ "ops",
+ None,
+ other_room_names=["hub", "triage"],
)
assert msg is not None
assert "**hub**" in msg
@@ -341,10 +363,13 @@ class TestCodexKnownAgent:
def test_assume_role_folded_into_prompt(self) -> None:
opts = CodexOptions(repo_dir="/r")
msg = CodexKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", None, assume_role="reviewer"
+ opts, _agent_named("codex.test"), "ops", None, assume_role="reviewer"
)
assert msg is not None
- assert 'codex "connect to switch room ops and assume the role reviewer"' in msg
+ assert (
+ 'codex "connect to switch room ops and assume the role reviewer'
+ f'{_identity("codex.test")}"'
+ ) in msg
def test_empty_string_repo_dir_normalised_to_placeholder(self) -> None:
opts = CodexOptions(repo_dir="")
@@ -449,19 +474,19 @@ class TestOpenCodeKnownAgent:
# that name. The prompt must go through --prompt.
opts = OpenCodeOptions(repo_dir="/Users/x/repo")
msg = OpenCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "hub", None
+ opts, _agent_named("opencode.test"), "hub", None
)
assert msg is not None
assert (
- 'cd "/Users/x/repo" && opencode --prompt "connect to switch room hub"'
- in msg
- )
+ 'cd "/Users/x/repo" && opencode --prompt "connect to switch room hub'
+ f'{_identity("opencode.test")}"'
+ ) in msg
assert 'opencode "connect' not in msg
def test_start_session_instructions_emit_opencode_only(self) -> None:
opts = OpenCodeOptions(repo_dir="/Users/x/repo")
msg = OpenCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "hub", None
+ opts, _agent_named("opencode.test"), "hub", None
)
assert msg is not None
assert "claude" not in msg
@@ -481,12 +506,13 @@ class TestOpenCodeKnownAgent:
def test_assume_role_is_folded_into_the_prompt(self) -> None:
opts = OpenCodeOptions(repo_dir="/r")
msg = OpenCodeKnownAgent.start_session_instructions(
- opts, _agent({}), "ops", None, assume_role="reviewer"
+ opts, _agent_named("opencode.test"), "ops", None, assume_role="reviewer"
)
assert msg is not None
assert (
- '--prompt "connect to switch room ops and assume the role reviewer"' in msg
- )
+ '--prompt "connect to switch room ops and assume the role reviewer'
+ f'{_identity("opencode.test")}"'
+ ) in msg
def test_blank_repo_dir_uses_placeholder(self) -> None:
msg = OpenCodeKnownAgent.start_session_instructions(
diff --git a/core/tests/switch_core/test_matrix_admin_kick.py b/core/tests/switch_core/test_matrix_admin_kick.py
new file mode 100644
index 000000000..68424fb10
--- /dev/null
+++ b/core/tests/switch_core/test_matrix_admin_kick.py
@@ -0,0 +1,67 @@
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from switch_core.matrix_admin import MatrixAdmin, MatrixAdminError
+
+ROOM = "!T5MphZvo650rb9LDq2:switch.local"
+USER = "@switch-agent-d322f24a:switch.local"
+
+# Verbatim from Tuwunel, typo included — the guard matches on this text, so a
+# paraphrase would test nothing.
+TUWUNEL_NOT_A_MEMBER = (
+ '{"errcode":"M_FORBIDDEN","error":"M_FORBIDDEN: Cannot kick a user who is '
+ 'not apart of the room (current membership: leave)"}'
+)
+SYNAPSE_NOT_A_MEMBER = (
+ '{"errcode":"M_FORBIDDEN","error":"The target user is not in the room"}'
+)
+
+
+def _admin(handler: object) -> MatrixAdmin:
+ http = httpx.AsyncClient(
+ base_url="http://homeserver.invalid",
+ transport=httpx.MockTransport(handler), # type: ignore[arg-type]
+ )
+ return MatrixAdmin(
+ server_url="http://homeserver.invalid",
+ admin_user="@admin:switch.local",
+ access_token="token",
+ shared_secret="secret",
+ http=http,
+ )
+
+
+class TestKickUser:
+ @pytest.mark.parametrize("body", [TUWUNEL_NOT_A_MEMBER, SYNAPSE_NOT_A_MEMBER])
+ async def test_already_gone_is_not_an_error(self, body: str) -> None:
+ """Tearing a room down kicks every client it ever had, and a client that
+ already left answers 403. Deleting a room must not abort on it
+ (CHOO-2344: disconnecting a messaging app failed with a 500)."""
+ admin = _admin(lambda request: httpx.Response(403, text=body))
+
+ await admin.kick_user(ROOM, USER)
+
+ await admin._http.aclose()
+
+ async def test_real_forbidden_still_raises(self) -> None:
+ admin = _admin(
+ lambda request: httpx.Response(
+ 403,
+ text='{"errcode":"M_FORBIDDEN","error":"You don\'t have permission to kick"}',
+ )
+ )
+
+ with pytest.raises(MatrixAdminError, match="Failed to kick"):
+ await admin.kick_user(ROOM, USER)
+
+ await admin._http.aclose()
+
+ async def test_other_failures_still_raise(self) -> None:
+ admin = _admin(lambda request: httpx.Response(500, text="boom"))
+
+ with pytest.raises(MatrixAdminError, match="Failed to kick"):
+ await admin.kick_user(ROOM, USER)
+
+ await admin._http.aclose()