Skip to content

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

feat(console): Create from template view (CHOO-2656) (#405)

Abel Dantas2e0706f54f27
diff --git a/console/apps/switch-console-desktop/electron.vite.config.ts b/console/apps/switch-console-desktop/electron.vite.config.ts
index a44337fe4..b471b950f 100644
--- a/console/apps/switch-console-desktop/electron.vite.config.ts
+++ b/console/apps/switch-console-desktop/electron.vite.config.ts
@@ -58,7 +58,9 @@ export default defineConfig({
},
},
server: {
- port: 3000,
+ // Per-instance so two dev builds from different worktrees can run at
+ // once; the main process follows through ELECTRON_RENDERER_URL.
+ port: Number(process.env.SWITCH_CONSOLE_RENDERER_PORT) || 3000,
},
},
});
diff --git a/console/apps/switch-console-desktop/package.json b/console/apps/switch-console-desktop/package.json
index 3602376e9..1133ffe72 100644
--- a/console/apps/switch-console-desktop/package.json
+++ b/console/apps/switch-console-desktop/package.json
@@ -59,6 +59,7 @@
"@switch-console/plugins": "workspace:*",
"@switch-console/shared": "workspace:*",
"@typescript/native-preview": "7.0.0-dev.20260609.1",
+ "ajv": "^8.17.1",
"better-sqlite3": "^12.6.0",
"croner": "^10.0.1",
"cronstrue": "^3.14.0",
diff --git a/console/apps/switch-console-desktop/src/main/app/configure-app-identity.ts b/console/apps/switch-console-desktop/src/main/app/configure-app-identity.ts
index 932712a10..cc0b54a42 100644
--- a/console/apps/switch-console-desktop/src/main/app/configure-app-identity.ts
+++ b/console/apps/switch-console-desktop/src/main/app/configure-app-identity.ts
@@ -3,4 +3,10 @@ import { app } from 'electron';
import { OS_APP_NAME, USER_DATA_DIR_NAME } from '@shared/app-identity';
app.setName(OS_APP_NAME);
-app.setPath('userData', join(app.getPath('appData'), USER_DATA_DIR_NAME));
+
+// Several dev builds can run side by side on one machine (one per worktree)
+// when each keeps its own userData: the server list, sessions and the local
+// database live there. Dev-only, so a packaged app never reads it.
+const userDataDirName =
+ (import.meta.env.DEV && process.env.SWITCH_CONSOLE_USER_DATA_DIR) || USER_DATA_DIR_NAME;
+app.setPath('userData', join(app.getPath('appData'), userDataDirName));
diff --git a/console/apps/switch-console-desktop/src/main/app/window.ts b/console/apps/switch-console-desktop/src/main/app/window.ts
index 7bb44e84a..d186cc583 100644
--- a/console/apps/switch-console-desktop/src/main/app/window.ts
+++ b/console/apps/switch-console-desktop/src/main/app/window.ts
@@ -24,8 +24,8 @@ export function createMainWindow(): BrowserWindow {
contextIsolation: true,
// Required for ESM preload scripts (.mjs)
sandbox: false,
- // __dirname resolves to out/main/ at runtime; preload is at out/preload/index.mjs
- preload: join(__dirname, '../preload/index.mjs'),
+ // import.meta.dirname resolves to out/main/ at runtime; preload is at out/preload/index.mjs
+ preload: join(import.meta.dirname, '../preload/index.mjs'),
// Enables the embedded room view's <webview> (CHOO-1674). Guests are
// constrained in the will-attach-webview handler below, which is what
// actually keeps this from widening the app's attack surface.
@@ -105,7 +105,7 @@ export function createMainWindow(): BrowserWindow {
* preload the app ships. Anything else is dropped.
*/
function constrainEmbeddedWebviews(window: BrowserWindow): void {
- const guestPreload = join(__dirname, '../preload/mattermost-guest.mjs');
+ const guestPreload = join(import.meta.dirname, '../preload/mattermost-guest.mjs');
window.webContents.on('will-attach-webview', (event, webPreferences, params) => {
// Never honour a preload named in markup — pin it to the one we ship.
diff --git a/console/apps/switch-console-desktop/src/main/core/app/utils.ts b/console/apps/switch-console-desktop/src/main/core/app/utils.ts
index 22a8494df..7773d4df8 100644
--- a/console/apps/switch-console-desktop/src/main/core/app/utils.ts
+++ b/console/apps/switch-console-desktop/src/main/core/app/utils.ts
@@ -155,7 +155,7 @@ export const resolveAppVersion = async (): Promise<string> => {
}
const possiblePaths = [
- join(__dirname, '../../package.json'),
+ join(import.meta.dirname, '../../package.json'),
join(process.cwd(), 'package.json'),
join(app.getAppPath(), 'package.json'),
];
diff --git a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts
new file mode 100644
index 000000000..46bf212e7
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.test.ts
@@ -0,0 +1,257 @@
+import { describe, expect, it } from 'vitest';
+import { roomTemplatesController } from './controller';
+
+const parse = (yamlText: string, schema?: Record<string, unknown>) =>
+ roomTemplatesController.parse({ yamlText, schema });
+
+/** A permissive schema that accepts both `room:` and `params:`, standing in
+ * for a server that supports template params. */
+const PARAMS_SCHEMA = {
+ type: 'object',
+ required: ['room'],
+ properties: {
+ room: { type: 'object' },
+ params: { type: 'object' },
+ },
+ additionalProperties: false,
+};
+
+describe('roomTemplatesController.parse', () => {
+ it('extracts params with types and defaults', () => {
+ const result = parse(
+ `
+room:
+ name: test-room
+ agents:
+ - bot-a
+ - '{deploy_agent}'
+params:
+ label:
+ type: string
+ description: A label
+ default: hello
+ count:
+ type: number
+ default: 3
+ enabled:
+ type: boolean
+ default: true
+ env:
+ type: enum
+ enum: [dev, prod]
+`,
+ PARAMS_SCHEMA
+ );
+ expect(result.roomName).toBe('test-room');
+ expect(result.agents).toEqual(['bot-a', '{deploy_agent}']);
+ expect(result.params).toHaveLength(4);
+ expect(result.params[0]).toMatchObject({
+ name: 'label',
+ type: 'string',
+ default: 'hello',
+ });
+ expect(result.params[1]).toMatchObject({ name: 'count', type: 'number', default: 3 });
+ expect(result.params[2]).toMatchObject({ name: 'enabled', type: 'boolean', default: true });
+ expect(result.params[3]).toMatchObject({ name: 'env', type: 'enum', enum: ['dev', 'prod'] });
+ expect(result.warnings).toEqual([]);
+ });
+
+ it('carries entity param types through instead of guessing from the name', () => {
+ const result = parse(
+ `
+room:
+ name: test
+params:
+ agent:
+ type: string
+ coder:
+ type: agent
+ where:
+ type: bridge
+ escalate_to:
+ type: room
+ owner:
+ type: user
+`,
+ PARAMS_SCHEMA
+ );
+ const byName = Object.fromEntries(result.params.map((p) => [p.name, p.type]));
+ expect(byName).toEqual({
+ agent: 'string',
+ coder: 'agent',
+ where: 'bridge',
+ escalate_to: 'room',
+ owner: 'user',
+ });
+ });
+
+ it('reads an unknown type as string and leaves the schema to reject it', () => {
+ const result = parse('room:\n name: test\nparams:\n x:\n type: widget\n');
+ expect(result.params[0].type).toBe('string');
+ });
+
+ it('paramless template returns empty params', () => {
+ const result = parse(`
+room:
+ name: simple-room
+ description: No params
+`);
+ expect(result.params).toEqual([]);
+ expect(result.roomName).toBe('simple-room');
+ });
+
+ it('passes through params without schema (server validates on create)', () => {
+ const result = parse('room:\n name: test\nparams:\n x:\n type: string\n');
+ expect(result.params).toHaveLength(1);
+ });
+
+ it('throws on invalid YAML', () => {
+ expect(() => parse('{{{')).toThrow(/Invalid YAML/);
+ });
+
+ it('rejects non-mapping YAML', () => {
+ expect(() => parse('- a\n- b\n')).toThrow('Template must be a YAML mapping');
+ });
+
+ it('rejects template without room block', () => {
+ expect(() => parse('something_else:\n name: test\n')).toThrow(/must have a "room:" block/);
+ });
+
+ it('handles bare param names (no spec object)', () => {
+ const result = parse(
+ `
+room:
+ name: test
+params:
+ deploy_agent:
+ label:
+`,
+ PARAMS_SCHEMA
+ );
+ expect(result.params[0]).toMatchObject({
+ name: 'deploy_agent',
+ type: 'string',
+ default: null,
+ });
+ expect(result.params[1]).toMatchObject({
+ name: 'label',
+ type: 'string',
+ });
+ });
+
+ it('validates YAML against a JSON Schema when provided', () => {
+ const schema = {
+ type: 'object',
+ required: ['room'],
+ properties: {
+ room: {
+ type: 'object',
+ required: ['name', 'description'],
+ properties: {
+ name: { type: 'string' },
+ description: { type: 'string' },
+ },
+ },
+ },
+ };
+ // Valid template passes
+ const result = parse('room:\n name: test\n description: hello\n', schema);
+ expect(result.roomName).toBe('test');
+
+ // Missing required field fails
+ expect(() => parse('room:\n name: test\n', schema)).toThrow(/description/);
+ });
+
+ it('skips fallback validation when schema is provided', () => {
+ // With a permissive schema, params are allowed even though it would
+ // fail the no-schema fallback check
+ const result = parse('room:\n name: test\nparams:\n x:\n type: string\n', PARAMS_SCHEMA);
+ expect(result.params).toHaveLength(1);
+ });
+});
+
+describe('roomTemplatesController.parse: kickoff and creator', () => {
+ it('extracts kickoff, bridge, users, and the creator flag', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: [
+ 'params:',
+ ' coder:',
+ ' type: string',
+ 'room:',
+ ' name: "Work: {task}"',
+ ' description: d',
+ ' bridge: "Slack"',
+ ' agents: ["{coder}", "helper"]',
+ ' users: ["{$creator}", "bob"]',
+ 'kickoff: |',
+ ' @{coder} start on the brief.',
+ ].join('\n'),
+ });
+ expect(result.kickoff).toBe('@{coder} start on the brief.\n');
+ expect(result.bridge).toBe('Slack');
+ expect(result.users).toEqual(['{$creator}', 'bob']);
+ expect(result.hardcodedUsers).toEqual(['bob']);
+ expect(result.usesCreator).toBe(true);
+ });
+
+ it('warns about the stale room-level kickoff form and ignores it', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: ['room:', ' name: n', ' description: d', ' kickoff: go'].join('\n'),
+ });
+ expect(result.kickoff).toBeNull();
+ expect(result.warnings.some((w) => w.includes('kickoff'))).toBe(true);
+ });
+
+ it('defaults kickoff/bridge to null and usesCreator to false', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: 'room:\n name: n\n description: d\n',
+ });
+ expect(result.kickoff).toBeNull();
+ expect(result.bridge).toBeNull();
+ expect(result.users).toEqual([]);
+ expect(result.usesCreator).toBe(false);
+ });
+
+ it('treats an interpolated bridge name as unknown', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: 'room:\n name: n\n description: d\n bridge: "{which}"\n',
+ });
+ expect(result.bridge).toBeNull();
+ });
+});
+
+describe('roomTemplatesController.parse: multiline params', () => {
+ it('marks a string param declared multiline', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: [
+ 'params:',
+ ' brief:',
+ ' type: string',
+ ' multiline: true',
+ ' task_name:',
+ ' type: string',
+ 'room:',
+ ' name: n',
+ ' description: d',
+ ].join('\n'),
+ });
+ const byName = Object.fromEntries(result.params.map((p) => [p.name, p]));
+ expect(byName.brief.multiline).toBe(true);
+ expect(byName.task_name.multiline).toBe(false);
+ });
+
+ it('ignores multiline on non-string params', () => {
+ const result = roomTemplatesController.parse({
+ yamlText: [
+ 'params:',
+ ' flag:',
+ ' type: boolean',
+ ' multiline: true',
+ 'room:',
+ ' name: n',
+ ' description: d',
+ ].join('\n'),
+ });
+ expect(result.params[0].multiline).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
new file mode 100644
index 000000000..51c68d6bf
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/room-templates/controller.ts
@@ -0,0 +1,160 @@
+import Ajv from 'ajv';
+import { dump, load } from 'js-yaml';
+import { PARAM_TYPES, type ParamType } from '@shared/core/switch-servers/room-template-params';
+import { createRPCController } from '@shared/lib/ipc/rpc';
+
+export type ParamSpec = {
+ name: string;
+ type: ParamType;
+ description: string | null;
+ default: string | number | boolean | null;
+ enum: string[] | null;
+ /** String params carrying long text render as a textarea (a one-line input
+ * would strip pasted newlines). Declared in the template: `multiline: true`. */
+ multiline: boolean;
+};
+
+export type ParsedTemplate = {
+ params: ParamSpec[];
+ roomName: string | null;
+ /** All agents from the template (both interpolated and hardcoded). */
+ agents: string[];
+ /** Hardcoded agents (no `{param}` interpolation), editable in the form. */
+ hardcodedAgents: string[];
+ /** Hardcoded users, editable in the form. */
+ hardcodedUsers: string[];
+ /** All users from the template, interpolated entries included. */
+ users: string[];
+ /** The bridge the template names, or null when unset or interpolated. */
+ bridge: string | null;
+ /** Message the server posts as the creating user after the room exists. */
+ kickoff: string | null;
+ /** Whether the template references the `{$creator}` builtin anywhere. */
+ usesCreator: boolean;
+ warnings: string[];
+};
+
+function extractParams(raw: unknown): ParamSpec[] {
+ if (raw === null || raw === undefined || typeof raw !== 'object') return [];
+ const params = raw as Record<string, unknown>;
+ return Object.entries(params).map(([name, spec]) => {
+ if (spec === null || typeof spec !== 'object') {
+ return {
+ name,
+ type: 'string' as const,
+ description: null,
+ default: null,
+ enum: null,
+ multiline: false,
+ };
+ }
+ const s = spec as Record<string, unknown>;
+ const type = typeof s.type === 'string' ? s.type : 'string';
+ // An unknown type is read as a string so the form still renders; the
+ // server's schema is what rejects it, with a message naming the type.
+ const validType = PARAM_TYPES.includes(type as ParamType) ? (type as ParamType) : 'string';
+ return {
+ name,
+ type: validType,
+ description: typeof s.description === 'string' ? s.description : null,
+ default: s.default !== undefined ? (s.default as ParamSpec['default']) : null,
+ enum: Array.isArray(s.enum) ? (s.enum as string[]) : null,
+ multiline: validType === 'string' && s.multiline === true,
+ };
+ });
+}
+
+function parseYaml(yamlText: string): Record<string, unknown> {
+ let doc: Record<string, unknown>;
+ try {
+ const parsed = load(yamlText);
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error('Template must be a YAML mapping');
+ }
+ doc = parsed as Record<string, unknown>;
+ } catch (e) {
+ throw new Error(`Invalid YAML: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ return doc;
+}
+
+const hasInterpolation = (s: string) => /\{[^}]+\}/.test(s);
+
+const usesCreator = (s: string) => /\{\$creator(_email)?\}/.test(s);
+
+function extractStringList(raw: unknown): string[] {
+ if (!Array.isArray(raw)) return [];
+ return raw.filter((a): a is string => typeof a === 'string');
+}
+
+const ajv = new Ajv({ allErrors: true, strict: false });
+
+export const roomTemplatesController = createRPCController({
+ parse: (params: { yamlText: string; schema?: Record<string, unknown> }): ParsedTemplate => {
+ const warnings: string[] = [];
+ const doc = parseYaml(params.yamlText);
+
+ // Validate against server schema if provided
+ if (params.schema) {
+ const validate = ajv.compile(params.schema);
+ if (!validate(doc)) {
+ const errors = (validate.errors ?? [])
+ .map((err) => {
+ const path = err.instancePath || '/';
+ return `${path}: ${err.message}`;
+ })
+ .slice(0, 5);
+ throw new Error(errors.join('\n'));
+ }
+ } else if (!doc.room) {
+ throw new Error('Template must have a "room:" block.');
+ }
+
+ const room = doc.room as Record<string, unknown> | undefined;
+ const roomName = room && typeof room.name === 'string' ? room.name : null;
+ const allAgents = extractStringList(room?.agents);
+ const allUsers = extractStringList(room?.users);
+ const paramSpecs = extractParams(doc.params);
+ const kickoff = typeof doc.kickoff === 'string' ? doc.kickoff : null;
+ if (room && typeof room.kickoff === 'string') {
+ warnings.push(
+ '`kickoff:` belongs at the top level, beside `room:`. Inside `room:` the server ignores it.'
+ );
+ }
+ const bridge =
+ room && typeof room.bridge === 'string' && !hasInterpolation(room.bridge)
+ ? room.bridge
+ : null;
+
+ if (!room) {
+ warnings.push('Template has no "room:" block, so the server may reject it.');
+ }
+
+ return {
+ params: paramSpecs,
+ roomName,
+ agents: allAgents,
+ hardcodedAgents: allAgents.filter((a) => !hasInterpolation(a)),
+ hardcodedUsers: allUsers.filter((u) => !hasInterpolation(u)),
+ users: allUsers,
+ bridge,
+ kickoff,
+ usesCreator: usesCreator(params.yamlText),
+ warnings,
+ };
+ },
+
+ /** Rewrite the template YAML, replacing room.agents and room.users with edited lists. */
+ rewriteYaml: (params: { yamlText: string; agents: string[]; users: string[] }): string => {
+ const doc = parseYaml(params.yamlText);
+ const room = doc.room as Record<string, unknown> | undefined;
+ if (!room) return params.yamlText;
+ room.agents = params.agents;
+ if (params.users.length > 0) {
+ room.users = params.users;
+ } else {
+ delete room.users;
+ }
+ return dump(doc, { lineWidth: -1 });
+ },
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 71d65b0b5..d9e6232b7 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -106,7 +106,10 @@ import {
GatewayError,
ownsOwnerAddressedAgent,
releaseBridgeIdentity,
+ createRoomFromTemplate,
+ fetchTemplateSchema,
removeRoomAgent,
+ type TemplateProvisionResult,
updateAddressingPolicy,
updateAgentIcon,
updateRoom,
@@ -548,6 +551,16 @@ export const switchServersController = createRPCController({
return result;
},
+ createRoomFromTemplate: async (
+ serverId: string,
+ yamlText: string,
+ inputs: Record<string, string | number | boolean>
+ ): Promise<TemplateProvisionResult> =>
+ createRoomFromTemplate(await requireServer(serverId), yamlText, inputs),
+
+ fetchTemplateSchema: async (serverId: string): Promise<Record<string, unknown> | null> =>
+ fetchTemplateSchema(await requireServer(serverId)),
+
listAgentRooms: async (params: {
serverId: string;
agentId: string;
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.ts
index 55a1825a6..9b43bd397 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
@@ -1043,6 +1043,63 @@ export async function deleteAgent(server: SwitchServer, agentId: string): Promis
});
}
+/** The result of provisioning a room from a YAML template. */
+export type TemplateProvisionResult = {
+ roomId: string;
+ roomName: string;
+ failedAttachments: Array<{ kind: string; id: string; error: string }>;
+};
+
+/**
+ * Create a room from a YAML template (`POST /rooms/from-yaml`). Sends the
+ * template as a JSON body with the YAML text and any user-supplied inputs.
+ * The server parses the template, interpolates inputs, and provisions
+ * everything in one call.
+ *
+ * A 400 carries a `detail` naming the bad input; the caller maps it back to
+ * the form field.
+ */
+export async function createRoomFromTemplate(
+ server: SwitchServer,
+ yamlText: string,
+ inputs: Record<string, string | number | boolean>
+): Promise<TemplateProvisionResult> {
+ const res = await gatewayFetch(server, '/rooms/from-yaml', {
+ authenticated: true,
+ method: 'POST',
+ body: { yaml: yamlText, inputs },
+ });
+ const json = (await res.json()) as {
+ room_id: string;
+ room_name: string;
+ failed_attachments?: Array<{ kind: string; id: string; error: string }>;
+ };
+ return {
+ roomId: json.room_id,
+ roomName: json.room_name,
+ failedAttachments: json.failed_attachments ?? [],
+ };
+}
+
+/**
+ * Fetch the JSON Schema describing a valid room template. Returns null when
+ * the server does not support the endpoint (404): older servers without
+ * `params:` support.
+ */
+export async function fetchTemplateSchema(
+ server: SwitchServer
+): Promise<Record<string, unknown> | null> {
+ try {
+ const res = await gatewayFetch(server, '/rooms/template-schema', {
+ authenticated: true,
+ });
+ return (await res.json()) as Record<string, unknown>;
+ } catch (e) {
+ if (e instanceof GatewayError && e.status === 404) return null;
+ throw e;
+ }
+}
+
export async function fetchRoomRoles(
server: SwitchServer,
roomId: string
diff --git a/console/apps/switch-console-desktop/src/main/rpc.ts b/console/apps/switch-console-desktop/src/main/rpc.ts
index 84e297228..230e58447 100644
--- a/console/apps/switch-console-desktop/src/main/rpc.ts
+++ b/console/apps/switch-console-desktop/src/main/rpc.ts
@@ -11,6 +11,7 @@ import { providersController } from './core/providers/controller';
import { ptyController } from './core/pty/controller';
import { remoteHostsController } from './core/remote-hosts/controller';
import { resourceMonitorController } from './core/resource-monitor/controller';
+import { roomTemplatesController } from './core/room-templates/controller';
import { searchController } from './core/search/controller';
import { sessionController } from './core/sessions/controller';
import { appSettingsController } from './core/settings/controller';
@@ -44,6 +45,7 @@ export const rpcRouter = createRPCRouter({
localSwitchServer: localSwitchServerController,
remoteSwitchServer: remoteSwitchServerController,
remoteHosts: remoteHostsController,
+ roomTemplates: roomTemplatesController,
sidecar: sidecarController,
telemetry: telemetryController,
fs: createRPCNamespace({
diff --git a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
index d4536aa00..c2b25fe60 100644
--- a/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
+++ b/console/apps/switch-console-desktop/src/renderer/app/view-registry.ts
@@ -3,6 +3,7 @@ import { homeView } from '@renderer/app/home-view';
import { locationView } from '@renderer/features/locations/view';
import { remoteHostView } from '@renderer/features/remote-hosts/views/remote-host-view';
import { remoteHostsView } from '@renderer/features/remote-hosts/views/remote-hosts-view';
+import { roomTemplateImportView } from '@renderer/features/room-templates/room-template-import-view';
import { sessionView } from '@renderer/features/sessions/view';
import { settingsView } from '@renderer/features/settings/settings-view';
import { roomView } from '@renderer/features/switch-rooms/view';
@@ -27,6 +28,7 @@ export const views = {
serverRooms: serverRoomsView,
remoteHosts: remoteHostsView,
remoteHost: remoteHostView,
+ roomTemplateImport: roomTemplateImportView,
// oxlint-disable-next-line typescript/no-explicit-any
} satisfies Record<string, ViewDefinition<any>>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.test.ts b/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.test.ts
new file mode 100644
index 000000000..e6be12913
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+import { blockedHandoffs, type HandoffAgent } from './agent-handoff';
+
+const ownerOnly = {
+ rules: [{ rooms: '*' as const, room_groups: '*' as const, users: [], agents: [], owner: true }],
+};
+
+function agent(name: string, overrides: Partial<HandoffAgent> = {}): HandoffAgent {
+ return { id: `id-${name}`, name, ownerId: 'u1', addressingPolicy: null, ...overrides };
+}
+
+describe('blockedHandoffs', () => {
+ it('open agents hear each other', () => {
+ expect(blockedHandoffs([agent('coder'), agent('reviewer')])).toEqual([]);
+ });
+
+ it('an owner-only agent does not hear the other agent', () => {
+ const blocked = blockedHandoffs([
+ agent('coder'),
+ agent('reviewer', { addressingPolicy: ownerOnly }),
+ ]);
+ expect(blocked).toEqual([{ from: 'coder', to: 'reviewer' }]);
+ });
+
+ it('owner_agents admits an agent of the same owner and nobody else', () => {
+ const policy = { rules: [{ ...ownerOnly.rules[0], owner_agents: true }] };
+ const reviewer = agent('reviewer', { addressingPolicy: policy });
+ expect(blockedHandoffs([agent('coder'), reviewer])).toEqual([]);
+ expect(blockedHandoffs([agent('stranger', { ownerId: 'u2' }), reviewer])).toEqual([
+ { from: 'stranger', to: 'reviewer' },
+ ]);
+ });
+
+ it('an explicit agent id in the rule admits that agent', () => {
+ const policy = {
+ rules: [{ rooms: '*' as const, room_groups: '*' as const, users: [], agents: ['id-coder'] }],
+ };
+ expect(
+ blockedHandoffs([agent('coder'), agent('reviewer', { addressingPolicy: policy })])
+ ).toEqual([]);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.ts b/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.ts
new file mode 100644
index 000000000..d46f982c0
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/agent-handoff.ts
@@ -0,0 +1,48 @@
+import type { AddressingPolicy } from '@shared/core/switch-servers/switch-servers';
+
+/** What the hand-off check needs to know about one agent in the room. */
+export type HandoffAgent = {
+ id: string;
+ name: string;
+ ownerId: string | null;
+ addressingPolicy: AddressingPolicy | null;
+};
+
+/** One agent that will not hear another, and why. */
+export type BlockedHandoff = {
+ from: string;
+ to: string;
+};
+
+/**
+ * Whether `target` would accept a message from `source`, by the same rules the
+ * server applies to an agent sender: an open policy admits anyone, a rule
+ * admits the agent by id or, with `owner_agents`, any agent of the same owner.
+ */
+function admitsAgent(target: HandoffAgent, source: HandoffAgent): boolean {
+ const policy = target.addressingPolicy;
+ if (policy === null || policy.rules.length === 0) return true;
+ return policy.rules.some((rule) => {
+ if (rule.agents === '*') return true;
+ if (rule.agents.includes(source.id)) return true;
+ return (
+ rule.owner_agents === true && target.ownerId !== null && target.ownerId === source.ownerId
+ );
+ });
+}
+
+/**
+ * The pairs of agents in a room that cannot talk to each other. A template
+ * with a hand-off only works if it goes through, and an agent created from
+ * the Console starts owner-only, so the wizard warns before the room exists.
+ */
+export function blockedHandoffs(agents: HandoffAgent[]): BlockedHandoff[] {
+ const blocked: BlockedHandoff[] = [];
+ for (const source of agents) {
+ for (const target of agents) {
+ if (source.id === target.id) continue;
+ if (!admitsAgent(target, source)) blocked.push({ from: source.name, to: target.name });
+ }
+ }
+ return blocked;
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
new file mode 100644
index 000000000..17f52e235
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/entity-fields.tsx
@@ -0,0 +1,394 @@
+import { useQuery } from '@tanstack/react-query';
+import { User as UserIcon } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import {
+ type AgentPick,
+ AgentPickerRow,
+ ChosenAgentTile,
+ agentProviderLabelFor,
+} from '@renderer/lib/components/agent-picker';
+import { BridgeTile, bridgeUnusableReason } from '@renderer/lib/components/bridge-tile';
+import { ChosenTile } from '@renderer/lib/components/chosen-tile';
+import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
+import { ChosenRoomTile, type RoomPick, RoomPickerRow } from '@renderer/lib/components/room-picker';
+import { useDebounce } from '@renderer/lib/hooks/useDebounce';
+import { rpc } from '@renderer/lib/ipc';
+import type {
+ LinkedIdentity,
+ RemoteBridge,
+ RemoteExternalUser,
+} from '@shared/core/switch-servers/switch-servers';
+
+/**
+ * Everything the server has that a template can point at, read once by the
+ * wizard and handed to every field that offers a choice from it.
+ */
+export type EntityLists = {
+ serverId: string;
+ agents: AgentPick[];
+ agentsLoading: boolean;
+ rooms: RoomPick[];
+ roomsLoading: boolean;
+ bridges: RemoteBridge[];
+ /** Null while the signed-in user's linked accounts are unknown. */
+ identities: LinkedIdentity[] | null;
+ /** Platform users Switch has already seen on this server. */
+ knownUsers: RemoteExternalUser[];
+ /** The bridge the room will land on, for directory lookups. Null when the
+ * template leaves it open and the server has no default. */
+ bridgeId: string | null;
+};
+
+const NOT_ON_SERVER = 'Not on this server';
+
+/** The grid every chosen tile sits in, so single picks and lists line up. */
+function TileGrid({ children }: { children: React.ReactNode }) {
+ return <div className="grid grid-cols-3 gap-2.5">{children}</div>;
+}
+
+// ── Agents ──────────────────────────────────────────────────────────────────
+
+function agentTileFor(name: string, lists: EntityLists, onRemove: () => void) {
+ const found = lists.agents.find((a) => a.name === name);
+ return found ? (
+ <ChosenAgentTile
+ key={name}
+ agent={found}
+ subtitle={agentProviderLabelFor(found.id, lists.serverId)}
+ onRemove={onRemove}
+ />
+ ) : (
+ <ChosenAgentTile
+ key={name}
+ agent={{ id: name, name, iconUrl: null }}
+ subtitle={NOT_ON_SERVER}
+ subtitleTone="warning"
+ onRemove={onRemove}
+ />
+ );
+}
+
+function AgentCombobox({
+ lists,
+ exclude,
+ onPick,
+}: {
+ lists: EntityLists;
+ exclude: string[];
+ onPick: (name: string) => void;
+}) {
+ const items = lists.agents.filter((a) => !exclude.includes(a.name));
+ return (
+ <PickerCombobox
+ items={items}
+ onPick={(agent) => onPick(agent.name)}
+ searchText={(agent) => agent.name}
+ renderItem={(agent) => (
+ <AgentPickerRow agent={agent} subtitle={agentProviderLabelFor(agent.id, lists.serverId)} />
+ )}
+ disabled={lists.agentsLoading}
+ placeholder={lists.agentsLoading ? 'Loading agents…' : 'Search agents…'}
+ emptyText="No agents found"
+ />
+ );
+}
+
+/** One agent, by name: a search box until picked, then the agent's tile. */
+export function AgentField({
+ value,
+ onChange,
+ lists,
+}: {
+ value: string;
+ onChange: (name: string) => void;
+ lists: EntityLists;
+}) {
+ if (value === '') return <AgentCombobox lists={lists} exclude={[]} onPick={onChange} />;
+ return <TileGrid>{agentTileFor(value, lists, () => onChange(''))}</TileGrid>;
+}
+
+/**
+ * A list of agents by name, each a tile, with a search box to add more.
+ *
+ * The template's fixed `agents:` come in pre-filled. A name the server does
+ * not know stays in the list and says so on its tile, so the person can drop
+ * it rather than find out from a failed create.
+ */
+export function AgentListField({
+ items,
+ onChange,
+ lists,
+}: {
+ items: string[];
+ onChange: (items: string[]) => void;
+ lists: EntityLists;
+}) {
+ return (
+ <div className="flex flex-col gap-2.5">
+ {items.length > 0 && (
+ <TileGrid>
+ {items.map((name) =>
+ agentTileFor(name, lists, () => onChange(items.filter((n) => n !== name)))
+ )}
+ </TileGrid>
+ )}
+ <AgentCombobox lists={lists} exclude={items} onPick={(name) => onChange([...items, name])} />
+ </div>
+ );
+}
+
+// ── Rooms ───────────────────────────────────────────────────────────────────
+
+/** One existing room, by name: a search box until picked, then its tile. */
+export function RoomField({
+ value,
+ onChange,
+ lists,
+}: {
+ value: string;
+ onChange: (name: string) => void;
+ lists: EntityLists;
+}) {
+ if (value === '') {
+ return (
+ <PickerCombobox
+ items={lists.rooms}
+ onPick={(room) => onChange(room.name)}
+ searchText={(room) => room.name}
+ renderItem={(room) => <RoomPickerRow room={room} />}
+ disabled={lists.roomsLoading}
+ placeholder={lists.roomsLoading ? 'Loading rooms…' : 'Search rooms…'}
+ emptyText="No rooms found"
+ />
+ );
+ }
+ const found = lists.rooms.find((r) => r.name === value);
+ return (
+ <TileGrid>
+ {found ? (
+ <ChosenRoomTile room={found} onRemove={() => onChange('')} />
+ ) : (
+ <ChosenRoomTile
+ room={{ id: value, name: value, bridgeType: null }}
+ subtitle={NOT_ON_SERVER}
+ subtitleTone="warning"
+ onRemove={() => onChange('')}
+ />
+ )}
+ </TileGrid>
+ );
+}
+
+// ── Bridges ─────────────────────────────────────────────────────────────────
+
+/**
+ * One messaging app, by display name, from the same tile grid the new-room
+ * dialog uses. The room's channel is created wherever the template says, so
+ * only a running app is selectable; a stopped one is shown and says so.
+ */
+export function BridgeField({
+ value,
+ onChange,
+ lists,
+}: {
+ value: string;
+ onChange: (displayName: string) => void;
+ lists: EntityLists;
+}) {
+ const unknown = value !== '' && !lists.bridges.some((b) => b.displayName === value);
+ return (
+ <div className="flex flex-col gap-2">
+ {lists.bridges.length > 0 ? (
+ <div className="grid grid-cols-2 gap-2.5">
+ {lists.bridges.map((bridge) => (
+ <BridgeTile
+ key={bridge.id}
+ bridge={bridge}
+ identity={lists.identities?.find((i) => i.bridgeId === bridge.id) ?? null}
+ identitiesKnown={lists.identities !== null}
+ unusable={bridgeUnusableReason(bridge, { needsChannelCreation: false })}
+ selected={value === bridge.displayName}
+ onSelect={() => onChange(bridge.displayName)}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-foreground-muted">
+ This server has no messaging app connected, so there is nothing to choose from.
+ </p>
+ )}
+ {unknown && (
+ <p className="text-xs text-amber-600 dark:text-amber-500">
+ The template names <strong>{value}</strong>, which is not a messaging app on this server.
+ Pick one above.
+ </p>
+ )}
+ </div>
+ );
+}
+
+// ── Users ───────────────────────────────────────────────────────────────────
+
+type UserCandidate = {
+ id: string;
+ username: string;
+ /** Where the row came from, for the right of the row. */
+ source: 'known' | 'directory' | 'typed';
+ displayName: string | null;
+};
+
+/** How long to wait after the last keystroke before asking the platform. Every
+ * search is a live call out to Slack or Mattermost, so this is a courtesy to
+ * their rate limits as much as to ours. */
+const SEARCH_DEBOUNCE_MS = 300;
+const MIN_QUERY_LENGTH = 2;
+
+function userSourceLabel(candidate: UserCandidate): string {
+ switch (candidate.source) {
+ case 'known':
+ return 'Known';
+ case 'directory':
+ return candidate.displayName ?? 'Directory';
+ case 'typed':
+ return 'Use as typed';
+ }
+}
+
+/**
+ * Pick a person by platform username.
+ *
+ * Three sources feed the list: the users Switch has already seen on this
+ * server, a live search of the messaging app's directory once two characters
+ * are typed, and the typed text itself, offered last. The last one is there
+ * because the server looks an unseen name up in the directory when it creates
+ * the room, so a name the search did not surface is not necessarily wrong.
+ */
+function UserCombobox({
+ lists,
+ exclude,
+ onPick,
+}: {
+ lists: EntityLists;
+ exclude: string[];
+ onPick: (username: string) => void;
+}) {
+ const [query, setQuery] = useState('');
+ const debounced = useDebounce(query.trim(), SEARCH_DEBOUNCE_MS);
+ const bridgeId = lists.bridgeId;
+ const searchable = bridgeId !== null && debounced.length >= MIN_QUERY_LENGTH;
+ const directory = useQuery({
+ queryKey: ['bridge-directory', lists.serverId, bridgeId, debounced],
+ queryFn: () =>
+ rpc.switchServers.searchBridgeDirectory({
+ serverId: lists.serverId,
+ bridgeId: bridgeId as string,
+ query: debounced,
+ }),
+ enabled: searchable,
+ });
+
+ const items = useMemo((): UserCandidate[] => {
+ const seen = new Set<string>(exclude);
+ const out: UserCandidate[] = [];
+ for (const user of lists.knownUsers) {
+ if (seen.has(user.username)) continue;
+ seen.add(user.username);
+ out.push({
+ id: `known:${user.id}`,
+ username: user.username,
+ source: 'known',
+ displayName: null,
+ });
+ }
+ if (directory.data?.kind === 'results') {
+ for (const person of directory.data.users) {
+ if (seen.has(person.username)) continue;
+ seen.add(person.username);
+ out.push({
+ id: `directory:${person.externalUserId}`,
+ username: person.username,
+ source: 'directory',
+ displayName: person.displayName || null,
+ });
+ }
+ }
+ const typed = query.trim();
+ if (typed !== '' && !seen.has(typed)) {
+ out.push({ id: `typed:${typed}`, username: typed, source: 'typed', displayName: null });
+ }
+ return out;
+ }, [lists.knownUsers, directory.data, query, exclude]);
+
+ return (
+ <PickerCombobox
+ items={items}
+ onPick={(candidate) => onPick(candidate.username)}
+ onQueryChange={setQuery}
+ searchText={(candidate) =>
+ `${candidate.username} ${candidate.displayName ?? ''}`.toLowerCase()
+ }
+ renderItem={(candidate) => (
+ <>
+ <UserIcon className="size-4 shrink-0 text-foreground-muted" />
+ <span className="min-w-0 flex-1 truncate">{candidate.username}</span>
+ <span className="shrink-0 text-xs text-foreground-muted">
+ {userSourceLabel(candidate)}
+ </span>
+ </>
+ )}
+ placeholder={bridgeId === null ? 'Username (no messaging app to search)' : 'Search people…'}
+ emptyText="Type a username"
+ />
+ );
+}
+
+function userTileFor(username: string, lists: EntityLists, onRemove: () => void) {
+ const known = lists.knownUsers.some((u) => u.username === username);
+ return (
+ <ChosenTile
+ key={username}
+ mark={<UserIcon className="size-5 text-foreground-muted" />}
+ title={username}
+ subtitle={known ? 'Known to this server' : 'Looked up when the room is created'}
+ onRemove={onRemove}
+ />
+ );
+}
+
+/** One person, by platform username: a search box until picked, then a tile. */
+export function UserField({
+ value,
+ onChange,
+ lists,
+}: {
+ value: string;
+ onChange: (username: string) => void;
+ lists: EntityLists;
+}) {
+ if (value === '') return <UserCombobox lists={lists} exclude={[]} onPick={onChange} />;
+ return <TileGrid>{userTileFor(value, lists, () => onChange(''))}</TileGrid>;
+}
+
+/** A list of people by username, each a tile, with a search box to add more. */
+export function UserListField({
+ items,
+ onChange,
+ lists,
+}: {
+ items: string[];
+ onChange: (items: string[]) => void;
+ lists: EntityLists;
+}) {
+ return (
+ <div className="flex flex-col gap-2.5">
+ {items.length > 0 && (
+ <TileGrid>
+ {items.map((name) =>
+ userTileFor(name, lists, () => onChange(items.filter((n) => n !== name)))
+ )}
+ </TileGrid>
+ )}
+ <UserCombobox lists={lists} exclude={items} onPick={(name) => onChange([...items, name])} />
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
new file mode 100644
index 000000000..9d53485fc
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/room-templates/room-template-import-view.tsx
@@ -0,0 +1,1010 @@
+import Editor from '@monaco-editor/react';
+import { useQuery, useQueryClient } from '@tanstack/react-query';
+import { ArrowRight, Check, FileText, Loader2, Upload } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import type { ParamSpec, ParsedTemplate } from '@main/core/room-templates/controller';
+import type { GuardResult, ViewDefinition } from '@renderer/app/view-registry';
+import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
+import { ServerPage } from '@renderer/features/switch-servers/server-page';
+import { ServerSectionTitlebar } from '@renderer/features/switch-servers/server-section-titlebar';
+import { useMyIdentities } from '@renderer/features/switch-servers/use-my-identities';
+import { failureText } from '@renderer/lib/errors/describe-failure';
+import { rpc } from '@renderer/lib/ipc';
+import { useParams } from '@renderer/lib/layout/navigation-provider';
+import { useModalContext } from '@renderer/lib/modal/modal-provider';
+import { appState } from '@renderer/lib/stores/app-state';
+import { remoteAgentsQueryKey, useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
+import { Alert, AlertDescription } from '@renderer/lib/ui/alert';
+import { Button } from '@renderer/lib/ui/button';
+import { Field, FieldGroup, FieldLabel } from '@renderer/lib/ui/field';
+import { Input } from '@renderer/lib/ui/input';
+import { Textarea } from '@renderer/lib/ui/textarea';
+import { isEntityParamType } from '@shared/core/switch-servers/room-template-params';
+import { RpcError } from '@shared/lib/ipc/rpc-error';
+import { type BlockedHandoff, blockedHandoffs } from './agent-handoff';
+import {
+ AgentField,
+ AgentListField,
+ BridgeField,
+ type EntityLists,
+ RoomField,
+ UserField,
+ UserListField,
+} from './entity-fields';
+
+type Step = 'source' | 'inputs' | 'creating';
+
+/** Interpolate `{param}` and `{$builtin}` patterns with current form values. */
+function interpolate(template: string, values: Record<string, string | number | boolean>): string {
+ return template.replace(/\{(\$?\w+)\}/g, (match, key: string) => {
+ const val = values[key];
+ return val !== undefined && val !== '' ? String(val) : match;
+ });
+}
+
+// ── Source step ─────────────────────────────────────────────────────────────
+
+function readFileAsText(file: File, onText: (text: string) => void): void {
+ const reader = new FileReader();
+ reader.onload = () => {
+ if (typeof reader.result === 'string') onText(reader.result);
+ };
+ reader.readAsText(file);
+}
+
+function SourceStep({
+ yamlText,
+ onYamlChange,
+ parseError,
+ onNext,
+ onFileSelect,
+}: {
+ yamlText: string;
+ onYamlChange: (text: string) => void;
+ parseError: string | null;
+ onNext: () => void;
+ onFileSelect: (name: string) => void;
+}) {
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [dragging, setDragging] = useState(false);
+
+ const handleFileChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ onFileSelect(file.name);
+ readFileAsText(file, onYamlChange);
+ e.target.value = '';
+ },
+ [onYamlChange, onFileSelect]
+ );
+
+ const handleDrop = useCallback(
+ (e: React.DragEvent) => {
+ e.preventDefault();
+ setDragging(false);
+ const file = e.dataTransfer.files[0];
+ if (!file) return;
+ onFileSelect(file.name);
+ readFileAsText(file, onYamlChange);
+ },
+ [onYamlChange, onFileSelect]
+ );
+
+ // Auto-expand: 18px per line, min 256px, max 600px
+ const lineCount = Math.max(yamlText.split('\n').length, 1);
+ const editorHeight = Math.min(Math.max(lineCount * 18 + 20, 256), 600);
+
+ return (
+ <div className="flex flex-col gap-4">
+ <FieldGroup>
+ <Field>
+ <FieldLabel>Paste a room template</FieldLabel>
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDragging(true);
+ }}
+ onDragLeave={() => setDragging(false)}
+ onDrop={handleDrop}
+ className={`overflow-hidden rounded-md border border-border transition-colors ${dragging ? 'ring-primary ring-2' : ''}`}
+ >
+ <Editor
+ height={editorHeight}
+ language="yaml"
+ theme="vs-dark"
+ value={yamlText}
+ onChange={(v) => onYamlChange(v ?? '')}
+ options={{
+ minimap: { enabled: false },
+ lineNumbers: 'on',
+ folding: true,
+ tabSize: 2,
+ fontSize: 13,
+ scrollBeyondLastLine: false,
+ wordWrap: 'on',
+ automaticLayout: true,
+ renderLineHighlight: 'none',
+ overviewRulerLanes: 0,
+ hideCursorInOverviewRuler: true,
+ scrollbar: { vertical: 'auto', horizontal: 'auto' },
+ }}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+
+ <div className="flex items-center gap-3">
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".yaml,.yml"
+ className="hidden"
+ onChange={handleFileChange}
+ />
+ <Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
+ <Upload className="mr-1.5 size-3.5" />
+ Choose file
+ </Button>
+ <span className="text-xs text-foreground-passive">
+ or paste YAML above, or drag and drop
+ </span>
+ </div>
+
+ {parseError && (
+ <Alert variant="destructive">
+ <AlertDescription>{parseError}</AlertDescription>
+ </Alert>
+ )}
+
+ <div className="flex justify-end pt-2">
+ <Button disabled={!yamlText.trim()} onClick={onNext}>
+ Next
+ <ArrowRight className="ml-1.5 size-3.5" />
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+// ── Param field ────────────────────────────────────────────────────────────
+
+/** The label, description and error every param field shares, around
+ * whatever control the param's type calls for. */
+function ParamFieldShell({
+ param,
+ value,
+ error,
+ children,
+}: {
+ param: ParamSpec;
+ value: string | number | boolean;
+ error: string | null;
+ children: React.ReactNode;
+}) {
+ const isRequired = param.default === null;
+ const defaultKept = param.default !== null && value === param.default;
+ // Label: param name (humanized) + default annotation
+ const nameLabel = param.name.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
+ return (
+ <Field>
+ <FieldLabel>
+ {nameLabel}
+ {defaultKept && (
+ <span className="ml-1 font-normal text-foreground-muted">(default kept)</span>
+ )}
+ {isRequired && <span className="ml-1 text-destructive">*</span>}
+ </FieldLabel>
+ {children}
+ {param.description && (
+ <p className="mt-1 text-xs text-foreground-muted">{param.description}</p>
+ )}
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ </Field>
+ );
+}
+
+function ParamField({
+ param,
+ value,
+ onChange,
+ error,
+ lists,
+}: {
+ param: ParamSpec;
+ value: string | number | boolean;
+ onChange: (v: string | number | boolean) => void;
+ error: string | null;
+ lists: EntityLists;
+}) {
+ if (param.type === 'boolean') {
+ const isRequired = param.default === null;
+ const nameLabel = param.name.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
+ return (
+ <Field>
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={Boolean(value)}
+ onChange={(e) => onChange(e.target.checked)}
+ className="size-4 rounded border-border"
+ />
+ <span className="text-sm font-medium">
+ {nameLabel}
+ {isRequired && <span className="ml-1 text-destructive">*</span>}
+ </span>
+ </label>
+ {param.description && (
+ <p className="mt-1 text-xs text-foreground-muted">{param.description}</p>
+ )}
+ </Field>
+ );
+ }
+
+ // Entity-typed params pick from what the server has, the same way the
+ // new-room dialog does; the value is the entity's name as the template
+ // would spell it, and the server checks it again on create.
+ if (isEntityParamType(param.type)) {
+ const strVal = typeof value === 'string' ? value : String(value ?? '');
+ const control =
+ param.type === 'agent' ? (
+ <AgentField value={strVal} onChange={onChange} lists={lists} />
+ ) : param.type === 'room' ? (
+ <RoomField value={strVal} onChange={onChange} lists={lists} />
+ ) : param.type === 'bridge' ? (
+ <BridgeField value={strVal} onChange={onChange} lists={lists} />
+ ) : (
+ <UserField value={strVal} onChange={onChange} lists={lists} />
+ );
+ return (
+ <ParamFieldShell param={param} value={value} error={error}>
+ {control}
+ </ParamFieldShell>
+ );
+ }
+
+ if (param.type === 'enum' && param.enum) {
+ return (
+ <ParamFieldShell param={param} value={value} error={error}>
+ <select
+ value={String(value)}
+ onChange={(e) => onChange(e.target.value)}
+ className="flex h-9 w-full rounded-md border border-border bg-transparent px-2.5 text-sm"
+ aria-invalid={error ? true : undefined}
+ >
+ <option value="">Select…</option>
+ {param.enum.map((opt) => (
+ <option key={opt} value={opt}>
+ {opt}
+ </option>
+ ))}
+ </select>
+ </ParamFieldShell>
+ );
+ }
+
+ if (param.type === 'number') {
+ return (
+ <ParamFieldShell param={param} value={value} error={error}>
+ <Input
+ type="number"
+ value={value === '' ? '' : Number(value)}
+ onChange={(e) => onChange(e.target.value === '' ? '' : Number(e.target.value))}
+ aria-invalid={error ? true : undefined}
+ />
+ </ParamFieldShell>
+ );
+ }
+
+ // Long-text string param: a textarea, because a one-line input strips the
+ // newlines out of a pasted brief.
+ if (param.multiline) {
+ return (
+ <ParamFieldShell param={param} value={value} error={error}>
+ <Textarea
+ value={String(value)}
+ onChange={(e) => onChange(e.target.value)}
+ className="min-h-40 resize-y font-mono text-xs"
+ aria-invalid={error ? true : undefined}
+ />
+ </ParamFieldShell>
+ );
+ }
+
+ return (
+ <ParamFieldShell param={param} value={value} error={error}>
+ <Input
+ value={String(value)}
+ onChange={(e) => onChange(e.target.value)}
+ aria-invalid={error ? true : undefined}
+ />
+ </ParamFieldShell>
+ );
+}
+
+// ── Summary panel ──────────────────────────────────────────────────────────
+
+function SummaryPanel({
+ parsed,
+ values,
+ sourceName,
+ creatorIdentity,
+ bridgeName,
+ onLinkAccount,
+}: {
+ parsed: ParsedTemplate;
+ values: Record<string, string | number | boolean>;
+ sourceName: string | null;
+ /** How the signed-in user resolves on the template's bridge, or null. */
+ creatorIdentity: string | null;
+ /** The bridge the room will land on, when known. */
+ bridgeName: string | null;
+ /** Opens the link-account flow for the template's bridge; null when the
+ * bridge is not known, so there is nothing to link to yet. */
+ onLinkAccount: (() => void) | null;
+}) {
+ const preview = (s: string) => interpolate(s, { ...values, $creator: creatorIdentity ?? 'you' });
+ const roomNamePreview = parsed.roomName ? preview(parsed.roomName) : null;
+
+ // Agent names with interpolation applied
+ const agentPreviews = parsed.agents.map(preview).filter((a) => !a.includes('{'));
+ const userPreviews = parsed.users.map(preview).filter((u) => !u.includes('{'));
+ const kickoffPreview = parsed.kickoff ? preview(parsed.kickoff) : null;
+
+ const steps: React.ReactNode[] = [];
+ if (roomNamePreview) {
+ steps.push(
+ <span>
+ Room <strong>{roomNamePreview}</strong>
+ {bridgeName ? (
+ <>
+ {' '}
+ with its channel on <strong>{bridgeName}</strong>
+ </>
+ ) : null}
+ </span>
+ );
+ }
+ steps.push(<span>Instructions filled with your inputs</span>);
+ for (const agent of agentPreviews) {
+ steps.push(
+ <span>
+ Agent <strong>{agent}</strong> added as member
+ </span>
+ );
+ }
+ for (const user of userPreviews) {
+ steps.push(
+ <span>
+ {creatorIdentity !== null && user === creatorIdentity ? (
+ <>
+ <strong>You</strong> invited as <strong>{user}</strong>
+ </>
+ ) : (
+ <>
+ <strong>{user}</strong> invited to the channel
+ </>
+ )}
+ </span>
+ );
+ }
+ if (kickoffPreview) {
+ steps.push(<span>Switch posts the kickoff on your behalf to start the agents</span>);
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="rounded-lg border border-border p-5">
+ <h3 className="mb-3 text-sm font-semibold">What this creates</h3>
+ <ol className="space-y-2 text-sm">
+ {steps.map((step, i) => (
+ <li key={i} className="flex items-start gap-2">
+ <span className="flex size-5 shrink-0 items-center justify-center rounded border border-border text-xs">
+ {i + 1}
+ </span>
+ {step}
+ </li>
+ ))}
+ </ol>
+ <p className="mt-3 text-xs text-foreground-muted">Nothing else. One room, from one file.</p>
+ </div>
+
+ {parsed.usesCreator && (
+ <div className="rounded-lg border border-border p-4">
+ <h4 className="mb-1 text-xs font-semibold text-foreground-muted">You in this room</h4>
+ {creatorIdentity ? (
+ <p className="text-sm">
+ The server knows you{bridgeName ? ` on ${bridgeName}` : ''} as{' '}
+ <strong>{creatorIdentity}</strong> <Check className="inline size-3" />
+ </p>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <p className="text-sm text-amber-600 dark:text-amber-500">
+ This template puts you in the room, and the server does not know which account is
+ yours{bridgeName ? ` on ${bridgeName}` : ''}. Link it first; the room cannot be
+ created until then, or you would end up with a channel you cannot enter.
+ </p>
+ {onLinkAccount ? (
+ <Button variant="outline" size="sm" className="self-start" onClick={onLinkAccount}>
+ Link your account
+ </Button>
+ ) : (
+ <p className="text-xs text-foreground-muted">
+ Pick the messaging app first, then link your account there.
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
+ {kickoffPreview && (
+ <div className="rounded-lg border border-border p-4">
+ <h4 className="mb-1 text-xs font-semibold text-foreground-muted">Kickoff message</h4>
+ <p className="mb-2 text-xs text-foreground-muted">
+ Posted by Switch on your behalf: a one-line headline in the channel, with this text in
+ its thread. Each agent it mentions checks whether you may address it, the same as if you
+ had typed it, and answers in that thread.
+ </p>
+ <pre className="max-h-40 overflow-y-auto text-xs whitespace-pre-wrap text-foreground-muted">
+ {kickoffPreview}
+ </pre>
+ </div>
+ )}
+
+ <div className="rounded-lg border border-border p-4">
+ <h4 className="mb-1 text-xs font-semibold text-foreground-muted">Template source</h4>
+ <p className="text-sm font-medium">{sourceName ?? 'pasted template'}</p>
+ <p className="text-xs text-foreground-muted">
+ {sourceName ? 'file' : 'pasted'} · {parsed.params.length} param
+ {parsed.params.length !== 1 ? 's' : ''} · valid{' '}
+ <Check className="inline size-3 text-foreground-muted" />
+ </p>
+ </div>
+ </div>
+ );
+}
+
+// ── Inputs step ────────────────────────────────────────────────────────────
+
+function InputsStep({
+ parsed,
+ values,
+ onValuesChange,
+ fieldErrors,
+ lists,
+ onBack,
+ onSubmit,
+ sourceName,
+ createError,
+ editedAgents,
+ onEditedAgentsChange,
+ editedUsers,
+ onEditedUsersChange,
+ creatorIdentity,
+ bridgeName,
+ creatorBlocked,
+ onLinkAccount,
+ handoffBlocked,
+ onAllowHandoffs,
+ allowingHandoffs,
+}: {
+ parsed: ParsedTemplate;
+ values: Record<string, string | number | boolean>;
+ onValuesChange: (values: Record<string, string | number | boolean>) => void;
+ fieldErrors: Record<string, string>;
+ lists: EntityLists;
+ onBack: () => void;
+ onSubmit: () => void;
+ sourceName: string | null;
+ createError: string | null;
+ editedAgents: string[];
+ onEditedAgentsChange: (agents: string[]) => void;
+ editedUsers: string[];
+ onEditedUsersChange: (users: string[]) => void;
+ creatorIdentity: string | null;
+ bridgeName: string | null;
+ /** The template needs the creator's account on the bridge and none is linked. */
+ creatorBlocked: boolean;
+ onLinkAccount: (() => void) | null;
+ /** Agents in this room that will not hear each other. */
+ handoffBlocked: BlockedHandoff[];
+ /** Widen the blocked agents' policies so the hand-offs go through. */
+ onAllowHandoffs: () => void;
+ allowingHandoffs: boolean;
+}) {
+ // The template's fixed members are editable only when it has any: a
+ // template that names no agents gets no empty "Agents" section to puzzle
+ // over, the same way the params list only shows what is declared.
+ const showAgents = parsed.hardcodedAgents.length > 0 || editedAgents.length > 0;
+ const showUsers = parsed.hardcodedUsers.length > 0 || editedUsers.length > 0;
+
+ const handleChange = useCallback(
+ (name: string, value: string | number | boolean) => {
+ onValuesChange({ ...values, [name]: value });
+ },
+ [values, onValuesChange]
+ );
+
+ return (
+ <div className="flex gap-8">
+ {/* Left: form */}
+ <div className="flex min-w-0 flex-1 flex-col gap-4">
+ {createError && (
+ <Alert variant="destructive">
+ <AlertDescription>{createError}</AlertDescription>
+ </Alert>
+ )}
+ {handoffBlocked.length > 0 && (
+ <Alert>
+ <AlertDescription>
+ <div className="flex flex-col gap-2">
+ <span>
+ These agents will not hear each other:{' '}
+ {handoffBlocked.map((b) => `${b.to} ignores ${b.from}`).join(', ')}. An agent
+ created from the Console answers only its owner, so the hand-offs in this template
+ would bounce.
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start"
+ disabled={allowingHandoffs}
+ onClick={onAllowHandoffs}
+ >
+ {allowingHandoffs ? 'Updating…' : 'Let them hear each other'}
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+ )}
+ <FieldGroup>
+ {parsed.params.map((param) => (
+ <ParamField
+ key={param.name}
+ param={param}
+ value={values[param.name] ?? ''}
+ onChange={(v) => handleChange(param.name, v)}
+ error={fieldErrors[param.name] ?? null}
+ lists={lists}
+ />
+ ))}
+ {showAgents && (
+ <Field>
+ <div className="flex items-center justify-between gap-3">
+ <FieldLabel>Agents</FieldLabel>
+ {editedAgents.length > 0 && (
+ <span className="text-sm text-foreground-muted">{editedAgents.length} added</span>
+ )}
+ </div>
+ <AgentListField items={editedAgents} onChange={onEditedAgentsChange} lists={lists} />
+ <p className="mt-1 text-xs text-foreground-muted">
+ Agents the template puts in the room. Drop any the server does not have, or add
+ more.
+ </p>
+ </Field>
+ )}
+ {showUsers && (
+ <Field>
+ <div className="flex items-center justify-between gap-3">
+ <FieldLabel>Users</FieldLabel>
+ {editedUsers.length > 0 && (
+ <span className="text-sm text-foreground-muted">{editedUsers.length} added</span>
+ )}
+ </div>
+ <UserListField items={editedUsers} onChange={onEditedUsersChange} lists={lists} />
+ <p className="mt-1 text-xs text-foreground-muted">
+ People the template invites. A name the server has not seen is looked up in the
+ messaging app&apos;s directory when the room is created.
+ </p>
+ </Field>
+ )}
+ </FieldGroup>
+ <div className="flex flex-col gap-2 pt-2">
+ <Button variant="outline" className="w-full" onClick={onBack}>
+ Back to template
+ </Button>
+ <Button className="w-full" onClick={onSubmit} disabled={creatorBlocked}>
+ Create room
+ </Button>
+ {creatorBlocked && (
+ <p className="text-center text-xs text-foreground-muted">
+ Link your messaging account first, on the right.
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Right: summary */}
+ <div className="hidden w-80 shrink-0 lg:block">
+ <SummaryPanel
+ parsed={parsed}
+ values={values}
+ sourceName={sourceName}
+ creatorIdentity={creatorIdentity}
+ bridgeName={bridgeName}
+ onLinkAccount={onLinkAccount}
+ />
+ </div>
+ </div>
+ );
+}
+
+// ── Main view ──────────────────────────────────────────────────────────────
+
+function useServerId(): string {
+ return useParams('roomTemplateImport').params.serverId;
+}
+
+const TemplateImportTitlebar = observer(function TemplateImportTitlebar() {
+ return (
+ <ServerSectionTitlebar serverId={useServerId()} icon={FileText} label="Create from Template" />
+ );
+});
+
+const TemplateImportPanel = observer(function TemplateImportPanel() {
+ const serverId = useServerId();
+ const agents = useRemoteAgents(serverId);
+ const roomsQuery = useQuery({
+ queryKey: ['remote-rooms', serverId],
+ queryFn: () => rpc.switchServers.listRemoteRooms(serverId),
+ });
+ const bridgesQuery = useQuery({
+ queryKey: ['remote-bridges', serverId],
+ queryFn: () => rpc.switchServers.listRemoteBridges(serverId),
+ });
+ const knownUsersQuery = useQuery({
+ queryKey: ['remote-external-users', serverId],
+ queryFn: () => rpc.switchServers.listRemoteExternalUsers(serverId),
+ });
+ // Null from a server without the endpoint: the parser then falls back to
+ // its own shape check and the server validates on create.
+ const schemaQuery = useQuery({
+ queryKey: ['template-schema', serverId],
+ queryFn: () => rpc.switchServers.fetchTemplateSchema(serverId),
+ });
+ const { identities, refresh: refreshIdentities } = useMyIdentities(serverId);
+ const { showModal } = useModalContext();
+ const bridges = useMemo(() => bridgesQuery.data ?? [], [bridgesQuery.data]);
+ const templateSchema = schemaQuery.data ?? null;
+
+ const [step, setStep] = useState<Step>('source');
+ const [yamlText, setYamlText] = useState('');
+ const [parsed, setParsed] = useState<ParsedTemplate | null>(null);
+ const [parseError, setParseError] = useState<string | null>(null);
+ const [values, setValues] = useState<Record<string, string | number | boolean>>({});
+ const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
+ const [createError, setCreateError] = useState<string | null>(null);
+ const [sourceName, setSourceName] = useState<string | null>(null);
+ const [editedAgents, setEditedAgents] = useState<string[]>([]);
+ const [editedUsers, setEditedUsers] = useState<string[]>([]);
+
+ // The bridge the room will land on: what a bridge-typed param has been set
+ // to, else the one the template names, else the server's default, which is
+ // what the server itself falls back to. Following the param means the
+ // summary and the creator identity move with the pick.
+ const templateBridge = useMemo(() => {
+ const bridgeParam = parsed?.params.find((p) => p.type === 'bridge');
+ const picked = bridgeParam ? String(values[bridgeParam.name] ?? '') : '';
+ const named = picked !== '' ? picked : (parsed?.bridge ?? null);
+ if (named) {
+ return bridges.find((b) => b.displayName === named) ?? null;
+ }
+ return bridges.find((b) => b.isDefault) ?? (bridges.length === 1 ? bridges[0] : null);
+ }, [bridges, parsed, values]);
+
+ // How the signed-in user resolves on that bridge: what `{$creator}`
+ // becomes.
+ const creatorIdentity = useMemo(() => {
+ if (identities === null) return null;
+ if (templateBridge) {
+ return identities.find((i) => i.bridgeId === templateBridge.id)?.externalUsername ?? null;
+ }
+ return identities[0]?.externalUsername ?? null;
+ }, [identities, templateBridge]);
+
+ // The server refuses a template that needs the creator on the bridge when
+ // no account is linked; saying so here, with the fix one click away, beats
+ // a rejected create. Unknown identities (still loading) do not block.
+ const creatorBlocked =
+ parsed?.usesCreator === true && identities !== null && creatorIdentity === null;
+ const onLinkAccount = useMemo(() => {
+ if (!templateBridge) return null;
+ return () =>
+ showModal('claimIdentityModal', {
+ serverId,
+ bridgeId: templateBridge.id,
+ onSuccess: () => refreshIdentities(),
+ });
+ }, [templateBridge, serverId, showModal, refreshIdentities]);
+
+ // Every agent the room will hold: the template's fixed ones as edited, and
+ // whatever the agent-typed params have been set to.
+ const handoffBlocked = useMemo(() => {
+ if (!parsed) return [];
+ const names = new Set<string>(editedAgents);
+ for (const param of parsed.params) {
+ if (param.type === 'agent') {
+ const v = values[param.name];
+ if (typeof v === 'string' && v !== '') names.add(v);
+ }
+ }
+ const inRoom = (agents.data ?? []).filter((a) => names.has(a.name));
+ return blockedHandoffs(inRoom);
+ }, [parsed, editedAgents, values, agents.data]);
+
+ // The template implies these agents talk to each other, so the fix is
+ // offered here rather than found later in each agent's settings. Same
+ // owner gets "my agents" on every rule; a stranger is named outright.
+ const queryClient = useQueryClient();
+ const [allowingHandoffs, setAllowingHandoffs] = useState(false);
+ const allowHandoffs = useCallback(async () => {
+ const byName = new Map((agents.data ?? []).map((a) => [a.name, a]));
+ setAllowingHandoffs(true);
+ try {
+ const targets = new Set(handoffBlocked.map((b) => b.to));
+ for (const targetName of targets) {
+ const target = byName.get(targetName);
+ if (!target) continue;
+ const sources = handoffBlocked
+ .filter((b) => b.to === targetName)
+ .map((b) => byName.get(b.from))
+ .filter((a): a is NonNullable<typeof a> => a !== undefined);
+ const rules = (target.addressingPolicy?.rules ?? []).map((rule) => {
+ const next = { ...rule };
+ for (const source of sources) {
+ if (target.ownerId !== null && source.ownerId === target.ownerId) {
+ next.owner_agents = true;
+ } else if (next.agents !== '*' && !next.agents.includes(source.id)) {
+ next.agents = [...next.agents, source.id];
+ }
+ }
+ return next;
+ });
+ await rpc.switchServers.updateAddressingPolicy({
+ serverId,
+ agentId: target.id,
+ policy: { rules },
+ });
+ }
+ await queryClient.invalidateQueries({ queryKey: remoteAgentsQueryKey(serverId) });
+ } catch (e) {
+ toast.error(failureText(e, 'Could not update the agents.'));
+ } finally {
+ setAllowingHandoffs(false);
+ }
+ }, [agents.data, handoffBlocked, serverId, queryClient]);
+
+ const lists = useMemo(
+ (): EntityLists => ({
+ serverId,
+ agents: agents.data ?? [],
+ agentsLoading: agents.isLoading,
+ rooms: roomsQuery.data ?? [],
+ roomsLoading: roomsQuery.isLoading,
+ bridges,
+ identities,
+ knownUsers: knownUsersQuery.data ?? [],
+ bridgeId: templateBridge?.id ?? null,
+ }),
+ [
+ serverId,
+ agents.data,
+ agents.isLoading,
+ roomsQuery.data,
+ roomsQuery.isLoading,
+ bridges,
+ identities,
+ knownUsersQuery.data,
+ templateBridge,
+ ]
+ );
+
+ const validateInputs = useCallback((): boolean => {
+ if (!parsed) return false;
+ const errors: Record<string, string> = {};
+ for (const param of parsed.params) {
+ const val = values[param.name];
+ if (param.default === null) {
+ if (val === '' || val === undefined) {
+ errors[param.name] = 'This field is required';
+ }
+ }
+ if (param.type === 'number' && val !== '' && val !== undefined) {
+ if (typeof val === 'string' && isNaN(Number(val))) {
+ errors[param.name] = 'Must be a number';
+ }
+ }
+ }
+ setFieldErrors(errors);
+ return Object.keys(errors).length === 0;
+ }, [parsed, values]);
+
+ const handleCreate = useCallback(
+ async (template?: ParsedTemplate) => {
+ const t = template ?? parsed;
+ if (!t) return;
+
+ if (t.params.length > 0 && !validateInputs()) return;
+
+ setStep('creating');
+ setCreateError(null);
+
+ try {
+ const inputs: Record<string, string | number | boolean> = {};
+ for (const param of t.params) {
+ const val = values[param.name];
+ if (val !== '' && val !== undefined) {
+ if (param.type === 'number') {
+ inputs[param.name] = Number(val);
+ } else {
+ inputs[param.name] = val;
+ }
+ }
+ }
+
+ // Rewrite YAML with the user's edited agents/users lists. Entries
+ // still carrying `{...}` (params and `{$creator}`) are not editable
+ // in the form and must survive the rewrite for the server to resolve.
+ const interpolatedAgents = t.agents.filter((a) => /\{[^}]+\}/.test(a));
+ const finalAgents = [...interpolatedAgents, ...editedAgents];
+ const interpolatedUsers = t.users.filter((u) => /\{[^}]+\}/.test(u));
+ const finalUsers = [...interpolatedUsers, ...editedUsers];
+ const finalYaml = await rpc.roomTemplates.rewriteYaml({
+ yamlText,
+ agents: finalAgents,
+ users: finalUsers,
+ });
+
+ const result = await rpc.switchServers.createRoomFromTemplate(serverId, finalYaml, inputs);
+ await refreshSidebarRoomState(true);
+ if (result.failedAttachments.length > 0) {
+ const names = result.failedAttachments.map((f) => `${f.id} (${f.error})`).join(', ');
+ toast.warning('Room created, but some items could not be added', {
+ description: names,
+ duration: 8000,
+ });
+ }
+ appState.navigation.navigate('room', { roomId: result.roomId });
+ } catch (e) {
+ const serverDetail =
+ e instanceof RpcError && e.code === 'GatewayError' ? e.stringField('detail') : undefined;
+ const message =
+ serverDetail ?? failureText(e, 'Could not create the room from this template.');
+ const paramMatch = message.match(/param(?:\(s\))?:?\s*['"]?(\w+)/i);
+ if (paramMatch && t.params.some((p) => p.name === paramMatch[1])) {
+ setFieldErrors({ [paramMatch[1]]: message });
+ setStep('inputs');
+ } else {
+ setCreateError(message);
+ setStep(t.params.length > 0 ? 'inputs' : 'source');
+ }
+ }
+ },
+ [parsed, values, serverId, yamlText, validateInputs, editedAgents, editedUsers]
+ );
+
+ const handleParseAndAdvance = useCallback(async () => {
+ setParseError(null);
+ try {
+ const result = await rpc.roomTemplates.parse({
+ yamlText,
+ schema: templateSchema ?? undefined,
+ });
+ setParsed(result);
+
+ const defaults: Record<string, string | number | boolean> = {};
+ for (const param of result.params) {
+ if (param.default !== null) {
+ defaults[param.name] = param.default;
+ } else if (param.type === 'boolean') {
+ defaults[param.name] = false;
+ } else {
+ defaults[param.name] = '';
+ }
+ }
+ setValues((prev) => ({ ...defaults, ...prev }));
+ setEditedAgents(result.hardcodedAgents);
+ setEditedUsers(result.hardcodedUsers);
+ setFieldErrors({});
+ setCreateError(null);
+
+ const hasForm =
+ result.params.length > 0 ||
+ result.hardcodedAgents.length > 0 ||
+ result.hardcodedUsers.length > 0;
+ if (!hasForm) {
+ await handleCreate(result);
+ } else {
+ setStep('inputs');
+ }
+ } catch (e) {
+ setParseError(failureText(e, 'Could not parse this template.'));
+ }
+ }, [yamlText, handleCreate, templateSchema]);
+
+ const stepNumber = step === 'source' ? 1 : 2;
+ const totalSteps = 2;
+
+ const subtitle =
+ step === 'source'
+ ? 'Paste a room template or pick a YAML file.'
+ : `${sourceName ?? 'template'}: ${parsed?.params.length ?? 0} input${(parsed?.params.length ?? 0) !== 1 ? 's' : ''}. The room is created only when you hit Create.`;
+
+ return (
+ <ServerPage
+ title="Create from template"
+ description={subtitle}
+ action={
+ <span className="text-xs text-foreground-muted">
+ Step {stepNumber} of {totalSteps}
+ </span>
+ }
+ >
+ {step === 'source' && (
+ <SourceStep
+ yamlText={yamlText}
+ onYamlChange={setYamlText}
+ parseError={parseError}
+ onNext={handleParseAndAdvance}
+ onFileSelect={setSourceName}
+ />
+ )}
+
+ {step === 'inputs' && parsed && (
+ <>
+ {parsed.warnings.map((w, i) => (
+ <Alert key={i} className="mb-4">
+ <AlertDescription>{w}</AlertDescription>
+ </Alert>
+ ))}
+ <InputsStep
+ parsed={parsed}
+ values={values}
+ onValuesChange={setValues}
+ fieldErrors={fieldErrors}
+ lists={lists}
+ onBack={() => setStep('source')}
+ onSubmit={() => handleCreate()}
+ sourceName={sourceName}
+ createError={createError}
+ editedAgents={editedAgents}
+ onEditedAgentsChange={setEditedAgents}
+ editedUsers={editedUsers}
+ onEditedUsersChange={setEditedUsers}
+ creatorIdentity={creatorIdentity}
+ bridgeName={templateBridge?.displayName ?? parsed.bridge}
+ creatorBlocked={creatorBlocked}
+ onLinkAccount={onLinkAccount}
+ handoffBlocked={handoffBlocked}
+ onAllowHandoffs={() => void allowHandoffs()}
+ allowingHandoffs={allowingHandoffs}
+ />
+ </>
+ )}
+
+ {step === 'creating' && (
+ <div className="flex items-center justify-center py-12">
+ <Loader2 className="size-6 animate-spin text-foreground-passive" />
+ <span className="ml-2 text-sm text-foreground-passive">Creating room…</span>
+ </div>
+ )}
+ </ServerPage>
+ );
+});
+
+export const roomTemplateImportView = {
+ WrapView: ({ children }: { children: React.ReactNode; serverId: string }) => <>{children}</>,
+ TitlebarSlot: TemplateImportTitlebar,
+ MainPanel: TemplateImportPanel,
+ canActivate: (params: unknown): GuardResult => {
+ const serverId =
+ typeof params === 'object' && params !== null
+ ? (params as { serverId?: unknown }).serverId
+ : undefined;
+ if (typeof serverId !== 'string') return { ok: false, redirect: 'home' };
+ return { ok: true };
+ },
+} satisfies ViewDefinition<{ serverId: string }>;
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
index 90cd39f8a..40a5ea955 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
@@ -1,4 +1,4 @@
-import { Bot, DoorOpen, House } from 'lucide-react';
+import { Bot, DoorOpen, FileText, House } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { switchServersStore } from '@renderer/features/switch-servers/switch-servers-store';
import { isCurrentView, useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';
@@ -18,6 +18,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
const { params: homeParams } = useParams('server');
const { params: agentsParams } = useParams('serverAgents');
const { params: roomsParams } = useParams('serverRooms');
+ const { params: templatesParams } = useParams('roomTemplateImport');
const active = switchServersStore.activeServer;
if (!active) return null;
@@ -25,6 +26,7 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
{ view: 'server', icon: House, label: 'Home', params: homeParams },
{ view: 'serverAgents', icon: Bot, label: 'Your Agents', params: agentsParams },
{ view: 'serverRooms', icon: DoorOpen, label: 'Your Rooms', params: roomsParams },
+ { view: 'roomTemplateImport', icon: FileText, label: 'Templates', params: templatesParams },
] as const;
return (
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
index 0e7a58514..e4a435895 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentToRoomsModal.tsx
@@ -1,21 +1,12 @@
-import { Hash, Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
-import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
+import { ChosenRoomTile, RoomPickerRow } from '@renderer/lib/components/room-picker';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { Button } from '@renderer/lib/ui/button';
-import {
- Combobox,
- ComboboxContent,
- ComboboxEmpty,
- ComboboxInput,
- ComboboxItem,
- ComboboxList,
-} from '@renderer/lib/ui/combobox';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
DialogContentArea,
@@ -34,20 +25,6 @@ type Props = BaseModalProps<void> & {
/** A room the agent can be put in: one on its own server it is not already in. */
type Candidate = { id: string; name: string; bridgeType: string | null };
-/** Where a room's conversation actually happens, for the right of its row. */
-function whereLabel(bridgeType: string | null): string {
- return bridgeType ? bridgePlatformLabel(bridgeType) : 'Switch only';
-}
-
-/** The mark of the app a room is bridged to, or a plain channel mark when it
- * lives on Switch alone. */
-function RoomMark({ bridgeType, size }: { bridgeType: string | null; size: number }) {
- if (!hasBridgeIcon(bridgeType)) {
- return <Hash className="size-4 shrink-0 text-foreground-muted" />;
- }
- return <BridgeIcon bridgeType={bridgeType} size={size} />;
-}
-
/**
* Puts one agent into rooms — the agent's side of `AddAgentsToRoomModal`, which
* puts agents into one room.
@@ -139,43 +116,18 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
</div>
)}
- <Combobox
+ <PickerCombobox
items={candidates}
- value={null}
- onValueChange={(next: Candidate | null) => {
- if (next) setSelected((current) => [...current, next]);
+ onPick={(next) => {
+ setSelected((current) => [...current, next]);
setError(null);
}}
- isItemEqualToValue={(a: Candidate, b: Candidate) => a.id === b.id}
- filter={(item: Candidate, query) =>
- item.name.toLowerCase().includes(query.toLowerCase())
- }
- autoHighlight
- >
- {/* The search box is the control rather than something a button
- has to open: putting an agent in several rooms at once is the
- reason this dialog exists. */}
- <ComboboxInput
- showTrigger={false}
- disabled={nothingToAdd}
- placeholder="Search rooms to add..."
- leftAddon={<Search className="size-3.5 text-foreground-muted" />}
- />
- <ComboboxContent className="min-w-(--anchor-width)">
- <ComboboxList>
- {(item: Candidate) => (
- <ComboboxItem key={item.id} value={item} showCheck={false}>
- <RoomMark bridgeType={item.bridgeType} size={16} />
- <span className="min-w-0 flex-1 truncate">{item.name}</span>
- <span className="shrink-0 text-xs text-foreground-muted">
- {whereLabel(item.bridgeType)}
- </span>
- </ComboboxItem>
- )}
- </ComboboxList>
- <ComboboxEmpty>No rooms found</ComboboxEmpty>
- </ComboboxContent>
- </Combobox>
+ searchText={(item) => item.name}
+ renderItem={(item) => <RoomPickerRow room={item} />}
+ disabled={nothingToAdd}
+ placeholder="Search rooms to add..."
+ emptyText="No rooms found"
+ />
{membershipUnknown && (
<p className="mt-1 text-xs text-foreground-warning">
Which rooms {agentName} is already in could not be read, so every room on the server
@@ -206,29 +158,3 @@ export const AddAgentToRoomsModal = observer(function AddAgentToRoomsModal({
</>
);
});
-
-/** A room already chosen, with the way to take it back out. */
-function ChosenRoomTile({ room, onRemove }: { room: Candidate; onRemove: () => void }) {
- return (
- // `--fill` rather than `--surface-2`: in dark mode that surface is the
- // dialog's own background, so a tile drawn in it was a tile nobody could
- // see.
- <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
- <RoomMark bridgeType={room.bridgeType} size={22} />
- <div className="flex min-w-0 flex-col">
- <span className="truncate text-sm text-foreground">{room.name}</span>
- <span className="truncate text-xs text-foreground-muted">
- {whereLabel(room.bridgeType)}
- </span>
- </div>
- <button
- type="button"
- aria-label={`Remove ${room.name}`}
- onClick={onRemove}
- className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"
- >
- <X className="size-3.5" />
- </button>
- </div>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
index 1fed4f6f5..6e73e9157 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-rooms/AddAgentsToRoomModal.tsx
@@ -1,23 +1,15 @@
-import { Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { switchRoomsStore } from '@renderer/features/switch-servers/switch-rooms-store';
-import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
+import { AgentPickerRow, ChosenAgentTile } from '@renderer/lib/components/agent-picker';
+import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { useRemoteAgents } from '@renderer/lib/stores/use-remote-agents';
import { Button } from '@renderer/lib/ui/button';
-import {
- Combobox,
- ComboboxContent,
- ComboboxEmpty,
- ComboboxInput,
- ComboboxItem,
- ComboboxList,
-} from '@renderer/lib/ui/combobox';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
DialogContentArea,
@@ -124,6 +116,7 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
<ChosenAgentTile
key={agent.id}
agent={agent}
+ subtitle={agentProviderLabel(agent.providerId)}
onRemove={() =>
setSelected((current) => current.filter((a) => a.id !== agent.id))
}
@@ -132,43 +125,20 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
</div>
)}
- <Combobox
+ <PickerCombobox
items={candidates}
- value={null}
- onValueChange={(next: Candidate | null) => {
- if (next) setSelected((current) => [...current, next]);
+ onPick={(next) => {
+ setSelected((current) => [...current, next]);
setError(null);
}}
- isItemEqualToValue={(a: Candidate, b: Candidate) => a.id === b.id}
- filter={(item: Candidate, query) =>
- item.name.toLowerCase().includes(query.toLowerCase())
- }
- autoHighlight
- >
- {/* The search box is the control rather than something a button
- has to open: putting several agents in a room at once is the
- reason this dialog exists. */}
- <ComboboxInput
- showTrigger={false}
- disabled={nothingToAdd}
- placeholder="Search agents to add..."
- leftAddon={<Search className="size-3.5 text-foreground-muted" />}
- />
- <ComboboxContent className="min-w-(--anchor-width)">
- <ComboboxList>
- {(item: Candidate) => (
- <ComboboxItem key={item.id} value={item} showCheck={false}>
- <AgentAvatar name={item.name} iconUrl={item.iconUrl} size={22} />
- <span className="min-w-0 flex-1 truncate">{item.name}</span>
- <span className="shrink-0 text-xs text-foreground-muted">
- {agentProviderLabel(item.providerId)}
- </span>
- </ComboboxItem>
- )}
- </ComboboxList>
- <ComboboxEmpty>No agents found</ComboboxEmpty>
- </ComboboxContent>
- </Combobox>
+ searchText={(item) => item.name}
+ renderItem={(item) => (
+ <AgentPickerRow agent={item} subtitle={agentProviderLabel(item.providerId)} />
+ )}
+ disabled={nothingToAdd}
+ placeholder="Search agents to add..."
+ emptyText="No agents found"
+ />
{nothingToAdd && (
<p className="mt-1 text-xs text-foreground-muted">
Every agent on this copy of Switch Console is already in the room. Agents registered
@@ -194,29 +164,3 @@ export const AddAgentsToRoomModal = observer(function AddAgentsToRoomModal({
</>
);
});
-
-/** An agent already chosen, with the way to take it back out. */
-function ChosenAgentTile({ agent, onRemove }: { agent: Candidate; onRemove: () => void }) {
- return (
- // `--fill` rather than `--surface-2`: in dark mode that surface is the
- // dialog's own background, so a tile drawn in it was a tile nobody could
- // see.
- <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
- <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />
- <div className="flex min-w-0 flex-col">
- <span className="truncate text-sm text-foreground">{agent.name}</span>
- <span className="truncate text-xs text-foreground-muted">
- {agentProviderLabel(agent.providerId)}
- </span>
- </div>
- <button
- type="button"
- aria-label={`Remove ${agent.name}`}
- onClick={onRemove}
- className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"
- >
- <X className="size-3.5" />
- </button>
- </div>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
index 4ea49105b..759887001 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/CreateRoomModal.tsx
@@ -1,27 +1,21 @@
import { useQuery } from '@tanstack/react-query';
-import { MessageSquare, Search, X } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useCallback, useState } from 'react';
import { agentsStore } from '@renderer/features/locations/stores/agents-store';
import { openRoomView } from '@renderer/features/sidebar/sidebar-room-grouping';
import { refreshSidebarRoomState } from '@renderer/features/sidebar/sidebar-tree-data';
-import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
-import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
-import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
-import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import {
+ AgentPickerRow,
+ ChosenAgentTile,
+ agentProviderLabelFor,
+} from '@renderer/lib/components/agent-picker';
+import { BridgeTile, bridgeUnusableReason } from '@renderer/lib/components/bridge-tile';
+import { PickerCombobox } from '@renderer/lib/components/picker-combobox';
import { failureText } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { type BaseModalProps, useModalContext } from '@renderer/lib/modal/modal-provider';
import { sidebarStore } from '@renderer/lib/stores/app-state';
import { Button } from '@renderer/lib/ui/button';
-import {
- Combobox,
- ComboboxContent,
- ComboboxEmpty,
- ComboboxInput,
- ComboboxItem,
- ComboboxList,
-} from '@renderer/lib/ui/combobox';
import { ConfirmButton } from '@renderer/lib/ui/confirm-button';
import {
DialogContentArea,
@@ -32,12 +26,7 @@ import {
import { DisclosureRow } from '@renderer/lib/ui/disclosure-row';
import { Input } from '@renderer/lib/ui/input';
import { Textarea } from '@renderer/lib/ui/textarea';
-import { cn } from '@renderer/utils/utils';
-import type {
- LinkedIdentity,
- RemoteAgentSummary,
- RemoteBridge,
-} from '@shared/core/switch-servers/switch-servers';
+import type { RemoteAgentSummary } from '@shared/core/switch-servers/switch-servers';
import { switchServersStore } from './switch-servers-store';
import { useMyIdentities } from './use-my-identities';
@@ -215,6 +204,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
bridge={bridge}
identity={identities?.find((i) => i.bridgeId === bridge.id) ?? null}
identitiesKnown={identities !== null}
+ unusable={bridgeUnusableReason(bridge, { needsChannelCreation: true })}
selected={selectedBridge?.id === bridge.id}
onSelect={() => setBridgeId(bridge.id)}
/>
@@ -296,7 +286,7 @@ export const CreateRoomModal = observer(function CreateRoomModal({
<ChosenAgentTile
key={agent.id}
agent={agent}
- serverId={serverId}
+ subtitle={agentProviderLabelFor(agent.id, serverId)}
onRemove={() =>
setAgents((current) => current.filter((a) => a.id !== agent.id))
}
@@ -305,43 +295,17 @@ export const CreateRoomModal = observer(function CreateRoomModal({
</div>
)}
- <Combobox
+ <PickerCombobox
items={invitableAgents.filter((a) => !agents.some((s) => s.id === a.id))}
- value={null}
- onValueChange={(next: RemoteAgentSummary | null) => {
- if (next) setAgents((current) => [...current, next]);
- }}
- isItemEqualToValue={(a: RemoteAgentSummary, b: RemoteAgentSummary) => a.id === b.id}
- filter={(item: RemoteAgentSummary, query) =>
- item.name.toLowerCase().includes(query.toLowerCase())
- }
- autoHighlight
- >
- {/* The search box is the control, rather than a button that opens
- one: adding several agents is the normal case, and a picker
- that has to be reopened per agent makes the normal case the
- laborious one. */}
- <ComboboxInput
- showTrigger={false}
- disabled={agentsQuery.isLoading}
- placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}
- leftAddon={<Search className="size-3.5 text-foreground-muted" />}
- />
- <ComboboxContent className="min-w-(--anchor-width)">
- <ComboboxList>
- {(item: RemoteAgentSummary) => (
- <ComboboxItem key={item.id} value={item} showCheck={false}>
- <AgentAvatar name={item.name} iconUrl={item.iconUrl} size={22} />
- <span className="min-w-0 flex-1 truncate">{item.name}</span>
- <span className="shrink-0 text-xs text-foreground-muted">
- {providerLabelFor(item.id, serverId)}
- </span>
- </ComboboxItem>
- )}
- </ComboboxList>
- <ComboboxEmpty>No agents found</ComboboxEmpty>
- </ComboboxContent>
- </Combobox>
+ onPick={(next) => setAgents((current) => [...current, next])}
+ searchText={(item) => item.name}
+ renderItem={(item) => (
+ <AgentPickerRow agent={item} subtitle={agentProviderLabelFor(item.id, serverId)} />
+ )}
+ disabled={agentsQuery.isLoading}
+ placeholder={agentsQuery.isLoading ? 'Loading agents…' : 'Search agents to add...'}
+ emptyText="No agents found"
+ />
<span className="text-xs text-foreground-muted">
Optional — agents can be added to the room later.
@@ -391,130 +355,6 @@ function FormRow({ label, children }: { label: string; children: React.ReactNode
);
}
-/**
- * One messaging app to put the room in, with the account the user has on it.
- *
- * Every connected app is drawn, including the ones that cannot back a new room
- * — those are disabled and say why. Omitting them would be quieter and worse:
- * the user knows their server has Telegram on it, and a grid that simply does
- * not mention it reads as a bug rather than as a refusal.
- */
-function BridgeTile({
- bridge,
- identity,
- identitiesKnown,
- selected,
- onSelect,
-}: {
- bridge: RemoteBridge;
- identity: LinkedIdentity | null;
- identitiesKnown: boolean;
- selected: boolean;
- onSelect: () => void;
-}) {
- const platform = bridgePlatformLabel(bridge.type);
- const unusable =
- bridge.status !== 'active'
- ? 'Not running'
- : !bridge.channelCreationSupported
- ? `${platform} cannot create channels`
- : !bridge.canCreateChannels
- ? 'Channel creation is off'
- : null;
-
- return (
- <button
- type="button"
- disabled={unusable !== null}
- aria-pressed={selected}
- onClick={onSelect}
- className={cn(
- 'flex cursor-pointer items-center gap-2.5 rounded-[10px] border p-3 text-left transition-colors',
- // Overlay tokens rather than `background-1`, which in dark mode is
- // exactly the dialog's own surface — the hover was being drawn, in the
- // colour of the thing behind it.
- selected ? 'border-foreground bg-[var(--sel)]' : 'border-border hover:bg-[var(--sel-soft)]',
- unusable !== null && 'cursor-not-allowed opacity-50 hover:bg-transparent'
- )}
- >
- <span className="flex size-6 shrink-0 items-center justify-center">
- {hasBridgeIcon(bridge.type) ? (
- <BridgeIcon bridgeType={bridge.type} size={20} />
- ) : (
- <MessageSquare className="size-5 text-foreground-muted" />
- )}
- </span>
- <span className="flex min-w-0 flex-col">
- <span className="truncate text-sm text-foreground">{bridge.displayName}</span>
- {/* Three different things, never conflated: why this app cannot be
- used, which account on it is you, or that Switch cannot tell. */}
- {unusable !== null ? (
- <span className="truncate text-xs text-foreground-muted">{unusable}</span>
- ) : !identitiesKnown ? null : identity === null ? (
- <span className="truncate text-xs text-amber-600 dark:text-amber-500">
- No account linked
- </span>
- ) : (
- <span className="truncate text-xs text-foreground-muted">{handleOf(identity)}</span>
- )}
- </span>
- </button>
- );
-}
-
-/** An agent already added to the room, with the way to take it back out. */
-function ChosenAgentTile({
- agent,
- serverId,
- onRemove,
-}: {
- agent: RemoteAgentSummary;
- serverId: string;
- onRemove: () => void;
-}) {
- return (
- // `--fill` rather than `--surface-2`: in dark mode that surface is the
- // dialog's own background, so a tile drawn in it was a tile nobody could
- // see.
- <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
- <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />
- <div className="flex min-w-0 flex-col">
- <span className="truncate text-sm text-foreground">{agent.name}</span>
- <span className="truncate text-xs text-foreground-muted">
- {providerLabelFor(agent.id, serverId)}
- </span>
- </div>
- <button
- type="button"
- aria-label={`Remove ${agent.name}`}
- onClick={onRemove}
- className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"
- >
- <X className="size-3.5" />
- </button>
- </div>
- );
-}
-
-/** This install's record of a Switch agent, which is where its provider is
- * known — the server's summary says what type it is, not what runs it here. */
-function localAgentFor(switchAgentId: string, serverId: string) {
- return (
- agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null
- );
-}
-
-function providerLabelFor(switchAgentId: string, serverId: string): string {
- return agentProviderLabel(localAgentFor(switchAgentId, serverId)?.providerId);
-}
-
-/** The claimed account as a handle. Platforms differ on whether the username
- * they report already carries the sigil, so add one only when it is missing. */
-function handleOf(identity: LinkedIdentity): string {
- const username = identity.externalUsername;
- return username.startsWith('@') ? username : `@${username}`;
-}
-
/** Turn a failed create into something the user can act on. */
function messageFor(result: { kind: string; message?: string }): string {
switch (result.kind) {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
index dfcc4fb0f..44e5ec903 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/addressing-policy-editor.tsx
@@ -27,6 +27,7 @@ const EMPTY_RULE: AddressingRule = {
agents: '*',
owner: false,
owner_agents: false,
+ platform: false,
};
/**
@@ -223,6 +224,20 @@ export function AddressingPolicyEditor({
disabled={disabled}
onChange={(agents) => updateRule(index, withAgents(rule, agents))}
/>
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ className="size-4 rounded border-border"
+ checked={rule.platform === true}
+ disabled={disabled}
+ onChange={(e) => updateRule(index, { ...rule, platform: e.target.checked })}
+ />
+ <span>Switch itself</span>
+ <span className="text-xs text-foreground-muted">
+ Let the platform address this agent on its own account. A message it sends for a
+ person, such as a template kickoff, is judged as that person and needs no opt-in.
+ </span>
+ </label>
{deadRuleReason(rule) !== null && (
<p className="text-xs text-destructive">{deadRuleReason(rule)}</p>
)}
@@ -315,6 +330,11 @@ function RuleSummary({
<span className="font-medium">Agents:</span>{' '}
{dimLabel(agentsOf(rule), [MY_AGENTS_OPTION, ...agents])}
</span>
+ {rule.platform === true && (
+ <span>
+ <span className="font-medium">Switch itself:</span> allowed
+ </span>
+ )}
</div>
{dead !== null && <span className="text-xs text-destructive">{dead}</span>}
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
new file mode 100644
index 000000000..38e8388d1
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/agent-picker.tsx
@@ -0,0 +1,56 @@
+import { agentsStore } from '@renderer/features/locations/stores/agents-store';
+import { AgentAvatar } from '@renderer/lib/components/agent-avatar';
+import { agentProviderLabel } from '@renderer/lib/components/agent-mark';
+import { ChosenTile } from '@renderer/lib/components/chosen-tile';
+
+/** The least an agent row or tile needs to draw itself. */
+export type AgentPick = {
+ id: string;
+ name: string;
+ iconUrl: string | null;
+};
+
+/**
+ * What runs an agent, as this install knows it. The server's summary says what
+ * type an agent is, not what provider drives it here; an agent registered from
+ * another Switch Console has no local record and reads as a plain "Agent".
+ */
+export function agentProviderLabelFor(switchAgentId: string, serverId: string): string {
+ const local =
+ agentsStore.agentsOnServer(serverId).find((a) => a.switchAgentId === switchAgentId) ?? null;
+ return agentProviderLabel(local?.providerId);
+}
+
+/** One agent in a picker list: avatar, name, and what runs it. */
+export function AgentPickerRow({ agent, subtitle }: { agent: AgentPick; subtitle: string }) {
+ return (
+ <>
+ <AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={22} />
+ <span className="min-w-0 flex-1 truncate">{agent.name}</span>
+ <span className="shrink-0 text-xs text-foreground-muted">{subtitle}</span>
+ </>
+ );
+}
+
+/** An agent already chosen, with the way to take it back out. */
+export function ChosenAgentTile({
+ agent,
+ subtitle,
+ subtitleTone,
+ onRemove,
+}: {
+ agent: AgentPick;
+ subtitle: string;
+ subtitleTone?: 'muted' | 'warning';
+ onRemove: () => void;
+}) {
+ return (
+ <ChosenTile
+ mark={<AgentAvatar name={agent.name} iconUrl={agent.iconUrl} size={26} />}
+ title={agent.name}
+ subtitle={subtitle}
+ subtitleTone={subtitleTone}
+ onRemove={onRemove}
+ />
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-tile.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-tile.tsx
new file mode 100644
index 000000000..cb662c9cc
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/bridge-tile.tsx
@@ -0,0 +1,96 @@
+import { MessageSquare } from 'lucide-react';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { cn } from '@renderer/utils/utils';
+import type { LinkedIdentity, RemoteBridge } from '@shared/core/switch-servers/switch-servers';
+
+/** The claimed account as a handle. Platforms differ on whether the username
+ * they report already carries the sigil, so add one only when it is missing. */
+export function handleOf(identity: LinkedIdentity): string {
+ const username = identity.externalUsername;
+ return username.startsWith('@') ? username : `@${username}`;
+}
+
+/**
+ * Why a bridge cannot back a new room right now, or null when it can.
+ *
+ * `needsChannelCreation` is for surfaces that will create a channel on the
+ * bridge; a surface that only names the bridge (a template param) needs it
+ * running and nothing more.
+ */
+export function bridgeUnusableReason(
+ bridge: RemoteBridge,
+ { needsChannelCreation }: { needsChannelCreation: boolean }
+): string | null {
+ if (bridge.status !== 'active') return 'Not running';
+ if (!needsChannelCreation) return null;
+ const platform = bridgePlatformLabel(bridge.type);
+ if (!bridge.channelCreationSupported) return `${platform} cannot create channels`;
+ if (!bridge.canCreateChannels) return 'Channel creation is off';
+ return null;
+}
+
+/**
+ * One messaging app to choose from, with the account on it that is you.
+ *
+ * An unusable app is shown but not selectable, and says which of the ways it
+ * is unusable: an app that is simply absent from the grid explains nothing,
+ * and the user goes looking for it.
+ */
+export function BridgeTile({
+ bridge,
+ identity,
+ identitiesKnown,
+ unusable,
+ selected,
+ onSelect,
+}: {
+ bridge: RemoteBridge;
+ identity: LinkedIdentity | null;
+ /** False while the identity list has not arrived: "no account linked" is
+ * only true once the list says so. */
+ identitiesKnown: boolean;
+ /** From `bridgeUnusableReason`, or null when selectable. */
+ unusable: string | null;
+ selected: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ disabled={unusable !== null}
+ aria-pressed={selected}
+ onClick={onSelect}
+ className={cn(
+ 'flex cursor-pointer items-center gap-2.5 rounded-[10px] border p-3 text-left transition-colors',
+ // Overlay tokens rather than `background-1`, which in dark mode is
+ // exactly the dialog's own surface: the hover was being drawn, in the
+ // colour of the thing behind it.
+ selected ? 'border-foreground bg-[var(--sel)]' : 'border-border hover:bg-[var(--sel-soft)]',
+ unusable !== null && 'cursor-not-allowed opacity-50 hover:bg-transparent'
+ )}
+ >
+ <span className="flex size-6 shrink-0 items-center justify-center">
+ {hasBridgeIcon(bridge.type) ? (
+ <BridgeIcon bridgeType={bridge.type} size={20} />
+ ) : (
+ <MessageSquare className="size-5 text-foreground-muted" />
+ )}
+ </span>
+ <span className="flex min-w-0 flex-col">
+ <span className="truncate text-sm text-foreground">{bridge.displayName}</span>
+ {/* Three different things, never conflated: why this app cannot be
+ used, which account on it is you, or that Switch cannot tell. */}
+ {unusable !== null ? (
+ <span className="truncate text-xs text-foreground-muted">{unusable}</span>
+ ) : !identitiesKnown ? null : identity === null ? (
+ <span className="truncate text-xs text-amber-600 dark:text-amber-500">
+ No account linked
+ </span>
+ ) : (
+ <span className="truncate text-xs text-foreground-muted">{handleOf(identity)}</span>
+ )}
+ </span>
+ </button>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/chosen-tile.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/chosen-tile.tsx
new file mode 100644
index 000000000..4dafd7a57
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/chosen-tile.tsx
@@ -0,0 +1,53 @@
+import { X } from 'lucide-react';
+import { cn } from '@renderer/utils/utils';
+
+/**
+ * Something already picked, with the way to take it back out: a mark, a name,
+ * a line under it, and a remove button on hover. One shape behind every
+ * "chosen" grid, so the grids match and a new kind of pick gets it for free.
+ */
+export function ChosenTile({
+ mark,
+ title,
+ subtitle,
+ subtitleTone = 'muted',
+ onRemove,
+}: {
+ mark: React.ReactNode;
+ title: string;
+ subtitle: string;
+ /** `warning` for a subtitle that says something is off with the pick, such
+ * as a name the server does not know. */
+ subtitleTone?: 'muted' | 'warning';
+ onRemove: () => void;
+}) {
+ return (
+ // `--fill` rather than `--surface-2`: in dark mode that surface is the
+ // dialog's own background, so a tile drawn in it was a tile nobody could
+ // see.
+ <div className="group relative flex flex-col gap-2 rounded-[10px] bg-[var(--fill)] p-3">
+ {mark}
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate text-sm text-foreground">{title}</span>
+ <span
+ className={cn(
+ 'truncate text-xs',
+ subtitleTone === 'warning'
+ ? 'text-amber-600 dark:text-amber-500'
+ : 'text-foreground-muted'
+ )}
+ >
+ {subtitle}
+ </span>
+ </div>
+ <button
+ type="button"
+ aria-label={`Remove ${title}`}
+ onClick={onRemove}
+ className="absolute top-1.5 right-1.5 flex size-5 cursor-pointer items-center justify-center rounded-md text-foreground-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-[var(--fill-2)] hover:text-foreground focus-visible:opacity-100"
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/picker-combobox.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/picker-combobox.tsx
new file mode 100644
index 000000000..2bb00cd6b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/picker-combobox.tsx
@@ -0,0 +1,69 @@
+import { Search } from 'lucide-react';
+import {
+ Combobox,
+ ComboboxContent,
+ ComboboxEmpty,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+} from '@renderer/lib/ui/combobox';
+
+/**
+ * A search box that picks one item from a list, hands it to the caller and
+ * clears for the next pick. The box is the control rather than something a
+ * button opens, because picking several in a row is the normal case. Rows are
+ * the caller's to draw, so the same box serves agents, rooms and people.
+ */
+export function PickerCombobox<T extends { id: string }>({
+ items,
+ onPick,
+ searchText,
+ renderItem,
+ placeholder,
+ emptyText,
+ disabled = false,
+ onQueryChange,
+}: {
+ items: T[];
+ onPick: (item: T) => void;
+ /** The text a row is matched against as the user types. */
+ searchText: (item: T) => string;
+ renderItem: (item: T) => React.ReactNode;
+ placeholder: string;
+ emptyText: string;
+ disabled?: boolean;
+ /** What the user has typed, for callers whose list depends on it (a live
+ * directory search, an offer to use the typed text as-is). */
+ onQueryChange?: (query: string) => void;
+}) {
+ return (
+ <Combobox
+ items={items}
+ value={null}
+ onValueChange={(next: T | null) => {
+ if (next) onPick(next);
+ }}
+ onInputValueChange={onQueryChange ? (query: string) => onQueryChange(query) : undefined}
+ isItemEqualToValue={(a: T, b: T) => a.id === b.id}
+ filter={(item: T, query) => searchText(item).toLowerCase().includes(query.toLowerCase())}
+ autoHighlight
+ >
+ <ComboboxInput
+ showTrigger={false}
+ disabled={disabled}
+ placeholder={placeholder}
+ leftAddon={<Search className="size-3.5 text-foreground-muted" />}
+ />
+ <ComboboxContent className="min-w-(--anchor-width)">
+ <ComboboxList>
+ {(item: T) => (
+ <ComboboxItem key={item.id} value={item} showCheck={false}>
+ {renderItem(item)}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ <ComboboxEmpty>{emptyText}</ComboboxEmpty>
+ </ComboboxContent>
+ </Combobox>
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/room-picker.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/room-picker.tsx
new file mode 100644
index 000000000..1f7131977
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/room-picker.tsx
@@ -0,0 +1,62 @@
+import { Hash } from 'lucide-react';
+import { BridgeIcon, hasBridgeIcon } from '@renderer/lib/components/bridge-icon';
+import { bridgePlatformLabel } from '@renderer/lib/components/bridge-platform';
+import { ChosenTile } from '@renderer/lib/components/chosen-tile';
+
+/** The least a room row or tile needs to draw itself. */
+export type RoomPick = {
+ id: string;
+ name: string;
+ bridgeType: string | null;
+};
+
+/** Where a room's conversation happens, for the right of its row. */
+export function roomWhereLabel(bridgeType: string | null): string {
+ return bridgeType ? bridgePlatformLabel(bridgeType) : 'Switch only';
+}
+
+/** The mark of the app a room is bridged to, or a plain channel mark when it
+ * lives on Switch alone. */
+export function RoomMark({ bridgeType, size }: { bridgeType: string | null; size: number }) {
+ if (!hasBridgeIcon(bridgeType)) {
+ return <Hash className="size-4 shrink-0 text-foreground-muted" />;
+ }
+ return <BridgeIcon bridgeType={bridgeType} size={size} />;
+}
+
+/** One room in a picker list: its mark, name, and where it lives. */
+export function RoomPickerRow({ room }: { room: RoomPick }) {
+ return (
+ <>
+ <RoomMark bridgeType={room.bridgeType} size={16} />
+ <span className="min-w-0 flex-1 truncate">{room.name}</span>
+ <span className="shrink-0 text-xs text-foreground-muted">
+ {roomWhereLabel(room.bridgeType)}
+ </span>
+ </>
+ );
+}
+
+/** A room already chosen, with the way to take it back out. */
+export function ChosenRoomTile({
+ room,
+ subtitle,
+ subtitleTone,
+ onRemove,
+}: {
+ room: RoomPick;
+ /** Defaults to where the room lives. */
+ subtitle?: string;
+ subtitleTone?: 'muted' | 'warning';
+ onRemove: () => void;
+}) {
+ return (
+ <ChosenTile
+ mark={<RoomMark bridgeType={room.bridgeType} size={22} />}
+ title={room.name}
+ subtitle={subtitle ?? roomWhereLabel(room.bridgeType)}
+ subtitleTone={subtitleTone}
+ onRemove={onRemove}
+ />
+ );
+}
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts
new file mode 100644
index 000000000..8db483441
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/room-template-params.ts
@@ -0,0 +1,24 @@
+/**
+ * The param types a room template can declare, shared by the main-process
+ * parser and the renderer's form. Mirrors `ParamType` in core's `rooms_yaml`.
+ */
+
+/** Param types whose value names something that exists on the server. The
+ * form offers a picker over the matching list, and the server checks the
+ * value before provisioning. Mirrors `ENTITY_PARAM_TYPES` in core. */
+export const ENTITY_PARAM_TYPES = ['agent', 'bridge', 'room', 'user'] as const;
+export type EntityParamType = (typeof ENTITY_PARAM_TYPES)[number];
+
+export type ParamType = 'string' | 'number' | 'boolean' | 'enum' | EntityParamType;
+
+export const PARAM_TYPES: readonly ParamType[] = [
+ 'string',
+ 'number',
+ 'boolean',
+ 'enum',
+ ...ENTITY_PARAM_TYPES,
+];
+
+export function isEntityParamType(type: ParamType): type is EntityParamType {
+ return (ENTITY_PARAM_TYPES as readonly string[]).includes(type);
+}
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.ts
index 5ac0427ad..466cc363e 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
@@ -625,6 +625,15 @@ export type AddressingRule = {
* Optional for the same reason as `owner`: absent reads as false.
*/
owner_agents?: boolean;
+ /**
+ * Admit the Switch platform speaking on its own account. Denied
+ * by default, even by an open policy, so an agent has to opt in here. A
+ * platform message sent on a person's behalf, such as a template kickoff,
+ * is judged as that person instead and needs no opt-in.
+ *
+ * Optional for the same reason as `owner`: absent reads as false.
+ */
+ platform?: boolean;
};
export type AddressingPolicy = {
diff --git a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
index e389cb56d..af1089b54 100644
--- a/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/views/view-ids.ts
@@ -18,6 +18,7 @@ export const VIEW_IDS = [
'serverRooms',
'remoteHosts',
'remoteHost',
+ 'roomTemplateImport',
] as const;
export type ViewIdName = (typeof VIEW_IDS)[number];
diff --git a/console/package.json b/console/package.json
index d041065d5..0ffd3cb23 100644
--- a/console/package.json
+++ b/console/package.json
@@ -29,7 +29,7 @@
],
"overrides": {
"brace-expansion@>=4.0.0 <5.0.9": ">=5.0.9 <6",
- "js-yaml@>=4.0.0 <4.3.0": ">=4.3.0 <5",
+ "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5",
"fast-uri@>=3.0.0 <3.1.5": ">=3.1.5 <4",
"tar@<=7.5.20": ">=7.5.21 <8"
}
diff --git a/console/packages/switch-agent-runtime/src/bin.ts b/console/packages/switch-agent-runtime/src/bin.ts
index 4d019ffe1..8a9d290c6 100644
--- a/console/packages/switch-agent-runtime/src/bin.ts
+++ b/console/packages/switch-agent-runtime/src/bin.ts
@@ -389,6 +389,8 @@ type MessagePayload = {
addressed: boolean;
sender: string;
sender_name: string;
+ sender_kind?: string | null;
+ on_behalf_of?: string | null;
message_id: string;
body: string;
timestamp: number;
diff --git a/console/packages/switch-agent-runtime/src/types.ts b/console/packages/switch-agent-runtime/src/types.ts
index 4f2313315..ad81d6891 100644
--- a/console/packages/switch-agent-runtime/src/types.ts
+++ b/console/packages/switch-agent-runtime/src/types.ts
@@ -24,6 +24,12 @@ export interface MessagePayload {
addressed: boolean;
sender: string;
sender_name: string;
+ /** "user", "agent", or "platform" (the Switch app itself). Absent from
+ * servers that predate the field. */
+ sender_kind?: string | null;
+ /** For a platform message: the person whose authority it carries, such as
+ * the creator behind a template's kickoff. */
+ on_behalf_of?: string | null;
message_id: string;
body: string;
timestamp: number;
diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yaml
index bd938b458..1ef12dde4 100644
--- a/console/pnpm-lock.yaml
+++ b/console/pnpm-lock.yaml
@@ -6,7 +6,7 @@ settings:
overrides:
brace-expansion@>=4.0.0 <5.0.9: '>=5.0.9 <6'
- js-yaml@>=4.0.0 <4.3.0: '>=4.3.0 <5'
+ js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5'
fast-uri@>=3.0.0 <3.1.5: '>=3.1.5 <4'
tar@<=7.5.20: '>=7.5.21 <8'
@@ -34,6 +34,9 @@ importers:
'@typescript/native-preview':
specifier: 7.0.0-dev.20260609.1
version: 7.0.0-dev.20260609.1
+ ajv:
+ specifier: ^8.17.1
+ version: 8.20.0
better-sqlite3:
specifier: ^12.6.0
version: 12.10.0
@@ -3982,8 +3985,8 @@ packages:
resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}
- resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==}
+ resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==}
hasBin: true
@@ -7613,7 +7616,7 @@ snapshots:
hosted-git-info: 4.1.0
isbinaryfile: 5.0.7
jiti: 2.7.0
- js-yaml: 4.3.1
+ js-yaml: 4.3.2
json5: 2.2.3
lazy-val: 1.0.5
minimatch: 10.2.5
@@ -7770,7 +7773,7 @@ snapshots:
fs-extra: 10.1.0
http-proxy-agent: 7.0.2
https-proxy-agent: 7.0.6
- js-yaml: 4.3.1
+ js-yaml: 4.3.2
sanitize-filename: 1.6.4
source-map-support: 0.5.21
stat-mode: 1.0.0
@@ -8250,7 +8253,7 @@ snapshots:
app-builder-lib: 26.15.2([email protected])([email protected])
builder-util: 26.15.0
fs-extra: 10.1.0
- js-yaml: 4.3.1
+ js-yaml: 4.3.2
transitivePeerDependencies:
- electron-builder-squirrel-windows
- supports-color
@@ -8350,7 +8353,7 @@ snapshots:
dependencies:
builder-util-runtime: 9.7.0
fs-extra: 10.1.0
- js-yaml: 4.3.1
+ js-yaml: 4.3.2
lazy-val: 1.0.5
lodash.escaperegexp: 4.1.2
lodash.isequal: 4.5.0
@@ -9079,7 +9082,7 @@ snapshots:
dependencies:
argparse: 2.0.1
diff --git a/core/switch_core/addressing.py b/core/switch_core/addressing.py
index f753a5dea..90d7e9010 100644
--- a/core/switch_core/addressing.py
+++ b/core/switch_core/addressing.py
@@ -14,8 +14,11 @@ Model:
* `agents` — matched when the sender is another agent
- Each dimension is either ``"*"`` (any), or an explicit list of ids. An
empty list ``[]`` is the "none" value: it matches nothing. The sender is
- exactly one kind (user XOR agent), so a rule that should admit only humans
- sets ``agents: []`` and vice-versa.
+ exactly one kind (user, agent, or platform), so a rule that should admit
+ only humans sets ``agents: []`` and vice-versa.
+ - A rule carries a ``platform`` boolean. When True, the rule admits the
+ Switch platform as a sender. Platform is denied by default, even by an
+ open policy (no rules), so an agent must opt in with ``platform=True``.
- A rule additionally carries two *symbolic* subjects (CHOO-2137), resolved
at enforcement time rather than stored as ids, so they survive the owner
claiming a new platform identity, a bridge being recreated, or the agent
@@ -41,6 +44,11 @@ Defaults / precedence:
are permitted.
- Agents created from CHOO-2137 onwards start owner-only (see
`owner_only_policy`) rather than open.
+ - **Platform senders are always deny-by-default**, even for an open
+ policy. An agent needs a rule with ``platform=True`` to receive the
+ platform's own messages. A platform message sent on a person's behalf is
+ judged as that person instead (`allows_on_behalf_of`), so the platform
+ never reaches an agent the person could not.
This module is deliberately pure (no DB, no I/O) so it is trivially testable
and reusable from the receive path, the protocol service, and the gateway.
@@ -52,7 +60,7 @@ from typing import Literal
from pydantic import BaseModel, field_validator
-SenderKind = Literal["user", "agent"]
+SenderKind = Literal["user", "agent", "platform"]
ANY = "*"
@@ -72,6 +80,7 @@ class AddressingRule(BaseModel):
agents: Dimension = ANY
owner: bool = False
owner_agents: bool = False
+ platform: bool = False
@field_validator("rooms", "room_groups", "users", "agents")
@classmethod
@@ -97,6 +106,8 @@ class AddressingRule(BaseModel):
return False
if not _dim_contains(self.room_groups, group_id):
return False
+ if sender_kind == "platform":
+ return self.platform
if sender_kind == "user" and self._is_owner(sender_user_ids, owner_user_id):
return True
if sender_kind == "agent" and self._is_owners_agent(
@@ -162,13 +173,16 @@ class AddressingPolicy(BaseModel):
permitted. Allow-all when the policy is open; otherwise permitted iff
at least one rule matches.
+ Platform senders are denied even by an open policy; an agent must opt
+ in with a rule that sets ``platform=True``.
+
`sender_user_ids` are the Switch users who have claimed a human
sender's platform account (empty when nobody has);
`sender_owner_user_id` is who owns an agent sender (None for a human
or an ownerless agent); `owner_user_id` is the addressed agent's
owner. Together they resolve the `owner` and `owner_agents` rules.
"""
- if self.is_open():
+ if self.is_open() and sender_kind != "platform":
return True
return any(
rule._matches(
@@ -254,6 +268,61 @@ def owner_and_owner_agents_policy() -> AddressingPolicy:
)
+def platform_allowed_policy() -> AddressingPolicy:
+ """A policy that admits the platform sender.
+
+ Returns a single rule allowing ``platform`` in any room. Combine with
+ owner/agent rules by appending to their rule list rather than replacing
+ their policy with this one.
+ """
+ return AddressingPolicy(
+ rules=[
+ AddressingRule(
+ rooms=ANY,
+ room_groups=ANY,
+ users=[],
+ agents=[],
+ platform=True,
+ )
+ ]
+ )
+
+
+def allows_on_behalf_of(
+ policy: AddressingPolicy,
+ *,
+ room_id: str,
+ group_id: str | None,
+ user_id: str,
+ external_user_ids: list[str],
+ owner_user_id: str | None,
+) -> bool:
+ """Whether the platform may address this agent with `user_id`'s authority.
+
+ The answer is exactly what the policy would say to that person speaking
+ in the room themselves: an open policy admits them, an owner rule admits
+ them when they own the agent, and a ``users`` list admits them when one
+ of the platform accounts they have claimed (`external_user_ids`) is in
+ it. A person with no claimed account can still pass ``users: "*"`` and an
+ owner rule, which is what they could do as a human sender too.
+ """
+ if policy.is_open():
+ return True
+ candidates = external_user_ids or [""]
+ return any(
+ policy.allows(
+ room_id=room_id,
+ group_id=group_id,
+ sender_kind="user",
+ sender_id=external_id,
+ sender_user_ids=[user_id],
+ sender_owner_user_id=None,
+ owner_user_id=owner_user_id,
+ )
+ for external_id in candidates
+ )
+
+
def can_address(
policy: AddressingPolicy,
*,
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 14d87b6c9..bc296ae29 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -56,6 +56,11 @@ from switch_core.bridges.agent.registration_bootstrap import (
resolve_registration_owner_id,
)
from switch_core.bridges.resource.service import ResourceService
+from switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKER
+from switch_core.clients.admin_messages import (
+ platform_on_behalf_of,
+ platform_replies_in_channel,
+)
from switch_core.crypto import encrypt_token
from switch_core.db.models import (
Agent,
@@ -1713,15 +1718,25 @@ class ProtocolService:
@staticmethod
def _timeline_entry(
- message: Message, attachments: list[MessageAttachment]
+ message: Message,
+ attachments: list[MessageAttachment],
+ sender_kinds: dict[str, str] | None = None,
) -> dict[str, Any]:
"""Build the agent-facing entry for a recorded row.
An arrival is stored with no body — how it reads is this function's to
decide, not the writer's — so the sentence is composed here and can be
changed without rewriting history.
+
+ ``sender_kinds`` is an optional pre-resolved map of sender mxid to
+ kind ("user", "agent", "platform"). When absent, ``sender_kind`` is
+ read from the message content: "platform" for a PLATFORM_MARKER, else
+ None.
"""
name = message.sender_name or message.sender_id
+ sender_kind = (sender_kinds or {}).get(message.sender_id)
+ if sender_kind is None and _PLATFORM_MARKER in (message.content or {}):
+ sender_kind = "platform"
if message.event_type == MEMBERSHIP_EVENT_TYPE:
return {
"id": message.transport_event_id,
@@ -1732,7 +1747,7 @@ class ProtocolService:
"timestamp": _epoch_ms(message.sent_at),
"attachments": [],
}
- return {
+ entry: dict[str, Any] = {
"id": message.transport_event_id,
"kind": "message",
"sender": message.sender_id,
@@ -1750,10 +1765,24 @@ class ProtocolService:
for attachment in attachments
],
}
+ if sender_kind is not None:
+ entry["sender_kind"] = sender_kind
+ person = platform_on_behalf_of(message.content or {})
+ if person is not None:
+ entry["on_behalf_of"] = person.name
+ return entry
@staticmethod
def _thread_root_id(message: Message) -> str:
- """A threaded reply belongs to its root; anything else is its own root."""
+ """A threaded reply belongs to its root; anything else is its own root.
+
+ A platform message flagged reply_in_channel (a template's kickoff
+ text, threaded under its headline only to keep the channel tidy) is
+ read as its own root, so an agent catching up sees the work it starts
+ at the top level and answers there.
+ """
+ if platform_replies_in_channel(message.content or {}):
+ return message.transport_event_id
return message.thread_root_event_id or message.transport_event_id
async def read_context(
@@ -1776,8 +1805,10 @@ class ProtocolService:
{"root": <entry>, "replies": [<entry>, ...]}
An <entry> is {"id", "kind", "sender", "sender_name", "body",
- "timestamp", "attachments"}. `kind` is "message" for something someone
- said and "room_join" for an arrival. Top-level entries are roots with
+ "timestamp", "attachments"}, plus "sender_kind" ("platform" for a
+ message the Switch app posted) and "on_behalf_of" (the person a
+ platform message spoke for) when they apply. `kind` is "message" for
+ something someone said and "room_join" for an arrival. Top-level entries are roots with
an empty replies list; replies are ordered oldest-first within a
thread. A root that falls outside the fetched window but has a reply
inside it is fetched alongside; if no record of it exists it is
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index 6bd40ce77..1a86a03c5 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -213,6 +213,12 @@ class MessagePayload(BaseModel):
addressed: bool
sender: str
sender_name: str
+ # Who sent this: "user" (a human on a bridge), "agent", or "platform"
+ # (the Switch app itself). None on rows written before the field existed.
+ sender_kind: str | None = None
+ # For a platform message: the display name of the person whose authority
+ # it carries (a template's creator behind its kickoff), else None.
+ on_behalf_of: str | None = None
message_id: str
body: str
timestamp: int
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.py
index 60c86db54..1c9f9dbc8 100644
--- a/core/switch_core/bridges/collaboration/bridge_core.py
+++ b/core/switch_core/bridges/collaboration/bridge_core.py
@@ -4,7 +4,7 @@ import asyncio
import logging
import re
import uuid
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, TypeVar
@@ -26,7 +26,12 @@ from switch_core.bridges.collaboration.models import (
InboundUserJoin,
OutboundAttachment,
)
-from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageType
+from switch_core.clients.admin_messages import (
+ ADMIN_MARKER,
+ PLATFORM_MARKER,
+ AdminMessageType,
+ platform_on_behalf_of,
+)
from switch_core.clients.client_base import ClientBase, ClientConfig
from switch_core.clients.mentions import mention_regex, strip_emphasis
from switch_core.db.models import BridgeMessageMap, ExternalUser
@@ -77,6 +82,11 @@ PUPPET_JOIN_TIMEOUT = 30.0
OUTBOUND_GROUP_TIMEOUT_SECONDS = 5.0
+def _is_thread_reply(content: Mapping[str, object]) -> bool:
+ relates = content.get("m.relates_to")
+ return isinstance(relates, dict) and relates.get("rel_type") == "m.thread"
+
+
@dataclass
class _PendingOutboundGroup:
"""Files of a multi-attachment message seen so far, keyed by group index."""
@@ -1080,6 +1090,12 @@ class BridgeCore:
Only resolvable names appear in the returned dict; names with no
matching external user on this bridge are omitted (and logged), so the
caller can diff against the input to learn which ones failed.
+
+ When the DB lookup misses, falls back to an exact match in the
+ platform directory, so a person who has never messaged through Switch
+ still resolves. A hit is persisted (an ``ExternalUser`` row and its
+ puppet), so room membership, addressing and export all see the same
+ person this resolution found.
"""
async with self._session_factory() as session:
users = await self._external_user_store.get_by_bridge(
@@ -1092,6 +1108,29 @@ class BridgeCore:
if ext_id:
resolved[name] = ext_id
else:
+ # Exact match on username or email only: a fuzzy directory
+ # hit is a real person, and being wrong invites a stranger
+ # into a private channel.
+ try:
+ results = await self.adapter.search_directory_users(name)
+ match = next(
+ (
+ r
+ for r in results
+ if r.username == name
+ or (r.email is not None and r.email.lower() == name.lower())
+ ),
+ None,
+ )
+ if match:
+ ext = await self.ensure_external_user(
+ external_user_id=match.external_user_id,
+ external_username=match.username,
+ )
+ resolved[name] = ext.external_user_id
+ continue
+ except (NotImplementedError, RuntimeError):
+ pass
logger.warning(
"No external user found for username '%s' on bridge %s",
name,
@@ -1109,17 +1148,27 @@ class BridgeCore:
matrix_room_id: str,
user_names: list[str],
) -> None:
- """For each known external user matching one of `user_names` on this
- bridge, ensure a running puppet client exists and is joined to the
- Matrix room. Names without an existing ExternalUser row are skipped
- — they will be picked up by the on_user_joined callback (when the
- adapter sees them join externally) or by the lazy inbound-message
- path."""
- async with self._session_factory() as session:
- users = await self._external_user_store.get_by_bridge_and_names(
- session, self._bridge_id, user_names
- )
- for ext_user in users:
+ """For each resolvable name in `user_names`, ensure a running puppet
+ client exists and is joined to the Matrix room.
+
+ Resolution goes through `resolve_external_user_id_map`, the same
+ answer the channel-invite path uses, so a person the platform
+ directory can find is added here too. Unresolvable names are skipped
+ (the resolver logs them); the on_user_joined callback or the inbound
+ message path picks them up later."""
+ resolved = await self.resolve_external_user_id_map(user_names)
+ for ext_id in resolved.values():
+ async with self._session_factory() as session:
+ ext_user = await self._external_user_store.get_by_external_id(
+ session, self._bridge_id, ext_id
+ )
+ if ext_user is None:
+ logger.error(
+ "External user %s resolved on bridge %s but has no record",
+ ext_id,
+ self._bridge_id,
+ )
+ continue
await self._ensure_user_in_matrix_room(
external_user_id=ext_user.external_user_id,
external_username=ext_user.external_username,
@@ -1436,27 +1485,31 @@ class BridgeCore:
) -> None:
event_content = event.content
admin_marker = event_content.get(ADMIN_MARKER)
+ platform_marker = event_content.get(PLATFORM_MARKER)
sender_name = event.sender_name
- # An admin/system message renders natively per bridge (admin_message)
- # rather than on behalf of its Matrix sender, so it needs no sender_name.
- if sender_name is None and admin_marker is None:
+ # An admin/system or platform message renders natively per bridge
+ # (admin_message) rather than on behalf of its Matrix sender, so it
+ # needs no sender_name.
+ is_system = admin_marker is not None or platform_marker is not None
+ if sender_name is None and not is_system:
logger.error(
"No sender_name in event from %s — skipping outbound", event.sender
)
return
logger.debug(
- "[BRIDGE-OUT] sending to channel=%s sender=%s admin=%s",
+ "[BRIDGE-OUT] sending to channel=%s sender=%s admin=%s platform=%s",
channel_id,
sender_name,
admin_marker is not None,
+ platform_marker is not None,
)
thread_root_ref = await self._outbound_thread_root_ref(
event_content, channel_id
)
- if admin_marker is not None:
+ if is_system:
message_type = (
admin_marker.get("type") if isinstance(admin_marker, dict) else None
)
@@ -1465,9 +1518,20 @@ class BridgeCore:
# here as well ran the body through twice, and the second pass
# escapes the markup the first one produced — a command reply
# arrived showing its own `<b>` tags.
+ # A platform message sent for a person says so, so the room sees
+ # whose authority it carries. A thread reply sits under a root that
+ # already said it, and a body naming the person needs no second line.
+ body = event.body
+ person = platform_on_behalf_of(event_content)
+ if (
+ person is not None
+ and not _is_thread_reply(event_content)
+ and f"@{person.name}" not in body
+ ):
+ body = f"On behalf of @{person.name}:\n\n{body}"
message_ref = await self._adapter.admin_message(
channel_id,
- event.body,
+ body,
thread_root_ref,
message_type=message_type,
)
diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.py
index 160d655d4..320170786 100644
--- a/core/switch_core/clients/admin_client.py
+++ b/core/switch_core/clients/admin_client.py
@@ -8,7 +8,9 @@ from switch_core.bridges.agent.commands import dispatch_admin_command
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
from switch_core.clients.admin_messages import (
ADMIN_MARKER,
+ PLATFORM_MARKER,
AdminMessageType,
+ OnBehalfOf,
admin_extra_content,
)
from switch_core.clients.client_base import (
@@ -125,6 +127,44 @@ class AdminClient(ClientBase[ClientConfig]):
extra_content=admin_extra_content(AdminMessageType.COMMAND_RESULT),
)
+ # ── Platform messages ───────────────────────────────────────────────────
+
+ async def send_platform_message(
+ self,
+ room_id: str,
+ body: str,
+ *,
+ thread_root_id: str | None = None,
+ on_behalf_of: OnBehalfOf | None = None,
+ reply_in_channel: bool = False,
+ ) -> str | None:
+ """Send an addressed message as the Switch platform.
+
+ Unlike an admin notice it carries no ADMIN_MARKER and IS addressed to
+ agents. ``on_behalf_of`` names the person whose authority it carries:
+ each addressed agent applies its policy to that person, so the
+ platform can say what they could have said and nothing more. Without
+ it the message is the platform's own, which agents deny unless a rule
+ opts them in.
+ """
+ marker_value: dict[str, object] = {}
+ if on_behalf_of is not None:
+ marker_value["on_behalf_of"] = {
+ "user_id": on_behalf_of.user_id,
+ "name": on_behalf_of.name,
+ }
+ if reply_in_channel:
+ # Only meaningful for a threaded message: the agents it addresses
+ # answer at the top level instead of under it.
+ marker_value["reply_in_channel"] = True
+ return await self.send_message(
+ room_id,
+ body,
+ format="markdown",
+ thread_root_id=thread_root_id,
+ extra_content={PLATFORM_MARKER: marker_value},
+ )
+
# ── Admin notices ─────────────────────────────────────────────────────────
async def _warn_unreachable_roles(
diff --git a/core/switch_core/clients/admin_messages.py b/core/switch_core/clients/admin_messages.py
index 51a90e5dd..18a585681 100644
--- a/core/switch_core/clients/admin_messages.py
+++ b/core/switch_core/clients/admin_messages.py
@@ -1,6 +1,8 @@
from __future__ import annotations
+from collections.abc import Mapping
from enum import StrEnum
+from typing import NamedTuple
# Marker stamped on the content of an admin/system `m.room.message`. Two jobs,
# mirroring AUTO_REPLY_FLAG:
@@ -15,6 +17,51 @@ from enum import StrEnum
# human-readable default text, so a vanilla Matrix client still renders it.
ADMIN_MARKER = "com.switch.admin"
+# Marker for a message the Switch platform posts. Unlike ADMIN_MARKER it IS
+# addressed to agents and expects action; the marker tells the bridge to
+# render it as the Switch app and lets resolve_sender see sender_kind
+# "platform". Carried as a content field on a plain m.room.message.
+#
+# Value: {} for the platform's own message, or {"on_behalf_of": {"user_id",
+# "name"}} when it speaks with a person's authority (a template's kickoff).
+# The authority is per message: the addressed agent's policy is evaluated
+# for that person when the event arrives, and nothing is granted beyond it.
+# Only server-side code writes the marker.
+PLATFORM_MARKER = "com.switch.platform"
+
+
+class OnBehalfOf(NamedTuple):
+ """The person a platform message carries the authority of."""
+
+ user_id: str
+ name: str
+
+
+def platform_replies_in_channel(content: Mapping[str, object]) -> bool:
+ """Whether a platform message asks the agents it addresses to answer in
+ the channel rather than in its thread. A template's kickoff sits in a
+ thread only to keep the channel to one line; the work belongs at the top
+ level, where a person would have started it.
+ """
+ marker = content.get(PLATFORM_MARKER)
+ return isinstance(marker, dict) and marker.get("reply_in_channel") is True
+
+
+def platform_on_behalf_of(content: Mapping[str, object]) -> OnBehalfOf | None:
+ """The person behind a platform-marked event, or None for a bare platform
+ message or an event without the marker."""
+ marker = content.get(PLATFORM_MARKER)
+ if not isinstance(marker, dict):
+ return None
+ person = marker.get("on_behalf_of")
+ if not isinstance(person, dict):
+ return None
+ user_id = person.get("user_id")
+ name = person.get("name")
+ if not isinstance(user_id, str) or not user_id:
+ return None
+ return OnBehalfOf(user_id, name if isinstance(name, str) and name else user_id)
+
class AdminMessageType(StrEnum):
"""The kind of admin/system message, carried in the marker so a bridge
diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.py
index 6f703c3a8..0d2c855ea 100644
--- a/core/switch_core/clients/agent_client.py
+++ b/core/switch_core/clients/agent_client.py
@@ -4,6 +4,7 @@ import asyncio
import logging
import random
import re
+from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Literal, NamedTuple, Unpack
@@ -28,6 +29,11 @@ from switch_core.bridges.agent.protocol.types import (
TaskFinalisePayload,
TaskUpdatePayload,
)
+from switch_core.clients.admin_messages import (
+ PLATFORM_MARKER,
+ platform_on_behalf_of,
+ platform_replies_in_channel,
+)
from switch_core.clients.client_base import (
ClientBase,
ClientBaseKwargs,
@@ -402,8 +408,13 @@ class AgentClient(ClientBase[ClientConfig]):
return
thread_id = event.thread_root_id
-
- reply_thread_root = thread_id if thread_id is not None else event.event_id
+ if platform_replies_in_channel(event.content):
+ # A threaded kickoff that wants its work in the channel: the agent
+ # sees it as top-level, so its replies and notices go there.
+ thread_id = None
+ reply_thread_root = None
+ else:
+ reply_thread_root = thread_id if thread_id is not None else event.event_id
# Every database read this message needs happens in one session, and
# nothing is posted to Matrix while it is open. A busy room fans one
@@ -464,6 +475,17 @@ class AgentClient(ClientBase[ClientConfig]):
sender_name,
)
+ sender_kind: str | None = None
+ on_behalf_of: str | None = None
+ if PLATFORM_MARKER in event.content:
+ sender_kind = "platform"
+ person = platform_on_behalf_of(event.content)
+ if person is not None:
+ # The agent answers the person the platform spoke for, not
+ # the admin client that carried the message.
+ on_behalf_of = person.name
+ sender_name = person.name
+
agent_event = AgentEvent(
type="message",
room_id=meta.room_id,
@@ -473,6 +495,8 @@ class AgentClient(ClientBase[ClientConfig]):
addressed=is_addressed,
sender=event.sender,
sender_name=sender_name,
+ sender_kind=sender_kind,
+ on_behalf_of=on_behalf_of,
message_id=event.event_id,
body=text,
timestamp=event.timestamp,
@@ -662,6 +686,17 @@ class AgentClient(ClientBase[ClientConfig]):
room.room_id, event, gate.refusal, reply_thread_root
)
+ sender_kind: str | None = None
+ on_behalf_of: str | None = None
+ if PLATFORM_MARKER in event.content:
+ sender_kind = "platform"
+ person = platform_on_behalf_of(event.content)
+ if person is not None:
+ # The agent answers the person the platform spoke for, not
+ # the admin client that carried the message.
+ on_behalf_of = person.name
+ sender_name = person.name
+
agent_event = AgentEvent(
type="message",
room_id=meta.room_id,
@@ -671,6 +706,8 @@ class AgentClient(ClientBase[ClientConfig]):
addressed=is_addressed,
sender=event.sender,
sender_name=sender_name,
+ sender_kind=sender_kind,
+ on_behalf_of=on_behalf_of,
message_id=event.event_id,
body=body,
timestamp=event.timestamp,
@@ -1225,7 +1262,12 @@ class AgentClient(ClientBase[ClientConfig]):
)
async def _addressing_allowed(
- self, session: AsyncSession, agent: Agent, matrix_sender: str, room_id: str
+ self,
+ session: AsyncSession,
+ agent: Agent,
+ matrix_sender: str,
+ room_id: str,
+ content: Mapping[str, object] | None = None,
) -> AddressingDecision:
"""Whether `matrix_sender` may address this agent in `room_id`, per the
agent's scoped addressing policy.
@@ -1233,9 +1275,15 @@ class AgentClient(ClientBase[ClientConfig]):
`agent` is the freshly-read row rather than the cached snapshot: the
policy is the thing being enforced, and enforcing a stale copy of it is
the one way this check can be wrong in the dangerous direction.
+ `content` is the event's content when there is one: a platform message
+ says there whose authority it carries.
"""
return await self._addressing.permitted(
- session, agent=agent, room_id=room_id, sender=matrix_sender
+ session,
+ agent=agent,
+ room_id=room_id,
+ sender=matrix_sender,
+ content=content,
)
async def _gate_addressed(
@@ -1254,7 +1302,7 @@ class AgentClient(ClientBase[ClientConfig]):
tag this agent are ever checked, and open policies short-circuit.
"""
decision = await self._addressing_allowed(
- session, agent, event.sender, meta.room_id
+ session, agent, event.sender, meta.room_id, event.content
)
if decision.allowed:
return _GateOutcome(addressed=True, refusal=None)
@@ -1320,6 +1368,9 @@ class AgentClient(ClientBase[ClientConfig]):
(paired with `mentions=[event.sender]` so Matrix renders a pill).
"""
content = event.content
+ person = platform_on_behalf_of(content)
+ if person is not None:
+ return person.name
name = content.get("sender_name")
if name:
return str(name)
diff --git a/core/switch_core/delivery/addressing.py b/core/switch_core/delivery/addressing.py
index 279225f2e..6e367847f 100644
--- a/core/switch_core/delivery/addressing.py
+++ b/core/switch_core/delivery/addressing.py
@@ -24,11 +24,21 @@ rewrite to expose it.
from __future__ import annotations
import logging
+from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, NamedTuple
-from switch_core.addressing import SenderKind, can_address, parse_policy
-from switch_core.clients.admin_messages import ADMIN_MARKER
+from switch_core.addressing import (
+ SenderKind,
+ allows_on_behalf_of,
+ can_address,
+ parse_policy,
+)
+from switch_core.clients.admin_messages import (
+ ADMIN_MARKER,
+ PLATFORM_MARKER,
+ platform_on_behalf_of,
+)
from switch_core.clients.mentions import mention_regex, strip_emphasis
if TYPE_CHECKING:
@@ -101,6 +111,10 @@ class SenderPrincipal(NamedTuple):
id: str
user_ids: list[str]
owner_user_id: str | None
+ #: For a platform sender: the Switch user whose authority the message
+ #: carries, read from the event's marker. None for the platform's own
+ #: message and for every other kind.
+ on_behalf_of: str | None = None
class AddressingResolver:
@@ -257,7 +271,13 @@ class AddressingResolver:
# ── Permitted ─────────────────────────────────────────────────────────────
async def permitted(
- self, session: AsyncSession, *, agent: Agent, room_id: str, sender: str
+ self,
+ session: AsyncSession,
+ *,
+ agent: Agent,
+ room_id: str,
+ sender: str,
+ content: Mapping[str, object] | None = None,
) -> AddressingDecision:
"""Whether `sender` may address this agent in this room.
@@ -266,15 +286,29 @@ class AddressingResolver:
that resolves to nothing is refused rather than given the benefit of
the doubt, because an identity nobody can name is exactly what a
restricted agent is restricted against.
+
+ `content` is the event's content. A platform-marked event is the one
+ case an open policy does not settle up front: the platform's own
+ message is denied unless a rule admits it, and a message it sends on
+ a person's behalf is judged as that person. Checking the marker is a
+ dict lookup, so the open-policy fast path stays free for everyone
+ else.
"""
policy = parse_policy(agent.addressing_policy)
- if policy.is_open():
+ content = content or {}
+ if policy.is_open() and PLATFORM_MARKER not in content:
return AddressingDecision(allowed=True, refusal="")
- principal = await self.resolve_sender(session, sender)
+ principal = await self.resolve_sender(session, sender, content)
room = await self._room_store.get(session, room_id)
+ group_id = room.group_id if room is not None else None
if principal is None:
+ if policy.is_open():
+ # The marker was on an event from a sender that is not the
+ # platform. It carries no authority, so the sender is treated
+ # as anyone else the open policy already admits.
+ return AddressingDecision(allowed=True, refusal="")
logger.warning(
"Addressing denied for %s: unresolvable sender %s in room %s",
agent.name,
@@ -283,16 +317,31 @@ class AddressingResolver:
)
return AddressingDecision(allowed=False, refusal=ADDRESSING_DENIED_MESSAGE)
- allowed = can_address(
- policy,
- room_id=room_id,
- group_id=room.group_id if room is not None else None,
- sender_kind=principal.kind,
- sender_id=principal.id,
- sender_user_ids=principal.user_ids,
- sender_owner_user_id=principal.owner_user_id,
- owner_user_id=agent.owner_id,
- )
+ if principal.kind == "platform" and principal.on_behalf_of is not None:
+ claimed = await self._external_user_store.get_by_user(
+ session, principal.on_behalf_of
+ )
+ allowed = allows_on_behalf_of(
+ policy,
+ room_id=room_id,
+ group_id=group_id,
+ user_id=principal.on_behalf_of,
+ external_user_ids=[ext.id for ext in claimed],
+ owner_user_id=agent.owner_id,
+ )
+ elif policy.is_open() and principal.kind != "platform":
+ allowed = True
+ else:
+ allowed = can_address(
+ policy,
+ room_id=room_id,
+ group_id=group_id,
+ sender_kind=principal.kind,
+ sender_id=principal.id,
+ sender_user_ids=principal.user_ids,
+ sender_owner_user_id=principal.owner_user_id,
+ owner_user_id=agent.owner_id,
+ )
if allowed:
return AddressingDecision(allowed=True, refusal="")
@@ -328,14 +377,22 @@ class AddressingResolver:
)
async def resolve_sender(
- self, session: AsyncSession, matrix_user_id: str
+ self,
+ session: AsyncSession,
+ matrix_user_id: str,
+ content: Mapping[str, object] | None = None,
) -> SenderPrincipal | None:
"""Map a sender's mxid to the principal a policy is written about.
Every participant is a Switch client, so the mxid resolves to a Client
- and from there to either an Agent (an agent-to-agent attempt) or an
- ExternalUser (a human on a bridge). None means neither, which a
- restricted agent should not trust.
+ and from there to an Agent, an ExternalUser, or the admin client
+ (the platform). None means none of those, which a restricted agent
+ should not trust.
+
+ `content` matters only for the admin client: its platform marker may
+ name the person the message speaks for. The marker is read for no
+ other sender, so a copy of it on an agent's or a human's message
+ changes nothing.
The two symbolic subjects come from different fields and only one
applies to any sender: `user_ids` are the Switch users who have claimed
@@ -357,4 +414,13 @@ class AddressingResolver:
session, external_user.id
)
return SenderPrincipal("user", external_user.id, claimants, None)
+ if client.type == "admin":
+ person = platform_on_behalf_of(content or {})
+ return SenderPrincipal(
+ "platform",
+ client.id,
+ [],
+ None,
+ on_behalf_of=person.user_id if person is not None else None,
+ )
return None
diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.py
index abc1e3782..962561960 100644
--- a/core/switch_core/gateway/dependencies.py
+++ b/core/switch_core/gateway/dependencies.py
@@ -143,6 +143,7 @@ def get_room_yaml_service() -> RoomYamlService:
external_user_store=_state["external_user_store"],
room_role_store=protocol.room_role_store,
session_factory=_state["session_factory"],
+ client_lifecycle=_state["client_lifecycle"],
)
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 752326e05..9486be951 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -52,7 +52,7 @@ from switch_core.gateway.schemas import (
RoomUsersRequest,
)
from switch_core.room_service import RoleSpec, RoomCreateConfig, RoomService
-from switch_core.rooms_yaml import ProvisionResult, RoomYamlService
+from switch_core.rooms_yaml import ProvisionResult, RoomYamlService, TemplateDocument
logger = logging.getLogger(__name__)
@@ -406,8 +406,18 @@ async def create_room_from_yaml(
else:
text = (await request.body()).decode("utf-8")
inputs = None
- spec = rooms_yaml.parse(text, inputs=inputs)
- return await rooms_yaml.provision(spec, user_id=user.id, is_admin=is_admin)
+ builtins = await rooms_yaml.builtins_for(
+ user_id=user.id, name=user.name, email=user.email, text=text
+ )
+ parsed = rooms_yaml.parse_template(text, inputs=inputs, builtins=builtins)
+ await rooms_yaml.check_entity_params(parsed)
+ return await rooms_yaml.provision(
+ parsed.spec,
+ kickoff=parsed.kickoff,
+ user_id=user.id,
+ is_admin=is_admin,
+ creator_name=builtins["$creator"],
+ )
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e)) from e
except PermissionError as e:
@@ -416,6 +426,14 @@ async def create_room_from_yaml(
raise HTTPException(status_code=502, detail=str(e)) from e
[email protected]("/template-schema")
+async def get_template_schema(
+ _user: Annotated[User, Depends(get_current_user)],
+) -> dict:
+ """Return the JSON Schema describing a valid room template document."""
+ return TemplateDocument.model_json_schema()
+
+
@router.get("/{room_id}/yaml")
async def export_room_yaml(
room_id: str,
diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.py
index 5c8788f39..f8f748846 100644
--- a/core/switch_core/room_service.py
+++ b/core/switch_core/room_service.py
@@ -678,13 +678,14 @@ class RoomService:
logger.info("Deleted room %s", room_id)
async def _resolve_names_to_ids(self, agent_names: list[str]) -> list[str]:
+ unique_names = list(dict.fromkeys(agent_names))
async with self._session_factory() as session:
- agents = await self._agent_store.get_by_names(session, agent_names)
+ agents = await self._agent_store.get_by_names(session, unique_names)
name_to_id = {a.name: a.id for a in agents}
- missing = [n for n in agent_names if n not in name_to_id]
+ missing = [n for n in unique_names if n not in name_to_id]
if missing:
raise ValueError(f"Unknown agents: {', '.join(missing)}")
- return [name_to_id[n] for n in agent_names]
+ return [name_to_id[n] for n in unique_names]
async def add_agents_to_room(
self,
@@ -1236,6 +1237,22 @@ class RoomService:
await session.commit()
logger.info("Reconciled %d client(s) into room %s", len(missing), room.id)
+ async def resolve_bridge_users(
+ self, bridge_id: str, names: list[str]
+ ) -> dict[str, str]:
+ """Which of ``names`` are people on the bridge, as name to external id.
+
+ The same resolution room creation applies to a template's ``users:``
+ (known users first, then an exact directory match), exposed so a
+ ``user``-typed template param can be checked before the room exists.
+ Raises when the bridge is not running, since nothing can be looked up
+ on it then.
+ """
+ bridge_core = self._collab_lifecycle.get(bridge_id)
+ if bridge_core is None:
+ raise ValueError("the room's messaging app is not running")
+ return await bridge_core.resolve_external_user_id_map(names)
+
async def ensure_client_in_room(self, room_id: str, client_id: str) -> None:
"""Invite a single running client to the room (it auto-joins) and record
its membership. Idempotent — safe to call repeatedly, e.g. on every
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index 2ef5eb0da..64468557a 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -22,6 +22,9 @@ from __future__ import annotations
import logging
import re
+import time
+from dataclasses import dataclass
+from datetime import date
from typing import TYPE_CHECKING, Any, Literal, cast
import yaml
@@ -29,12 +32,16 @@ from pydantic import BaseModel, ValidationError, model_validator
from switch_core.bridges.collaboration.models import ChannelType
from switch_core.bridges.resource.registry import validate_reference_value
+from switch_core.clients.admin_client import AdminClient
+from switch_core.clients.admin_messages import OnBehalfOf
from switch_core.room_service import RoleSpec, RoomCreateConfig
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.resource.service import ResourceService
+ from switch_core.clients.client_lifecycle_service import ClientLifecycleService
+ from switch_core.db.models import Room
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.collaboration_bridge_store import (
CollaborationBridgeStore,
@@ -48,21 +55,39 @@ logger = logging.getLogger(__name__)
# ── Template parameters (v0) ─────────────────────────────────────────────
-PLACEHOLDER_RE = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")
+# How long a kickoff waits for the room's members to join before posting.
+KICKOFF_JOIN_TIMEOUT = 30.0
+
+PLACEHOLDER_RE = re.compile(r"\{(\$?[A-Za-z_][A-Za-z0-9_]*)\}")
+
+# Param types whose value names something the server already has. They
+# interpolate as plain strings; the difference is that the server checks the
+# name before provisioning and the Console offers a picker instead of a text
+# box. The value is the name a template would write: an agent's name, a
+# bridge's display name, a room's name, a platform username.
+ENTITY_PARAM_TYPES = ("agent", "bridge", "room", "user")
+
+ParamType = Literal[
+ "string", "number", "boolean", "enum", "agent", "bridge", "room", "user"
+]
class ParamSpec(BaseModel):
model_config = {"extra": "forbid"}
- type: Literal["string", "number", "boolean", "enum"] = "string"
+ type: ParamType = "string"
description: str | None = None
default: str | int | float | bool | None = None
enum: list[str] | None = None
+ # Rendering hint for string params that carry long text (a task brief,
+ # instructions): the form shows a textarea instead of a one-line input,
+ # which would strip the pasted text's newlines.
+ multiline: bool = False
def _coerce(value: Any, spec: ParamSpec, name: str) -> str | int | float | bool:
"""Coerce a raw input value to the declared type."""
t = spec.type
- if t == "string":
+ if t == "string" or t in ENTITY_PARAM_TYPES:
return str(value)
if t == "number":
if isinstance(value, bool):
@@ -223,6 +248,26 @@ class RoomSpec(BaseModel):
docs: list[DocSpec] = []
+class TemplateDocument(BaseModel):
+ """Top-level shape of a room template file (for JSON Schema generation)."""
+
+ room: RoomSpec
+ params: dict[str, ParamSpec] | None = None
+ kickoff: str | None = None
+
+
+@dataclass(frozen=True)
+class ParsedTemplate:
+ """What ``parse_template`` makes of one template plus one set of inputs."""
+
+ spec: RoomSpec
+ kickoff: str | None
+ #: The template's declared params, by name.
+ params: dict[str, ParamSpec]
+ #: The value each declared param resolved to (input or default), coerced.
+ values: dict[str, str | int | float | bool]
+
+
class ProvisionResult(BaseModel):
room_id: str
room_name: str
@@ -263,6 +308,7 @@ class RoomYamlService:
external_user_store: ExternalUserStore,
room_role_store: RoomRoleStore,
session_factory: async_sessionmaker[AsyncSession],
+ client_lifecycle: ClientLifecycleService | None = None,
) -> None:
self._rooms = room_service
self._resources = resource_service
@@ -272,10 +318,39 @@ class RoomYamlService:
self._external_users = external_user_store
self._room_roles = room_role_store
self._session_factory = session_factory
+ self._client_lifecycle = client_lifecycle
# ── Parse ─────────────────────────────────────────────────────────────
- def parse(self, text: str, inputs: dict[str, Any] | None = None) -> RoomSpec:
+ def parse(
+ self,
+ text: str,
+ inputs: dict[str, Any] | None = None,
+ builtins: dict[str, str] | None = None,
+ ) -> tuple[RoomSpec, str | None]:
+ """Parse a YAML template into a ``RoomSpec`` and optional kickoff message.
+
+ The short form of ``parse_template`` for callers that only need the
+ room; the gateway uses the long form so it can also check the
+ entity-typed params before provisioning.
+ """
+ parsed = self.parse_template(text, inputs=inputs, builtins=builtins)
+ return parsed.spec, parsed.kickoff
+
+ def parse_template(
+ self,
+ text: str,
+ inputs: dict[str, Any] | None = None,
+ builtins: dict[str, str] | None = None,
+ ) -> ParsedTemplate:
+ """Parse a YAML template into its room spec, kickoff, and resolved params.
+
+ ``builtins`` are server-injected variables (e.g. ``{creator}``) that
+ are always available for interpolation alongside user-supplied
+ ``inputs``. They are resolved first and never collide with declared
+ params; a param named ``creator`` would shadow the built-in, which is
+ intentional (the template author owns the namespace).
+ """
try:
data = yaml.safe_load(text)
except yaml.YAMLError as e:
@@ -283,7 +358,7 @@ class RoomYamlService:
if not isinstance(data, dict) or "room" not in data:
raise ValueError("YAML must have a single top-level 'room:' mapping")
- allowed_keys = {"room", "params", "version"}
+ allowed_keys = {"room", "params", "version", "kickoff"}
extra = set(data) - allowed_keys
if extra:
raise ValueError(f"Unknown top-level key(s): {', '.join(sorted(extra))}")
@@ -311,22 +386,186 @@ class RoomYamlService:
if inputs and not declared:
raise ValueError("Inputs supplied but the template declares no params")
+ # Build the interpolation values: builtins first, then params override
+ values: dict[str, str | int | float | bool] = dict(builtins or {})
+ resolved: dict[str, str | int | float | bool] = {}
if declared:
- values = resolve_params(declared, inputs)
+ resolved = resolve_params(declared, inputs)
+ values.update(resolved)
+
+ if values:
room_data = interpolate(data["room"], values)
+ kickoff_raw = data.get("kickoff")
+ kickoff = (
+ interpolate(kickoff_raw, values)
+ if isinstance(kickoff_raw, str)
+ else None
+ )
else:
room_data = data["room"]
+ kickoff = (
+ data.get("kickoff") if isinstance(data.get("kickoff"), str) else None
+ )
try:
- return RoomSpec.model_validate(room_data)
+ spec = RoomSpec.model_validate(room_data)
except ValidationError as e:
raise ValueError(f"Invalid room spec: {e}") from e
+ return ParsedTemplate(
+ spec=spec, kickoff=kickoff, params=declared, values=resolved
+ )
+
+ # ── Entity params ─────────────────────────────────────────────────────
+
+ async def check_entity_params(self, parsed: ParsedTemplate) -> None:
+ """Every entity-typed param must name something this server has.
+
+ Raises ``ValueError`` in the ``param 'x': ...`` form the Console maps
+ back onto the field. Runs between ``parse_template`` and ``provision``
+ so a bad name fails at the input, not as a half-built room. A ``user``
+ param resolves on the bridge the room will land on, hence the parsed
+ spec rather than the raw inputs.
+ """
+ wanted: dict[str, list[tuple[str, str]]] = {}
+ for name, spec in parsed.params.items():
+ if spec.type in ENTITY_PARAM_TYPES:
+ wanted.setdefault(spec.type, []).append(
+ (name, str(parsed.values[name]))
+ )
+ if not wanted:
+ return
+
+ async with self._session_factory() as session:
+ if "agent" in wanted:
+ names = [value for _, value in wanted["agent"]]
+ agents = await self._agent_store.get_by_names(session, names)
+ known = {a.name for a in agents}
+ for param, value in wanted["agent"]:
+ if value not in known:
+ raise ValueError(
+ f"param {param!r}: no agent named {value!r} on this server"
+ )
+ if "bridge" in wanted:
+ bridges = {
+ b.display_name: b for b in await self._bridge_store.get_all(session)
+ }
+ for param, value in wanted["bridge"]:
+ bridge = bridges.get(value)
+ if bridge is None:
+ raise ValueError(
+ f"param {param!r}: no messaging app named {value!r} "
+ "on this server"
+ )
+ if bridge.status != "active":
+ raise ValueError(
+ f"param {param!r}: messaging app {value!r} is not running"
+ )
+ if "room" in wanted:
+ rooms = {r.name for r in await self._room_store.get_all(session)}
+ for param, value in wanted["room"]:
+ if value not in rooms:
+ raise ValueError(
+ f"param {param!r}: no room named {value!r} on this server"
+ )
+
+ if "user" in wanted:
+ bridge_id = await self._resolve_bridge_id(parsed.spec.bridge)
+ if bridge_id is None:
+ param = wanted["user"][0][0]
+ raise ValueError(
+ f"param {param!r}: a user can only be looked up on a messaging "
+ "app, and this template has none"
+ )
+ names = [value for _, value in wanted["user"]]
+ found = await self._rooms.resolve_bridge_users(bridge_id, names)
+ for param, value in wanted["user"]:
+ if value not in found:
+ raise ValueError(
+ f"param {param!r}: no user named {value!r} on the "
+ "room's messaging app"
+ )
+
+ async def builtins_for(
+ self, *, user_id: str, name: str, email: str, text: str
+ ) -> dict[str, str]:
+ """The server-injected ``{$...}`` variables for one create call.
+
+ ``$creator`` is the name the creator goes by on the template's bridge,
+ the identity they have linked there, which is what ``users:``
+ resolution and channel invites understand. A bridged template that
+ uses ``{$creator}`` is refused without such a link rather than guessed
+ from the gateway account name, which is rarely a platform account.
+ Without a bridge there is nobody to invite, so the gateway name stands
+ in.
+ """
+ creator = name
+ bridge_id = await self._peek_bridge_id(text)
+ if bridge_id is not None:
+ async with self._session_factory() as session:
+ claimed = await self._external_users.get_by_user(session, user_id)
+ bridge = await self._bridge_store.get(session, bridge_id)
+ claim = next((ext for ext in claimed if ext.bridge_id == bridge_id), None)
+ if claim is not None:
+ creator = claim.external_username
+ elif "{$creator}" in text:
+ app = (
+ bridge.display_name if bridge is not None else "this messaging app"
+ )
+ raise ValueError(
+ f"this template puts you in the room as {{$creator}}, but you "
+ f"have no linked account on {app}. Link your account under "
+ "Identities, then create the room again"
+ )
+ return {
+ "$creator": creator,
+ "$creator_email": email,
+ "$date": str(date.today()),
+ "$timestamp": str(int(time.time())),
+ }
+
+ async def _peek_bridge_id(self, text: str) -> str | None:
+ """The bridge the template will land on, read before interpolation.
+
+ Best-effort: an unparseable template, an interpolated bridge name, or
+ an unknown bridge all answer None; parse/provision fails loudly later
+ when it matters. A template naming no bridge lands on the default one,
+ same as provisioning."""
+ try:
+ data = yaml.safe_load(text)
+ except yaml.YAMLError:
+ return None
+ if not isinstance(data, dict):
+ return None
+ room = data.get("room")
+ if not isinstance(room, dict):
+ return None
+ bridge = room.get("bridge")
+ if bridge is not None and (
+ not isinstance(bridge, str) or PLACEHOLDER_RE.search(bridge)
+ ):
+ return None
+ try:
+ return await self._resolve_bridge_id(bridge)
+ except ValueError:
+ return None
# ── Provision ───────────────────────────────────────────────────────────
async def provision(
- self, spec: RoomSpec, *, user_id: str, is_admin: bool
+ self,
+ spec: RoomSpec,
+ *,
+ user_id: str,
+ is_admin: bool,
+ kickoff: str | None = None,
+ creator_name: str | None = None,
) -> ProvisionResult:
+ """Create the room and everything the spec attaches to it.
+
+ ``kickoff`` is posted once the room exists, by the platform on the
+ creator's behalf (see ``_send_kickoff``); ``creator_name`` is how the
+ message names them.
+ """
bridge_id = await self._resolve_bridge_id(spec.bridge)
if spec.users and bridge_id is None:
raise ValueError(
@@ -366,6 +605,16 @@ class RoomYamlService:
room_id, spec.docs, user_id=user_id, failures=failures
)
+ if kickoff:
+ await self._send_kickoff(
+ result.room,
+ kickoff,
+ agent_names=spec.agents,
+ user_id=user_id,
+ user_name=creator_name,
+ failures=failures,
+ )
+
return ProvisionResult(
room_id=room_id,
room_name=result.room.name,
@@ -378,7 +627,9 @@ class RoomYamlService:
async def _resolve_bridge_id(self, bridge_name: str | None) -> str | None:
if bridge_name is None:
- return None
+ async with self._session_factory() as session:
+ default = await self._bridge_store.get_default(session)
+ return default.id if default else None
async with self._session_factory() as session:
bridges = await self._bridge_store.get_all(session)
matches = [b for b in bridges if b.display_name == bridge_name]
@@ -497,6 +748,106 @@ class RoomYamlService:
await session.commit()
return created
+ # ── Kickoff ───────────────────────────────────────────────────────────
+
+ async def _send_kickoff(
+ self,
+ room: Room,
+ text: str,
+ *,
+ agent_names: list[str],
+ user_id: str,
+ user_name: str | None,
+ failures: list[dict[str, Any]],
+ ) -> None:
+ """Post the kickoff into the room the template just created.
+
+ Switch posts it on the creator's behalf, so nobody is impersonated:
+ the message renders as the app, and each agent it mentions applies
+ its policy to the creator, for this one event. It goes out as a
+ one-line headline in the channel plus the text in that headline's
+ thread, so the channel keeps one line per kickoff.
+
+ Best-effort like references and docs: a kickoff that cannot be posted
+ is reported in ``failures``, not fatal. The agents are waited for
+ first, because a client drops events that land before its own join.
+ """
+
+ def fail(error: str) -> None:
+ failures.append({"kind": "kickoff", "id": "kickoff", "error": error})
+
+ if self._client_lifecycle is None:
+ fail("kickoff posting is not configured on this server")
+ return
+ admins = self._client_lifecycle.get_by_type("admin", room.tenant_id)
+ admin = next((c for c in admins if isinstance(c, AdminClient)), None)
+ if admin is None:
+ fail("the platform has no client to post with")
+ return
+
+ late = await self._wait_for_kickoff_audience(
+ room.matrix_room_id, admin, agent_names
+ )
+ if late:
+ fail("did not join the room in time to see the kickoff: " + ", ".join(late))
+ if "the platform" in late:
+ return
+
+ person = OnBehalfOf(user_id, user_name or user_id)
+ headline = f"Template kickoff on behalf of @{person.name}"
+ try:
+ root_id = await admin.send_platform_message(
+ room.matrix_room_id, headline, on_behalf_of=person
+ )
+ if root_id is None:
+ fail("the platform could not post the kickoff")
+ return
+ event_id = await admin.send_platform_message(
+ room.matrix_room_id,
+ text,
+ thread_root_id=root_id,
+ on_behalf_of=person,
+ reply_in_channel=True,
+ )
+ except Exception as e:
+ fail(str(e))
+ return
+ if event_id is None:
+ fail("the platform posted the kickoff headline but not its thread")
+
+ async def _wait_for_kickoff_audience(
+ self,
+ matrix_room_id: str,
+ admin: AdminClient,
+ agent_names: list[str],
+ ) -> list[str]:
+ """Wait for the sender and the template's agents to be in the room.
+
+ Returns the names of those that were not joined within the timeout:
+ "the platform" for the sender itself, else the agent's name. An agent
+ with no running client is not waited for; it is not in the room to
+ miss anything.
+ """
+ late: list[str] = []
+ if not await admin.wait_joined(matrix_room_id, KICKOFF_JOIN_TIMEOUT):
+ late.append("the platform")
+ if not agent_names or self._client_lifecycle is None:
+ return late
+ async with self._session_factory() as session:
+ agents = await self._agent_store.get_by_names(session, agent_names)
+ for agent in agents:
+ client = self._client_lifecycle.get_by_agent_id(agent.id)
+ if client is None:
+ continue
+ try:
+ joined = await client.wait_joined(matrix_room_id, KICKOFF_JOIN_TIMEOUT)
+ except RuntimeError:
+ # Not connected: it is not receiving anything either way.
+ continue
+ if not joined:
+ late.append(agent.name)
+ return late
+
# ── Export ────────────────────────────────────────────────────────────
async def export(
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_read_context.py b/core/tests/switch_core/bridges/agent/protocol/test_read_context.py
index 79b617e1c..9fa37a9aa 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_read_context.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_read_context.py
@@ -23,6 +23,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.attachments import ATTACHMENT_GROUP_KEY
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.clients.admin_messages import PLATFORM_MARKER
from switch_core.db.models import Client, Message, MessageAttachment, Room
from switch_core.db.stores.message_store import MessageStore
@@ -291,6 +292,74 @@ class TestEntries:
assert result["threads"][0]["root"]["sender_name"] == "@x:s"
+ async def test_a_platform_message_carries_its_kind_and_the_person_behind_it(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """A kickoff the platform posted for someone reads back with both
+ facts, from the stored content; an ordinary row carries neither."""
+ async with session_factory() as session:
+ room_id, client_id = await _make_room(session)
+ await _write(session, room_id, client_id, "$plain", at=0)
+ await _write(
+ session,
+ room_id,
+ client_id,
+ "$kick",
+ at=1,
+ sender="@switch-admin:s",
+ sender_name=None,
+ body="@scout go",
+ content={
+ "body": "@scout go",
+ PLATFORM_MARKER: {
+ "on_behalf_of": {"user_id": "user-9", "name": "Abel"}
+ },
+ },
+ )
+ await session.commit()
+
+ result = await _service(session_factory).read_context("agent-1", room_id)
+
+ by_id = {t["root"]["id"]: t["root"] for t in result["threads"]}
+ assert "sender_kind" not in by_id["$plain"]
+ assert "on_behalf_of" not in by_id["$plain"]
+ assert by_id["$kick"]["sender_kind"] == "platform"
+ assert by_id["$kick"]["on_behalf_of"] == "Abel"
+
+ async def test_a_kickoff_flagged_for_the_channel_reads_as_its_own_root(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ """Threaded under the headline in the room, top-level in the history
+ an agent reads, so the work it starts is answered in the channel."""
+ async with session_factory() as session:
+ room_id, client_id = await _make_room(session)
+ await _write(
+ session, room_id, client_id, "$head", at=0, body="Template kickoff"
+ )
+ await _write(
+ session,
+ room_id,
+ client_id,
+ "$kick",
+ at=1,
+ thread_root="$head",
+ body="@scout go",
+ content={
+ "body": "@scout go",
+ PLATFORM_MARKER: {
+ "on_behalf_of": {"user_id": "user-9", "name": "Abel"},
+ "reply_in_channel": True,
+ },
+ },
+ )
+ await session.commit()
+
+ result = await _service(session_factory).read_context("agent-1", room_id)
+
+ roots = {t["root"]["id"]: t for t in result["threads"]}
+ assert set(roots) == {"$head", "$kick"}
+ assert roots["$head"]["replies"] == []
+
class TestTruncation:
"""`truncated` is now exact rather than conservative.
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py
new file mode 100644
index 000000000..5ee6ccb36
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_platform_rendering.py
@@ -0,0 +1,126 @@
+"""A platform message on its way out of Matrix renders as the Switch app, and
+says whose authority it carries when it was sent on a person's behalf.
+
+The kickoff a template posts is the case this exists for: the room has to see
+that Switch posted it for the creator, not a bare notice from the app and not
+a message pretending to be the person.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+from switch_core.clients.admin_messages import PLATFORM_MARKER
+from switch_core.transport import InboundMessage, RoomRef
+
+BODY = "@scout kicking off **task-1**."
+
+
+class _RecordingAdapter:
+ def __init__(self) -> None:
+ self.admin_calls: list[str] = []
+ self.message_calls: list[str] = []
+
+ def translate_outbound(self, content: str) -> str:
+ return content
+
+ async def admin_message(
+ self,
+ channel_id: str,
+ content: str,
+ thread_root_id: str | None = None,
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
+ self.admin_calls.append(content)
+ return "ref-admin"
+
+ async def send_message(
+ self,
+ channel_id: str,
+ sender_name: str,
+ content: str,
+ thread_root_id: str | None = None,
+ ) -> str | None:
+ self.message_calls.append(content)
+ return "ref-msg"
+
+
+async def _noop(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+
+async def _tenant(*_args: Any, **_kwargs: Any) -> str:
+ return "tenant-1"
+
+
+def _bridge(adapter: _RecordingAdapter) -> BridgeCore:
+ core = object.__new__(BridgeCore)
+ core._adapter = adapter # type: ignore[assignment]
+ core._puppet_matrix_ids = set() # type: ignore[assignment]
+ core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]
+ core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]
+ core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]
+ core._room_tenant = _tenant # type: ignore[assignment]
+ core._record_message_map = _noop # type: ignore[assignment]
+ core._move_indicator_for_sender = _noop # type: ignore[assignment]
+ core._outbound_thread_root_ref = _noop # type: ignore[assignment]
+ return core
+
+
+def _event(
+ marker: dict[str, Any], body: str = BODY, threaded: bool = False
+) -> InboundMessage:
+ content: dict[str, Any] = {PLATFORM_MARKER: marker}
+ if threaded:
+ content["m.relates_to"] = {"rel_type": "m.thread", "event_id": "$root"}
+ return InboundMessage(
+ room_id="!r:switch.local",
+ event_id="$e1",
+ sender="@switch-admin:switch.local",
+ timestamp=1700000000000,
+ content=content,
+ body=body,
+ sender_name=None,
+ )
+
+
+async def test_a_bare_platform_message_renders_as_the_app() -> None:
+ adapter = _RecordingAdapter()
+ await _bridge(adapter).handle_outbound_message(
+ RoomRef("!r:switch.local"), _event({})
+ )
+ assert adapter.admin_calls == [BODY]
+ assert adapter.message_calls == []
+
+
+async def test_a_message_on_someones_behalf_says_so() -> None:
+ adapter = _RecordingAdapter()
+ marker = {"on_behalf_of": {"user_id": "user-9", "name": "Abel"}}
+ await _bridge(adapter).handle_outbound_message(
+ RoomRef("!r:switch.local"), _event(marker)
+ )
+ assert adapter.admin_calls == [f"On behalf of @Abel:\n\n{BODY}"]
+ assert adapter.message_calls == []
+
+
+async def test_a_body_that_already_names_the_person_is_left_alone() -> None:
+ # The kickoff headline is that body: one line, no second attribution.
+ adapter = _RecordingAdapter()
+ marker = {"on_behalf_of": {"user_id": "user-9", "name": "Abel"}}
+ await _bridge(adapter).handle_outbound_message(
+ RoomRef("!r:switch.local"),
+ _event(marker, body="Template kickoff on behalf of @Abel"),
+ )
+ assert adapter.admin_calls == ["Template kickoff on behalf of @Abel"]
+
+
+async def test_a_thread_reply_is_not_prefixed() -> None:
+ # It sits under a root that said whose it is.
+ adapter = _RecordingAdapter()
+ marker = {"on_behalf_of": {"user_id": "user-9", "name": "Abel"}}
+ await _bridge(adapter).handle_outbound_message(
+ RoomRef("!r:switch.local"), _event(marker, threaded=True)
+ )
+ assert adapter.admin_calls == [BODY]
diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py b/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py
new file mode 100644
index 000000000..28db8526d
--- /dev/null
+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_user_resolution.py
@@ -0,0 +1,143 @@
+"""User resolution on a bridge: directory hits persist, and a Switch user
+resolves to their platform identity claims-first.
+
+A directory hit used to answer the caller and leave no record, so the next
+step that read the database (room membership, addressing, export) did not see
+the person the resolution had just found. These tests pin the persisted-hit
+behaviour.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.collaboration.bridge_core import BridgeCore
+from switch_core.bridges.collaboration.models import DirectoryUser
+from switch_core.db.models import (
+ TENANT_ZERO_ID,
+ Client,
+ CollaborationBridge,
+)
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.external_user_store import ExternalUserStore
+
+
+class _DirectoryAdapter:
+ """Serves one directory; counts lookups so the DB fast path is provable."""
+
+ def __init__(self, directory: list[DirectoryUser]) -> None:
+ self.directory = directory
+ self.searches: list[str] = []
+
+ async def search_directory_users(self, query: str) -> list[DirectoryUser]:
+ self.searches.append(query)
+ return self.directory
+
+ def prime_mention_targets(self, targets: dict[str, str]) -> None:
+ pass
+
+
+class _FakeLifecycle:
+ """Creates a real Client row (the ExternalUser FK needs one) and hands
+ back its id the way `create_and_start` does."""
+
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._sf = session_factory
+
+ async def create_and_start(
+ self, *, client_type: str, display_name: str, localpart: str
+ ):
+ async with self._sf() as session:
+ client = Client(
+ matrix_user_id=f"@{localpart}:test.local",
+ display_name=display_name,
+ type=client_type,
+ )
+ session.add(client)
+ await session.commit()
+
+ class _Handle:
+ client_id = client.id
+ matrix_user_id = client.matrix_user_id
+
+ return _Handle()
+
+
+async def _seed_bridge(session_factory) -> str:
+ async with session_factory() as session:
+ bridge_client = Client(
+ matrix_user_id="@bridge:test.local",
+ display_name="bridge",
+ type="collaboration_bridge",
+ )
+ session.add(bridge_client)
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name="Slack",
+ client_id=bridge_client.id,
+ status="active",
+ )
+ session.add(bridge)
+ await session.commit()
+ return bridge.id
+
+
+def _core(
+ session_factory,
+ bridge_id: str,
+ adapter: _DirectoryAdapter,
+) -> BridgeCore:
+ core = object.__new__(BridgeCore)
+ core._bridge_id = bridge_id
+ core._bridge_type = "slack"
+ core._adapter = adapter
+ core._session_factory = session_factory
+ core._external_user_store = ExternalUserStore()
+ core._agent_store = AgentStore()
+ core._client_lifecycle = _FakeLifecycle(session_factory)
+ core._user_puppets = {}
+ core._puppet_locks = {}
+ core._puppet_matrix_ids = set()
+ core._bridge_tenant_id = TENANT_ZERO_ID
+ return core
+
+
+CAROL = DirectoryUser(
+ external_user_id="U-carol",
+ username="carol",
+ display_name="Carol",
+)
+
+
+async def test_directory_hit_is_persisted(session_factory):
+ bridge_id = await _seed_bridge(session_factory)
+ adapter = _DirectoryAdapter([CAROL])
+ core = _core(session_factory, bridge_id, adapter)
+
+ resolved = await core.resolve_external_user_id_map(["carol"])
+ assert resolved == {"carol": "U-carol"}
+
+ async with session_factory() as session:
+ row = await ExternalUserStore().get_by_external_id(
+ session, bridge_id, "U-carol"
+ )
+ assert row is not None
+ assert row.external_username == "carol"
+
+ # Second resolution answers from the database, not the platform.
+ resolved_again = await core.resolve_external_user_id_map(["carol"])
+ assert resolved_again == {"carol": "U-carol"}
+ assert adapter.searches == ["carol"]
+
+
+async def test_directory_matches_email_case_insensitively(session_factory):
+ bridge_id = await _seed_bridge(session_factory)
+ core = _core(session_factory, bridge_id, _DirectoryAdapter([CAROL]))
+
+ resolved = await core.resolve_external_user_id_map(["[email protected]"])
+ assert resolved == {"[email protected]": "U-carol"}
diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.py
index 6d67e1df6..1bc1a6900 100644
--- a/core/tests/switch_core/clients/test_addressing_enforcement.py
+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from contextlib import asynccontextmanager
from types import SimpleNamespace
+from switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKER
from switch_core.clients.agent_client import AUTO_REPLY_FLAG, AgentClient
from switch_core.delivery.addressing import (
ADDRESSING_DENIED_MESSAGE as _ADDRESSING_DENIED_MESSAGE,
@@ -82,7 +83,7 @@ class TestResolveSenderPrincipal:
result = await AddressingResolver.resolve_sender(
client, object(), "@a:switch.local"
)
- assert result == ("agent", "agent-7", [], "user-1")
+ assert result == ("agent", "agent-7", [], "user-1", None)
async def test_human_sender_claimed(self) -> None:
client = self._client(
@@ -94,7 +95,7 @@ class TestResolveSenderPrincipal:
result = await AddressingResolver.resolve_sender(
client, object(), "@u:switch.local"
)
- assert result == ("user", "ext-3", ["user-1"], None)
+ assert result == ("user", "ext-3", ["user-1"], None, None)
async def test_human_sender_claimed_by_several(self) -> None:
# Claiming is not exclusive, so the principal carries every claimant
@@ -108,7 +109,7 @@ class TestResolveSenderPrincipal:
result = await AddressingResolver.resolve_sender(
client, object(), "@u:switch.local"
)
- assert result == ("user", "ext-3", ["user-1", "user-2"], None)
+ assert result == ("user", "ext-3", ["user-1", "user-2"], None, None)
async def test_human_sender_unclaimed(self) -> None:
# Nobody has linked this platform identity to a Switch user.
@@ -120,7 +121,7 @@ class TestResolveSenderPrincipal:
result = await AddressingResolver.resolve_sender(
client, object(), "@u:switch.local"
)
- assert result == ("user", "ext-3", [], None)
+ assert result == ("user", "ext-3", [], None, None)
async def test_unknown_client_is_none(self) -> None:
client = self._client(client=None, agent=None, external_user=None)
@@ -130,16 +131,60 @@ class TestResolveSenderPrincipal:
assert result is None
async def test_client_with_no_agent_or_external_user_is_none(self) -> None:
- # A Client that is neither an agent nor a bridged human (e.g. a system
- # client) does not resolve to an addressing principal.
+ # A Client that is neither an agent nor a bridged human and is not the
+ # admin (e.g. a bridge client) does not resolve to an addressing principal.
client = self._client(
- client=SimpleNamespace(id="c1"), agent=None, external_user=None
+ client=SimpleNamespace(id="c1", type="bridge"),
+ agent=None,
+ external_user=None,
)
result = await AddressingResolver.resolve_sender(
client, object(), "@system:switch.local"
)
assert result is None
+ async def test_admin_client_resolves_to_platform(self) -> None:
+ # The admin client resolves to sender_kind="platform".
+ client = self._client(
+ client=SimpleNamespace(id="c1", type="admin"),
+ agent=None,
+ external_user=None,
+ )
+ result = await AddressingResolver.resolve_sender(
+ client, object(), "@switch-admin:switch.local"
+ )
+ assert result == ("platform", "c1", [], None, None)
+
+ async def test_admin_client_carries_the_person_it_speaks_for(self) -> None:
+ client = self._client(
+ client=SimpleNamespace(id="c1", type="admin"),
+ agent=None,
+ external_user=None,
+ )
+ content = {
+ _PLATFORM_MARKER: {"on_behalf_of": {"user_id": "user-9", "name": "Abel"}}
+ }
+ result = await AddressingResolver.resolve_sender(
+ client, object(), "@switch-admin:switch.local", content
+ )
+ assert result == ("platform", "c1", [], None, "user-9")
+
+ async def test_marker_on_a_human_sender_is_ignored(self) -> None:
+ # Only the admin client's marker is read: a human or agent event that
+ # carries a copy of it borrows no authority.
+ client = self._client(
+ client=SimpleNamespace(id="c1", type="external_user"),
+ agent=None,
+ external_user=SimpleNamespace(id="ext-3"),
+ )
+ content = {
+ _PLATFORM_MARKER: {"on_behalf_of": {"user_id": "user-9", "name": "Abel"}}
+ }
+ result = await AddressingResolver.resolve_sender(
+ client, object(), "@u:switch.local", content
+ )
+ assert result == ("user", "ext-3", [], None, None)
+
def _allowed_client(
*,
@@ -148,6 +193,8 @@ def _allowed_client(
sender_owner_id: str | None = None,
group_id: str | None = None,
owner_id: str | None = None,
+ on_behalf_of: str | None = None,
+ claimed_external_ids: tuple[str, ...] = (),
) -> SimpleNamespace:
"""Fake resolver for `permitted`: the agent carries `policy` and is owned
by `owner_id`, the sender resolves to `principal` (kind, id, claimants)
@@ -155,30 +202,46 @@ def _allowed_client(
agent = SimpleNamespace(name="fixer", addressing_policy=policy, owner_id=owner_id)
- async def _resolve(_session, _mxid): # type: ignore[no-untyped-def]
+ async def _resolve(_session, _mxid, _content=None): # type: ignore[no-untyped-def]
if principal is None:
return None
kind, sender_id, claimants = principal
- return _SenderPrincipal(kind, sender_id, claimants, sender_owner_id) # type: ignore[arg-type]
+ return _SenderPrincipal( # type: ignore[arg-type]
+ kind, sender_id, claimants, sender_owner_id, on_behalf_of=on_behalf_of
+ )
async def _get_room(_session, _room_id): # type: ignore[no-untyped-def]
return SimpleNamespace(group_id=group_id)
+ async def _claimed(_session, _user_id): # type: ignore[no-untyped-def]
+ return [SimpleNamespace(id=ext_id) for ext_id in claimed_external_ids]
+
return SimpleNamespace(
agent=agent,
resolve_sender=_resolve,
_room_store=SimpleNamespace(get=_get_room),
+ _external_user_store=SimpleNamespace(get_by_user=_claimed),
)
-async def _decide(client: SimpleNamespace, room_id: str = "room-1"): # type: ignore[no-untyped-def]
+async def _decide( # type: ignore[no-untyped-def]
+ client: SimpleNamespace, room_id: str = "room-1", content: dict | None = None
+):
# No session is opened here: the resolver reads through the one it is
# handed, so `permitted` never takes a pool slot of its own.
return await AddressingResolver.permitted(
- client, object(), agent=client.agent, room_id=room_id, sender="@u:switch.local"
+ client,
+ object(),
+ agent=client.agent,
+ room_id=room_id,
+ sender="@u:switch.local",
+ content=content,
)
+PLATFORM_CONTENT = {_PLATFORM_MARKER: {}}
+
+
class TestAddressingAllowed:
async def test_open_policy_allows_without_lookup(self) -> None:
# No policy → open; must not even need a resolvable sender.
@@ -217,6 +280,80 @@ class TestAddressingAllowed:
assert (await _decide(denied)).allowed is False
+class TestPlatformAddressing:
+ """The platform's own messages are denied unless a rule opts the agent
+ in, even by an open policy. A message it sends on a person's behalf is
+ judged as that person, for that one event."""
+
+ async def test_open_policy_denies_bare_platform(self) -> None:
+ client = _allowed_client(policy=None, principal=("platform", "c1", []))
+ decision = await _decide(client, content=PLATFORM_CONTENT)
+ assert decision.allowed is False
+ assert decision.refusal == _ADDRESSING_DENIED_MESSAGE
+
+ async def test_platform_rule_admits_bare_platform(self) -> None:
+ policy = {"rules": [{"users": [], "agents": [], "platform": True}]}
+ client = _allowed_client(policy=policy, principal=("platform", "c1", []))
+ assert (await _decide(client, content=PLATFORM_CONTENT)).allowed is True
+
+ async def test_open_policy_admits_platform_on_behalf_of_anyone(self) -> None:
+ client = _allowed_client(
+ policy=None, principal=("platform", "c1", []), on_behalf_of="user-9"
+ )
+ assert (await _decide(client, content=PLATFORM_CONTENT)).allowed is True
+
+ async def test_owner_rule_admits_platform_on_behalf_of_the_owner(self) -> None:
+ policy = {"rules": [{"users": [], "agents": [], "owner": True}]}
+ as_owner = _allowed_client(
+ policy=policy,
+ principal=("platform", "c1", []),
+ owner_id="user-9",
+ on_behalf_of="user-9",
+ )
+ as_stranger = _allowed_client(
+ policy=policy,
+ principal=("platform", "c1", []),
+ owner_id="user-9",
+ on_behalf_of="user-2",
+ )
+ assert (await _decide(as_owner, content=PLATFORM_CONTENT)).allowed is True
+ assert (await _decide(as_stranger, content=PLATFORM_CONTENT)).allowed is False
+
+ async def test_users_list_admits_platform_via_a_claimed_account(self) -> None:
+ policy = {"rules": [{"users": ["ext-3"], "agents": []}]}
+ claimed = _allowed_client(
+ policy=policy,
+ principal=("platform", "c1", []),
+ on_behalf_of="user-9",
+ claimed_external_ids=("ext-1", "ext-3"),
+ )
+ unclaimed = _allowed_client(
+ policy=policy,
+ principal=("platform", "c1", []),
+ on_behalf_of="user-9",
+ )
+ assert (await _decide(claimed, content=PLATFORM_CONTENT)).allowed is True
+ assert (await _decide(unclaimed, content=PLATFORM_CONTENT)).allowed is False
+
+ async def test_on_behalf_of_never_reaches_a_platform_rule(self) -> None:
+ # A platform opt-in admits the platform's own voice, not everyone it
+ # might speak for: the person is judged as a user, and this rule
+ # admits no users.
+ policy = {"rules": [{"users": [], "agents": [], "platform": True}]}
+ client = _allowed_client(
+ policy=policy, principal=("platform", "c1", []), on_behalf_of="user-9"
+ )
+ assert (await _decide(client, content=PLATFORM_CONTENT)).allowed is False
+
+ async def test_marked_event_from_a_human_keeps_the_open_fast_path(self) -> None:
+ # The marker on a non-platform sender is noise: an open policy still
+ # admits them, and a restricted one judges them as themselves.
+ open_client = _allowed_client(policy=None, principal=("user", "ext-3", []))
+ assert (await _decide(open_client, content=PLATFORM_CONTENT)).allowed is True
+ unresolved = _allowed_client(policy=None, principal=None)
+ assert (await _decide(unresolved, content=PLATFORM_CONTENT)).allowed is True
+
+
class TestOwnerAddressing:
"""An owner-scoped policy resolves the owner at enforcement time from the
agent's `owner_id` and the Switch users who have claimed the sender's
@@ -375,7 +512,9 @@ def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE):
"""Fake client for _gate_addressed and the auto-reply it hands back."""
sent: list[dict] = []
- async def _addressing_allowed(_session, _agent, _matrix_sender, _room_id): # type: ignore[no-untyped-def]
+ async def _addressing_allowed(
+ _session, _agent, _matrix_sender, _room_id, _content=None
+ ): # type: ignore[no-untyped-def]
return _AddressingDecision(allowed=allowed, refusal="" if allowed else refusal)
async def _send_message(room_id, body, **kwargs): # type: ignore[no-untyped-def]
@@ -473,7 +612,9 @@ def _command_client(*, allowed: bool, targets_me: bool): # type: ignore[no-unty
"""Fake client for _gate_command: records any command reply posted."""
replies: list[dict] = []
- async def _addressing_allowed(_session, _agent, _matrix_sender, _room_id): # type: ignore[no-untyped-def]
+ async def _addressing_allowed(
+ _session, _agent, _matrix_sender, _room_id, _content=None
+ ): # type: ignore[no-untyped-def]
return _AddressingDecision(
allowed=allowed, refusal="" if allowed else _ADDRESSING_DENIED_MESSAGE
)
diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.py
index e07f91a94..99467989b 100644
--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py
+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py
@@ -5,6 +5,7 @@ from types import SimpleNamespace
import pytest
+from switch_core.clients.admin_messages import PLATFORM_MARKER
from switch_core.clients.agent_client import (
_STARTING_SESSION_MESSAGE,
AUTO_REPLY_FLAG,
@@ -264,3 +265,22 @@ class TestTerminalReplyThreadsOffTheTrigger:
)
assert send_message.calls[0]["thread_root_id"] == "$thread-root"
+
+
+async def test_a_kickoff_that_wants_the_channel_gets_its_reply_at_top_level() -> None:
+ # The template kickoff sits in a thread to keep the channel to one line,
+ # but flags that the work belongs in the channel: the agent's reply goes
+ # to the top level, not under the kickoff.
+ send_message = _Recorder()
+ room = RoomRef(room_id="!matrix:server")
+ event = _event(thread_id="$kickoff-headline")
+ event.content[PLATFORM_MARKER] = {
+ "on_behalf_of": {"user_id": "u9", "name": "dantas.abel"},
+ "reply_in_channel": True,
+ }
+ await AgentClient.on_message(_fake_self(send_message), room, event)
+
+ assert len(send_message.calls) == 1
+ assert send_message.calls[0]["thread_root_id"] is None
+ assert send_message.calls[0]["body"].startswith("@dantas.abel ")
diff --git a/core/tests/switch_core/clients/test_platform_sender_replies.py b/core/tests/switch_core/clients/test_platform_sender_replies.py
new file mode 100644
index 000000000..7827a3e78
--- /dev/null
+++ b/core/tests/switch_core/clients/test_platform_sender_replies.py
@@ -0,0 +1,47 @@
+"""An agent answers the person a platform message spoke for, not the admin
+client that carried it. The kickoff a template posts is the case: replying
+"@admin" named a client nobody is, while the creator waited unaddressed."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from switch_core.clients.admin_messages import PLATFORM_MARKER
+from switch_core.clients.agent_client import AgentClient
+from switch_core.transport import InboundMessage
+
+
+def _event(content: dict) -> InboundMessage:
+ return InboundMessage(
+ room_id="!r:switch.local",
+ event_id="$e",
+ sender="@switch-admin:switch.local",
+ timestamp=1700000000000,
+ content=content,
+ body="@fixer go",
+ sender_name="admin",
+ )
+
+
+def _handle(event: InboundMessage) -> str:
+ ns = SimpleNamespace()
+ return AgentClient._sender_handle(ns, event) # type: ignore[arg-type]
+
+
+def test_reply_handle_is_the_person_behind_a_platform_message() -> None:
+ content = {
+ "sender_name": "admin",
+ PLATFORM_MARKER: {"on_behalf_of": {"user_id": "u9", "name": "dantas.abel"}},
+ }
+ assert _handle(_event(content)) == "dantas.abel"
+
+
+def test_reply_handle_stays_the_sender_for_a_bare_platform_message() -> None:
+ assert _handle(_event({"sender_name": "admin", PLATFORM_MARKER: {}})) == "admin"
+
+
+def test_reply_handle_ignores_a_marker_without_a_person() -> None:
+ assert (
+ _handle(_event({"sender_name": "human", PLATFORM_MARKER: {"on_behalf_of": {}}}))
+ == "human"
+ )
diff --git a/core/tests/switch_core/test_addressing.py b/core/tests/switch_core/test_addressing.py
index 78d0c7fc9..815126789 100644
--- a/core/tests/switch_core/test_addressing.py
+++ b/core/tests/switch_core/test_addressing.py
@@ -10,6 +10,7 @@ from switch_core.addressing import (
owner_and_owner_agents_policy,
owner_only_policy,
parse_policy,
+ platform_allowed_policy,
)
@@ -458,6 +459,7 @@ class TestOwnerAndOwnerAgentsPolicy:
"agents": [],
"owner": True,
"owner_agents": True,
+ "platform": False,
}
]
}
@@ -578,6 +580,7 @@ class TestOwnerOnlyPolicy:
"agents": ["a1"],
"owner": True,
"owner_agents": False,
+ "platform": False,
}
]
}
@@ -629,3 +632,144 @@ class TestValidation:
# A pre-CHOO-2137 blob has no `owner` key; it must not become truthy.
policy = parse_policy({"rules": [{"users": ["u1"], "agents": []}]})
assert policy.requires_owner_identity() is False
+
+ def test_stored_policy_without_platform_key_defaults_to_false(self) -> None:
+ # A policy stored before the platform key existed must deny the platform.
+ policy = parse_policy({"rules": [{"users": ["u1"], "agents": []}]})
+ assert policy.rules[0].platform is False
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_platform_flag_roundtrips(self) -> None:
+ policy = platform_allowed_policy()
+ assert parse_policy(policy.model_dump()) == policy
+
+
+class TestPlatformSenderKind:
+ """Platform senders are always denied unless explicitly allowed.
+
+ Unlike user/agent, an open policy (no rules) also refuses the platform.
+ This is "deny by default with no configuration needed."
+ """
+
+ def test_open_policy_denies_platform(self) -> None:
+ policy = AddressingPolicy()
+ assert policy.is_open() is True
+ # Users and agents still allowed; only platform is refused.
+ assert _allows(policy, sender_kind="user", sender_id="u1") is True
+ assert _allows(policy, sender_kind="agent", sender_id="a1") is True
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_rules_without_platform_deny_it(self) -> None:
+ # A rule admitting everyone (wildcard users + agents) still denies platform.
+ policy = AddressingPolicy(rules=[AddressingRule()])
+ assert _allows(policy, sender_kind="user", sender_id="u1") is True
+ assert _allows(policy, sender_kind="agent", sender_id="a1") is True
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_platform_rule_allows_it(self) -> None:
+ policy = AddressingPolicy(
+ rules=[AddressingRule(users=[], agents=[], platform=True)]
+ )
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is True
+
+ def test_platform_rule_respects_room_scoping(self) -> None:
+ policy = AddressingPolicy(
+ rules=[AddressingRule(rooms=["r1"], users=[], agents=[], platform=True)]
+ )
+ assert (
+ _allows(policy, room_id="r1", sender_kind="platform", sender_id="switch")
+ is True
+ )
+ assert (
+ _allows(policy, room_id="r2", sender_kind="platform", sender_id="switch")
+ is False
+ )
+
+ def test_platform_rule_respects_group_scoping(self) -> None:
+ policy = AddressingPolicy(
+ rules=[
+ AddressingRule(room_groups=["g1"], users=[], agents=[], platform=True)
+ ]
+ )
+ assert (
+ _allows(policy, group_id="g1", sender_kind="platform", sender_id="switch")
+ is True
+ )
+ assert (
+ _allows(policy, group_id="g2", sender_kind="platform", sender_id="switch")
+ is False
+ )
+
+ def test_platform_does_not_fall_through_to_agents_dim(self) -> None:
+ # A wildcard agents dimension must NOT admit platform: the platform
+ # early return in _matches() prevents the fallthrough.
+ policy = AddressingPolicy(rules=[AddressingRule(agents="*")])
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_platform_flag_off_by_default_for_old_policies(self) -> None:
+ # A policy stored before the platform key existed carries none; it must
+ # default to False rather than silently admitting the platform.
+ policy = parse_policy({"rules": [{"users": [], "agents": [], "owner": True}]})
+ assert policy.rules[0].platform is False
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_owner_only_policy_denies_platform(self) -> None:
+ policy = owner_only_policy([])
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_owner_and_owner_agents_policy_denies_platform(self) -> None:
+ policy = owner_and_owner_agents_policy()
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is False
+
+ def test_platform_allowed_policy_shape(self) -> None:
+ policy = platform_allowed_policy()
+ assert policy.model_dump() == {
+ "rules": [
+ {
+ "rooms": "*",
+ "room_groups": "*",
+ "users": [],
+ "agents": [],
+ "owner": False,
+ "owner_agents": False,
+ "platform": True,
+ }
+ ]
+ }
+
+ def test_platform_allowed_policy_admits_platform(self) -> None:
+ policy = platform_allowed_policy()
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is True
+
+ def test_platform_allowed_policy_denies_users_and_agents(self) -> None:
+ # Platform-only: no human, no agent.
+ policy = platform_allowed_policy()
+ assert _allows(policy, sender_kind="user", sender_id="u1") is False
+ assert _allows(policy, sender_kind="agent", sender_id="a1") is False
+
+ def test_mixed_rule_with_platform_and_owner(self) -> None:
+ # A single rule that admits the owner AND the platform.
+ policy = AddressingPolicy(
+ rules=[AddressingRule(users=[], agents=[], owner=True, platform=True)]
+ )
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-3",
+ sender_user_ids=["user-1"],
+ owner_user_id="user-1",
+ )
+ is True
+ )
+ assert _allows(policy, sender_kind="platform", sender_id="switch") is True
+ assert (
+ _allows(
+ policy,
+ sender_kind="user",
+ sender_id="ext-9",
+ sender_user_ids=["user-2"],
+ owner_user_id="user-1",
+ )
+ is False
+ )
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index 8aaa0d3b2..20752d80c 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -11,6 +11,7 @@ for real.
from __future__ import annotations
import uuid
+from typing import Any
import pytest
import pytest_asyncio
@@ -18,6 +19,8 @@ from sqlalchemy import insert, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.resource.service import ResourceService
+from switch_core.clients.admin_client import AdminClient
+from switch_core.clients.admin_messages import OnBehalfOf
from switch_core.db.models import (
Agent,
ApiKey,
@@ -25,6 +28,7 @@ from switch_core.db.models import (
ClientRoom,
CollaborationBridge,
ExternalUser,
+ ExternalUserClaim,
Reference,
ReferenceType,
Room,
@@ -53,6 +57,17 @@ from switch_core.rooms_yaml import (
)
+class _AnyStr:
+ def __eq__(self, other: object) -> bool:
+ return isinstance(other, str)
+
+ def __repr__(self) -> str:
+ return "<any str>"
+
+
+ANY_ROOM = _AnyStr()
+
+
class FakeRoomService:
"""DB-only stand-in for RoomService.create_room.
@@ -68,6 +83,15 @@ class FakeRoomService:
) -> None:
self._sf = session_factory
self._agents = agent_store
+ #: username → external id, the people a bridge would resolve.
+ self.bridge_users: dict[str, str] = {}
+ self.bridge_user_lookups: list[tuple[str, list[str]]] = []
+
+ async def resolve_bridge_users(
+ self, bridge_id: str, names: list[str]
+ ) -> dict[str, str]:
+ self.bridge_user_lookups.append((bridge_id, names))
+ return {n: self.bridge_users[n] for n in names if n in self.bridge_users}
async def create_room(self, config: RoomCreateConfig) -> RoomCreateResult:
async with self._sf() as session:
@@ -156,8 +180,9 @@ async def env(session_factory: async_sessionmaker[AsyncSession]):
session_factory=session_factory,
)
agent_store = AgentStore()
+ fake_rooms = FakeRoomService(session_factory, agent_store)
svc = RoomYamlService(
- room_service=FakeRoomService(session_factory, agent_store), # type: ignore[arg-type]
+ room_service=fake_rooms, # type: ignore[arg-type]
resource_service=resource_service,
room_store=RoomStore(),
agent_store=agent_store,
@@ -178,6 +203,7 @@ async def env(session_factory: async_sessionmaker[AsyncSession]):
return {
"svc": svc,
+ "rooms": fake_rooms,
"resource_service": resource_service,
"session_factory": session_factory,
"user_id": user_id,
@@ -192,7 +218,7 @@ def _svc(env) -> RoomYamlService:
def test_parse_minimal(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Room A"
@@ -204,6 +230,57 @@ def test_parse_minimal(env):
assert spec.references == []
+def test_parse_returns_kickoff(env):
+ spec, kickoff = _svc(env).parse(
+ """
+ room:
+ name: "Room K"
+ description: "desc"
+ kickoff: "Start working now."
+ """
+ )
+ assert spec.name == "Room K"
+ assert kickoff == "Start working now."
+
+
+def test_parse_no_kickoff_returns_none(env):
+ _, kickoff = _svc(env).parse(
+ """
+ room:
+ name: "Room N"
+ description: "desc"
+ """
+ )
+ assert kickoff is None
+
+
+def test_parse_kickoff_interpolates_builtins(env):
+ _, kickoff = _svc(env).parse(
+ """
+ room:
+ name: "Room B"
+ description: "desc"
+ kickoff: "Welcome {$creator}, today is {$date}."
+ """,
+ builtins={"$creator": "alice", "$date": "2026-09-11"},
+ )
+ assert kickoff == "Welcome alice, today is 2026-09-11."
+
+
+def test_parse_builtins_resolve_in_room(env):
+ spec, _ = _svc(env).parse(
+ """
+ room:
+ name: "{$creator}'s room"
+ description: "desc"
+ users: ["{$creator_email}"]
+ """,
+ builtins={"$creator": "alice", "$creator_email": "[email protected]"},
+ )
+ assert spec.name == "alice's room"
+ assert spec.users == ["[email protected]"]
+
+
def test_parse_rejects_missing_room_key(env):
with pytest.raises(ValueError, match="top-level 'room:'"):
_svc(env).parse("name: oops\ndescription: d\n")
@@ -266,7 +343,7 @@ def test_parse_reference_entry_requires_one_form(env):
@pytest.mark.asyncio
async def test_provision_basic_with_agents_roles_and_inline_ref(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Pilot"
@@ -299,7 +376,7 @@ async def test_provision_basic_with_agents_roles_and_inline_ref(env):
@pytest.mark.asyncio
async def test_provision_no_agents_or_users(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Agentless"
@@ -316,7 +393,7 @@ async def test_provision_no_agents_or_users(env):
@pytest.mark.asyncio
async def test_provision_unknown_agent_fails_loud(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -336,7 +413,7 @@ async def test_provision_unknown_reference_type_fails_before_the_room_exists(env
nor a principal — so the check lives in ``_resolve_references``, which runs
before ``create_room``. Nothing may be created.
"""
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Bad type"
@@ -388,7 +465,7 @@ async def test_provision_inline_ref_of_a_user_defined_type(env):
)
await session.commit()
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Custom type"
@@ -425,7 +502,7 @@ async def test_provision_attach_reference_by_name(env):
await session.commit()
ref_id = ref.id
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -441,7 +518,7 @@ async def test_provision_attach_reference_by_name(env):
@pytest.mark.asyncio
async def test_provision_attach_reference_by_name_unknown_fails(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -472,7 +549,7 @@ async def test_provision_ambiguous_reference_name_fails(env):
)
await session.commit()
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -487,7 +564,7 @@ async def test_provision_ambiguous_reference_name_fails(env):
@pytest.mark.asyncio
async def test_provision_duplicate_doc_name_is_best_effort(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -507,7 +584,7 @@ async def test_provision_duplicate_doc_name_is_best_effort(env):
@pytest.mark.asyncio
async def test_provision_users_without_bridge_fails(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "R"
@@ -524,7 +601,7 @@ async def test_provision_users_without_bridge_fails(env):
@pytest.mark.asyncio
async def test_export_round_trips_within_import_surface(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Export me"
@@ -549,7 +626,7 @@ async def test_export_round_trips_within_import_surface(env):
result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
yaml_text = await _svc(env).export(result.room_id)
- reparsed = _svc(env).parse(yaml_text)
+ reparsed, _ = _svc(env).parse(yaml_text)
assert reparsed.name == "Export me"
assert reparsed.instructions == "instr"
@@ -567,7 +644,7 @@ async def test_export_round_trips_within_import_surface(env):
@pytest.mark.asyncio
async def test_export_toggles_drop_sections(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
room:
name: "Toggle"
@@ -584,7 +661,7 @@ async def test_export_toggles_drop_sections(env):
yaml_text = await _svc(env).export(
result.room_id, agents=False, roles=False, docs=False
)
- reparsed = _svc(env).parse(yaml_text)
+ reparsed, _ = _svc(env).parse(yaml_text)
assert reparsed.agents == []
assert reparsed.roles == []
assert reparsed.docs == []
@@ -646,7 +723,7 @@ async def test_export_includes_users_from_bridge(env):
room_id = room.id
yaml_text = await _svc(env).export(room_id)
- reparsed = _svc(env).parse(yaml_text)
+ reparsed, _ = _svc(env).parse(yaml_text)
# The "Mattermost: " display-name prefix is stripped on export.
assert reparsed.name == "Bridged"
assert reparsed.bridge == "Mattermost"
@@ -780,7 +857,7 @@ def test_interpolate_non_string_passthrough():
def test_parse_with_params_defaults_only(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
owner:
@@ -796,7 +873,7 @@ def test_parse_with_params_defaults_only(env):
def test_parse_with_params_override(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
owner:
@@ -853,7 +930,7 @@ def test_parse_inputs_against_paramless_file_raises(env):
def test_parse_unknown_placeholder_left_intact(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
owner:
@@ -869,7 +946,7 @@ def test_parse_unknown_placeholder_left_intact(env):
def test_parse_whole_field_typed_substitution(env):
"""An enum param used as the whole value of channel_type stays valid."""
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
visibility:
@@ -886,7 +963,7 @@ def test_parse_whole_field_typed_substitution(env):
def test_parse_interpolation_into_docs_content(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
owner:
@@ -906,7 +983,7 @@ def test_parse_interpolation_into_docs_content(env):
def test_parse_interpolation_into_references_value(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
params:
repo:
@@ -928,7 +1005,7 @@ def test_parse_interpolation_into_references_value(env):
def test_parse_version_key_accepted(env):
- spec = _svc(env).parse(
+ spec, _ = _svc(env).parse(
"""
version: 0
room:
@@ -995,18 +1072,14 @@ room:
async def test_provision_template_two_owners(env):
"""The same template instantiates twice with different owners."""
svc = _svc(env)
- r1 = await svc.provision(
- svc.parse(
- TEMPLATE, inputs={"owner": "alice", "deploy_agent": "claude-code.alice"}
- ),
- user_id=env["user_id"],
- is_admin=False,
+ spec1, _ = svc.parse(
+ TEMPLATE, inputs={"owner": "alice", "deploy_agent": "claude-code.alice"}
)
- r2 = await svc.provision(
- svc.parse(TEMPLATE, inputs={"owner": "bob", "deploy_agent": "claude-code.bob"}),
- user_id=env["user_id"],
- is_admin=False,
+ r1 = await svc.provision(spec1, user_id=env["user_id"], is_admin=False)
+ spec2, _ = svc.parse(
+ TEMPLATE, inputs={"owner": "bob", "deploy_agent": "claude-code.bob"}
)
+ r2 = await svc.provision(spec2, user_id=env["user_id"], is_admin=False)
assert r1.room_name == "alice local-deploy"
assert r2.room_name == "bob local-deploy"
assert r1.room_id != r2.room_id
@@ -1085,3 +1158,529 @@ async def test_endpoint_json_body(env):
with pytest.raises(HTTPException) as exc_info:
await create_room_from_yaml(request, session, svc, user, is_admin)
assert exc_info.value.status_code == 400
+
+
+# ── kickoff ─────────────────────────────────────────────────────────────────
+
+
+class FakeAdminClient(AdminClient):
+ """Records platform sends; never touches a transport."""
+
+ def __init__(self) -> None: # noqa: D107 - test double, no super().__init__
+ self.sent: list[dict[str, Any]] = []
+ self.joined = True
+ self.send_error: Exception | None = None
+ self.send_returns: str | None = "$kickoff"
+
+ async def wait_joined(self, room_id: str, timeout: float) -> bool:
+ return self.joined
+
+ async def send_platform_message( # type: ignore[override]
+ self,
+ room_id: str,
+ body: str,
+ *,
+ thread_root_id=None,
+ on_behalf_of=None,
+ reply_in_channel=False,
+ ) -> str | None:
+ if self.send_error is not None:
+ raise self.send_error
+ self.sent.append(
+ {
+ "room_id": room_id,
+ "body": body,
+ "on_behalf_of": on_behalf_of,
+ "thread_root_id": thread_root_id,
+ "reply_in_channel": reply_in_channel,
+ }
+ )
+ return self.send_returns
+
+
+class FakeAgentClient:
+ def __init__(self, joined: bool = True) -> None:
+ self.joined = joined
+
+ async def wait_joined(self, room_id: str, timeout: float) -> bool:
+ return self.joined
+
+
+class FakeLifecycle:
+ def __init__(self, admin: AdminClient | None) -> None:
+ self.admin = admin
+ self.agent_clients: dict[str, FakeAgentClient] = {}
+
+ def get_by_type(self, client_type: str, tenant_id: str) -> list:
+ if self.admin is not None and client_type == "admin":
+ return [self.admin]
+ return []
+
+ def get_by_agent_id(self, agent_id: str):
+ return self.agent_clients.get(agent_id)
+
+
+def _with_kickoff(
+ env, admin: AdminClient | None
+) -> tuple[RoomYamlService, FakeLifecycle]:
+ lifecycle = FakeLifecycle(admin)
+ svc = _svc(env)
+ svc._client_lifecycle = lifecycle # type: ignore[assignment]
+ return svc, lifecycle
+
+
+KICKOFF_TEMPLATE = """
+params:
+ coder:
+ type: agent
+room:
+ name: "kick"
+ description: "d"
+ agents: ["{coder}"]
+kickoff: |
+ @{coder} start on the brief.
+"""
+
+
+async def test_provision_kickoff_posts_as_platform_on_behalf_of_creator(env):
+ """The kickoff goes out through the admin client with the creator named
+ in the marker, after interpolation, and the room reports no failure."""
+ admin = FakeAdminClient()
+ svc, _ = _with_kickoff(env, admin)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec,
+ kickoff=kickoff,
+ user_id=env["user_id"],
+ is_admin=False,
+ creator_name="alice",
+ )
+ assert result.failed_attachments == []
+ person = OnBehalfOf(env["user_id"], "alice")
+ assert admin.sent == [
+ {
+ "room_id": ANY_ROOM,
+ "body": "Template kickoff on behalf of @alice",
+ "on_behalf_of": person,
+ "thread_root_id": None,
+ "reply_in_channel": False,
+ },
+ {
+ "room_id": ANY_ROOM,
+ "body": "@claude-code.alice start on the brief.\n",
+ "on_behalf_of": person,
+ "thread_root_id": "$kickoff",
+ "reply_in_channel": True,
+ },
+ ]
+
+
+async def test_provision_kickoff_send_failure_is_reported_not_fatal(env):
+ admin = FakeAdminClient()
+ admin.send_error = RuntimeError("transport down")
+ svc, _ = _with_kickoff(env, admin)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert result.room_id
+ assert result.failed_attachments == [
+ {"kind": "kickoff", "id": "kickoff", "error": "transport down"}
+ ]
+
+
+async def test_provision_kickoff_none_event_id_is_a_failure(env):
+ """The admin client answers None when the send did not happen; that is a
+ failure, not a silent success."""
+ admin = FakeAdminClient()
+ admin.send_returns = None
+ svc, _ = _with_kickoff(env, admin)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert [f["error"] for f in result.failed_attachments] == [
+ "the platform could not post the kickoff"
+ ]
+
+
+async def test_provision_kickoff_waits_for_agents_and_reports_the_late(env):
+ """An agent whose client has not joined by the timeout is named in the
+ failure; the kickoff is still posted for the ones that did."""
+ admin = FakeAdminClient()
+ svc, lifecycle = _with_kickoff(env, admin)
+ async with env["session_factory"]() as session:
+ agent = await AgentStore().get_by_name(session, "claude-code.alice")
+ lifecycle.agent_clients[agent.id] = FakeAgentClient(joined=False)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert [f["error"] for f in result.failed_attachments] == [
+ "did not join the room in time to see the kickoff: claude-code.alice"
+ ]
+ assert len(admin.sent) == 2
+
+
+async def test_provision_kickoff_not_posted_when_platform_never_joins(env):
+ admin = FakeAdminClient()
+ admin.joined = False
+ svc, _ = _with_kickoff(env, admin)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert admin.sent == []
+ assert result.failed_attachments[0]["error"].startswith("did not join")
+
+
+async def test_provision_kickoff_without_admin_client_is_reported(env):
+ svc, _ = _with_kickoff(env, None)
+ spec, kickoff = svc.parse(KICKOFF_TEMPLATE, inputs={"coder": "claude-code.alice"})
+ result = await svc.provision(
+ spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False
+ )
+ assert result.failed_attachments == [
+ {
+ "kind": "kickoff",
+ "id": "kickoff",
+ "error": "the platform has no client to post with",
+ }
+ ]
+
+
+async def test_provision_without_kickoff_posts_nothing(env):
+ admin = FakeAdminClient()
+ svc, _ = _with_kickoff(env, admin)
+ spec, kickoff = svc.parse("room:\n name: quiet\n description: d\n")
+ assert kickoff is None
+ await svc.provision(spec, kickoff=kickoff, user_id=env["user_id"], is_admin=False)
+ assert admin.sent == []
+
+
+# ── builtins_for ────────────────────────────────────────────────────────────
+
+
+async def _seed_bridge_with_claim(
+ session_factory,
+ *,
+ display_name: str,
+ is_default: bool,
+ claimed_by: str | None,
+ external_username: str,
+) -> str:
+ """A bridge, an external user on it, and optionally a claim. Returns the
+ bridge id."""
+ async with session_factory() as session:
+ bridge_client = Client(
+ matrix_user_id=f"@bridge-{display_name.lower()}:test.local",
+ display_name=display_name,
+ type="collaboration_bridge",
+ )
+ user_client = Client(
+ matrix_user_id=f"@{external_username}-{display_name.lower()}:test.local",
+ display_name=external_username,
+ type="external_user",
+ )
+ session.add_all([bridge_client, user_client])
+ await session.flush()
+ bridge = CollaborationBridge(
+ type="slack",
+ display_name=display_name,
+ client_id=bridge_client.id,
+ status="active",
+ is_default=is_default,
+ )
+ session.add(bridge)
+ await session.flush()
+ ext = ExternalUser(
+ bridge_id=bridge.id,
+ external_user_id=f"U-{external_username}",
+ external_username=external_username,
+ client_id=user_client.id,
+ )
+ session.add(ext)
+ await session.flush()
+ if claimed_by is not None:
+ session.add(ExternalUserClaim(external_user_id=ext.id, user_id=claimed_by))
+ await session.commit()
+ return bridge.id
+
+
+async def test_builtins_creator_falls_back_to_gateway_name(env):
+ """No bridge at all: $creator is the gateway account name."""
+ builtins = await _svc(env).builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text="room:\n name: n\n description: d\n",
+ )
+ assert builtins["$creator"] == "alice"
+ assert builtins["$creator_email"] == "[email protected]"
+ assert "$date" in builtins and "$timestamp" in builtins
+
+
+async def test_builtins_creator_uses_claimed_identity_on_default_bridge(env):
+ """A claim on the template's (default) bridge wins over the gateway name."""
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=True,
+ claimed_by=env["user_id"],
+ external_username="abel.dantas",
+ )
+ builtins = await _svc(env).builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text="room:\n name: n\n description: d\n",
+ )
+ assert builtins["$creator"] == "abel.dantas"
+
+
+async def test_builtins_creator_ignores_unclaimed_identity(env):
+ """An external user nobody claimed does not become $creator."""
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=True,
+ claimed_by=None,
+ external_username="abel.dantas",
+ )
+ builtins = await _svc(env).builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text="room:\n name: n\n description: d\n",
+ )
+ assert builtins["$creator"] == "alice"
+
+
+async def test_builtins_refuses_unclaimed_creator_when_the_template_needs_one(env):
+ """A bridged template that uses {$creator} needs a linked account: the
+ gateway name is not a platform handle, and guessing produced private
+ channels the creator could not enter."""
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=True,
+ claimed_by=None,
+ external_username="abel.dantas",
+ )
+ with pytest.raises(ValueError, match=r"no linked account on Slack"):
+ await _svc(env).builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text='room:\n name: n\n description: d\n users: ["{$creator}"]\n',
+ )
+
+
+async def test_builtins_creator_resolves_named_bridge(env):
+ """A template naming a non-default bridge resolves the claim on THAT
+ bridge."""
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Mattermost",
+ is_default=True,
+ claimed_by=env["user_id"],
+ external_username="abel.mm",
+ )
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=False,
+ claimed_by=env["user_id"],
+ external_username="abel.slack",
+ )
+ builtins = await _svc(env).builtins_for(
+ user_id=env["user_id"],
+ name="alice",
+ text='room:\n name: n\n description: d\n bridge: "Slack"\n',
+ )
+ assert builtins["$creator"] == "abel.slack"
+
+
+def test_parse_multiline_param_option(env):
+ """`multiline: true` is a valid param option and rides into the schema."""
+ spec, _ = _svc(env).parse(
+ "params:\n"
+ " brief:\n"
+ " type: string\n"
+ " multiline: true\n"
+ "room:\n"
+ " name: n\n"
+ " description: d\n"
+ " instructions: |\n"
+ " {brief}\n",
+ inputs={"brief": "line one\nline two\n## Acceptance\n- item"},
+ )
+ assert spec.instructions == "line one\nline two\n## Acceptance\n- item\n"
+
+ from switch_core.rooms_yaml import TemplateDocument
+
+ schema = TemplateDocument.model_json_schema()
+ assert "multiline" in schema["$defs"]["ParamSpec"]["properties"]
+
+
+# ── entity params ───────────────────────────────────────────────────────────
+
+
+def test_resolve_params_entity_types_coerce_to_string():
+ """agent/bridge/room/user are string-valued: the entity's name."""
+ declared = {
+ "coder": ParamSpec(type="agent"),
+ "app": ParamSpec(type="bridge"),
+ "escalate_to": ParamSpec(type="room"),
+ "owner": ParamSpec(type="user"),
+ }
+ resolved = resolve_params(
+ declared,
+ {
+ "coder": "claude-code.alice",
+ "app": "Slack",
+ "escalate_to": "ops",
+ "owner": 7,
+ },
+ )
+ assert resolved == {
+ "coder": "claude-code.alice",
+ "app": "Slack",
+ "escalate_to": "ops",
+ "owner": "7",
+ }
+
+
+def test_template_schema_advertises_entity_types():
+ """The Console reads the allowed types off the schema, so the new ones
+ must be in it or every typed template is rejected client-side."""
+ from switch_core.rooms_yaml import TemplateDocument
+
+ schema = TemplateDocument.model_json_schema()
+ allowed = schema["$defs"]["ParamSpec"]["properties"]["type"]["enum"]
+ assert {"agent", "bridge", "room", "user"} <= set(allowed)
+
+
+def _entity_template(param_type: str, extra_room: str = "") -> str:
+ return (
+ "params:\n"
+ " pick:\n"
+ f" type: {param_type}\n"
+ "room:\n"
+ " name: n\n"
+ " description: d\n"
+ f"{extra_room}"
+ " instructions: 'uses {pick}'\n"
+ )
+
+
+async def test_check_entity_params_agent_must_exist(env):
+ svc = _svc(env)
+ ok = svc.parse_template(
+ _entity_template("agent"), inputs={"pick": "claude-code.alice"}
+ )
+ await svc.check_entity_params(ok)
+
+ bad = svc.parse_template(_entity_template("agent"), inputs={"pick": "nobody"})
+ with pytest.raises(ValueError, match=r"param 'pick': no agent named 'nobody'"):
+ await svc.check_entity_params(bad)
+
+
+async def test_check_entity_params_bridge_must_exist_and_run(env):
+ svc = _svc(env)
+ await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=True,
+ claimed_by=None,
+ external_username="someone",
+ )
+ ok = svc.parse_template(_entity_template("bridge"), inputs={"pick": "Slack"})
+ await svc.check_entity_params(ok)
+
+ bad = svc.parse_template(_entity_template("bridge"), inputs={"pick": "Teams"})
+ with pytest.raises(
+ ValueError, match=r"param 'pick': no messaging app named 'Teams'"
+ ):
+ await svc.check_entity_params(bad)
+
+ async with env["session_factory"]() as session:
+ bridge = (await session.execute(select(CollaborationBridge))).scalar_one()
+ bridge.status = "stopped"
+ await session.commit()
+ stopped = svc.parse_template(_entity_template("bridge"), inputs={"pick": "Slack"})
+ with pytest.raises(
+ ValueError, match=r"param 'pick': messaging app 'Slack' is not running"
+ ):
+ await svc.check_entity_params(stopped)
+
+
+async def test_check_entity_params_room_must_exist(env):
+ svc = _svc(env)
+ spec, _ = svc.parse("room:\n name: ops\n description: d\n")
+ await svc.provision(spec, user_id=env["user_id"], is_admin=False)
+
+ ok = svc.parse_template(_entity_template("room"), inputs={"pick": "ops"})
+ await svc.check_entity_params(ok)
+
+ bad = svc.parse_template(_entity_template("room"), inputs={"pick": "nowhere"})
+ with pytest.raises(ValueError, match=r"param 'pick': no room named 'nowhere'"):
+ await svc.check_entity_params(bad)
+
+
+async def test_check_entity_params_user_resolves_on_the_rooms_bridge(env):
+ svc = _svc(env)
+ bridge_id = await _seed_bridge_with_claim(
+ env["session_factory"],
+ display_name="Slack",
+ is_default=False,
+ claimed_by=None,
+ external_username="someone",
+ )
+ env["rooms"].bridge_users = {"bob": "U-bob"}
+ text = _entity_template("user", extra_room=' bridge: "Slack"\n')
+
+ ok = svc.parse_template(text, inputs={"pick": "bob"})
+ await svc.check_entity_params(ok)
+ assert env["rooms"].bridge_user_lookups == [(bridge_id, ["bob"])]
+
+ bad = svc.parse_template(text, inputs={"pick": "eve"})
+ with pytest.raises(ValueError, match=r"param 'pick': no user named 'eve'"):
+ await svc.check_entity_params(bad)
+
+
+async def test_check_entity_params_user_needs_a_bridge(env):
+ """No bridge named and no default: a user param has nowhere to look."""
+ svc = _svc(env)
+ parsed = svc.parse_template(_entity_template("user"), inputs={"pick": "bob"})
+ with pytest.raises(ValueError, match=r"param 'pick': a user can only be looked up"):
+ await svc.check_entity_params(parsed)
+
+
+async def test_check_entity_params_ignores_plain_params(env):
+ """Nothing to check means no store access and no error."""
+ svc = _svc(env)
+ parsed = svc.parse_template(
+ "params:\n label:\n type: string\nroom:\n name: '{label}'\n description: d\n",
+ inputs={"label": "anything"},
+ )
+ await svc.check_entity_params(parsed)
diff --git a/core/tests/switch_core/test_template_lint.py b/core/tests/switch_core/test_template_lint.py
index 8203cdaa4..82bf928ae 100644
--- a/core/tests/switch_core/test_template_lint.py
+++ b/core/tests/switch_core/test_template_lint.py
@@ -91,16 +91,21 @@ class TestTheCanonicalExample:
assert "unused_param" not in _codes(result.warnings)
def test_a_newer_param_field_is_a_warning_not_an_error(self) -> None:
- """`multiline` lands with CHOO-2656; this branch predates it.
+ """A param field this Switch does not know yet.
Reported so a typo is still visible, but not as an error — a document
written for a newer Switch is the ordinary case for a registry, not a
broken document.
"""
- result = lint_template(_CANONICAL_EXAMPLE)
+ text = _CANONICAL_EXAMPLE.replace(
+ " multiline: true\n",
+ " multiline: true\n placeholder: Paste it here\n",
+ )
+ assert text != _CANONICAL_EXAMPLE
+ result = lint_template(text)
(warning,) = [w for w in result.warnings if w.code == "unknown_param_field"]
assert warning.subject == "brief"
- assert "multiline" in warning.message
+ assert "placeholder" in warning.message
class TestWhatBarsTheDoor:
@@ -185,7 +190,7 @@ class TestUnknownParamFields:
"params:\n"
" visibility:\n"
" type: enum\n"
- " multiline: true\n"
+ " placeholder: Paste it here\n"
"room:\n"
" channel_type: '{visibility}'\n"
)
@@ -197,7 +202,7 @@ class TestUnknownParamFields:
"params:\n"
" owner:\n"
" type: nonsense\n"
- " multiline: true\n"
+ " placeholder: Paste it here\n"
"room:\n"
" name: '{owner}'\n"
)
diff --git a/docs/official/internals/agent-protocol.md b/docs/official/internals/agent-protocol.md
index c3f77f5e5..a4a1a085c 100644
--- a/docs/official/internals/agent-protocol.md
+++ b/docs/official/internals/agent-protocol.md
@@ -168,7 +168,7 @@ sequenceDiagram
| Event | Payload fields |
|---|---|
-| `message` | `addressed` (bool), `sender`, `sender_name`, `message_id`, `body`, `timestamp` (ms), `thread_id` (nullable), `attachments` (list) |
+| `message` | `addressed` (bool), `sender`, `sender_name`, `sender_kind` (`platform` when the Switch app posted it, else absent), `on_behalf_of` (the person a platform message speaks for, else absent), `message_id`, `body`, `timestamp` (ms), `thread_id` (nullable), `attachments` (list) |
| `command` | `command`, `args` (empty by default), `user_id`, `user_name`, `thread_id` (nullable) |
| `room_join` | `member`, `member_name`, `timestamp`, `listening` (bool) |
diff --git a/examples/room-templates/red-blue-workroom.template.yaml b/examples/room-templates/red-blue-workroom.template.yaml
new file mode 100644
index 000000000..ead6ccc0f
--- /dev/null
+++ b/examples/room-templates/red-blue-workroom.template.yaml
@@ -0,0 +1,63 @@
+# Red-blue workroom: a coder/reviewer loop with a human gate.
+#
+# The canonical example for the room-template surface. Conventions it
+# demonstrates:
+#
+# params: Typed inputs the Console's "Create from template" wizard
+# collects. Besides string, number, boolean and enum, a param
+# can be typed `agent`, `bridge`, `room` or `user`: the wizard
+# then offers a picker over what the server has, and the
+# server checks the chosen name exists before creating
+# anything. The value is the entity's name as the template
+# would spell it.
+#
+# {$creator}: Server-injected builtin: the creating user's name on the
+# room's bridge (their linked identity when they have claimed
+# one, otherwise their account name). Putting it in `users:`
+# invites whoever instantiates the template into the room.
+# Other builtins: {$creator_email}, {$date}, {$timestamp}.
+#
+# kickoff: Top-level key beside room: and params:. Posted into the room
+# by Switch on the creator's behalf once provisioning
+# completes: each agent it mentions applies its addressing
+# policy to the creator, as if they had typed it. Agents only
+# start working when a message addresses them, so mention
+# them here. This is what turns a provisioned room into
+# running work.
+params:
+ task_name:
+ type: string
+ description: Short name for the task (used in the room name)
+ coder_agent:
+ type: agent
+ description: Agent that implements the task
+ reviewer_agent:
+ type: agent
+ description: Agent that reviews and drives the acceptance loop
+ brief:
+ type: string
+ multiline: true
+ description: The task brief (paste the full text)
+room:
+ name: "Switch work: {task_name}"
+ description: "Workroom for {task_name}: coder/reviewer loop, human-gated."
+ channel_type: channel_private
+ agents: ["{coder_agent}", "{reviewer_agent}"]
+ users: ["{$creator}"]
+ instructions: |
+ This room implements {task_name}. {coder_agent} owns the branch and
+ commits. {reviewer_agent} reviews against the Acceptance section of the
+ brief and pushes the coder in a loop until every item is met. Only
+ {$creator}'s explicit confirmation stops the loop.
+
+ Brief:
+ {brief}
+kickoff: |
+ @{coder_agent} @{reviewer_agent} — kicking off {task_name}.
+
+ @{coder_agent}: read the brief in the room instructions and start
+ implementing. Post your plan here before your first commit.
+
+ @{reviewer_agent}: drive the acceptance loop. Review every hand-off
+ against the brief's Acceptance section and push back until every item is
+ met, then ping {$creator} to confirm and close.
diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.ts
index 30489c490..0bae2bc28 100644
--- a/gateway/src/data/api.ts
+++ b/gateway/src/data/api.ts
@@ -102,6 +102,14 @@ export interface AddressingRule {
room_groups: AddressingDimension;
users: AddressingDimension;
agents: AddressingDimension;
+ // Symbolic subjects, resolved when a message arrives. Absent reads as
+ // false, as it does server-side.
+ owner?: boolean;
+ owner_agents?: boolean;
+ // Admit the Switch platform on its own account. Denied by default even for
+ // an open policy. A platform message sent for a person is judged as that
+ // person instead.
+ platform?: boolean;
}
export interface AddressingPolicy {
diff --git a/gateway/src/pages/agents/AddressingPolicySection.tsx b/gateway/src/pages/agents/AddressingPolicySection.tsx
index 0ee0e2a68..680b4a535 100644
--- a/gateway/src/pages/agents/AddressingPolicySection.tsx
+++ b/gateway/src/pages/agents/AddressingPolicySection.tsx
@@ -3,6 +3,7 @@ import {
Autocomplete,
Box,
Button,
+ Checkbox,
CircularProgress,
FormControlLabel,
IconButton,
@@ -51,6 +52,12 @@ interface RuleState {
room_groups: DimState;
users: DimState;
agents: DimState;
+ // The owner and owner-agents subjects and the platform opt-in are carried
+ // through untouched: this editor does not offer them, and saving must not
+ // strip what another surface set.
+ owner?: boolean;
+ owner_agents?: boolean;
+ platform: boolean;
}
function toDimState(value: AddressingDimension, allowNone: boolean): DimState {
@@ -73,16 +80,23 @@ function toRuleState(rule: AddressingRule): RuleState {
room_groups: toDimState(rule.room_groups, false),
users: toDimState(rule.users, true),
agents: toDimState(rule.agents, true),
+ owner: rule.owner,
+ owner_agents: rule.owner_agents,
+ platform: rule.platform === true,
};
}
function fromRuleState(state: RuleState): AddressingRule {
- return {
+ const rule: AddressingRule = {
rooms: fromDimState(state.rooms),
room_groups: fromDimState(state.room_groups),
users: fromDimState(state.users),
agents: fromDimState(state.agents),
};
+ if (state.owner !== undefined) rule.owner = state.owner;
+ if (state.owner_agents !== undefined) rule.owner_agents = state.owner_agents;
+ if (state.platform) rule.platform = true;
+ return rule;
}
// A rule that can never match (so it would silently never apply): a context
@@ -103,6 +117,7 @@ const EMPTY_RULE: RuleState = {
room_groups: { mode: "any", ids: [] },
users: { mode: "any", ids: [] },
agents: { mode: "any", ids: [] },
+ platform: false,
};
function DimensionField({
@@ -342,6 +357,19 @@ export default function AddressingPolicySection({
disabled={!canEdit}
onChange={(agents) => updateRule(index, { ...rule, agents })}
/>
+ <FormControlLabel
+ control={
+ <Checkbox
+ size="small"
+ checked={rule.platform}
+ disabled={!canEdit}
+ onChange={(e) =>
+ updateRule(index, { ...rule, platform: e.target.checked })
+ }
+ />
+ }
+ label="Switch itself: let the platform address this agent on its own account. A message it sends for a person, such as a template kickoff, is judged as that person and needs no opt-in."
+ />
{ruleIsDead(rule) && (
<Alert severity="warning">
This rule can never match (an empty Specific/None dimension