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(slack): give each agent a user group so its name autocompletes (CHOO-2277) (#269)
Louis Amaudruz731eb957c4fc
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.tsindex 519713c1c..9f5331552 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/create-bridge.test.ts@@ -232,6 +232,44 @@ describe('fetchBridgeTypes', () => {description: 'The xoxb token.',required: true,secret: true,+ kind: 'string',+ default: null,+ });+ });++ it('carries a boolean field as one, with its default', async () => {+ // Fields used to be strings without exception. A boolean sent as the empty+ // string the form would otherwise produce is rejected by the server, so the+ // type has to survive the flattening.+ fetchMock.mockResolvedValue(+ response(200, [+ {+ key: 'slack',+ config_schema: {+ properties: {+ bot_token: { title: 'Bot Token', type: 'string' },+ agent_usergroups: {+ title: 'Agent Usergroups',+ type: 'boolean',+ default: true,+ },+ },+ required: ['bot_token'],+ },+ },+ ])+ );++ const [slack] = await fetchBridgeTypes(SERVER);++ expect(slack.fields[1]).toEqual({+ key: 'agent_usergroups',+ label: 'Agent Usergroups',+ description: null,+ required: false,+ secret: false,+ kind: 'boolean',+ default: true,});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.tsindex fa16f5c1a..bffffe26e 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts@@ -633,11 +633,27 @@ export async function fetchBridges(server: SwitchServer): Promise<RemoteBridge[]const SECRET_FIELD_RE = /token|password|secret|api[_-]?key|private[_-]?key|credential/i;/** JSON Schema as Pydantic's `model_json_schema()` emits it for a bridge config. */+type BridgeConfigSchemaProperty = {+ title?: string;+ description?: string;+ format?: string;+ type?: string;+ default?: unknown;+ /** Pydantic emits `bool | None` as `anyOf: [{type:"boolean"},{type:"null"}]`+ * rather than a top-level `type`, so look through it. */+ anyOf?: Array<{ type?: string }>;+};+type BridgeConfigSchema = {- properties?: Record<string, { title?: string; description?: string; format?: string }>;+ properties?: Record<string, BridgeConfigSchemaProperty>;required?: string[];};+function primitiveType(prop: BridgeConfigSchemaProperty): string | undefined {+ if (prop.type) return prop.type;+ return prop.anyOf?.find((variant) => variant.type && variant.type !== 'null')?.type;+}+function humanizeFieldKey(key: string): string {return key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());}@@ -647,13 +663,22 @@ function toConfigFields(schema: BridgeConfigSchema): BridgeConfigField[] {// Object key order follows the Pydantic model's field order, which puts the// required credentials before the optional tuning knobs — worth preserving,// so the form reads the way the platform's setup docs do.- return Object.entries(schema.properties ?? {}).map(([key, prop]) => ({- key,- label: prop.title ?? humanizeFieldKey(key),- description: prop.description ?? null,- required: required.has(key),- secret: prop.format === 'password' || SECRET_FIELD_RE.test(key),- }));+ return Object.entries(schema.properties ?? {}).map(([key, prop]) => {+ const kind = primitiveType(prop) === 'boolean' ? 'boolean' : 'string';+ const fallback = kind === 'boolean' ? false : null;+ return {+ key,+ label: prop.title ?? humanizeFieldKey(key),+ description: prop.description ?? null,+ required: required.has(key),+ secret: prop.format === 'password' || SECRET_FIELD_RE.test(key),+ kind,+ default:+ typeof prop.default === 'string' || typeof prop.default === 'boolean'+ ? prop.default+ : fallback,+ };+ });}/**@@ -665,9 +690,9 @@ function toConfigFields(schema: BridgeConfigSchema): BridgeConfigField[] {* than hard-coded per platform. A server running a newer switch-core that adds* a bridge type, or a field to an existing one, works without an app release.*- * Every schema-visible field is a string today (the sole int, the Teams listen- * port, is `SkipJsonSchema`), so values are collected as strings and the server- * coerces.+ * Fields carry their primitive type, because they are no longer all strings:+ * the Slack bridge's agent-user-groups toggle is a boolean, and the server+ * rejects an empty string as one rather than coercing it.*/export async function fetchBridgeTypes(server: SwitchServer): Promise<RemoteBridgeType[]> {const res = await gatewayFetch(server, '/collaborations/types', { authenticated: true });@@ -705,7 +730,7 @@ export async function createBridge(params: {bridgeType: string;displayName: string;- connectionConfig: Record<string, string>;+ connectionConfig: Record<string, string | boolean>;setAsDefault: boolean;channelCreationEnabled: boolean;}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsxindex e879cdf4e..9814801b0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/ConnectMessagingAppModal.tsx@@ -62,7 +62,9 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModconst [displayName, setDisplayName] = useState('');// Credential values. Renderer-local and never persisted: this state dies with// the modal, and the only thing that reads it is the submit call.- const [config, setConfig] = useState<Record<string, string>>({});+ // Typed by the schema, not all strings: a boolean field posts a real boolean,+ // since the server rejects an empty string as one.+ const [config, setConfig] = useState<Record<string, string | boolean>>({});const [setAsDefault, setSetAsDefault] = useState(false);// Defaults on: most platforms can create channels, and the server rejects// this staying true for one that can't rather than us guessing wrong.@@ -82,20 +84,34 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod// isn't forced off while that request is in flight.const channelCreationSupported = selectedType?.channelCreationSupported ?? true;- const handleTypeChange = useCallback((next: string | null) => {- // Switching platform drops whatever was typed for the previous one — those- // fields do not exist on the new type, and carrying a stale token forward- // would silently submit a credential the user thinks they replaced.- setTypeKey(next);- setConfig({});- setChannelCreationEnabled(true);- setError(null);- }, []);+ const handleTypeChange = useCallback(+ (next: string | null) => {+ // Switching platform drops whatever was typed for the previous one — those+ // fields do not exist on the new type, and carrying a stale token forward+ // would silently submit a credential the user thinks they replaced. The+ // new type's defaults are seeded, so a field left untouched posts what the+ // platform expects rather than nothing.+ setTypeKey(next);+ const fields = types.find((t) => t.key === next)?.fields ?? [];+ const defaults: Record<string, string | boolean> = {};+ for (const field of fields) {+ if (field.default !== null) defaults[field.key] = field.default;+ }+ setConfig(defaults);+ setChannelCreationEnabled(true);+ setError(null);+ },+ [types]+ );const trimmedName = displayName.trim();- const missingRequired = (selectedType?.fields ?? []).some(- (f) => f.required && !(config[f.key] ?? '').trim()- );+ const missingRequired = (selectedType?.fields ?? []).some((f) => {+ if (!f.required) return false;+ const value = config[f.key];+ // `false` is an answer, not an omission — only a blank string is missing.+ if (typeof value === 'boolean') return false;+ return !(value ?? '').trim();+ });const canSubmit =!!serverId && isAdmin && !!selectedType && !!trimmedName && !missingRequired && !isSubmitting;@@ -108,10 +124,15 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppModtry {// Send only the fields this type declares, trimmed. A value left over in// state from a field that is no longer rendered must not ride along.- const connectionConfig: Record<string, string> = {};+ const connectionConfig: Record<string, string | boolean> = {};for (const field of selectedType.fields) {- const value = (config[field.key] ?? '').trim();- if (value) connectionConfig[field.key] = value;+ const value = config[field.key];+ if (typeof value === 'boolean') {+ connectionConfig[field.key] = value;+ continue;+ }+ const trimmed = (value ?? '').trim();+ if (trimmed) connectionConfig[field.key] = trimmed;}const result = await rpc.switchServers.createBridge({@@ -239,32 +260,56 @@ export const ConnectMessagingAppModal = observer(function ConnectMessagingAppMod<ExternalLink className="size-3" /></button>- {selectedType.fields.map((field) => (- <Field key={field.key}>- <FieldLabel>- {field.label}- {!field.required && (- <span className="ml-1 font-normal text-foreground-muted">(optional)</span>+ {selectedType.fields.map((field) =>+ field.kind === 'boolean' ? (+ <label+ key={field.key}+ className="group/field flex cursor-pointer items-start gap-2.5"+ >+ <Checkbox+ checked={config[field.key] === true}+ onCheckedChange={(checked) => {+ setConfig((prev) => ({ ...prev, [field.key]: checked === true }));+ setError(null);+ }}+ className="mt-0.5"+ />+ <span className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">{field.label}</span>+ {field.description && (+ <span className="text-xs text-foreground-muted">{field.description}</span>+ )}+ </span>+ </label>+ ) : (+ <Field key={field.key}>+ <FieldLabel>+ {field.label}+ {!field.required && (+ <span className="ml-1 font-normal text-foreground-muted">(optional)</span>+ )}+ </FieldLabel>+ <Input+ // Masked for credentials, so a token is not left readable on+ // screen while the user checks the rest of the form.+ type={field.secret ? 'password' : 'text'}+ autoComplete={field.secret ? 'new-password' : 'off'}+ spellCheck={false}+ value={+ typeof config[field.key] === 'string' ? (config[field.key] as string) : ''+ }+ onChange={(e) => {+ const { value } = e.target;+ setConfig((prev) => ({ ...prev, [field.key]: value }));+ setError(null);+ }}+ />+ {field.description && (+ <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>)}- </FieldLabel>- <Input- // Masked for credentials, so a token is not left readable on- // screen while the user checks the rest of the form.- type={field.secret ? 'password' : 'text'}- autoComplete={field.secret ? 'new-password' : 'off'}- spellCheck={false}- value={config[field.key] ?? ''}- onChange={(e) => {- const { value } = e.target;- setConfig((prev) => ({ ...prev, [field.key]: value }));- setError(null);- }}- />- {field.description && (- <p className="mt-1 text-xs text-foreground-muted">{field.description}</p>- )}- </Field>- ))}+ </Field>+ )+ )}<labelclassName={cn(diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.tsindex c334f1599..626e677db 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts@@ -370,6 +370,13 @@ export type BridgeConfigField = {/** Render masked and keep out of logs. Set from the schema's* `format: "password"` hint, falling back to a name heuristic. */secret: boolean;+ /** The schema's primitive type, so the form renders a control that matches+ * it. A boolean posted as the string the server cannot parse is rejected+ * outright, so this is not only about how it looks. */+ kind: 'string' | 'boolean';+ /** The schema's default, so an untouched field posts what the platform+ * expects rather than nothing. */+ default: string | boolean | null;};/** A bridge type registered on a server, with the fields needed to attach one@@ -402,7 +409,7 @@ export type CreateBridgeParams = {serverId: string;bridgeType: string;displayName: string;- connectionConfig: Record<string, string>;+ connectionConfig: Record<string, string | boolean>;/** Make this the bridge new rooms land on when none is named. */setAsDefault: boolean;/** Whether this connection may create channels on the platform. Thediff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 7c1231dd7..9c56fa18d 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -162,6 +162,8 @@ class BridgeCore:# (channel_id, agent_name) -> the last message the agent reported having# been handed. Cleared when its turn ends. See _follow_reported_anchor.self._reported_anchors: dict[tuple[str, str], str] = {}+ # Identity provisioning runs in the background — see _create_agent_identities.+ self._identity_task: asyncio.Task[None] | None = None@propertydef adapter(self) -> CollaborationAdapter:@@ -180,9 +182,18 @@ class BridgeCore:on_app_joined=self._handle_app_joined_channel,)await self._ensure_channel_captures()- await self._create_agent_identities()+ # Deliberately not awaited. Provisioning is one call per agent against+ # the platform, and a rate-limited platform makes that minutes of+ # mostly waiting — which would hold up the bridge coming online, and+ # with it every other bridge behind it at startup and any request that+ # restarts one. Messages do not depend on it: an agent is addressable+ # by name whether or not its platform identity exists yet.+ self._identity_task = asyncio.create_task(self._run_agent_identities())async def stop(self) -> None:+ if self._identity_task and not self._identity_task.done():+ self._identity_task.cancel()+ self._identity_task = Noneawait self._adapter.stop()# ── Startup loading ──────────────────────────────────────────────────────@@ -222,23 +233,59 @@ class BridgeCore:if client:self._puppet_matrix_ids.add(client.matrix_user_id)+ async def _run_agent_identities(self) -> None:+ """Wrapper for the background provisioning task.++ A bare create_task swallows whatever the coroutine raises, so anything+ escaping the per-agent handling below would vanish without trace.+ Cancellation is ordinary shutdown and says so quietly."""+ try:+ await self._create_agent_identities()+ except asyncio.CancelledError:+ logger.info(+ "%s identity provisioning cancelled before finishing",+ self._bridge_type,+ )+ raise+ except Exception:+ logger.exception(+ "%s identity provisioning stopped unexpectedly", self._bridge_type+ )+async def _create_agent_identities(self) -> None:async with self._session_factory() as session:agents = await self._agent_store.get_all(session)+ failed = 0for agent in agents:try:await self._adapter.create_agent_identity(agent.name, agent.description)except Exception:+ failed += 1logger.exception("Failed to create %s identity for agent %s",self._bridge_type,agent.name,)- logger.info(- "Created %s identities for %d agents", self._bridge_type, len(agents)- )+ # Counts calls that returned, not identities that now exist: an adapter+ # that cannot provision at all reports that itself. Reporting the agent+ # count regardless of failures would read as success on a run where+ # every one of them failed.+ if failed:+ logger.warning(+ "Provisioned %s identities for %d of %d agents; %d failed",+ self._bridge_type,+ len(agents) - failed,+ len(agents),+ failed,+ )+ else:+ logger.info(+ "Provisioned %s identities for %d agents",+ self._bridge_type,+ len(agents),+ )async def _ensure_channel_captures(self) -> None:"""Ask the adapter to (re)establish server-side message capture for thisdiff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 84b083959..3d0b5c7c2 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -155,6 +155,19 @@ class CollaborationBridgeLifecycleService:raise ValueError(f"Unknown bridge type: {bridge_type}")return config_cls.model_json_schema()+ def validate_connection_config(+ self, bridge_type: str, connection_config: dict[str, object]+ ) -> None:+ """Raise unless `connection_config` is valid for this bridge type.++ Editing a connection has to be checked before it is stored: a config+ the adapter cannot parse would take the bridge down on its next start,+ long after the request that caused it."""+ config_cls = self._config_registry.get(bridge_type)+ if config_cls is None:+ raise ValueError(f"Unknown bridge type: {bridge_type}")+ config_cls.model_validate(connection_config)+async def start_all(self) -> None:async with self._session_factory() as session:bridges = await self._bridge_store.get_active(session)@@ -330,6 +343,15 @@ class CollaborationBridgeLifecycleService:self._bridges.pop(bridge_id, None)logger.info("Stopped collaboration bridge %s", bridge_id)+ async def restart(self, bridge_id: str) -> None:+ """Stop and start a bridge so it picks up its stored config.++ An adapter is built from the config it was given at start, so an edit+ is inert until the bridge is rebuilt."""+ await self.stop(bridge_id)+ await self.start(bridge_id)+ logger.info("Restarted collaboration bridge %s", bridge_id)+async def stop_all(self) -> None:logger.info("Stopping all %d collaboration bridges", len(self._bridges))for bridge_id in list(self._bridges):diff --git a/core/switch_core/bridges/collaboration/slack/adapter.py b/core/switch_core/bridges/collaboration/slack/adapter.pyindex cf0e8f4de..4d0825166 100644--- a/core/switch_core/bridges/collaboration/slack/adapter.py+++ b/core/switch_core/bridges/collaboration/slack/adapter.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport loggingimport reimport time@@ -7,10 +8,10 @@ import uuidfrom collections import OrderedDictfrom collections.abc import Awaitable, Callablefrom dataclasses import replace-from typing import Any+from typing import Any, ClassVarimport httpx-from pydantic import BaseModel+from pydantic import BaseModel, Fieldfrom slack_sdk.errors import SlackApiErrorfrom slack_sdk.socket_mode.aiohttp import SocketModeClientfrom slack_sdk.socket_mode.request import SocketModeRequest@@ -38,6 +39,145 @@ from switch_core.bridges.collaboration.slack.avatar import on_slack_backgroundlogger = logging.getLogger(__name__)+# Stamped on the description of every user group we mint for an agent, so a+# reload can tell ours apart from the workspace's own groups.+_AGENT_GROUP_MARKER = "Switch agent — "++# User group calls are rate-limited at roughly 20/minute, and the Slack client+# retries connection errors but not throttling.+_RATE_LIMIT_MAX_ATTEMPTS = 5+_RATE_LIMIT_DEFAULT_DELAY = 30++# Slack refusals that mean this workspace cannot host agent user groups at all,+# rather than that one particular call went wrong. Each maps to what an operator+# would have to change to get autocomplete working.+_USERGROUPS_UNAVAILABLE_ERRORS = {+ "permission_denied": (+ "this workspace restricts managing user groups to admins — allow the "+ "Switch bot to manage them under Workspace settings → Roles & "+ "permissions → Account types."+ ),+ "no_permission": (+ "this workspace restricts managing user groups to admins — allow the "+ "Switch bot to manage them under Workspace settings → Roles & "+ "permissions → Account types."+ ),+ "plan_upgrade_required": ("user groups need a paid Slack plan (Pro or above)."),+ "paid_teams_only": ("user groups need a paid Slack plan (Pro or above)."),+ "missing_scope": (+ "the Slack app is missing the usergroups:read / usergroups:write "+ "scopes — reinstall it with the scopes from SLACK_SETUP.md."+ ),+}+++# Slack caps a user group's description but does not publish the limit, so this+# is a conservative guess; the create path falls back to a bare marker if Slack+# refuses it anyway.+_GROUP_DESCRIPTION_MAX = 140+++def _group_description(agent_description: str) -> str:+ """The marker, plus as much of the agent's description as will fit."""+ full = f"{_AGENT_GROUP_MARKER}{agent_description}".strip()+ if len(full) <= _GROUP_DESCRIPTION_MAX:+ return full+ return full[: _GROUP_DESCRIPTION_MAX - 1].rstrip() + "…"+++# Slack refusals that mean this app cannot host agent sessions at all, rather+# than that one call went wrong. Each says what an operator would have to change.+# How many identical unrecognised refusals before agent sessions are given up+# on. Slack returns codes this list does not know about, and a status that+# cannot work must not warn on every turn for the life of the bridge.+_AGENT_SESSIONS_FAILURE_LIMIT = 3++# Prefix on the trace lines that follow a turn through the session, so a run+# can be read end to end when something does not render. Debug level: the+# per-turn detail is only wanted when someone is looking for it.+_TRACE = "[agent-sessions] "++# Put on the message an agent is working on, for the whole turn.+_WORKING_REACTION = "eyes"++# Slack caps a task chunk's text; keep well inside it.+_STREAM_STEP_MAX = 200+++def _plain(text: str) -> str:+ """Strip Switch's markup for somewhere that renders none.++ A task card's title is plain text, so markup passed into it arrives as+ literal `_underscores_` and backticks rather than emphasis."""+ text = re.sub(r"`([^`]*)`", r"\1", text)+ text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text)+ text = re.sub(r"(?<!\w)[*_]([^*_]+)[*_](?!\w)", r"\1", text)+ return text.strip()+++def _task_chunk(+ title: str, deeplink_url: str | None = None, *, done: bool = False+) -> dict[str, Any]:+ """One step in a streamed session.++ Slack documents this payload three mutually incompatible ways — the method+ reference, the guide's sample, and the guide's full example all differ. The+ method reference is the one followed here, and the shape is kept in this+ single function so correcting it against the live API is a one-line change+ rather than a hunt.+ """+ chunk: dict[str, Any] = {+ "type": "task_update",+ "id": "current",+ "title": title,+ "status": "complete" if done else "in_progress",+ }+ if deeplink_url:+ # The way back into the live session. It used to ride on the message+ # Switch posted; now the card stands alone, so it travels here.+ chunk["sources"] = [+ {"type": "url", "text": "Open in Switch Console", "url": deeplink_url}+ ]+ return chunk+++_AGENT_SESSIONS_UNAVAILABLE_ERRORS = {+ "not_an_agent": (+ "the Slack app is not declared as an Agent — enable the Agents feature "+ "in the app's settings. Note that doing so removes access for workspace "+ "guests and cannot be undone."+ ),+ "not_authorized": (+ "Slack says the app is not a member of that channel. If it plainly is, "+ "the other cause is that the app is not declared as an Agent — only an "+ "Agent app may open sessions. Enabling that removes access for "+ "workspace guests and cannot be undone."+ ),+ "feature_disabled": (+ "the agent tasks feature is not enabled for this Slack workspace."+ ),+ "not_allowed_token_type": (+ "agent sessions need a granular bot token; this app's token is not one."+ ),+ "unknown_method": ("this Slack deployment does not offer the agent sessions API."),+ "missing_scope": (+ "the Slack app is missing the assistant:write scope — reinstall it with "+ "the scopes from SLACK_SETUP.md."+ ),+ "method_not_supported_for_channel_type": (+ "agent sessions are not supported in this kind of conversation."+ ),+}+++def _retry_after_seconds(error: SlackApiError) -> int:+ """Seconds Slack asked us to wait, falling back to a safe default."""+ headers = getattr(error.response, "headers", None) or {}+ try:+ return max(1, int(headers.get("Retry-After", _RATE_LIMIT_DEFAULT_DELAY)))+ except (TypeError, ValueError):+ return _RATE_LIMIT_DEFAULT_DELAY+class SlackUser(BaseModel):name: str@@ -48,9 +188,37 @@ class SlackConnectionConfig(BridgeConnectionConfig):bot_token: strapp_token: strworkspace_id: str+ # The descriptions are not decoration: both registration forms build+ # themselves from this schema, so what is written here is the only+ # explanation an operator gets next to the checkbox.+ agent_usergroups: bool = Field(+ default=True,+ title="Agent name autocomplete",+ description=(+ "Give each agent a Slack user group so its name completes when you "+ "type @ in a channel. Needs a paid Slack plan and permission for "+ "the bot to manage user groups; without either, agents are still "+ "addressed by typing their name."+ ),+ )+ agent_sessions: bool = Field(+ default=True,+ title="Native progress card",+ description=(+ "Show an agent's progress in Slack's own live card instead of a "+ "message Switch posts. Needs the Slack app to be declared an "+ "Agent; without that, the posted message is used instead."+ ),+ )class SlackAdapter(CollaborationAdapter):+ # Pin a turn's status to the message being worked on, opening a thread on+ # it when there is none. Without this a question asked at the channel root+ # has no thread, so its progress has nowhere to live and no session can be+ # opened for it — which was most turns.+ runtime_state_follows_anchor: ClassVar[bool] = True+def __init__(self, *, config: SlackConnectionConfig) -> None:super().__init__()self._config = config@@ -58,6 +226,7 @@ class SlackAdapter(CollaborationAdapter):self._socket_client: SocketModeClient | None = Noneself._bot_user_id: str = ""self._bot_id: str = ""+ self._team_id: str = ""self._user_cache: dict[str, SlackUser] = {}self._channel_name_cache: dict[str, str] = {}self._seen_ts: OrderedDict[str, None] = OrderedDict()@@ -73,6 +242,58 @@ class SlackAdapter(CollaborationAdapter):# topped up as new ones are resolved.self._username_to_id: dict[str, str] = {}self._thinking_ts: dict[tuple[str, str], str] = {}+ # Agent user groups, when enabled. Slack owns these objects, so the maps+ # are built by reading them back rather than stored alongside the agent:+ # a group edited or removed in Slack would otherwise leave us pointing+ # at an id that no longer means what we think it does.+ # Folded agent name → subteam id, and subteam id → agent name.+ self._agent_group_ids: dict[str, str] = {}+ self._agent_group_names: dict[str, str] = {}+ # Retired agents keep their group in a disabled state — Slack has no+ # delete — so re-adding an agent re-enables rather than colliding.+ self._agent_groups_disabled: dict[str, str] = {}+ # Every group in the workspace, id → handle, so a mention of one we do+ # not own still renders as a handle instead of raw markup.+ self._group_handles: dict[str, str] = {}+ # Groups without our marker, keyed by folded handle and folded name, so+ # an agent can claim one that was created by hand.+ self._unadopted_groups: dict[str, str] = {}+ self._agent_groups_loaded = False+ # Set to Slack's error code once the workspace has told us it cannot+ # host user groups, so the bridge stops asking and says so only once.+ self._agent_usergroups_off_reason: str | None = None+ # Set once Slack has told us it will not host agent sessions, so the+ # bridge stops asking and says so only once.+ self._agent_sessions_off_reason: str | None = None+ # Consecutive identical session-status failures, so an error code this+ # build does not recognise still stops complaining eventually.+ self._session_failures = 0+ self._last_session_error: str | None = None+ # (channel_id, thread_ts) -> agent whose turn owns that session, so the+ # stop button can be routed to the agent it belongs to.+ self._session_owner: dict[tuple[str, str], str] = {}+ # (channel_id, thread_ts) -> the open stream's ts, and the last step+ # pushed into it. A stream is what creates the session Slack renders.+ self._stream_ts: dict[tuple[str, str], str] = {}+ self._stream_step: dict[tuple[str, str], str] = {}+ # (channel_id, thread_ts) -> who asked. Streaming into a channel has to+ # name the person being replied to, which the runtime-state path does+ # not carry, so it is remembered from the message that started it.+ self._thread_requester: dict[tuple[str, str], str] = {}+ # (channel_id, agent_name) already reported as having no thread, so the+ # trace says it once rather than on every state report.+ self._threadless_logged: set[tuple[str, str]] = set()+ # (channel_id, ts) currently carrying the "being worked on" reaction.+ self._eyes: set[tuple[str, str]] = set()+ # (channel_id, agent_name) -> every thread that agent is working in.+ # A turn ends once but may have opened several.+ self._agent_threads: dict[tuple[str, str], set[str]] = {}+ # (channel_id, agent_name) -> every message that agent has marked. Not+ # the same as the threads: the mark goes on the message that asked,+ # which inside a thread is a reply rather than the root.+ self._agent_eyes: dict[tuple[str, str], set[str]] = {}+ # (channel_id, thread_ts) -> ts of the last message asking in it.+ self._thread_trigger: dict[tuple[str, str], str] = {}# ── Lifecycle ────────────────────────────────────────────────────────────@@ -102,6 +323,11 @@ class SlackAdapter(CollaborationAdapter):)self._bot_user_id = auth["user_id"]self._bot_id = str(auth.get("bot_id", ""))+ # The team this bot is installed in. Not the same as the configured+ # workspace id on an Enterprise Grid org, where that is the org id+ # (`E…`) and streaming wants the team (`T…`) — so take it from the+ # authenticated identity rather than from config.+ self._team_id = str(auth.get("team_id", ""))logger.info("Slack adapter authenticated as %s (workspace %s)",auth.get("user", ""),@@ -117,6 +343,10 @@ class SlackAdapter(CollaborationAdapter):)await self._socket_client.connect()logger.info("Slack Socket Mode connected")+ logger.debug(+ _TRACE + "build carries agent sessions; config agent_sessions=%s",+ self._config.agent_sessions,+ )async def stop(self) -> None:if self._socket_client:@@ -480,11 +710,30 @@ class SlackAdapter(CollaborationAdapter):When the agent was addressed in a thread, messages surface in thatthread (``thread_root_id``); otherwise at the channel root."""+ # Handled before the branching below, because the working branch+ # returns early when it only has to refresh the message in place — and+ # the session still has to track the turn.+ await self._track_turn(+ channel_id,+ thread_root_id,+ agent_name,+ state=state,+ detail=detail,+ deeplink_url=deeplink_url,+ )+key = (channel_id, agent_name)if state == "working":# Resuming work means the requested input was provided — clear the# now-resolved pings, then ensure the working indicator is up.await self._clear_input_pings(channel_id, agent_name)+ if self._streaming(channel_id, thread_root_id):+ # Slack is drawing this turn itself, and better: the card is+ # live, named for the agent, and carries the console link. A+ # posted message beside it would say the same thing twice, so+ # any earlier one is taken down.+ await self._clear_working(channel_id, agent_name)+ return# Posted under the agent's own name/icon, so the body just states# the activity — no need to repeat the agent name in the text.body = self._working_body(detail, deeplink_url)@@ -515,6 +764,412 @@ class SlackAdapter(CollaborationAdapter):await self._clear_working(channel_id, agent_name)await self._clear_input_pings(channel_id, agent_name)+ async def _track_turn(+ self,+ channel_id: str,+ thread_root_id: str | None,+ agent_name: str,+ *,+ state: str,+ detail: str | None,+ deeplink_url: str | None,+ ) -> None:+ """Keep every thread this agent has in flight, and end them together.++ An agent asked two things at once works on both, and each message gets+ its own card and its own eyes — but the turn ends **once**, naming only+ the thread it last touched. Cleaning up just that one leaves the first+ message marked as being worked on for good, and its card frozen+ mid-task. So the threads are remembered per agent and closed together.+ """+ akey = (channel_id, agent_name)+ thread_ts = self._thread_ts_of(thread_root_id)++ if state in ("working", "awaiting-input"):+ if not thread_ts:+ await self._update_session(+ channel_id,+ thread_root_id,+ agent_name,+ state=state,+ detail=detail,+ deeplink_url=deeplink_url,+ )+ return+ self._agent_threads.setdefault(akey, set()).add(thread_ts)+ asked_on = self._thread_trigger.get((channel_id, thread_ts), thread_ts)+ self._agent_eyes.setdefault(akey, set()).add(asked_on)+ await self._mark_being_read(channel_id, asked_on, working=True)+ await self._update_session(+ channel_id,+ thread_root_id,+ agent_name,+ state=state,+ detail=detail,+ deeplink_url=deeplink_url,+ )+ return++ for ts in sorted(self._agent_eyes.pop(akey, set())):+ await self._mark_being_read(channel_id, ts, working=False)+ for ts in sorted(self._agent_threads.pop(akey, set())):+ # Ownership goes with the turn: a stop pressed afterwards must not+ # interrupt whatever the agent moved on to.+ self._session_owner.pop((channel_id, ts), None)+ await self._drive_stream(+ channel_id,+ ts,+ agent_name,+ working=False,+ detail=None,+ deeplink_url=None,+ )++ async def _mark_being_read(+ self, channel_id: str, thread_ts: str | None, *, working: bool+ ) -> None:+ """Put 👀 on the message an agent is working on, and take it off after.++ Unlike the session card this needs nothing from Slack beyond a scope we+ already hold, and it works at the channel root as well as in a thread —+ so it is the one progress signal that is always available. It also says+ *which* message is being handled, which a status elsewhere cannot.+ """+ ts = thread_ts+ if not ts or not self._web_client:+ return+ key = (channel_id, ts)+ if working == (key in self._eyes):+ return++ try:+ if working:+ await self._web_client.reactions_add(+ channel=channel_id, timestamp=ts, name=_WORKING_REACTION+ )+ self._eyes.add(key)+ else:+ await self._web_client.reactions_remove(+ channel=channel_id, timestamp=ts, name=_WORKING_REACTION+ )+ self._eyes.discard(key)+ except SlackApiError as e:+ error = e.response.get("error", "")+ # Already there, or already gone: the end state is what was wanted,+ # so record it and say nothing.+ if error in ("already_reacted", "no_reaction"):+ self._eyes.add(key) if working else self._eyes.discard(key)+ return+ logger.warning(+ "Could not %s the working reaction on %s: %s",+ "add" if working else "remove",+ channel_id,+ error or e,+ )++ def _streaming(self, channel_id: str, thread_root_id: str | None) -> bool:+ """Whether Slack is already drawing this turn's progress itself."""+ thread_ts = self._thread_ts_of(thread_root_id)+ return bool(thread_ts) and (channel_id, thread_ts) in self._stream_ts++ # ── Native agent session ─────────────────────────────────────────────────++ async def _update_session(+ self,+ channel_id: str,+ thread_root_id: str | None,+ agent_name: str,+ *,+ state: str,+ detail: str | None = None,+ deeplink_url: str | None = None,+ ) -> None:+ """Mirror the turn onto a Slack agent session.++ This is additive: the status messages Switch posts are what actually+ carry the detail, and they are unchanged. This adds Slack's own live+ card of what the agent is doing, under the agent's name and icon.++ The card is the stream. Slack also has a session *status*, which does+ render — but as a second element attributed to the app rather than the+ agent, with Slack's own generic wording and no way to rename it. Two+ cards for one turn, one of them anonymous, reads worse than one, so it+ is deliberately not set here. The stop button that hangs off it goes+ with it.++ A session is scoped to a thread, so a turn with none is left to the+ posted messages alone.+ """+ if not self._config.agent_sessions:+ logger.debug(_TRACE + "skipped for %s: turned off in config", agent_name)+ return+ if self._agent_sessions_off_reason:+ # Silent by design. Giving up is announced once, where it happens;+ # saying so again per skipped turn produced eleven thousand lines+ # in a night — an instrument that ruins the thing it measures.+ return+ if not self._web_client:+ logger.debug(_TRACE + "skipped for %s: Slack not connected", agent_name)+ return+ thread_ts = self._thread_ts_of(thread_root_id)+ if not thread_ts:+ # Once per agent per channel. Runtime state is reported many times+ # a turn and most turns have no thread, so logging every one buries+ # everything else.+ if (channel_id, agent_name) not in self._threadless_logged:+ self._threadless_logged.add((channel_id, agent_name))+ logger.debug(+ _TRACE + "no thread for %s in %s, so no session (state '%s')",+ agent_name,+ channel_id,+ state,+ )+ return+ self._threadless_logged.discard((channel_id, agent_name))++ working = state in ("working", "awaiting-input")+ key = (channel_id, thread_ts)+ if working:+ self._session_owner[key] = agent_name+ else:+ self._session_owner.pop(key, None)++ await self._drive_stream(+ channel_id,+ thread_ts,+ agent_name,+ working=working,+ detail=detail,+ deeplink_url=deeplink_url,+ )++ def _note_session_failure(+ self, error: str, agent_name: str, channel_id: str+ ) -> None:+ """Log a failed status call, and give up if it is not going to improve.++ A known refusal names its cause immediately. An unrecognised one cannot+ be told apart from a passing fault on the first sight of it, so it is+ logged and retried — but only so many times. Slack returns codes this+ list does not know about (`not_authorized` for an app that is not an+ agent, found in the pilot), and without a backstop each one means a+ warning on every turn for as long as the bridge runs.+ """+ if error in _AGENT_SESSIONS_UNAVAILABLE_ERRORS:+ self._disable_agent_sessions(error)+ return++ # One turn's status failing is not worth losing the turn over — the+ # posted indicator still says what is happening.+ self._session_failures = (+ self._session_failures + 1 if error == self._last_session_error else 1+ )+ self._last_session_error = error+ logger.warning(+ "Could not set the Slack session status for agent %s in %s: %s",+ agent_name,+ channel_id,+ error or "unknown error",+ )+ if self._session_failures >= _AGENT_SESSIONS_FAILURE_LIMIT:+ self._disable_agent_sessions(error)++ async def _drive_stream(+ self,+ channel_id: str,+ thread_ts: str,+ agent_name: str,+ *,+ working: bool,+ detail: str | None,+ deeplink_url: str | None,+ ) -> None:+ """Open, extend and close the stream that backs the session.++ The stream calls go through the SDK's own methods, which send JSON and+ keep the argument names honest; only the session status has no typed+ method to use."""+ client = self._web_client+ if client is None:+ return+ key = (channel_id, thread_ts)+ open_ts = self._stream_ts.get(key)++ if not working:+ if open_ts:+ closing_ts = open_ts+ if self._stream_step.get(key):+ # Marked done before closing. The card is deleted a moment+ # later, so this only shows if that delete is refused — and+ # a leftover reading "finished" beats one reading "failed",+ # which is what an unfinished step renders as.+ await self._call_session_api(+ lambda: client.chat_appendStream(+ channel=channel_id,+ ts=closing_ts,+ chunks=[_task_chunk(self._stream_step[key], done=True)],+ ),+ agent_name=agent_name,+ channel_id=channel_id,+ )+ await self._call_session_api(+ lambda: client.chat_stopStream(channel=channel_id, ts=closing_ts),+ agent_name=agent_name,+ channel_id=channel_id,+ )+ # The card is a progress indicator, not a record. Once the turn+ # is over the agent's own reply is the thing worth reading, so+ # the card goes the way the posted status message always did.+ await self.delete_message(channel_id, f"{channel_id}:{closing_ts}")+ self._stream_ts.pop(key, None)+ self._stream_step.pop(key, None)+ logger.debug(_TRACE + "closed stream for %s on %s", agent_name, key[1])+ return++ step = (_plain(detail or "") or "Working")[:_STREAM_STEP_MAX]+ if open_ts is None:+ requester = self._thread_requester.get(key)+ if not requester:+ logger.debug(+ _TRACE + "no stream for %s on %s: nobody recorded to stream to",+ agent_name,+ thread_ts,+ )+ return+ if not self._team_id:+ logger.debug(+ _TRACE + "no stream for %s: the bot's team id is unknown",+ agent_name,+ )+ return+ icon_url = await self.agent_icon_url(agent_name)+ open_ts = await self._call_session_api(+ lambda: client.chat_startStream(+ channel=channel_id,+ thread_ts=thread_ts,+ recipient_user_id=requester,+ recipient_team_id=self._team_id,+ task_display_mode="timeline",+ username=agent_name,+ icon_url=icon_url,+ ),+ agent_name=agent_name,+ channel_id=channel_id,+ )+ if open_ts is None:+ return+ if not open_ts:+ logger.warning(+ _TRACE + "Slack opened a stream for %s with no ts", agent_name+ )+ return+ self._stream_ts[key] = open_ts+ logger.debug(_TRACE + "opened stream %s for %s", open_ts, agent_name)+ elif self._stream_step.get(key) == step:+ return++ # Slack accumulates a task's sources across updates rather than+ # replacing them, so the link goes on the first step only — sending it+ # every time stacked eight identical links under one card.+ first_link = deeplink_url if self._stream_step.get(key) is None else None+ stream_ts = open_ts+ await self._call_session_api(+ lambda: client.chat_appendStream(+ channel=channel_id,+ ts=stream_ts,+ chunks=[_task_chunk(step, first_link)],+ ),+ agent_name=agent_name,+ channel_id=channel_id,+ )+ self._stream_step[key] = step++ async def _call_session_api(+ self,+ call: Callable[[], Awaitable[Any]],+ *,+ agent_name: str,+ channel_id: str,+ ) -> str | None:+ """Make a session call, routing a refusal through the same give-up path.++ Returns the response's `ts` on success (empty string when it has none)+ and None on failure, so a caller that needs the stream's id cannot+ mistake a refusal for a stream it can append to."""+ try:+ result = await call()+ except SlackApiError as e:+ self._note_session_failure(+ str(e.response.get("error", "")), agent_name, channel_id+ )+ return None+ self._session_failures = 0+ return str(result.get("ts", ""))++ def _disable_agent_sessions(self, error: str) -> None:+ if self._agent_sessions_off_reason:+ return+ self._agent_sessions_off_reason = error+ reason = _AGENT_SESSIONS_UNAVAILABLE_ERRORS.get(+ error,+ f"Slack kept refusing with '{error or 'an unknown error'}'. If the "+ "app is not declared as an Agent in its settings, that is the "+ "likeliest cause.",+ )+ logger.warning(+ "Slack agent sessions are unavailable for this app (%s): %s "+ "Turns still show Switch's own status messages; only Slack's native "+ "loading UX and stop button are missing.",+ error,+ reason,+ )++ @staticmethod+ def _thread_ts_of(thread_root_id: str | None) -> str | None:+ if not thread_root_id:+ return None+ return (+ thread_root_id.split(":", 1)[1] if ":" in thread_root_id else thread_root_id+ )++ async def _handle_session_stopped(self, event: dict[str, object]) -> None:+ """Route Slack's stop button to the agent whose turn it belongs to.++ Setting a session to `processing` puts a stop button on the thread. A+ button that does nothing is worse than no button, so it is wired to the+ same interrupt an operator can type — anything less would be a control+ that lies about what it does.+ """+ channel_id = str(event.get("channel_id") or event.get("channel") or "")+ thread_ts = str(event.get("thread_ts") or "")+ if not channel_id or not thread_ts or self._on_command is None:+ return++ agent_name = self._session_owner.pop((channel_id, thread_ts), None)+ if not agent_name:+ logger.info(+ "Slack session stopped in %s (%s) with no agent turn to interrupt",+ channel_id,+ thread_ts,+ )+ return++ user_id = str(event.get("user_id") or event.get("user") or "")+ user = await self._resolve_user_name(user_id) if user_id else None+ await self._on_command(+ InboundCommand(+ channel_id=channel_id,+ channel_type=await self.get_channel_type(channel_id),+ sender_id=user_id,+ sender_name=user.name if user else "slack",+ command="interrupt",+ args=f"@{agent_name}",+ message_ref=None,+ root_id=f"{channel_id}:{thread_ts}",+ channel_name=await self._resolve_channel_name(channel_id),+ )+ )+async def _clear_working(self, channel_id: str, agent_name: str) -> None:live = self._working_msg.pop((channel_id, agent_name), None)if live is not None:@@ -665,10 +1320,332 @@ class SlackAdapter(CollaborationAdapter):async def create_agent_identity(self, agent_name: str, agent_description: str) -> None:- pass+ """Give the agent a Slack user group so its name completes on `@`.++ Slack only offers autocomplete for things it knows about, and an agent+ is not a Slack user — one app serves all of them. A user group is the+ one handle an app can mint that still appears in the composer's `@`+ menu, so each agent gets one. The group is left empty: it exists to be+ completable and to arrive as a structured mention, and mentioning it+ notifies nobody.+ """+ if not self._agent_usergroups_available():+ return+ if not self._web_client:+ raise RuntimeError("Cannot create agent user group: Slack not connected")++ await self._ensure_agent_groups_loaded()+ if not self._agent_usergroups_available():+ return+ folded = agent_name.casefold()+ if folded in self._agent_group_ids:+ return++ handle = self._usergroup_handle(agent_name)+ adopted_id = self._unadopted_groups.get(folded) or self._unadopted_groups.get(+ handle.casefold()+ )+ if adopted_id:+ await self._adopt_group(adopted_id, agent_name)+ return++ disabled_id = self._agent_groups_disabled.get(folded)+ if disabled_id:+ await self._web_client.usergroups_enable(usergroup=disabled_id)+ self._agent_groups_disabled.pop(folded, None)+ self._remember_agent_group(disabled_id, agent_name)+ logger.info(+ "Re-enabled Slack user group %s for agent %s", disabled_id, agent_name+ )+ return++ try:+ result = await self._rate_limited(+ lambda: self._create_usergroup(agent_name, handle, agent_description),+ what=f"create a Slack user group for agent '{agent_name}'",+ )+ except SlackApiError as e:+ error = e.response.get("error", "")+ if error in ("handle_already_exists", "name_already_exists"):+ # Something already owns the handle. If it is one of ours the+ # reload adopts it; if it is a real group or a channel, say so+ # rather than leaving the agent silently unmentionable.+ await self._load_agent_usergroups()+ if folded in self._agent_group_ids:+ return+ raise RuntimeError(+ f"Cannot create a Slack user group for agent '{agent_name}': "+ f"the handle '@{handle}' is already taken by a channel, "+ "person or group that is not ours. Rename the agent or free "+ "the handle."+ ) from e+ if error in _USERGROUPS_UNAVAILABLE_ERRORS:+ self._disable_agent_usergroups(error)+ return+ raise++ group = result.get("usergroup") or {}+ group_id = str(group.get("id", ""))+ if not group_id:+ raise RuntimeError(+ f"Slack returned no user group id when creating one for agent "+ f"'{agent_name}'"+ )+ self._remember_agent_group(group_id, agent_name)+ logger.info(+ "Created Slack user group @%s (%s) for agent %s",+ handle,+ group_id,+ agent_name,+ )async def remove_agent_identity(self, agent_name: str) -> None:- pass+ if not self._agent_usergroups_available():+ return+ if not self._web_client:+ raise RuntimeError("Cannot remove agent user group: Slack not connected")++ await self._ensure_agent_groups_loaded()+ if not self._agent_usergroups_available():+ return+ folded = agent_name.casefold()+ group_id = self._agent_group_ids.get(folded)+ if not group_id:+ return++ # Slack has no delete for user groups — disabling is the documented way+ # to retire one, and it stops the handle resolving.+ await self._web_client.usergroups_disable(usergroup=group_id)+ self._agent_group_ids.pop(folded, None)+ self._agent_group_names.pop(group_id, None)+ self._agent_groups_disabled[folded] = group_id+ logger.info("Disabled Slack user group %s for agent %s", group_id, agent_name)++ # ── Agent user groups ────────────────────────────────────────────────────++ def _agent_usergroups_available(self) -> bool:+ return self._config.agent_usergroups and not self._agent_usergroups_off_reason++ def _disable_agent_usergroups(self, error: str) -> None:+ """Stop attempting user groups on this bridge, saying why, once.++ The setting is on by default, so a workspace that simply cannot host+ user groups is an ordinary situation rather than a misconfiguration —+ but it must not be a silent one, and it must not repeat the complaint+ for every agent on every startup. Latching turns it into one warning+ that names the cause and the consequence.+ """+ if self._agent_usergroups_off_reason:+ return+ self._agent_usergroups_off_reason = error+ logger.warning(+ "Slack agent user groups are unavailable on this workspace (%s): %s "+ "Agent names will not autocomplete in the Slack composer; agents "+ "remain addressable by typing their name.",+ error,+ _USERGROUPS_UNAVAILABLE_ERRORS[error],+ )++ def _require_web_client(self) -> AsyncWebClient:+ if not self._web_client:+ raise RuntimeError("Slack client not connected")+ return self._web_client++ async def _rate_limited(+ self, call: Callable[[], Awaitable[Any]], *, what: str+ ) -> Any:+ """Run a Slack call, waiting out rate limits rather than losing it.++ Provisioning runs once per agent at startup, so a workspace with more+ agents than the per-minute allowance would otherwise come up with some+ agents mentionable and some not — and the caller only logs, so nothing+ would say which. Waiting keeps the backfill whole; giving up after a+ bounded number of attempts keeps a persistently throttled workspace+ from hanging startup, and says so rather than continuing quietly.+ """+ for attempt in range(_RATE_LIMIT_MAX_ATTEMPTS):+ try:+ return await call()+ except SlackApiError as e:+ if e.response.get("error") != "ratelimited":+ raise+ if attempt == _RATE_LIMIT_MAX_ATTEMPTS - 1:+ raise RuntimeError(+ f"Slack kept rate-limiting the attempt to {what} after "+ f"{_RATE_LIMIT_MAX_ATTEMPTS} tries. Some agents may have "+ "no user group and so will not autocomplete; restart the "+ "bridge to finish provisioning."+ ) from e+ delay = _retry_after_seconds(e)+ logger.warning(+ "Slack rate-limited the attempt to %s; retrying in %ss "+ "(attempt %d/%d)",+ what,+ delay,+ attempt + 1,+ _RATE_LIMIT_MAX_ATTEMPTS,+ )+ await asyncio.sleep(delay)+ raise RuntimeError(f"Unreachable: exhausted retries to {what}")++ async def _create_usergroup(+ self, agent_name: str, handle: str, agent_description: str+ ) -> Any:+ """Create the group, retrying without the blurb if Slack rejects it.++ An agent's description is free text and can run to a paragraph, while+ Slack caps a user group's description and does not publish the limit —+ so a conservative truncation can still be refused. The description is+ decoration; the marker is the part that carries meaning. Losing an+ agent's autocomplete over the length of its blurb would be absurd, so+ the blurb is what gets dropped.+ """+ client = self._require_web_client()+ try:+ return await client.usergroups_create(+ name=agent_name,+ handle=handle,+ description=_group_description(agent_description),+ )+ except SlackApiError as e:+ if e.response.get("error") != "description_too_long":+ raise+ logger.warning(+ "Slack rejected the description for agent %s's user group as too "+ "long; creating it with just the marker instead.",+ agent_name,+ )+ return await client.usergroups_create(+ name=agent_name,+ handle=handle,+ description=f"{_AGENT_GROUP_MARKER}{agent_name}",+ )++ async def _adopt_group(self, group_id: str, agent_name: str) -> None:+ """Claim a user group someone made by hand for this agent.++ Where a workspace will not let the bot create groups, making them by+ hand is the only way to use the feature — so a group whose handle or+ name is exactly an agent's is taken to be that agent's. The match has to+ be exact: a workspace's own group must never be captured by an agent+ that happens to be named similarly.++ The marker is stamped on so later loads recognise it without needing+ the agent list. That is an optimisation, not a requirement — adoption+ happens per agent at startup either way — so failing to write it is+ worth a warning rather than abandoning the adoption.+ """+ for key in (agent_name.casefold(), self._usergroup_handle(agent_name)):+ self._unadopted_groups.pop(key, None)+ self._remember_agent_group(group_id, agent_name)+ logger.info(+ "Adopted existing Slack user group %s for agent %s", group_id, agent_name+ )++ try:+ await self._rate_limited(+ lambda: self._require_web_client().usergroups_update(+ usergroup=group_id,+ description=f"{_AGENT_GROUP_MARKER}{agent_name}",+ ),+ what=f"mark the adopted user group for agent '{agent_name}'",+ )+ except (SlackApiError, RuntimeError):+ logger.warning(+ "Adopted Slack user group %s for agent %s but could not mark it "+ "as ours; it will be re-adopted on each start.",+ group_id,+ agent_name,+ exc_info=True,+ )++ def _remember_agent_group(self, group_id: str, agent_name: str) -> None:+ self._agent_group_ids[agent_name.casefold()] = group_id+ self._agent_group_names[group_id] = agent_name++ @staticmethod+ def _usergroup_handle(agent_name: str) -> str:+ """Fold an agent name into a Slack handle.++ Agent names already share Slack's handle character class, so this is+ usually just a lowercase. Anything outside it collapses to a hyphen so+ an unusual name still yields a mentionable handle; the group's `name`+ carries the agent name verbatim, so the round trip does not depend on+ the handle surviving unchanged.+ """+ handle = re.sub(r"[^a-z0-9._-]+", "-", agent_name.casefold())+ return handle.strip("-._") or "switch-agent"++ async def _ensure_agent_groups_loaded(self) -> None:+ if not self._agent_groups_loaded:+ await self._load_agent_usergroups()++ async def _load_agent_usergroups(self) -> None:+ """Rebuild the agent ↔ user group maps from Slack.++ Only groups we created are adopted, recognised by the marker on their+ description — a workspace's own groups must never be mistaken for an+ agent, or mentioning one would address an agent that has nothing to do+ with it.+ """+ if not self._web_client:+ raise RuntimeError("Cannot load Slack user groups: Slack not connected")++ try:+ result = await self._rate_limited(+ lambda: self._require_web_client().usergroups_list(+ include_disabled=True+ ),+ what="list Slack user groups",+ )+ except SlackApiError as e:+ error = e.response.get("error", "")+ if error in _USERGROUPS_UNAVAILABLE_ERRORS:+ # The first call is where a workspace without the plan or the+ # permission finds out, so it is the natural place to give up.+ self._disable_agent_usergroups(error)+ self._agent_groups_loaded = True+ return+ raise++ groups: list[dict[str, Any]] = result.get("usergroups") or []++ self._agent_group_ids = {}+ self._agent_group_names = {}+ self._agent_groups_disabled = {}+ self._group_handles = {}+ self._unadopted_groups = {}+ for group in groups:+ group_id = str(group.get("id", ""))+ handle = str(group.get("handle", ""))+ name = str(group.get("name", ""))+ if not group_id:+ continue+ if handle:+ self._group_handles[group_id] = handle++ if not str(group.get("description", "")).startswith(_AGENT_GROUP_MARKER):+ # Not ours — but it may still be an agent's, made by hand. Keyed+ # both ways so an agent can claim it by either field.+ for key in (handle.casefold(), name.casefold()):+ if key:+ self._unadopted_groups[key] = group_id+ continue++ if not name:+ continue+ if group.get("date_delete"):+ self._agent_groups_disabled[name.casefold()] = group_id+ else:+ self._remember_agent_group(group_id, name)++ self._agent_groups_loaded = True+ logger.info(+ "Loaded %d Slack agent user groups (%d disabled, %d other groups seen)",+ len(self._agent_group_ids),+ len(self._agent_groups_disabled),+ len(self._group_handles) - len(self._agent_group_ids),+ )async def get_channel_agent_names(self, channel_id: str) -> list[str]:return []@@ -707,13 +1684,19 @@ class SlackAdapter(CollaborationAdapter):def _translate_mentions_to_slack(self, content: str) -> str:"""Rewrite `@username` to a Slack `<@USER_ID>` mention for users we know,- so Slack renders the person's display name. Unknown names (e.g. agents,- or users we have not resolved) are left as plain text."""+ so Slack renders the person's display name, and `@agent-name` to the+ agent's user group where one exists, so an agent mention renders as a+ real pill rather than bare text — the same thing a person sees when they+ pick the agent from autocomplete. The group is empty, so rendering the+ mention notifies nobody. Unknown names are left as plain text."""def _replace(match: re.Match[str]) -> str:username = match.group(1)user_id = self._username_to_id.get(username.casefold())- return f"<@{user_id}>" if user_id else match.group(0)+ if user_id:+ return f"<@{user_id}>"+ group_id = self._agent_group_ids.get(username.casefold())+ return f"<!subteam^{group_id}>" if group_id else match.group(0)return re.sub(r"@([A-Za-z0-9][A-Za-z0-9._-]*)", _replace, content)@@ -744,6 +1727,8 @@ class SlackAdapter(CollaborationAdapter):await self._handle_message_event(event)elif event_type == "member_joined_channel":await self._handle_member_joined_channel(event)+ elif event_type == "agent_session_stopped":+ await self._handle_session_stopped(event)async def _handle_member_joined_channel(self, event: dict[str, object]) -> None:user_id = str(event.get("user", ""))@@ -859,6 +1844,15 @@ class SlackAdapter(CollaborationAdapter):# Remember the thread this message belongs to so the "thinking"# indicator can be posted into the same conversation.self._last_thread_ts[channel_id] = thread_ts or message_ts+ # Streaming a reply into a channel has to name who it is for, and the+ # runtime-state path never sees the asker — so keep it per thread.+ if user_id and not bot_id:+ root = thread_ts or message_ts+ self._thread_requester[(channel_id, root)] = user_id+ # The message that actually asked. Inside a thread this is a reply,+ # not the root, and the mark belongs on what was said — not on the+ # conversation it happens to sit in.+ self._thread_trigger[(channel_id, root)] = message_tsmessage_ref = f"{channel_id}:{message_ts}"stripped = text.strip()@@ -1240,7 +2234,43 @@ class SlackAdapter(CollaborationAdapter):# command escapes its text — as `<@U123|username>`. Accept the optional# `|label` so escaped slash-command mentions (including the bridge bot's# own id, used as its room alias) resolve the same as message mentions.- return re.sub(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>", _replace_mention, message)+ message = re.sub(r"<@(U[A-Z0-9]+)(?:\|[^>]+)?>", _replace_mention, message)+ return self._translate_usergroup_mentions(message)++ def _translate_usergroup_mentions(self, message: str) -> str:+ """Rewrite a user group mention to the plain `@agent-name` text.++ An agent's group is how its name reaches the composer's autocomplete,+ so a user picking it from the `@` menu sends `<!subteam^S123>` rather+ than the typed name. Resolving it back to the agent's name is what lets+ the rest of Switch treat it as an ordinary mention — the addressing+ layer downstream matches on the name, and knows nothing about Slack.++ The id maps to the agent name we stored on the group, not to the handle,+ so an agent whose name had to be folded to make a legal handle still+ resolves to its real name. Groups we do not know are left untouched: a+ workspace's own group is not an agent, and rewriting it would invent a+ mention of someone who does not exist.+ """++ def _replace(match: re.Match[str]) -> str:+ group_id = match.group(1)+ agent_name = self._agent_group_names.get(group_id)+ if agent_name:+ return f"@{agent_name}"+ label = match.group(2)+ if label:+ return label.lstrip("|")+ # Not an agent's group, or one we have not adopted yet. Its handle+ # still reads as a mention, where the raw tag is just broken output+ # in the room — and if the handle is an agent's name, the ordinary+ # text matching downstream picks it up anyway.+ handle = self._group_handles.get(group_id)+ return f"@{handle}" if handle else match.group(0)++ # `<!subteam^S123>` is the documented form; the `|@handle` variant is+ # what Slack actually sends on some paths, so accept both.+ return re.sub(r"<!subteam\^([A-Z0-9]+)(\|[^>]*)?>", _replace, message)# ── Markdown → mrkdwn ────────────────────────────────────────────────────diff --git a/core/switch_core/db/stores/collaboration_bridge_store.py b/core/switch_core/db/stores/collaboration_bridge_store.pyindex 0999f31b5..cc4d8eb3a 100644--- a/core/switch_core/db/stores/collaboration_bridge_store.py+++ b/core/switch_core/db/stores/collaboration_bridge_store.py@@ -86,6 +86,21 @@ class CollaborationBridgeStore:await session.flush()return bridge+ async def merge_connection_config(+ self, session: AsyncSession, bridge_id: str, changes: dict[str, object]+ ) -> CollaborationBridge:+ """Merge `changes` into ``connection_config``, keeping untouched keys.++ Merging rather than replacing means an operator can flip one setting+ without re-sending the platform's tokens. Reassigns the dict so+ SQLAlchemy tracks the change."""+ bridge = await session.get(CollaborationBridge, bridge_id)+ if bridge is None:+ raise ValueError(f"Bridge not found: {bridge_id}")+ bridge.connection_config = {**(bridge.connection_config or {}), **changes}+ await session.flush()+ return bridge+async def set_service_url(self, session: AsyncSession, bridge_id: str, service_url: str) -> None:diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 87c8cd542..c05685a69 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -272,7 +272,23 @@ async def update_bridge(bridge = await bridge_store.set_channel_creation_enabled(session, bridge_id, payload.channel_creation_enabled)+ if payload.connection_config is not None:+ merged = {**(bridge.connection_config or {}), **payload.connection_config}+ try:+ collab_lifecycle.validate_connection_config(bridge.type, merged)+ except ValidationError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ bridge = await bridge_store.merge_connection_config(+ session, bridge_id, dict(payload.connection_config)+ )await session.commit()++ # A running adapter holds the config it was built with, so a change only+ # takes effect on restart. Doing it here means enabling something is the+ # whole operation rather than a change that quietly does nothing until the+ # next deploy.+ if payload.connection_config is not None:+ await collab_lifecycle.restart(bridge_id)rooms = await room_store.get_by_bridge(session, bridge_id)return await _detail(bridge, room_count=len(rooms), collab_lifecycle=collab_lifecyclediff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 896002106..f2931cdee 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -468,11 +468,16 @@ class BridgeDetail(BaseModel):class BridgeUpdateRequest(BaseModel):- # Both optional so a caller can change one without restating the other; a- # request that sets neither changes nothing rather than silently resetting+ # All optional so a caller can change one without restating the others; a+ # request that sets none changes nothing rather than silently resetting# a field it did not mention.agent_greetings_enabled: bool | None = Nonechannel_creation_enabled: bool | None = None+ # Merged over the stored config, not substituted for it, so changing one+ # setting does not mean re-sending the platform's secrets. The merged+ # result is validated against the bridge type's schema before it is kept,+ # and the bridge is restarted so the change actually takes effect.+ connection_config: dict[str, object] | None = Noneclass BridgeTypeInfo(BaseModel):diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.pynew file mode 100644index 000000000..73021b84c--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_identity_backfill.py@@ -0,0 +1,133 @@+"""Agent identity provisioning must not hold up the bridge coming online.++Provisioning is one platform call per agent, and a rate-limited platform turns+that into minutes of mostly waiting. Awaiting it inside start() would delay the+bridge, every other bridge queued behind it, and any request that restarts one.+"""++from __future__ import annotations++import asyncio+from typing import Any++import pytest++from switch_core.bridges.collaboration.bridge_core import BridgeCore+++class _FakeAdapter:+ def __init__(self) -> None:+ self.started = False+ self.stopped = False++ def set_channel_migration_handler(self, handler: Any) -> None:+ pass++ def set_agent_icon_resolver(self, resolver: Any) -> None:+ pass++ async def start(self, **kwargs: Any) -> None:+ self.started = True++ async def stop(self) -> None:+ self.stopped = True+++def _core(provision: Any) -> tuple[BridgeCore, _FakeAdapter]:+ """A BridgeCore with everything start() touches stubbed but the task logic."""+ core = object.__new__(BridgeCore)+ adapter = _FakeAdapter()+ core._bridge_type = "slack" # type: ignore[attr-defined]+ core._adapter = adapter # type: ignore[attr-defined]+ core._identity_task = None # type: ignore[attr-defined]++ async def _noop() -> None:+ return None++ core._load_channel_map = _noop # type: ignore[assignment]+ core._load_existing_puppets = _noop # type: ignore[assignment]+ core._ensure_channel_captures = _noop # type: ignore[assignment]+ core._handle_channel_migrated = None # type: ignore[attr-defined]+ core._agent_icon_url = None # type: ignore[attr-defined]+ core._handle_inbound_message = None # type: ignore[attr-defined]+ core._handle_inbound_command = None # type: ignore[attr-defined]+ core._handle_agent_joined_channel = None # type: ignore[attr-defined]+ core._handle_user_joined_channel = None # type: ignore[attr-defined]+ core._handle_app_joined_channel = None # type: ignore[attr-defined]+ core._create_agent_identities = provision # type: ignore[assignment]+ return core, adapter+++async def test_start_returns_without_waiting_for_provisioning() -> None:+ finished = False++ async def _slow_provision() -> None:+ nonlocal finished+ await asyncio.sleep(30)+ finished = True++ core, adapter = _core(_slow_provision)++ await asyncio.wait_for(core.start(), timeout=1)++ assert adapter.started+ assert not finished+ assert core._identity_task is not None+ await core.stop()+++async def test_provisioning_still_runs_after_start_returns() -> None:+ done = asyncio.Event()++ async def _provision() -> None:+ done.set()++ core, _ = _core(_provision)++ await core.start()+ await asyncio.wait_for(done.wait(), timeout=1)++ await core.stop()+++async def test_stop_cancels_provisioning_in_flight() -> None:+ """A bridge being torn down must not leave work running against the+ platform on its behalf."""+ started = asyncio.Event()++ async def _slow_provision() -> None:+ started.set()+ await asyncio.sleep(30)++ core, _ = _core(_slow_provision)++ await core.start()+ task = core._identity_task+ await asyncio.wait_for(started.wait(), timeout=1)+ await core.stop()++ assert task is not None+ await asyncio.sleep(0)+ assert task.cancelled() or task.done()+ assert core._identity_task is None+++async def test_a_failure_is_logged_rather_than_swallowed(+ caplog: pytest.LogCaptureFixture,+) -> None:+ """create_task discards whatever the coroutine raises, so anything escaping+ the per-agent handling would otherwise vanish without trace."""++ async def _explode() -> None:+ raise RuntimeError("provisioning blew up")++ core, _ = _core(_explode)++ with caplog.at_level("ERROR"):+ await core.start()+ task = core._identity_task+ assert task is not None+ await task++ assert any("stopped unexpectedly" in r.getMessage() for r in caplog.records)+ await core.stop()diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.pyindex 4c3d6308e..bbba1d669 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_type_registry.py@@ -1,6 +1,7 @@from __future__ import annotationsimport pytest+from pydantic import ValidationError as PydanticValidationErrorfrom switch_core.bridges.collaboration.discord.adapter import (DiscordAdapter,@@ -87,7 +88,15 @@ def test_get_config_schema_exposes_required_fields() -> None:schema = service.get_config_schema("slack")- assert set(schema["properties"]) == {"bot_token", "app_token", "workspace_id"}+ # agent_usergroups is offered but not required: it needs a paid plan and an+ # admin-granted permission, so a connection stays valid without it.+ assert set(schema["properties"]) == {+ "bot_token",+ "app_token",+ "workspace_id",+ "agent_usergroups",+ "agent_sessions",+ }assert set(schema["required"]) == {"bot_token", "app_token", "workspace_id"}@@ -175,3 +184,38 @@ def test_teams_adapter_registers_with_expected_required_fields() -> None:assert "listen_host" not in schema["properties"]assert "listen_port" not in schema["properties"]assert "service_url" not in schema["properties"]+++# ── Connection config validation ─────────────────────────────────────────────+++def test_validate_connection_config_accepts_a_valid_edit() -> None:+ service = _service()+ service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)++ service.validate_connection_config(+ "slack",+ {+ "bot_token": "xoxb-1",+ "app_token": "xapp-1",+ "workspace_id": "T1",+ "agent_usergroups": True,+ },+ )+++def test_validate_connection_config_rejects_a_broken_edit() -> None:+ # Editing a connection is checked before it is stored: a config the adapter+ # cannot parse would otherwise take the bridge down at its next start, long+ # after the request that caused it.+ service = _service()+ service.register_adapter("slack", SlackAdapter, SlackConnectionConfig)++ with pytest.raises(PydanticValidationError):+ service.validate_connection_config("slack", {"bot_token": "xoxb-1"})+++def test_validate_connection_config_unknown_type_raises() -> None:+ service = _service()+ with pytest.raises(ValueError, match="Unknown bridge type"):+ service.validate_connection_config("does-not-exist", {})diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.pyindex 190d90c76..05dd58a4d 100644--- a/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py+++ b/core/tests/switch_core/bridges/collaboration/test_slack_adapter.py@@ -50,6 +50,8 @@ class _FakeWebClient:self.calls: list[dict[str, Any]] = []self.deletes: list[dict[str, Any]] = []self.updates: list[dict[str, Any]] = []+ self.reactions: list[tuple[str, str]] = []+ self.api_calls: list[tuple[str, dict[str, Any]]] = []# ts values actually handed back, in order — lets a test assert that# everything posted was also removed.self.issued: list[str] = []@@ -72,6 +74,22 @@ class _FakeWebClient:self.updates.append(kwargs)return {"ok": True}+ async def reactions_add(self, **kwargs: Any) -> dict[str, bool]:+ # The eyes that mark the message an agent is working on.+ self.reactions.append(("add", kwargs["timestamp"]))+ return {"ok": True}++ async def reactions_remove(self, **kwargs: Any) -> dict[str, bool]:+ self.reactions.append(("remove", kwargs["timestamp"]))+ return {"ok": True}++ async def api_call(self, method: str, **kwargs: Any) -> dict[str, bool]:+ # Slack's agent session status, which the pinned SDK has no typed+ # method for. Captured rather than ignored so a test can assert the+ # native status tracks the turn.+ self.api_calls.append((method, kwargs))+ return {"ok": True}+# ── Attachments ────────────────────────────────────────────────────────────diff --git a/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.py b/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.pynew file mode 100644index 000000000..88c6344e0--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_slack_agent_sessions.py@@ -0,0 +1,670 @@+"""Slack's native agent session, and the reaction that marks work in progress.++The session card replaces the status message Switch used to post: it is live,+named for the agent, and carries the link back to the session. Where a card+cannot be opened the posted message is still the fallback — so much of what+matters here is which of the two appears, and that exactly one of them does.+"""++from __future__ import annotations++import asyncio+from typing import Any++import pytest+from slack_sdk.errors import SlackApiError++from switch_core.bridges.collaboration.models import InboundCommand+from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+ SlackUser,+)++_TRACE_MARKER = "[agent-sessions]"+THREAD = "C1:111.0"+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class FakeResponse(dict):+ pass+++class FakeWebClient:+ def __init__(self) -> None:+ self.api_calls: list[tuple[str, dict[str, Any]]] = []+ self.posted: list[dict[str, Any]] = []+ self.deleted: list[dict[str, Any]] = []+ self.reactions: list[tuple[str, str, str]] = []+ self.stream_error: str | None = None+ self.reaction_error: str | None = None+ self._ts = 0++ def _fail(self) -> None:+ if self.stream_error:+ raise SlackApiError("failed", FakeResponse({"error": self.stream_error}))++ async def chat_startStream(self, **kwargs: Any) -> FakeResponse:+ self._fail()+ self.api_calls.append(("chat.startStream", kwargs))+ self._ts += 1+ return FakeResponse({"ok": True, "ts": f"stream-{self._ts}"})++ async def chat_appendStream(self, **kwargs: Any) -> FakeResponse:+ self._fail()+ self.api_calls.append(("chat.appendStream", kwargs))+ return FakeResponse({"ok": True})++ async def chat_stopStream(self, **kwargs: Any) -> FakeResponse:+ self._fail()+ self.api_calls.append(("chat.stopStream", kwargs))+ return FakeResponse({"ok": True})++ async def api_call(self, method: str, **kwargs: Any) -> FakeResponse:+ self._fail()+ self.api_calls.append((method, kwargs))+ return FakeResponse({"ok": True})++ async def reactions_add(self, **kwargs: Any) -> FakeResponse:+ if self.reaction_error:+ raise SlackApiError("no", FakeResponse({"error": self.reaction_error}))+ self.reactions.append(("add", kwargs["timestamp"], kwargs["name"]))+ return FakeResponse({"ok": True})++ async def reactions_remove(self, **kwargs: Any) -> FakeResponse:+ if self.reaction_error:+ raise SlackApiError("no", FakeResponse({"error": self.reaction_error}))+ self.reactions.append(("remove", kwargs["timestamp"], kwargs["name"]))+ return FakeResponse({"ok": True})++ async def chat_postMessage(self, **kwargs: Any) -> FakeResponse:+ self._ts += 1+ self.posted.append(kwargs)+ return FakeResponse({"ts": f"{self._ts}.0"})++ async def chat_delete(self, **kwargs: Any) -> FakeResponse:+ self.deleted.append(kwargs)+ return FakeResponse({"ok": True})++ async def chat_update(self, **kwargs: Any) -> FakeResponse:+ return FakeResponse({"ok": True})++ async def conversations_info(self, **kwargs: Any) -> FakeResponse:+ return FakeResponse({"channel": {"is_private": False}})++ async def users_info(self, **kwargs: Any) -> FakeResponse:+ return FakeResponse({"user": {"name": "someone", "profile": {}}})+++def _adapter(*, enabled: bool = True) -> tuple[SlackAdapter, FakeWebClient]:+ adapter = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test",+ app_token="xapp-test",+ workspace_id="T123",+ agent_sessions=enabled,+ )+ )+ client = FakeWebClient()+ adapter._web_client = client # type: ignore[assignment]+ adapter._channel_type_cache["C1"] = "channel"+ # Learned from auth_test at startup. On an Enterprise Grid org this is not+ # the configured workspace id, which is the org (`E…`) rather than the team.+ adapter._team_id = "T02TEAM"+ # Recorded in life from the message that started the turn.+ adapter._thread_requester[("C1", "111.0")] = "U1"+ return adapter, client+++def _methods(client: FakeWebClient) -> list[str]:+ return [method for method, _ in client.api_calls]+++def _chunks(client: FakeWebClient) -> list[dict[str, Any]]:+ return [p["chunks"][0] for m, p in client.api_calls if m == "chat.appendStream"]+++def _state(+ adapter: SlackAdapter,+ state: str,+ *,+ detail: str | None = None,+ thread: str | None = THREAD,+ deeplink: str | None = None,+) -> Any:+ return adapter.apply_runtime_state(+ "C1",+ "flint-tracker",+ state,+ mention_handle=None,+ thread_root_id=thread,+ detail=detail,+ deeplink_url=deeplink,+ )+++# ── The card replaces the posted message ─────────────────────────────────────+++def test_a_streamed_turn_posts_no_message_of_our_own() -> None:+ """One turn, one indicator. The card says everything the message did."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading the codebase"))++ assert "chat.startStream" in _methods(client)+ assert client.posted == []+++def test_an_earlier_posted_message_is_taken_down_once_a_card_exists() -> None:+ adapter, client = _adapter()+ adapter._agent_sessions_off_reason = "not_authorized"+ _run(_state(adapter, "working", detail="first"))+ assert len(client.posted) == 1++ adapter._agent_sessions_off_reason = None+ _run(_state(adapter, "working", detail="second"))++ assert len(client.deleted) == 1+++def test_without_a_card_the_posted_message_is_still_the_indicator() -> None:+ adapter, client = _adapter(enabled=False)++ _run(_state(adapter, "working", detail="reading"))++ assert client.api_calls == []+ assert len(client.posted) == 1+++def test_a_turn_with_no_thread_falls_back_to_the_posted_message() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading", thread=None))++ assert "chat.startStream" not in _methods(client)+ assert len(client.posted) == 1+++def test_a_refused_card_falls_back_to_the_posted_message() -> None:+ """Losing the card must never mean losing the turn's progress entirely."""+ adapter, client = _adapter()+ client.stream_error = "not_authorized"++ _run(_state(adapter, "working", detail="reading"))++ assert len(client.posted) == 1+ assert adapter._stream_ts == {}+++def test_the_session_status_is_never_set() -> None:+ """Setting it draws a second card under the app's own name, with Slack's+ generic wording and no way to rename it — two cards for one turn."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert "agents.sessions.setStatus" not in _methods(client)+++# ── What the card carries ────────────────────────────────────────────────────+++def test_the_card_is_opened_for_the_agent_and_the_asker() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))++ opened = next(p for m, p in client.api_calls if m == "chat.startStream")+ assert opened["thread_ts"] == "111.0"+ assert opened["recipient_user_id"] == "U1"+ assert opened["recipient_team_id"] == "T02TEAM"+ assert opened["username"] == "flint-tracker"+++def test_each_new_activity_becomes_a_step() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading the codebase"))+ _run(_state(adapter, "working", detail="running the tests"))++ assert [c["title"] for c in _chunks(client)] == [+ "reading the codebase",+ "running the tests",+ ]+++def test_the_same_activity_is_not_sent_twice() -> None:+ adapter, client = _adapter()++ for _ in range(4):+ _run(_state(adapter, "working", detail="reading the codebase"))++ assert len(_chunks(client)) == 1+++def test_switch_markup_is_stripped_from_a_step() -> None:+ """A card's title is plain text, so markup arrives as literal underscores+ and backticks — which is exactly how it looked in the pilot."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="_Running tool_ `Bash` — sleep 10"))++ assert _chunks(client)[0]["title"] == "Running tool Bash — sleep 10"+++def test_the_console_link_travels_with_the_card() -> None:+ """It used to live on the message Switch posted. With the card standing+ alone, losing it would cost the way back into the live session."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading", deeplink="https://switch/x"))++ assert _chunks(client)[0]["sources"] == [+ {"type": "url", "text": "Open in Switch Console", "url": "https://switch/x"}+ ]+++def test_no_sources_when_there_is_no_link() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))++ assert "sources" not in _chunks(client)[0]+++def test_the_card_is_closed_when_the_turn_ends() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert "chat.stopStream" in _methods(client)+ assert adapter._stream_ts == {}+++def test_a_second_turn_opens_a_fresh_card() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="first"))+ _run(_state(adapter, "idle"))+ _run(_state(adapter, "working", detail="second"))++ assert _methods(client).count("chat.startStream") == 2+++def test_no_card_without_the_team_id() -> None:+ adapter, client = _adapter()+ adapter._team_id = ""++ _run(_state(adapter, "working", detail="reading"))++ assert "chat.startStream" not in _methods(client)+++def test_no_card_without_someone_to_stream_to() -> None:+ adapter, client = _adapter()+ adapter._thread_requester.clear()++ _run(_state(adapter, "working", detail="reading"))++ assert "chat.startStream" not in _methods(client)+++# ── The eyes on the message being worked on ──────────────────────────────────+++def test_the_message_being_worked_on_gets_the_eyes() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))++ assert ("add", "111.0", "eyes") in client.reactions+++def test_the_eyes_come_off_when_the_turn_ends() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert ("remove", "111.0", "eyes") in client.reactions+++def test_the_eyes_are_added_once_for_a_turn() -> None:+ adapter, client = _adapter()++ for _ in range(5):+ _run(_state(adapter, "working", detail="reading"))++ assert [r for r in client.reactions if r[0] == "add"] == [("add", "111.0", "eyes")]+++def test_the_eyes_work_without_a_session() -> None:+ """The one progress signal needing nothing from Slack beyond a scope we+ already hold — so it must not be tied to the card."""+ adapter, client = _adapter(enabled=False)++ _run(_state(adapter, "working", detail="reading"))++ assert ("add", "111.0", "eyes") in client.reactions+++def test_an_already_present_reaction_is_not_an_error(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, client = _adapter()+ client.reaction_error = "already_reacted"++ with caplog.at_level("WARNING"):+ _run(_state(adapter, "working", detail="reading"))++ assert [r for r in caplog.records if "working reaction" in r.getMessage()] == []+ assert ("C1", "111.0") in adapter._eyes+++# ── Refusals ─────────────────────────────────────────────────────────────────+++ "error,expected",+ [+ ("not_authorized", "not a member of that channel"),+ ("missing_scope", "assistant:write"),+ ("feature_disabled", "not enabled for this Slack workspace"),+ ("unknown_method", "does not offer"),+ ],+)+def test_a_refusal_is_reported_once_and_not_retried(+ error: str, expected: str, caplog: pytest.LogCaptureFixture+) -> None:+ adapter, client = _adapter()+ client.stream_error = error++ with caplog.at_level("WARNING"):+ for _ in range(3):+ _run(_state(adapter, "working", detail="reading"))++ warnings = [r for r in caplog.records if r.levelname == "WARNING"]+ assert len(warnings) == 1+ assert expected in warnings[0].getMessage()+++def test_an_unknown_refusal_gives_up_rather_than_warning_forever(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, client = _adapter()+ client.stream_error = "some_code_we_have_never_seen"++ with caplog.at_level("WARNING"):+ for _ in range(3):+ _run(_state(adapter, "working", detail="reading"))+ settled = len([r for r in caplog.records if r.levelname == "WARNING"])+ for _ in range(5):+ _run(_state(adapter, "working", detail="reading"))++ assert adapter._agent_sessions_off_reason == "some_code_we_have_never_seen"+ assert len([r for r in caplog.records if r.levelname == "WARNING"]) == settled+++def test_a_given_up_session_says_nothing_further(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, _ = _adapter()+ adapter._agent_sessions_off_reason = "not_authorized"++ with caplog.at_level("DEBUG"):+ for _ in range(20):+ _run(_state(adapter, "working", detail="reading"))++ assert [r for r in caplog.records if _TRACE_MARKER in r.getMessage()] == []+++def test_a_threadless_agent_is_only_reported_once(+ caplog: pytest.LogCaptureFixture,+) -> None:+ adapter, _ = _adapter()++ with caplog.at_level("DEBUG"):+ for _ in range(20):+ _run(_state(adapter, "working", detail="reading", thread=None))++ assert len([r for r in caplog.records if "no thread for" in r.getMessage()]) == 1+++# ── The stop button ──────────────────────────────────────────────────────────+++def test_stop_interrupts_the_agent_whose_turn_it_is() -> None:+ adapter, _ = _adapter()+ commands: list[InboundCommand] = []++ async def on_command(cmd: InboundCommand) -> None:+ commands.append(cmd)++ adapter._on_command = on_command # type: ignore[assignment]+ adapter._user_cache["U1"] = SlackUser(name="louis", display_name="Louis")++ _run(_state(adapter, "working", detail="reading"))+ _run(+ adapter._handle_session_stopped(+ {"channel_id": "C1", "thread_ts": "111.0", "user_id": "U1"}+ )+ )++ assert len(commands) == 1+ assert commands[0].command == "interrupt"+ assert commands[0].args == "@flint-tracker"+++def test_a_finished_turn_no_longer_answers_the_stop_button() -> None:+ adapter, _ = _adapter()+ commands: list[InboundCommand] = []++ async def on_command(cmd: InboundCommand) -> None:+ commands.append(cmd)++ adapter._on_command = on_command # type: ignore[assignment]++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))+ _run(+ adapter._handle_session_stopped(+ {"channel_id": "C1", "thread_ts": "111.0", "user_id": "U1"}+ )+ )++ assert commands == []+++def test_the_requester_is_recorded_from_an_incoming_message() -> None:+ adapter, _ = _adapter()+ adapter._thread_requester.clear()+ adapter._bot_user_id = "UBOT"++ _run(+ adapter._handle_message_event(+ {+ "channel": "C1",+ "ts": "333.0",+ "user": "U9",+ "text": "hi",+ "channel_type": "channel",+ }+ )+ )++ assert adapter._thread_requester[("C1", "333.0")] == "U9"+++# ── Two messages at once ─────────────────────────────────────────────────────+++def _thread_b(adapter: SlackAdapter) -> None:+ adapter._thread_requester[("C1", "222.0")] = "U1"+++def test_both_messages_lose_their_eyes_when_the_turn_ends() -> None:+ """A turn ends once, naming only the thread it last touched. The first+ message kept its eyes for good until this was tracked per agent."""+ adapter, client = _adapter()+ _thread_b(adapter)++ _run(_state(adapter, "working", detail="first", thread="C1:111.0"))+ _run(_state(adapter, "working", detail="second", thread="C1:222.0"))+ _run(_state(adapter, "idle", thread="C1:222.0"))++ removed = {ts for kind, ts, _ in client.reactions if kind == "remove"}+ assert removed == {"111.0", "222.0"}+++def test_both_cards_are_closed_when_the_turn_ends() -> None:+ adapter, client = _adapter()+ _thread_b(adapter)++ _run(_state(adapter, "working", detail="first", thread="C1:111.0"))+ _run(_state(adapter, "working", detail="second", thread="C1:222.0"))+ _run(_state(adapter, "idle", thread="C1:222.0"))++ stopped = {p["ts"] for m, p in client.api_calls if m == "chat.stopStream"}+ assert len(stopped) == 2+ assert adapter._stream_ts == {}+++def test_a_stop_on_either_thread_stops_answering_after_the_turn() -> None:+ adapter, _ = _adapter()+ _thread_b(adapter)++ _run(_state(adapter, "working", detail="first", thread="C1:111.0"))+ _run(_state(adapter, "working", detail="second", thread="C1:222.0"))+ _run(_state(adapter, "idle", thread="C1:222.0"))++ assert adapter._session_owner == {}+++# ── The card's own end state ─────────────────────────────────────────────────+++def test_the_last_step_is_marked_done_before_the_card_closes() -> None:+ """Slack draws a step left in progress as a failure — every finished turn+ was ending under a red error icon."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert [c["status"] for c in _chunks(client)] == ["in_progress", "complete"]+ # And the completion lands before the stream is closed, not after.+ methods = _methods(client)+ assert methods.index("chat.appendStream") < methods.index("chat.stopStream")+++def test_a_card_with_no_step_is_just_closed() -> None:+ adapter, client = _adapter()+ adapter._stream_ts[("C1", "111.0")] = "stream-1"++ _run(_state(adapter, "idle"))++ assert _chunks(client) == []+++def test_the_console_link_is_sent_once_per_card() -> None:+ """Slack accumulates a task's sources rather than replacing them, so+ sending the link every step stacked eight identical links under one card."""+ adapter, client = _adapter()++ for detail in ("reading", "running tests", "writing"):+ _run(_state(adapter, "working", detail=detail, deeplink="https://switch/x"))++ with_sources = [c for c in _chunks(client) if "sources" in c]+ assert len(with_sources) == 1+++# ── Nothing left behind ──────────────────────────────────────────────────────+++def test_the_card_is_deleted_when_the_turn_ends() -> None:+ """It is a progress indicator, not a record — once the turn is over the+ agent's own reply is the thing worth reading."""+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert [d["ts"] for d in client.deleted] == ["stream-1"]+++def test_every_card_is_deleted_when_two_were_open() -> None:+ adapter, client = _adapter()+ adapter._thread_requester[("C1", "222.0")] = "U1"++ _run(_state(adapter, "working", detail="first", thread="C1:111.0"))+ _run(_state(adapter, "working", detail="second", thread="C1:222.0"))+ _run(_state(adapter, "idle", thread="C1:222.0"))++ assert sorted(d["ts"] for d in client.deleted) == ["stream-1", "stream-2"]+++# ── Which message gets the eyes ──────────────────────────────────────────────+++def test_the_eyes_go_on_the_message_that_asked_not_the_thread_root() -> None:+ """Inside a thread the question is a reply. Marking the root says the+ conversation is busy; marking the reply says which request is being run."""+ adapter, client = _adapter()+ adapter._bot_user_id = "UBOT"++ _run(+ adapter._handle_message_event(+ {+ "channel": "C1",+ "ts": "555.0",+ "thread_ts": "111.0",+ "user": "U1",+ "text": "hi",+ "channel_type": "channel",+ }+ )+ )+ _run(_state(adapter, "working", detail="reading"))++ assert ("add", "555.0", "eyes") in client.reactions+ assert not any(ts == "111.0" for _, ts, _ in client.reactions)+++def test_the_eyes_come_off_the_message_that_asked() -> None:+ adapter, client = _adapter()+ adapter._bot_user_id = "UBOT"++ _run(+ adapter._handle_message_event(+ {+ "channel": "C1",+ "ts": "555.0",+ "thread_ts": "111.0",+ "user": "U1",+ "text": "hi",+ "channel_type": "channel",+ }+ )+ )+ _run(_state(adapter, "working", detail="reading"))+ _run(_state(adapter, "idle"))++ assert ("remove", "555.0", "eyes") in client.reactions+++def test_a_root_question_is_marked_on_itself() -> None:+ adapter, client = _adapter()++ _run(_state(adapter, "working", detail="reading"))++ assert ("add", "111.0", "eyes") in client.reactionsdiff --git a/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.pynew file mode 100644index 000000000..602845865--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_slack_agent_usergroups.py@@ -0,0 +1,575 @@+"""Per-agent Slack user groups — the handle that makes an agent name complete.++An agent is not a Slack user, so Slack's `@` menu cannot offer it. Minting a+user group per agent is what puts the name in that menu; these tests cover the+round trip (group id in, agent name out), the lifecycle, and the refusals that+must stay loud rather than leaving an agent silently unmentionable.+"""++from __future__ import annotations++import asyncio+from typing import Any++import pytest+from slack_sdk.errors import SlackApiError++from switch_core.bridges.collaboration.slack.adapter import (+ SlackAdapter,+ SlackConnectionConfig,+)+++def _run(coro: Any) -> Any:+ loop = asyncio.new_event_loop()+ try:+ return loop.run_until_complete(coro)+ finally:+ loop.close()+++class FakeResponse(dict):+ """Stands in for a slack_sdk response, which is dict-like."""+++class FakeWebClient:+ def __init__(self, groups: list[dict[str, Any]] | None = None) -> None:+ self.groups = groups or []+ self.created: list[dict[str, Any]] = []+ self.disabled: list[str] = []+ self.enabled: list[str] = []+ self.list_calls = 0+ self.create_error: str | None = None+ self.list_error: str | None = None+ # Clear create_error after this many failures, to model a transient+ # condition (throttling) rather than a permanent one.+ self.clear_error_after: int | None = None+ self.create_attempts = 0+ self.updated: list[tuple[str, str]] = []+ self.update_error: str | None = None++ async def usergroups_list(self, **kwargs: Any) -> FakeResponse:+ self.list_calls += 1+ if self.list_error:+ raise SlackApiError("list failed", FakeResponse({"error": self.list_error}))+ return FakeResponse({"usergroups": self.groups})++ async def usergroups_create(self, **kwargs: Any) -> FakeResponse:+ self.create_attempts += 1+ if (+ self.clear_error_after is not None+ and self.create_attempts > self.clear_error_after+ ):+ self.create_error = None+ if self.create_error:+ raise SlackApiError(+ "create failed", FakeResponse({"error": self.create_error})+ )+ self.created.append(kwargs)+ group = {+ "id": f"S{len(self.created):03d}",+ "name": kwargs["name"],+ "handle": kwargs["handle"],+ "description": kwargs["description"],+ }+ self.groups.append(group)+ return FakeResponse({"usergroup": group})++ async def usergroups_disable(self, *, usergroup: str) -> FakeResponse:+ self.disabled.append(usergroup)+ return FakeResponse({"ok": True})++ async def usergroups_enable(self, *, usergroup: str) -> FakeResponse:+ self.enabled.append(usergroup)+ return FakeResponse({"ok": True})++ async def usergroups_update(+ self, *, usergroup: str, description: str+ ) -> FakeResponse:+ if self.update_error:+ raise SlackApiError(+ "update failed", FakeResponse({"error": self.update_error})+ )+ self.updated.append((usergroup, description))+ return FakeResponse({"ok": True})+++def _adapter(+ *, enabled: bool = True, groups: list[dict[str, Any]] | None = None+) -> tuple[SlackAdapter, FakeWebClient]:+ adapter = SlackAdapter(+ config=SlackConnectionConfig(+ bot_token="xoxb-test",+ app_token="xapp-test",+ workspace_id="T123",+ agent_usergroups=enabled,+ )+ )+ client = FakeWebClient(groups)+ adapter._web_client = client # type: ignore[assignment]+ return adapter, client+++def _agent_group(group_id: str, name: str, *, disabled: bool = False) -> dict[str, Any]:+ group = {+ "id": group_id,+ "name": name,+ "handle": name.lower(),+ "description": f"Switch agent — {name} does things",+ }+ if disabled:+ group["date_delete"] = 1700000000+ return group+++# ── Provisioning ─────────────────────────────────────────────────────────────+++def test_creates_a_group_for_a_new_agent() -> None:+ adapter, client = _adapter()++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert len(client.created) == 1+ created = client.created[0]+ assert created["name"] == "flint-tracker"+ assert created["handle"] == "flint-tracker"+ assert created["description"].startswith("Switch agent — ")+++def test_does_nothing_when_the_feature_is_off() -> None:+ adapter, client = _adapter(enabled=False)++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.created == []+ assert client.list_calls == 0+++def test_provisioning_is_idempotent_for_an_existing_agent() -> None:+ adapter, client = _adapter(groups=[_agent_group("S001", "flint-tracker")])++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.created == []+++def test_readding_an_agent_reenables_its_disabled_group() -> None:+ """Slack has no delete for user groups, so a removed agent's group is only+ disabled. Re-adding it must revive that group rather than collide with it."""+ adapter, client = _adapter(+ groups=[_agent_group("S001", "flint-tracker", disabled=True)]+ )++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.enabled == ["S001"]+ assert client.created == []+ assert adapter._agent_group_ids["flint-tracker"] == "S001"+++def test_removing_an_agent_disables_its_group() -> None:+ adapter, client = _adapter(groups=[_agent_group("S001", "flint-tracker")])++ _run(adapter.remove_agent_identity("flint-tracker"))++ assert client.disabled == ["S001"]+ assert "flint-tracker" not in adapter._agent_group_ids+++def test_workspace_groups_are_not_mistaken_for_agents() -> None:+ """A workspace's own group must never resolve to an agent — mentioning+ @designers would otherwise address whatever agent shared its name."""+ adapter, _ = _adapter(+ groups=[+ {+ "id": "S999",+ "name": "designers",+ "handle": "designers",+ "description": "The design team",+ }+ ]+ )++ _run(adapter._load_agent_usergroups())++ assert adapter._agent_group_ids == {}+ # It renders as its own handle rather than raw markup, but as the group's+ # handle — never as an agent, which is what would misroute a message.+ assert adapter._translate_usergroup_mentions("<!subteam^S999>") == "@designers"+++def test_an_unusual_agent_name_still_yields_a_legal_handle() -> None:+ adapter, client = _adapter()++ _run(adapter.create_agent_identity("Flint Tracker!", "Tracks flint"))++ assert client.created[0]["handle"] == "flint-tracker"+ # The group's name keeps the agent name verbatim, so the mention still+ # resolves back to the agent even though the handle had to be folded.+ assert client.created[0]["name"] == "Flint Tracker!"+++# ── A workspace that cannot host user groups ─────────────────────────────────+++ "error,expected",+ [+ ("permission_denied", "restricts managing user groups to admins"),+ ("no_permission", "restricts managing user groups to admins"),+ ("plan_upgrade_required", "paid Slack plan"),+ ("paid_teams_only", "paid Slack plan"),+ ("missing_scope", "usergroups:read"),+ ],+)+def test_a_workspace_refusal_is_reported_once_and_not_retried(+ error: str, expected: str, caplog: pytest.LogCaptureFixture+) -> None:+ """The setting is on by default, so a workspace that simply cannot host user+ groups is ordinary — but it must say so, and only once, rather than+ complaining per agent on every startup."""+ adapter, client = _adapter()+ client.create_error = error++ with caplog.at_level("WARNING"):+ _run(adapter.create_agent_identity("agent-one", "One"))+ _run(adapter.create_agent_identity("agent-two", "Two"))++ warnings = [r for r in caplog.records if r.levelname == "WARNING"]+ assert len(warnings) == 1+ message = warnings[0].getMessage()+ assert expected in message+ # The consequence, not just the cause: someone reading the log should know+ # what stopped working and that agents still answer to a typed name.+ assert "autocomplete" in message+ assert "addressable" in message+++def test_a_refusal_stops_further_slack_calls() -> None:+ adapter, client = _adapter()+ client.create_error = "plan_upgrade_required"++ _run(adapter.create_agent_identity("agent-one", "One"))+ calls_after_first = len(client.created) + client.list_calls+ _run(adapter.create_agent_identity("agent-two", "Two"))++ assert len(client.created) + client.list_calls == calls_after_first+++def test_a_refusal_on_listing_disables_it_too() -> None:+ """A free workspace fails at the very first call — listing — so that path+ has to give up the same way rather than raising past the caller."""+ adapter, client = _adapter()+ client.list_error = "plan_upgrade_required"++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.created == []+ assert adapter._agent_usergroups_off_reason == "plan_upgrade_required"+++def test_an_unexpected_slack_error_still_propagates() -> None:+ """Only the refusals that mean 'this workspace cannot' are swallowed; a+ genuine fault must still reach the caller."""+ adapter, client = _adapter()+ client.create_error = "internal_error"++ with pytest.raises(SlackApiError):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+++def test_a_handle_taken_by_someone_else_raises() -> None:+ adapter, client = _adapter()+ client.create_error = "handle_already_exists"++ with pytest.raises(RuntimeError, match="already taken"):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+++def test_a_handle_taken_by_our_own_group_is_adopted() -> None:+ """A create can lose a race with our own earlier one; adopting the existing+ group is correct, and must not be reported as a collision."""+ adapter, client = _adapter()+ client.create_error = "handle_already_exists"+ client.groups = [_agent_group("S001", "flint-tracker")]++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert adapter._agent_group_ids["flint-tracker"] == "S001"+++# ── Translation ──────────────────────────────────────────────────────────────+++def test_inbound_group_mention_becomes_the_agent_name() -> None:+ adapter, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(adapter._load_agent_usergroups())++ assert (+ adapter.translate_inbound("<!subteam^S001> please run the summary")+ == "@flint-tracker please run the summary"+ )+++def test_inbound_group_mention_with_a_handle_label() -> None:+ adapter, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(adapter._load_agent_usergroups())++ assert (+ adapter.translate_inbound("<!subteam^S001|@flint-tracker> hi")+ == "@flint-tracker hi"+ )+++def test_inbound_resolves_to_the_agent_name_not_the_handle() -> None:+ """The handle may have been folded to be legal; addressing downstream+ matches on the agent's real name, so that is what must come out."""+ adapter, _ = _adapter(+ groups=[+ {+ "id": "S001",+ "name": "Flint.Tracker",+ "handle": "flint-tracker",+ "description": "Switch agent — tracks flint",+ }+ ]+ )+ _run(adapter._load_agent_usergroups())++ assert adapter.translate_inbound("<!subteam^S001> hi") == "@Flint.Tracker hi"+++def test_unknown_group_mention_falls_back_to_its_label() -> None:+ adapter, _ = _adapter()++ assert (+ adapter._translate_usergroup_mentions("<!subteam^S999|@designers> ping")+ == "@designers ping"+ )+++def test_outbound_agent_mention_renders_as_a_group_pill() -> None:+ adapter, _ = _adapter(groups=[_agent_group("S001", "flint-tracker")])+ _run(adapter._load_agent_usergroups())++ assert (+ adapter._translate_mentions_to_slack("hey @flint-tracker")+ == "hey <!subteam^S001>"+ )+++def test_outbound_leaves_unknown_names_alone() -> None:+ adapter, _ = _adapter()++ assert adapter._translate_mentions_to_slack("hey @nobody") == "hey @nobody"+++def test_outbound_prefers_a_real_person_over_an_agent_group() -> None:+ adapter, _ = _adapter(groups=[_agent_group("S001", "ambiguous")])+ _run(adapter._load_agent_usergroups())+ adapter.prime_mention_targets({"ambiguous": "U123"})++ assert adapter._translate_mentions_to_slack("@ambiguous") == "<@U123>"+++# ── Rate limiting ────────────────────────────────────────────────────────────+++def test_a_rate_limited_create_is_retried_rather_than_lost(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Provisioning runs once per agent at startup and the allowance is about+ 20/minute, so a workspace with more agents than that would otherwise come up+ with some mentionable and some not — and the caller only logs."""+ slept: list[float] = []++ async def _no_sleep(seconds: float) -> None:+ slept.append(seconds)++ monkeypatch.setattr(+ "switch_core.bridges.collaboration.slack.adapter.asyncio.sleep", _no_sleep+ )++ adapter, client = _adapter()+ client.create_error = "ratelimited"+ client.clear_error_after = 2++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert len(client.created) == 1+ assert len(slept) == 2+ assert adapter._agent_group_ids["flint-tracker"]+++def test_persistent_rate_limiting_says_provisioning_is_incomplete(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def _no_sleep(seconds: float) -> None:+ return None++ monkeypatch.setattr(+ "switch_core.bridges.collaboration.slack.adapter.asyncio.sleep", _no_sleep+ )++ adapter, client = _adapter()+ client.create_error = "ratelimited"++ with pytest.raises(RuntimeError, match="restart the bridge"):+ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))+++def test_rate_limiting_does_not_disable_the_feature() -> None:+ """Throttling is temporary; it must not be mistaken for a workspace that+ cannot host user groups at all."""+ adapter, _ = _adapter()++ assert adapter._agent_usergroups_off_reason is None+++# ── Groups created by hand ───────────────────────────────────────────────────+++def _plain_group(group_id: str, handle: str, name: str) -> dict[str, Any]:+ """A group with no marker — what an admin creating one by hand produces."""+ return {+ "id": group_id,+ "name": name,+ "handle": handle,+ "description": "",+ }+++def test_a_hand_made_group_is_adopted_by_handle() -> None:+ """Where a workspace will not let the bot create groups, making them by hand+ is the only way to use the feature, so an exact handle match is claimed."""+ adapter, client = _adapter(+ groups=[_plain_group("S0BRK25CG86", "switch-usecase-builder", "Use case bot")]+ )++ _run(adapter.create_agent_identity("switch-usecase-builder", "Builds use cases"))++ assert client.created == []+ assert adapter._agent_group_ids["switch-usecase-builder"] == "S0BRK25CG86"+ assert adapter._agent_group_names["S0BRK25CG86"] == "switch-usecase-builder"+++def test_a_hand_made_group_is_adopted_by_name() -> None:+ adapter, client = _adapter(+ groups=[_plain_group("S001", "some-other-handle", "flint-tracker")]+ )++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.created == []+ assert adapter._agent_group_ids["flint-tracker"] == "S001"+++def test_adoption_stamps_the_marker_so_it_is_recognised_later() -> None:+ adapter, client = _adapter(+ groups=[_plain_group("S001", "flint-tracker", "flint-tracker")]+ )++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert client.updated == [("S001", "Switch agent — flint-tracker")]+++def test_adoption_survives_a_failed_marker_write() -> None:+ """Marking is an optimisation — adoption happens per agent at startup+ regardless — so losing the write must not lose the adoption."""+ adapter, client = _adapter(+ groups=[_plain_group("S001", "flint-tracker", "flint-tracker")]+ )+ client.update_error = "permission_denied"++ _run(adapter.create_agent_identity("flint-tracker", "Tracks flint"))++ assert adapter._agent_group_ids["flint-tracker"] == "S001"+++def test_a_hand_made_group_resolves_to_the_agent_after_adoption() -> None:+ adapter, _ = _adapter(+ groups=[_plain_group("S0BRK25CG86", "switch-usecase-builder", "Use case bot")]+ )++ _run(adapter.create_agent_identity("switch-usecase-builder", "Builds use cases"))++ assert (+ adapter.translate_inbound("<!subteam^S0BRK25CG86> hi there")+ == "@switch-usecase-builder hi there"+ )+++def test_a_similar_name_does_not_capture_a_workspace_group() -> None:+ """Adoption matches exactly; anything looser would let an agent capture a+ real group and silently swallow messages meant for people."""+ adapter, client = _adapter(groups=[_plain_group("S999", "designers", "Designers")])++ _run(adapter.create_agent_identity("designer", "Not the design team"))++ assert adapter._agent_group_ids.get("designer") != "S999"+ assert len(client.created) == 1+++def test_an_unknown_group_renders_as_its_handle_not_raw_markup() -> None:+ """The bug behind the pilot report: a bare tag reached Matrix verbatim."""+ adapter, _ = _adapter(groups=[_plain_group("S999", "designers", "Designers")])+ _run(adapter._load_agent_usergroups())++ assert adapter.translate_inbound("<!subteam^S999> ping") == "@designers ping"+++def test_a_group_we_have_never_seen_is_left_alone() -> None:+ adapter, _ = _adapter()++ assert (+ adapter._translate_usergroup_mentions("<!subteam^SNEVER>")+ == "<!subteam^SNEVER>"+ )+++# ── Long descriptions ────────────────────────────────────────────────────────+++def test_a_long_description_is_truncated_but_keeps_the_marker() -> None:+ adapter, client = _adapter()++ _run(adapter.create_agent_identity("flint-tracker", "x" * 500))++ description = client.created[0]["description"]+ assert description.startswith("Switch agent — ")+ assert len(description) <= 140+++def test_a_rejected_description_falls_back_to_the_marker() -> None:+ """Slack does not publish the limit, so a conservative truncation can still+ be refused. Losing the agent's autocomplete over its blurb would be absurd —+ the blurb is what gets dropped."""+ adapter, client = _adapter()+ client.create_error = "description_too_long"+ client.clear_error_after = 1++ _run(adapter.create_agent_identity("flint-tracker", "a long blurb"))++ assert len(client.created) == 1+ assert client.created[0]["description"] == "Switch agent — flint-tracker"+ assert adapter._agent_group_ids["flint-tracker"]+++def test_a_marker_only_group_is_still_recognised_on_reload() -> None:+ """The fallback description must not cost us recognition later."""+ adapter, _ = _adapter(+ groups=[+ {+ "id": "S001",+ "name": "flint-tracker",+ "handle": "flint-tracker",+ "description": "Switch agent — flint-tracker",+ }+ ]+ )++ _run(adapter._load_agent_usergroups())++ assert adapter._agent_group_names["S001"] == "flint-tracker"diff --git a/docs/bridges/SLACK_SETUP.md b/docs/bridges/SLACK_SETUP.mdindex abcce2e80..bafd563c1 100644--- a/docs/bridges/SLACK_SETUP.md+++ b/docs/bridges/SLACK_SETUP.md@@ -45,6 +45,9 @@ You need one Slack app for the whole bridge. There are two ways to create it —"display_name": "Agent Switch","always_online": false},+ "agent_view": {+ "agent_description": "Switch agents. Mention one by name in a channel and it answers there; its progress appears on the message while it works."+ },"slash_commands": [{ "command": "/admin", "description": "Toggle admin mode on/off for this room", "should_escape": false },{ "command": "/help", "description": "Show the list of available in-room commands", "should_escape": false },@@ -90,7 +93,9 @@ You need one Slack app for the whole bridge. There are two ways to create it —"mpim:history","reactions:read","reactions:write",- "users:read"+ "users:read",+ "usergroups:read",+ "usergroups:write"]},"pkce_enabled": false@@ -180,8 +185,172 @@ Under **OAuth & Permissions → Scopes → Bot Token Scopes**:- `im:read`, `im:write` — direct messages.- `users:read` — resolve user display names.- `files:read`, `files:write` — relay attachments (incl. agent image uploads).-- `reactions:read`, `reactions:write` — reaction-based acknowledgements.-- `assistant:write` — assistant/app-home surface.+- `reactions:read`, `reactions:write` — reaction-based acknowledgements, and+ the 👀 that marks the message an agent is working on.+- `assistant:write` — declares the app an Agent, which is what lets it open the+ session its progress card lives in. Slack adds this scope itself when the+ Agents feature is switched on.+- `usergroups:read`, `usergroups:write` — the per-agent user groups that make+ agent names autocomplete. See below.++### Declaring the app an Agent (`agent_view`)++The manifest's `features.agent_view` is what makes the app an **Agent**, and+only an Agent app may open the sessions the progress card is drawn in. Without+it, the calls are refused and turns fall back to a status message Switch posts+itself — everything still works, it just looks like a bot rather than part of+Slack.++⚠️ **Two consequences, and neither can be walked back.** Enabling the Agents+feature **removes access to the app for workspace guests**, and turns every DM+with it into a thread. The switch from the older `assistant_view` to+`agent_view` is **irreversible**, and a distributed app needs re-review. Decide+deliberately; a workspace with external collaborators as guests loses them.++On the from-scratch path this is the **Agents** toggle in the app's settings+rather than a scope you tick.++### Agent name autocomplete (`agent_usergroups`)++**On by default.** Every agent gets a Slack **user group** whose handle is its+name. Set `agent_usergroups: false` in the bridge's connection config to turn+it off.++This is a workaround and worth naming as one: Slack offers no way to make an+app's agents mentionable, so Switch borrows the one mentionable object an app+can create and uses it as a name. Turning `agent_usergroups` off is a+reasonable choice for a workspace that does not want a group per agent.++Slack autocompletes only things it knows about, and an agent is not a Slack+user — one app serves all of them, so a typed `@agent-name` is just text that+happens to start with `@`. There is no completion, no pill, and a typo is+indistinguishable from an agent ignoring you. A user group is the one handle an+app can mint that still appears in the composer's `@` menu, so each agent gets+one and its name completes like a person's.++The groups are created empty and stay empty: they exist to be completable, and+mentioning one notifies nobody. Switch recognises its own groups by a marker on+their description and ignores the workspace's own.++**Groups made by hand are adopted.** Where a workspace will not let the bot+create them, making them manually is the only way to use the feature — so a+group whose **handle or name is exactly an agent's name** is taken to be that+agent's, and the marker is stamped on it. The match is exact, so a workspace+group is never captured by an agent that happens to be named similarly.++Two things gate it, both outside Switch:++- **A paid plan.** User groups do not exist on Slack's free tier.+- **Permission to manage user groups.** Most workspaces restrict this to admins,+ and the bot token is refused until an admin widens it under+ *Workspace settings → Roles & permissions → Account types → "Create and edit+ user groups"*.++A workspace missing either is a normal case, not a misconfiguration: the bridge+logs **one** warning naming the cause and what it costs, then runs without user+groups. Agents stay addressable by typing their name, exactly as before — you+lose the autocomplete, nothing else. It does not retry per agent or repeat the+warning on every startup.++### Native session status (`agent_sessions`)++**On by default.** A turn opens a Slack **agent session** and streams its+progress into the client's own live card, under the agent's name and icon,+carrying the link back to the session in Switch Console.++**The card replaces the status message Switch used to post**, rather than+sitting beside it — two indicators for one turn said the same thing twice.+Where a card cannot be opened, the posted message is still the fallback, so a+turn always shows its progress somewhere.++A session exists because a **stream** is opened for it — setting a session's+status without one is accepted by Slack and renders nothing at all. So each+turn opens a stream, pushes a step whenever the agent's activity changes, and+closes it at the end.++Switch does **not** set the session *status*. It renders as a second card+attributed to the app rather than the agent, with Slack's own generic wording+and no way to rename it. Slack's native stop button hangs off that status, so+it is not offered either.++Streaming into a channel has to name the person being replied to and their+team. The person comes from the message that started the thread; the team from+the app's own identity, which on an Enterprise Grid org is **not** the+configured workspace id (that is the org). A thread Switch never saw a question+on gets no card, and falls back to the posted message.++The card is a progress indicator, not a record: it is removed when the turn+ends, the way the posted status message always was. An agent working on two+messages at once has a card and a mark on each, and both are cleared together+when its turn finishes.++Separately, and needing nothing but the reaction scopes: the message that asked+is marked with **👀** for the duration of the turn — the message itself, not the+thread it sits in. That works at the channel root as well as in a thread, so it+is the one progress signal that is always available.++The stop button is wired to the same interrupt an operator can type, so+pressing it stops the agent whose turn it is. Setting `agent_sessions: false`+turns the whole thing off.++**Sessions only work if the Slack app is declared an Agent** (the Agents+feature in the app's settings, which brings `assistant:write` with it). The+default being on only means "use this where the app has it" — it does not make+that change for you. Until it is made, the first call is refused, the bridge+logs one warning naming the reason, and turns carry on showing Switch's own+status messages.++Think before enabling the Agents feature in Slack: it **removes access to the+app for workspace guests**, turns every DM with it into a thread, and **cannot+be reverted**.++### Running without a paid Slack plan++Two of the features above lean on things a Slack workspace may not have, and+each has its own switch on the bridge connection. Both default to on.++- **`agent_usergroups`** needs a **paid plan** — user groups do not exist on the+ free tier — and an admin willing to let the bot manage them.+- **`agent_sessions`** needs the app to be declared an **Agent**. Slack+ documents that some AI features require a paid plan without saying which, so+ treat the plan question there as answered by trying it: a refusal names its+ own cause.++**Neither has to be switched off to be safe.** A refusal is caught, reported+once with what would fix it, and the feature is dropped for the life of the+process — it is not retried per turn and nothing else is affected. Setting them+to `false` on a workspace that cannot host them simply skips the attempt and+the warning.++What a workspace still gets with both off:++- Agents are addressed by typing `@agent-name`, exactly as before. What is lost+ is the autocomplete, not the addressing.+- An agent's progress appears as a status message posted under its own name and+ icon, carrying the **Open in Switch Console** link.+- The message being worked on is marked with **👀** for the turn. That needs+ only the reaction scopes, so it works on any plan and in any channel.++### Turning it on for an existing bridge++`PATCH /collaborations/{bridge_id}` accepts `connection_config`, merged over the+stored one — so you change a setting without re-sending the platform's tokens:++```json+{ "connection_config": { "agent_usergroups": true } }+```++The bridge restarts to pick it up, and provisioning at startup covers every+agent that already exists. There is no separate migration step.++Provisioning runs **in the background**: it is one Slack call per agent against+a rate limit of roughly 20/minute, so a few hundred agents take minutes. The+bridge is online and relaying throughout, and agents stay addressable by typed+name while their groups are still being made — autocomplete is what arrives+late, nothing else. Watch the per-group log lines for progress.++The session's own trace lines are at debug level: enough to follow a turn end+to end when something does not render, and out of the way when it does.### Event subscriptions (over Socket Mode)diff --git a/gateway/src/pages/agents/optionFields.tsx b/gateway/src/pages/agents/optionFields.tsxindex 3ead575c4..b2d24f932 100644--- a/gateway/src/pages/agents/optionFields.tsx+++ b/gateway/src/pages/agents/optionFields.tsx@@ -63,12 +63,22 @@ function humanizeKey(key: string): string {return key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());}+/** Whether a value satisfies a required field. A blank string does not; `false`+ * does — it is an answer, not an omission. */+export function isProvided(value: unknown): boolean {+ if (typeof value === "string") return value.trim().length > 0;+ return value !== undefined && value !== null;+}+export function renderOptionFields(schema: Record<string, unknown> | undefined,values: Record<string, unknown>,setValues: (update: (prev: Record<string, unknown>) => Record<string, unknown>,) => void,+ // Marks a field with the usual asterisk. Optional because agent options have+ // no required fields; a bridge connection's credentials do.+ requiredFields: string[] = [],) {const obj = asSchemaObject(schema);if (!obj?.properties) return null;@@ -122,6 +132,7 @@ export function renderOptionFields(setValues((prev) => ({ ...prev, [key]: e.target.value }))}fullWidth+ required={requiredFields.includes(key)}helperText={prop.description}/>);diff --git a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsxindex ad58cd5de..28de38081 100644--- a/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx+++ b/gateway/src/pages/collaborations/RegisterMessagingAppDialog.tsx@@ -16,7 +16,11 @@ import {import { useCallback, useMemo, useState } from "react";import { type BridgeDetail, createBridge } from "../../data/api";import { useBridgeTypes } from "../../data/hooks";-import { isSecretField } from "../agents/optionFields";+import {+ extractDefaults,+ isProvided,+ renderOptionFields,+} from "../agents/optionFields";interface Props {open: boolean;@@ -36,7 +40,9 @@ export default function RegisterMessagingAppDialog({const { data: bridgeTypes } = useBridgeTypes();const [selectedType, setSelectedType] = useState("");const [displayName, setDisplayName] = useState("");- const [config, setConfig] = useState<Record<string, string>>({});+ // Values are typed by the schema, not all strings: a boolean field must post+ // a real boolean, since the backend rejects "" as one.+ const [config, setConfig] = useState<Record<string, unknown>>({});const [channelCreationEnabled, setChannelCreationEnabled] = useState(true);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);@@ -50,13 +56,19 @@ export default function RegisterMessagingAppDialog({// isn't forced off while that request is in flight.const channelCreationSupported = selectedTypeInfo?.channel_creation_supported ?? true;- const handleTypeChange = useCallback((key: string) => {- // Switching type clears any fields entered for the previous one.- setSelectedType(key);- setConfig({});- setChannelCreationEnabled(true);- setError(null);- }, []);+ const handleTypeChange = useCallback(+ (key: string) => {+ // Switching type clears any fields entered for the previous one, then+ // seeds the new type's defaults — a field left untouched should post what+ // the schema says it defaults to, not an empty value.+ setSelectedType(key);+ const schema = bridgeTypes?.find((t) => t.key === key)?.config_schema;+ setConfig(extractDefaults(schema as Record<string, unknown> | undefined));+ setChannelCreationEnabled(true);+ setError(null);+ },+ [bridgeTypes],+ );const reset = useCallback(() => {setSelectedType("");@@ -76,7 +88,7 @@ export default function RegisterMessagingAppDialog({const canSubmit =!!selectedType &&displayName.trim().length > 0 &&- requiredFields.every((f) => (config[f] ?? "").trim().length > 0);+ requiredFields.every((f) => isProvided(config[f]));const handleSubmit = useCallback(async () => {if (!canSubmit) return;@@ -164,21 +176,12 @@ export default function RegisterMessagingAppDialog({</Typography>)}</Stack>- {configSchema &&- Object.entries(configSchema.properties).map(([field, prop]) => (- <TextField- key={field}- label={prop.title ?? humanize(field)}- type={isSecretField(field, prop) ? "password" : "text"}- value={config[field] ?? ""}- onChange={(e) =>- setConfig((prev) => ({ ...prev, [field]: e.target.value }))- }- fullWidth- required={requiredFields.includes(field)}- helperText={prop.description}- />- ))}+ {renderOptionFields(+ configSchema as Record<string, unknown> | undefined,+ config,+ setConfig,+ requiredFields,+ )}</>)}</Stack>